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.

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