1 /* 2 Copyright 2022 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package printers 18 19 import ( 20 "io" 21 "os" 22 "runtime" 23 "strings" 24 25 "github.com/moby/term" 26 ) 27 28 // terminalEscaper replaces ANSI escape sequences and other terminal special 29 // characters to avoid terminal escape character attacks (issue #101695). 30 var terminalEscaper = strings.NewReplacer("\x1b", "^[", "\r", "\\r") 31 32 // WriteEscaped replaces unsafe terminal characters with replacement strings 33 // and writes them to the given writer. 34 func WriteEscaped(writer io.Writer, output string) error { 35 _, err := terminalEscaper.WriteString(writer, output) 36 return err 37 } 38 39 // EscapeTerminal escapes terminal special characters in a human readable (but 40 // non-reversible) format. 41 func EscapeTerminal(in string) string { 42 return terminalEscaper.Replace(in) 43 } 44 45 // IsTerminal returns whether the passed object is a terminal or not 46 func IsTerminal(i interface{}) bool { 47 _, terminal := term.GetFdInfo(i) 48 return terminal 49 } 50 51 // AllowsColorOutput returns true if the specified writer is a terminal and 52 // the process environment indicates color output is supported and desired. 53 func AllowsColorOutput(w io.Writer) bool { 54 if !IsTerminal(w) { 55 return false 56 } 57 58 // https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals 59 if os.Getenv("TERM") == "dumb" { 60 return false 61 } 62 63 // https://no-color.org/ 64 if _, nocolor := os.LookupEnv("NO_COLOR"); nocolor { 65 return false 66 } 67 68 // On Windows WT_SESSION is set by the modern terminal component. 69 // Older terminals have poor support for UTF-8, VT escape codes, etc. 70 if runtime.GOOS == "windows" && os.Getenv("WT_SESSION") == "" { 71 return false 72 } 73 74 return true 75 } 76