github.com/apptainer/singularity@v3.1.1+incompatible/internal/pkg/util/env/clean.go (about) 1 // Copyright (c) 2018, Sylabs Inc. All rights reserved. 2 // This software is licensed under a 3-clause BSD license. Please consult the 3 // LICENSE.md file distributed with the sources of this project regarding your 4 // rights to use or distribute this software. 5 6 package env 7 8 import ( 9 "os" 10 "strings" 11 12 "github.com/opencontainers/runtime-tools/generate" 13 "github.com/sylabs/singularity/internal/pkg/sylog" 14 ) 15 16 const ( 17 envPrefix = "SINGULARITYENV_" 18 ) 19 20 var alwaysPassKeys = map[string]bool{ 21 "TERM": true, 22 "http_proxy": true, 23 "HTTP_PROXY": true, 24 "https_proxy": true, 25 "HTTPS_PROXY": true, 26 "no_proxy": true, 27 "NO_PROXY": true, 28 "all_proxy": true, 29 "ALL_PROXY": true, 30 "ftp_proxy": true, 31 "FTP_PROXY": true, 32 } 33 34 // SetContainerEnv cleans environment variables before running the container 35 func SetContainerEnv(g *generate.Generator, env []string, cleanEnv bool, homeDest string) { 36 // first deal with special variables that allow user to control $PATH at 37 // runtime (meh... special cases) 38 if prependPath := os.Getenv("SINGULARITYENV_PREPEND_PATH"); prependPath != "" { 39 g.AddProcessEnv("SING_USER_DEFINED_PREPEND_PATH", prependPath) 40 } 41 42 if appendPath := os.Getenv("SINGULARITYENV_APPEND_PATH"); appendPath != "" { 43 g.AddProcessEnv("SING_USER_DEFINED_APPEND_PATH", appendPath) 44 } 45 46 if userPath := os.Getenv("SINGULARITYENV_PATH"); userPath != "" { 47 g.AddProcessEnv("SING_USER_DEFINED_PATH", userPath) 48 } 49 50 for _, env := range env { 51 e := strings.SplitN(env, "=", 2) 52 if len(e) != 2 { 53 sylog.Verbosef("Can't process environment variable %s", env) 54 continue 55 } 56 57 if e[0] == "SINGULARITYENV_PREPEND_PATH" || 58 e[0] == "SINGULARITYENV_APPEND_PATH" || 59 e[0] == "SINGULARITYENV_PATH" { 60 sylog.Verbosef("Not adding special case PATH control variable %s to container environment", e[0]) 61 continue 62 } 63 64 // Transpose host env variables into config 65 if addKey, ok := addIfReq(e[0], cleanEnv); ok { 66 g.AddProcessEnv(addKey, e[1]) 67 } 68 } 69 70 g.AddProcessEnv("HOME", homeDest) 71 g.AddProcessEnv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin") 72 73 // Set LANG env 74 if cleanEnv { 75 g.AddProcessEnv("LANG", "C") 76 } 77 } 78 79 func addIfReq(key string, cleanEnv bool) (string, bool) { 80 if strings.HasPrefix(key, envPrefix) { 81 return strings.TrimPrefix(key, envPrefix), true 82 } else if _, ok := alwaysPassKeys[key]; cleanEnv && !ok { 83 return "", false 84 } 85 86 return key, true 87 }