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;
187 char message_buf[512];
190 unsigned int highest_fds = 0;
194 struct pollfd fds[FD_MAX];
196 #define MAXCLIENTS FD_MAX
198 fd_set master_fds, master_send_fds;
199 #define MAXCLIENTS FD_SETSIZE
203 FILE *xferlog = NULL;
206 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
207 int sendfile_supported = 1;
211 * This variable specifies if it's soon time to check for timed out
212 * clients, and timed out directory listing cache entries. It is
213 * set to 1 by a signal handler every minute, and set to 0 when the
214 * checking has been performed.
216 int time_to_check = 1;
220 * snprintf(): snprintf() replacement for systems that miss it. Note
221 * that this implementation does _not_ necessarily protect
222 * against all buffer overflows. Get a real snprintf() in
223 * your C library. That being said, the 8k limit is
224 * substantially larger than any other string in BetaFTPD,
225 * which should make such an attack harder.
227 int snprintf(char *str, size_t n, const char *format, ...)
233 va_start(args, format);
234 err = vsprintf(buf, format, args);
244 #ifndef HAVE_VSNPRINTF
246 * vsnprintf: vsnprintf() replacement for systems that miss it. Please
247 * see snprintf (above) for more information.
249 int vsnprintf(char *str, size_t n, const char *format, va_list ap)
254 err = vsprintf(buf, format, ap);
262 * add_fd(): Add an fd to the set we monitor. Return 0 on success.
263 * This code is shared between poll() and select() versions.
265 int add_fd(const int fd, const int events)
269 printf("add_fd(%d, %x): failed\n", fd, events);
274 fds[fd].events = events;
275 if (highest_fds < fd)
278 if (fd >= FD_SETSIZE)
281 FD_SET(fd, &master_fds);
282 if (events & POLLOUT)
283 FD_SET(fd, &master_send_fds);
289 * del_fd(): Close and remove an fd from the set(s) we monitor. (See also add_fd().)
291 void del_fd(const int fd)
300 /* Reduce poll()'s workload by not making it watch past end of array */
301 while ((highest_fds > 0) && (fds[highest_fds].fd == -1))
304 if (fd >= FD_SETSIZE)
306 FD_CLR(fd, &master_fds);
307 FD_CLR(fd, &master_send_fds);
316 struct conn *c = first_conn;
317 printf("list_clients:\n");
318 while (c && c->next_conn) {
320 printf("list_clients: fd %d\n", c->sock);
326 * add_to_linked_list():
327 * Inserts an element (conn, ftran or dcache) into its linked list.
328 * The list is placed at the beginning, right after the (bogus)
329 * first element of the list.
331 void add_to_linked_list(struct list_element * const first,
332 struct list_element * const elem)
337 elem->next = first->next;
338 if (elem->next) elem->next->prev = elem;
341 /* this is the bogus head of the list */
347 * remove_from_linked_list():
348 * Removes an element (conn, ftran or dcache) from its linked list,
351 void remove_from_linked_list(struct list_element * const elem)
353 if (elem->prev != NULL) elem->prev->next = elem->next;
354 if (elem->next != NULL) elem->next->prev = elem->prev;
360 * Allocates a new control connection (type `struct conn'),
361 * initializes it, and adds it to the linked list. The connection
362 * operates on the socket SOCK.
364 struct conn *alloc_new_conn(const int sock)
366 const unsigned int one = 1;
367 struct conn *c = (struct conn *)(malloc(sizeof(struct conn)));
369 if (c == NULL) return NULL;
372 ioctl(sock, FIONBIO, &one);
373 if (add_fd(sock, POLLIN) != 0) {
375 send(sock, "230 Server too busy, please try again later.\r\n", 46, 0);
380 add_to_linked_list((struct list_element *)first_conn,
381 (struct list_element *)c);
383 /* this is the bogus head of the list */
390 c->buf_len = c->auth = c->rest_pos = 0;
398 * strcpy(c->curr_dir, "/");
399 * strcpy(c->last_cmd, "");
400 * strcpy(c->rename_from, "")
402 c->curr_dir[0] = '/';
404 c->curr_dir[1] = c->last_cmd[0] = c->rename_from[0] = '\0';
406 c->curr_dir[1] = c->rename_from[0] = '\0';
409 time(&(c->last_transfer));
411 /* list_clients(); */
418 * Allocates a new data connection (type `struct ftran'), and
419 * adds it to the linked list. The connection operates on the
420 * socket SOCK, and has the control connection C as its parent.
422 struct ftran *alloc_new_ftran(const int sock, const struct conn * const c)
424 struct ftran *f = (struct ftran *)(malloc(sizeof(struct ftran)));
426 if (f == NULL) return f;
428 /* this is the bogus head of the list */
429 f->next_ftran = NULL;
430 f->prev_ftran = NULL;
432 add_to_linked_list((struct list_element *)first_ftran,
433 (struct list_element *)f);
439 f->owner = (struct conn * const)c;
454 * Destroy a control connection, remove it from the linked
455 * list, and clean up after it.
457 void destroy_conn(struct conn * const c)
459 if (c == NULL) return;
462 destroy_ftran(c->transfer);
463 remove_from_linked_list((struct list_element *)c);
468 * Destroy a data connection, remove it from the linked list,
469 * and clean up after it.
471 * For some reason, TCP_CORK (Linux 2.2.x-only) doesn't flush
472 * even _after_ the socket is closed, so we zero it just before
473 * closing. We also zero just before sending the last packet,
474 * as it seems to be needed on some systems.
476 * If you wonder why I check for `defined(SOL_TCP)' and don't
477 * provide an alternative, see the comments on init_file_transfer().
479 void destroy_ftran(struct ftran * const f)
481 const unsigned int zero = 0;
483 if (f == NULL) return;
484 #if defined(TCP_CORK) && defined(SOL_TCP)
485 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
491 time(&(f->dir_cache->last_used));
492 f->dir_cache->use_count--;
498 if (f->dir_listing) {
502 munmap(f->file_data, f->size);
508 if (f->local_file != -1) close(f->local_file);
511 if (f->dir_listing) unlink(f->filename);
514 f->owner->transfer = NULL;
517 if (f->dir_cache != NULL) f->dir_cache->use_count--;
520 remove_from_linked_list((struct list_element *)f);
524 * process_all_clients():
525 * Processes all the _control_ connections in active_clients
526 * (normally returned from a select(), there are at max
527 * NUM_AC active connections in the set), sending them
528 * through to the command parser if a command has been
532 int process_all_clients(const int num_ac)
534 int process_all_clients(const fd_set * const active_clients, const int num_ac)
537 struct conn *c = NULL, *next = first_conn->next_conn;
538 int checked_through = 0;
540 /* run through the linked list */
541 while (next != NULL && checked_through < num_ac) {
547 if ((fds[c->sock].revents & (POLLIN|POLLERR|POLLHUP|POLLNVAL)) == 0) {
551 if (!FD_ISSET(c->sock, active_clients)) {
558 bytes_avail = recv(c->sock, c->recv_buf + c->buf_len,
559 255 - c->buf_len, 0);
560 if (bytes_avail <= 0) {
562 * select() has already told us there's something about
563 * this socket, so if we get a return value of zero, the
564 * client has closed the socket. If we get a return value
565 * of -1 (error), we close the socket ourselves.
567 * We do the same for poll(), even though we actually have
568 * bits that tell us what is happening (in case of new
569 * input AND error/hangup at the same time, we do an
570 * explicit check at the bottom of the loop as well).
576 /* overrun = disconnect */
577 if (c->buf_len + bytes_avail > 254) {
578 numeric(c, 503, "Buffer overrun; disconnecting.");
583 c->buf_len += bytes_avail;
586 if (fds[c->sock].revents & (POLLERR|POLLHUP|POLLNVAL)) {
590 return checked_through;
595 * Send a message that the transfer is completed, write xferlog
596 * entry (optional), and update the last_transfer record in the
597 * file transfer object. Goes for both uploads and downloads.
599 void finish_transfer(struct ftran * const f)
601 char finished[] = "226 Transfer complete.\r\n";
602 if (send(f->owner->sock, finished, sizeof(finished), 0) == -1 && errno == EPIPE) {
603 destroy_conn(f->owner);
607 time(&(f->owner->last_transfer));
610 if (!f->dir_listing) {
617 update_display(first_conn);
622 * process_all_sendfiles():
623 * Sends data to all clients that are ready to receive it.
624 * Also checks for data connections that are newly-connected,
625 * and handler xferlog entries for the files that are finished.
628 int process_all_sendfiles(const int num_ac)
630 int process_all_sendfiles(fd_set * const active_clients, const int num_ac)
633 struct ftran *f = NULL, *next = first_ftran->next_ftran;
634 int checked_through = 0;
635 int tempaddr_len = sizeof(struct sockaddr_in);
637 while (next != NULL && checked_through < num_ac) {
639 next = f->next_ftran;
642 if ((f->upload == 1) && (fds[f->sock].revents & POLLHUP)) {
649 if (fds[f->sock].revents & (POLLERR|POLLNVAL|POLLHUP)) {
655 /* state = 2: incoming PASV, state >3: send file */
657 if ((f->state < 2) || (f->state == 3) || (fds[f->sock].revents & (POLLIN|POLLOUT)) == 0) {
659 if ((f->state < 2) || (f->state == 3) || !FD_ISSET(f->sock, active_clients)) {
667 /* Nothing is needed for the poll() version? */
669 FD_CLR(f->sock, active_clients);
672 if (f->state == 2) { /* incoming PASV */
673 const unsigned int one = 1;
674 const int tempsock = accept(f->sock, &(f->sin), &tempaddr_len);
678 if (tempsock == -1) {
684 ioctl(f->sock, FIONBIO, &one);
685 init_file_transfer(f);
687 if (f->upload) continue;
691 init_file_transfer(f);
693 if (f->upload) continue;
697 /* for download, we send the first packets right away */
700 if (do_upload(f)) continue;
703 if (do_download(f)) continue;
705 /* do_{upload,download} returned 0, the transfer is complete */
708 update_display(first_conn);
712 return checked_through;
716 int do_upload(struct ftran *f)
718 char upload_buf[16384];
721 /* keep buffer size small in ascii transfers
722 to prevent process stalling while filtering
723 data on slower computers */
726 * This isn't a big problem, since we won't get
727 * packets this big anyway, the biggest I've seen
728 * was 12kB on 100mbit (but that was from a Windows
729 * machine), so I've reduced the buffer from 64 kB
730 * to 16 kB :-) --Steinar
732 const int maxlen = (f->ascii_mode == 1) ? 4096 : 16384;
734 const int maxlen = 16384;
738 size = recv(f->sock, upload_buf, maxlen, 0);
743 if (size > 0 && f->ascii_mode == 1) {
744 size = ascii_uploadfilter(upload_buf, size);
747 if (size > 0 && (write(f->local_file, upload_buf, size) == size)) {
749 } else if (size == -1) {
750 /* don't write xferlog... or? */
751 numeric(f->owner, 426, strerror(errno));
759 int do_download(struct ftran *f)
761 #if defined(TCP_CORK) && defined(SOL_TCP)
762 unsigned int zero = 0;
766 int more_to_send = 0;
769 char buf[MAX_BLOCK_SIZE];
772 char buf2[MAX_BLOCK_SIZE * 2];
776 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
778 * We handle the optimal case first, which is sendfile().
779 * Here we use a rather simplified sending `algorithm',
780 * leaving most of the quirks to the system calls.
782 if (sendfile_supported == 1 && f->dir_listing == 0) {
784 size = f->size - f->pos;
786 if (size > f->block_size) size = f->block_size;
787 if (size < 0) size = 0;
790 if (size != f->block_size) {
791 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
795 err = mysendfile(f->sock, f->local_file, &f->pos, size);
796 return (f->pos < f->size) && (err > -1);
801 size = f->size - f->pos;
803 if (size > f->block_size) size = f->block_size;
804 if (size < 0) size = 0;
806 bytes_to_send = size;
807 sendfrom_buf = f->file_data + f->pos;
809 bytes_to_send = read(f->local_file, buf, f->block_size);
813 if (bytes_to_send == f->block_size) more_to_send = 1;
816 if (f->ascii_mode == 1) {
817 bytes_to_send = ascii_downloadfilter(sendfrom_buf,
818 buf2, bytes_to_send);
821 #endif /* WANT_ASCII */
823 #if defined(TCP_CORK) && defined(SOL_TCP)
824 /* if we believe this is the last packet, unset TCP_CORK */
825 if (more_to_send == 0) {
826 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
830 size = send(f->sock, sendfrom_buf, bytes_to_send, 0);
831 if (size < bytes_to_send) more_to_send = 1;
834 if (f->ascii_mode == 1 && size < bytes_to_send && size > 0) {
835 size = ascii_findlength(sendfrom_buf, size);
840 if (size > 0) f->pos += size;
847 void write_xferlog(struct ftran *f)
850 time_t now = time(NULL);
851 struct tm *t = localtime(&now);
853 if (xferlog == NULL) return;
855 strftime(temp, 256, "%a %b %d %H:%M:%S %Y", t);
857 fprintf(xferlog, "%s %u %s %lu %s b _ %c %c %s ftp 0 *\n",
859 fprintf(xferlog, "%s %u %s %lu %s b _ o %c %s ftp 0 *\n",
861 temp, (int)(difftime(now, f->tran_start)),
862 inet_ntoa(f->sin.sin_addr), f->size,
865 (f->upload) ? 'i' : 'o',
867 (f->owner->auth == 4) ? 'r' : 'a', f->owner->username);
871 /* vim needs this to work properly :-( */
878 /* Reallocate the buggers constantly */
881 struct conn *c = first_conn;
882 int maxloops = MAXCLIENTS;
884 while (c && c->next_conn) {
885 struct conn *temp = malloc(sizeof(*temp));
887 *temp = *(c->next_conn);
888 if (temp->transfer) temp->transfer->owner = temp;
889 memset(c->next_conn, 0, sizeof(struct conn));
895 assert(maxloops > 0);
901 * main(): Main function. Does the initialization, and contains
902 * the main server loop. Takes no command-line arguments
903 * (see README for justification).
910 /* the sets are declared globally if we use poll() */
912 fd_set fds, fds_send;
915 /*setlinebuf(stdout);*/
916 setvbuf(stdout, (char *)NULL, _IOLBF, 0);
918 signal(SIGPIPE, SIG_IGN);
920 printf("BetaFTPD version %s, Copyright (C) 1999-2000 Steinar H. Gunderson\n", VERSION);
921 puts("BetaFTPD comes with ABSOLUTELY NO WARRANTY; for details see the file");
922 puts("COPYING. This is free software, and you are welcome to redistribute it");
923 puts("under certain conditions; again see the file COPYING for details.");
926 /* we don't need stdin */
932 for (i = 0; i < FD_MAX; i++) {
938 FD_ZERO(&master_fds);
939 FD_ZERO(&master_send_fds);
942 server_sock = create_server_socket();
945 printf("%cc", (char)27); /* reset and clear the screen */
948 /* init dummy first connection */
949 first_conn = alloc_new_conn(-1);
950 first_ftran = alloc_new_ftran(0, NULL);
952 first_dcache = alloc_new_dcache();
957 #warning No xferlog support for nonroot yet
960 xferlog = fopen("/var/log/xferlog", "a");
961 if (xferlog == NULL) xferlog = fopen("/usr/adm/xferlog", "a");
963 if (xferlog != NULL) {
964 fseek(xferlog, 0L, SEEK_END);
973 puts("fork() failed, exiting");
978 puts("BetaFTPD forked into the background");
982 puts("BetaFTPD active");
985 /* set timeout alarm here (after the fork) */
987 signal(SIGALRM, handle_alarm);
989 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
990 /* check that sendfile() is really implemented (same check as configure does) */
992 int out_fd = 1, in_fd = 0;
997 mysendfile(out_fd, in_fd, &offset, size);
998 if (errno == ENOSYS) sendfile_supported = 0;
1005 struct timeval timeout;
1008 /*screw_clients(); //look for memory errors */
1011 update_display(first_conn);
1015 i = poll(fds, highest_fds + 1, 60000);
1019 for (j=0; j<=highest_fds; j++) {
1020 if (fds[j].revents) printf("fds[%d].fd %d, .revents %x\n", j, fds[j].fd, fds[j].revents);
1025 /* reset fds (gets changed by select()) */
1027 fds_send = master_send_fds;
1030 * wait up to 60 secs for any activity
1032 timeout.tv_sec = 60;
1033 timeout.tv_usec = 0;
1035 i = select(FD_SETSIZE, &fds, &fds_send, NULL, &timeout);
1039 if (errno == EBADF) {
1041 /* don't like this, but we have to */
1042 clear_bad_fds(&server_sock);
1044 } else if (errno != EINTR) {
1055 /* fix an invalid server socket */
1056 if (fds[server_sock].revents & POLLERR) {
1057 del_fd(server_sock);
1058 server_sock = create_server_socket();
1062 /* remove any timed out sockets */
1063 if (time_to_check) {
1071 if (i <= 0) continue;
1074 i -= process_all_sendfiles(i);
1075 process_all_clients(i);
1077 /* sends are given highest `priority' */
1078 i -= process_all_sendfiles(&fds_send, i);
1080 /* incoming PASV connections and uploads */
1081 i -= process_all_sendfiles(&fds, i);
1084 * check the incoming PASV connections first, so
1085 * process_all_clients() won't be confused.
1087 process_all_clients(&fds, i);
1091 if (fds[server_sock].revents & POLLIN) {
1093 if (FD_ISSET(server_sock, &fds)) {
1095 accept_new_client(&server_sock);
1102 * accept_new_client():
1103 * Open a socket for the new client, say hello and put it in
1106 void accept_new_client(int * const server_sock)
1108 struct sockaddr_in tempaddr;
1109 int tempaddr_len = sizeof(tempaddr);
1110 const int tempsock = accept(*server_sock, (struct sockaddr *)&tempaddr, &tempaddr_len);
1112 static int num_err = 0;
1119 if ((errno == EBADF || errno == EPIPE) && ++num_err >= 3) {
1120 del_fd(*server_sock);
1121 *server_sock = create_server_socket();
1124 struct conn * const c = alloc_new_conn(tempsock);
1127 char hello[] = "220 BetaFTPD " VERSION " ready.\r\n";
1130 memcpy(&(c->addr), &tempaddr, sizeof(struct sockaddr));
1133 if (send(tempsock, hello, sizeof(hello), 0) == -1 && errno == EPIPE)
1140 * time_out_sockets():
1141 * Times out any socket that has not had any transfer
1142 * in the last 15 minutes (delay not customizable by FTP
1143 * user -- you must change it in ftpd.h).
1145 * Note that RFC959 explicitly states that there are no
1146 * `spontaneous' error replies, yet we have to do it to
1147 * get the message through at all.
1149 * If we check this list for every accept() call, it's
1150 * actually eating a lot of CPU time, so we only check
1151 * it every minute. We used to do a time() call here,
1152 * but we've changed to do use an alarm() call and set
1153 * the time_to_check_flag in the SIGALRM handler.
1155 RETSIGTYPE handle_alarm(int signum)
1161 signal(SIGALRM, handle_alarm);
1164 void time_out_sockets()
1166 struct conn *c = NULL, *next = first_conn->next_conn;
1167 time_t now = time(NULL);
1169 /* run through the linked list */
1170 while (next != NULL) {
1172 next = c->next_conn;
1174 if ((c->transfer == NULL || c->transfer->state != 5) &&
1175 (now - c->last_transfer > TIMEOUT_SECS)) {
1176 /* RFC violation? */
1177 numeric(c, 421, "Timeout (%u minutes): Closing control connection.", TIMEOUT_SECS/60);
1185 * Remove some bytes from the incoming buffer. This gives
1186 * room for new data on the control connection, and should
1187 * be called when the code has finished using the data.
1188 * (This is done automatically for all commands, so you
1189 * normally need not worry about it.)
1191 void remove_bytes(struct conn * const c, const int num)
1193 if (c->buf_len <= num) {
1197 memmove(c->recv_buf, c->recv_buf + num, c->buf_len);
1202 * numeric(): Sends a numeric FTP reply to the client. Note that
1203 * you can use this command much the same way as you
1204 * would use a printf() (with all the normal %s, %d,
1205 * etc.), since it actually uses printf() internally.
1207 * This command doesn't actually SEND the data -- it
1208 * just puts it in a buffer which is sent after the
1209 * command handler has completed. The reasons for this
1210 * are simple -- it makes error checking and cleanup
1211 * MUCH cleaner, so we won't have to check for errors
1212 * in every single little branch of the code.
1214 void numeric(struct conn * const c, const int numeric, const char * const format, ...)
1219 int in_buf = strlen(message_buf);
1221 snprintf(fmt, 256, "%03u %s\r\n", numeric, format);
1223 va_start(args, format);
1224 i = vsnprintf(message_buf + in_buf, 512 - in_buf, fmt, args);
1229 * init_file_transfer():
1230 * Initiate a data connection for sending. This does not open
1231 * any files etc., just does whatever is needed for the socket,
1232 * if needed. It does, however, send the 150 reply to the client,
1233 * and mmap()s if needed.
1235 * Linux systems (others?) define SOL_TCP right away, which saves us
1236 * some grief and code size. Perhaps using getprotoent() is the `right'
1237 * way, but it's bigger :-) (Optionally, we could figure it out at
1238 * configure time, of course...)
1240 * For optimal speed, we use the Linux 2.2.x-only TCP_CORK flag if
1241 * possible. Note that this is only defined in the first `arm' --
1242 * we silently assume that Linux is the only OS supporting this
1243 * flag. This might be an over-generalization, but I it looks like
1244 * we'll have to depend on it other places as well, so we might
1245 * just as well be evil here.
1247 void init_file_transfer(struct ftran * const f)
1250 struct conn * const c = f->owner;
1251 const int mode = IPTOS_THROUGHPUT, zero = 0, one = 1;
1256 /* we want max throughput */
1257 setsockopt(f->sock, SOL_IP, IP_TOS, (void *)&mode, sizeof(mode));
1258 setsockopt(f->sock, SOL_TCP, TCP_NODELAY, (void *)&zero, sizeof(zero));
1260 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&one, sizeof(one));
1263 /* should these pointers be freed afterwards? */
1265 getprotoent(); /* legal? */
1267 const struct protoent * const pe_ip = getprotobyname("ip");
1268 const struct protoent * const pe_tcp = getprotobyname("tcp");
1269 setsockopt(f->sock, pe_ip->p_proto, IP_TOS, (void *)&mode, sizeof(mode));
1270 setsockopt(f->sock, pe_tcp->p_proto, TCP_NODELAY, (void *)&zero, sizeof(zero));
1276 if (f->dir_listing) {
1277 f->block_size = MAX_BLOCK_SIZE;
1280 f->ascii_mode = f->owner->ascii_mode;
1283 /* find the preferred block size */
1284 f->block_size = MAX_BLOCK_SIZE;
1285 if (fstat(f->local_file, &buf) != -1 &&
1286 buf.st_blksize < MAX_BLOCK_SIZE) {
1287 f->block_size = buf.st_blksize;
1298 #endif /* WANT_UPLOAD */
1300 TRAP_ERROR(add_fd(f->sock, events), 500, return);
1304 setsockopt(f->sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
1306 #if !HAVE_POLL && WANT_UPLOAD
1308 * if we let an upload socket stay in master_send_fds, we would
1309 * get data that would fool us into closing the socket... (sigh)
1312 FD_CLR(f->sock, &master_send_fds);
1313 FD_SET(f->sock, &master_fds);
1317 time(&(f->owner->last_transfer));
1319 if (f->dir_listing) {
1321 numeric(f->owner, 150, "Opening ASCII mode data connection for directory listing.");
1324 * slightly kludged -- perhaps we should kill the second arm,
1325 * at the expense of code size? Or perhaps we could collapse
1326 * the two possible replies into one?
1332 #endif /* WANT_UPLOAD */
1334 numeric(f->owner, 150, "Opening %s mode data connection for '%s'",
1335 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename);
1337 numeric(f->owner, 150, "Opening %s mode data connection for '%s' (%u bytes)",
1338 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename,
1341 #else /* !WANT_ASCII */
1344 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s'", f->filename);
1346 #endif /* WANT_UPLOAD */
1347 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s' (%u bytes)", f->filename, f->size);
1348 #endif /* !WANT_ASCII */
1352 * This section _could_ in theory be more optimized, but it's
1353 * much easier this way, and hopefully, the compiler will be
1354 * intelligent enough to optimize most of this away. The idea
1355 * is, some modes _require_ use of mmap (or not). The preferred
1356 * thing is using mmap() when we don't have sendfile(), and not
1357 * using mmap() when we have sendfile().
1360 if (f->dir_listing == 0) {
1361 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
1362 int do_mmap = (sendfile_supported) ? 0 : 1;
1367 if (f->ascii_mode == 1) do_mmap = 1;
1370 if (f->upload == 1) do_mmap = 0;
1374 f->file_data = mmap(NULL, f->size, PROT_READ, MAP_SHARED, f->local_file, 0);
1375 if (f->file_data == MAP_FAILED) f->file_data = NULL;
1377 f->file_data = NULL;
1379 f->pos = f->owner->rest_pos;
1381 #else /* !HAVE_MMAP */
1382 lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1387 * create_server_socket():
1388 * Create and bind a server socket, that we can use to
1389 * listen to new clients on.
1391 int create_server_socket()
1393 int server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1394 const unsigned int one = 1;
1395 struct sockaddr_in addr;
1399 * In the `perfect' world, if an address was in use, we could
1400 * just wait for the kernel to clear everything up, and everybody
1401 * would be happy. But when you just found out your server socket
1402 * was invalid, it has to be `re-made', and 3000 users are trying
1403 * to access your fileserver, I think it's nice that it comes
1404 * up right away... hence this option.
1406 setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1407 ioctl(server_sock, FIONBIO, &one); /* just in case */
1409 addr.sin_family = AF_INET;
1410 addr.sin_addr.s_addr = INADDR_ANY;
1411 addr.sin_port = htons(FTP_PORT);
1414 err = bind(server_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
1419 /* try to recover from recoverable errors... */
1420 if (errno == ENOMEM || errno == EADDRINUSE) {
1421 puts("Waiting 1 sec before trying again...");
1428 } while (err == -1);
1430 listen(server_sock, 20);
1432 err = add_fd(server_sock, POLLIN);
1444 * Try to find invalid socket descriptors, and clean them.
1445 * The methods used are rather UGLY, but I can't think of
1446 * any good way of checking e.g. server_sock without
1447 * doing anything to it :-(
1449 * poll() is able to do this in a much cleaner way, which
1450 * we use if we use poll(). That checking isn't done here,
1453 void clear_bad_fds(int * const server_sock)
1457 struct timeval tv = { 0, 0 };
1460 FD_SET(*server_sock, &fds);
1461 if (select(*server_sock, &fds, NULL, NULL, &tv) == -1) {
1462 FD_CLR(*server_sock, &master_fds);
1463 close(*server_sock);
1464 *server_sock = create_server_socket();
1468 /* could do this (conn, ftran) in any order */
1470 struct conn *c = NULL, *next = first_conn->next_conn;
1472 /* run through the linked list */
1473 while (next != NULL) {
1477 next = c->next_conn;
1479 if (read(c->sock, &buf, 0) == -1 &&
1487 struct ftran *f = NULL, *next = first_ftran->next_ftran;
1489 while (next != NULL) {
1493 next = f->next_ftran;
1495 if (read(f->sock, &buf, 0) == -1 &&
1504 #if HAVE_BSD_SENDFILE || HAVE_LINUX_SENDFILE
1505 int mysendfile(int sock, int fd, off_t *offset, size_t count)
1507 #if HAVE_BSD_SENDFILE
1511 err = sendfile(fd, sock, *offset, count, NULL, &ssize, 0);
1512 if (ssize > 0) *offset += ssize;
1513 #else /* !HAVE_BSD_SENDFILE */
1514 #if HAVE_LINUX_SENDFILE
1515 return sendfile(sock, fd, offset, count);
1516 #endif /* HAVE_LINUX_SENDFILE */
1517 #endif /* !HAVE_BSD_SENDFILE */
1519 #endif /* HAVE_BSD_SENDFILE || HAVE_LINUX_SENDFILE */
1524 * dump_file(): Dumps a file on the control connection. Used for
1525 * welcome messages and the likes. Note that outbuf
1526 * is so big, to prevent any crashing from users creating
1527 * weird .message files (like 1024 LFs)... The size of
1528 * the file is limited to 1024 bytes (by truncation).
1530 void dump_file(struct conn * const c, const int num, const char * const filename)
1532 char buf[1024], outbuf[5121];
1533 char *ptr = outbuf + 4;
1536 const int dumpfile = open(filename, O_RDONLY);
1537 if (dumpfile == -1) return;
1539 i = read(dumpfile, buf, 1024);
1545 sprintf(outbuf, "%03u-", num);
1548 if (buf[j] == '\n') {
1549 sprintf(ptr, "%03u-", num);
1555 send(c->sock, outbuf, ptr - outbuf, 0);
1562 * Lists all README file in the current (ie. OS current)
1563 * directory, in a 250- message.
1565 void list_readmes(struct conn * const c)
1568 const time_t now = time(NULL);
1571 if (glob("README*", 0, NULL, &pglob) != 0) return;
1573 for (i = 0; i < pglob.gl_pathc; i++) {
1578 if (stat(pglob.gl_pathv[i], &buf) == -1) continue;
1580 /* remove trailing LF */
1581 tm = ctime(&buf.st_mtime);
1582 tm[strlen(tm) - 1] = 0;
1584 snprintf(str, 256, "250-Please read the file %s\r\n"
1585 "250-\tIt was last modified %s - %ld days ago\r\n",
1586 pglob.gl_pathv[i], tm,
1587 (now - buf.st_mtime) / 86400);
1588 send(c->sock, str, strlen(str), 0);