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.

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