Generic RETR implementation added and other stuff too.
[uftps.git] / send_file-sendfile.c
blobc9b14c5d330043c31297ed22a6f0e8995b8e78ea
1 /*
2 * User FTP Server, Share folders over FTP without being root.
3 * Copyright (C) 2008 Isaac Jurado
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU General Public License as published by the Free Software
7 * Foundation; either version 2 of the License, or (at your option) any later
8 * version.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 * details.
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20 #include "uftps.h"
21 #include <sys/stat.h>
22 #include <sys/sendfile.h>
23 #include <unistd.h>
24 #include <fcntl.h>
28 * RETR command implementation. It uses sendfile() because seems quite optimal,
29 * just as vsftpd does.
31 void send_file (void)
33 int fd, e;
34 struct stat s;
36 if (SS.arg == NULL)
38 reply_c("501 Argument required.\r\n");
39 return;
41 expand_arg();
43 e = lstat(SS.arg, &s);
44 if (e == -1 || !S_ISREG(s.st_mode))
46 reply_c("550 Not a file.\r\n");
47 return;
50 fd = open(SS.arg, O_RDONLY, 0);
51 if (fd == -1)
53 reply_c("550 Could not open file.\r\n");
54 return;
57 e = open_data_channel();
58 if (e == -1)
60 close(fd);
61 return;
64 reply_c("150 Sending file content.\r\n");
66 /* Apply a possible previous REST command. Ignore errors, is it allowd
67 * by the RFC? */
68 if (SS.file_offset > 0)
69 lseek(fd, SS.file_offset, SEEK_SET);
71 e = 0;
72 while (SS.file_offset < s.st_size && e != -1)
74 debug("Offset step: %lld", (long long) SS.file_offset);
76 e = sendfile(SS.data_sk, fd, &SS.file_offset, INT_MAX);
77 if (e == -1)
78 error("Sending file");
81 debug("Offset end: %lld", (long long) SS.file_offset);
83 if (e != -1)
84 reply_c("226 File content sent.\r\n");
85 else
86 reply_c("426 Connection closed, transfer aborted.\r\n");
88 close(fd);
89 close(SS.data_sk);
90 SS.data_sk = -1;
91 SS.file_offset = 0;