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.

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