main.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2019 winlin
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. /*
  21. This the main entrance of https-proxy, proxy to api or other http server.
  22. */
  23. package main
  24. import (
  25. "context"
  26. "crypto/tls"
  27. "flag"
  28. "fmt"
  29. oe "github.com/ossrs/go-oryx-lib/errors"
  30. oh "github.com/ossrs/go-oryx-lib/http"
  31. "github.com/ossrs/go-oryx-lib/https"
  32. ol "github.com/ossrs/go-oryx-lib/logger"
  33. "io/ioutil"
  34. "log"
  35. "net"
  36. "net/http"
  37. "net/http/httputil"
  38. "net/url"
  39. "os"
  40. "path"
  41. "strconv"
  42. "strings"
  43. "sync"
  44. )
  45. type Strings []string
  46. func (v *Strings) String() string {
  47. return fmt.Sprintf("strings [%v]", strings.Join(*v, ","))
  48. }
  49. func (v *Strings) Set(value string) error {
  50. *v = append(*v, value)
  51. return nil
  52. }
  53. func shouldProxyURL(srcPath, proxyPath string) bool {
  54. if !strings.HasSuffix(srcPath, "/") {
  55. // /api to /api/
  56. // /api.js to /api.js/
  57. // /api/100 to /api/100/
  58. srcPath += "/"
  59. }
  60. if !strings.HasSuffix(proxyPath, "/") {
  61. // /api/ to /api/
  62. // to match /api/ or /api/100
  63. // and not match /api.js/
  64. proxyPath += "/"
  65. }
  66. return strings.HasPrefix(srcPath, proxyPath)
  67. }
  68. // about x-real-ip and x-forwarded-for or
  69. // about X-Real-IP and X-Forwarded-For or
  70. // https://segmentfault.com/q/1010000002409659
  71. // https://distinctplace.com/2014/04/23/story-behind-x-forwarded-for-and-x-real-ip-headers/
  72. // @remark http proxy will set the X-Forwarded-For.
  73. func addProxyAddToHeader(remoteAddr, realIP string, fwd []string, header http.Header, omitForward bool) {
  74. rip, _, err := net.SplitHostPort(remoteAddr)
  75. if err != nil {
  76. return
  77. }
  78. if realIP != "" {
  79. header.Set("X-Real-IP", realIP)
  80. } else {
  81. header.Set("X-Real-IP", rip)
  82. }
  83. if !omitForward {
  84. header["X-Forwarded-For"] = fwd[:]
  85. header.Add("X-Forwarded-For", rip)
  86. }
  87. }
  88. func filterByPreHook(ctx context.Context, preHook *url.URL, req *http.Request) error {
  89. target := *preHook
  90. target.RawQuery = strings.Join([]string{target.RawQuery, req.URL.RawQuery}, "&")
  91. api := target.String()
  92. r, err := http.NewRequestWithContext(ctx, req.Method, api, nil)
  93. if err != nil {
  94. return err
  95. }
  96. // Add real ip and forwarded for to header.
  97. // We should append the forward for pass-by.
  98. addProxyAddToHeader(req.RemoteAddr, req.Header.Get("X-Real-IP"), req.Header["X-Forwarded-For"], r.Header, false)
  99. ol.Tf(ctx, "Pre-hook proxy addr req=%v, r=%v", req.Header, r.Header)
  100. r2, err := http.DefaultClient.Do(r)
  101. if err != nil {
  102. return err
  103. }
  104. defer r2.Body.Close()
  105. if r2.StatusCode != http.StatusOK {
  106. return fmt.Errorf("Pre-hook HTTP StatusCode=%v %v", r2.StatusCode, r2.Status)
  107. }
  108. b, err := ioutil.ReadAll(r2.Body)
  109. if err != nil {
  110. return err
  111. }
  112. ol.Tf(ctx, "Pre-hook %v url=%v, res=%v, headers=%v", req.Method, api, string(b), r.Header)
  113. return nil
  114. }
  115. func NewComplexProxy(ctx context.Context, proxyUrl, preHook *url.URL, originalRequest *http.Request) http.Handler {
  116. // Hook before proxy it.
  117. if preHook != nil {
  118. if err := filterByPreHook(ctx, preHook, originalRequest); err != nil {
  119. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  120. ol.Ef(ctx, "Pre-hook err %+v", err)
  121. http.Error(w, err.Error(), http.StatusInternalServerError)
  122. })
  123. }
  124. }
  125. // Start proxy it.
  126. proxy := &httputil.ReverseProxy{}
  127. proxyUrlQuery := proxyUrl.Query()
  128. // Create a proxy which attach a isolate logger.
  129. elogger := log.New(os.Stderr, fmt.Sprintf("%v ", originalRequest.RemoteAddr), log.LstdFlags)
  130. proxy.ErrorLog = elogger
  131. proxy.Director = func(r *http.Request) {
  132. // about the x-real-schema, we proxy to backend to identify the client schema.
  133. if rschema := r.Header.Get("X-Real-Schema"); rschema == "" {
  134. if r.TLS == nil {
  135. r.Header.Set("X-Real-Schema", "http")
  136. } else {
  137. r.Header.Set("X-Real-Schema", "https")
  138. }
  139. }
  140. // Add real ip and forwarded for to header.
  141. // We should omit the forward header, because the ReverseProxy will doit.
  142. addProxyAddToHeader(r.RemoteAddr, r.Header.Get("X-Real-IP"), r.Header["X-Forwarded-For"], r.Header, true)
  143. ol.Tf(ctx, "Proxy addr header %v", r.Header)
  144. r.URL.Scheme = proxyUrl.Scheme
  145. r.URL.Host = proxyUrl.Host
  146. // Trim the prefix path.
  147. if trimPrefix := proxyUrlQuery.Get("trimPrefix"); trimPrefix != "" {
  148. r.URL.Path = strings.TrimPrefix(r.URL.Path, trimPrefix)
  149. }
  150. // Aadd the prefix to path.
  151. if addPrefix := proxyUrlQuery.Get("addPrefix"); addPrefix != "" {
  152. r.URL.Path = addPrefix + r.URL.Path
  153. }
  154. // The original request.Host requested by the client.
  155. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Host
  156. if r.Header.Get("X-Forwarded-Host") == "" {
  157. r.Header.Set("X-Forwarded-Host", r.Host)
  158. }
  159. // Set the Host of client request to the upstream server's, to act as client
  160. // directly access the upstream server.
  161. if proxyUrlQuery.Get("modifyRequestHost") != "false" {
  162. r.Host = proxyUrl.Host
  163. }
  164. ra, url, rip := r.RemoteAddr, r.URL.String(), r.Header.Get("X-Real-Ip")
  165. ol.Tf(ctx, "proxy http rip=%v, addr=%v %v %v with headers %v", rip, ra, r.Method, url, r.Header)
  166. }
  167. proxy.ModifyResponse = func(w *http.Response) error {
  168. // We have already set the server, so remove the upstream one.
  169. if proxyUrlQuery.Get("keepUpsreamServer") != "true" {
  170. w.Header.Del("Server")
  171. }
  172. // We already added this header, it will cause chrome failed when duplicated.
  173. if w.Header.Get("Access-Control-Allow-Origin") != "" {
  174. w.Header.Del("Access-Control-Allow-Origin")
  175. }
  176. return nil
  177. }
  178. return proxy
  179. }
  180. func run(ctx context.Context) error {
  181. oh.Server = fmt.Sprintf("%v/%v", Signature(), Version())
  182. fmt.Println(oh.Server, "HTTP/HTTPS static server with API proxy.")
  183. var httpPorts Strings
  184. flag.Var(&httpPorts, "t", "http listen")
  185. flag.Var(&httpPorts, "http", "http listen at. 0 to disable http.")
  186. var httpsPorts Strings
  187. flag.Var(&httpsPorts, "s", "https listen")
  188. flag.Var(&httpsPorts, "https", "https listen at. 0 to disable https. 443 to serve. ")
  189. var httpsDomains string
  190. flag.StringVar(&httpsDomains, "d", "", "https the allow domains")
  191. flag.StringVar(&httpsDomains, "domains", "", "https the allow domains, empty to allow all. for example: ossrs.net,www.ossrs.net")
  192. var html string
  193. flag.StringVar(&html, "r", "./html", "the www web root")
  194. flag.StringVar(&html, "root", "./html", "the www web root. support relative dir to argv[0].")
  195. var cacheFile string
  196. flag.StringVar(&cacheFile, "e", "./letsencrypt.cache", "https the cache for letsencrypt")
  197. flag.StringVar(&cacheFile, "cache", "./letsencrypt.cache", "https the cache for letsencrypt. support relative dir to argv[0].")
  198. var useLetsEncrypt bool
  199. flag.BoolVar(&useLetsEncrypt, "l", false, "whether use letsencrypt CA")
  200. flag.BoolVar(&useLetsEncrypt, "lets", false, "whether use letsencrypt CA. self sign if not.")
  201. var ssKey string
  202. flag.StringVar(&ssKey, "k", "", "https self-sign key")
  203. flag.StringVar(&ssKey, "ssk", "", "https self-sign key")
  204. var ssCert string
  205. flag.StringVar(&ssCert, "c", "", `https self-sign cert`)
  206. flag.StringVar(&ssCert, "ssc", "", `https self-sign cert`)
  207. var oproxies Strings
  208. flag.Var(&oproxies, "p", "proxy ruler")
  209. flag.Var(&oproxies, "proxy", "one or more proxy the matched path to backend, for example, -proxy http://127.0.0.1:8888/api/webrtc")
  210. var oprehooks Strings
  211. flag.Var(&oprehooks, "pre-hook", "the pre-hook ruler, with request")
  212. var sdomains, skeys, scerts Strings
  213. flag.Var(&sdomains, "sdomain", "the SSL hostname")
  214. flag.Var(&skeys, "skey", "the SSL key for domain")
  215. flag.Var(&scerts, "scert", "the SSL cert for domain")
  216. var trimSlashLimit int
  217. var noRedirectIndex, trimLastSlash bool
  218. flag.BoolVar(&noRedirectIndex, "no-redirect-index", false, "Whether serve with index.html without redirect.")
  219. flag.BoolVar(&trimLastSlash, "trim-last-slash", false, "Whether trim last slash by HTTP redirect(302).")
  220. flag.IntVar(&trimSlashLimit, "trim-slash-limit", 0, "Only trim last slash when got enough directories.")
  221. flag.Usage = func() {
  222. fmt.Println(fmt.Sprintf("Usage: %v -t http -s https -d domains -r root -e cache -l lets -k ssk -c ssc -p proxy", os.Args[0]))
  223. fmt.Println(fmt.Sprintf(" "))
  224. fmt.Println(fmt.Sprintf("Options:"))
  225. fmt.Println(fmt.Sprintf(" -t, -http string"))
  226. fmt.Println(fmt.Sprintf(" Listen at port for HTTP server. Default: 0, disable HTTP."))
  227. fmt.Println(fmt.Sprintf(" -s, -https string"))
  228. fmt.Println(fmt.Sprintf(" Listen at port for HTTPS server. Default: 0, disable HTTPS."))
  229. fmt.Println(fmt.Sprintf(" -r, -root string"))
  230. fmt.Println(fmt.Sprintf(" The www root path. Supports relative to argv[0]=%v. Default: ./html", path.Dir(os.Args[0])))
  231. fmt.Println(fmt.Sprintf(" -no-redirect-index=bool"))
  232. fmt.Println(fmt.Sprintf(" Whether serve with index.html without redirect. Default: false"))
  233. fmt.Println(fmt.Sprintf(" -p, -proxy string"))
  234. fmt.Println(fmt.Sprintf(" Proxy path to backend. For example: http://127.0.0.1:8888/api/webrtc"))
  235. fmt.Println(fmt.Sprintf(" Proxy path to backend. For example: http://127.0.0.1:8888/api/webrtc?modifyRequestHost=false"))
  236. fmt.Println(fmt.Sprintf(" Proxy path to backend. For example: http://127.0.0.1:8888/api/webrtc?keepUpsreamServer=true"))
  237. fmt.Println(fmt.Sprintf(" Proxy path to backend. For example: http://127.0.0.1:8888/api/webrtc?trimPrefix=/ffmpeg"))
  238. fmt.Println(fmt.Sprintf(" Proxy path to backend. For example: http://127.0.0.1:8888/api/webrtc?addPrefix=/release"))
  239. fmt.Println(fmt.Sprintf(" -pre-hook string"))
  240. fmt.Println(fmt.Sprintf(" Pre-hook to backend, with request. For example: http://127.0.0.1:8888/api/stat"))
  241. fmt.Println(fmt.Sprintf("Options for HTTPS(letsencrypt cert):"))
  242. fmt.Println(fmt.Sprintf(" -l, -lets=bool"))
  243. fmt.Println(fmt.Sprintf(" Whether use letsencrypt CA. Default: false"))
  244. fmt.Println(fmt.Sprintf(" -e, -cache string"))
  245. fmt.Println(fmt.Sprintf(" The letsencrypt cache. Default: ./letsencrypt.cache"))
  246. fmt.Println(fmt.Sprintf(" -d, -domains string"))
  247. fmt.Println(fmt.Sprintf(" Set the validate HTTPS domain. For example: ossrs.net,www.ossrs.net"))
  248. fmt.Println(fmt.Sprintf("Options for HTTPS(file-based cert):"))
  249. fmt.Println(fmt.Sprintf(" -k, -ssk string"))
  250. fmt.Println(fmt.Sprintf(" The self-sign or validate file-based key file."))
  251. fmt.Println(fmt.Sprintf(" -c, -ssc string"))
  252. fmt.Println(fmt.Sprintf(" The self-sign or validate file-based cert file."))
  253. fmt.Println(fmt.Sprintf(" -sdomain string"))
  254. fmt.Println(fmt.Sprintf(" For multiple HTTPS site, the domain name. For example: ossrs.net"))
  255. fmt.Println(fmt.Sprintf(" -skey string"))
  256. fmt.Println(fmt.Sprintf(" For multiple HTTPS site, the key file."))
  257. fmt.Println(fmt.Sprintf(" -scert string"))
  258. fmt.Println(fmt.Sprintf(" For multiple HTTPS site, the cert file."))
  259. fmt.Println(fmt.Sprintf("For example:"))
  260. fmt.Println(fmt.Sprintf(" %v -t 8080 -s 9443 -r ./html", os.Args[0]))
  261. fmt.Println(fmt.Sprintf(" %v -t 8080 -s 9443 -r ./html -p http://ossrs.net:1985/api/v1/versions", os.Args[0]))
  262. fmt.Println(fmt.Sprintf("Generate cert for self-sign HTTPS:"))
  263. fmt.Println(fmt.Sprintf(" openssl genrsa -out server.key 2048"))
  264. fmt.Println(fmt.Sprintf(` openssl req -new -x509 -key server.key -out server.crt -days 365 -subj "/C=CN/ST=Beijing/L=Beijing/O=Me/OU=Me/CN=me.org"`))
  265. fmt.Println(fmt.Sprintf("For example:"))
  266. fmt.Println(fmt.Sprintf(" %v -s 9443 -r ./html -sdomain ossrs.net -skey ossrs.net.key -scert ossrs.net.pem", os.Args[0]))
  267. }
  268. flag.Parse()
  269. if useLetsEncrypt && len(httpsPorts) == 0 {
  270. return oe.Errorf("for letsencrypt, https=%v must be 0(disabled) or 443(enabled)", httpsPorts)
  271. }
  272. if len(httpPorts) == 0 && len(httpsPorts) == 0 {
  273. flag.Usage()
  274. os.Exit(-1)
  275. }
  276. // If trim last slash, we should enable no redirect index, to avoid infinitely redirect.
  277. if trimLastSlash {
  278. noRedirectIndex = true
  279. }
  280. fmt.Println(fmt.Sprintf("Config trimLastSlash=%v, trimSlashLimit=%v, noRedirectIndex=%v", trimLastSlash, trimSlashLimit, noRedirectIndex))
  281. var proxyUrls []*url.URL
  282. proxies := make(map[string]*url.URL)
  283. for _, oproxy := range []string(oproxies) {
  284. if oproxy == "" {
  285. return oe.Errorf("empty proxy in %v", oproxies)
  286. }
  287. proxyUrl, err := url.Parse(oproxy)
  288. if err != nil {
  289. return oe.Wrapf(err, "parse proxy %v", oproxy)
  290. }
  291. if _, ok := proxies[proxyUrl.Path]; ok {
  292. return oe.Errorf("proxy %v duplicated", proxyUrl.Path)
  293. }
  294. proxyUrls = append(proxyUrls, proxyUrl)
  295. proxies[proxyUrl.Path] = proxyUrl
  296. ol.Tf(ctx, "Proxy %v to %v", proxyUrl.Path, oproxy)
  297. }
  298. var preHookUrls []*url.URL
  299. preHooks := make(map[string]*url.URL)
  300. for _, oprehook := range []string(oprehooks) {
  301. if oprehook == "" {
  302. return oe.Errorf("empty pre-hook in %v", oprehooks)
  303. }
  304. preHookUrl, err := url.Parse(oprehook)
  305. if err != nil {
  306. return oe.Wrapf(err, "parse pre-hook %v", oprehook)
  307. }
  308. if _, ok := preHooks[preHookUrl.Path]; ok {
  309. return oe.Errorf("pre-hook %v duplicated", preHookUrl.Path)
  310. }
  311. preHookUrls = append(preHookUrls, preHookUrl)
  312. preHooks[preHookUrl.Path] = preHookUrl
  313. ol.Tf(ctx, "pre-hook %v to %v", preHookUrl.Path, oprehook)
  314. }
  315. if !path.IsAbs(cacheFile) && path.IsAbs(os.Args[0]) {
  316. cacheFile = path.Join(path.Dir(os.Args[0]), cacheFile)
  317. }
  318. if !path.IsAbs(html) && path.IsAbs(os.Args[0]) {
  319. html = path.Join(path.Dir(os.Args[0]), html)
  320. }
  321. serveFileNoRedirect := func (w http.ResponseWriter, r *http.Request, name string) {
  322. upath := path.Join(html, path.Clean(r.URL.Path))
  323. // Redirect without the last slash.
  324. if trimLastSlash && r.URL.Path != "/" && strings.HasSuffix(r.URL.Path, "/") {
  325. u := strings.TrimSuffix(r.URL.Path, "/")
  326. if r.URL.RawQuery != "" {
  327. u += "?" + r.URL.RawQuery
  328. }
  329. if strings.Count(u, "/") >= trimSlashLimit {
  330. http.Redirect(w, r, u, http.StatusFound)
  331. return
  332. }
  333. }
  334. // Append the index.html path if access a directory.
  335. if noRedirectIndex && !strings.Contains(path.Base(upath), ".") {
  336. if d, err := os.Stat(upath); err != nil {
  337. http.Error(w, err.Error(), http.StatusInternalServerError)
  338. return
  339. } else if d.IsDir() {
  340. upath = path.Join(upath, "index.html")
  341. }
  342. }
  343. http.ServeFile(w, r, upath)
  344. }
  345. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  346. oh.SetHeader(w)
  347. if o := r.Header.Get("Origin"); len(o) > 0 {
  348. // SRS does not need cookie or credentials, so we disable CORS credentials, and use * for CORS origin,
  349. // headers, expose headers and methods.
  350. w.Header().Set("Access-Control-Allow-Origin", "*")
  351. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
  352. w.Header().Set("Access-Control-Allow-Headers", "*")
  353. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
  354. w.Header().Set("Access-Control-Allow-Methods", "*")
  355. // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
  356. w.Header().Set("Access-Control-Expose-Headers", "*")
  357. // https://stackoverflow.com/a/24689738/17679565
  358. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  359. w.Header().Set("Access-Control-Allow-Credentials", "false")
  360. }
  361. // For matched OPTIONS, directly return without response.
  362. if r.Method == "OPTIONS" {
  363. return
  364. }
  365. if proxyUrls == nil {
  366. if r.URL.Path == "/httpx/v1/versions" {
  367. oh.WriteVersion(w, r, Version())
  368. return
  369. }
  370. serveFileNoRedirect(w, r, path.Join(html, path.Clean(r.URL.Path)))
  371. return
  372. }
  373. // Find pre-hook to serve with proxy.
  374. var preHook *url.URL
  375. for _, preHookUrl := range preHookUrls {
  376. if !shouldProxyURL(r.URL.Path, preHookUrl.Path) {
  377. continue
  378. }
  379. if p, ok := preHooks[preHookUrl.Path]; ok {
  380. preHook = p
  381. }
  382. }
  383. // Find proxy to serve it.
  384. for _, proxyUrl := range proxyUrls {
  385. if !shouldProxyURL(r.URL.Path, proxyUrl.Path) {
  386. continue
  387. }
  388. if proxy, ok := proxies[proxyUrl.Path]; ok {
  389. p := NewComplexProxy(ctx, proxy, preHook, r)
  390. p.ServeHTTP(w, r)
  391. return
  392. }
  393. }
  394. serveFileNoRedirect(w, r, path.Join(html, path.Clean(r.URL.Path)))
  395. })
  396. var protos []string
  397. if len(httpPorts) > 0 {
  398. protos = append(protos, fmt.Sprintf("http(:%v)", strings.Join(httpPorts, ",")))
  399. }
  400. for _, httpsPort := range httpsPorts {
  401. if httpsPort == "0" {
  402. continue
  403. }
  404. s := httpsDomains
  405. if httpsDomains == "" {
  406. s = "all domains"
  407. }
  408. if useLetsEncrypt {
  409. protos = append(protos, fmt.Sprintf("https(:%v, %v, %v)", httpsPort, s, cacheFile))
  410. } else {
  411. protos = append(protos, fmt.Sprintf("https(:%v)", httpsPort))
  412. }
  413. if useLetsEncrypt {
  414. protos = append(protos, "letsencrypt")
  415. } else if ssKey != "" {
  416. protos = append(protos, fmt.Sprintf("self-sign(%v, %v)", ssKey, ssCert))
  417. } else if len(sdomains) == 0 {
  418. return oe.New("no ssl config")
  419. }
  420. for i := 0; i < len(sdomains); i++ {
  421. sdomain, skey, scert := sdomains[i], skeys[i], scerts[i]
  422. if f, err := os.Open(scert); err != nil {
  423. return oe.Wrapf(err, "open cert %v for %v err %+v", scert, sdomain, err)
  424. } else {
  425. f.Close()
  426. }
  427. if f, err := os.Open(skey); err != nil {
  428. return oe.Wrapf(err, "open key %v for %v err %+v", skey, sdomain, err)
  429. } else {
  430. f.Close()
  431. }
  432. protos = append(protos, fmt.Sprintf("ssl(%v,%v,%v)", sdomain, skey, scert))
  433. }
  434. }
  435. ol.Tf(ctx, "%v html root at %v", strings.Join(protos, ", "), string(html))
  436. if len(httpsPorts) > 0 && !useLetsEncrypt && ssKey != "" {
  437. if f, err := os.Open(ssCert); err != nil {
  438. return oe.Wrapf(err, "open cert %v err %+v", ssCert, err)
  439. } else {
  440. f.Close()
  441. }
  442. if f, err := os.Open(ssKey); err != nil {
  443. return oe.Wrapf(err, "open key %v err %+v", ssKey, err)
  444. } else {
  445. f.Close()
  446. }
  447. }
  448. wg := sync.WaitGroup{}
  449. ctx, cancel := context.WithCancel(ctx)
  450. defer cancel()
  451. var httpServers []*http.Server
  452. for _, v := range httpPorts {
  453. httpPort, err := strconv.ParseInt(v, 10, 64)
  454. if err != nil {
  455. return oe.Wrapf(err, "parse %v", v)
  456. }
  457. wg.Add(1)
  458. go func(httpPort int) {
  459. defer wg.Done()
  460. ctx = ol.WithContext(ctx)
  461. if httpPort == 0 {
  462. ol.W(ctx, "http server disabled")
  463. return
  464. }
  465. defer cancel()
  466. hs := &http.Server{Addr: fmt.Sprintf(":%v", httpPort), Handler: nil}
  467. httpServers = append(httpServers, hs)
  468. ol.Tf(ctx, "http serve at %v", httpPort)
  469. if err := hs.ListenAndServe(); err != nil {
  470. ol.Ef(ctx, "http serve err %+v", err)
  471. return
  472. }
  473. ol.T("http server ok")
  474. }(int(httpPort))
  475. }
  476. for _, v := range httpsPorts {
  477. httpsPort, err := strconv.ParseInt(v, 10, 64)
  478. if err != nil {
  479. return oe.Wrapf(err, "parse %v", v)
  480. }
  481. wg.Add(1)
  482. go func() {
  483. defer wg.Done()
  484. ctx = ol.WithContext(ctx)
  485. if httpsPort == 0 {
  486. ol.W(ctx, "https server disabled")
  487. return
  488. }
  489. defer cancel()
  490. var err error
  491. var m https.Manager
  492. if useLetsEncrypt {
  493. var domains []string
  494. if httpsDomains != "" {
  495. domains = strings.Split(httpsDomains, ",")
  496. }
  497. if m, err = https.NewLetsencryptManager("", domains, cacheFile); err != nil {
  498. ol.Ef(ctx, "create letsencrypt manager err %+v", err)
  499. return
  500. }
  501. } else if ssKey != "" {
  502. if m, err = https.NewSelfSignManager(ssCert, ssKey); err != nil {
  503. ol.Ef(ctx, "create self-sign manager err %+v", err)
  504. return
  505. }
  506. } else if len(sdomains) > 0 {
  507. if m, err = NewCertsManager(sdomains, skeys, scerts); err != nil {
  508. ol.Ef(ctx, "create ssl managers err %+v", err)
  509. return
  510. }
  511. }
  512. hss := &http.Server{
  513. Addr: fmt.Sprintf(":%v", httpsPort),
  514. TLSConfig: &tls.Config{
  515. GetCertificate: m.GetCertificate,
  516. },
  517. }
  518. httpServers = append(httpServers, hss)
  519. ol.Tf(ctx, "https serve at %v", httpsPort)
  520. if err = hss.ListenAndServeTLS("", ""); err != nil {
  521. ol.Ef(ctx, "https serve err %+v", err)
  522. return
  523. }
  524. ol.T("https serve ok")
  525. }()
  526. }
  527. select {
  528. case <-ctx.Done():
  529. for _, server := range httpServers {
  530. server.Close()
  531. }
  532. }
  533. wg.Wait()
  534. return nil
  535. }
  536. func main() {
  537. ctx := ol.WithContext(context.Background())
  538. if err := run(ctx); err != nil {
  539. ol.Ef(ctx, "run err %+v", err)
  540. os.Exit(-1)
  541. }
  542. }