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.

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