]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/ftp.c
vf_sab: Fix memleak
[ffmpeg] / libavformat / ftp.c
index e497c1a9def970bdcfd1ce6465a2a82eae7d4b12..a256a25335a6af08fa4135eda9775b158dd3940d 100644 (file)
@@ -20,6 +20,7 @@
 
 #include <stdlib.h>
 #include "libavutil/avstring.h"
+#include "libavutil/time.h"
 #include "avformat.h"
 #include "internal.h"
 #include "network.h"
@@ -129,70 +130,121 @@ static int ftp_get_line(FTPContext *s, char *line, int line_size)
     }
 }
 
+static int ftp_flush_control_input(FTPContext *s)
+{
+    char buf[CONTROL_BUFFER_SIZE];
+    int err, ori_block_flag = s->conn_control_block_flag;
+
+    s->conn_control_block_flag = 1;
+    do {
+        err = ftp_get_line(s, buf, sizeof(buf));
+    } while (!err);
+
+    s->conn_control_block_flag = ori_block_flag;
+
+    if (err < 0 && err != AVERROR_EXIT)
+        return err;
+
+    return 0;
+}
+
 /*
  * This routine returns ftp server response code.
  * Server may send more than one response for a certain command, following priorities are used:
- *   - 5xx code is returned if occurred. (means error)
- *   - When pref_code is set then pref_code is return if occurred. (expected result)
- *   - The lowest code is returned. (means success)
+ *   - When pref_codes are set then pref_code is return if occurred. (expected result)
+ *   - 0 is returned when no pref_codes or not occurred
  */
-static int ftp_status(FTPContext *s, int *major, int *minor, int *extra, char **line, int pref_code)
+static int ftp_status(FTPContext *s, char **line, const int response_codes[])
 {
-    int err, result = -1, pref_code_found = 0;
+    int err, i, result = 0, pref_code_found = 0, wait_count = 100;
     char buf[CONTROL_BUFFER_SIZE];
-    unsigned char d_major, d_minor, d_extra;
 
     /* Set blocking mode */
     s->conn_control_block_flag = 0;
     for (;;) {
-        if ((err = ftp_get_line(s, buf, CONTROL_BUFFER_SIZE)) < 0) {
-            if (err == AVERROR_EXIT)
-                return result;
-            return err;
+        if ((err = ftp_get_line(s, buf, sizeof(buf))) < 0) {
+            if (err == AVERROR_EXIT) {
+                if (!pref_code_found && wait_count--) {
+                    av_usleep(10000);
+                    continue;
+                }
+            }
+            return result;
         }
 
-        if (strlen(buf) < 3)
-            continue;
-        d_major = buf[0];
-        if (d_major < '1' || d_major > '6' || d_major == '4')
-            continue;
-        d_minor = buf[1];
-        if (d_minor < '0' || d_minor > '9')
-            continue;
-        d_extra = buf[2];
-        if (d_extra < '0' || d_extra > '9')
-            continue;
-
         av_log(s, AV_LOG_DEBUG, "%s\n", buf);
 
-        err = d_major * 100 + d_minor * 10 + d_extra - 111 * '0';
-
-        if ((result < 0 || err < result || pref_code == err) && !pref_code_found || d_major == '5') {
-            if (pref_code == err || d_major == '5')
-                pref_code_found = 1;
-            result = err;
-            if (major)
-                *major = d_major - '0';
-            if (minor)
-                *minor = d_minor - '0';
-            if (extra)
-                *extra = d_extra - '0';
-            if (line)
-                *line = av_strdup(buf);
-        }
+        if (!pref_code_found) {
+            if (strlen(buf) < 3)
+                continue;
 
-        /* first code received. Now get all lines in non blocking mode */
-        if (pref_code < 0 || pref_code_found)
-            s->conn_control_block_flag = 1;
+            err = 0;
+            for (i = 0; i < 3; ++i) {
+                if (buf[i] < '0' || buf[i] > '9')
+                    continue;
+                err *= 10;
+                err += buf[i] - '0';
+            }
+
+            for (i = 0; response_codes[i]; ++i) {
+                if (err == response_codes[i]) {
+                    /* first code received. Now get all lines in non blocking mode */
+                    s->conn_control_block_flag = 1;
+                    pref_code_found = 1;
+                    result = err;
+                    if (line)
+                        *line = av_strdup(buf);
+                    break;
+                }
+            }
+        }
     }
     return result;
 }
 
+static int ftp_send_command(FTPContext *s, const char *command,
+                            const int response_codes[], char **response)
+{
+    int err;
+
+    /* Flush control connection input to get rid of non relevant responses if any */
+    if ((err = ftp_flush_control_input(s)) < 0)
+        return err;
+
+    /* send command in blocking mode */
+    s->conn_control_block_flag = 0;
+    if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
+        return err;
+    if (!err)
+        return -1;
+
+    /* return status */
+    if (response_codes) {
+        return ftp_status(s, response, response_codes);
+    }
+    return 0;
+}
+
+static void ftp_close_data_connection(FTPContext *s)
+{
+    ffurl_closep(&s->conn_data);
+    s->position = 0;
+    s->state = DISCONNECTED;
+}
+
+static void ftp_close_both_connections(FTPContext *s)
+{
+    ffurl_closep(&s->conn_control);
+    ftp_close_data_connection(s);
+}
+
 static int ftp_auth(FTPContext *s)
 {
     const char *user = NULL, *pass = NULL;
     char *end = NULL, buf[CONTROL_BUFFER_SIZE], credencials[CREDENTIALS_BUFFER_SIZE];
     int err;
+    const int user_codes[] = {331, 230, 500, 530, 0}; /* 500, 530 are incorrect codes */
+    const int pass_codes[] = {230, 503, 530, 0}; /* 503, 530 are incorrect codes */
 
     /* Authentication may be repeated, original string has to be saved */
     av_strlcpy(credencials, s->credencials, sizeof(credencials));
@@ -206,38 +258,31 @@ static int ftp_auth(FTPContext *s)
     }
 
     snprintf(buf, sizeof(buf), "USER %s\r\n", user);
-    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
-        return err;
-    ftp_status(s, &err, NULL, NULL, NULL, -1);
-    if (err == 3) {
+    err = ftp_send_command(s, buf, user_codes, NULL);
+    if (err == 331) {
         if (pass) {
             snprintf(buf, sizeof(buf), "PASS %s\r\n", pass);
-            if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
-                return err;
-            ftp_status(s, &err, NULL, NULL, NULL, -1);
+            err = ftp_send_command(s, buf, pass_codes, NULL);
         } else
             return AVERROR(EACCES);
     }
-    if (err != 2) {
+    if (err != 230)
         return AVERROR(EACCES);
-    }
 
     return 0;
 }
 
 static int ftp_passive_mode(FTPContext *s)
 {
-    char *res = NULL, *start, *end;
-    int err, i;
+    char *res = NULL, *start = NULL, *end = NULL;
+    int i;
     const char *command = "PASV\r\n";
+    const int pasv_codes[] = {227, 501, 0}; /* 501 is incorrect code */
 
-    if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
-        return err;
-    if (ftp_status(s, NULL, NULL, NULL, &res, 227) != 227)
+    if (ftp_send_command(s, command, pasv_codes, &res) != 227 || !res)
         goto fail;
 
-    start = NULL;
-    for (i = 0; i < strlen(res); ++i) {
+    for (i = 0; res[i]; ++i) {
         if (res[i] == '(') {
             start = res + i + 1;
         } else if (res[i] == ')') {
@@ -276,12 +321,11 @@ static int ftp_passive_mode(FTPContext *s)
 static int ftp_current_dir(FTPContext *s)
 {
     char *res = NULL, *start = NULL, *end = NULL;
-    int err, i;
+    int i;
     const char *command = "PWD\r\n";
+    const int pwd_codes[] = {257, 0};
 
-    if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
-        return err;
-    if (ftp_status(s, NULL, NULL, NULL, &res, 257) != 257)
+    if (ftp_send_command(s, command, pwd_codes, &res) != 257 || !res)
         goto fail;
 
     for (i = 0; res[i]; ++i) {
@@ -314,14 +358,12 @@ static int ftp_current_dir(FTPContext *s)
 
 static int ftp_file_size(FTPContext *s)
 {
-    char buf[CONTROL_BUFFER_SIZE];
-    int err;
+    char command[CONTROL_BUFFER_SIZE];
     char *res = NULL;
+    const int size_codes[] = {213, 501, 550, 0}; /* 501, 550 are incorrect codes */
 
-    snprintf(buf, sizeof(buf), "SIZE %s\r\n", s->path);
-    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
-        return err;
-    if (ftp_status(s, NULL, NULL, NULL, &res, 213) == 213) {
+    snprintf(command, sizeof(command), "SIZE %s\r\n", s->path);
+    if (ftp_send_command(s, command, size_codes, &res) == 213 && res) {
         s->filesize = strtoll(&res[4], NULL, 10);
     } else {
         s->filesize = -1;
@@ -335,13 +377,11 @@ static int ftp_file_size(FTPContext *s)
 
 static int ftp_retrieve(FTPContext *s)
 {
-    char buf[CONTROL_BUFFER_SIZE];
-    int err;
+    char command[CONTROL_BUFFER_SIZE];
+    const int retr_codes[] = {150, 550, 554, 0}; /* 550, 554 are incorrect codes */
 
-    snprintf(buf, sizeof(buf), "RETR %s\r\n", s->path);
-    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
-        return err;
-    if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
+    snprintf(command, sizeof(command), "RETR %s\r\n", s->path);
+    if (ftp_send_command(s, command, retr_codes, NULL) != 150)
         return AVERROR(EIO);
 
     s->state = DOWNLOADING;
@@ -351,13 +391,11 @@ static int ftp_retrieve(FTPContext *s)
 
 static int ftp_store(FTPContext *s)
 {
-    char buf[CONTROL_BUFFER_SIZE];
-    int err;
+    char command[CONTROL_BUFFER_SIZE];
+    const int stor_codes[] = {150, 0};
 
-    snprintf(buf, sizeof(buf), "STOR %s\r\n", s->path);
-    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
-        return err;
-    if (ftp_status(s, NULL, NULL, NULL, NULL, 150) != 150)
+    snprintf(command, sizeof(command), "STOR %s\r\n", s->path);
+    if (ftp_send_command(s, command, stor_codes, NULL) != 150)
         return AVERROR(EIO);
 
     s->state = UPLOADING;
@@ -367,12 +405,22 @@ static int ftp_store(FTPContext *s)
 
 static int ftp_type(FTPContext *s)
 {
-    int err;
     const char *command = "TYPE I\r\n";
+    const int type_codes[] = {200, 500, 504, 0}; /* 500, 504 are incorrect codes */
 
-    if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)
-        return err;
-    if (ftp_status(s, NULL, NULL, NULL, NULL, 200) != 200)
+    if (ftp_send_command(s, command, type_codes, NULL) != 200)
+        return AVERROR(EIO);
+
+    return 0;
+}
+
+static int ftp_restart(FTPContext *s, int64_t pos)
+{
+    char command[CONTROL_BUFFER_SIZE];
+    const int rest_codes[] = {350, 500, 501, 0}; /* 500, 501 are incorrect codes */
+
+    snprintf(command, sizeof(command), "REST %"PRId64"\r\n", pos);
+    if (ftp_send_command(s, command, rest_codes, NULL) != 350)
         return AVERROR(EIO);
 
     return 0;
@@ -384,6 +432,7 @@ static int ftp_connect_control_connection(URLContext *h)
     int err;
     AVDictionary *opts = NULL;
     FTPContext *s = h->priv_data;
+    const int connect_codes[] = {220, 0};
 
     s->conn_control_block_flag = 0;
 
@@ -398,15 +447,14 @@ static int ftp_connect_control_connection(URLContext *h)
                          &s->conn_control_interrupt_cb, &opts);
         av_dict_free(&opts);
         if (err < 0) {
-            av_dlog(h, "Cannot open control connection, error %d\n", err);
+            av_log(h, AV_LOG_ERROR, "Cannot open control connection\n");
             return err;
         }
 
         /* consume all messages from server */
-        if (ftp_status(s, NULL, NULL, NULL, NULL, 220) != 220) {
+        if (ftp_status(s, NULL, connect_codes) != 220) {
             av_log(h, AV_LOG_ERROR, "FTP server not ready for new users\n");
-            err = AVERROR(EACCES);
-            return err;
+            return AVERROR(EACCES);
         }
 
         if ((err = ftp_auth(s)) < 0) {
@@ -446,9 +494,51 @@ static int ftp_connect_data_connection(URLContext *h)
         av_dict_free(&opts);
         if (err < 0)
             return err;
+
+        if (s->position)
+            if ((err = ftp_restart(s, s->position)) < 0)
+                return err;
     }
     s->state = READY;
-    s->position = 0;
+    return 0;
+}
+
+static int ftp_abort(URLContext *h)
+{
+    const char *command = "ABOR\r\n";
+    int err;
+    const int abor_codes[] = {225, 226, 0};
+    FTPContext *s = h->priv_data;
+
+    /* According to RCF 959:
+       "ABOR command tells the server to abort the previous FTP
+       service command and any associated transfer of data."
+
+       There are FTP server implementations that don't response
+       to any commands during data transfer in passive mode (including ABOR).
+
+       This implementation closes data connection by force.
+    */
+
+    if (ftp_send_command(s, command, NULL, NULL) < 0) {
+        ftp_close_both_connections(s);
+        if ((err = ftp_connect_control_connection(h)) < 0) {
+            av_log(h, AV_LOG_ERROR, "Reconnect failed.\n");
+            return err;
+        }
+    } else {
+        ftp_close_data_connection(s);
+    }
+
+    if (ftp_status(s, NULL, abor_codes) < 225) {
+        /* wu-ftpd also closes control connection after data connection closing */
+        ffurl_closep(&s->conn_control);
+        if ((err = ftp_connect_control_connection(h)) < 0) {
+            av_log(h, AV_LOG_ERROR, "Reconnect failed.\n");
+            return err;
+        }
+    }
+
     return 0;
 }
 
@@ -462,6 +552,7 @@ static int ftp_open(URLContext *h, const char *url, int flags)
 
     s->state = DISCONNECTED;
     s->filesize = -1;
+    s->position = 0;
     s->conn_control_interrupt_cb.opaque = s;
     s->conn_control_interrupt_cb.callback = ftp_conn_control_block_control;
 
@@ -482,15 +573,17 @@ static int ftp_open(URLContext *h, const char *url, int flags)
         goto fail;
     av_strlcat(s->path, path, sizeof(s->path));
 
-    if (ftp_file_size(s) < 0 && flags & AVIO_FLAG_READ)
+    if (ftp_restart(s, 0) < 0) {
         h->is_streamed = 1;
-    if (s->write_seekable != 1 && flags & AVIO_FLAG_WRITE)
-        h->is_streamed = 1;
-
-    if ((err = ftp_connect_data_connection(h)) < 0)
-        goto fail;
+    } else {
+        if (ftp_file_size(s) < 0 && flags & AVIO_FLAG_READ)
+            h->is_streamed = 1;
+        if (s->write_seekable != 1 && flags & AVIO_FLAG_WRITE)
+            h->is_streamed = 1;
+    }
 
     return 0;
+
   fail:
     av_log(h, AV_LOG_ERROR, "FTP open failed\n");
     ffurl_closep(&s->conn_control);
@@ -501,9 +594,8 @@ static int ftp_open(URLContext *h, const char *url, int flags)
 static int64_t ftp_seek(URLContext *h, int64_t pos, int whence)
 {
     FTPContext *s = h->priv_data;
-    char buf[CONTROL_BUFFER_SIZE];
     int err;
-    int64_t new_pos;
+    int64_t new_pos, fake_pos;
 
     av_dlog(h, "ftp protocol seek %"PRId64" %d\n", pos, whence);
 
@@ -528,40 +620,13 @@ static int64_t ftp_seek(URLContext *h, int64_t pos, int whence)
     if  (h->is_streamed)
         return AVERROR(EIO);
 
-    if (new_pos < 0 || (s->filesize >= 0 && new_pos > s->filesize))
-        return AVERROR(EINVAL);
-
-    if (new_pos != s->position) {
-        /* close existing data connection */
-        if (s->state != READY) {
-            if (s->conn_data) {
-                /* abort existing transfer */
-                if (s->state == DOWNLOADING) {
-                    snprintf(buf, sizeof(buf), "ABOR\r\n");
-                    if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
-                        return err;
-                }
-                ffurl_closep(&s->conn_data);
-                s->state = DISCONNECTED;
-                /* Servers return 225 or 226 */
-                ftp_status(s, &err, NULL, NULL, NULL, -1);
-                if (err != 2)
-                    return AVERROR(EIO);
-            }
-
-            /* open new data connection */
-            if ((err = ftp_connect_data_connection(h)) < 0)
-                return err;
-        }
+    new_pos = FFMAX(0, new_pos);
+    fake_pos = s->filesize != -1 ? FFMIN(new_pos, s->filesize) : new_pos;
 
-        /* resume from pos position */
-        snprintf(buf, sizeof(buf), "REST %"PRId64"\r\n", pos);
-        if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)
+    if (fake_pos != s->position) {
+        if ((err = ftp_abort(h)) < 0)
             return err;
-        if (ftp_status(s, NULL, NULL, NULL, NULL, 350) != 350)
-            return AVERROR(EIO);
-
-        s->position = pos;
+        s->position = fake_pos;
     }
     return new_pos;
 }
@@ -573,35 +638,40 @@ static int ftp_read(URLContext *h, unsigned char *buf, int size)
 
     av_dlog(h, "ftp protocol read %d bytes\n", size);
   retry:
+    if (s->state == DISCONNECTED) {
+        if (s->position >= s->filesize)
+            return 0;
+        if ((err = ftp_connect_data_connection(h)) < 0)
+            return err;
+    }
     if (s->state == READY) {
-        ftp_retrieve(s);
+        if (s->position >= s->filesize)
+            return 0;
+        if ((err = ftp_retrieve(s)) < 0)
+            return err;
     }
     if (s->conn_data && s->state == DOWNLOADING) {
         read = ffurl_read(s->conn_data, buf, size);
         if (read >= 0) {
             s->position += read;
             if (s->position >= s->filesize) {
-                ffurl_closep(&s->conn_data);
-                s->state = DISCONNECTED;
-                if (ftp_status(s, NULL, NULL, NULL,NULL, 226) != 226)
+                /* server will terminate, but keep current position to avoid madness */
+                int64_t pos = s->position;
+                if (ftp_abort(h) < 0) {
+                    s->position = pos;
                     return AVERROR(EIO);
+                }
+                s->position = pos;
             }
         }
-        if (!read && s->position < s->filesize && !h->is_streamed) {
+        if (read <= 0 && s->position < s->filesize && !h->is_streamed) {
             /* Server closed connection. Probably due to inactivity */
-            /* TODO: Consider retry before reconnect */
             int64_t pos = s->position;
             av_log(h, AV_LOG_INFO, "Reconnect to FTP server.\n");
-            ffurl_closep(&s->conn_control);
-            ffurl_closep(&s->conn_data);
-            s->position = 0;
-            s->state = DISCONNECTED;
-            if ((err = ftp_connect_control_connection(h)) < 0) {
-                av_log(h, AV_LOG_ERROR, "Reconnect failed\n");
+            if ((err = ftp_abort(h)) < 0)
                 return err;
-            }
             if ((err = ftp_seek(h, pos, SEEK_SET)) < 0) {
-                av_dlog(h, "Seek failed after reconnect\n");
+                av_log(h, AV_LOG_ERROR, "Position cannot be restored.\n");
                 return err;
             }
             if (!retry_done) {
@@ -618,13 +688,19 @@ static int ftp_read(URLContext *h, unsigned char *buf, int size)
 
 static int ftp_write(URLContext *h, const unsigned char *buf, int size)
 {
+    int err;
     FTPContext *s = h->priv_data;
     int written;
 
     av_dlog(h, "ftp protocol write %d bytes\n", size);
 
+    if (s->state == DISCONNECTED) {
+        if ((err = ftp_connect_data_connection(h)) < 0)
+            return err;
+    }
     if (s->state == READY) {
-        ftp_store(s);
+        if ((err = ftp_store(s)) < 0)
+            return err;
     }
     if (s->conn_data && s->state == UPLOADING) {
         written = ffurl_write(s->conn_data, buf, size);
@@ -641,12 +717,9 @@ static int ftp_write(URLContext *h, const unsigned char *buf, int size)
 
 static int ftp_close(URLContext *h)
 {
-    FTPContext *s = h->priv_data;
-
     av_dlog(h, "ftp protocol close\n");
 
-    ffurl_closep(&s->conn_control);
-    ffurl_closep(&s->conn_data);
+    ftp_close_both_connections(h->priv_data);
 
     return 0;
 }