|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net" |
| 9 | + "os" |
| 10 | + "os/signal" |
| 11 | + "strings" |
| 12 | + "sync" |
| 13 | + "syscall" |
| 14 | +) |
| 15 | + |
| 16 | +func main() { |
| 17 | + listen := flag.String("listen", ":10000", "listen") |
| 18 | + network := flag.String("network", "tcp", "") |
| 19 | + notlsaction := flag.String("notlsaction", "notls", "") |
| 20 | + tlsaction := flag.String("tlsaction", "dunno", "") |
| 21 | + flag.Parse() |
| 22 | + |
| 23 | + listener, err := net.Listen(*network, *listen) |
| 24 | + if err != nil { |
| 25 | + fmt.Fprintf(os.Stderr, "%v\n", err) |
| 26 | + os.Exit(1) |
| 27 | + } |
| 28 | + wg := sync.WaitGroup{} |
| 29 | + |
| 30 | + done := make(chan struct{}) |
| 31 | + |
| 32 | + sig := make(chan os.Signal) |
| 33 | + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) |
| 34 | + go func() { |
| 35 | + <-sig |
| 36 | + fmt.Println("Terminating") |
| 37 | + close(done) |
| 38 | + listener.Close() |
| 39 | + }() |
| 40 | + |
| 41 | + wg.Add(1) |
| 42 | + go func() { |
| 43 | + defer wg.Done() |
| 44 | + out: |
| 45 | + for { |
| 46 | + con, err := listener.Accept() |
| 47 | + if err != nil { |
| 48 | + select { |
| 49 | + case <-done: |
| 50 | + return |
| 51 | + default: |
| 52 | + fmt.Fprintf(os.Stderr, "Accept failed: %v\n", err) |
| 53 | + continue out |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + wg.Add(1) |
| 58 | + |
| 59 | + connEnd := make(chan struct{}) |
| 60 | + |
| 61 | + go func() { |
| 62 | + select { |
| 63 | + case <-connEnd: |
| 64 | + case <-done: |
| 65 | + con.Close() |
| 66 | + <-connEnd |
| 67 | + } |
| 68 | + wg.Done() |
| 69 | + }() |
| 70 | + go func() { |
| 71 | + defer func() { |
| 72 | + connEnd <- struct{}{} |
| 73 | + }() |
| 74 | + scanner := bufio.NewScanner(con) |
| 75 | + scanner.Split(bufio.ScanLines) |
| 76 | + |
| 77 | + var tls string |
| 78 | + for scanner.Scan() { |
| 79 | + s := scanner.Text() |
| 80 | + if strings.HasPrefix(s, "encryption_protocol=") { |
| 81 | + fmt.Sscanf(s, "encryption_protocol=%s", &tls) |
| 82 | + } |
| 83 | + |
| 84 | + //empty line |
| 85 | + if len(s) == 0 { |
| 86 | + if len(tls) == 0 { |
| 87 | + io.WriteString(con, fmt.Sprintf("action=%v\n\n", *notlsaction)) |
| 88 | + } else { |
| 89 | + io.WriteString(con, fmt.Sprintf("action=%v\n\n", *tlsaction)) |
| 90 | + } |
| 91 | + tls = "" |
| 92 | + } |
| 93 | + |
| 94 | + } |
| 95 | + if err := scanner.Err(); err != nil { |
| 96 | + select { |
| 97 | + case <-done: |
| 98 | + default: |
| 99 | + fmt.Fprintf(os.Stderr, "%v\n", err) |
| 100 | + } |
| 101 | + } |
| 102 | + }() |
| 103 | + } |
| 104 | + }() |
| 105 | + wg.Wait() |
| 106 | +} |
0 commit comments