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.

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