1 /* ftpd.c: BetaFTPD main
2 Copyright (C) 1999-2000 Steinar H. Gunderson
4 This program is is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License, version 2 of the
6 License as published by the Free Software Foundation.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 * Special note: this file has been overwritten by another (0-byte) file, been
20 * through the dead, and restored (with the help of dd, grep, gpm, vi and less)
21 * with a sucess rate of 99.9%. Show it a little respect -- don't add junk
40 #include <sys/types.h>
79 #if HAVE_NETINET_IN_SYSTM_H
80 #include <netinet/in_systm.h>
84 #include <netinet/in.h>
88 #include <netinet/ip.h>
91 #if HAVE_NETINET_TCP_H
92 #include <netinet/tcp.h>
96 #include <arpa/inet.h>
100 #include <sys/stat.h>
104 #include <sys/ioctl.h>
107 #if HAVE_LINUX_SOCKET_H
108 #include <linux/socket.h>
112 #include <linux/tcp.h>
116 #include <sys/mman.h>
124 #include <sys/time.h>
128 #include <sys/time.h>
132 #include <sys/filio.h>
147 #if HAVE_SYS_SIGNAL_H
148 #include <sys/signal.h>
152 #include <sys/poll.h>
155 #if HAVE_SYS_SENDFILE_H
156 #include <sys/sendfile.h>
160 * <linux/socket.h> does not export this to glibc2 systems, and it isn't
161 * always defined anywhere else.
163 #if !defined(TCP_CORK) && defined(__linux__)
179 #define MAP_FAILED -1
182 struct conn *first_conn = NULL;
183 struct ftran *first_ftran = NULL;
185 struct dcache *first_dcache = NULL;
189 unsigned int highest_fds = 0;
193 struct pollfd fds[FD_MAX];
195 #define MAXCLIENTS FD_MAX
197 fd_set master_fds, master_send_fds;
198 #define MAXCLIENTS FD_SETSIZE
202 FILE *xferlog = NULL;
205 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
206 int sendfile_supported = 1;
210 * This variable specifies if it's soon time to check for timed out
211 * clients, and timed out directory listing cache entries. It is
212 * set to 1 by a signal handler every minute, and set to 0 when the
213 * checking has been performed.
215 int time_to_check = 1;
219 * snprintf(): snprintf() replacement for systems that miss it. Note
220 * that this implementation does _not_ necessarily protect
221 * against all buffer overflows. Get a real snprintf() in
222 * your C library. That being said, the 8k limit is
223 * substantially larger than any other string in BetaFTPD,
224 * which should make such an attack harder.
226 int snprintf(char *str, size_t n, const char *format, ...)
232 va_start(args, format);
233 err = vsprintf(buf, format, args);
243 #ifndef HAVE_VSNPRINTF
245 * vsnprintf: vsnprintf() replacement for systems that miss it. Please
246 * see snprintf (above) for more information.
248 int vsnprintf(char *str, size_t n, const char *format, va_list ap)
253 err = vsprintf(buf, format, ap);
261 * add_fd(): Add an fd to the set we monitor. Return 0 on success.
262 * This code is shared between poll() and select() versions.
264 int add_fd(const int fd, const int events)
268 printf("add_fd(%d, %x): failed\n", fd, events);
273 fds[fd].events = events;
274 if (highest_fds < fd)
277 if (fd >= FD_SETSIZE)
280 FD_SET(fd, &master_fds);
281 if (events & POLLOUT)
282 FD_SET(fd, &master_send_fds);
288 * del_fd(): Close and remove an fd from the set(s) we monitor. (See also add_fd().)
290 void del_fd(const int fd)
299 /* Reduce poll()'s workload by not making it watch past end of array */
300 while ((highest_fds > 0) && (fds[highest_fds].fd == -1))
303 if (fd >= FD_SETSIZE)
305 FD_CLR(fd, &master_fds);
306 FD_CLR(fd, &master_send_fds);
315 struct conn *c = first_conn;
316 printf("list_clients:\n");
317 while (c && c->next_conn) {
319 printf("list_clients: fd %d\n", c->sock);
325 * add_to_linked_list():
326 * Inserts an element (conn, ftran or dcache) into its linked list.
327 * The list is placed at the beginning, right after the (bogus)
328 * first element of the list.
330 void add_to_linked_list(struct list_element * const first,
331 struct list_element * const elem)
336 elem->next = first->next;
337 if (elem->next) elem->next->prev = elem;
340 /* this is the bogus head of the list */
346 * remove_from_linked_list():
347 * Removes an element (conn, ftran or dcache) from its linked list,
350 void remove_from_linked_list(struct list_element * const elem)
352 if (elem->prev != NULL) elem->prev->next = elem->next;
353 if (elem->next != NULL) elem->next->prev = elem->prev;
359 * Allocates a new control connection (type `struct conn'),
360 * initializes it, and adds it to the linked list. The connection
361 * operates on the socket SOCK.
363 struct conn *alloc_new_conn(const int sock)
365 const unsigned int one = 1;
366 struct conn *c = (struct conn *)(malloc(sizeof(struct conn)));
368 if (c == NULL) return c;
371 ioctl(sock, FIONBIO, &one);
372 if (add_fd(sock, POLLIN) != 0) {
374 send(sock, "230 Server too busy, please try again later.\r\n", 46, 0);
379 add_to_linked_list((struct list_element *)first_conn,
380 (struct list_element *)c);
382 /* this is the bogus head of the list */
389 c->buf_len = c->auth = c->rest_pos = 0;
396 * strcpy(c->curr_dir, "/");
397 * strcpy(c->last_cmd, "");
398 * strcpy(c->rename_from, "")
400 c->curr_dir[0] = '/';
402 c->curr_dir[1] = c->last_cmd[0] = c->rename_from[0] = '\0';
404 c->curr_dir[1] = c->rename_from[0] = '\0';
407 time(&(c->last_transfer));
416 * Allocates a new data connection (type `struct ftran'), and
417 * adds it to the linked list. The connection operates on the
418 * socket SOCK, and has the control connection C as its parent.
420 struct ftran *alloc_new_ftran(const int sock, const struct conn * const c)
422 struct ftran *f = (struct ftran *)(malloc(sizeof(struct ftran)));
424 if (f == NULL) return f;
426 /* this is the bogus head of the list */
427 f->next_ftran = NULL;
428 f->prev_ftran = NULL;
430 add_to_linked_list((struct list_element *)first_ftran,
431 (struct list_element *)f);
437 f->owner = (struct conn * const)c;
452 * Destroy a control connection, remove it from the linked
453 * list, and clean up after it.
455 void destroy_conn(struct conn * const c)
457 if (c == NULL) return;
460 destroy_ftran(c->transfer);
461 remove_from_linked_list((struct list_element *)c);
466 * Destroy a data connection, remove it from the linked list,
467 * and clean up after it.
469 * For some reason, TCP_CORK (Linux 2.2.x-only) doesn't flush
470 * even _after_ the socket is closed, so we zero it just before
471 * closing. We also zero just before sending the last packet,
472 * as it seems to be needed on some systems.
474 * If you wonder why I check for `defined(SOL_TCP)' and don't
475 * provide an alternative, see the comments on init_file_transfer().
477 void destroy_ftran(struct ftran * const f)
479 const unsigned int zero = 0;
481 if (f == NULL) return;
482 #if defined(TCP_CORK) && defined(SOL_TCP)
483 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
489 time(&(f->dir_cache->last_used));
490 f->dir_cache->use_count--;
496 if (f->dir_listing) {
500 munmap(f->file_data, f->size);
506 if (f->local_file != -1) close(f->local_file);
509 if (f->dir_listing) unlink(f->filename);
512 f->owner->transfer = NULL;
515 if (f->dir_cache != NULL) f->dir_cache->use_count--;
518 remove_from_linked_list((struct list_element *)f);
522 * process_all_clients():
523 * Processes all the _control_ connections in active_clients
524 * (normally returned from a select(), there are at max
525 * NUM_AC active connections in the set), sending them
526 * through to the command parser if a command has been
530 int process_all_clients(const int num_ac)
532 int process_all_clients(const fd_set * const active_clients, const int num_ac)
535 struct conn *c = NULL, *next = first_conn->next_conn;
536 int checked_through = 0;
538 /* run through the linked list */
539 while (next != NULL && checked_through < num_ac) {
545 if ((fds[c->sock].revents & (POLLIN|POLLERR|POLLHUP|POLLNVAL)) == 0) {
549 if (!FD_ISSET(c->sock, active_clients)) {
556 bytes_avail = recv(c->sock, c->recv_buf + c->buf_len,
557 255 - c->buf_len, 0);
558 if (bytes_avail <= 0) {
560 * select() has already told us there's something about
561 * this socket, so if we get a return value of zero, the
562 * client has closed the socket. If we get a return value
563 * of -1 (error), we close the socket ourselves.
565 * We do the same for poll(), even though we actually have
566 * bits that tell us what is happening (in case of new
567 * input AND error/hangup at the same time, we do an
568 * explicit check at the bottom of the loop as well).
574 /* overrun = disconnect */
575 if (c->buf_len + bytes_avail > 254) {
576 numeric(c, 503, "Buffer overrun; disconnecting.");
581 c->buf_len += bytes_avail;
584 if (fds[c->sock].revents & (POLLERR|POLLHUP|POLLNVAL)) {
588 return checked_through;
593 * Send a message that the transfer is completed, write xferlog
594 * entry (optional), and update the last_transfer record in the
595 * file transfer object. Goes for both uploads and downloads.
597 void finish_transfer(struct ftran * const f)
599 numeric(f->owner, 226, "Transfer complete.");
600 time(&(f->owner->last_transfer));
603 if (!f->dir_listing) {
610 update_display(first_conn);
615 * process_all_sendfiles():
616 * Sends data to all clients that are ready to receive it.
617 * Also checks for data connections that are newly-connected,
618 * and handler xferlog entries for the files that are finished.
621 int process_all_sendfiles(const int num_ac)
623 int process_all_sendfiles(fd_set * const active_clients, const int num_ac)
626 struct ftran *f = NULL, *next = first_ftran->next_ftran;
627 int checked_through = 0;
628 int tempaddr_len = sizeof(struct sockaddr_in);
630 while (next != NULL && checked_through < num_ac) {
632 next = f->next_ftran;
635 if ((f->upload == 1) && (fds[f->sock].revents & POLLHUP)) {
642 if (fds[f->sock].revents & (POLLERR|POLLNVAL|POLLHUP)) {
648 /* state = 2: incoming PASV, state >3: send file */
650 if ((f->state < 2) || (f->state == 3) || (fds[f->sock].revents & (POLLIN|POLLOUT)) == 0) {
652 if ((f->state < 2) || (f->state == 3) || !FD_ISSET(f->sock, active_clients)) {
660 /* Nothing is needed for the poll() version? */
662 FD_CLR(f->sock, active_clients);
665 if (f->state == 2) { /* incoming PASV */
666 const unsigned int one = 1;
667 const int tempsock = accept(f->sock, &(f->sin), &tempaddr_len);
671 if (tempsock == -1) {
677 ioctl(f->sock, FIONBIO, &one);
678 init_file_transfer(f);
680 if (f->upload) continue;
684 init_file_transfer(f);
686 if (f->upload) continue;
690 /* for download, we send the first packets right away */
693 if (do_upload(f)) continue;
696 if (do_download(f)) continue;
698 /* do_{upload,download} returned 0, the transfer is complete */
701 update_display(first_conn);
705 return checked_through;
709 int do_upload(struct ftran *f)
711 char upload_buf[16384];
714 /* keep buffer size small in ascii transfers
715 to prevent process stalling while filtering
716 data on slower computers */
719 * This isn't a big problem, since we won't get
720 * packets this big anyway, the biggest I've seen
721 * was 12kB on 100mbit (but that was from a Windows
722 * machine), so I've reduced the buffer from 64 kB
723 * to 16 kB :-) --Steinar
725 const int maxlen = (f->ascii_mode == 1) ? 4096 : 16384;
727 const int maxlen = 16384;
731 size = recv(f->sock, upload_buf, maxlen, 0);
736 if (size > 0 && f->ascii_mode == 1) {
737 size = ascii_uploadfilter(upload_buf, size);
740 if (size > 0 && (write(f->local_file, upload_buf, size) == size)) {
742 } else if (size == -1) {
743 /* don't write xferlog... or? */
744 numeric(f->owner, 426, strerror(errno));
752 int do_download(struct ftran *f)
754 #if defined(TCP_CORK) && defined(SOL_TCP)
755 unsigned int zero = 0;
759 int more_to_send = 0;
762 char buf[MAX_BLOCK_SIZE];
765 char buf2[MAX_BLOCK_SIZE * 2];
769 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
771 * We handle the optimal case first, which is sendfile().
772 * Here we use a rather simplified sending `algorithm',
773 * leaving most of the quirks to the system calls.
775 if (sendfile_supported == 1 && f->dir_listing == 0) {
777 size = f->size - f->pos;
779 if (size > f->block_size) size = f->block_size;
780 if (size < 0) size = 0;
783 if (size != f->block_size) {
784 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
788 err = mysendfile(f->sock, f->local_file, &f->pos, size);
789 return (f->pos < f->size) && (err > -1);
794 size = f->size - f->pos;
796 if (size > f->block_size) size = f->block_size;
797 if (size < 0) size = 0;
799 bytes_to_send = size;
800 sendfrom_buf = f->file_data + f->pos;
802 bytes_to_send = read(f->local_file, buf, f->block_size);
806 if (bytes_to_send == f->block_size) more_to_send = 1;
809 if (f->ascii_mode == 1) {
810 bytes_to_send = ascii_downloadfilter(sendfrom_buf,
811 buf2, bytes_to_send);
814 #endif /* WANT_ASCII */
816 #if defined(TCP_CORK) && defined(SOL_TCP)
817 /* if we believe this is the last packet, unset TCP_CORK */
818 if (more_to_send == 0) {
819 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
823 size = send(f->sock, sendfrom_buf, bytes_to_send, 0);
824 if (size < bytes_to_send) more_to_send = 1;
827 if (f->ascii_mode == 1 && size < bytes_to_send && size > 0) {
828 size = ascii_findlength(sendfrom_buf, size);
833 if (size > 0) f->pos += size;
840 void write_xferlog(struct ftran *f)
843 time_t now = time(NULL);
844 struct tm *t = localtime(&now);
846 if (xferlog == NULL) return;
848 strftime(temp, 256, "%a %b %d %H:%M:%S %Y", t);
850 fprintf(xferlog, "%s %u %s %lu %s b _ %c %c %s ftp 0 *\n",
852 fprintf(xferlog, "%s %u %s %lu %s b _ o %c %s ftp 0 *\n",
854 temp, (int)(difftime(now, f->tran_start)),
855 inet_ntoa(f->sin.sin_addr), f->size,
858 (f->upload) ? 'i' : 'o',
860 (f->owner->auth == 4) ? 'r' : 'a', f->owner->username);
864 /* vim needs this to work properly :-( */
871 /* Reallocate the buggers constantly */
874 struct conn *c = first_conn;
875 int maxloops = MAXCLIENTS;
877 while (c && c->next_conn) {
878 struct conn *temp = malloc(sizeof(*temp));
880 *temp = *(c->next_conn);
881 if (temp->transfer) temp->transfer->owner = temp;
882 memset(c->next_conn, 0, sizeof(struct conn));
888 assert(maxloops > 0);
894 * main(): Main function. Does the initialization, and contains
895 * the main server loop. Takes no command-line arguments
896 * (see README for justification).
903 /* the sets are declared globally if we use poll() */
905 fd_set fds, fds_send;
908 /*setlinebuf(stdout);*/
909 setvbuf(stdout, (char *)NULL, _IOLBF, 0);
911 signal(SIGPIPE, SIG_IGN);
913 printf("BetaFTPD version %s, Copyright (C) 1999-2000 Steinar H. Gunderson\n", VERSION);
914 puts("BetaFTPD comes with ABSOLUTELY NO WARRANTY; for details see the file");
915 puts("COPYING. This is free software, and you are welcome to redistribute it");
916 puts("under certain conditions; again see the file COPYING for details.");
919 /* we don't need stdin */
925 for (i = 0; i < FD_MAX; i++) {
931 FD_ZERO(&master_fds);
932 FD_ZERO(&master_send_fds);
935 server_sock = create_server_socket();
938 printf("%cc", (char)27); /* reset and clear the screen */
941 /* init dummy first connection */
942 first_conn = alloc_new_conn(-1);
943 first_ftran = alloc_new_ftran(0, NULL);
945 first_dcache = alloc_new_dcache();
950 #warning No xferlog support for nonroot yet
953 xferlog = fopen("/var/log/xferlog", "a");
954 if (xferlog == NULL) xferlog = fopen("/usr/adm/xferlog", "a");
956 if (xferlog != NULL) {
957 fseek(xferlog, 0L, SEEK_END);
966 puts("fork() failed, exiting");
971 puts("BetaFTPD forked into the background");
975 puts("BetaFTPD active");
978 /* set timeout alarm here (after the fork) */
980 signal(SIGALRM, handle_alarm);
982 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
983 /* check that sendfile() is really implemented (same check as configure does) */
985 int out_fd = 1, in_fd = 0;
990 mysendfile(out_fd, in_fd, &offset, size);
991 if (errno == ENOSYS) sendfile_supported = 0;
998 struct timeval timeout;
1001 /*screw_clients(); //look for memory errors */
1004 update_display(first_conn);
1008 i = poll(fds, highest_fds + 1, 60000);
1012 for (j=0; j<=highest_fds; j++) {
1013 if (fds[j].revents) printf("fds[%d].fd %d, .revents %x\n", j, fds[j].fd, fds[j].revents);
1018 /* reset fds (gets changed by select()) */
1020 fds_send = master_send_fds;
1023 * wait up to 60 secs for any activity
1025 timeout.tv_sec = 60;
1026 timeout.tv_usec = 0;
1028 i = select(FD_SETSIZE, &fds, &fds_send, NULL, &timeout);
1032 if (errno == EBADF) {
1034 /* don't like this, but we have to */
1035 clear_bad_fds(&server_sock);
1037 } else if (errno != EINTR) {
1048 /* fix an invalid server socket */
1049 if (fds[server_sock].revents & POLLERR) {
1050 del_fd(server_sock);
1051 server_sock = create_server_socket();
1055 /* remove any timed out sockets */
1056 if (time_to_check) {
1064 if (i <= 0) continue;
1067 i -= process_all_sendfiles(i);
1068 process_all_clients(i);
1070 /* sends are given highest `priority' */
1071 i -= process_all_sendfiles(&fds_send, i);
1073 /* incoming PASV connections and uploads */
1074 i -= process_all_sendfiles(&fds, i);
1077 * check the incoming PASV connections first, so
1078 * process_all_clients() won't be confused.
1080 process_all_clients(&fds, i);
1084 if (fds[server_sock].revents & POLLIN) {
1086 if (FD_ISSET(server_sock, &fds)) {
1088 accept_new_client(&server_sock);
1095 * accept_new_client():
1096 * Open a socket for the new client, say hello and put it in
1099 void accept_new_client(int * const server_sock)
1101 struct sockaddr_in tempaddr;
1102 int tempaddr_len = sizeof(tempaddr);
1103 const int tempsock = accept(*server_sock, (struct sockaddr *)&tempaddr, &tempaddr_len);
1105 static int num_err = 0;
1112 if ((errno == EBADF || errno == EPIPE) && ++num_err >= 3) {
1113 del_fd(*server_sock);
1114 *server_sock = create_server_socket();
1117 struct conn * const c = alloc_new_conn(tempsock);
1120 numeric(c, 220, "BetaFTPD " VERSION " ready.");
1122 memcpy(&(c->addr), &tempaddr, sizeof(struct sockaddr));
1129 * time_out_sockets():
1130 * Times out any socket that has not had any transfer
1131 * in the last 15 minutes (delay not customizable by FTP
1132 * user -- you must change it in ftpd.h).
1134 * Note that RFC959 explicitly states that there are no
1135 * `spontaneous' error replies, yet we have to do it to
1136 * get the message through at all.
1138 * If we check this list for every accept() call, it's
1139 * actually eating a lot of CPU time, so we only check
1140 * it every minute. We used to do a time() call here,
1141 * but we've changed to do use an alarm() call and set
1142 * the time_to_check_flag in the SIGALRM handler.
1144 RETSIGTYPE handle_alarm(int signum)
1150 signal(SIGALRM, handle_alarm);
1153 void time_out_sockets()
1155 struct conn *c = NULL, *next = first_conn->next_conn;
1156 time_t now = time(NULL);
1158 /* run through the linked list */
1159 while (next != NULL) {
1161 next = c->next_conn;
1163 if ((c->transfer == NULL || c->transfer->state != 5) &&
1164 (now - c->last_transfer > TIMEOUT_SECS)) {
1165 /* RFC violation? */
1166 numeric(c, 421, "Timeout (%u minutes): Closing control connection.", TIMEOUT_SECS/60);
1174 * Remove some bytes from the incoming buffer. This gives
1175 * room for new data on the control connection, and should
1176 * be called when the code has finished using the data.
1177 * (This is done automatically for all commands, so you
1178 * normally need not worry about it.)
1180 void remove_bytes(struct conn * const c, const int num)
1182 if (c->buf_len <= num) {
1186 memmove(c->recv_buf, c->recv_buf + num, c->buf_len);
1191 * numeric(): Sends a numeric FTP reply to the client. Note that
1192 * you can use this command much the same way as you
1193 * would use a printf() (with all the normal %s, %d,
1194 * etc.), since it actually uses printf() internally.
1196 void numeric(struct conn * const c, const int numeric, const char * const format, ...)
1198 char buf[256], fmt[256];
1202 snprintf(fmt, 256, "%03u %s\r\n", numeric, format);
1204 va_start(args, format);
1205 i = vsnprintf(buf, 256, fmt, args);
1208 err = send(c->sock, buf, i, 0);
1209 if (err == -1 && errno == EPIPE) {
1215 * init_file_transfer():
1216 * Initiate a data connection for sending. This does not open
1217 * any files etc., just does whatever is needed for the socket,
1218 * if needed. It does, however, send the 150 reply to the client,
1219 * and mmap()s if needed.
1221 * Linux systems (others?) define SOL_TCP right away, which saves us
1222 * some grief and code size. Perhaps using getprotoent() is the `right'
1223 * way, but it's bigger :-) (Optionally, we could figure it out at
1224 * configure time, of course...)
1226 * For optimal speed, we use the Linux 2.2.x-only TCP_CORK flag if
1227 * possible. Note that this is only defined in the first `arm' --
1228 * we silently assume that Linux is the only OS supporting this
1229 * flag. This might be an over-generalization, but I it looks like
1230 * we'll have to depend on it other places as well, so we might
1231 * just as well be evil here.
1233 void init_file_transfer(struct ftran * const f)
1236 struct conn * const c = f->owner;
1237 const int mode = IPTOS_THROUGHPUT, zero = 0, one = 1;
1242 /* we want max throughput */
1243 setsockopt(f->sock, SOL_IP, IP_TOS, (void *)&mode, sizeof(mode));
1244 setsockopt(f->sock, SOL_TCP, TCP_NODELAY, (void *)&zero, sizeof(zero));
1246 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&one, sizeof(one));
1249 /* should these pointers be freed afterwards? */
1251 getprotoent(); /* legal? */
1253 const struct protoent * const pe_ip = getprotobyname("ip");
1254 const struct protoent * const pe_tcp = getprotobyname("tcp");
1255 setsockopt(f->sock, pe_ip->p_proto, IP_TOS, (void *)&mode, sizeof(mode));
1256 setsockopt(f->sock, pe_tcp->p_proto, TCP_NODELAY, (void *)&zero, sizeof(zero));
1262 if (f->dir_listing) {
1263 f->block_size = MAX_BLOCK_SIZE;
1266 f->ascii_mode = f->owner->ascii_mode;
1269 /* find the preferred block size */
1270 f->block_size = MAX_BLOCK_SIZE;
1271 if (fstat(f->local_file, &buf) != -1 &&
1272 buf.st_blksize < MAX_BLOCK_SIZE) {
1273 f->block_size = buf.st_blksize;
1284 #endif /* WANT_UPLOAD */
1286 TRAP_ERROR(add_fd(f->sock, events), 500, return);
1290 setsockopt(f->sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
1292 #if !HAVE_POLL && WANT_UPLOAD
1294 * if we let an upload socket stay in master_send_fds, we would
1295 * get data that would fool us into closing the socket... (sigh)
1298 FD_CLR(f->sock, &master_send_fds);
1299 FD_SET(f->sock, &master_fds);
1303 time(&(f->owner->last_transfer));
1305 if (f->dir_listing) {
1307 numeric(f->owner, 150, "Opening ASCII mode data connection for directory listing.");
1310 * slightly kludged -- perhaps we should kill the second arm,
1311 * at the expense of code size? Or perhaps we could collapse
1312 * the two possible replies into one?
1318 #endif /* WANT_UPLOAD */
1320 numeric(f->owner, 150, "Opening %s mode data connection for '%s'",
1321 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename);
1323 numeric(f->owner, 150, "Opening %s mode data connection for '%s' (%u bytes)",
1324 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename,
1327 #else /* !WANT_ASCII */
1330 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s'", f->filename);
1332 #endif /* WANT_UPLOAD */
1333 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s' (%u bytes)", f->filename, f->size);
1334 #endif /* !WANT_ASCII */
1338 * This section _could_ in theory be more optimized, but it's
1339 * much easier this way, and hopefully, the compiler will be
1340 * intelligent enough to optimize most of this away. The idea
1341 * is, some modes _require_ use of mmap (or not). The preferred
1342 * thing is using mmap() when we don't have sendfile(), and not
1343 * using mmap() when we have sendfile().
1346 if (f->dir_listing == 0) {
1347 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
1348 int do_mmap = (sendfile_supported) ? 0 : 1;
1353 if (f->ascii_mode == 1) do_mmap = 1;
1356 if (f->upload == 1) do_mmap = 0;
1360 f->file_data = mmap(NULL, f->size, PROT_READ, MAP_SHARED, f->local_file, 0);
1361 if (f->file_data == MAP_FAILED) f->file_data = NULL;
1363 f->file_data = NULL;
1365 f->pos = f->owner->rest_pos;
1367 #else /* !HAVE_MMAP */
1368 lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1373 * create_server_socket():
1374 * Create and bind a server socket, that we can use to
1375 * listen to new clients on.
1377 int create_server_socket()
1379 int server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1380 const unsigned int one = 1;
1381 struct sockaddr_in addr;
1385 * In the `perfect' world, if an address was in use, we could
1386 * just wait for the kernel to clear everything up, and everybody
1387 * would be happy. But when you just found out your server socket
1388 * was invalid, it has to be `re-made', and 3000 users are trying
1389 * to access your fileserver, I think it's nice that it comes
1390 * up right away... hence this option.
1392 setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1393 ioctl(server_sock, FIONBIO, &one); /* just in case */
1395 addr.sin_family = AF_INET;
1396 addr.sin_addr.s_addr = INADDR_ANY;
1397 addr.sin_port = htons(FTP_PORT);
1400 err = bind(server_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
1405 /* try to recover from recoverable errors... */
1406 if (errno == ENOMEM || errno == EADDRINUSE) {
1407 puts("Waiting 1 sec before trying again...");
1414 } while (err == -1);
1416 listen(server_sock, 20);
1418 err = add_fd(server_sock, POLLIN);
1430 * Try to find invalid socket descriptors, and clean them.
1431 * The methods used are rather UGLY, but I can't think of
1432 * any good way of checking e.g. server_sock without
1433 * doing anything to it :-(
1435 * poll() is able to do this in a much cleaner way, which
1436 * we use if we use poll(). That checking isn't done here,
1439 void clear_bad_fds(int * const server_sock)
1443 struct timeval tv = { 0, 0 };
1446 FD_SET(*server_sock, &fds);
1447 if (select(*server_sock, &fds, NULL, NULL, &tv) == -1) {
1448 FD_CLR(*server_sock, &master_fds);
1449 close(*server_sock);
1450 *server_sock = create_server_socket();
1454 /* could do this (conn, ftran) in any order */
1456 struct conn *c = NULL, *next = first_conn->next_conn;
1458 /* run through the linked list */
1459 while (next != NULL) {
1463 next = c->next_conn;
1465 if (read(c->sock, &buf, 0) == -1 &&
1473 struct ftran *f = NULL, *next = first_ftran->next_ftran;
1475 while (next != NULL) {
1479 next = f->next_ftran;
1481 if (read(f->sock, &buf, 0) == -1 &&
1490 #if HAVE_BSD_SENDFILE || HAVE_LINUX_SENDFILE
1491 int mysendfile(int sock, int fd, off_t *offset, size_t count)
1493 #if HAVE_BSD_SENDFILE
1497 err = sendfile(fd, sock, *offset, count, NULL, &ssize, 0);
1498 if (ssize > 0) *offset += ssize;
1499 #else /* !HAVE_BSD_SENDFILE */
1500 #if HAVE_LINUX_SENDFILE
1501 return sendfile(sock, fd, offset, count);
1502 #endif /* HAVE_LINUX_SENDFILE */
1503 #endif /* !HAVE_BSD_SENDFILE */
1505 #endif /* HAVE_BSD_SENDFILE || HAVE_LINUX_SENDFILE */
1510 * dump_file(): Dumps a file on the control connection. Used for
1511 * welcome messages and the likes. Note that outbuf
1512 * is so big, to prevent any crashing from users creating
1513 * weird .message files (like 1024 LFs)... The size of
1514 * the file is limited to 1024 bytes (by truncation).
1516 void dump_file(struct conn * const c, const int num, const char * const filename)
1518 char buf[1024], outbuf[5121];
1519 char *ptr = outbuf + 4;
1522 const int dumpfile = open(filename, O_RDONLY);
1523 if (dumpfile == -1) return;
1525 i = read(dumpfile, buf, 1024);
1531 sprintf(outbuf, "%03u-", num);
1534 if (buf[j] == '\n') {
1535 sprintf(ptr, "%03u-", num);
1541 send(c->sock, outbuf, ptr - outbuf, 0);
1548 * Lists all README file in the current (ie. OS current)
1549 * directory, in a 250- message.
1551 void list_readmes(struct conn * const c)
1554 const time_t now = time(NULL);
1557 if (glob("README*", 0, NULL, &pglob) != 0) return;
1559 for (i = 0; i < pglob.gl_pathc; i++) {
1564 if (stat(pglob.gl_pathv[i], &buf) == -1) continue;
1566 /* remove trailing LF */
1567 tm = ctime(&buf.st_mtime);
1568 tm[strlen(tm) - 1] = 0;
1570 snprintf(str, 256, "250-Please read the file %s\r\n"
1571 "250-\tIt was last modified %s - %ld days ago\r\n",
1572 pglob.gl_pathv[i], tm,
1573 (now - buf.st_mtime) / 86400);
1574 send(c->sock, str, strlen(str), 0);