api_request.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 ResolveHeaderOverride(info *common.RelayInfo, c *gin.Context) (map[string]string, error) {
  242. return processHeaderOverride(info, c)
  243. }
  244. func applyHeaderOverrideToRequest(req *http.Request, headerOverride map[string]string) {
  245. if req == nil {
  246. return
  247. }
  248. for key, value := range headerOverride {
  249. req.Header.Set(key, value)
  250. // set Host in req
  251. if strings.EqualFold(key, "Host") {
  252. req.Host = value
  253. }
  254. }
  255. }
  256. func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  257. fullRequestURL, err := a.GetRequestURL(info)
  258. if err != nil {
  259. return nil, fmt.Errorf("get request url failed: %w", err)
  260. }
  261. if common2.DebugEnabled {
  262. println("fullRequestURL:", fullRequestURL)
  263. }
  264. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  265. if err != nil {
  266. return nil, fmt.Errorf("new request failed: %w", err)
  267. }
  268. headers := req.Header
  269. err = a.SetupRequestHeader(c, &headers, info)
  270. if err != nil {
  271. return nil, fmt.Errorf("setup request header failed: %w", err)
  272. }
  273. // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
  274. // 这样可以覆盖默认的 Authorization header 设置
  275. headerOverride, err := processHeaderOverride(info, c)
  276. if err != nil {
  277. return nil, err
  278. }
  279. applyHeaderOverrideToRequest(req, headerOverride)
  280. resp, err := doRequest(c, req, info)
  281. if err != nil {
  282. return nil, fmt.Errorf("do request failed: %w", err)
  283. }
  284. return resp, nil
  285. }
  286. func DoFormRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  287. fullRequestURL, err := a.GetRequestURL(info)
  288. if err != nil {
  289. return nil, fmt.Errorf("get request url failed: %w", err)
  290. }
  291. if common2.DebugEnabled {
  292. println("fullRequestURL:", fullRequestURL)
  293. }
  294. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  295. if err != nil {
  296. return nil, fmt.Errorf("new request failed: %w", err)
  297. }
  298. // set form data
  299. req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  300. headers := req.Header
  301. err = a.SetupRequestHeader(c, &headers, info)
  302. if err != nil {
  303. return nil, fmt.Errorf("setup request header failed: %w", err)
  304. }
  305. // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
  306. // 这样可以覆盖默认的 Authorization header 设置
  307. headerOverride, err := processHeaderOverride(info, c)
  308. if err != nil {
  309. return nil, err
  310. }
  311. applyHeaderOverrideToRequest(req, headerOverride)
  312. resp, err := doRequest(c, req, info)
  313. if err != nil {
  314. return nil, fmt.Errorf("do request failed: %w", err)
  315. }
  316. return resp, nil
  317. }
  318. func DoWssRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*websocket.Conn, error) {
  319. fullRequestURL, err := a.GetRequestURL(info)
  320. if err != nil {
  321. return nil, fmt.Errorf("get request url failed: %w", err)
  322. }
  323. targetHeader := http.Header{}
  324. err = a.SetupRequestHeader(c, &targetHeader, info)
  325. if err != nil {
  326. return nil, fmt.Errorf("setup request header failed: %w", err)
  327. }
  328. // 在 SetupRequestHeader 之后应用 Header Override,确保用户设置优先级最高
  329. // 这样可以覆盖默认的 Authorization header 设置
  330. headerOverride, err := processHeaderOverride(info, c)
  331. if err != nil {
  332. return nil, err
  333. }
  334. for key, value := range headerOverride {
  335. targetHeader.Set(key, value)
  336. }
  337. targetHeader.Set("Content-Type", c.Request.Header.Get("Content-Type"))
  338. targetConn, _, err := websocket.DefaultDialer.Dial(fullRequestURL, targetHeader)
  339. if err != nil {
  340. return nil, fmt.Errorf("dial failed to %s: %w", fullRequestURL, err)
  341. }
  342. // send request body
  343. //all, err := io.ReadAll(requestBody)
  344. //err = service.WssString(c, targetConn, string(all))
  345. return targetConn, nil
  346. }
  347. func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.CancelFunc {
  348. pingerCtx, stopPinger := context.WithCancel(context.Background())
  349. gopool.Go(func() {
  350. defer func() {
  351. // 增加panic恢复处理
  352. if r := recover(); r != nil {
  353. if common2.DebugEnabled {
  354. println("SSE ping goroutine panic recovered:", fmt.Sprintf("%v", r))
  355. }
  356. }
  357. if common2.DebugEnabled {
  358. println("SSE ping goroutine stopped.")
  359. }
  360. }()
  361. if pingInterval <= 0 {
  362. pingInterval = helper.DefaultPingInterval
  363. }
  364. ticker := time.NewTicker(pingInterval)
  365. // 确保在任何情况下都清理ticker
  366. defer func() {
  367. ticker.Stop()
  368. if common2.DebugEnabled {
  369. println("SSE ping ticker stopped")
  370. }
  371. }()
  372. var pingMutex sync.Mutex
  373. if common2.DebugEnabled {
  374. println("SSE ping goroutine started")
  375. }
  376. // 增加超时控制,防止goroutine长时间运行
  377. maxPingDuration := 120 * time.Minute // 最大ping持续时间
  378. pingTimeout := time.NewTimer(maxPingDuration)
  379. defer pingTimeout.Stop()
  380. for {
  381. select {
  382. // 发送 ping 数据
  383. case <-ticker.C:
  384. if err := sendPingData(c, &pingMutex); err != nil {
  385. if common2.DebugEnabled {
  386. println("SSE ping error, stopping goroutine:", err.Error())
  387. }
  388. return
  389. }
  390. // 收到退出信号
  391. case <-pingerCtx.Done():
  392. return
  393. // request 结束
  394. case <-c.Request.Context().Done():
  395. return
  396. // 超时保护,防止goroutine无限运行
  397. case <-pingTimeout.C:
  398. if common2.DebugEnabled {
  399. println("SSE ping goroutine timeout, stopping")
  400. }
  401. return
  402. }
  403. }
  404. })
  405. return stopPinger
  406. }
  407. func sendPingData(c *gin.Context, mutex *sync.Mutex) error {
  408. // 增加超时控制,防止锁死等待
  409. done := make(chan error, 1)
  410. go func() {
  411. mutex.Lock()
  412. defer mutex.Unlock()
  413. err := helper.PingData(c)
  414. if err != nil {
  415. logger.LogError(c, "SSE ping error: "+err.Error())
  416. done <- err
  417. return
  418. }
  419. if common2.DebugEnabled {
  420. println("SSE ping data sent.")
  421. }
  422. done <- nil
  423. }()
  424. // 设置发送ping数据的超时时间
  425. select {
  426. case err := <-done:
  427. return err
  428. case <-time.After(10 * time.Second):
  429. return errors.New("SSE ping data send timeout")
  430. case <-c.Request.Context().Done():
  431. return errors.New("request context cancelled during ping")
  432. }
  433. }
  434. func DoRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
  435. return doRequest(c, req, info)
  436. }
  437. func doRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
  438. var client *http.Client
  439. var err error
  440. if info.ChannelSetting.Proxy != "" {
  441. client, err = service.NewProxyHttpClient(info.ChannelSetting.Proxy)
  442. if err != nil {
  443. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  444. }
  445. } else {
  446. client = service.GetHttpClient()
  447. }
  448. var stopPinger context.CancelFunc
  449. if info.IsStream {
  450. helper.SetEventStreamHeaders(c)
  451. // 处理流式请求的 ping 保活
  452. generalSettings := operation_setting.GetGeneralSetting()
  453. if generalSettings.PingIntervalEnabled && !info.DisablePing {
  454. pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second
  455. stopPinger = startPingKeepAlive(c, pingInterval)
  456. // 使用defer确保在任何情况下都能停止ping goroutine
  457. defer func() {
  458. if stopPinger != nil {
  459. stopPinger()
  460. if common2.DebugEnabled {
  461. println("SSE ping goroutine stopped by defer")
  462. }
  463. }
  464. }()
  465. }
  466. }
  467. resp, err := client.Do(req)
  468. if err != nil {
  469. logger.LogError(c, "do request failed: "+err.Error())
  470. return nil, types.NewError(err, types.ErrorCodeDoRequestFailed, types.ErrOptionWithHideErrMsg("upstream error: do request failed"))
  471. }
  472. if resp == nil {
  473. return nil, errors.New("resp is nil")
  474. }
  475. _ = req.Body.Close()
  476. _ = c.Request.Body.Close()
  477. return resp, nil
  478. }
  479. func DoTaskApiRequest(a TaskAdaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  480. fullRequestURL, err := a.BuildRequestURL(info)
  481. if err != nil {
  482. return nil, err
  483. }
  484. req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
  485. if err != nil {
  486. return nil, fmt.Errorf("new request failed: %w", err)
  487. }
  488. req.GetBody = func() (io.ReadCloser, error) {
  489. return io.NopCloser(requestBody), nil
  490. }
  491. err = a.BuildRequestHeader(c, req, info)
  492. if err != nil {
  493. return nil, fmt.Errorf("setup request header failed: %w", err)
  494. }
  495. resp, err := doRequest(c, req, info)
  496. if err != nil {
  497. return nil, fmt.Errorf("do request failed: %w", err)
  498. }
  499. return resp, nil
  500. }