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 if 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
76 #include <arpa/inet.h>
84 #include <sys/ioctl.h>
87 #if HAVE_NETINET_IN_SYSTM_H
88 #include <netinet/in_systm.h>
92 #include <netinet/ip.h>
95 #if HAVE_NETINET_TCP_H
96 #include <netinet/tcp.h>
99 #if HAVE_LINUX_SOCKET_H
100 #include <linux/socket.h>
104 #include <linux/tcp.h>
108 #include <sys/mman.h>
116 #include <sys/time.h>
120 #include <sys/time.h>
124 #include <sys/filio.h>
139 #if HAVE_SYS_SIGNAL_H
140 #include <sys/signal.h>
144 #include <sys/poll.h>
147 #if HAVE_SYS_SENDFILE_H
148 #include <sys/sendfile.h>
152 * <linux/socket.h> does not export this to glibc2 systems, and it isn't
153 * always defined anywhere else.
155 #if !defined(TCP_CORK) && defined(__linux__)
171 #define MAP_FAILED -1
174 struct conn *first_conn = NULL;
175 struct ftran *first_ftran = NULL;
177 struct dcache *first_dcache = NULL;
181 unsigned int highest_fds = 0;
185 struct pollfd fds[FD_MAX];
187 #define MAXCLIENTS FD_MAX
189 fd_set master_fds, master_send_fds;
190 #define MAXCLIENTS FD_SETSIZE
194 FILE *xferlog = NULL;
197 #if HAVE_LINUX_SENDFILE
198 int sendfile_supported = 1;
202 * This variable specifies if it's soon time to check for timed out
203 * clients, and timed out directory listing cache entries. It is
204 * set to 1 by a signal handler every minute, and set to 0 when the
205 * checking has been performed.
207 int time_to_check = 1;
211 * snprintf(): snprintf() replacement for systems that miss it. Note
212 * that this implementation does _not_ necessarily protect
213 * against all buffer overflows. Get a real snprintf() in
214 * your C library. That being said, the 8k limit is
215 * substantially larger than any other string in BetaFTPD,
216 * which should make such an attack harder.
218 int snprintf(char *str, size_t n, const char *format, ...)
224 va_start(args, format);
225 err = vsprintf(buf, format, args);
235 #ifndef HAVE_VSNPRINTF
237 * vsnprintf: vsnprintf() replacement for systems that miss it. Please
238 * see snprintf (above) for more information.
240 int vsnprintf(char *str, size_t n, const char *format, va_list ap)
245 err = vsprintf(buf, format, ap);
253 * add_fd(): Add an fd to the set we monitor. Return 0 on success.
254 * This code is shared between poll() and select() versions.
256 int add_fd(const int fd, const int events)
260 printf("add_fd(%d, %x): failed\n", fd, events);
265 fds[fd].events = events;
266 if (highest_fds < fd)
269 if (fd >= FD_SETSIZE)
272 FD_SET(fd, &master_fds);
273 if (events & POLLOUT)
274 FD_SET(fd, &master_send_fds);
280 * del_fd(): Close and remove an fd from the set(s) we monitor. (See also add_fd().)
282 void del_fd(const int fd)
291 /* Reduce poll()'s workload by not making it watch past end of array */
292 while ((highest_fds > 0) && (fds[highest_fds].fd == -1))
295 if (fd >= FD_SETSIZE)
297 FD_CLR(fd, &master_fds);
298 FD_CLR(fd, &master_send_fds);
307 struct conn *c = first_conn;
308 printf("list_clients:\n");
309 while (c && c->next_conn) {
311 printf("list_clients: fd %d\n", c->sock);
317 * add_to_linked_list():
318 * Inserts an element (conn, ftran or dcache) into its linked list.
319 * The list is placed at the beginning, right after the (bogus)
320 * first element of the list.
322 void add_to_linked_list(struct list_element * const first,
323 struct list_element * const elem)
328 elem->next = first->next;
329 if (elem->next) elem->next->prev = elem;
332 /* this is the bogus head of the list */
338 * remove_from_linked_list():
339 * Removes an element (conn, ftran or dcache) from its linked list,
342 void remove_from_linked_list(struct list_element * const elem)
344 if (elem->prev != NULL) elem->prev->next = elem->next;
345 if (elem->next != NULL) elem->next->prev = elem->prev;
351 * Allocates a new control connection (type `struct conn'),
352 * initializes it, and adds it to the linked list. The connection
353 * operates on the socket SOCK.
355 struct conn *alloc_new_conn(const int sock)
357 const unsigned int one = 1;
358 struct conn *c = (struct conn *)(malloc(sizeof(struct conn)));
360 if (c == NULL) return c;
363 ioctl(sock, FIONBIO, &one);
364 if (add_fd(sock, POLLIN) != 0) {
366 send(sock, "230 Server too busy, please try again later.\r\n", 46, 0);
371 add_to_linked_list((struct list_element *)first_conn,
372 (struct list_element *)c);
374 /* this is the bogus head of the list */
381 c->buf_len = c->auth = c->rest_pos = 0;
388 * strcpy(c->curr_dir, "/");
389 * strcpy(c->last_cmd, "");
390 * strcpy(c->rename_from, "")
392 c->curr_dir[0] = '/';
394 c->curr_dir[1] = c->last_cmd[0] = c->rename_from[0] = '\0';
396 c->curr_dir[1] = c->rename_from[0] = '\0';
399 time(&(c->last_transfer));
408 * Allocates a new data connection (type `struct ftran'), and
409 * adds it to the linked list. The connection operates on the
410 * socket SOCK, and has the control connection C as its parent.
412 struct ftran *alloc_new_ftran(const int sock, const struct conn * const c)
414 struct ftran *f = (struct ftran *)(malloc(sizeof(struct ftran)));
416 if (f == NULL) return f;
418 /* this is the bogus head of the list */
419 f->next_ftran = NULL;
420 f->prev_ftran = NULL;
422 add_to_linked_list((struct list_element *)first_ftran,
423 (struct list_element *)f);
429 f->owner = (struct conn * const)c;
444 * Destroy a control connection, remove it from the linked
445 * list, and clean up after it.
447 void destroy_conn(struct conn * const c)
449 if (c == NULL) return;
452 destroy_ftran(c->transfer);
453 remove_from_linked_list((struct list_element *)c);
458 * Destroy a data connection, remove it from the linked list,
459 * and clean up after it.
461 * For some reason, TCP_CORK (Linux 2.2.x-only) doesn't flush
462 * even _after_ the socket is closed, so we zero it just before
463 * closing. We also zero just before sending the last packet,
464 * as it seems to be needed on some systems.
466 * If you wonder why I check for `defined(SOL_TCP)' and don't
467 * provide an alternative, see the comments on init_file_transfer().
469 void destroy_ftran(struct ftran * const f)
471 const unsigned int zero = 0;
473 if (f == NULL) return;
474 #if defined(TCP_CORK) && defined(SOL_TCP)
475 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
481 time(&(f->dir_cache->last_used));
482 f->dir_cache->use_count--;
488 if (f->dir_listing) {
492 munmap(f->file_data, f->size);
498 if (f->local_file != -1) close(f->local_file);
501 if (f->dir_listing) unlink(f->filename);
504 f->owner->transfer = NULL;
507 if (f->dir_cache != NULL) f->dir_cache->use_count--;
510 remove_from_linked_list((struct list_element *)f);
514 * process_all_clients():
515 * Processes all the _control_ connections in active_clients
516 * (normally returned from a select(), there are at max
517 * NUM_AC active connections in the set), sending them
518 * through to the command parser if a command has been
522 int process_all_clients(const int num_ac)
524 int process_all_clients(const fd_set * const active_clients, const int num_ac)
527 struct conn *c = NULL, *next = first_conn->next_conn;
528 int checked_through = 0;
530 /* run through the linked list */
531 while (next != NULL && checked_through < num_ac) {
537 if ((fds[c->sock].revents & (POLLIN|POLLERR|POLLHUP|POLLNVAL)) == 0) {
541 if (!FD_ISSET(c->sock, active_clients)) {
548 bytes_avail = recv(c->sock, c->recv_buf + c->buf_len,
549 255 - c->buf_len, 0);
550 if (bytes_avail <= 0) {
552 * select() has already told us there's something about
553 * this socket, so if we get a return value of zero, the
554 * client has closed the socket. If we get a return value
555 * of -1 (error), we close the socket ourselves.
557 * We do the same for poll(), even though we actually have
558 * bits that tell us what is happening (in case of new
559 * input AND error/hangup at the same time, we do an
560 * explicit check at the bottom of the loop as well).
566 /* overrun = disconnect */
567 if (c->buf_len + bytes_avail > 254) {
568 numeric(c, 503, "Buffer overrun; disconnecting.");
573 c->buf_len += bytes_avail;
576 if (fds[c->sock].revents & (POLLERR|POLLHUP|POLLNVAL)) {
580 return checked_through;
584 * process_all_sendfiles():
585 * Sends data to all clients that are ready to receive it.
586 * Also checks for data connections that are newly-connected,
587 * and handler xferlog entries for the files that are finished.
590 int process_all_sendfiles(const int num_ac)
592 int process_all_sendfiles(fd_set * const active_clients, const int num_ac)
595 struct ftran *f = NULL, *next = first_ftran->next_ftran;
596 int checked_through = 0;
597 struct sockaddr tempaddr;
598 int tempaddr_len = sizeof(tempaddr);
600 while (next != NULL && checked_through < num_ac) {
602 next = f->next_ftran;
605 if (fds[f->sock].revents & (POLLHUP|POLLERR|POLLNVAL)) {
611 /* state = 2: incoming PASV, state >3: send file */
613 if ((f->state < 2) || (f->state == 3) || (fds[f->sock].revents & (POLLIN|POLLOUT)) == 0) {
615 if ((f->state < 2) || (f->state == 3) || !FD_ISSET(f->sock, active_clients)) {
623 /* Nothing is needed for the poll() version? */
625 FD_CLR(f->sock, active_clients);
628 if (f->state == 2) { /* incoming PASV */
629 const unsigned int one = 1;
630 const int tempsock = accept(f->sock, (struct sockaddr *)&tempaddr,
635 if (tempsock == -1) {
641 ioctl(f->sock, FIONBIO, &one);
642 init_file_transfer(f);
644 if (f->upload) continue;
648 init_file_transfer(f);
650 if (f->upload) continue;
654 /* for download, we send the first packets right away */
657 if (do_upload(f)) continue;
660 if (do_download(f)) continue;
662 /* do_{upload,download} returned 0, the transfer is complete */
663 numeric(f->owner, 226, "Transfer complete.");
664 time(&(f->owner->last_transfer));
667 if (!f->dir_listing) {
674 update_display(first_conn);
678 return checked_through;
682 int do_upload(struct ftran *f)
684 char upload_buf[16384];
687 /* keep buffer size small in ascii transfers
688 to prevent process stalling while filtering
689 data on slower computers */
692 * This isn't a big problem, since we won't get
693 * packets this big anyway, the biggest I've seen
694 * was 12kB on 100mbit (but that was from a Windows
695 * machine), so I've reduced the buffer from 64 kB
696 * to 16 kB :-) --Steinar
698 const int maxlen = (f->ascii_mode == 1) ? 4096 : 16384;
700 const int maxlen = 16384;
704 size = recv(f->sock, upload_buf, maxlen, 0);
709 if (size > 0 && f->ascii_mode == 1) {
710 size = ascii_uploadfilter(upload_buf, size);
713 if (size > 0 && (write(f->local_file, upload_buf, size) == size)) {
715 } else if (size == -1) {
716 /* don't write xferlog... or? */
717 numeric(f->owner, 426, strerror(errno));
725 int do_download(struct ftran *f)
727 #if defined(TCP_CORK) && defined(SOL_TCP)
728 unsigned int zero = 0;
732 int more_to_send = 0;
735 char buf[MAX_BLOCK_SIZE];
738 char buf2[MAX_BLOCK_SIZE * 2];
742 #if HAVE_LINUX_SENDFILE
744 * We handle the optimal case first, which is sendfile().
745 * Here we use a rather simplified sending `algorithm',
746 * leaving most of the quirks to the system calls.
748 if (sendfile_supported == 1 && f->dir_listing == 0) {
750 size = f->size - f->pos;
752 if (size > f->block_size) size = f->block_size;
753 if (size < 0) size = 0;
756 if (size != f->block_size) {
757 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
761 err = sendfile(f->sock, f->local_file, &f->pos, size);
762 return (f->pos < f->size) && (err > -1);
767 size = f->size - f->pos;
769 if (size > f->block_size) size = f->block_size;
770 if (size < 0) size = 0;
772 bytes_to_send = size;
773 sendfrom_buf = f->file_data + f->pos;
775 bytes_to_send = read(f->local_file, buf, f->block_size);
779 if (bytes_to_send == f->block_size) more_to_send = 1;
782 if (f->ascii_mode == 1) {
783 bytes_to_send = ascii_downloadfilter(sendfrom_buf,
784 buf2, bytes_to_send);
787 #endif /* WANT_ASCII */
789 #if defined(TCP_CORK) && defined(SOL_TCP)
790 /* if we believe this is the last packet, unset TCP_CORK */
791 if (more_to_send == 0) {
792 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
796 size = send(f->sock, sendfrom_buf, bytes_to_send, 0);
797 if (size < bytes_to_send) more_to_send = 1;
800 if (f->ascii_mode == 1 && size < bytes_to_send && size > 0) {
801 size = ascii_findlength(sendfrom_buf, size);
806 if (size > 0) f->pos += size;
813 void write_xferlog(struct ftran *f)
816 time_t now = time(NULL);
817 struct tm *t = localtime(&now);
819 if (xferlog == NULL) return;
821 strftime(temp, 256, "%a %b %d %H:%M:%S %Y", t);
823 fprintf(xferlog, "%s %u %s %lu %s b _ %c a %s ftp 0 * \n",
825 fprintf(xferlog, "%s %u %s %lu %s b _ o a %s ftp 0 *\n",
827 temp, (int)(difftime(now, f->tran_start)),
828 inet_ntoa(f->sin.sin_addr), f->size,
831 (f->upload) ? 'i' : 'o',
837 /* vim needs this to work properly :-( */
844 /* Reallocate the buggers constantly */
847 struct conn *c = first_conn;
848 int maxloops = MAXCLIENTS;
850 while (c && c->next_conn) {
851 struct conn *temp = malloc(sizeof(*temp));
853 *temp = *(c->next_conn);
854 if (temp->transfer) temp->transfer->owner = temp;
855 memset(c->next_conn, 0, sizeof(struct conn));
861 assert(maxloops > 0);
867 * main(): Main function. Does the initialization, and contains
868 * the main server loop. Takes no command-line arguments
869 * (see README for justification).
876 /* the sets are declared globally if we use poll() */
878 fd_set fds, fds_send;
881 /*setlinebuf(stdout);*/
882 setvbuf(stdout, (char *)NULL, _IOLBF, 0);
884 signal(SIGPIPE, SIG_IGN);
886 printf("BetaFTPD version %s, Copyright (C) 1999-2000 Steinar H. Gunderson\n", VERSION);
887 puts("BetaFTPD comes with ABSOLUTELY NO WARRANTY; for details see the file");
888 puts("COPYING. This is free software, and you are welcome to redistribute it");
889 puts("under certain conditions; again see the file COPYING for details.");
892 /* we don't need stdin */
898 for (i = 0; i < FD_MAX; i++) {
904 FD_ZERO(&master_fds);
905 FD_ZERO(&master_send_fds);
908 server_sock = create_server_socket();
911 printf("%cc", (char)27); /* reset and clear the screen */
914 /* init dummy first connection */
915 first_conn = alloc_new_conn(-1);
916 first_ftran = alloc_new_ftran(0, NULL);
918 first_dcache = alloc_new_dcache();
923 #warning No xferlog support for nonroot yet
926 xferlog = fopen("/var/log/xferlog", "r+");
927 if (xferlog == NULL) xferlog = fopen("/usr/adm/xferlog", "r+");
929 if (xferlog != NULL) {
930 fseek(xferlog, 0L, SEEK_END);
939 puts("fork() failed, exiting");
944 puts("BetaFTPD forked into the background");
948 puts("BetaFTPD active");
951 /* set timeout alarm here (after the fork) */
953 signal(SIGALRM, handle_alarm);
955 #if HAVE_LINUX_SENDFILE
956 /* check that sendfile() is really implemented (same check as configure does) */
958 int out_fd = 1, in_fd = 0;
963 sendfile(out_fd, in_fd, &offset, size);
964 if (errno == ENOSYS) sendfile_supported = 0;
971 struct timeval timeout;
974 /*screw_clients(); //look for memory errors */
977 update_display(first_conn);
981 i = poll(fds, highest_fds + 1, 60000);
985 for (j=0; j<=highest_fds; j++) {
986 if (fds[j].revents) printf("fds[%d].fd %d, .revents %x\n", j, fds[j].fd, fds[j].revents);
991 /* reset fds (gets changed by select()) */
993 fds_send = master_send_fds;
996 * wait up to 60 secs for any activity
1001 i = select(FD_SETSIZE, &fds, &fds_send, NULL, &timeout);
1005 if (errno == EBADF) {
1007 /* don't like this, but we have to */
1008 clear_bad_fds(&server_sock);
1010 } else if (errno != EINTR) {
1021 /* fix an invalid server socket */
1022 if (fds[server_sock].revents & POLLERR) {
1023 del_fd(server_sock);
1024 server_sock = create_server_socket();
1028 /* remove any timed out sockets */
1029 if (time_to_check) {
1037 if (i <= 0) continue;
1040 i -= process_all_sendfiles(i);
1041 process_all_clients(i);
1043 /* sends are given highest `priority' */
1044 i -= process_all_sendfiles(&fds_send, i);
1046 /* incoming PASV connections and uploads */
1047 i -= process_all_sendfiles(&fds, i);
1050 * check the incoming PASV connections first, so
1051 * process_all_clients() won't be confused.
1053 process_all_clients(&fds, i);
1057 if (fds[server_sock].revents & POLLIN) {
1059 if (FD_ISSET(server_sock, &fds)) {
1061 accept_new_client(&server_sock);
1068 * accept_new_client():
1069 * Open a socket for the new client, say hello and put it in
1072 void accept_new_client(int * const server_sock)
1074 struct sockaddr_in tempaddr;
1075 int tempaddr_len = sizeof(tempaddr);
1076 const int tempsock = accept(*server_sock, (struct sockaddr *)&tempaddr, &tempaddr_len);
1078 static int num_err = 0;
1085 if ((errno == EBADF || errno == EPIPE) && ++num_err >= 3) {
1086 del_fd(*server_sock);
1087 *server_sock = create_server_socket();
1090 struct conn * const c = alloc_new_conn(tempsock);
1093 numeric(c, 220, "BetaFTPD " VERSION " ready.");
1095 memcpy(&(c->addr), &tempaddr, sizeof(struct sockaddr));
1102 * time_out_sockets():
1103 * Times out any socket that has not had any transfer
1104 * in the last 15 minutes (delay not customizable by FTP
1105 * user -- you must change it in ftpd.h).
1107 * Note that RFC959 explicitly states that there are no
1108 * `spontaneous' error replies, yet we have to do it to
1109 * get the message through at all.
1111 * If we check this list for every accept() call, it's
1112 * actually eating a lot of CPU time, so we only check
1113 * it every minute. We used to do a time() call here,
1114 * but we've changed to do use an alarm() call and set
1115 * the time_to_check_flag in the SIGALRM handler.
1117 RETSIGTYPE handle_alarm(int signum)
1123 signal(SIGALRM, handle_alarm);
1126 void time_out_sockets()
1128 struct conn *c = NULL, *next = first_conn->next_conn;
1129 time_t now = time(NULL);
1131 /* run through the linked list */
1132 while (next != NULL) {
1134 next = c->next_conn;
1136 if ((c->transfer == NULL || c->transfer->state != 5) &&
1137 (now - c->last_transfer > TIMEOUT_SECS)) {
1138 /* RFC violation? */
1139 numeric(c, 421, "Timeout (%u minutes): Closing control connection.", TIMEOUT_SECS/60);
1147 * Remove some bytes from the incoming buffer. This gives
1148 * room for new data on the control connection, and should
1149 * be called when the code has finished using the data.
1150 * (This is done automatically for all commands, so you
1151 * normally need not worry about it.)
1153 void remove_bytes(struct conn * const c, const int num)
1155 if (c->buf_len <= num) {
1159 memmove(c->recv_buf, c->recv_buf + num, c->buf_len);
1164 * numeric(): Sends a numeric FTP reply to the client. Note that
1165 * you can use this command much the same way as you
1166 * would use a printf() (with all the normal %s, %d,
1167 * etc.), since it actually uses printf() internally.
1169 void numeric(struct conn * const c, const int numeric, const char * const format, ...)
1171 char buf[256], fmt[256];
1175 snprintf(fmt, 256, "%03u %s\r\n", numeric, format);
1177 va_start(args, format);
1178 i = vsnprintf(buf, 256, fmt, args);
1181 err = send(c->sock, buf, i, 0);
1182 if (err == -1 && errno == EPIPE) {
1188 * init_file_transfer():
1189 * Initiate a data connection for sending. This does not open
1190 * any files etc., just does whatever is needed for the socket,
1191 * if needed. It does, however, send the 150 reply to the client,
1192 * and mmap()s if needed.
1194 * Linux systems (others?) define SOL_TCP right away, which saves us
1195 * some grief and code size. Perhaps using getprotoent() is the `right'
1196 * way, but it's bigger :-) (Optionally, we could figure it out at
1197 * configure time, of course...)
1199 * For optimal speed, we use the Linux 2.2.x-only TCP_CORK flag if
1200 * possible. Note that this is only defined in the first `arm' --
1201 * we silently assume that Linux is the only OS supporting this
1202 * flag. This might be an over-generalization, but I it looks like
1203 * we'll have to depend on it other places as well, so we might
1204 * just as well be evil here.
1206 void init_file_transfer(struct ftran * const f)
1209 struct conn * const c = f->owner;
1210 const int mode = IPTOS_THROUGHPUT, zero = 0, one = 1;
1215 /* we want max throughput */
1216 setsockopt(f->sock, SOL_IP, IP_TOS, (void *)&mode, sizeof(mode));
1217 setsockopt(f->sock, SOL_TCP, TCP_NODELAY, (void *)&zero, sizeof(zero));
1219 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&one, sizeof(one));
1222 /* should these pointers be freed afterwards? */
1224 getprotoent(); /* legal? */
1226 const struct protoent * const pe_ip = getprotobyname("ip");
1227 const struct protoent * const pe_tcp = getprotobyname("tcp");
1228 setsockopt(f->sock, pe_ip->p_proto, IP_TOS, (void *)&mode, sizeof(mode));
1229 setsockopt(f->sock, pe_tcp->p_proto, TCP_NODELAY, (void *)&zero, sizeof(zero));
1235 if (f->dir_listing) {
1236 f->block_size = MAX_BLOCK_SIZE;
1239 f->ascii_mode = f->owner->ascii_mode;
1242 /* find the preferred block size */
1243 f->block_size = MAX_BLOCK_SIZE;
1244 if (fstat(f->local_file, &buf) != -1 &&
1245 buf.st_blksize < MAX_BLOCK_SIZE) {
1246 f->block_size = buf.st_blksize;
1257 #endif /* WANT_UPLOAD */
1259 TRAP_ERROR(add_fd(f->sock, events), 500, return);
1263 setsockopt(f->sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
1265 #if !HAVE_POLL && WANT_UPLOAD
1267 * if we let an upload socket stay in master_send_fds, we would
1268 * get data that would fool us into closing the socket... (sigh)
1271 FD_CLR(f->sock, &master_send_fds);
1272 FD_SET(f->sock, &master_fds);
1276 time(&(f->owner->last_transfer));
1278 if (f->dir_listing) {
1280 numeric(f->owner, 150, "Opening ASCII mode data connection for directory listing.");
1283 * slightly kludged -- perhaps we should kill the second arm,
1284 * at the expense of code size? Or perhaps we could collapse
1285 * the two possible replies into one?
1291 #endif /* WANT_UPLOAD */
1293 numeric(f->owner, 150, "Opening %s mode data connection for '%s'",
1294 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename);
1296 numeric(f->owner, 150, "Opening %s mode data connection for '%s' (%u bytes)",
1297 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename,
1300 #else /* !WANT_ASCII */
1303 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s'", f->filename);
1305 #endif /* WANT_UPLOAD */
1306 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s' (%u bytes)", f->filename, f->size);
1307 #endif /* !WANT_ASCII */
1311 * This section _could_ in theory be more optimized, but it's
1312 * much easier this way, and hopefully, the compiler will be
1313 * intelligent enough to optimize most of this away. The idea
1314 * is, some modes _require_ use of mmap (or not). The preferred
1315 * thing is using mmap() when we don't have sendfile(), and not
1316 * using mmap() when we have sendfile().
1319 if (f->dir_listing == 0) {
1320 #if HAVE_LINUX_SENDFILE
1321 int do_mmap = (sendfile_supported) ? 0 : 1;
1326 if (f->ascii_mode == 1) do_mmap = 1;
1329 if (f->upload == 1) do_mmap = 0;
1333 f->file_data = mmap(NULL, f->size, PROT_READ, MAP_SHARED, f->local_file, 0);
1334 if (f->file_data == MAP_FAILED) f->file_data = NULL;
1336 f->file_data = NULL;
1338 f->pos = f->owner->rest_pos;
1340 #else /* !HAVE_MMAP */
1341 lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1346 * create_server_socket():
1347 * Create and bind a server socket, that we can use to
1348 * listen to new clients on.
1350 int create_server_socket()
1352 int server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1353 const unsigned int one = 1;
1354 struct sockaddr_in addr;
1358 * In the `perfect' world, if an address was in use, we could
1359 * just wait for the kernel to clear everything up, and everybody
1360 * would be happy. But when you just found out your server socket
1361 * was invalid, it has to be `re-made', and 3000 users are trying
1362 * to access your fileserver, I think it's nice that it comes
1363 * up right away... hence this option.
1365 setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1366 ioctl(server_sock, FIONBIO, &one); /* just in case */
1368 addr.sin_family = AF_INET;
1369 addr.sin_addr.s_addr = INADDR_ANY;
1370 addr.sin_port = htons(FTP_PORT);
1373 err = bind(server_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
1378 /* try to recover from recoverable errors... */
1379 if (errno == ENOMEM || errno == EADDRINUSE) {
1380 puts("Waiting 1 sec before trying again...");
1387 } while (err == -1);
1389 listen(server_sock, 20);
1391 err = add_fd(server_sock, POLLIN);
1403 * Try to find invalid socket descriptors, and clean them.
1404 * The methods used are rather UGLY, but I can't think of
1405 * any good way of checking e.g. server_sock without
1406 * doing anything to it :-(
1408 * poll() is able to do this in a much cleaner way, which
1409 * we use if we use poll(). That checking isn't done here,
1412 void clear_bad_fds(int * const server_sock)
1416 struct timeval tv = { 0, 0 };
1419 FD_SET(*server_sock, &fds);
1420 if (select(*server_sock, &fds, NULL, NULL, &tv) == -1) {
1421 FD_CLR(*server_sock, &master_fds);
1422 close(*server_sock);
1423 *server_sock = create_server_socket();
1427 /* could do this (conn, ftran) in any order */
1429 struct conn *c = NULL, *next = first_conn->next_conn;
1431 /* run through the linked list */
1432 while (next != NULL) {
1436 next = c->next_conn;
1438 if (read(c->sock, &buf, 0) == -1 &&
1446 struct ftran *f = NULL, *next = first_ftran->next_ftran;
1448 while (next != NULL) {
1452 next = f->next_ftran;
1454 if (read(f->sock, &buf, 0) == -1 &&
1465 * dump_file(): Dumps a file on the control connection. Used for
1466 * welcome messages and the likes. Note that outbuf
1467 * is so big, to prevent any crashing from users creating
1468 * weird .message files (like 1024 LFs)... The size of
1469 * the file is limited to 1024 bytes (by truncation).
1471 void dump_file(struct conn * const c, const int num, const char * const filename)
1473 char buf[1024], outbuf[5121];
1474 char *ptr = outbuf + 4;
1477 const int dumpfile = open(filename, O_RDONLY);
1478 if (dumpfile == -1) return;
1480 i = read(dumpfile, buf, 1024);
1486 sprintf(outbuf, "%03u-", num);
1489 if (buf[j] == '\n') {
1490 sprintf(ptr, "%03u-", num);
1496 send(c->sock, outbuf, ptr - outbuf, 0);
1503 * Lists all README file in the current (ie. OS current)
1504 * directory, in a 250- message.
1506 void list_readmes(struct conn * const c)
1509 const time_t now = time(NULL);
1512 if (glob("README*", 0, NULL, &pglob) != 0) return;
1514 for (i = 0; i < pglob.gl_pathc; i++) {
1519 if (stat(pglob.gl_pathv[i], &buf) == -1) continue;
1521 /* remove trailing LF */
1522 tm = ctime(&buf.st_mtime);
1523 tm[strlen(tm) - 1] = 0;
1525 snprintf(str, 256, "250-Please read the file %s\r\n"
1526 "250-\tIt was last modified %s - %ld days ago\r\n",
1527 pglob.gl_pathv[i], tm,
1528 (now - buf.st_mtime) / 86400);
1529 send(c->sock, str, strlen(str), 0);