oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "context"
5 "crypto/tls"
6 "fmt"
7 "io"
8 "net"
9 "net/http"
10 "net/http/httptrace"
11 "sync"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/equipo"
15)
16
17func runCheckCommand(args []string, out io.Writer, transport http.RoundTripper) (bool, int) {
18 if len(args) != 1 || args[0] != "check-github" {
19 return false, 0
20 }
21 return true, checkGitHub(context.Background(), out, transport)
22}
23
24func githubCheckClient(transport http.RoundTripper) *http.Client {
25 if transport == nil {
26 // Direct egress: no environment proxy, cookies or ambient credentials.
27 transport = &http.Transport{
28 DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext,
29 TLSHandshakeTimeout: 5 * time.Second,
30 MaxResponseHeaderBytes: 16 << 10,
31 DisableKeepAlives: true,
32 }
33 }
34 return &http.Client{
35 Transport: transport,
36 Timeout: 5 * time.Second,
37 CheckRedirect: func(*http.Request, []*http.Request) error {
38 return http.ErrUseLastResponse
39 },
40 }
41}
42
43func checkGitHub(ctx context.Context, out io.Writer, transport http.RoundTripper) int {
44 started := time.Now()
45 peer := "-"
46 var peerMu sync.Mutex
47 trace := &httptrace.ClientTrace{GotConn: func(info httptrace.GotConnInfo) {
48 if conn, ok := info.Conn.(*tls.Conn); ok && len(conn.ConnectionState().VerifiedChains) > 0 {
49 peerMu.Lock()
50 peer = conn.RemoteAddr().String()
51 peerMu.Unlock()
52 }
53 }}
54 req, _ := http.NewRequestWithContext(httptrace.WithClientTrace(ctx, trace), http.MethodGet, "https://api.github.com/meta", nil)
55 client := githubCheckClient(transport)
56 defer client.CloseIdleConnections()
57 resp, err := client.Do(req)
58 status := 0
59 reachable := false
60 if resp != nil {
61 status = resp.StatusCode
62 reachable = resp.TLS != nil && len(resp.TLS.VerifiedChains) > 0
63 // No response body is read, including error and redirect bodies.
64 _ = resp.Body.Close()
65 }
66 peerMu.Lock()
67 _, writeErr := fmt.Fprintf(out, equipo.CopyGitHubEgress, reachable, status, time.Since(started).Round(time.Millisecond), peer)
68 peerMu.Unlock()
69 if err != nil || writeErr != nil || !reachable || status < 200 || status >= 300 {
70 return 1
71 }
72 return 0
73}
74