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.

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