httpserver_test.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package httputil
  10. import (
  11. "bytes"
  12. "crypto/tls"
  13. "crypto/x509"
  14. "flag"
  15. "fmt"
  16. "html"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "os"
  21. "sync"
  22. "syscall"
  23. "testing"
  24. "time"
  25. "devt.de/krotik/common/cryptutil"
  26. "devt.de/krotik/common/fileutil"
  27. )
  28. const certdir = "certs"
  29. const testporthttp = ":9050"
  30. const testporthttps = ":9051"
  31. const invalidFileName = "**\x00"
  32. func TestMain(m *testing.M) {
  33. flag.Parse()
  34. // Setup
  35. if res, _ := fileutil.PathExists(certdir); res {
  36. os.RemoveAll(certdir)
  37. }
  38. err := os.Mkdir(certdir, 0770)
  39. if err != nil {
  40. fmt.Print("Could not create test directory:", err.Error())
  41. os.Exit(1)
  42. }
  43. // Run the tests
  44. res := m.Run()
  45. // Teardown
  46. err = os.RemoveAll(certdir)
  47. if err != nil {
  48. fmt.Print("Could not remove test directory:", err.Error())
  49. }
  50. os.Exit(res)
  51. }
  52. func TestHTTPSServer(t *testing.T) {
  53. // Generate a certificate and private key
  54. err := cryptutil.GenCert(certdir, "cert.pem", "key.pem", "localhost", "", 365*24*time.Hour, true, 2048, "")
  55. if err != nil {
  56. t.Error(err)
  57. return
  58. }
  59. // Add dummy handler
  60. http.HandleFunc("/httpsserver_test", func(w http.ResponseWriter, r *http.Request) {
  61. fmt.Fprintf(w, "Hello over HTTPS, %q", html.EscapeString(r.URL.Path))
  62. })
  63. hs := &HTTPServer{}
  64. var wg sync.WaitGroup
  65. wg.Add(1)
  66. go hs.RunHTTPSServer(certdir, "cert.pem", "key.pem", testporthttps, &wg)
  67. wg.Wait()
  68. // HTTPS Server has started
  69. if hs.LastError != nil {
  70. t.Error(hs.LastError)
  71. return
  72. }
  73. // Check we can't start two servers
  74. var wg2 sync.WaitGroup
  75. hs2 := &HTTPServer{}
  76. wg2.Add(1)
  77. err = hs2.RunHTTPSServer(certdir, "c.pem", "k.pem", testporthttps, &wg2)
  78. if hs2.LastError == nil ||
  79. (hs2.LastError.Error() != "open certs/c.pem: no such file or directory" &&
  80. hs2.LastError.Error() != "open certs/c.pem: The system cannot find the file specified.") ||
  81. err != hs2.LastError {
  82. t.Error("Unexpected error return:", hs2.LastError)
  83. return
  84. }
  85. // Add again to wait group so we can try again
  86. wg2.Add(1)
  87. err = hs2.RunHTTPSServer(certdir, "cert.pem", "key.pem", testporthttps, &wg2)
  88. if hs2.LastError == nil || (hs2.LastError.Error() != "listen tcp "+testporthttps+
  89. ": bind: address already in use" && hs2.LastError.Error() != "listen tcp "+testporthttps+
  90. ": bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.") ||
  91. err != hs2.LastError {
  92. t.Error("Unexpected error return:", hs2.LastError)
  93. }
  94. // Add to the wait group so we can wait for the shutdown
  95. wg.Add(1)
  96. // Send something to the server
  97. if res := sendTestHTTPSRequest(certdir + "/cert.pem"); res != `Hello over HTTPS, "/httpsserver_test"` {
  98. t.Error("Unexpected request response:", res)
  99. return
  100. }
  101. // Server is shut down
  102. hs.Shutdown()
  103. if hs.Running == true {
  104. wg.Wait()
  105. } else {
  106. t.Error("Server was not running as expected")
  107. }
  108. }
  109. func TestSignalling(t *testing.T) {
  110. // Add dummy handler
  111. http.HandleFunc("/httpserver_test", func(w http.ResponseWriter, r *http.Request) {
  112. fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
  113. })
  114. hs := &HTTPServer{}
  115. var wg sync.WaitGroup
  116. wg.Add(1)
  117. go hs.RunHTTPServer(testporthttp, &wg)
  118. wg.Wait()
  119. // Server is started
  120. if hs.LastError != nil {
  121. t.Error(hs.LastError)
  122. return
  123. }
  124. // Check we can't start two servers
  125. var wg2 sync.WaitGroup
  126. wg2.Add(1)
  127. hs2 := &HTTPServer{}
  128. err := hs2.RunHTTPServer(testporthttp, &wg2)
  129. if hs2.LastError == nil || (hs2.LastError.Error() != "listen tcp "+testporthttp+
  130. ": bind: address already in use" && hs2.LastError.Error() != "listen tcp "+testporthttp+
  131. ": bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.") ||
  132. err != hs2.LastError {
  133. t.Error("Unexpected error return:", hs2.LastError)
  134. }
  135. // Add to the wait group so we can wait for the shutdown
  136. wg.Add(1)
  137. // Send something to the server
  138. if res := sendTestRequest(); res != `Hello, "/httpserver_test"` {
  139. t.Error("Unexpected request response:", res)
  140. return
  141. }
  142. // Check we can send other signals
  143. hs.signalling <- syscall.SIGHUP
  144. time.Sleep(time.Duration(50) * time.Millisecond)
  145. if hs.Running != true {
  146. t.Error("Server should still be running after sending wrong shutdown signal")
  147. return
  148. }
  149. // Server is shut down
  150. hs.Shutdown()
  151. if hs.Running == true {
  152. wg.Wait()
  153. } else {
  154. t.Error("Server was not running as expected")
  155. }
  156. // Test listener panic
  157. originalListener, _ := net.Listen("tcp", testporthttp)
  158. sl := newSignalTCPListener(originalListener, originalListener.(*net.TCPListener), nil)
  159. go testUnknownSignalPanic(t, sl)
  160. sl.Signals <- -1
  161. }
  162. func testUnknownSignalPanic(t *testing.T, sl *signalTCPListener) {
  163. defer func() {
  164. if r := recover(); r == nil {
  165. t.Error("Sending an unknown signal did not cause a panic.")
  166. }
  167. }()
  168. sl.Accept()
  169. }
  170. func sendTestRequest() string {
  171. url := "http://localhost" + testporthttp + "/httpserver_test"
  172. var jsonStr = []byte(`{"msg":"Hello!"}`)
  173. req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  174. req.Header.Set("X-Custom-Header", "myvalue")
  175. req.Header.Set("Content-Type", "application/json")
  176. client := &http.Client{}
  177. resp, err := client.Do(req)
  178. if err != nil {
  179. panic(err)
  180. }
  181. defer resp.Body.Close()
  182. body, _ := ioutil.ReadAll(resp.Body)
  183. return string(body)
  184. }
  185. func sendTestHTTPSRequest(caCert string) string {
  186. // Build ca cert pool
  187. caPool := x509.NewCertPool()
  188. serverCert, err := ioutil.ReadFile(caCert)
  189. if err != nil {
  190. panic(err)
  191. }
  192. caPool.AppendCertsFromPEM(serverCert)
  193. tr := &http.Transport{
  194. TLSClientConfig: &tls.Config{RootCAs: caPool},
  195. DisableCompression: true,
  196. }
  197. url := "https://localhost" + testporthttps + "/httpsserver_test"
  198. var jsonStr = []byte(`{"msg":"Hello!"}`)
  199. req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
  200. req.Header.Set("X-Custom-Header", "myvalue")
  201. req.Header.Set("Content-Type", "application/json")
  202. client := &http.Client{Transport: tr}
  203. resp, err := client.Do(req)
  204. if err != nil {
  205. panic(err)
  206. }
  207. defer resp.Body.Close()
  208. body, _ := ioutil.ReadAll(resp.Body)
  209. return string(body)
  210. }