]>
Commit | Line | Data |
---|---|---|
1 | import { createWriteStream, remove } from 'fs-extra' | |
2 | import got, { CancelableRequest, NormalizedOptions, Options as GotOptions, RequestError, Response } from 'got' | |
3 | import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent' | |
4 | import { ACTIVITY_PUB, BINARY_CONTENT_TYPES, PEERTUBE_VERSION, REQUEST_TIMEOUTS, WEBSERVER } from '../initializers/constants' | |
5 | import { pipelinePromise } from './core-utils' | |
6 | import { logger, loggerTagsFactory } from './logger' | |
7 | import { getProxy, isProxyEnabled } from './proxy' | |
8 | ||
9 | const lTags = loggerTagsFactory('request') | |
10 | ||
11 | const httpSignature = require('@peertube/http-signature') | |
12 | ||
13 | export interface PeerTubeRequestError extends Error { | |
14 | statusCode?: number | |
15 | responseBody?: any | |
16 | responseHeaders?: any | |
17 | } | |
18 | ||
19 | type PeerTubeRequestOptions = { | |
20 | timeout?: number | |
21 | activityPub?: boolean | |
22 | bodyKBLimit?: number // 1MB | |
23 | httpSignature?: { | |
24 | algorithm: string | |
25 | authorizationHeaderName: string | |
26 | keyId: string | |
27 | key: string | |
28 | headers: string[] | |
29 | } | |
30 | jsonResponse?: boolean | |
31 | } & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'> | |
32 | ||
33 | const peertubeGot = got.extend({ | |
34 | ...getAgent(), | |
35 | ||
36 | headers: { | |
37 | 'user-agent': getUserAgent() | |
38 | }, | |
39 | ||
40 | handlers: [ | |
41 | (options, next) => { | |
42 | const promiseOrStream = next(options) as CancelableRequest<any> | |
43 | const bodyKBLimit = options.context?.bodyKBLimit as number | |
44 | if (!bodyKBLimit) throw new Error('No KB limit for this request') | |
45 | ||
46 | const bodyLimit = bodyKBLimit * 1000 | |
47 | ||
48 | /* eslint-disable @typescript-eslint/no-floating-promises */ | |
49 | promiseOrStream.on('downloadProgress', progress => { | |
50 | if (progress.transferred > bodyLimit && progress.percent !== 1) { | |
51 | const message = `Exceeded the download limit of ${bodyLimit} B` | |
52 | logger.warn(message, lTags()) | |
53 | ||
54 | // CancelableRequest | |
55 | if (promiseOrStream.cancel) { | |
56 | promiseOrStream.cancel() | |
57 | return | |
58 | } | |
59 | ||
60 | // Stream | |
61 | (promiseOrStream as any).destroy() | |
62 | } | |
63 | }) | |
64 | ||
65 | return promiseOrStream | |
66 | } | |
67 | ], | |
68 | ||
69 | hooks: { | |
70 | beforeRequest: [ | |
71 | options => { | |
72 | const headers = options.headers || {} | |
73 | headers['host'] = options.url.host | |
74 | }, | |
75 | ||
76 | options => { | |
77 | const httpSignatureOptions = options.context?.httpSignature | |
78 | ||
79 | if (httpSignatureOptions) { | |
80 | const method = options.method ?? 'GET' | |
81 | const path = options.path ?? options.url.pathname | |
82 | ||
83 | if (!method || !path) { | |
84 | throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`) | |
85 | } | |
86 | ||
87 | httpSignature.signRequest({ | |
88 | getHeader: function (header: string) { | |
89 | const value = options.headers[header.toLowerCase()] | |
90 | ||
91 | if (!value) logger.warn('Unknown header requested by http-signature.', { headers: options.headers, header }) | |
92 | return value | |
93 | }, | |
94 | ||
95 | setHeader: function (header: string, value: string) { | |
96 | options.headers[header] = value | |
97 | }, | |
98 | ||
99 | method, | |
100 | path | |
101 | }, httpSignatureOptions) | |
102 | } | |
103 | } | |
104 | ], | |
105 | ||
106 | beforeRetry: [ | |
107 | (_options: NormalizedOptions, error: RequestError, retryCount: number) => { | |
108 | logger.debug('Retrying request to %s.', error.request.requestUrl, { retryCount, error: buildRequestError(error), ...lTags() }) | |
109 | } | |
110 | ] | |
111 | } | |
112 | }) | |
113 | ||
114 | function doRequest (url: string, options: PeerTubeRequestOptions = {}) { | |
115 | const gotOptions = buildGotOptions(options) | |
116 | ||
117 | return peertubeGot(url, gotOptions) | |
118 | .catch(err => { throw buildRequestError(err) }) | |
119 | } | |
120 | ||
121 | function doJSONRequest <T> (url: string, options: PeerTubeRequestOptions = {}) { | |
122 | const gotOptions = buildGotOptions(options) | |
123 | ||
124 | return peertubeGot<T>(url, { ...gotOptions, responseType: 'json' }) | |
125 | .catch(err => { throw buildRequestError(err) }) | |
126 | } | |
127 | ||
128 | async function doRequestAndSaveToFile ( | |
129 | url: string, | |
130 | destPath: string, | |
131 | options: PeerTubeRequestOptions = {} | |
132 | ) { | |
133 | const gotOptions = buildGotOptions({ ...options, timeout: options.timeout ?? REQUEST_TIMEOUTS.FILE }) | |
134 | ||
135 | const outFile = createWriteStream(destPath) | |
136 | ||
137 | try { | |
138 | await pipelinePromise( | |
139 | peertubeGot.stream(url, gotOptions), | |
140 | outFile | |
141 | ) | |
142 | } catch (err) { | |
143 | remove(destPath) | |
144 | .catch(err => logger.error('Cannot remove %s after request failure.', destPath, { err, ...lTags() })) | |
145 | ||
146 | throw buildRequestError(err) | |
147 | } | |
148 | } | |
149 | ||
150 | function getAgent () { | |
151 | if (!isProxyEnabled()) return {} | |
152 | ||
153 | const proxy = getProxy() | |
154 | ||
155 | logger.info('Using proxy %s.', proxy, lTags()) | |
156 | ||
157 | const proxyAgentOptions = { | |
158 | keepAlive: true, | |
159 | keepAliveMsecs: 1000, | |
160 | maxSockets: 256, | |
161 | maxFreeSockets: 256, | |
162 | scheduling: 'lifo' as 'lifo', | |
163 | proxy | |
164 | } | |
165 | ||
166 | return { | |
167 | agent: { | |
168 | http: new HttpProxyAgent(proxyAgentOptions), | |
169 | https: new HttpsProxyAgent(proxyAgentOptions) | |
170 | } | |
171 | } | |
172 | } | |
173 | ||
174 | function getUserAgent () { | |
175 | return `PeerTube/${PEERTUBE_VERSION} (+${WEBSERVER.URL})` | |
176 | } | |
177 | ||
178 | function isBinaryResponse (result: Response<any>) { | |
179 | return BINARY_CONTENT_TYPES.has(result.headers['content-type']) | |
180 | } | |
181 | ||
182 | async function findLatestRedirection (url: string, options: PeerTubeRequestOptions, iteration = 1) { | |
183 | if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url) | |
184 | ||
185 | const { headers } = await peertubeGot(url, { followRedirect: false, ...buildGotOptions(options) }) | |
186 | ||
187 | if (headers.location) return findLatestRedirection(headers.location, options, iteration + 1) | |
188 | ||
189 | return url | |
190 | } | |
191 | ||
192 | // --------------------------------------------------------------------------- | |
193 | ||
194 | export { | |
195 | PeerTubeRequestOptions, | |
196 | ||
197 | doRequest, | |
198 | doJSONRequest, | |
199 | doRequestAndSaveToFile, | |
200 | isBinaryResponse, | |
201 | getAgent, | |
202 | findLatestRedirection, | |
203 | peertubeGot | |
204 | } | |
205 | ||
206 | // --------------------------------------------------------------------------- | |
207 | ||
208 | function buildGotOptions (options: PeerTubeRequestOptions) { | |
209 | const { activityPub, bodyKBLimit = 1000 } = options | |
210 | ||
211 | const context = { bodyKBLimit, httpSignature: options.httpSignature } | |
212 | ||
213 | let headers = options.headers || {} | |
214 | ||
215 | if (!headers.date) { | |
216 | headers = { ...headers, date: new Date().toUTCString() } | |
217 | } | |
218 | ||
219 | if (activityPub && !headers.accept) { | |
220 | headers = { ...headers, accept: ACTIVITY_PUB.ACCEPT_HEADER } | |
221 | } | |
222 | ||
223 | return { | |
224 | method: options.method, | |
225 | dnsCache: true, | |
226 | timeout: options.timeout ?? REQUEST_TIMEOUTS.DEFAULT, | |
227 | json: options.json, | |
228 | searchParams: options.searchParams, | |
229 | retry: 2, | |
230 | headers, | |
231 | context | |
232 | } | |
233 | } | |
234 | ||
235 | function buildRequestError (error: RequestError) { | |
236 | const newError: PeerTubeRequestError = new Error(error.message) | |
237 | newError.name = error.name | |
238 | newError.stack = error.stack | |
239 | ||
240 | if (error.response) { | |
241 | newError.responseBody = error.response.body | |
242 | newError.responseHeaders = error.response.headers | |
243 | newError.statusCode = error.response.statusCode | |
244 | } | |
245 | ||
246 | return newError | |
247 | } |