code.gitea.io/gitea@v1.19.3/modules/private/internal.go (about) 1 // Copyright 2017 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package private 5 6 import ( 7 "context" 8 "crypto/tls" 9 "fmt" 10 "net" 11 "net/http" 12 "os" 13 "strings" 14 15 "code.gitea.io/gitea/modules/httplib" 16 "code.gitea.io/gitea/modules/json" 17 "code.gitea.io/gitea/modules/log" 18 "code.gitea.io/gitea/modules/proxyprotocol" 19 "code.gitea.io/gitea/modules/setting" 20 ) 21 22 func newRequest(ctx context.Context, url, method, sourceIP string) *httplib.Request { 23 if setting.InternalToken == "" { 24 log.Fatal(`The INTERNAL_TOKEN setting is missing from the configuration file: %q. 25 Ensure you are running in the correct environment or set the correct configuration file with -c.`, setting.CustomConf) 26 } 27 return httplib.NewRequest(url, method). 28 SetContext(ctx). 29 Header("X-Real-IP", sourceIP). 30 Header("Authorization", fmt.Sprintf("Bearer %s", setting.InternalToken)) 31 } 32 33 // Response internal request response 34 type Response struct { 35 Err string `json:"err"` 36 } 37 38 func decodeJSONError(resp *http.Response) *Response { 39 var res Response 40 err := json.NewDecoder(resp.Body).Decode(&res) 41 if err != nil { 42 res.Err = err.Error() 43 } 44 return &res 45 } 46 47 func getClientIP() string { 48 sshConnEnv := strings.TrimSpace(os.Getenv("SSH_CONNECTION")) 49 if len(sshConnEnv) == 0 { 50 return "127.0.0.1" 51 } 52 return strings.Fields(sshConnEnv)[0] 53 } 54 55 func newInternalRequest(ctx context.Context, url, method string) *httplib.Request { 56 req := newRequest(ctx, url, method, getClientIP()).SetTLSClientConfig(&tls.Config{ 57 InsecureSkipVerify: true, 58 ServerName: setting.Domain, 59 }) 60 if setting.Protocol == setting.HTTPUnix { 61 req.SetTransport(&http.Transport{ 62 DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { 63 var d net.Dialer 64 conn, err := d.DialContext(ctx, "unix", setting.HTTPAddr) 65 if err != nil { 66 return conn, err 67 } 68 if setting.LocalUseProxyProtocol { 69 if err = proxyprotocol.WriteLocalHeader(conn); err != nil { 70 _ = conn.Close() 71 return nil, err 72 } 73 } 74 return conn, err 75 }, 76 }) 77 } else if setting.LocalUseProxyProtocol { 78 req.SetTransport(&http.Transport{ 79 DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { 80 var d net.Dialer 81 conn, err := d.DialContext(ctx, network, address) 82 if err != nil { 83 return conn, err 84 } 85 if err = proxyprotocol.WriteLocalHeader(conn); err != nil { 86 _ = conn.Close() 87 return nil, err 88 } 89 return conn, err 90 }, 91 }) 92 } 93 return req 94 }