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.

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