1 package main
   2 
   3 /*
   4 license note
   5 Copyright (c) 2017, Eliezer Croitoru
   6 All rights reserved.
   7 
   8 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
   9 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  10 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  11 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  12 
  13 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14 */
  15 
  16 // Resources:
  17 // - http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/
  18 // - https://gobyexample.com/base64-encoding
  19 
  20 import (
  21         "bufio"
  22         "crypto/tls"
  23         "crypto/x509"
  24         "encoding/base64"
  25         "flag"
  26         "fmt"
  27         "golang.org/x/net/http2"
  28         "io/ioutil"
  29         //"net"
  30         // Net libs can be used to parse IP addresses
  31         "net/http"
  32         "net/url"
  33         "os"
  34         "strings"
  35         "sync"
  36 )
  37 
  38 var debug *bool
  39 var storeIdApiUrl *string
  40 var user *string
  41 var pass *string
  42 var tlsConfig *tls.Config
  43 var tlsCert *string
  44 var pemCert []byte
  45 var dontVerifyTls *bool
  46 var useOsTls *bool
  47 var http_version *string
  48 
  49 var err error
  50 
  51 func process_request(line string, wg *sync.WaitGroup) {
  52         defer wg.Done()
  53         answer := "ERR"
  54         lparts := strings.Split(strings.TrimRight(line, "\n"), " ")
  55         if len(lparts[0]) > 0 {
  56                 if *debug {
  57                         fmt.Fprintln(os.Stderr, "ERRlog: Proccessing request => \""+strings.TrimRight(line, "\n")+"\"")
  58                 }
  59         }
  60 
  61         var client *http.Client
  62         switch *http_version {
  63         case "2":
  64                 client = &http.Client{
  65                         Transport: &http2.Transport{TLSClientConfig: tlsConfig},
  66                 }
  67         default:
  68                 client = &http.Client{}
  69         }
  70 
  71         testurl, _ := url.Parse(*storeIdApiUrl)
  72         testurlVals := url.Values{}
  73         testurlVals.Set("url", base64.StdEncoding.EncodeToString([]byte(lparts[1])))
  74         //testurlVals.Set("other", port)
  75         //testurlVals.Set("otherother", srcip)
  76         testurl.RawQuery = testurlVals.Encode()
  77 
  78         request, err := http.NewRequest("GET", testurl.String(), nil)
  79         request.Close = true
  80         request.SetBasicAuth(*user, *pass)
  81 
  82         resp, err := client.Do(request)
  83         if err != nil {
  84                 fmt.Fprintln(os.Stderr, "ERRlog: reporting a http connection error1 => \""+err.Error()+"\"")
  85                 fmt.Println(lparts[0] + " " + answer)
  86                 return
  87         }
  88 
  89         defer resp.Body.Close()
  90 
  91         body, err := ioutil.ReadAll(resp.Body)
  92         if err != nil {
  93                 fmt.Fprintln(os.Stderr, "ERRlog: reporting a http connection error2 => \""+err.Error()+"\"")
  94                 fmt.Println(lparts[0] + " " + answer)
  95                 return
  96         }
  97 
  98         if body != nil {
  99                 response := string(body)
 100                 if strings.HasPrefix(response, "OK ") {
 101                         fmt.Println(lparts[0] + " " + response)
 102                 }
 103         }
 104 
 105         fmt.Println(lparts[0] + " " + answer)
 106 }
 107 
 108 func init() {
 109 
 110         fmt.Fprintln(os.Stderr, "ERRlog: Starting Fake helper")
 111 
 112         debug = flag.Bool("d", false, "Debug mode can be \"yes\" or something else for no")
 113         storeIdApiUrl = flag.String("api-url", "http://ngtech.co.il/fake-storeid-url/", "The url of the api")
 114         user = flag.String("api-user", "admin", "Basic auth username for server authentication")
 115         pass = flag.String("api-pass", "admin", "Basic auth password for server authentication")
 116         http_version = flag.String("api-httpv", "1", "http client version: 1\\2")
 117         tlsCert = flag.String("tlscert", "cert.pem", "tls certificate")
 118         dontVerifyTls = flag.Bool("skiptls", false, "Verify tls certificate, use \"1\" to enable")
 119         useOsTls = flag.Bool("ostls", false, "Use OS tls certificates, use \"1\" to enable")
 120 
 121         flag.Parse()
 122         flagsMap := make(map[string]interface{})
 123         flagsMap["debug"] = *debug
 124         flagsMap["api-url"] = *storeIdApiUrl
 125         flagsMap["api_user"] = *user
 126         flagsMap["api_pass"] = *pass
 127         flagsMap["api-httpv"] = *http_version
 128         flagsMap["tlscert"] = *tlsCert
 129         flagsMap["skiptls"] = *dontVerifyTls
 130         flagsMap["ostls"] = *useOsTls
 131 
 132         if *debug {
 133                 fmt.Fprintln(os.Stderr, "ERRlog: Config Variables:")
 134                 for k, v := range flagsMap {
 135                         fmt.Fprintf(os.Stderr, "ERRlog:\t%v =>  %v\n", k, v)
 136                 }
 137         }
 138 }
 139 
 140 func main() {
 141         if *http_version == "2" && strings.HasPrefix(*storeIdApiUrl, "http://") {
 142                 fmt.Fprintf(os.Stderr, "ERRlog: ### The http2 library doesn't support \"https://\" scheme, you are using => %v\n", *storeIdApiUrl)
 143                 return
 144         }
 145 
 146         switch {
 147         case *http_version == "2" && *useOsTls:
 148 
 149         case (*http_version == "2") && !*dontVerifyTls:
 150                 tlsConfig = &tls.Config{RootCAs: x509.NewCertPool()}
 151 
 152                 var err error
 153                 pemCert, err = ioutil.ReadFile(*tlsCert)
 154                 if err != nil {
 155                         fmt.Println(err)
 156                 }
 157                 ok := tlsConfig.RootCAs.AppendCertsFromPEM(pemCert)
 158                 if !ok {
 159                         panic("Couldn't load PEM data")
 160                 }
 161         case (*http_version == "2" && (*dontVerifyTls)):
 162                 tlsConfig = &tls.Config{InsecureSkipVerify: true}
 163         default:
 164 
 165         }
 166 
 167         var wg sync.WaitGroup
 168 
 169         reader := bufio.NewReader(os.Stdin)
 170 
 171         for {
 172                 line, err := reader.ReadString('\n')
 173 
 174                 if err != nil {
 175                         // You may check here if err == io.EOF
 176                         break
 177                 }
 178                 if strings.HasPrefix(line, "q") || strings.HasPrefix(line, "Q") {
 179                         fmt.Fprintln(os.Stderr, "ERRlog: Exiting cleanly")
 180                         break
 181                 }
 182 
 183                 wg.Add(1)
 184                 go process_request(line, &wg)
 185 
 186         }
 187         wg.Wait()
 188 
 189 }

Features/StoreID/Helper/Golang-2-api (last edited 2017-06-14 18:05:26 by Eliezer Croitoru)