Stable APIs for Go. https://go.code.as
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

515 lines
14 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "errors"
  6. "flag"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "os"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "text/template"
  17. "time"
  18. "golang.org/x/crypto/acme/autocert"
  19. )
  20. var (
  21. httpFlag = flag.String("http", ":8080", "Serve HTTP at given address")
  22. httpsFlag = flag.String("https", "", "Serve HTTPS at given address")
  23. certFlag = flag.String("cert", "", "Use the provided TLS certificate")
  24. keyFlag = flag.String("key", "", "Use the provided TLS key")
  25. acmeFlag = flag.String("acme", "", "Auto-request TLS certs and store in given directory")
  26. )
  27. var httpServer = &http.Server{
  28. ReadTimeout: 30 * time.Second,
  29. WriteTimeout: 5 * time.Minute,
  30. }
  31. var httpClient = &http.Client{
  32. Timeout: 10 * time.Second,
  33. }
  34. var bulkClient = &http.Client{
  35. Timeout: 5 * time.Minute,
  36. }
  37. func main() {
  38. if err := run(); err != nil {
  39. fmt.Fprintf(os.Stderr, "error: %v\n", err)
  40. os.Exit(1)
  41. }
  42. }
  43. func run() error {
  44. flag.Parse()
  45. http.HandleFunc("/", handler)
  46. if *httpFlag == "" && *httpsFlag == "" {
  47. return fmt.Errorf("must provide -http and/or -https")
  48. }
  49. if *acmeFlag != "" && *httpsFlag == "" {
  50. return fmt.Errorf("cannot use -acme without -https")
  51. }
  52. if *acmeFlag != "" && (*certFlag != "" || *keyFlag != "") {
  53. return fmt.Errorf("cannot provide -acme with -key or -cert")
  54. }
  55. if *acmeFlag == "" && (*httpsFlag != "" || *certFlag != "" || *keyFlag != "") && (*httpsFlag == "" || *certFlag == "" || *keyFlag == "") {
  56. return fmt.Errorf("-https -cert and -key must be used together")
  57. }
  58. ch := make(chan error, 2)
  59. if *acmeFlag != "" {
  60. // So a potential error is seen upfront.
  61. if err := os.MkdirAll(*acmeFlag, 0700); err != nil {
  62. return err
  63. }
  64. }
  65. if *httpFlag != "" && (*httpsFlag == "" || *acmeFlag == "") {
  66. server := *httpServer
  67. server.Addr = *httpFlag
  68. go func() {
  69. ch <- server.ListenAndServe()
  70. }()
  71. }
  72. if *httpsFlag != "" {
  73. server := *httpServer
  74. server.Addr = *httpsFlag
  75. if *acmeFlag != "" {
  76. m := autocert.Manager{
  77. ForceRSA: true,
  78. Prompt: autocert.AcceptTOS,
  79. Cache: autocert.DirCache(*acmeFlag),
  80. RenewBefore: 24 * 30 * time.Hour,
  81. HostPolicy: autocert.HostWhitelist(
  82. "localhost",
  83. "gopkg.in",
  84. "p1.gopkg.in",
  85. "p2.gopkg.in",
  86. "p3.gopkg.in",
  87. "mup.labix.org",
  88. ),
  89. Email: "gustavo@niemeyer.net",
  90. }
  91. server.TLSConfig = &tls.Config{
  92. GetCertificate: m.GetCertificate,
  93. }
  94. go func() {
  95. ch <- http.ListenAndServe(":80", m.HTTPHandler(nil))
  96. }()
  97. }
  98. go func() {
  99. ch <- server.ListenAndServeTLS(*certFlag, *keyFlag)
  100. }()
  101. }
  102. return <-ch
  103. }
  104. var gogetTemplate = template.Must(template.New("").Parse(`
  105. <html>
  106. <head>
  107. <meta name="go-import" content="{{.GopkgRoot}} git https://{{.GopkgRoot}}">
  108. {{$root := .GitHubRoot}}{{$tree := .GitHubTree}}<meta name="go-source" content="{{.GopkgRoot}} _ https://{{$root}}/tree/{{$tree}}{/dir} https://{{$root}}/blob/{{$tree}}{/dir}/{file}#L{line}">
  109. </head>
  110. <body>
  111. go get {{.GopkgPath}}
  112. </body>
  113. </html>
  114. `))
  115. // Repo represents a source code repository on GitHub.
  116. type Repo struct {
  117. User string
  118. Name string
  119. SubPath string
  120. OldFormat bool // The old /v2/pkg format.
  121. MajorVersion Version
  122. // FullVersion is the best version in AllVersions that matches MajorVersion.
  123. // It defaults to InvalidVersion if there are no matches.
  124. FullVersion Version
  125. // AllVersions holds all versions currently available in the repository,
  126. // either coming from branch names or from tag names. Version zero (v0)
  127. // is only present in the list if it really exists in the repository.
  128. AllVersions VersionList
  129. }
  130. // SetVersions records in the relevant fields the details about which
  131. // package versions are available in the repository.
  132. func (repo *Repo) SetVersions(all []Version) {
  133. repo.AllVersions = all
  134. for _, v := range repo.AllVersions {
  135. if v.Major == repo.MajorVersion.Major && v.Unstable == repo.MajorVersion.Unstable && repo.FullVersion.Less(v) {
  136. repo.FullVersion = v
  137. }
  138. }
  139. }
  140. type repoBase struct {
  141. user string
  142. name string
  143. }
  144. var redirect = map[repoBase]repoBase{
  145. // https://github.com/go-fsnotify/fsnotify/issues/1
  146. {"", "fsnotify"}: {"fsnotify", "fsnotify"},
  147. }
  148. // GitHubRoot returns the repository root at GitHub, without a schema.
  149. func (repo *Repo) GitHubRoot() string {
  150. if repo.User == "" {
  151. return "github.com/go-" + repo.Name + "/" + repo.Name
  152. } else {
  153. return "github.com/" + repo.User + "/" + repo.Name
  154. }
  155. }
  156. // GitHubTree returns the repository tree name at GitHub for the selected version.
  157. func (repo *Repo) GitHubTree() string {
  158. if repo.FullVersion == InvalidVersion {
  159. return "master"
  160. }
  161. return repo.FullVersion.String()
  162. }
  163. // GopkgRoot returns the package root at gopkg.in, without a schema.
  164. func (repo *Repo) GopkgRoot() string {
  165. return repo.GopkgVersionRoot(repo.MajorVersion)
  166. }
  167. // GopkgPath returns the package path at gopkg.in, without a schema.
  168. func (repo *Repo) GopkgPath() string {
  169. return repo.GopkgVersionRoot(repo.MajorVersion) + repo.SubPath
  170. }
  171. // GopkgVersionRoot returns the package root in gopkg.in for the
  172. // provided version, without a schema.
  173. func (repo *Repo) GopkgVersionRoot(version Version) string {
  174. version.Minor = -1
  175. version.Patch = -1
  176. v := version.String()
  177. if repo.OldFormat {
  178. if repo.User == "" {
  179. return "gopkg.in/" + v + "/" + repo.Name
  180. } else {
  181. return "gopkg.in/" + repo.User + "/" + v + "/" + repo.Name
  182. }
  183. } else {
  184. if repo.User == "" {
  185. return "gopkg.in/" + repo.Name + "." + v
  186. } else {
  187. return "gopkg.in/" + repo.User + "/" + repo.Name + "." + v
  188. }
  189. }
  190. }
  191. var patternOld = regexp.MustCompile(`^/(?:([a-z0-9][-a-z0-9]+)/)?((?:v0|v[1-9][0-9]*)(?:\.0|\.[1-9][0-9]*){0,2}(?:-unstable)?)/([a-zA-Z][-a-zA-Z0-9]*)(?:\.git)?((?:/[a-zA-Z][-a-zA-Z0-9]*)*)$`)
  192. var patternNew = regexp.MustCompile(`^/(?:([a-zA-Z0-9][-a-zA-Z0-9]+)/)?([a-zA-Z][-.a-zA-Z0-9]*)\.((?:v0|v[1-9][0-9]*)(?:\.0|\.[1-9][0-9]*){0,2}(?:-unstable)?)(?:\.git)?((?:/[a-zA-Z0-9][-.a-zA-Z0-9]*)*)$`)
  193. func handler(resp http.ResponseWriter, req *http.Request) {
  194. if req.URL.Path == "/health-check" {
  195. resp.Write([]byte("ok"))
  196. return
  197. }
  198. log.Printf("%s requested %s", req.RemoteAddr, req.URL)
  199. if req.URL.Path == "/" {
  200. resp.Header().Set("Location", "http://labix.org/gopkg.in")
  201. resp.WriteHeader(http.StatusTemporaryRedirect)
  202. return
  203. }
  204. m := patternNew.FindStringSubmatch(req.URL.Path)
  205. oldFormat := false
  206. if m == nil {
  207. m = patternOld.FindStringSubmatch(req.URL.Path)
  208. if m == nil {
  209. sendNotFound(resp, "Unsupported URL pattern; see the documentation at gopkg.in for details.")
  210. return
  211. }
  212. // "/v2/name" <= "/name.v2"
  213. m[2], m[3] = m[3], m[2]
  214. oldFormat = true
  215. }
  216. if strings.Contains(m[3], ".") {
  217. sendNotFound(resp, "Import paths take the major version only (.%s instead of .%s); see docs at gopkg.in for the reasoning.",
  218. m[3][:strings.Index(m[3], ".")], m[3])
  219. return
  220. }
  221. repo := &Repo{
  222. User: m[1],
  223. Name: m[2],
  224. SubPath: m[4],
  225. OldFormat: oldFormat,
  226. FullVersion: InvalidVersion,
  227. }
  228. if r, ok := redirect[repoBase{repo.User, repo.Name}]; ok {
  229. repo.User, repo.Name = r.user, r.name
  230. }
  231. var ok bool
  232. repo.MajorVersion, ok = parseVersion(m[3])
  233. if !ok {
  234. sendNotFound(resp, "Version %q improperly considered invalid; please warn the service maintainers.", m[3])
  235. return
  236. }
  237. var changed []byte
  238. var versions VersionList
  239. original, err := fetchRefs(repo)
  240. if err == nil {
  241. changed, versions, err = changeRefs(original, repo.MajorVersion)
  242. repo.SetVersions(versions)
  243. }
  244. switch err {
  245. case nil:
  246. // all ok
  247. case ErrNoRepo:
  248. sendNotFound(resp, "GitHub repository not found at https://%s", repo.GitHubRoot())
  249. return
  250. case ErrNoVersion:
  251. major := repo.MajorVersion
  252. suffix := ""
  253. if major.Unstable {
  254. major.Unstable = false
  255. suffix = unstableSuffix
  256. }
  257. v := major.String()
  258. sendNotFound(resp, `GitHub repository at https://%s has no branch or tag "%s%s", "%s.N%s" or "%s.N.M%s"`, repo.GitHubRoot(), v, suffix, v, suffix, v, suffix)
  259. return
  260. default:
  261. resp.WriteHeader(http.StatusBadGateway)
  262. resp.Write([]byte(fmt.Sprintf("Cannot obtain refs from GitHub: %v", err)))
  263. return
  264. }
  265. if repo.SubPath == "/git-upload-pack" {
  266. proxyUploadPack(resp, req, repo)
  267. return
  268. }
  269. if repo.SubPath == "/info/refs" {
  270. resp.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement")
  271. resp.Write(changed)
  272. return
  273. }
  274. resp.Header().Set("Content-Type", "text/html")
  275. if req.FormValue("go-get") == "1" {
  276. // execute simple template when this is a go-get request
  277. err = gogetTemplate.Execute(resp, repo)
  278. if err != nil {
  279. log.Printf("error executing go get template: %s\n", err)
  280. }
  281. return
  282. }
  283. renderPackagePage(resp, req, repo)
  284. }
  285. func sendNotFound(resp http.ResponseWriter, msg string, args ...interface{}) {
  286. if len(args) > 0 {
  287. msg = fmt.Sprintf(msg, args...)
  288. }
  289. resp.WriteHeader(http.StatusNotFound)
  290. resp.Write([]byte(msg))
  291. }
  292. const refsSuffix = ".git/info/refs?service=git-upload-pack"
  293. func proxyUploadPack(resp http.ResponseWriter, req *http.Request, repo *Repo) {
  294. preq, err := http.NewRequest(req.Method, "https://"+repo.GitHubRoot()+"/git-upload-pack", req.Body)
  295. if err != nil {
  296. resp.WriteHeader(http.StatusInternalServerError)
  297. resp.Write([]byte(fmt.Sprintf("Cannot create GitHub request: %v", err)))
  298. return
  299. }
  300. preq.Header = req.Header
  301. presp, err := bulkClient.Do(preq)
  302. if err != nil {
  303. resp.WriteHeader(http.StatusBadGateway)
  304. resp.Write([]byte(fmt.Sprintf("Cannot obtain data pack from GitHub: %v", err)))
  305. return
  306. }
  307. defer presp.Body.Close()
  308. header := resp.Header()
  309. for key, values := range presp.Header {
  310. header[key] = values
  311. }
  312. resp.WriteHeader(presp.StatusCode)
  313. // Ignore errors. Dropped connections are usual and will make this fail.
  314. _, err = io.Copy(resp, presp.Body)
  315. if err != nil {
  316. log.Printf("Error copying data from GitHub: %v", err)
  317. }
  318. }
  319. var ErrNoRepo = errors.New("repository not found in GitHub")
  320. var ErrNoVersion = errors.New("version reference not found in GitHub")
  321. func fetchRefs(repo *Repo) (data []byte, err error) {
  322. resp, err := httpClient.Get("https://" + repo.GitHubRoot() + refsSuffix)
  323. if err != nil {
  324. return nil, fmt.Errorf("cannot talk to GitHub: %v", err)
  325. }
  326. defer resp.Body.Close()
  327. switch resp.StatusCode {
  328. case 200:
  329. // ok
  330. case 401, 404:
  331. return nil, ErrNoRepo
  332. default:
  333. return nil, fmt.Errorf("error from GitHub: %v", resp.Status)
  334. }
  335. data, err = ioutil.ReadAll(resp.Body)
  336. if err != nil {
  337. return nil, fmt.Errorf("error reading from GitHub: %v", err)
  338. }
  339. return data, err
  340. }
  341. func changeRefs(data []byte, major Version) (changed []byte, versions VersionList, err error) {
  342. var hlinei, hlinej int // HEAD reference line start/end
  343. var mlinei, mlinej int // master reference line start/end
  344. var vrefhash string
  345. var vrefname string
  346. var vrefv = InvalidVersion
  347. // Record all available versions, the locations of the master and HEAD lines,
  348. // and details of the best reference satisfying the requested major version.
  349. versions = make([]Version, 0)
  350. sdata := string(data)
  351. for i, j := 0, 0; i < len(data); i = j {
  352. size, err := strconv.ParseInt(sdata[i:i+4], 16, 32)
  353. if err != nil {
  354. return nil, nil, fmt.Errorf("cannot parse refs line size: %s", string(data[i:i+4]))
  355. }
  356. if size == 0 {
  357. size = 4
  358. }
  359. j = i + int(size)
  360. if j > len(sdata) {
  361. return nil, nil, fmt.Errorf("incomplete refs data received from GitHub")
  362. }
  363. if sdata[0] == '#' {
  364. continue
  365. }
  366. hashi := i + 4
  367. hashj := strings.IndexByte(sdata[hashi:j], ' ')
  368. if hashj < 0 || hashj != 40 {
  369. continue
  370. }
  371. hashj += hashi
  372. namei := hashj + 1
  373. namej := strings.IndexAny(sdata[namei:j], "\n\x00")
  374. if namej < 0 {
  375. namej = j
  376. } else {
  377. namej += namei
  378. }
  379. name := sdata[namei:namej]
  380. if name == "HEAD" {
  381. hlinei = i
  382. hlinej = j
  383. }
  384. if name == "refs/heads/master" {
  385. mlinei = i
  386. mlinej = j
  387. }
  388. if strings.HasPrefix(name, "refs/heads/v") || strings.HasPrefix(name, "refs/tags/v") {
  389. if strings.HasSuffix(name, "^{}") {
  390. // Annotated tag is peeled off and overrides the same version just parsed.
  391. name = name[:len(name)-3]
  392. }
  393. v, ok := parseVersion(name[strings.IndexByte(name, 'v'):])
  394. if ok && major.Contains(v) && (v == vrefv || !vrefv.IsValid() || vrefv.Less(v)) {
  395. vrefv = v
  396. vrefhash = sdata[hashi:hashj]
  397. vrefname = name
  398. }
  399. if ok {
  400. versions = append(versions, v)
  401. }
  402. }
  403. }
  404. // If there were absolutely no versions, and v0 was requested, accept the master as-is.
  405. if len(versions) == 0 && major == (Version{0, -1, -1, false}) {
  406. return data, nil, nil
  407. }
  408. // If the file has no HEAD line or the version was not found, report as unavailable.
  409. if hlinei == 0 || vrefhash == "" {
  410. return nil, nil, ErrNoVersion
  411. }
  412. var buf bytes.Buffer
  413. buf.Grow(len(data) + 256)
  414. // Copy the header as-is.
  415. buf.Write(data[:hlinei])
  416. // Extract the original capabilities.
  417. caps := ""
  418. if i := strings.Index(sdata[hlinei:hlinej], "\x00"); i > 0 {
  419. caps = strings.Replace(sdata[hlinei+i+1:hlinej-1], "symref=", "oldref=", -1)
  420. }
  421. // Insert the HEAD reference line with the right hash and a proper symref capability.
  422. var line string
  423. if strings.HasPrefix(vrefname, "refs/heads/") {
  424. if caps == "" {
  425. line = fmt.Sprintf("%s HEAD\x00symref=HEAD:%s\n", vrefhash, vrefname)
  426. } else {
  427. line = fmt.Sprintf("%s HEAD\x00symref=HEAD:%s %s\n", vrefhash, vrefname, caps)
  428. }
  429. } else {
  430. if caps == "" {
  431. line = fmt.Sprintf("%s HEAD\n", vrefhash)
  432. } else {
  433. line = fmt.Sprintf("%s HEAD\x00%s\n", vrefhash, caps)
  434. }
  435. }
  436. fmt.Fprintf(&buf, "%04x%s", 4+len(line), line)
  437. // Insert the master reference line.
  438. line = fmt.Sprintf("%s refs/heads/master\n", vrefhash)
  439. fmt.Fprintf(&buf, "%04x%s", 4+len(line), line)
  440. // Append the rest, dropping the original master line if necessary.
  441. if mlinei > 0 {
  442. buf.Write(data[hlinej:mlinei])
  443. buf.Write(data[mlinej:])
  444. } else {
  445. buf.Write(data[hlinej:])
  446. }
  447. return buf.Bytes(), versions, nil
  448. }