You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

522 lines
15KB

  1. /*
  2. * HTTP protocol for ffmpeg client
  3. * Copyright (c) 2000, 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avstring.h"
  22. #include "avformat.h"
  23. #include <unistd.h>
  24. #include "internal.h"
  25. #include "network.h"
  26. #include "http.h"
  27. #include "os_support.h"
  28. #include "httpauth.h"
  29. #include "url.h"
  30. #include "libavutil/opt.h"
  31. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  32. only a subset of it. */
  33. /* used for protocol handling */
  34. #define BUFFER_SIZE 1024
  35. #define MAX_REDIRECTS 8
  36. typedef struct {
  37. const AVClass *class;
  38. URLContext *hd;
  39. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  40. int line_count;
  41. int http_code;
  42. int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
  43. int64_t off, filesize;
  44. char location[MAX_URL_SIZE];
  45. HTTPAuthState auth_state;
  46. unsigned char headers[BUFFER_SIZE];
  47. int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
  48. } HTTPContext;
  49. #define OFFSET(x) offsetof(HTTPContext, x)
  50. static const AVOption options[] = {
  51. {"chunksize", "use chunked transfer-encoding for posts, -1 disables it, 0 enables it", OFFSET(chunksize), AV_OPT_TYPE_INT64, {.dbl = 0}, -1, 0 }, /* Default to 0, for chunked POSTs */
  52. {NULL}
  53. };
  54. static const AVClass httpcontext_class = {
  55. .class_name = "HTTP",
  56. .item_name = av_default_item_name,
  57. .option = options,
  58. .version = LIBAVUTIL_VERSION_INT,
  59. };
  60. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  61. const char *auth, int *new_location);
  62. void ff_http_set_headers(URLContext *h, const char *headers)
  63. {
  64. HTTPContext *s = h->priv_data;
  65. int len = strlen(headers);
  66. if (len && strcmp("\r\n", headers + len - 2))
  67. av_log(h, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
  68. av_strlcpy(s->headers, headers, sizeof(s->headers));
  69. }
  70. void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
  71. {
  72. ((HTTPContext*)h->priv_data)->chunksize = is_chunked ? 0 : -1;
  73. }
  74. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  75. {
  76. memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
  77. &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
  78. }
  79. /* return non zero if error */
  80. static int http_open_cnx(URLContext *h)
  81. {
  82. const char *path, *proxy_path;
  83. char hostname[1024], hoststr[1024];
  84. char auth[1024];
  85. char path1[1024];
  86. char buf[1024];
  87. int port, use_proxy, err, location_changed = 0, redirects = 0;
  88. HTTPAuthType cur_auth_type;
  89. HTTPContext *s = h->priv_data;
  90. URLContext *hd = NULL;
  91. proxy_path = getenv("http_proxy");
  92. use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
  93. av_strstart(proxy_path, "http://", NULL);
  94. /* fill the dest addr */
  95. redo:
  96. /* needed in any case to build the host string */
  97. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  98. path1, sizeof(path1), s->location);
  99. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  100. if (use_proxy) {
  101. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  102. NULL, 0, proxy_path);
  103. path = s->location;
  104. } else {
  105. if (path1[0] == '\0')
  106. path = "/";
  107. else
  108. path = path1;
  109. }
  110. if (port < 0)
  111. port = 80;
  112. ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
  113. err = ffurl_open(&hd, buf, AVIO_FLAG_READ_WRITE);
  114. if (err < 0)
  115. goto fail;
  116. s->hd = hd;
  117. cur_auth_type = s->auth_state.auth_type;
  118. if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
  119. goto fail;
  120. if (s->http_code == 401) {
  121. if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
  122. ffurl_close(hd);
  123. goto redo;
  124. } else
  125. goto fail;
  126. }
  127. if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  128. && location_changed == 1) {
  129. /* url moved, get next */
  130. ffurl_close(hd);
  131. if (redirects++ >= MAX_REDIRECTS)
  132. return AVERROR(EIO);
  133. location_changed = 0;
  134. goto redo;
  135. }
  136. return 0;
  137. fail:
  138. if (hd)
  139. ffurl_close(hd);
  140. s->hd = NULL;
  141. return AVERROR(EIO);
  142. }
  143. static int http_open(URLContext *h, const char *uri, int flags)
  144. {
  145. HTTPContext *s = h->priv_data;
  146. h->is_streamed = 1;
  147. s->filesize = -1;
  148. av_strlcpy(s->location, uri, sizeof(s->location));
  149. return http_open_cnx(h);
  150. }
  151. static int http_getc(HTTPContext *s)
  152. {
  153. int len;
  154. if (s->buf_ptr >= s->buf_end) {
  155. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  156. if (len < 0) {
  157. return AVERROR(EIO);
  158. } else if (len == 0) {
  159. return -1;
  160. } else {
  161. s->buf_ptr = s->buffer;
  162. s->buf_end = s->buffer + len;
  163. }
  164. }
  165. return *s->buf_ptr++;
  166. }
  167. static int http_get_line(HTTPContext *s, char *line, int line_size)
  168. {
  169. int ch;
  170. char *q;
  171. q = line;
  172. for(;;) {
  173. ch = http_getc(s);
  174. if (ch < 0)
  175. return AVERROR(EIO);
  176. if (ch == '\n') {
  177. /* process line */
  178. if (q > line && q[-1] == '\r')
  179. q--;
  180. *q = '\0';
  181. return 0;
  182. } else {
  183. if ((q - line) < line_size - 1)
  184. *q++ = ch;
  185. }
  186. }
  187. }
  188. static int process_line(URLContext *h, char *line, int line_count,
  189. int *new_location)
  190. {
  191. HTTPContext *s = h->priv_data;
  192. char *tag, *p, *end;
  193. /* end of header */
  194. if (line[0] == '\0')
  195. return 0;
  196. p = line;
  197. if (line_count == 0) {
  198. while (!isspace(*p) && *p != '\0')
  199. p++;
  200. while (isspace(*p))
  201. p++;
  202. s->http_code = strtol(p, &end, 10);
  203. av_dlog(NULL, "http_code=%d\n", s->http_code);
  204. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  205. * don't abort until all headers have been parsed. */
  206. if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) {
  207. end += strspn(end, SPACE_CHARS);
  208. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
  209. s->http_code, end);
  210. return -1;
  211. }
  212. } else {
  213. while (*p != '\0' && *p != ':')
  214. p++;
  215. if (*p != ':')
  216. return 1;
  217. *p = '\0';
  218. tag = line;
  219. p++;
  220. while (isspace(*p))
  221. p++;
  222. if (!av_strcasecmp(tag, "Location")) {
  223. strcpy(s->location, p);
  224. *new_location = 1;
  225. } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  226. s->filesize = atoll(p);
  227. } else if (!av_strcasecmp (tag, "Content-Range")) {
  228. /* "bytes $from-$to/$document_size" */
  229. const char *slash;
  230. if (!strncmp (p, "bytes ", 6)) {
  231. p += 6;
  232. s->off = atoll(p);
  233. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  234. s->filesize = atoll(slash+1);
  235. }
  236. h->is_streamed = 0; /* we _can_ in fact seek */
  237. } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
  238. h->is_streamed = 0;
  239. } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
  240. s->filesize = -1;
  241. s->chunksize = 0;
  242. } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
  243. ff_http_auth_handle_header(&s->auth_state, tag, p);
  244. } else if (!av_strcasecmp (tag, "Authentication-Info")) {
  245. ff_http_auth_handle_header(&s->auth_state, tag, p);
  246. } else if (!av_strcasecmp (tag, "Connection")) {
  247. if (!strcmp(p, "close"))
  248. s->willclose = 1;
  249. }
  250. }
  251. return 1;
  252. }
  253. static inline int has_header(const char *str, const char *header)
  254. {
  255. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  256. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  257. }
  258. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  259. const char *auth, int *new_location)
  260. {
  261. HTTPContext *s = h->priv_data;
  262. int post, err;
  263. char line[1024];
  264. char headers[1024] = "";
  265. char *authstr = NULL;
  266. int64_t off = s->off;
  267. int len = 0;
  268. /* send http header */
  269. post = h->flags & AVIO_FLAG_WRITE;
  270. authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
  271. post ? "POST" : "GET");
  272. /* set default headers if needed */
  273. if (!has_header(s->headers, "\r\nUser-Agent: "))
  274. len += av_strlcatf(headers + len, sizeof(headers) - len,
  275. "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  276. if (!has_header(s->headers, "\r\nAccept: "))
  277. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  278. sizeof(headers) - len);
  279. if (!has_header(s->headers, "\r\nRange: "))
  280. len += av_strlcatf(headers + len, sizeof(headers) - len,
  281. "Range: bytes=%"PRId64"-\r\n", s->off);
  282. if (!has_header(s->headers, "\r\nConnection: "))
  283. len += av_strlcpy(headers + len, "Connection: close\r\n",
  284. sizeof(headers)-len);
  285. if (!has_header(s->headers, "\r\nHost: "))
  286. len += av_strlcatf(headers + len, sizeof(headers) - len,
  287. "Host: %s\r\n", hoststr);
  288. /* now add in custom headers */
  289. av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
  290. snprintf(s->buffer, sizeof(s->buffer),
  291. "%s %s HTTP/1.1\r\n"
  292. "%s"
  293. "%s"
  294. "%s"
  295. "\r\n",
  296. post ? "POST" : "GET",
  297. path,
  298. post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
  299. headers,
  300. authstr ? authstr : "");
  301. av_freep(&authstr);
  302. if (ffurl_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
  303. return AVERROR(EIO);
  304. /* init input buffer */
  305. s->buf_ptr = s->buffer;
  306. s->buf_end = s->buffer;
  307. s->line_count = 0;
  308. s->off = 0;
  309. s->filesize = -1;
  310. s->willclose = 0;
  311. if (post) {
  312. /* Pretend that it did work. We didn't read any header yet, since
  313. * we've still to send the POST data, but the code calling this
  314. * function will check http_code after we return. */
  315. s->http_code = 200;
  316. return 0;
  317. }
  318. s->chunksize = -1;
  319. /* wait for header */
  320. for(;;) {
  321. if (http_get_line(s, line, sizeof(line)) < 0)
  322. return AVERROR(EIO);
  323. av_dlog(NULL, "header='%s'\n", line);
  324. err = process_line(h, line, s->line_count, new_location);
  325. if (err < 0)
  326. return err;
  327. if (err == 0)
  328. break;
  329. s->line_count++;
  330. }
  331. return (off == s->off) ? 0 : -1;
  332. }
  333. static int http_read(URLContext *h, uint8_t *buf, int size)
  334. {
  335. HTTPContext *s = h->priv_data;
  336. int len;
  337. if (s->chunksize >= 0) {
  338. if (!s->chunksize) {
  339. char line[32];
  340. for(;;) {
  341. do {
  342. if (http_get_line(s, line, sizeof(line)) < 0)
  343. return AVERROR(EIO);
  344. } while (!*line); /* skip CR LF from last chunk */
  345. s->chunksize = strtoll(line, NULL, 16);
  346. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  347. if (!s->chunksize)
  348. return 0;
  349. break;
  350. }
  351. }
  352. size = FFMIN(size, s->chunksize);
  353. }
  354. /* read bytes from input buffer first */
  355. len = s->buf_end - s->buf_ptr;
  356. if (len > 0) {
  357. if (len > size)
  358. len = size;
  359. memcpy(buf, s->buf_ptr, len);
  360. s->buf_ptr += len;
  361. } else {
  362. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  363. return AVERROR_EOF;
  364. len = ffurl_read(s->hd, buf, size);
  365. }
  366. if (len > 0) {
  367. s->off += len;
  368. if (s->chunksize > 0)
  369. s->chunksize -= len;
  370. }
  371. return len;
  372. }
  373. /* used only when posting data */
  374. static int http_write(URLContext *h, const uint8_t *buf, int size)
  375. {
  376. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  377. int ret;
  378. char crlf[] = "\r\n";
  379. HTTPContext *s = h->priv_data;
  380. if (s->chunksize == -1) {
  381. /* non-chunked data is sent without any special encoding */
  382. return ffurl_write(s->hd, buf, size);
  383. }
  384. /* silently ignore zero-size data since chunk encoding that would
  385. * signal EOF */
  386. if (size > 0) {
  387. /* upload data using chunked encoding */
  388. snprintf(temp, sizeof(temp), "%x\r\n", size);
  389. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  390. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  391. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  392. return ret;
  393. }
  394. return size;
  395. }
  396. static int http_close(URLContext *h)
  397. {
  398. int ret = 0;
  399. char footer[] = "0\r\n\r\n";
  400. HTTPContext *s = h->priv_data;
  401. /* signal end of chunked encoding if used */
  402. if ((h->flags & AVIO_FLAG_WRITE) && s->chunksize != -1) {
  403. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  404. ret = ret > 0 ? 0 : ret;
  405. }
  406. if (s->hd)
  407. ffurl_close(s->hd);
  408. return ret;
  409. }
  410. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  411. {
  412. HTTPContext *s = h->priv_data;
  413. URLContext *old_hd = s->hd;
  414. int64_t old_off = s->off;
  415. uint8_t old_buf[BUFFER_SIZE];
  416. int old_buf_size;
  417. if (whence == AVSEEK_SIZE)
  418. return s->filesize;
  419. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  420. return -1;
  421. /* we save the old context in case the seek fails */
  422. old_buf_size = s->buf_end - s->buf_ptr;
  423. memcpy(old_buf, s->buf_ptr, old_buf_size);
  424. s->hd = NULL;
  425. if (whence == SEEK_CUR)
  426. off += s->off;
  427. else if (whence == SEEK_END)
  428. off += s->filesize;
  429. s->off = off;
  430. /* if it fails, continue on old connection */
  431. if (http_open_cnx(h) < 0) {
  432. memcpy(s->buffer, old_buf, old_buf_size);
  433. s->buf_ptr = s->buffer;
  434. s->buf_end = s->buffer + old_buf_size;
  435. s->hd = old_hd;
  436. s->off = old_off;
  437. return -1;
  438. }
  439. ffurl_close(old_hd);
  440. return off;
  441. }
  442. static int
  443. http_get_file_handle(URLContext *h)
  444. {
  445. HTTPContext *s = h->priv_data;
  446. return ffurl_get_file_handle(s->hd);
  447. }
  448. URLProtocol ff_http_protocol = {
  449. .name = "http",
  450. .url_open = http_open,
  451. .url_read = http_read,
  452. .url_write = http_write,
  453. .url_seek = http_seek,
  454. .url_close = http_close,
  455. .url_get_file_handle = http_get_file_handle,
  456. .priv_data_size = sizeof(HTTPContext),
  457. .priv_data_class = &httpcontext_class,
  458. };