2 * Copyright (c) 2013 Lukasz Marek <lukasz.m.luki@gmail.com>
4 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavutil/avstring.h"
23 #include "libavutil/avassert.h"
27 #include "os_support.h"
29 #include "libavutil/opt.h"
31 #define CONTROL_BUFFER_SIZE 1024
44 URLContext *conn_control; /**< Control connection */
45 int conn_control_block_flag; /**< Controls block/unblock mode of data connection */
46 AVIOInterruptCB conn_control_interrupt_cb; /**< Controls block/unblock mode of data connection */
47 URLContext *conn_data; /**< Data connection, NULL when not connected */
48 uint8_t control_buffer[CONTROL_BUFFER_SIZE], *control_buf_ptr, *control_buf_end; /**< Control connection buffer */
49 int server_data_port; /**< Data connection port opened by server, -1 on error. */
50 char hostname[512]; /**< Server address. */
51 char path[MAX_URL_SIZE]; /**< Path to resource on server. */
52 int64_t filesize; /**< Size of file on server, -1 on error. */
53 int64_t position; /**< Current position, calculated. */
54 int rw_timeout; /**< Network timeout. */
55 const char *anonymous_password; /**< Password to be used for anonymous user. An email should be used. */
56 int write_seekable; /**< Control seekability, 0 = disable, 1 = enable. */
57 FTPState state; /**< State of data connection */
60 #define OFFSET(x) offsetof(FTPContext, x)
61 #define D AV_OPT_FLAG_DECODING_PARAM
62 #define E AV_OPT_FLAG_ENCODING_PARAM
63 static const AVOption options[] = {
64 {"timeout", "set timeout of socket I/O operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
65 {"ftp-write-seekable", "control seekability of connection during encoding", OFFSET(write_seekable), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
66 {"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 },
70 static const AVClass ftp_context_class = {
72 .item_name = av_default_item_name,
74 .version = LIBAVUTIL_VERSION_INT,
77 static int ftp_conn_control_block_control(void *data)
80 return s->conn_control_block_flag;
83 static int ftp_getc(FTPContext *s)
86 if (s->control_buf_ptr >= s->control_buf_end) {
87 if (s->conn_control_block_flag)
89 len = ffurl_read(s->conn_control, s->control_buffer, CONTROL_BUFFER_SIZE);
95 s->control_buf_ptr = s->control_buffer;
96 s->control_buf_end = s->control_buffer + len;
99 return *s->control_buf_ptr++;
102 static int ftp_get_line(FTPContext *s, char *line, int line_size)
106 int ori_block_flag = s->conn_control_block_flag;
111 s->conn_control_block_flag = ori_block_flag;
116 if (q > line && q[-1] == '\r')
120 s->conn_control_block_flag = ori_block_flag;
123 s->conn_control_block_flag = 0; /* line need to be finished */
124 if ((q - line) < line_size - 1)
131 * This routine returns ftp server response code.
132 * Server may send more than one response for a certain command, following priorites are used:
133 * - 5xx code is returned if occurred. (means error)
134 * - When pref_code is set then pref_code is return if occurred. (expected result)
135 * - The lowest code is returned. (means success)
137 static int ftp_status(FTPContext *s, int *major, int *minor, int *extra, char **line, int pref_code)
139 int err, result = -1, pref_code_found = 0;
140 char buf[CONTROL_BUFFER_SIZE];
141 unsigned char d_major, d_minor, d_extra;
143 /* Set blocking mode */
144 s->conn_control_block_flag = 0;
146 if ((err = ftp_get_line(s, buf, CONTROL_BUFFER_SIZE)) < 0) {
147 if (err == AVERROR_EXIT)
155 if (d_major < '1' || d_major > '6' || d_major == '4')
158 if (d_minor < '0' || d_minor > '9')
161 if (d_extra < '0' || d_extra > '9')
164 av_log(s, AV_LOG_DEBUG, "%s\n", buf);
166 err = d_major * 100 + d_minor * 10 + d_extra - 111 * '0';
168 if ((result < 0 || err < result || pref_code == err) && !pref_code_found || d_major == '5') {
169 if (pref_code == err || d_major == '5')
173 *major = d_major - '0';
175 *minor = d_minor - '0';
177 *extra = d_extra - '0';
179 *line = av_strdup(buf);
182 /* first code received. Now get all lines in non blocking mode */
183 if (pref_code < 0 || pref_code_found)
184 s->conn_control_block_flag = 1;
189 static int ftp_auth(FTPContext *s, char *auth)
191 const char *user = NULL, *pass = NULL;
192 char *end = NULL, buf[CONTROL_BUFFER_SIZE];
196 user = av_strtok(auth, ":", &end);
197 pass = av_strtok(end, ":", &end);
200 snprintf(buf, sizeof(buf), "USER %s\r\n", user);
201 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
203 ftp_status(s, &err, NULL, NULL, NULL, -1);
206 snprintf(buf, sizeof(buf), "PASS %s\r\n", pass);
207 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
209 ftp_status(s, &err, NULL, NULL, NULL, -1);
211 return AVERROR(EACCES);
214 return AVERROR(EACCES);
217 const char* command = "USER anonymous\r\n";
218 if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
220 ftp_status(s, &err, NULL, NULL, NULL, -1);
222 if (s->anonymous_password) {
223 snprintf(buf, sizeof(buf), "PASS %s\r\n", s->anonymous_password);
225 snprintf(buf, sizeof(buf), "PASS nopassword\r\n");
226 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
228 ftp_status(s, &err, NULL, NULL, NULL, -1);
231 return AVERROR(EACCES);
238 static int ftp_passive_mode(FTPContext *s)
240 char *res = NULL, *start, *end;
242 const char *command = "PASV\r\n";
244 if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
246 if (ftp_status(s, NULL, NULL, NULL, &res, 227) != 227)
250 for (i = 0; i < strlen(res); ++i) {
253 } else if (res[i] == ')') {
263 if (!av_strtok(start, ",", &end)) goto fail;
264 if (!av_strtok(end, ",", &end)) goto fail;
265 if (!av_strtok(end, ",", &end)) goto fail;
266 if (!av_strtok(end, ",", &end)) goto fail;
268 /* parse port number */
269 start = av_strtok(end, ",", &end);
270 if (!start) goto fail;
271 s->server_data_port = atoi(start) * 256;
272 start = av_strtok(end, ",", &end);
273 if (!start) goto fail;
274 s->server_data_port += atoi(start);
275 av_dlog(s, "Server data port: %d\n", s->server_data_port);
282 s->server_data_port = -1;
286 static int ftp_current_dir(FTPContext *s)
288 char *res = NULL, *start = NULL, *end = NULL;
290 const char *command = "PWD\r\n";
292 if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
294 if (ftp_status(s, NULL, NULL, NULL, &res, 257) != 257)
297 for (i = 0; res[i]; ++i) {
311 if (end > res && end[-1] == '/') {
315 av_strlcpy(s->path, start, sizeof(s->path));
325 static int ftp_file_size(FTPContext *s)
327 char buf[CONTROL_BUFFER_SIZE];
331 snprintf(buf, sizeof(buf), "SIZE %s\r\n", s->path);
332 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
334 if (ftp_status(s, NULL, NULL, NULL, &res, 213) == 213) {
335 s->filesize = strtoll(&res[4], NULL, 10);
346 static int ftp_retrieve(FTPContext *s)
348 char buf[CONTROL_BUFFER_SIZE];
351 snprintf(buf, sizeof(buf), "RETR %s\r\n", s->path);
352 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
354 if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
357 s->state = DOWNLOADING;
362 static int ftp_store(FTPContext *s)
364 char buf[CONTROL_BUFFER_SIZE];
367 snprintf(buf, sizeof(buf), "STOR %s\r\n", s->path);
368 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
370 if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
373 s->state = UPLOADING;
378 static int ftp_send_command(FTPContext *s, const char* command)
382 if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
384 ftp_status(s, &err, NULL, NULL, NULL, -1);
391 static int ftp_reconnect_data_connection(URLContext *h)
394 char buf[CONTROL_BUFFER_SIZE], opts_format[20];
395 AVDictionary *opts = NULL;
396 FTPContext *s = h->priv_data;
399 ff_url_join(buf, sizeof(buf), "tcp", NULL, s->hostname, s->server_data_port, NULL);
400 if (s->rw_timeout != -1) {
401 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
402 av_dict_set(&opts, "timeout", opts_format, 0);
403 } /* if option is not given, don't pass it and let tcp use its own default */
404 err = ffurl_open(&s->conn_data, buf, AVIO_FLAG_READ_WRITE,
405 &h->interrupt_callback, &opts);
415 static int ftp_open(URLContext *h, const char *url, int flags)
417 char proto[10], auth[1024], path[MAX_URL_SIZE], buf[CONTROL_BUFFER_SIZE], opts_format[20];
418 AVDictionary *opts = NULL;
420 FTPContext *s = h->priv_data;
422 av_dlog(h, "ftp protocol open\n");
424 s->state = DISCONNECTED;
426 s->conn_control_interrupt_cb.opaque = s;
427 s->conn_control_interrupt_cb.callback = ftp_conn_control_block_control;
429 av_url_split(proto, sizeof(proto),
431 s->hostname, sizeof(s->hostname),
439 if (!s->conn_control) {
440 ff_url_join(buf, sizeof(buf), "tcp", NULL, s->hostname, port, NULL);
441 if (s->rw_timeout != -1) {
442 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
443 av_dict_set(&opts, "timeout", opts_format, 0);
444 } /* if option is not given, don't pass it and let tcp use its own default */
445 err = ffurl_open(&s->conn_control, buf, AVIO_FLAG_READ_WRITE,
446 &s->conn_control_interrupt_cb, &opts);
451 /* consume all messages from server */
452 if (ftp_status(s, NULL, NULL, NULL, NULL, 220) != 220) {
453 av_log(h, AV_LOG_ERROR, "Server not ready for new users\n");
454 err = AVERROR(EACCES);
458 if ((err = ftp_auth(s, auth)) < 0)
461 if ((err = ftp_send_command(s, "TYPE I\r\n")) < 0)
464 if ((err = ftp_current_dir(s)) < 0)
466 av_strlcat(s->path, path, sizeof(s->path));
468 if ((err = ftp_passive_mode(s)) < 0)
471 if (ftp_file_size(s) < 0 && flags & AVIO_FLAG_READ)
473 if (s->write_seekable != 1 && flags & AVIO_FLAG_WRITE)
477 if ((err = ftp_reconnect_data_connection(h)) < 0)
482 av_log(h, AV_LOG_ERROR, "FTP open failed\n");
483 ffurl_closep(&s->conn_control);
484 ffurl_closep(&s->conn_data);
488 static int ftp_read(URLContext *h, unsigned char *buf, int size)
490 FTPContext *s = h->priv_data;
493 av_dlog(h, "ftp protocol read %d bytes\n", size);
495 if (s->state == READY) {
498 if (s->conn_data && s->state == DOWNLOADING) {
499 read = ffurl_read(s->conn_data, buf, size);
502 if (s->position >= s->filesize) {
503 ffurl_closep(&s->conn_data);
504 s->state = DISCONNECTED;
505 if (ftp_status(s, NULL, NULL, NULL,NULL, 226) != 226)
512 av_log(h, AV_LOG_DEBUG, "FTP read failed\n");
516 static int ftp_write(URLContext *h, const unsigned char *buf, int size)
518 FTPContext *s = h->priv_data;
521 av_dlog(h, "ftp protocol write %d bytes\n", size);
523 if (s->state == READY) {
526 if (s->conn_data && s->state == UPLOADING) {
527 written = ffurl_write(s->conn_data, buf, size);
529 s->position += written;
530 s->filesize = FFMAX(s->filesize, s->position);
535 av_log(h, AV_LOG_ERROR, "FTP write failed\n");
539 static int64_t ftp_seek(URLContext *h, int64_t pos, int whence)
541 FTPContext *s = h->priv_data;
542 char buf[CONTROL_BUFFER_SIZE];
546 av_dlog(h, "ftp protocol seek %"PRId64" %d\n", pos, whence);
555 new_pos = s->position + pos;
560 new_pos = s->filesize + pos;
563 return AVERROR(EINVAL);
569 if (new_pos < 0 || (s->filesize >= 0 && new_pos > s->filesize))
570 return AVERROR(EINVAL);
572 if (new_pos != s->position) {
573 /* close existing data connection */
574 if (s->state != READY) {
576 /* abort existing transfer */
577 if (s->state == DOWNLOADING) {
578 snprintf(buf, sizeof(buf), "ABOR\r\n");
579 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
582 ffurl_closep(&s->conn_data);
583 s->state = DISCONNECTED;
584 /* Servers return 225 or 226 */
585 ftp_status(s, &err, NULL, NULL, NULL, -1);
591 if ((err = ftp_passive_mode(s)) < 0)
594 /* open new data connection */
595 if ((err = ftp_reconnect_data_connection(h)) < 0)
599 /* resume from pos position */
600 snprintf(buf, sizeof(buf), "REST %"PRId64"\r\n", pos);
601 if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
603 if (ftp_status(s, NULL, NULL, NULL, NULL, 350) != 350)
611 static int ftp_close(URLContext *h)
613 FTPContext *s = h->priv_data;
615 av_dlog(h, "ftp protocol close\n");
617 ffurl_closep(&s->conn_control);
618 ffurl_closep(&s->conn_data);
623 static int ftp_get_file_handle(URLContext *h)
625 FTPContext *s = h->priv_data;
627 av_dlog(h, "ftp protocol get_file_handle\n");
630 return ffurl_get_file_handle(s->conn_data);
635 static int ftp_shutdown(URLContext *h, int flags)
637 FTPContext *s = h->priv_data;
639 av_dlog(h, "ftp protocol shutdown\n");
642 return ffurl_shutdown(s->conn_data, flags);
647 URLProtocol ff_ftp_protocol = {
649 .url_open = ftp_open,
650 .url_read = ftp_read,
651 .url_write = ftp_write,
652 .url_seek = ftp_seek,
653 .url_close = ftp_close,
654 .url_get_file_handle = ftp_get_file_handle,
655 .url_shutdown = ftp_shutdown,
656 .priv_data_size = sizeof(FTPContext),
657 .priv_data_class = &ftp_context_class,
658 .flags = URL_PROTOCOL_FLAG_NETWORK,