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.

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