utils.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "bytes"
  22. "crypto/rand"
  23. "crypto/x509"
  24. "encoding/base64"
  25. "encoding/json"
  26. "errors"
  27. "fmt"
  28. "io"
  29. "math/big"
  30. "os"
  31. "runtime"
  32. "strings"
  33. "sync"
  34. )
  35. // Contains is a helper function that returns true
  36. // if the target string is in the list.
  37. func Contains(list []string, target string) bool {
  38. for _, listItem := range list {
  39. if listItem == target {
  40. return true
  41. }
  42. }
  43. return false
  44. }
  45. // MakeSecureRandomInt is a helper function that wraps
  46. // MakeSecureRandomInt64.
  47. func MakeSecureRandomInt(max int) (int, error) {
  48. randomInt, err := MakeSecureRandomInt64(int64(max))
  49. return int(randomInt), err
  50. }
  51. // MakeSecureRandomInt64 is a helper function that wraps
  52. // crypto/rand.Int, which returns a uniform random value in [0, max).
  53. func MakeSecureRandomInt64(max int64) (int64, error) {
  54. randomInt, err := rand.Int(rand.Reader, big.NewInt(max))
  55. if err != nil {
  56. return 0, ContextError(err)
  57. }
  58. return randomInt.Int64(), nil
  59. }
  60. // MakeSecureRandomBytes is a helper function that wraps
  61. // crypto/rand.Read.
  62. func MakeSecureRandomBytes(length int) ([]byte, error) {
  63. randomBytes := make([]byte, length)
  64. n, err := rand.Read(randomBytes)
  65. if err != nil {
  66. return nil, ContextError(err)
  67. }
  68. if n != length {
  69. return nil, ContextError(errors.New("insufficient random bytes"))
  70. }
  71. return randomBytes, nil
  72. }
  73. func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error) {
  74. derEncodedCertificate, err := base64.StdEncoding.DecodeString(encodedCertificate)
  75. if err != nil {
  76. return nil, ContextError(err)
  77. }
  78. certificate, err = x509.ParseCertificate(derEncodedCertificate)
  79. if err != nil {
  80. return nil, ContextError(err)
  81. }
  82. return certificate, nil
  83. }
  84. // TrimError removes the middle of over-long error message strings
  85. func TrimError(err error) error {
  86. const MAX_LEN = 100
  87. message := fmt.Sprintf("%s", err)
  88. if len(message) > MAX_LEN {
  89. return errors.New(message[:MAX_LEN/2] + "..." + message[len(message)-MAX_LEN/2:])
  90. }
  91. return err
  92. }
  93. // ContextError prefixes an error message with the current function name
  94. func ContextError(err error) error {
  95. if err == nil {
  96. return nil
  97. }
  98. pc, _, line, _ := runtime.Caller(1)
  99. funcName := runtime.FuncForPC(pc).Name()
  100. index := strings.LastIndex(funcName, "/")
  101. if index != -1 {
  102. funcName = funcName[index+1:]
  103. }
  104. return fmt.Errorf("%s#%d: %s", funcName, line, err)
  105. }
  106. // IsNetworkBindError returns true when the err is due to EADDRINUSE.
  107. func IsNetworkBindError(err error) bool {
  108. return strings.Contains(err.Error(), "bind: address already in use")
  109. }
  110. // NoticeConsoleRewriter consumes JOSN-format notice input and parses each
  111. // notice and rewrites in a more human-readable format more suitable for
  112. // console output. The data payload field is left as JSON.
  113. type NoticeConsoleRewriter struct {
  114. mutex sync.Mutex
  115. writer io.Writer
  116. buffer []byte
  117. }
  118. // NewNoticeConsoleRewriter initializes a new NoticeConsoleRewriter
  119. func NewNoticeConsoleRewriter(writer io.Writer) *NoticeConsoleRewriter {
  120. return &NoticeConsoleRewriter{writer: writer}
  121. }
  122. // Write implements io.Writer.
  123. func (rewriter *NoticeConsoleRewriter) Write(p []byte) (n int, err error) {
  124. rewriter.mutex.Lock()
  125. defer rewriter.mutex.Unlock()
  126. rewriter.buffer = append(rewriter.buffer, p...)
  127. index := bytes.Index(rewriter.buffer, []byte("\n"))
  128. if index == -1 {
  129. return len(p), nil
  130. }
  131. line := rewriter.buffer[:index]
  132. rewriter.buffer = rewriter.buffer[index+1:]
  133. type NoticeObject struct {
  134. NoticeType string `json:"noticeType"`
  135. Data json.RawMessage `json:"data"`
  136. Timestamp string `json:"timestamp"`
  137. }
  138. var noticeObject NoticeObject
  139. _ = json.Unmarshal(line, &noticeObject)
  140. fmt.Fprintf(os.Stderr,
  141. "%s %s %s\n",
  142. noticeObject.Timestamp,
  143. noticeObject.NoticeType,
  144. string(noticeObject.Data))
  145. return len(p), nil
  146. }