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
32 #include <sys/types.h>
80 #include <netinet/in.h>
84 #include <arpa/inet.h>
92 #include <sys/socket.h>
96 #include <sys/ioctl.h>
99 #if HAVE_NETINET_IN_SYSTM_H
100 #include <netinet/in_systm.h>
103 #if HAVE_NETINET_IP_H
104 #include <netinet/ip.h>
107 #if HAVE_NETINET_TCP_H
108 #include <netinet/tcp.h>
111 #if HAVE_LINUX_SOCKET_H
112 #include <linux/socket.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__)
175 #define MAP_FAILED -1
178 struct conn *first_conn = NULL;
179 struct ftran *first_ftran = NULL;
181 struct dcache *first_dcache = NULL;
185 unsigned int highest_fds = 0;
189 struct pollfd fds[FD_MAX];
191 #define MAXCLIENTS FD_MAX
193 fd_set master_fds, master_send_fds;
194 #define MAXCLIENTS FD_SETSIZE
198 FILE *xferlog = NULL;
201 #if HAVE_LINUX_SENDFILE
202 int sendfile_supported = 1;
206 * This variable specifies if it's soon time to check for timed out
207 * clients, and timed out directory listing cache entries. It is
208 * set to 1 by a signal handler every minute, and set to 0 when the
209 * checking has been performed.
211 int time_to_check = 1;
215 * snprintf(): snprintf() replacement for systems that miss it. Note
216 * that this implementation does _not_ necessarily protect
217 * against all buffer overflows. Get a real snprintf() in
218 * your C library. That being said, the 8k limit is
219 * substantially larger than any other string in BetaFTPD,
220 * which should make such an attack harder.
222 int snprintf(char *str, size_t n, const char *format, ...)
228 va_start(args, format);
229 err = vsprintf(buf, format, args);
239 #ifndef HAVE_VSNPRINTF
241 * vsnprintf: vsnprintf() replacement for systems that miss it. Please
242 * see snprintf (above) for more information.
244 int vsnprintf(char *str, size_t n, const char *format, va_list ap)
249 err = vsprintf(buf, format, ap);
257 * add_fd(): Add an fd to the set we monitor. Return 0 on success.
258 * This code is shared between poll() and select() versions.
260 int add_fd(const int fd, const int events)
264 printf("add_fd(%d, %x): failed\n", fd, events);
269 fds[fd].events = events;
270 if (highest_fds < fd)
273 if (fd >= FD_SETSIZE)
276 FD_SET(fd, &master_fds);
277 if (events & POLLOUT)
278 FD_SET(fd, &master_send_fds);
284 * del_fd(): Close and remove an fd from the set(s) we monitor. (See also add_fd().)
286 void del_fd(const int fd)
295 /* Reduce poll()'s workload by not making it watch past end of array */
296 while ((highest_fds > 0) && (fds[highest_fds].fd == -1))
299 if (fd >= FD_SETSIZE)
301 FD_CLR(fd, &master_fds);
302 FD_CLR(fd, &master_send_fds);
311 struct conn *c = first_conn;
312 printf("list_clients:\n");
313 while (c && c->next_conn) {
315 printf("list_clients: fd %d\n", c->sock);
321 * add_to_linked_list():
322 * Inserts an element (conn, ftran or dcache) into its linked list.
323 * The list is placed at the beginning, right after the (bogus)
324 * first element of the list.
326 void add_to_linked_list(struct list_element * const first,
327 struct list_element * const elem)
332 elem->next = first->next;
333 if (elem->next) elem->next->prev = elem;
336 /* this is the bogus head of the list */
342 * remove_from_linked_list():
343 * Removes an element (conn, ftran or dcache) from its linked list,
346 void remove_from_linked_list(struct list_element * const elem)
348 if (elem->prev != NULL) elem->prev->next = elem->next;
349 if (elem->next != NULL) elem->next->prev = elem->prev;
355 * Allocates a new control connection (type `struct conn'),
356 * initializes it, and adds it to the linked list. The connection
357 * operates on the socket SOCK.
359 struct conn *alloc_new_conn(const int sock)
361 const unsigned int one = 1;
362 struct conn *c = (struct conn *)(malloc(sizeof(struct conn)));
364 if (c == NULL) return c;
367 ioctl(sock, FIONBIO, &one);
368 if (add_fd(sock, POLLIN) != 0) {
370 send(sock, "230 Server too busy, please try again later.\r\n", 46, 0);
375 add_to_linked_list((struct list_element *)first_conn,
376 (struct list_element *)c);
378 /* this is the bogus head of the list */
385 c->buf_len = c->auth = c->rest_pos = 0;
392 * strcpy(c->curr_dir, "/");
393 * strcpy(c->last_cmd, "");
394 * strcpy(c->rename_from, "")
396 c->curr_dir[0] = '/';
398 c->curr_dir[1] = c->last_cmd[0] = c->rename_from[0] = '\0';
400 c->curr_dir[1] = c->rename_from[0] = '\0';
403 time(&(c->last_transfer));
412 * Allocates a new data connection (type `struct ftran'), and
413 * adds it to the linked list. The connection operates on the
414 * socket SOCK, and has the control connection C as its parent.
416 struct ftran *alloc_new_ftran(const int sock, const struct conn * const c)
418 struct ftran *f = (struct ftran *)(malloc(sizeof(struct ftran)));
420 if (f == NULL) return f;
422 /* this is the bogus head of the list */
423 f->next_ftran = NULL;
424 f->prev_ftran = NULL;
426 add_to_linked_list((struct list_element *)first_ftran,
427 (struct list_element *)f);
433 f->owner = (struct conn * const)c;
448 * alloc_new_dcache():
449 * Allocates a new directory cache entry (type `struct dcache'),
450 * and adds it to the linked list.
452 struct dcache *alloc_new_dcache()
454 struct dcache *d = (struct dcache *)(malloc(sizeof(struct dcache)));
456 if (d == NULL) return d;
460 strcpy(d->dir_name, "");
463 add_to_linked_list((struct list_element *)first_dcache,
464 (struct list_element *)d);
472 * Destroy a control connection, remove it from the linked
473 * list, and clean up after it.
475 void destroy_conn(struct conn * const c)
477 if (c == NULL) return;
480 destroy_ftran(c->transfer);
481 remove_from_linked_list((struct list_element *)c);
486 * Destroy a data connection, remove it from the linked list,
487 * and clean up after it.
489 * For some reason, TCP_CORK (Linux 2.2.x-only) doesn't flush
490 * even _after_ the socket is closed, so we zero it just before
491 * closing. We also zero just before sending the last packet,
492 * as it seems to be needed on some systems.
494 * If you wonder why I check for `defined(SOL_TCP)' and don't
495 * provide an alternative, see the comments on init_file_transfer().
497 void destroy_ftran(struct ftran * const f)
499 const unsigned int zero = 0;
501 if (f == NULL) return;
502 #if defined(TCP_CORK) && defined(SOL_TCP)
503 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
509 time(&(f->dir_cache->last_used));
510 f->dir_cache->use_count--;
516 if (f->dir_listing) {
520 munmap(f->file_data, f->size);
526 if (f->local_file != -1) close(f->local_file);
529 if (f->dir_listing) unlink(f->filename);
532 f->owner->transfer = NULL;
535 if (f->dir_cache != NULL) f->dir_cache->use_count--;
538 remove_from_linked_list((struct list_element *)f);
544 * Destroy a directory listing cache entry, remove it from the
545 * linked list, and clean up after it.
547 * If you free a cache entry that is in use (use_count > 0),
548 * BetaFTPD will most likely crash (later). The thing you're supposed
549 * to do when you're done with a dcache entry, is to decrement
550 * its use_count, and let the timeout functions do the destroying
551 * when it's time to do so.
553 void destroy_dcache(struct dcache * const d)
555 if (d == NULL) return;
557 if (d->dir_data != NULL) free(d->dir_data);
558 remove_from_linked_list((struct list_element *)d);
563 * process_all_clients():
564 * Processes all the _control_ connections in active_clients
565 * (normally returned from a select(), there are at max
566 * NUM_AC active connections in the set), sending them
567 * through to the command parser if a command has been
571 int process_all_clients(const int num_ac)
573 int process_all_clients(const fd_set * const active_clients, const int num_ac)
576 struct conn *c = NULL, *next = first_conn->next_conn;
577 int checked_through = 0;
579 /* run through the linked list */
580 while (next != NULL && checked_through < num_ac) {
586 if ((fds[c->sock].revents & (POLLIN|POLLERR|POLLHUP|POLLNVAL)) == 0) {
590 if (!FD_ISSET(c->sock, active_clients)) {
597 bytes_avail = recv(c->sock, c->recv_buf + c->buf_len,
598 255 - c->buf_len, 0);
599 if (bytes_avail <= 0) {
601 * select() has already told us there's something about
602 * this socket, so if we get a return value of zero, the
603 * client has closed the socket. If we get a return value
604 * of -1 (error), we close the socket ourselves.
606 * We do the same for poll(), even though we actually have
607 * bits that tell us what is happening (in case of new
608 * input AND error/hangup at the same time, we do an
609 * explicit check at the bottom of the loop as well).
615 /* overrun = disconnect */
616 if (c->buf_len + bytes_avail > 254) {
617 numeric(c, 503, "Buffer overrun; disconnecting.");
622 c->buf_len += bytes_avail;
625 if (fds[c->sock].revents & (POLLERR|POLLHUP|POLLNVAL)) {
629 return checked_through;
633 * process_all_sendfiles():
634 * Sends data to all clients that are ready to receive it.
635 * Also checks for data connections that are newly-connected,
636 * and handler xferlog entries for the files that are finished.
639 int process_all_sendfiles(const int num_ac)
641 int process_all_sendfiles(fd_set * const active_clients, const int num_ac)
644 struct ftran *f = NULL, *next = first_ftran->next_ftran;
645 int checked_through = 0;
646 struct sockaddr tempaddr;
647 int tempaddr_len = sizeof(tempaddr);
649 while (next != NULL && checked_through < num_ac) {
651 next = f->next_ftran;
654 if (fds[f->sock].revents & (POLLHUP|POLLERR|POLLNVAL)) {
660 /* state = 2: incoming PASV, state >3: send file */
662 if ((f->state < 2) || (f->state == 3) || (fds[f->sock].revents & (POLLIN|POLLOUT)) == 0) {
664 if ((f->state < 2) || (f->state == 3) || !FD_ISSET(f->sock, active_clients)) {
672 /* Nothing is needed for the poll() version? */
674 FD_CLR(f->sock, active_clients);
677 if (f->state == 2) { /* incoming PASV */
678 const unsigned int one = 1;
679 const int tempsock = accept(f->sock, (struct sockaddr *)&tempaddr,
684 if (tempsock == -1) {
690 ioctl(f->sock, FIONBIO, &one);
691 init_file_transfer(f);
693 if (f->upload) continue;
697 init_file_transfer(f);
699 if (f->upload) continue;
703 /* for download, we send the first packets right away */
706 if (do_upload(f)) continue;
709 if (do_download(f)) continue;
711 /* do_{upload,download} returned 0, the transfer is complete */
712 numeric(f->owner, 226, "Transfer complete.");
713 time(&(f->owner->last_transfer));
716 if (!f->dir_listing) {
723 update_display(first_conn);
727 return checked_through;
731 int do_upload(struct ftran *f)
733 char upload_buf[16384];
736 /* keep buffer size small in ascii transfers
737 to prevent process stalling while filtering
738 data on slower computers */
741 * This isn't a big problem, since we won't get
742 * packets this big anyway, the biggest I've seen
743 * was 12kB on 100mbit (but that was from a Windows
744 * machine), so I've reduced the buffer from 64 kB
745 * to 16 kB :-) --Steinar
747 const int maxlen = (f->ascii_mode == 1) ? 4096 : 16384;
749 const int maxlen = 16384;
753 size = recv(f->sock, upload_buf, maxlen, 0);
758 if (size > 0 && f->ascii_mode == 1) {
759 size = ascii_uploadfilter(upload_buf, size);
762 if (size > 0 && (write(f->local_file, upload_buf, size) == size)) {
764 } else if (size == -1) {
765 /* don't write xferlog... or? */
766 numeric(f->owner, 426, strerror(errno));
774 int do_download(struct ftran *f)
776 #if defined(TCP_CORK) && defined(SOL_TCP)
777 unsigned int zero = 0;
781 int more_to_send = 0;
784 char buf[MAX_BLOCK_SIZE];
787 char buf2[MAX_BLOCK_SIZE * 2];
791 #if HAVE_LINUX_SENDFILE
793 * We handle the optimal case first, which is sendfile().
794 * Here we use a rather simplified sending `algorithm',
795 * leaving most of the quirks to the system calls.
797 if (sendfile_supported == 1 && f->dir_listing == 0) {
799 size = f->size - f->pos;
801 if (size > f->block_size) size = f->block_size;
802 if (size < 0) size = 0;
805 if (size != f->block_size) {
806 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
810 err = sendfile(f->sock, f->local_file, &f->pos, size);
811 return (f->pos < f->size) && (err > -1);
816 size = f->size - f->pos;
818 if (size > f->block_size) size = f->block_size;
819 if (size < 0) size = 0;
821 bytes_to_send = size;
822 sendfrom_buf = f->file_data + f->pos;
824 bytes_to_send = read(f->local_file, buf, f->block_size);
828 if (bytes_to_send == f->block_size) more_to_send = 1;
831 if (f->ascii_mode == 1) {
832 bytes_to_send = ascii_downloadfilter(sendfrom_buf,
833 buf2, bytes_to_send);
836 #endif /* WANT_ASCII */
838 #if defined(TCP_CORK) && defined(SOL_TCP)
839 /* if we believe this is the last packet, unset TCP_CORK */
840 if (more_to_send == 0) {
841 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
845 size = send(f->sock, sendfrom_buf, bytes_to_send, 0);
846 if (size < bytes_to_send) more_to_send = 1;
849 if (f->ascii_mode == 1 && size < bytes_to_send && size > 0) {
850 size = ascii_findlength(sendfrom_buf, size);
855 if (size > 0) f->pos += size;
862 void write_xferlog(struct ftran *f)
865 time_t now = time(NULL);
866 struct tm *t = localtime(&now);
868 if (xferlog == NULL) return;
870 strftime(temp, 256, "%a %b %d %H:%M:%S %Y", t);
872 fprintf(xferlog, "%s %u %s %lu %s b _ %c a %s ftp 0 * \n",
874 fprintf(xferlog, "%s %u %s %lu %s b _ o a %s ftp 0 *\n",
876 temp, (int)(difftime(now, f->tran_start)),
877 inet_ntoa(f->sin.sin_addr), f->size,
880 (f->upload) ? 'i' : 'o',
886 /* vim needs this to work properly :-( */
893 /* Reallocate the buggers constantly */
896 struct conn *c = first_conn;
897 int maxloops = MAXCLIENTS;
899 while (c && c->next_conn) {
900 struct conn *temp = malloc(sizeof(*temp));
902 *temp = *(c->next_conn);
903 if (temp->transfer) temp->transfer->owner = temp;
904 memset(c->next_conn, 0, sizeof(struct conn));
910 assert(maxloops > 0);
916 * main(): Main function. Does the initialization, and contains
917 * the main server loop. Takes no command-line arguments
918 * (see README for justification).
925 /* the sets are declared globally if we use poll() */
927 fd_set fds, fds_send;
930 /*setlinebuf(stdout);*/
931 setvbuf(stdout, (char *)NULL, _IOLBF, 0);
933 signal(SIGPIPE, SIG_IGN);
935 printf("BetaFTPD version %s, Copyright (C) 1999-2000 Steinar H. Gunderson\n", VERSION);
936 puts("BetaFTPD comes with ABSOLUTELY NO WARRANTY; for details see the file");
937 puts("COPYING. This is free software, and you are welcome to redistribute it");
938 puts("under certain conditions; again see the file COPYING for details.");
941 /* we don't need stdin */
947 for (i = 0; i < FD_MAX; i++) {
953 FD_ZERO(&master_fds);
954 FD_ZERO(&master_send_fds);
957 server_sock = create_server_socket();
960 printf("%cc", (char)27); /* reset and clear the screen */
963 /* init dummy first connection */
964 first_conn = alloc_new_conn(-1);
965 first_ftran = alloc_new_ftran(0, NULL);
967 first_dcache = alloc_new_dcache();
972 #warning No xferlog support for nonroot yet
975 xferlog = fopen("/var/log/xferlog", "r+");
976 if (xferlog == NULL) xferlog = fopen("/usr/adm/xferlog", "r+");
978 if (xferlog != NULL) {
979 fseek(xferlog, 0L, SEEK_END);
988 puts("fork() failed, exiting");
993 puts("BetaFTPD forked into the background");
997 puts("BetaFTPD active");
1000 /* set timeout alarm here (after the fork) */
1002 signal(SIGALRM, handle_alarm);
1004 #if HAVE_LINUX_SENDFILE
1005 /* check that sendfile() is really implemented (same check as configure does) */
1007 int out_fd = 1, in_fd = 0;
1012 sendfile(out_fd, in_fd, &offset, size);
1013 if (errno == ENOSYS) sendfile_supported = 0;
1020 struct timeval timeout;
1023 /*screw_clients(); //look for memory errors */
1026 update_display(first_conn);
1030 i = poll(fds, highest_fds + 1, 60000);
1034 for (j=0; j<=highest_fds; j++) {
1035 if (fds[j].revents) printf("fds[%d].fd %d, .revents %x\n", j, fds[j].fd, fds[j].revents);
1040 /* reset fds (gets changed by select()) */
1042 fds_send = master_send_fds;
1045 * wait up to 60 secs for any activity
1047 timeout.tv_sec = 60;
1048 timeout.tv_usec = 0;
1050 i = select(FD_SETSIZE, &fds, &fds_send, NULL, &timeout);
1054 if (errno == EBADF) {
1056 /* don't like this, but we have to */
1057 clear_bad_fds(&server_sock);
1059 } else if (errno != EINTR) {
1070 /* fix an invalid server socket */
1071 if (fds[server_sock].revents & POLLERR) {
1072 del_fd(server_sock);
1073 server_sock = create_server_socket();
1077 /* remove any timed out sockets */
1078 if (time_to_check) {
1086 if (i <= 0) continue;
1089 i -= process_all_sendfiles(i);
1090 process_all_clients(i);
1092 /* sends are given highest `priority' */
1093 i -= process_all_sendfiles(&fds_send, i);
1095 /* incoming PASV connections and uploads */
1096 i -= process_all_sendfiles(&fds, i);
1099 * check the incoming PASV connections first, so
1100 * process_all_clients() won't be confused.
1102 process_all_clients(&fds, i);
1106 if (fds[server_sock].revents & POLLIN) {
1108 if (FD_ISSET(server_sock, &fds)) {
1110 accept_new_client(&server_sock);
1117 * accept_new_client():
1118 * Open a socket for the new client, say hello and put it in
1121 void accept_new_client(int * const server_sock)
1123 struct sockaddr_in tempaddr;
1124 int tempaddr_len = sizeof(tempaddr);
1125 const int tempsock = accept(*server_sock, (struct sockaddr *)&tempaddr, &tempaddr_len);
1127 static int num_err = 0;
1134 if ((errno == EBADF || errno == EPIPE) && ++num_err >= 3) {
1135 del_fd(*server_sock);
1136 *server_sock = create_server_socket();
1139 struct conn * const c = alloc_new_conn(tempsock);
1142 numeric(c, 220, "BetaFTPD " VERSION " ready.");
1144 memcpy(&(c->addr), &tempaddr, sizeof(struct sockaddr));
1151 * time_out_sockets():
1152 * Times out any socket that has not had any transfer
1153 * in the last 15 minutes (delay not customizable by FTP
1154 * user -- you must change it in ftpd.h).
1156 * Note that RFC959 explicitly states that there are no
1157 * `spontaneous' error replies, yet we have to do it to
1158 * get the message through at all.
1160 * If we check this list for every accept() call, it's
1161 * actually eating a lot of CPU time, so we only check
1162 * it every minute. We used to do a time() call here,
1163 * but we've changed to do use an alarm() call and set
1164 * the time_to_check_flag in the SIGALRM handler.
1166 RETSIGTYPE handle_alarm(int signum)
1172 signal(SIGALRM, handle_alarm);
1175 void time_out_sockets()
1177 struct conn *c = NULL, *next = first_conn->next_conn;
1178 time_t now = time(NULL);
1180 /* run through the linked list */
1181 while (next != NULL) {
1183 next = c->next_conn;
1185 if ((c->transfer == NULL || c->transfer->state != 5) &&
1186 (now - c->last_transfer > TIMEOUT_SECS)) {
1187 /* RFC violation? */
1188 numeric(c, 421, "Timeout (%u minutes): Closing control connection.", TIMEOUT_SECS/60);
1196 * time_out_dcache():
1197 * Time out expired directory listing cache entries.
1198 * Uses much of the same code as time_out_sockets().
1200 void time_out_dcache()
1202 struct dcache *d = NULL, *next = first_dcache->next_dcache;
1203 time_t now = time(NULL);
1205 /* run through the linked list */
1206 while (next != NULL) {
1208 next = d->next_dcache;
1210 if (d->use_count == 0 && (now - d->last_used > 900)) {
1219 * Remove some bytes from the incoming buffer. This gives
1220 * room for new data on the control connection, and should
1221 * be called when the code has finished using the data.
1222 * (This is done automatically for all commands, so you
1223 * normally need not worry about it.)
1225 void remove_bytes(struct conn * const c, const int num)
1227 if (c->buf_len <= num) {
1231 memmove(c->recv_buf, c->recv_buf + num, c->buf_len);
1236 * numeric(): Sends a numeric FTP reply to the client. Note that
1237 * you can use this command much the same way as you
1238 * would use a printf() (with all the normal %s, %d,
1239 * etc.), since it actually uses printf() internally.
1241 void numeric(struct conn * const c, const int numeric, const char * const format, ...)
1243 char buf[256], fmt[256];
1247 snprintf(fmt, 256, "%03u %s\r\n", numeric, format);
1249 va_start(args, format);
1250 i = vsnprintf(buf, 256, fmt, args);
1253 err = send(c->sock, buf, i, 0);
1254 if (err == -1 && errno == EPIPE) {
1260 * init_file_transfer():
1261 * Initiate a data connection for sending. This does not open
1262 * any files etc., just does whatever is needed for the socket,
1263 * if needed. It does, however, send the 150 reply to the client,
1264 * and mmap()s if needed.
1266 * Linux systems (others?) define SOL_TCP right away, which saves us
1267 * some grief and code size. Perhaps using getprotoent() is the `right'
1268 * way, but it's bigger :-) (Optionally, we could figure it out at
1269 * configure time, of course...)
1271 * For optimal speed, we use the Linux 2.2.x-only TCP_CORK flag if
1272 * possible. Note that this is only defined in the first `arm' --
1273 * we silently assume that Linux is the only OS supporting this
1274 * flag. This might be an over-generalization, but I it looks like
1275 * we'll have to depend on it other places as well, so we might
1276 * just as well be evil here.
1278 void init_file_transfer(struct ftran * const f)
1281 struct conn * const c = f->owner;
1282 const int mode = IPTOS_THROUGHPUT, zero = 0, one = 1;
1287 /* we want max throughput */
1288 setsockopt(f->sock, SOL_IP, IP_TOS, (void *)&mode, sizeof(mode));
1289 setsockopt(f->sock, SOL_TCP, TCP_NODELAY, (void *)&zero, sizeof(zero));
1291 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&one, sizeof(one));
1294 /* should these pointers be freed afterwards? */
1296 getprotoent(); /* legal? */
1298 const struct protoent * const pe_ip = getprotobyname("ip");
1299 const struct protoent * const pe_tcp = getprotobyname("tcp");
1300 setsockopt(f->sock, pe_ip->p_proto, IP_TOS, (void *)&mode, sizeof(mode));
1301 setsockopt(f->sock, pe_tcp->p_proto, TCP_NODELAY, (void *)&zero, sizeof(zero));
1307 if (f->dir_listing) {
1308 f->block_size = MAX_BLOCK_SIZE;
1311 f->ascii_mode = f->owner->ascii_mode;
1314 /* find the preferred block size */
1315 f->block_size = MAX_BLOCK_SIZE;
1316 if (fstat(f->local_file, &buf) != -1 &&
1317 buf.st_blksize < MAX_BLOCK_SIZE) {
1318 f->block_size = buf.st_blksize;
1329 #endif /* WANT_UPLOAD */
1331 TRAP_ERROR(add_fd(f->sock, events), 500, return);
1335 setsockopt(f->sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
1337 #if !HAVE_POLL && WANT_UPLOAD
1339 * if we let an upload socket stay in master_send_fds, we would
1340 * get data that would fool us into closing the socket... (sigh)
1343 FD_CLR(f->sock, &master_send_fds);
1344 FD_SET(f->sock, &master_fds);
1348 time(&(f->owner->last_transfer));
1350 if (f->dir_listing) {
1352 numeric(f->owner, 150, "Opening ASCII mode data connection for directory listing.");
1355 * slightly kludged -- perhaps we should kill the second arm,
1356 * at the expense of code size? Or perhaps we could collapse
1357 * the two possible replies into one?
1363 #endif /* WANT_UPLOAD */
1365 numeric(f->owner, 150, "Opening %s mode data connection for '%s'",
1366 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename);
1368 numeric(f->owner, 150, "Opening %s mode data connection for '%s' (%u bytes)",
1369 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename,
1372 #else /* !WANT_ASCII */
1375 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s'", f->filename);
1377 #endif /* WANT_UPLOAD */
1378 numeric(f->owner, 150, "Opening BINARY mode data connection for '%s' (%u bytes)", f->filename, f->size);
1379 #endif /* !WANT_ASCII */
1383 * This section _could_ in theory be more optimized, but it's
1384 * much easier this way, and hopefully, the compiler will be
1385 * intelligent enough to optimize most of this away. The idea
1386 * is, some modes _require_ use of mmap (or not). The preferred
1387 * thing is using mmap() when we don't have sendfile(), and not
1388 * using mmap() when we have sendfile().
1391 if (f->dir_listing == 0) {
1392 #if HAVE_LINUX_SENDFILE
1393 int do_mmap = (sendfile_supported) ? 0 : 1;
1398 if (f->ascii_mode == 1) do_mmap = 1;
1401 if (f->upload == 1) do_mmap = 0;
1405 f->file_data = mmap(NULL, f->size, PROT_READ, MAP_SHARED, f->local_file, 0);
1406 if (f->file_data == MAP_FAILED) f->file_data = NULL;
1408 f->file_data = NULL;
1410 f->pos = f->owner->rest_pos;
1412 #else /* !HAVE_MMAP */
1413 lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1418 * create_server_socket():
1419 * Create and bind a server socket, that we can use to
1420 * listen to new clients on.
1422 int create_server_socket()
1424 int server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1425 const unsigned int one = 1;
1426 struct sockaddr_in addr;
1430 * In the `perfect' world, if an address was in use, we could
1431 * just wait for the kernel to clear everything up, and everybody
1432 * would be happy. But when you just found out your server socket
1433 * was invalid, it has to be `re-made', and 3000 users are trying
1434 * to access your fileserver, I think it's nice that it comes
1435 * up right away... hence this option.
1437 setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1438 ioctl(server_sock, FIONBIO, &one); /* just in case */
1440 addr.sin_family = AF_INET;
1441 addr.sin_addr.s_addr = INADDR_ANY;
1442 addr.sin_port = htons(FTP_PORT);
1445 err = bind(server_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
1450 /* try to recover from recoverable errors... */
1451 if (errno == ENOMEM || errno == EADDRINUSE) {
1452 puts("Waiting 1 sec before trying again...");
1459 } while (err == -1);
1461 listen(server_sock, 20);
1463 err = add_fd(server_sock, POLLIN);
1475 * Try to find invalid socket descriptors, and clean them.
1476 * The methods used are rather UGLY, but I can't think of
1477 * any good way of checking e.g. server_sock without
1478 * doing anything to it :-(
1480 * poll() is able to do this in a much cleaner way, which
1481 * we use if we use poll(). That checking isn't done here,
1484 void clear_bad_fds(int * const server_sock)
1488 struct timeval tv = { 0, 0 };
1491 FD_SET(*server_sock, &fds);
1492 if (select(*server_sock, &fds, NULL, NULL, &tv) == -1) {
1493 FD_CLR(*server_sock, &master_fds);
1494 close(*server_sock);
1495 *server_sock = create_server_socket();
1499 /* could do this (conn, ftran) in any order */
1501 struct conn *c = NULL, *next = first_conn->next_conn;
1503 /* run through the linked list */
1504 while (next != NULL) {
1508 next = c->next_conn;
1510 if (read(c->sock, &buf, 0) == -1 &&
1518 struct ftran *f = NULL, *next = first_ftran->next_ftran;
1520 while (next != NULL) {
1524 next = f->next_ftran;
1526 if (read(f->sock, &buf, 0) == -1 &&
1537 * dump_file(): Dumps a file on the control connection. Used for
1538 * welcome messages and the likes. Note that outbuf
1539 * is so big, to prevent any crashing from users creating
1540 * weird .message files (like 1024 LFs)... The size of
1541 * the file is limited to 1024 bytes (by truncation).
1543 void dump_file(struct conn * const c, const int num, const char * const filename)
1545 char buf[1024], outbuf[5121];
1546 char *ptr = outbuf + 4;
1549 const int dumpfile = open(filename, O_RDONLY);
1550 if (dumpfile == -1) return;
1552 i = read(dumpfile, buf, 1024);
1558 sprintf(outbuf, "%03u-", num);
1561 if (buf[j] == '\n') {
1562 sprintf(ptr, "%03u-", num);
1568 send(c->sock, outbuf, ptr - outbuf, 0);
1575 * Lists all README file in the current (ie. OS current)
1576 * directory, in a 250- message.
1578 void list_readmes(struct conn * const c)
1581 const time_t now = time(NULL);
1584 if (glob("README*", 0, NULL, &pglob) != 0) return;
1586 for (i = 0; i < pglob.gl_pathc; i++) {
1591 if (stat(pglob.gl_pathv[i], &buf) == -1) continue;
1593 /* remove trailing LF */
1594 tm = ctime(&buf.st_mtime);
1595 tm[strlen(tm) - 1] = 0;
1597 snprintf(str, 256, "250-Please read the file %s\r\n"
1598 "250-\tIt was last modified %s - %ld days ago\r\n",
1599 pglob.gl_pathv[i], tm,
1600 (now - buf.st_mtime) / 86400);
1601 send(c->sock, str, strlen(str), 0);