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.

661 lines
19KB

  1. /*
  2. * Copyright (c) 2013 Lukasz Marek <lukasz.m.luki@gmail.com>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <stdlib.h>
  21. #include "libavutil/avstring.h"
  22. #include "libavutil/avassert.h"
  23. #include "avformat.h"
  24. #include "internal.h"
  25. #include "network.h"
  26. #include "os_support.h"
  27. #include "url.h"
  28. #include "libavutil/opt.h"
  29. #define CONTROL_BUFFER_SIZE 1024
  30. typedef enum {
  31. UNKNOWN,
  32. READY,
  33. DOWNLOADING,
  34. UPLOADING,
  35. DISCONNECTED
  36. } FTPState;
  37. typedef struct {
  38. const AVClass *class;
  39. URLContext *conn_control; /**< Control connection */
  40. int conn_control_block_flag; /**< Controls block/unblock mode of data connection */
  41. AVIOInterruptCB conn_control_interrupt_cb; /**< Controls block/unblock mode of data connection */
  42. URLContext *conn_data; /**< Data connection, NULL when not connected */
  43. uint8_t control_buffer[CONTROL_BUFFER_SIZE]; /**< Control connection buffer */
  44. uint8_t *control_buf_ptr, *control_buf_end;
  45. int server_data_port; /**< Data connection port opened by server, -1 on error. */
  46. char hostname[512]; /**< Server address. */
  47. char path[MAX_URL_SIZE]; /**< Path to resource on server. */
  48. int64_t filesize; /**< Size of file on server, -1 on error. */
  49. int64_t position; /**< Current position, calculated. */
  50. int rw_timeout; /**< Network timeout. */
  51. const char *anonymous_password; /**< Password to be used for anonymous user. An email should be used. */
  52. int write_seekable; /**< Control seekability, 0 = disable, 1 = enable. */
  53. FTPState state; /**< State of data connection */
  54. } FTPContext;
  55. #define OFFSET(x) offsetof(FTPContext, x)
  56. #define D AV_OPT_FLAG_DECODING_PARAM
  57. #define E AV_OPT_FLAG_ENCODING_PARAM
  58. static const AVOption options[] = {
  59. {"timeout", "set timeout of socket I/O operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
  60. {"ftp-write-seekable", "control seekability of connection during encoding", OFFSET(write_seekable), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
  61. {"ftp-anonymous-password", "password for anonymous login. E-mail address should be used.", OFFSET(anonymous_password), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  62. {NULL}
  63. };
  64. static const AVClass ftp_context_class = {
  65. .class_name = "ftp",
  66. .item_name = av_default_item_name,
  67. .option = options,
  68. .version = LIBAVUTIL_VERSION_INT,
  69. };
  70. static int ftp_conn_control_block_control(void *data)
  71. {
  72. FTPContext *s = data;
  73. return s->conn_control_block_flag;
  74. }
  75. static int ftp_getc(FTPContext *s)
  76. {
  77. int len;
  78. if (s->control_buf_ptr >= s->control_buf_end) {
  79. if (s->conn_control_block_flag)
  80. return AVERROR_EXIT;
  81. len = ffurl_read(s->conn_control, s->control_buffer, CONTROL_BUFFER_SIZE);
  82. if (len < 0) {
  83. return len;
  84. } else if (!len) {
  85. return -1;
  86. } else {
  87. s->control_buf_ptr = s->control_buffer;
  88. s->control_buf_end = s->control_buffer + len;
  89. }
  90. }
  91. return *s->control_buf_ptr++;
  92. }
  93. static int ftp_get_line(FTPContext *s, char *line, int line_size)
  94. {
  95. int ch;
  96. char *q = line;
  97. int ori_block_flag = s->conn_control_block_flag;
  98. for (;;) {
  99. ch = ftp_getc(s);
  100. if (ch < 0) {
  101. s->conn_control_block_flag = ori_block_flag;
  102. return ch;
  103. }
  104. if (ch == '\n') {
  105. /* process line */
  106. if (q > line && q[-1] == '\r')
  107. q--;
  108. *q = '\0';
  109. s->conn_control_block_flag = ori_block_flag;
  110. return 0;
  111. } else {
  112. s->conn_control_block_flag = 0; /* line need to be finished */
  113. if ((q - line) < line_size - 1)
  114. *q++ = ch;
  115. }
  116. }
  117. }
  118. /*
  119. * This routine returns ftp server response code.
  120. * Server may send more than one response for a certain command, following priorities are used:
  121. * - 5xx code is returned if occurred. (means error)
  122. * - When pref_code is set then pref_code is return if occurred. (expected result)
  123. * - The lowest code is returned. (means success)
  124. */
  125. static int ftp_status(FTPContext *s, int *major, int *minor, int *extra, char **line, int pref_code)
  126. {
  127. int err, result = -1, pref_code_found = 0;
  128. char buf[CONTROL_BUFFER_SIZE];
  129. unsigned char d_major, d_minor, d_extra;
  130. /* Set blocking mode */
  131. s->conn_control_block_flag = 0;
  132. for (;;) {
  133. if ((err = ftp_get_line(s, buf, CONTROL_BUFFER_SIZE)) < 0) {
  134. if (err == AVERROR_EXIT)
  135. return result;
  136. return err;
  137. }
  138. if (strlen(buf) < 3)
  139. continue;
  140. d_major = buf[0];
  141. if (d_major < '1' || d_major > '6' || d_major == '4')
  142. continue;
  143. d_minor = buf[1];
  144. if (d_minor < '0' || d_minor > '9')
  145. continue;
  146. d_extra = buf[2];
  147. if (d_extra < '0' || d_extra > '9')
  148. continue;
  149. av_log(s, AV_LOG_DEBUG, "%s\n", buf);
  150. err = d_major * 100 + d_minor * 10 + d_extra - 111 * '0';
  151. if ((result < 0 || err < result || pref_code == err) && !pref_code_found || d_major == '5') {
  152. if (pref_code == err || d_major == '5')
  153. pref_code_found = 1;
  154. result = err;
  155. if (major)
  156. *major = d_major - '0';
  157. if (minor)
  158. *minor = d_minor - '0';
  159. if (extra)
  160. *extra = d_extra - '0';
  161. if (line)
  162. *line = av_strdup(buf);
  163. }
  164. /* first code received. Now get all lines in non blocking mode */
  165. if (pref_code < 0 || pref_code_found)
  166. s->conn_control_block_flag = 1;
  167. }
  168. return result;
  169. }
  170. static int ftp_auth(FTPContext *s, char *auth)
  171. {
  172. const char *user = NULL, *pass = NULL;
  173. char *end = NULL, buf[CONTROL_BUFFER_SIZE];
  174. int err;
  175. av_assert2(auth);
  176. user = av_strtok(auth, ":", &end);
  177. pass = av_strtok(end, ":", &end);
  178. if (user) {
  179. snprintf(buf, sizeof(buf), "USER %s\r\n", user);
  180. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  181. return err;
  182. ftp_status(s, &err, NULL, NULL, NULL, -1);
  183. if (err == 3) {
  184. if (pass) {
  185. snprintf(buf, sizeof(buf), "PASS %s\r\n", pass);
  186. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  187. return err;
  188. ftp_status(s, &err, NULL, NULL, NULL, -1);
  189. } else
  190. return AVERROR(EACCES);
  191. }
  192. if (err != 2) {
  193. return AVERROR(EACCES);
  194. }
  195. } else {
  196. const char* command = "USER anonymous\r\n";
  197. if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
  198. return err;
  199. ftp_status(s, &err, NULL, NULL, NULL, -1);
  200. if (err == 3) {
  201. if (s->anonymous_password) {
  202. snprintf(buf, sizeof(buf), "PASS %s\r\n", s->anonymous_password);
  203. } else
  204. snprintf(buf, sizeof(buf), "PASS nopassword\r\n");
  205. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  206. return err;
  207. ftp_status(s, &err, NULL, NULL, NULL, -1);
  208. }
  209. if (err != 2) {
  210. return AVERROR(EACCES);
  211. }
  212. }
  213. return 0;
  214. }
  215. static int ftp_passive_mode(FTPContext *s)
  216. {
  217. char *res = NULL, *start, *end;
  218. int err, i;
  219. const char *command = "PASV\r\n";
  220. if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
  221. return err;
  222. if (ftp_status(s, NULL, NULL, NULL, &res, 227) != 227)
  223. goto fail;
  224. start = NULL;
  225. for (i = 0; i < strlen(res); ++i) {
  226. if (res[i] == '(') {
  227. start = res + i + 1;
  228. } else if (res[i] == ')') {
  229. end = res + i;
  230. break;
  231. }
  232. }
  233. if (!start || !end)
  234. goto fail;
  235. *end = '\0';
  236. /* skip ip */
  237. if (!av_strtok(start, ",", &end)) goto fail;
  238. if (!av_strtok(end, ",", &end)) goto fail;
  239. if (!av_strtok(end, ",", &end)) goto fail;
  240. if (!av_strtok(end, ",", &end)) goto fail;
  241. /* parse port number */
  242. start = av_strtok(end, ",", &end);
  243. if (!start) goto fail;
  244. s->server_data_port = atoi(start) * 256;
  245. start = av_strtok(end, ",", &end);
  246. if (!start) goto fail;
  247. s->server_data_port += atoi(start);
  248. av_dlog(s, "Server data port: %d\n", s->server_data_port);
  249. av_free(res);
  250. return 0;
  251. fail:
  252. av_free(res);
  253. s->server_data_port = -1;
  254. return AVERROR(EIO);
  255. }
  256. static int ftp_current_dir(FTPContext *s)
  257. {
  258. char *res = NULL, *start = NULL, *end = NULL;
  259. int err, i;
  260. const char *command = "PWD\r\n";
  261. if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
  262. return err;
  263. if (ftp_status(s, NULL, NULL, NULL, &res, 257) != 257)
  264. goto fail;
  265. for (i = 0; res[i]; ++i) {
  266. if (res[i] == '"') {
  267. if (!start) {
  268. start = res + i + 1;
  269. continue;
  270. }
  271. end = res + i;
  272. break;
  273. }
  274. }
  275. if (!end)
  276. goto fail;
  277. if (end > res && end[-1] == '/') {
  278. end[-1] = '\0';
  279. } else
  280. *end = '\0';
  281. av_strlcpy(s->path, start, sizeof(s->path));
  282. av_free(res);
  283. return 0;
  284. fail:
  285. av_free(res);
  286. return AVERROR(EIO);
  287. }
  288. static int ftp_file_size(FTPContext *s)
  289. {
  290. char buf[CONTROL_BUFFER_SIZE];
  291. int err;
  292. char *res = NULL;
  293. snprintf(buf, sizeof(buf), "SIZE %s\r\n", s->path);
  294. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  295. return err;
  296. if (ftp_status(s, NULL, NULL, NULL, &res, 213) == 213) {
  297. s->filesize = strtoll(&res[4], NULL, 10);
  298. } else {
  299. s->filesize = -1;
  300. av_free(res);
  301. return AVERROR(EIO);
  302. }
  303. av_free(res);
  304. return 0;
  305. }
  306. static int ftp_retrieve(FTPContext *s)
  307. {
  308. char buf[CONTROL_BUFFER_SIZE];
  309. int err;
  310. snprintf(buf, sizeof(buf), "RETR %s\r\n", s->path);
  311. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  312. return err;
  313. if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
  314. return AVERROR(EIO);
  315. s->state = DOWNLOADING;
  316. return 0;
  317. }
  318. static int ftp_store(FTPContext *s)
  319. {
  320. char buf[CONTROL_BUFFER_SIZE];
  321. int err;
  322. snprintf(buf, sizeof(buf), "STOR %s\r\n", s->path);
  323. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  324. return err;
  325. if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
  326. return AVERROR(EIO);
  327. s->state = UPLOADING;
  328. return 0;
  329. }
  330. static int ftp_send_command(FTPContext *s, const char* command)
  331. {
  332. int err;
  333. if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
  334. return err;
  335. ftp_status(s, &err, NULL, NULL, NULL, -1);
  336. if (err != 2)
  337. return AVERROR(EIO);
  338. return 0;
  339. }
  340. static int ftp_reconnect_data_connection(URLContext *h)
  341. {
  342. int err;
  343. char buf[CONTROL_BUFFER_SIZE], opts_format[20];
  344. AVDictionary *opts = NULL;
  345. FTPContext *s = h->priv_data;
  346. if (!s->conn_data) {
  347. ff_url_join(buf, sizeof(buf), "tcp", NULL, s->hostname, s->server_data_port, NULL);
  348. if (s->rw_timeout != -1) {
  349. snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
  350. av_dict_set(&opts, "timeout", opts_format, 0);
  351. } /* if option is not given, don't pass it and let tcp use its own default */
  352. err = ffurl_open(&s->conn_data, buf, AVIO_FLAG_READ_WRITE,
  353. &h->interrupt_callback, &opts);
  354. av_dict_free(&opts);
  355. if (err < 0)
  356. return err;
  357. }
  358. s->state = READY;
  359. s->position = 0;
  360. return 0;
  361. }
  362. static int ftp_open(URLContext *h, const char *url, int flags)
  363. {
  364. char proto[10], auth[1024], path[MAX_URL_SIZE], buf[CONTROL_BUFFER_SIZE], opts_format[20];
  365. AVDictionary *opts = NULL;
  366. int port, err;
  367. FTPContext *s = h->priv_data;
  368. av_dlog(h, "ftp protocol open\n");
  369. s->state = DISCONNECTED;
  370. s->filesize = -1;
  371. s->conn_control_interrupt_cb.opaque = s;
  372. s->conn_control_interrupt_cb.callback = ftp_conn_control_block_control;
  373. av_url_split(proto, sizeof(proto),
  374. auth, sizeof(auth),
  375. s->hostname, sizeof(s->hostname),
  376. &port,
  377. path, sizeof(path),
  378. url);
  379. if (port < 0)
  380. port = 21;
  381. if (!s->conn_control) {
  382. ff_url_join(buf, sizeof(buf), "tcp", NULL, s->hostname, port, NULL);
  383. if (s->rw_timeout != -1) {
  384. snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
  385. av_dict_set(&opts, "timeout", opts_format, 0);
  386. } /* if option is not given, don't pass it and let tcp use its own default */
  387. err = ffurl_open(&s->conn_control, buf, AVIO_FLAG_READ_WRITE,
  388. &s->conn_control_interrupt_cb, &opts);
  389. av_dict_free(&opts);
  390. if (err < 0)
  391. goto fail;
  392. /* consume all messages from server */
  393. if (ftp_status(s, NULL, NULL, NULL, NULL, 220) != 220) {
  394. av_log(h, AV_LOG_ERROR, "Server not ready for new users\n");
  395. err = AVERROR(EACCES);
  396. goto fail;
  397. }
  398. if ((err = ftp_auth(s, auth)) < 0)
  399. goto fail;
  400. if ((err = ftp_send_command(s, "TYPE I\r\n")) < 0)
  401. goto fail;
  402. if ((err = ftp_current_dir(s)) < 0)
  403. goto fail;
  404. av_strlcat(s->path, path, sizeof(s->path));
  405. if ((err = ftp_passive_mode(s)) < 0)
  406. goto fail;
  407. if (ftp_file_size(s) < 0 && flags & AVIO_FLAG_READ)
  408. h->is_streamed = 1;
  409. if (s->write_seekable != 1 && flags & AVIO_FLAG_WRITE)
  410. h->is_streamed = 1;
  411. }
  412. if ((err = ftp_reconnect_data_connection(h)) < 0)
  413. goto fail;
  414. return 0;
  415. fail:
  416. av_log(h, AV_LOG_ERROR, "FTP open failed\n");
  417. ffurl_closep(&s->conn_control);
  418. ffurl_closep(&s->conn_data);
  419. return err;
  420. }
  421. static int ftp_read(URLContext *h, unsigned char *buf, int size)
  422. {
  423. FTPContext *s = h->priv_data;
  424. int read;
  425. av_dlog(h, "ftp protocol read %d bytes\n", size);
  426. if (s->state == READY) {
  427. ftp_retrieve(s);
  428. }
  429. if (s->conn_data && s->state == DOWNLOADING) {
  430. read = ffurl_read(s->conn_data, buf, size);
  431. if (read >= 0) {
  432. s->position += read;
  433. if (s->position >= s->filesize) {
  434. ffurl_closep(&s->conn_data);
  435. s->state = DISCONNECTED;
  436. if (ftp_status(s, NULL, NULL, NULL,NULL, 226) != 226)
  437. return AVERROR(EIO);
  438. }
  439. }
  440. return read;
  441. }
  442. av_log(h, AV_LOG_DEBUG, "FTP read failed\n");
  443. return AVERROR(EIO);
  444. }
  445. static int ftp_write(URLContext *h, const unsigned char *buf, int size)
  446. {
  447. FTPContext *s = h->priv_data;
  448. int written;
  449. av_dlog(h, "ftp protocol write %d bytes\n", size);
  450. if (s->state == READY) {
  451. ftp_store(s);
  452. }
  453. if (s->conn_data && s->state == UPLOADING) {
  454. written = ffurl_write(s->conn_data, buf, size);
  455. if (written > 0) {
  456. s->position += written;
  457. s->filesize = FFMAX(s->filesize, s->position);
  458. }
  459. return written;
  460. }
  461. av_log(h, AV_LOG_ERROR, "FTP write failed\n");
  462. return AVERROR(EIO);
  463. }
  464. static int64_t ftp_seek(URLContext *h, int64_t pos, int whence)
  465. {
  466. FTPContext *s = h->priv_data;
  467. char buf[CONTROL_BUFFER_SIZE];
  468. int err;
  469. int64_t new_pos;
  470. av_dlog(h, "ftp protocol seek %"PRId64" %d\n", pos, whence);
  471. switch(whence) {
  472. case AVSEEK_SIZE:
  473. return s->filesize;
  474. case SEEK_SET:
  475. new_pos = pos;
  476. break;
  477. case SEEK_CUR:
  478. new_pos = s->position + pos;
  479. break;
  480. case SEEK_END:
  481. if (s->filesize < 0)
  482. return AVERROR(EIO);
  483. new_pos = s->filesize + pos;
  484. break;
  485. default:
  486. return AVERROR(EINVAL);
  487. }
  488. if (h->is_streamed)
  489. return AVERROR(EIO);
  490. if (new_pos < 0 || (s->filesize >= 0 && new_pos > s->filesize))
  491. return AVERROR(EINVAL);
  492. if (new_pos != s->position) {
  493. /* close existing data connection */
  494. if (s->state != READY) {
  495. if (s->conn_data) {
  496. /* abort existing transfer */
  497. if (s->state == DOWNLOADING) {
  498. snprintf(buf, sizeof(buf), "ABOR\r\n");
  499. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  500. return err;
  501. }
  502. ffurl_closep(&s->conn_data);
  503. s->state = DISCONNECTED;
  504. /* Servers return 225 or 226 */
  505. ftp_status(s, &err, NULL, NULL, NULL, -1);
  506. if (err != 2)
  507. return AVERROR(EIO);
  508. }
  509. /* set passive */
  510. if ((err = ftp_passive_mode(s)) < 0)
  511. return err;
  512. /* open new data connection */
  513. if ((err = ftp_reconnect_data_connection(h)) < 0)
  514. return err;
  515. }
  516. /* resume from pos position */
  517. snprintf(buf, sizeof(buf), "REST %"PRId64"\r\n", pos);
  518. if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
  519. return err;
  520. if (ftp_status(s, NULL, NULL, NULL, NULL, 350) != 350)
  521. return AVERROR(EIO);
  522. s->position = pos;
  523. }
  524. return new_pos;
  525. }
  526. static int ftp_close(URLContext *h)
  527. {
  528. FTPContext *s = h->priv_data;
  529. av_dlog(h, "ftp protocol close\n");
  530. ffurl_closep(&s->conn_control);
  531. ffurl_closep(&s->conn_data);
  532. return 0;
  533. }
  534. static int ftp_get_file_handle(URLContext *h)
  535. {
  536. FTPContext *s = h->priv_data;
  537. av_dlog(h, "ftp protocol get_file_handle\n");
  538. if (s->conn_data)
  539. return ffurl_get_file_handle(s->conn_data);
  540. return AVERROR(EIO);
  541. }
  542. static int ftp_shutdown(URLContext *h, int flags)
  543. {
  544. FTPContext *s = h->priv_data;
  545. av_dlog(h, "ftp protocol shutdown\n");
  546. if (s->conn_data)
  547. return ffurl_shutdown(s->conn_data, flags);
  548. return AVERROR(EIO);
  549. }
  550. URLProtocol ff_ftp_protocol = {
  551. .name = "ftp",
  552. .url_open = ftp_open,
  553. .url_read = ftp_read,
  554. .url_write = ftp_write,
  555. .url_seek = ftp_seek,
  556. .url_close = ftp_close,
  557. .url_get_file_handle = ftp_get_file_handle,
  558. .url_shutdown = ftp_shutdown,
  559. .priv_data_size = sizeof(FTPContext),
  560. .priv_data_class = &ftp_context_class,
  561. .flags = URL_PROTOCOL_FLAG_NETWORK,
  562. };