Renamed session structure.
[uftps.git] / send_file.c
blob436190b013a517e477e8ab07f1877a25f308c0f5
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
19 #include "uftps.h"
22 * RETR command implementation. It uses sendfile() because seems quite optimal,
23 * just as VsFTPd does.
25 * Same restrictions, as in change_dir.c, apply for the argument. See that file
26 * for more details.
28 * Usually, a client sends a PASV command then immediately connects to the port
29 * indicated by the server reply. If we are continuously reusing the same port
30 * for passive data connections, we have to open whether theres is error or not
31 * to shift one position in the connection wait queue.
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/socket.h>
37 #include <sys/sendfile.h>
38 #include <netinet/in.h>
39 #include <unistd.h>
40 #include <fcntl.h>
43 void send_file (void)
45 int fd, err;
46 struct sockaddr_in saddr;
47 struct stat st;
48 socklen_t slen = sizeof(saddr);
50 if (SS.passive_mode)
51 SS.data_sk = accept(SS.passive_bind_sk,
52 (struct sockaddr *) &saddr, &slen);
54 if (SS.arg == NULL)
56 reply_c("501 Argument required.\r\n");
57 goto finish;
60 expand_arg();
61 fd = open(SS.arg, O_RDONLY, 0);
63 if (fd == -1) {
64 reply_c("550 Could not open file.\r\n");
65 goto finish;
68 err = fstat(fd, &st);
69 if (err == -1 || !S_ISREG(st.st_mode)) {
70 reply_c("550 Could not stat file.\r\n");
71 goto finish;
74 reply_c("150 Sending file content.\r\n");
76 /* Apply a possible previous REST command. Ignore errors, is it allowd
77 * by the RFC? */
78 if (SS.offset > 0)
79 (void) lseek(fd, (off_t) SS.offset, SEEK_SET);
81 while (SS.offset < st.st_size) {
82 debug("Offset step: %lld", SS.offset);
84 err = sendfile(SS.data_sk, fd, (off_t *) &SS.offset, INT_MAX);
85 if (err == -1)
86 fatal("Could not send file");
89 debug("Offset end: %lld", SS.offset);
91 reply_c("226 File content sent.\r\n");
93 finish:
94 close(SS.data_sk);
95 SS.passive_mode = 0;
96 SS.offset = 0;
97 SS.data_sk = -1;