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.

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