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.

506 lines
14KB

  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. unsigned char headers[BUFFER_SIZE];
  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, URL_SIZE);
  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;
  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, NULL, 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. return -1;
  204. } else {
  205. while (*p != '\0' && *p != ':')
  206. p++;
  207. if (*p != ':')
  208. return 1;
  209. *p = '\0';
  210. tag = line;
  211. p++;
  212. while (isspace(*p))
  213. p++;
  214. if (!strcmp(tag, "Location")) {
  215. strcpy(s->location, p);
  216. *new_location = 1;
  217. } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
  218. s->filesize = atoll(p);
  219. } else if (!strcmp (tag, "Content-Range")) {
  220. /* "bytes $from-$to/$document_size" */
  221. const char *slash;
  222. if (!strncmp (p, "bytes ", 6)) {
  223. p += 6;
  224. s->off = atoll(p);
  225. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  226. s->filesize = atoll(slash+1);
  227. }
  228. h->is_streamed = 0; /* we _can_ in fact seek */
  229. } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
  230. s->filesize = -1;
  231. s->chunksize = 0;
  232. } else if (!strcmp (tag, "WWW-Authenticate")) {
  233. ff_http_auth_handle_header(&s->auth_state, tag, p);
  234. } else if (!strcmp (tag, "Authentication-Info")) {
  235. ff_http_auth_handle_header(&s->auth_state, tag, p);
  236. }
  237. }
  238. return 1;
  239. }
  240. static inline int has_header(const char *str, const char *header)
  241. {
  242. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  243. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  244. }
  245. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  246. const char *auth, int *new_location)
  247. {
  248. HTTPContext *s = h->priv_data;
  249. int post, err;
  250. char line[1024];
  251. char headers[1024] = "";
  252. char *authstr = NULL;
  253. int64_t off = s->off;
  254. int len = 0;
  255. /* send http header */
  256. post = h->flags & URL_WRONLY;
  257. authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
  258. post ? "POST" : "GET");
  259. /* set default headers if needed */
  260. if (!has_header(s->headers, "\r\nUser-Agent: "))
  261. len += av_strlcatf(headers + len, sizeof(headers) - len,
  262. "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  263. if (!has_header(s->headers, "\r\nAccept: "))
  264. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  265. sizeof(headers) - len);
  266. if (!has_header(s->headers, "\r\nRange: "))
  267. len += av_strlcatf(headers + len, sizeof(headers) - len,
  268. "Range: bytes=%"PRId64"-\r\n", s->off);
  269. if (!has_header(s->headers, "\r\nConnection: "))
  270. len += av_strlcpy(headers + len, "Connection: close\r\n",
  271. sizeof(headers)-len);
  272. if (!has_header(s->headers, "\r\nHost: "))
  273. len += av_strlcatf(headers + len, sizeof(headers) - len,
  274. "Host: %s\r\n", hoststr);
  275. /* now add in custom headers */
  276. av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
  277. snprintf(s->buffer, sizeof(s->buffer),
  278. "%s %s HTTP/1.1\r\n"
  279. "%s"
  280. "%s"
  281. "%s"
  282. "\r\n",
  283. post ? "POST" : "GET",
  284. path,
  285. post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
  286. headers,
  287. authstr ? authstr : "");
  288. av_freep(&authstr);
  289. if (url_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
  290. return AVERROR(EIO);
  291. /* init input buffer */
  292. s->buf_ptr = s->buffer;
  293. s->buf_end = s->buffer;
  294. s->line_count = 0;
  295. s->off = 0;
  296. s->filesize = -1;
  297. if (post) {
  298. /* Pretend that it did work. We didn't read any header yet, since
  299. * we've still to send the POST data, but the code calling this
  300. * function will check http_code after we return. */
  301. s->http_code = 200;
  302. return 0;
  303. }
  304. s->chunksize = -1;
  305. /* wait for header */
  306. for(;;) {
  307. if (http_get_line(s, line, sizeof(line)) < 0)
  308. return AVERROR(EIO);
  309. dprintf(NULL, "header='%s'\n", line);
  310. err = process_line(h, line, s->line_count, new_location);
  311. if (err < 0)
  312. return err;
  313. if (err == 0)
  314. break;
  315. s->line_count++;
  316. }
  317. return (off == s->off) ? 0 : -1;
  318. }
  319. static int http_read(URLContext *h, uint8_t *buf, int size)
  320. {
  321. HTTPContext *s = h->priv_data;
  322. int len;
  323. if (s->chunksize >= 0) {
  324. if (!s->chunksize) {
  325. char line[32];
  326. for(;;) {
  327. do {
  328. if (http_get_line(s, line, sizeof(line)) < 0)
  329. return AVERROR(EIO);
  330. } while (!*line); /* skip CR LF from last chunk */
  331. s->chunksize = strtoll(line, NULL, 16);
  332. dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  333. if (!s->chunksize)
  334. return 0;
  335. break;
  336. }
  337. }
  338. size = FFMIN(size, s->chunksize);
  339. }
  340. /* read bytes from input buffer first */
  341. len = s->buf_end - s->buf_ptr;
  342. if (len > 0) {
  343. if (len > size)
  344. len = size;
  345. memcpy(buf, s->buf_ptr, len);
  346. s->buf_ptr += len;
  347. } else {
  348. len = url_read(s->hd, buf, size);
  349. }
  350. if (len > 0) {
  351. s->off += len;
  352. if (s->chunksize > 0)
  353. s->chunksize -= len;
  354. }
  355. return len;
  356. }
  357. /* used only when posting data */
  358. static int http_write(URLContext *h, const uint8_t *buf, int size)
  359. {
  360. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  361. int ret;
  362. char crlf[] = "\r\n";
  363. HTTPContext *s = h->priv_data;
  364. if (s->chunksize == -1) {
  365. /* non-chunked data is sent without any special encoding */
  366. return url_write(s->hd, buf, size);
  367. }
  368. /* silently ignore zero-size data since chunk encoding that would
  369. * signal EOF */
  370. if (size > 0) {
  371. /* upload data using chunked encoding */
  372. snprintf(temp, sizeof(temp), "%x\r\n", size);
  373. if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
  374. (ret = url_write(s->hd, buf, size)) < 0 ||
  375. (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  376. return ret;
  377. }
  378. return size;
  379. }
  380. static int http_close(URLContext *h)
  381. {
  382. int ret = 0;
  383. char footer[] = "0\r\n\r\n";
  384. HTTPContext *s = h->priv_data;
  385. /* signal end of chunked encoding if used */
  386. if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
  387. ret = url_write(s->hd, footer, sizeof(footer) - 1);
  388. ret = ret > 0 ? 0 : ret;
  389. }
  390. if (s->hd)
  391. url_close(s->hd);
  392. return ret;
  393. }
  394. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  395. {
  396. HTTPContext *s = h->priv_data;
  397. URLContext *old_hd = s->hd;
  398. int64_t old_off = s->off;
  399. uint8_t old_buf[BUFFER_SIZE];
  400. int old_buf_size;
  401. if (whence == AVSEEK_SIZE)
  402. return s->filesize;
  403. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  404. return -1;
  405. /* we save the old context in case the seek fails */
  406. old_buf_size = s->buf_end - s->buf_ptr;
  407. memcpy(old_buf, s->buf_ptr, old_buf_size);
  408. s->hd = NULL;
  409. if (whence == SEEK_CUR)
  410. off += s->off;
  411. else if (whence == SEEK_END)
  412. off += s->filesize;
  413. s->off = off;
  414. /* if it fails, continue on old connection */
  415. if (http_open_cnx(h) < 0) {
  416. memcpy(s->buffer, old_buf, old_buf_size);
  417. s->buf_ptr = s->buffer;
  418. s->buf_end = s->buffer + old_buf_size;
  419. s->hd = old_hd;
  420. s->off = old_off;
  421. return -1;
  422. }
  423. url_close(old_hd);
  424. return off;
  425. }
  426. static int
  427. http_get_file_handle(URLContext *h)
  428. {
  429. HTTPContext *s = h->priv_data;
  430. return url_get_file_handle(s->hd);
  431. }
  432. URLProtocol http_protocol = {
  433. "http",
  434. http_open,
  435. http_read,
  436. http_write,
  437. http_seek,
  438. http_close,
  439. .url_get_file_handle = http_get_file_handle,
  440. .priv_data_size = sizeof(HTTPContext),
  441. .priv_data_class = &httpcontext_class,
  442. };