Removed next_command.c.
[uftps.git] / send_file.c
bloba97d636f4fcb230d5beab9cf8d510719d2a28f77
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_sk, (struct sockaddr *) &saddr,
52 &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)
65 reply_c("550 Could not open file.\r\n");
66 goto finish;
69 err = fstat(fd, &st);
70 if (err == -1 || !S_ISREG(st.st_mode))
72 reply_c("550 Could not stat file.\r\n");
73 goto finish;
76 reply_c("150 Sending file content.\r\n");
78 /* Apply a possible previous REST command. Ignore errors, is it allowd
79 * by the RFC? */
80 if (SS.file_offset > 0)
81 lseek(fd, SS.file_offset, SEEK_SET);
83 while (SS.file_offset < st.st_size)
85 debug("Offset step: %lld", SS.file_offset);
87 err = sendfile(SS.data_sk, fd, &SS.file_offset, INT_MAX);
88 if (err == -1)
89 fatal("Could not send file");
92 debug("Offset end: %lld", SS.file_offset);
94 reply_c("226 File content sent.\r\n");
96 finish:
97 close(SS.data_sk);
98 SS.passive_mode = 0;
99 SS.file_offset = 0;
100 SS.data_sk = -1;