api_request.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. package channel
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. "time"
  12. common2 "github.com/QuantumNous/new-api/common"
  13. "github.com/QuantumNous/new-api/logger"
  14. "github.com/QuantumNous/new-api/relay/common"
  15. "github.com/QuantumNous/new-api/relay/constant"
  16. "github.com/QuantumNous/new-api/relay/helper"
  17. "github.com/QuantumNous/new-api/service"
  18. "github.com/QuantumNous/new-api/setting/operation_setting"
  19. "github.com/QuantumNous/new-api/types"
  20. "github.com/bytedance/gopkg/util/gopool"
  21. "github.com/gin-gonic/gin"
  22. "github.com/gorilla/websocket"
  23. )
  24. func SetupApiRequestHeader(info *common.RelayInfo, c *gin.Context, req *http.Header) {
  25. if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
  26. // multipart/form-data
  27. } else if info.RelayMode == constant.RelayModeRealtime {
  28. // websocket
  29. } else {
  30. req.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  31. req.Set("Accept", c.Request.Header.Get("Accept"))
  32. if info.IsStream && c.Request.Header.Get("Accept") == "" {
  33. req.Set("Accept", "text/event-stream")
  34. }
  35. }
  36. }
  37. const clientHeaderPlaceholderPrefix = "{client_header:"
  38. const (
  39. headerPassthroughAllKey = "*"
  40. headerPassthroughRegexPrefix = "re:"
  41. headerPassthroughRegexPrefixV2 = "regex:"
  42. )
  43. var passthroughSkipHeaderNamesLower = map[string]struct{}{
  44. // RFC 7230 hop-by-hop headers.
  45. "connection": {},
  46. "keep-alive": {},
  47. "proxy-authenticate": {},
  48. "proxy-authorization": {},
  49. "te": {},
  50. "trailer": {},
  51. "transfer-encoding": {},
  52. "upgrade": {},
  53. "cookie": {},
  54. // Additional headers that should not be forwarded by name-matching passthrough rules.
  55. "host": {},
  56. "content-length": {},
  57. "accept-encoding": {},
  58. // Do not passthrough credentials by wildcard/regex.
  59. "authorization": {},
  60. "x-api-key": {},
  61. "x-goog-api-key": {},
  62. // WebSocket handshake headers are generated by the client/dialer.
  63. "sec-websocket-key": {},
  64. "sec-websocket-version": {},
  65. "sec-websocket-extensions": {},
  66. }
  67. var headerPassthroughRegexCache sync.Map // map[string]*regexp.Regexp
  68. func getHeaderPassthroughRegex(pattern string) (*regexp.Regexp, error) {
  69. pattern = strings.TrimSpace(pattern)
  70. if pattern == "" {
  71. return nil, errors.New("empty regex pattern")
  72. }
  73. if v, ok := headerPassthroughRegexCache.Load(pattern); ok {
  74. if re, ok := v.(*regexp.Regexp); ok {
  75. return re, nil
  76. }
  77. headerPassthroughRegexCache.Delete(pattern)
  78. }
  79. compiled, err := regexp.Compile(pattern)
  80. if err != nil {
  81. return nil, err
  82. }
  83. actual, _ := headerPassthroughRegexCache.LoadOrStore(pattern, compiled)
  84. if re, ok := actual.(*regexp.Regexp); ok {
  85. return re, nil
  86. }
  87. return compiled, nil
  88. }
  89. func isHeaderPassthroughRuleKey(key string) bool {
  90. key = strings.TrimSpace(key)
  91. if key == "" {
  92. return false
  93. }
  94. if key == headerPassthroughAllKey {
  95. return true
  96. }
  97. lower := strings.ToLower(key)
  98. return strings.HasPrefix(lower, headerPassthroughRegexPrefix) || strings.HasPrefix(lower, headerPassthroughRegexPrefixV2)
  99. }
  100. func shouldSkipPassthroughHeader(name string) bool {
  101. name = strings.TrimSpace(name)
  102. if name == "" {
  103. return true
  104. }
  105. lower := strings.ToLower(name)
  106. if _, ok := passthroughSkipHeaderNamesLower[lower]; ok {
  107. return true
  108. }
  109. return false
  110. }
  111. func applyHeaderOverridePlaceholders(template string, c *gin.Context, apiKey string) (string, bool, error) {
  112. trimmed := strings.TrimSpace(template)
  113. if strings.HasPrefix(trimmed, clientHeaderPlaceholderPrefix) {
  114. afterPrefix := trimmed[len(clientHeaderPlaceholderPrefix):]
  115. end := strings.Index(afterPrefix, "}")
  116. if end < 0 || end != len(afterPrefix)-1 {
  117. return "", false, fmt.Errorf("client_header placeholder must be the full value: %q", template)
  118. }
  119. name := strings.TrimSpace(afterPrefix[:end])
  120. if name == "" {
  121. return "", false, fmt.Errorf("client_header placeholder name is empty: %q", template)
  122. }
  123. if c == nil || c.Request == nil {
  124. return "", false, fmt.Errorf("missing request context for client_header placeholder")
  125. }
  126. clientHeaderValue := c.Request.Header.Get(name)
  127. if strings.TrimSpace(clientHeaderValue) == "" {
  128. return "", false, nil
  129. }
  130. // Do not interpolate {api_key} inside client-supplied content.
  131. return clientHeaderValue, true, nil
  132. }
  133. if strings.Contains(template, "{api_key}") {
  134. template = strings.ReplaceAll(template, "{api_key}", apiKey)
  135. }
  136. if strings.TrimSpace(template) == "" {
  137. return "", false, nil
  138. }
  139. return template, true, nil
  140. }
  141. // processHeaderOverride applies channel header overrides, with placeholder substitution.
  142. // Supported placeholders:
  143. // - {api_key}: resolved to the channel API key
  144. // - {client_header:<name>}: resolved to the incoming request header value
  145. //
  146. // Header passthrough rules (keys only; values are ignored):
  147. // - "*": passthrough all incoming headers by name (excluding unsafe headers)
  148. // - "re:<regex>" / "regex:<regex>": passthrough headers whose names match the regex (Go regexp)
  149. //
  150. // Passthrough rules are applied first, then normal overrides are applied, so explicit overrides win.
  151. func processHeaderOverride(info *common.RelayInfo, c *gin.Context) (map[string]string, error) {
  152. headerOverride := make(map[string]string)
  153. if info == nil {
  154. return headerOverride, nil
  155. }
  156. headerOverrideSource := common.GetEffectiveHeaderOverride(info)
  157. passAll := false
  158. var passthroughRegex []*regexp.Regexp
  159. if !info.IsChannelTest {
  160. for k := range headerOverrideSource {
  161. key := strings.TrimSpace(strings.ToLower(k))
  162. if key == "" {
  163. continue
  164. }
  165. if key == headerPassthroughAllKey {
  166. passAll = true
  167. continue
  168. }
  169. var pattern string
  170. switch {
  171. case strings.HasPrefix(key, headerPassthroughRegexPrefix):
  172. pattern = strings.TrimSpace(key[len(headerPassthroughRegexPrefix):])
  173. case strings.HasPrefix(key, headerPassthroughRegexPrefixV2):
  174. pattern = strings.TrimSpace(key[len(headerPassthroughRegexPrefixV2):])
  175. default:
  176. continue
  177. }
  178. if pattern == "" {
  179. return nil, types.NewError(fmt.Errorf("header passthrough regex pattern is empty: %q", k), types.ErrorCodeChannelHeaderOverrideInvalid)
  180. }
  181. compiled, err := getHeaderPassthroughRegex(pattern)
  182. if err != nil {
  183. return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
  184. }
  185. passthroughRegex = append(passthroughRegex, compiled)
  186. }
  187. }
  188. if passAll || len(passthroughRegex) > 0 {
  189. if c == nil || c.Request == nil {
  190. return nil, types.NewError(fmt.Errorf("missing request context for header passthrough"), types.ErrorCodeChannelHeaderOverrideInvalid)
  191. }
  192. for name := range c.Request.Header {
  193. if shouldSkipPassthroughHeader(name) {
  194. continue
  195. }
  196. if !passAll {
  197. matched := false
  198. for _, re := range passthroughRegex {
  199. if re.MatchString(name) {
  200. matched = true
  201. break
  202. }
  203. }
  204. if !matched {
  205. continue
  206. }
  207. }
  208. value := strings.TrimSpace(c.Request.Header.Get(name))
  209. if value == "" {
  210. continue
  211. }
  212. headerOverride[strings.ToLower(strings.TrimSpace(name))] = value
  213. }
  214. }
  215. for k, v := range headerOverrideSource {
  216. if isHeaderPassthroughRuleKey(k) {
  217. continue
  218. }
  219. key := strings.TrimSpace(strings.ToLower(k))
  220. if key == "" {
  221. continue
  222. }
  223. str, ok := v.(string)
  224. if !ok {
  225. return nil, types.NewError(nil, types.ErrorCodeChannelHeaderOverrideInvalid)
  226. }
  227. if info.IsChannelTest && strings.HasPrefix(strings.TrimSpace(str), clientHeaderPlaceholderPrefix) {
  228. continue
  229. }
  230. value, include, err := applyHeaderOverridePlaceholders(str, c, info.ApiKey)
  231. if err != nil {
  232. return nil, types.NewError(err, types.ErrorCodeChannelHeaderOverrideInvalid)
  233. }
  234. if !include {
  235. continue
  236. }
  237. headerOverride[key] = value
  238. }
  239. return headerOverride, nil
  240. }
  241. func applyHeaderOverrideToRequest(req *http.Request, headerOverride map[string]string) {
  242. if req == nil {
  243. return
  244. }
  245. for key, value := range headerOverride {
  246. req.Header.Set(key, value)
  247. // set Host in req
  248. if strings.EqualFold(key, "Host") {
  249. req.Host = value
  250. }
  251. }
  252. }
  253. func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  254. fullRequestURL, err := a.GetRequestURL(info)
  255. if err != nil {
  256. return nil, fmt.Errorf("get request url failed: %w", err)
  257. }
  258. if common2.DebugEnabled {
  259. println("fullRequestURL:", fullRequestURL)
  260. }
  261. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  262. if err != nil {
  263. return nil, fmt.Errorf("new request failed: %w", err)
  264. }
  265. headers := req.Header
  266. err = a.SetupRequestHeader(c, &headers, info)
  267. if err != nil {
  268. return nil, fmt.Errorf("setup request header failed: %w", err)
  269. }
  270. // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
  271. // 这样可以覆盖默认的 Authorization header 设置
  272. headerOverride, err := processHeaderOverride(info, c)
  273. if err != nil {
  274. return nil, err
  275. }
  276. applyHeaderOverrideToRequest(req, headerOverride)
  277. resp, err := doRequest(c, req, info)
  278. if err != nil {
  279. return nil, fmt.Errorf("do request failed: %w", err)
  280. }
  281. return resp, nil
  282. }
  283. func DoFormRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  284. fullRequestURL, err := a.GetRequestURL(info)
  285. if err != nil {
  286. return nil, fmt.Errorf("get request url failed: %w", err)
  287. }
  288. if common2.DebugEnabled {
  289. println("fullRequestURL:", fullRequestURL)
  290. }
  291. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  292. if err != nil {
  293. return nil, fmt.Errorf("new request failed: %w", err)
  294. }
  295. // set form data
  296. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  297. headers := req.Header
  298. err = a.SetupRequestHeader(c, &headers, info)
  299. if err != nil {
  300. return nil, fmt.Errorf("setup request header failed: %w", err)
  301. }
  302. // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
  303. // 这样可以覆盖默认的 Authorization header 设置
  304. headerOverride, err := processHeaderOverride(info, c)
  305. if err != nil {
  306. return nil, err
  307. }
  308. applyHeaderOverrideToRequest(req, headerOverride)
  309. resp, err := doRequest(c, req, info)
  310. if err != nil {
  311. return nil, fmt.Errorf("do request failed: %w", err)
  312. }
  313. return resp, nil
  314. }
  315. func DoWssRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*websocket.Conn, error) {
  316. fullRequestURL, err := a.GetRequestURL(info)
  317. if err != nil {
  318. return nil, fmt.Errorf("get request url failed: %w", err)
  319. }
  320. targetHeader := http.Header{}
  321. err = a.SetupRequestHeader(c, &targetHeader, info)
  322. if err != nil {
  323. return nil, fmt.Errorf("setup request header failed: %w", err)
  324. }
  325. // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
  326. // 这样可以覆盖默认的 Authorization header 设置
  327. headerOverride, err := processHeaderOverride(info, c)
  328. if err != nil {
  329. return nil, err
  330. }
  331. for key, value := range headerOverride {
  332. targetHeader.Set(key, value)
  333. }
  334. targetHeader.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  335. targetConn, _, err := websocket.DefaultDialer.Dial(fullRequestURL, targetHeader)
  336. if err != nil {
  337. return nil, fmt.Errorf("dial failed to %s: %w", fullRequestURL, err)
  338. }
  339. // send request body
  340. //all, err := io.ReadAll(requestBody)
  341. //err = service.WssString(c, targetConn, string(all))
  342. return targetConn, nil
  343. }
  344. func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.CancelFunc {
  345. pingerCtx, stopPinger := context.WithCancel(context.Background())
  346. gopool.Go(func() {
  347. defer func() {
  348. // 增加panic恢复处理
  349. if r := recover(); r != nil {
  350. if common2.DebugEnabled {
  351. println("SSE ping goroutine panic recovered:", fmt.Sprintf("%v", r))
  352. }
  353. }
  354. if common2.DebugEnabled {
  355. println("SSE ping goroutine stopped.")
  356. }
  357. }()
  358. if pingInterval <= 0 {
  359. pingInterval = helper.DefaultPingInterval
  360. }
  361. ticker := time.NewTicker(pingInterval)
  362. // 确保在任何情况下都清理ticker
  363. defer func() {
  364. ticker.Stop()
  365. if common2.DebugEnabled {
  366. println("SSE ping ticker stopped")
  367. }
  368. }()
  369. var pingMutex sync.Mutex
  370. if common2.DebugEnabled {
  371. println("SSE ping goroutine started")
  372. }
  373. // 增加超时控制,防止goroutine长时间运行
  374. maxPingDuration := 120 * time.Minute // 最大ping持续时间
  375. pingTimeout := time.NewTimer(maxPingDuration)
  376. defer pingTimeout.Stop()
  377. for {
  378. select {
  379. // 发送 ping 数据
  380. case <-ticker.C:
  381. if err := sendPingData(c, &pingMutex); err != nil {
  382. if common2.DebugEnabled {
  383. println("SSE ping error, stopping goroutine:", err.Error())
  384. }
  385. return
  386. }
  387. // 收到退出信号
  388. case <-pingerCtx.Done():
  389. return
  390. // request 结束
  391. case <-c.Request.Context().Done():
  392. return
  393. // 超时保护,防止goroutine无限运行
  394. case <-pingTimeout.C:
  395. if common2.DebugEnabled {
  396. println("SSE ping goroutine timeout, stopping")
  397. }
  398. return
  399. }
  400. }
  401. })
  402. return stopPinger
  403. }
  404. func sendPingData(c *gin.Context, mutex *sync.Mutex) error {
  405. // 增加超时控制,防止锁死等待
  406. done := make(chan error, 1)
  407. go func() {
  408. mutex.Lock()
  409. defer mutex.Unlock()
  410. err := helper.PingData(c)
  411. if err != nil {
  412. logger.LogError(c, "SSE ping error: "+err.Error())
  413. done <- err
  414. return
  415. }
  416. if common2.DebugEnabled {
  417. println("SSE ping data sent.")
  418. }
  419. done <- nil
  420. }()
  421. // 设置发送ping数据的超时时间
  422. select {
  423. case err := <-done:
  424. return err
  425. case <-time.After(10 * time.Second):
  426. return errors.New("SSE ping data send timeout")
  427. case <-c.Request.Context().Done():
  428. return errors.New("request context cancelled during ping")
  429. }
  430. }
  431. func DoRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
  432. return doRequest(c, req, info)
  433. }
  434. func doRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
  435. var client *http.Client
  436. var err error
  437. if info.ChannelSetting.Proxy != "" {
  438. client, err = service.NewProxyHttpClient(info.ChannelSetting.Proxy)
  439. if err != nil {
  440. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  441. }
  442. } else {
  443. client = service.GetHttpClient()
  444. }
  445. var stopPinger context.CancelFunc
  446. if info.IsStream {
  447. helper.SetEventStreamHeaders(c)
  448. // 处理流式请求的 ping 保活
  449. generalSettings := operation_setting.GetGeneralSetting()
  450. if generalSettings.PingIntervalEnabled && !info.DisablePing {
  451. pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second
  452. stopPinger = startPingKeepAlive(c, pingInterval)
  453. // 使用defer确保在任何情况下都能停止ping goroutine
  454. defer func() {
  455. if stopPinger != nil {
  456. stopPinger()
  457. if common2.DebugEnabled {
  458. println("SSE ping goroutine stopped by defer")
  459. }
  460. }
  461. }()
  462. }
  463. }
  464. resp, err := client.Do(req)
  465. if err != nil {
  466. logger.LogError(c, "do request failed: "+err.Error())
  467. return nil, types.NewError(err, types.ErrorCodeDoRequestFailed, types.ErrOptionWithHideErrMsg("upstream error: do request failed"))
  468. }
  469. if resp == nil {
  470. return nil, errors.New("resp is nil")
  471. }
  472. _ = req.Body.Close()
  473. _ = c.Request.Body.Close()
  474. return resp, nil
  475. }
  476. func DoTaskApiRequest(a TaskAdaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  477. fullRequestURL, err := a.BuildRequestURL(info)
  478. if err != nil {
  479. return nil, err
  480. }
  481. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  482. if err != nil {
  483. return nil, fmt.Errorf("new request failed: %w", err)
  484. }
  485. req.GetBody = func() (io.ReadCloser, error) {
  486. return io.NopCloser(requestBody), nil
  487. }
  488. err = a.BuildRequestHeader(c, req, info)
  489. if err != nil {
  490. return nil, fmt.Errorf("setup request header failed: %w", err)
  491. }
  492. resp, err := doRequest(c, req, info)
  493. if err != nil {
  494. return nil, fmt.Errorf("do request failed: %w", err)
  495. }
  496. return resp, nil
  497. }