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.

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