Browse code

FTP protocol support

Implementation of ftp protocol.

Fixes #1672

Signed-off-by: Lukasz Marek <lukasz.m.luki@gmail.com>
Signed-off-by: Michael Niedermayer <michaelni@gmx.at>

Lukasz Marek authored on 2013/05/15 23:08:11
Showing 7 changed files
... ...
@@ -50,6 +50,7 @@ version <next>:
50 50
 - Wavelet denoiser filter ported from libmpcodecs as owdenoise (formerly "ow")
51 51
 - Apple Intermediate Codec decoder
52 52
 - Escape 130 video decoder
53
+- FTP protocol support
53 54
 
54 55
 
55 56
 version 1.2:
... ...
@@ -411,6 +411,7 @@ Muxers/Demuxers:
411 411
 
412 412
 Protocols:
413 413
   bluray.c                              Petri Hintukainen
414
+  ftp.c                                 Lukasz Marek
414 415
   http.c                                Ronald S. Bultje
415 416
   mms*.c                                Ronald S. Bultje
416 417
   udp.c                                 Luca Abeni
... ...
@@ -2090,6 +2090,7 @@ ffrtmpcrypt_protocol_deps_any="gcrypt nettle openssl"
2090 2090
 ffrtmpcrypt_protocol_select="tcp_protocol"
2091 2091
 ffrtmphttp_protocol_deps="!librtmp_protocol"
2092 2092
 ffrtmphttp_protocol_select="http_protocol"
2093
+ftp_protocol_select="tcp_protocol"
2093 2094
 gopher_protocol_select="network"
2094 2095
 httpproxy_protocol_select="tcp_protocol"
2095 2096
 http_protocol_select="tcp_protocol"
... ...
@@ -100,6 +100,40 @@ The ff* tools default to the file protocol, that is a resource
100 100
 specified with the name "FILE.mpeg" is interpreted as the URL
101 101
 "file:FILE.mpeg".
102 102
 
103
+@section ftp
104
+
105
+FTP (File Transfer Protocol)
106
+
107
+Allow to read from or write to remote resources using FTP protocol.
108
+
109
+Following syntax is required.
110
+@example
111
+ftp://[user[:password]@@]server[:port]/path/to/remote/resource.mpeg
112
+@end example
113
+
114
+This protocol accepts the following options.
115
+
116
+@table @option
117
+@item timeout
118
+Set timeout of socket I/O operations used by the underlying low level
119
+operation. By default it is set to -1, which means that the timeout is
120
+not specified.
121
+
122
+@item ftp-anonymous-password
123
+Password used when login as anonymous user. Typically an e-mail address
124
+should be used.
125
+
126
+@item ftp-write-seekable
127
+Control seekability of connection during encoding. If set to 1 the
128
+resource is supposed to be seekable, if set to 0 it is assumed not
129
+to be seekable. Default value is 0.
130
+@end table
131
+
132
+NOTE: Protocol can be used as output, but it is recommended to not do
133
+it, unless special care is taken (tests, customized server configuration
134
+etc.). Different FTP servers behave in different way during seek
135
+operation. ff* tools may produce incomplete content due to server limitations.
136
+
103 137
 @section gopher
104 138
 
105 139
 Gopher protocol.
... ...
@@ -424,6 +424,7 @@ OBJS-$(CONFIG_DATA_PROTOCOL)             += data_uri.o
424 424
 OBJS-$(CONFIG_FFRTMPCRYPT_PROTOCOL)      += rtmpcrypt.o rtmpdh.o
425 425
 OBJS-$(CONFIG_FFRTMPHTTP_PROTOCOL)       += rtmphttp.o
426 426
 OBJS-$(CONFIG_FILE_PROTOCOL)             += file.o
427
+OBJS-$(CONFIG_FTP_PROTOCOL)              += ftp.o
427 428
 OBJS-$(CONFIG_GOPHER_PROTOCOL)           += gopher.o
428 429
 OBJS-$(CONFIG_HLS_PROTOCOL)              += hlsproto.o
429 430
 OBJS-$(CONFIG_HTTP_PROTOCOL)             += http.o httpauth.o urldecode.o
... ...
@@ -313,6 +313,7 @@ void av_register_all(void)
313 313
     REGISTER_PROTOCOL(FFRTMPCRYPT,      ffrtmpcrypt);
314 314
     REGISTER_PROTOCOL(FFRTMPHTTP,       ffrtmphttp);
315 315
     REGISTER_PROTOCOL(FILE,             file);
316
+    REGISTER_PROTOCOL(FTP,              ftp);
316 317
     REGISTER_PROTOCOL(GOPHER,           gopher);
317 318
     REGISTER_PROTOCOL(HLS,              hls);
318 319
     REGISTER_PROTOCOL(HTTP,             http);
319 320
new file mode 100644
... ...
@@ -0,0 +1,659 @@
0
+/*
1
+ * Copyright (c) 2013 Lukasz Marek <lukasz.m.luki@gmail.com>
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
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
+
30
+#define CONTROL_BUFFER_SIZE 1024
31
+
32
+typedef enum {
33
+    UNKNOWN,
34
+    READY,
35
+    DOWNLOADING,
36
+    UPLOADING,
37
+    DISCONNECTED
38
+} FTPState;
39
+
40
+
41
+typedef struct {
42
+    const AVClass *class;
43
+    URLContext *conn_control;        /**< Control connection */
44
+    int conn_control_block_flag;     /**< Controls block/unblock mode of data connection */
45
+    AVIOInterruptCB conn_control_interrupt_cb; /**< Controls block/unblock mode of data connection */
46
+    URLContext *conn_data;           /**< Data connection, NULL when not connected */
47
+    uint8_t control_buffer[CONTROL_BUFFER_SIZE], *control_buf_ptr, *control_buf_end; /**< Control connection buffer */
48
+    int server_data_port;            /**< Data connection port opened by server, -1 on error. */
49
+    char hostname[512];              /**< Server address. */
50
+    char path[MAX_URL_SIZE];         /**< Path to resource on server. */
51
+    int64_t filesize;                /**< Size of file on server, -1 on error. */
52
+    int64_t position;                /**< Current position, calculated. */
53
+    int rw_timeout;                  /**< Network timeout. */
54
+    const char *anonymous_password;  /**< Password to be used for anonymous user. An email should be used. */
55
+    int write_seekable;              /**< Control seekability, 0 = disable, 1 = enable. */
56
+    FTPState state;                  /**< State of data connection */
57
+} FTPContext;
58
+
59
+#define OFFSET(x) offsetof(FTPContext, x)
60
+#define D AV_OPT_FLAG_DECODING_PARAM
61
+#define E AV_OPT_FLAG_ENCODING_PARAM
62
+static const AVOption options[] = {
63
+    {"timeout", "set timeout of socket I/O operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
64
+    {"ftp-write-seekable", "control seekability of connection during encoding", OFFSET(write_seekable), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
65
+    {"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 },
66
+    {NULL}
67
+};
68
+
69
+static const AVClass ftp_context_class = {
70
+    .class_name     = "ftp",
71
+    .item_name      = av_default_item_name,
72
+    .option         = options,
73
+    .version        = LIBAVUTIL_VERSION_INT,
74
+};
75
+
76
+static int ftp_conn_control_block_control(void *data)
77
+{
78
+    FTPContext *s = data;
79
+    return s->conn_control_block_flag;
80
+}
81
+
82
+static int ftp_getc(FTPContext *s)
83
+{
84
+    int len;
85
+    if (s->control_buf_ptr >= s->control_buf_end) {
86
+        if (s->conn_control_block_flag)
87
+            return AVERROR_EXIT;
88
+        len = ffurl_read(s->conn_control, s->control_buffer, CONTROL_BUFFER_SIZE);
89
+        if (len < 0) {
90
+            return len;
91
+        } else if (!len) {
92
+            return -1;
93
+        } else {
94
+            s->control_buf_ptr = s->control_buffer;
95
+            s->control_buf_end = s->control_buffer + len;
96
+        }
97
+    }
98
+    return *s->control_buf_ptr++;
99
+}
100
+
101
+static int ftp_get_line(FTPContext *s, char *line, int line_size)
102
+{
103
+    int ch;
104
+    char *q = line;
105
+    int ori_block_flag = s->conn_control_block_flag;
106
+
107
+    for (;;) {
108
+        ch = ftp_getc(s);
109
+        if (ch < 0) {
110
+            s->conn_control_block_flag = ori_block_flag;
111
+            return ch;
112
+        }
113
+        if (ch == '\n') {
114
+            /* process line */
115
+            if (q > line && q[-1] == '\r')
116
+                q--;
117
+            *q = '\0';
118
+
119
+            s->conn_control_block_flag = ori_block_flag;
120
+            return 0;
121
+        } else {
122
+            s->conn_control_block_flag = 0; /* line need to be finished */
123
+            if ((q - line) < line_size - 1)
124
+                *q++ = ch;
125
+        }
126
+    }
127
+}
128
+
129
+/*
130
+ * This routine returns ftp server response code.
131
+ * Server may send more than one response for a certain command, following priorites are used:
132
+ *   - 5xx code is returned if occurred. (means error)
133
+ *   - When pref_code is set then pref_code is return if occurred. (expected result)
134
+ *   - The lowest code is returned. (means success)
135
+ */
136
+static int ftp_status(FTPContext *s, int *major, int *minor, int *extra, char **line, int pref_code)
137
+{
138
+    int err, result = -1, pref_code_found = 0;
139
+    char buf[CONTROL_BUFFER_SIZE];
140
+    unsigned char d_major, d_minor, d_extra;
141
+
142
+    /* Set blocking mode */
143
+    s->conn_control_block_flag = 0;
144
+    for (;;) {
145
+        if ((err = ftp_get_line(s, buf, CONTROL_BUFFER_SIZE)) < 0) {
146
+            if (err == AVERROR_EXIT)
147
+                return result;
148
+            return err;
149
+        }
150
+
151
+        if (strlen(buf) < 3)
152
+            continue;
153
+        d_major = buf[0];
154
+        if (d_major < '1' || d_major > '6' || d_major == '4')
155
+            continue;
156
+        d_minor = buf[1];
157
+        if (d_minor < '0' || d_minor > '9')
158
+            continue;
159
+        d_extra = buf[2];
160
+        if (d_extra < '0' || d_extra > '9')
161
+            continue;
162
+
163
+        av_log(s, AV_LOG_DEBUG, "%s\n", buf);
164
+
165
+        err = d_major * 100 + d_minor * 10 + d_extra - 111 * '0';
166
+
167
+        if ((result < 0 || err < result || pref_code == err) && !pref_code_found || d_major == '5') {
168
+            if (pref_code == err || d_major == '5')
169
+                pref_code_found = 1;
170
+            result = err;
171
+            if (major)
172
+                *major = d_major - '0';
173
+            if (minor)
174
+                *minor = d_minor - '0';
175
+            if (extra)
176
+                *extra = d_extra - '0';
177
+            if (line)
178
+                *line = av_strdup(buf);
179
+        }
180
+
181
+        /* first code received. Now get all lines in non blocking mode */
182
+        if (pref_code < 0 || pref_code_found)
183
+            s->conn_control_block_flag = 1;
184
+    }
185
+    return result;
186
+}
187
+
188
+static int ftp_auth(FTPContext *s, char *auth)
189
+{
190
+    const char *user = NULL, *pass = NULL;
191
+    char *end = NULL, buf[CONTROL_BUFFER_SIZE];
192
+    int err;
193
+    av_assert2(auth);
194
+
195
+    user = av_strtok(auth, ":", &end);
196
+    pass = av_strtok(end, ":", &end);
197
+
198
+    if (user) {
199
+        snprintf(buf, sizeof(buf), "USER %s\r\n", user);
200
+        if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
201
+            return err;
202
+        ftp_status(s, &err, NULL, NULL, NULL, -1);
203
+        if (err == 3) {
204
+            if (pass) {
205
+                snprintf(buf, sizeof(buf), "PASS %s\r\n", pass);
206
+                if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
207
+                    return err;
208
+                ftp_status(s, &err, NULL, NULL, NULL, -1);
209
+            } else
210
+                return AVERROR(EACCES);
211
+        }
212
+        if (err != 2) {
213
+            return AVERROR(EACCES);
214
+        }
215
+    } else {
216
+        const char* command = "USER anonymous\r\n";
217
+        if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
218
+            return err;
219
+        ftp_status(s, &err, NULL, NULL, NULL, -1);
220
+        if (err == 3) {
221
+            if (s->anonymous_password) {
222
+                snprintf(buf, sizeof(buf), "PASS %s\r\n", s->anonymous_password);
223
+            } else
224
+                snprintf(buf, sizeof(buf), "PASS nopassword\r\n");
225
+            if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
226
+                return err;
227
+            ftp_status(s, &err, NULL, NULL, NULL, -1);
228
+        }
229
+        if (err != 2) {
230
+            return AVERROR(EACCES);
231
+        }
232
+    }
233
+
234
+    return 0;
235
+}
236
+
237
+static int ftp_passive_mode(FTPContext *s)
238
+{
239
+    char *res = NULL, *start, *end;
240
+    int err, i;
241
+    const char *command = "PASV\r\n";
242
+
243
+    if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
244
+        return err;
245
+    if (ftp_status(s, NULL, NULL, NULL, &res, 227) != 227)
246
+        goto fail;
247
+
248
+    start = NULL;
249
+    for (i = 0; i < strlen(res); ++i) {
250
+        if (res[i] == '(') {
251
+            start = res + i + 1;
252
+        } else if (res[i] == ')') {
253
+            end = res + i;
254
+            break;
255
+        }
256
+    }
257
+    if (!start || !end)
258
+        goto fail;
259
+
260
+    *end  = '\0';
261
+    /* skip ip */
262
+    if (!av_strtok(start, ",", &end)) goto fail;
263
+    if (!av_strtok(end, ",", &end)) goto fail;
264
+    if (!av_strtok(end, ",", &end)) goto fail;
265
+    if (!av_strtok(end, ",", &end)) goto fail;
266
+
267
+    /* parse port number */
268
+    start = av_strtok(end, ",", &end);
269
+    if (!start) goto fail;
270
+    s->server_data_port = atoi(start) * 256;
271
+    start = av_strtok(end, ",", &end);
272
+    if (!start) goto fail;
273
+    s->server_data_port += atoi(start);
274
+    av_dlog(s, "Server data port: %d\n", s->server_data_port);
275
+
276
+    av_free(res);
277
+    return 0;
278
+
279
+  fail:
280
+    av_free(res);
281
+    s->server_data_port = -1;
282
+    return AVERROR(EIO);
283
+}
284
+
285
+static int ftp_current_dir(FTPContext *s)
286
+{
287
+    char *res = NULL, *start = NULL, *end = NULL;
288
+    int err, i;
289
+    const char *command = "PWD\r\n";
290
+
291
+    if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
292
+        return err;
293
+    if (ftp_status(s, NULL, NULL, NULL, &res, 257) != 257)
294
+        goto fail;
295
+
296
+    for (i = 0; res[i]; ++i) {
297
+        if (res[i] == '"') {
298
+            if (!start) {
299
+                start = res + i + 1;
300
+                continue;
301
+            }
302
+            end = res + i;
303
+            break;
304
+        }
305
+    }
306
+
307
+    if (!end)
308
+        goto fail;
309
+
310
+    if (end > res && end[-1] == '/') {
311
+        end[-1] = '\0';
312
+    } else
313
+        *end = '\0';
314
+    av_strlcpy(s->path, start, sizeof(s->path));
315
+
316
+    av_free(res);
317
+    return 0;
318
+
319
+  fail:
320
+    av_free(res);
321
+    return AVERROR(EIO);
322
+}
323
+
324
+static int ftp_file_size(FTPContext *s)
325
+{
326
+    char buf[CONTROL_BUFFER_SIZE];
327
+    int err;
328
+    char *res = NULL;
329
+
330
+    snprintf(buf, sizeof(buf), "SIZE %s\r\n", s->path);
331
+    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
332
+        return err;
333
+    if (ftp_status(s, NULL, NULL, NULL, &res, 213) == 213) {
334
+        s->filesize = atoll(&res[4]);
335
+    } else {
336
+        s->filesize = -1;
337
+        av_free(res);
338
+        return AVERROR(EIO);
339
+    }
340
+
341
+    av_free(res);
342
+    return 0;
343
+}
344
+
345
+static int ftp_retrieve(FTPContext *s)
346
+{
347
+    char buf[CONTROL_BUFFER_SIZE];
348
+    int err;
349
+
350
+    snprintf(buf, sizeof(buf), "RETR %s\r\n", s->path);
351
+    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
352
+        return err;
353
+    if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
354
+        return AVERROR(EIO);
355
+
356
+    s->state = DOWNLOADING;
357
+
358
+    return 0;
359
+}
360
+
361
+static int ftp_store(FTPContext *s)
362
+{
363
+    char buf[CONTROL_BUFFER_SIZE];
364
+    int err;
365
+
366
+    snprintf(buf, sizeof(buf), "STOR %s\r\n", s->path);
367
+    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
368
+        return err;
369
+    if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
370
+        return AVERROR(EIO);
371
+
372
+    s->state = UPLOADING;
373
+
374
+    return 0;
375
+}
376
+
377
+static int ftp_send_command(FTPContext *s, const char* command)
378
+{
379
+    int err;
380
+
381
+    if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
382
+        return err;
383
+    ftp_status(s, &err, NULL, NULL, NULL, -1);
384
+    if (err != 2)
385
+        return AVERROR(EIO);
386
+
387
+    return 0;
388
+}
389
+
390
+static int ftp_reconnect_data_connection(URLContext *h)
391
+{
392
+    int err;
393
+    char buf[CONTROL_BUFFER_SIZE], opts_format[20];
394
+    AVDictionary *opts = NULL;
395
+    FTPContext *s = h->priv_data;
396
+
397
+    if (!s->conn_data) {
398
+        ff_url_join(buf, sizeof(buf), "tcp", NULL, s->hostname, s->server_data_port, NULL);
399
+        if (s->rw_timeout != -1) {
400
+            snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
401
+            av_dict_set(&opts, "timeout", opts_format, 0);
402
+        } /* if option is not given, don't pass it and let tcp use its own default */
403
+        err = ffurl_open(&s->conn_data, buf, AVIO_FLAG_READ_WRITE,
404
+                         &h->interrupt_callback, &opts);
405
+        av_dict_free(&opts);
406
+        if (err < 0)
407
+            return err;
408
+    }
409
+    s->state = READY;
410
+    s->position = 0;
411
+    return 0;
412
+}
413
+
414
+static int ftp_open(URLContext *h, const char *url, int flags)
415
+{
416
+    char proto[10], auth[1024], path[MAX_URL_SIZE], buf[CONTROL_BUFFER_SIZE], opts_format[20];
417
+    AVDictionary *opts = NULL;
418
+    int port, err;
419
+    FTPContext *s = h->priv_data;
420
+
421
+    av_dlog(h, "ftp protocol open\n");
422
+
423
+    s->state = DISCONNECTED;
424
+    s->filesize = -1;
425
+    s->conn_control_interrupt_cb.opaque = s;
426
+    s->conn_control_interrupt_cb.callback = ftp_conn_control_block_control;
427
+
428
+    av_url_split(proto, sizeof(proto),
429
+                 auth, sizeof(auth),
430
+                 s->hostname, sizeof(s->hostname),
431
+                 &port,
432
+                 path, sizeof(path),
433
+                 url);
434
+
435
+    if (port < 0)
436
+        port = 21;
437
+
438
+    if (!s->conn_control) {
439
+        ff_url_join(buf, sizeof(buf), "tcp", NULL, s->hostname, port, NULL);
440
+        if (s->rw_timeout != -1) {
441
+            snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
442
+            av_dict_set(&opts, "timeout", opts_format, 0);
443
+        } /* if option is not given, don't pass it and let tcp use its own default */
444
+        err = ffurl_open(&s->conn_control, buf, AVIO_FLAG_READ_WRITE,
445
+                         &s->conn_control_interrupt_cb, &opts);
446
+        av_dict_free(&opts);
447
+        if (err < 0)
448
+            goto fail;
449
+
450
+        /* consume all messages from server */
451
+        if (ftp_status(s, NULL, NULL, NULL, NULL, 220) != 220) {
452
+            av_log(h, AV_LOG_ERROR, "Server not ready for new users\n");
453
+            err = AVERROR(EACCES);
454
+            goto fail;
455
+        }
456
+
457
+        if ((err = ftp_auth(s, auth)) < 0)
458
+            goto fail;
459
+
460
+        if ((err = ftp_send_command(s, "TYPE I\r\n")) < 0)
461
+            goto fail;
462
+
463
+        if ((err = ftp_current_dir(s)) < 0)
464
+            goto fail;
465
+        av_strlcat(s->path, path, sizeof(s->path));
466
+
467
+        if ((err = ftp_passive_mode(s)) < 0)
468
+            goto fail;
469
+
470
+        if (ftp_file_size(s) < 0 && flags & AVIO_FLAG_READ)
471
+            h->is_streamed = 1;
472
+        if (s->write_seekable != 1 && flags & AVIO_FLAG_WRITE)
473
+            h->is_streamed = 1;
474
+    }
475
+
476
+    if ((err = ftp_reconnect_data_connection(h)) < 0)
477
+        goto fail;
478
+
479
+    return 0;
480
+  fail:
481
+    av_log(h, AV_LOG_ERROR, "FTP open failed\n");
482
+    ffurl_closep(&s->conn_control);
483
+    ffurl_closep(&s->conn_data);
484
+    return err;
485
+}
486
+
487
+static int ftp_read(URLContext *h, unsigned char *buf, int size)
488
+{
489
+    FTPContext *s = h->priv_data;
490
+    int read;
491
+
492
+    av_dlog(h, "ftp protocol read %d bytes\n", size);
493
+
494
+    if (s->state == READY) {
495
+        ftp_retrieve(s);
496
+    }
497
+    if (s->conn_data && s->state == DOWNLOADING) {
498
+        read = ffurl_read(s->conn_data, buf, size);
499
+        if (read >= 0) {
500
+            s->position += read;
501
+            if (s->position >= s->filesize) {
502
+                ffurl_closep(&s->conn_data);
503
+                s->state = DISCONNECTED;
504
+                if (ftp_status(s, NULL, NULL, NULL,NULL, 226) != 226)
505
+                    return AVERROR(EIO);
506
+            }
507
+        }
508
+        return read;
509
+    }
510
+
511
+    av_log(h, AV_LOG_DEBUG, "FTP read failed\n");
512
+    return AVERROR(EIO);
513
+}
514
+
515
+static int ftp_write(URLContext *h, const unsigned char *buf, int size)
516
+{
517
+    FTPContext *s = h->priv_data;
518
+    int written;
519
+
520
+    av_dlog(h, "ftp protocol write %d bytes\n", size);
521
+
522
+    if (s->state == READY) {
523
+        ftp_store(s);
524
+    }
525
+    if (s->conn_data && s->state == UPLOADING) {
526
+        written = ffurl_write(s->conn_data, buf, size);
527
+        if (written > 0) {
528
+            s->position += written;
529
+            s->filesize = FFMAX(s->filesize, s->position);
530
+        }
531
+        return written;
532
+    }
533
+
534
+    av_log(h, AV_LOG_ERROR, "FTP write failed\n");
535
+    return AVERROR(EIO);
536
+}
537
+
538
+static int64_t ftp_seek(URLContext *h, int64_t pos, int whence)
539
+{
540
+    FTPContext *s = h->priv_data;
541
+    char buf[CONTROL_BUFFER_SIZE];
542
+    int err;
543
+    int64_t new_pos;
544
+
545
+    av_dlog(h, "ftp protocol seek %"PRId64" %d\n", pos, whence);
546
+
547
+    switch(whence) {
548
+    case AVSEEK_SIZE:
549
+        return s->filesize;
550
+    case SEEK_SET:
551
+        new_pos = pos;
552
+        break;
553
+    case SEEK_CUR:
554
+        new_pos = s->position + pos;
555
+        break;
556
+    case SEEK_END:
557
+        if (s->filesize < 0)
558
+            return AVERROR(EIO);
559
+        new_pos = s->filesize + pos;
560
+        break;
561
+    default:
562
+        return AVERROR(EINVAL);
563
+    }
564
+
565
+    if  (h->is_streamed)
566
+        return AVERROR(EIO);
567
+
568
+    if (new_pos < 0 || (s->filesize >= 0 && new_pos > s->filesize))
569
+        return AVERROR(EINVAL);
570
+
571
+    if (new_pos != s->position) {
572
+        /* close existing data connection */
573
+        if (s->state != READY) {
574
+            if (s->conn_data) {
575
+                /* abort existing transfer */
576
+                if (s->state == DOWNLOADING) {
577
+                    snprintf(buf, sizeof(buf), "ABOR\r\n");
578
+                    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
579
+                        return err;
580
+                }
581
+                ffurl_closep(&s->conn_data);
582
+                s->state = DISCONNECTED;
583
+                /* Servers return 225 or 226 */
584
+                ftp_status(s, &err, NULL, NULL, NULL, -1);
585
+                if (err != 2)
586
+                    return AVERROR(EIO);
587
+            }
588
+
589
+            /* set passive */
590
+            if ((err = ftp_passive_mode(s)) < 0)
591
+                return err;
592
+
593
+            /* open new data connection */
594
+            if ((err = ftp_reconnect_data_connection(h)) < 0)
595
+                return err;
596
+        }
597
+
598
+        /* resume from pos position */
599
+        snprintf(buf, sizeof(buf), "REST %"PRId64"\r\n", pos);
600
+        if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
601
+            return err;
602
+        if (ftp_status(s, NULL, NULL, NULL, NULL, 350) != 350)
603
+            return AVERROR(EIO);
604
+
605
+        s->position = pos;
606
+    }
607
+    return new_pos;
608
+}
609
+
610
+static int ftp_close(URLContext *h)
611
+{
612
+    FTPContext *s = h->priv_data;
613
+
614
+    av_dlog(h, "ftp protocol close\n");
615
+
616
+    ffurl_closep(&s->conn_control);
617
+    ffurl_closep(&s->conn_data);
618
+
619
+    return 0;
620
+}
621
+
622
+static int ftp_get_file_handle(URLContext *h)
623
+{
624
+    FTPContext *s = h->priv_data;
625
+
626
+    av_dlog(h, "ftp protocol get_file_handle\n");
627
+
628
+    if (s->conn_data)
629
+        return ffurl_get_file_handle(s->conn_data);
630
+
631
+    return AVERROR(EIO);
632
+}
633
+
634
+static int ftp_shutdown(URLContext *h, int flags)
635
+{
636
+    FTPContext *s = h->priv_data;
637
+
638
+    av_dlog(h, "ftp protocol shutdown\n");
639
+
640
+    if (s->conn_data)
641
+        return ffurl_shutdown(s->conn_data, flags);
642
+
643
+    return AVERROR(EIO);
644
+}
645
+
646
+URLProtocol ff_ftp_protocol = {
647
+    .name                = "ftp",
648
+    .url_open            = ftp_open,
649
+    .url_read            = ftp_read,
650
+    .url_write           = ftp_write,
651
+    .url_seek            = ftp_seek,
652
+    .url_close           = ftp_close,
653
+    .url_get_file_handle = ftp_get_file_handle,
654
+    .url_shutdown        = ftp_shutdown,
655
+    .priv_data_size      = sizeof(FTPContext),
656
+    .priv_data_class     = &ftp_context_class,
657
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
658
+};