]> git.sesse.net Git - betaftpd/blob - ftpd.c
Updated the version number to 0.0.8pre18 (forgot to do so upon the release of 0.0...
[betaftpd] / ftpd.c
1 /*  ftpd.c: BetaFTPD main
2     Copyright (C) 1999-2000 Steinar H. Gunderson
3
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.
7
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.
12
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.
16 */
17
18 /*
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
22  * to it. :-)
23  */
24
25 #define _GNU_SOURCE
26
27 #if HAVE_CONFIG_H
28 #include <config.h>
29 #endif
30
31 #if HAVE_ERRNO_H
32 #include <errno.h>
33 #endif
34
35 #if HAVE_STROPTS_H
36 #include <stropts.h>
37 #endif
38
39 #if HAVE_SYS_CONF_H
40 #include <sys/conf.h>
41 #endif
42
43 #if HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46
47 #if HAVE_STDIO_H
48 #include <stdio.h>
49 #endif
50
51 #if HAVE_ASSERT_H
52 #include <assert.h>
53 #endif
54
55 #if HAVE_STRING_H
56 #include <string.h>
57 #endif
58
59 #if HAVE_STRINGS_H
60 #include <strings.h>
61 #endif
62
63 #if HAVE_STDARG_H
64 #include <stdarg.h>
65 #endif
66
67 #if HAVE_STDLIB_H
68 #include <stdlib.h>
69 #endif
70
71 #if HAVE_UNISTD_H
72 #include <unistd.h>
73 #endif
74
75 #if HAVE_ARPA_INET_H
76 #include <arpa/inet.h>
77 #endif
78
79 #if HAVE_SYS_STAT_H
80 #include <sys/stat.h>
81 #endif
82
83 #if HAVE_SYS_IOCTL_H
84 #include <sys/ioctl.h>
85 #endif
86
87 #if HAVE_NETINET_IN_SYSTM_H
88 #include <netinet/in_systm.h>
89 #endif
90
91 #if HAVE_NETINET_IP_H
92 #include <netinet/ip.h>
93 #endif
94
95 #if HAVE_NETINET_TCP_H
96 #include <netinet/tcp.h>
97 #endif
98
99 #if HAVE_LINUX_SOCKET_H
100 #include <linux/socket.h>
101 #endif
102
103 #if HAVE_LINUX_TCP_H
104 #include <linux/tcp.h>
105 #endif
106
107 #if HAVE_MMAP
108 #include <sys/mman.h>
109 #endif
110
111 #if HAVE_TIME_H
112 #include <time.h>
113 #endif
114
115 #if HAVE_SYS_TIME_H
116 #include <sys/time.h>
117 #endif
118
119 #if HAVE_SYS_TIME_H
120 #include <sys/time.h>
121 #endif
122
123 #if HAVE_SYS_FILIO_H
124 #include <sys/filio.h>
125 #endif
126
127 #if HAVE_NETDB_H
128 #include <netdb.h>
129 #endif
130
131 #if HAVE_SIGNAL_H
132 #include <signal.h>
133 #endif
134
135 #if HAVE_GLOB_H
136 #include <glob.h>
137 #endif
138
139 #if HAVE_SYS_SIGNAL_H
140 #include <sys/signal.h>
141 #endif
142
143 #if HAVE_SYS_POLL_H
144 #include <sys/poll.h>
145 #endif
146
147 #if HAVE_SYS_SENDFILE_H
148 #include <sys/sendfile.h>
149 #endif
150
151 /*
152  * <linux/socket.h> does not export this to glibc2 systems, and it isn't
153  * always defined anywhere else.
154  */
155 #if !defined(TCP_CORK) && defined(__linux__)
156 #define TCP_CORK 3
157 #endif
158
159 #include <ftpd.h>
160 #include <cmds.h>
161
162 #if WANT_ASCII
163 #include <ascii.h>
164 #endif
165
166 #if WANT_DCACHE
167 #include <dcache.h>
168 #endif
169
170 #ifndef MAP_FAILED
171 #define MAP_FAILED -1
172 #endif
173
174 struct conn *first_conn = NULL;
175 struct ftran *first_ftran = NULL;
176 #if WANT_DCACHE
177 struct dcache *first_dcache = NULL;
178 #endif
179
180 #if HAVE_POLL
181 unsigned int highest_fds = 0;
182
183 #define FD_MAX 1024
184 #define fds_send fds
185 struct pollfd fds[FD_MAX];
186
187 #define MAXCLIENTS FD_MAX
188 #else
189 fd_set master_fds, master_send_fds;
190 #define MAXCLIENTS FD_SETSIZE
191 #endif
192
193 #if WANT_XFERLOG
194 FILE *xferlog = NULL;
195 #endif
196
197 #if HAVE_LINUX_SENDFILE
198 int sendfile_supported = 1;
199 #endif
200
201 /*
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.
206  */
207 int time_to_check = 1;
208
209 #ifndef HAVE_SPRINTF
210 /*
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.
217  */
218 int snprintf(char *str, size_t n, const char *format, ...)
219 {
220         char buf[8192];
221         va_list args;
222         int err;
223
224         va_start(args, format);
225         err = vsprintf(buf, format, args);
226         va_end(args);
227
228         buf[(int)n] = 0;
229         strcpy(str, buf);
230
231         return err;
232 }
233 #endif
234
235 #ifndef HAVE_VSNPRINTF
236 /*
237  * vsnprintf:   vsnprintf() replacement for systems that miss it. Please
238  *              see snprintf (above) for more information.
239  */
240 int vsnprintf(char *str, size_t n, const char *format, va_list ap)
241 {
242         char buf[8192];
243         int err;
244
245         err = vsprintf(buf, format, ap);
246         buf[(int)n] = 0;
247         strcpy(str, buf);
248         return err;
249 }
250 #endif
251
252 /*
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.
255  */
256 int add_fd(const int fd, const int events)
257 {
258 #if HAVE_POLL
259         if (fd >= FD_MAX) {
260                 printf("add_fd(%d, %x): failed\n", fd, events);
261                 return E2BIG;
262         }
263
264         fds[fd].fd = fd;
265         fds[fd].events = events;
266         if (highest_fds < fd) 
267                 highest_fds = fd;
268 #else 
269         if (fd >= FD_SETSIZE)
270                 return E2BIG;
271         if (events & POLLIN)
272                 FD_SET(fd, &master_fds);
273         if (events & POLLOUT)
274                 FD_SET(fd, &master_send_fds);
275 #endif
276         return 0;
277 }
278
279 /*
280  * del_fd():    Close and remove an fd from the set(s) we monitor. (See also add_fd().)
281  */
282 void del_fd(const int fd)
283 {
284 #if HAVE_POLL
285         if (fd >= FD_MAX)
286                 return;
287
288         fds[fd].fd = -1;
289         fds[fd].events = 0;
290
291         /* Reduce poll()'s workload by not making it watch past end of array */
292         while ((highest_fds > 0) && (fds[highest_fds].fd == -1))
293                 highest_fds--;
294 #else 
295         if (fd >= FD_SETSIZE)
296                 return;
297         FD_CLR(fd, &master_fds);
298         FD_CLR(fd, &master_send_fds);
299 #endif
300
301         close(fd);
302 }
303
304 #if 0
305 void list_clients()
306 {
307         struct conn *c = first_conn;
308         printf("list_clients:\n");
309         while (c && c->next_conn) {
310                 c = c->next_conn;
311                 printf("list_clients: fd %d\n", c->sock);
312         }
313 }
314 #endif
315
316 /*
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.
321  */
322 void add_to_linked_list(struct list_element * const first,
323                         struct list_element * const elem)
324 {
325         elem->prev = first;
326
327         if (first) {
328                 elem->next = first->next;
329                 if (elem->next) elem->next->prev = elem;
330                 first->next = elem;
331         } else {
332                 /* this is the bogus head of the list */
333                 elem->next = NULL;
334         }
335 }
336
337 /*
338  * remove_from_linked_list():
339  *              Removes an element (conn, ftran or dcache) from its linked list,
340  *              then frees it.
341  */
342 void remove_from_linked_list(struct list_element * const elem)
343 {
344         if (elem->prev != NULL) elem->prev->next = elem->next;
345         if (elem->next != NULL) elem->next->prev = elem->prev;
346         free(elem);
347 }
348
349 /*
350  * alloc_new_conn():
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.
354  */
355 struct conn *alloc_new_conn(const int sock)
356 {
357         const unsigned int one = 1;
358         struct conn *c = (struct conn *)(malloc(sizeof(struct conn)));
359
360         if (c == NULL) return c;
361
362         if (sock != -1) {
363                 ioctl(sock, FIONBIO, &one);
364                 if (add_fd(sock, POLLIN) != 0) {
365                         /* temp unavail */
366                         send(sock, "230 Server too busy, please try again later.\r\n", 46, 0);
367                         close(sock);
368                         return NULL;
369                 }
370
371                 add_to_linked_list((struct list_element *)first_conn,
372                                    (struct list_element *)c);
373         } else {
374                 /* this is the bogus head of the list */
375                 c->next_conn = NULL;
376                 c->prev_conn = NULL;
377         }
378
379         c->transfer = NULL;
380         c->sock = sock;
381         c->buf_len = c->auth = c->rest_pos = 0;
382 #if WANT_ASCII
383         c->ascii_mode = 0;
384 #endif
385
386         /*
387          * equals:
388          * strcpy(c->curr_dir, "/");
389          * strcpy(c->last_cmd, "");
390          * strcpy(c->rename_from, "")
391          */
392         c->curr_dir[0] = '/';
393 #if WANT_FULLSCREEN
394         c->curr_dir[1] = c->last_cmd[0] = c->rename_from[0] = '\0';
395 #else
396         c->curr_dir[1] = c->rename_from[0] = '\0';
397 #endif
398
399         time(&(c->last_transfer));
400
401         /*list_clients();*/
402
403         return c;
404 }
405
406 /*
407  * alloc_new_ftran():
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.
411  */
412 struct ftran *alloc_new_ftran(const int sock, const struct conn * const c)
413 {
414         struct ftran *f = (struct ftran *)(malloc(sizeof(struct ftran)));
415
416         if (f == NULL) return f;
417         if (c == NULL) {
418                 /* this is the bogus head of the list */
419                 f->next_ftran = NULL;
420                 f->prev_ftran = NULL;
421         } else {
422                 add_to_linked_list((struct list_element *)first_ftran,
423                                    (struct list_element *)f);
424         }
425
426 #if HAVE_MMAP
427         f->file_data = NULL;
428 #endif
429         f->owner = (struct conn * const)c;
430         f->sock = sock;
431         f->state = 0;
432         f->local_file = -1;
433
434 #if WANT_DCACHE
435         f->dir_cache = NULL;
436 #endif
437
438         f->dir_listing = 0;
439         return f;
440 }
441
442 /*
443  * destroy_conn():
444  *              Destroy a control connection, remove it from the linked
445  *              list, and clean up after it.
446  */
447 void destroy_conn(struct conn * const c)
448 {
449         if (c == NULL) return;
450         del_fd(c->sock);
451
452         destroy_ftran(c->transfer);
453         remove_from_linked_list((struct list_element *)c);
454 }
455
456 /*
457  * destroy_ftran():
458  *              Destroy a data connection, remove it from the linked list,
459  *              and clean up after it.
460  *
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.
465  *
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().
468  */
469 void destroy_ftran(struct ftran * const f)
470 {
471         const unsigned int zero = 0;
472
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));
476 #endif
477         del_fd(f->sock);
478
479 #if WANT_DCACHE
480         if (f->dir_cache) {
481                 time(&(f->dir_cache->last_used));
482                 f->dir_cache->use_count--;
483                 f->dir_cache = NULL;
484         } else
485 #endif
486 #if HAVE_MMAP
487                 if (f->file_data) {
488                         if (f->dir_listing) {
489                                 free(f->file_data);
490                                 f->file_data = NULL;
491                         } else {
492                                 munmap(f->file_data, f->size);
493                         }
494                 }
495
496         if (!f->dir_listing)
497 #endif
498                 if (f->local_file != -1) close(f->local_file);
499
500 #if !HAVE_MMAP
501         if (f->dir_listing) unlink(f->filename);
502 #endif
503
504         f->owner->transfer = NULL;
505
506 #if WANT_DCACHE
507         if (f->dir_cache != NULL) f->dir_cache->use_count--;
508 #endif
509
510         remove_from_linked_list((struct list_element *)f);
511 }
512
513 /*
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
519  *              entered.
520  */
521 #if HAVE_POLL
522 int process_all_clients(const int num_ac)
523 #else
524 int process_all_clients(const fd_set * const active_clients, const int num_ac)
525 #endif
526 {
527         struct conn *c = NULL, *next = first_conn->next_conn;
528         int checked_through = 0;
529
530         /* run through the linked list */
531         while (next != NULL && checked_through < num_ac) {
532                 int bytes_avail;
533
534                 c = next;
535                 next = c->next_conn;
536 #if HAVE_POLL
537                 if ((fds[c->sock].revents & (POLLIN|POLLERR|POLLHUP|POLLNVAL)) == 0) {
538                         continue;
539                 }
540 #else
541                 if (!FD_ISSET(c->sock, active_clients)) {
542                         continue;
543                 }
544 #endif
545
546                 checked_through++;
547
548                 bytes_avail = recv(c->sock, c->recv_buf + c->buf_len,
549                                    255 - c->buf_len, 0);
550                 if (bytes_avail <= 0) {
551                         /*
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.
556                          *
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).
561                          */
562                         destroy_conn(c);
563                         continue;
564                 }
565
566                 /* overrun = disconnect */
567                 if (c->buf_len + bytes_avail > 254) {
568                         numeric(c, 503, "Buffer overrun; disconnecting.");
569                         destroy_conn(c);
570                         continue;
571                 }
572
573                 c->buf_len += bytes_avail;
574                 parse_command(c);
575
576                 if (fds[c->sock].revents & (POLLERR|POLLHUP|POLLNVAL)) {
577                         destroy_conn(c);
578                 }
579         }
580         return checked_through;
581 }
582
583 /*
584  * finish_transfer():
585  *              Send a message that the transfer is completed, write xferlog
586  *              entry (optional), and update the last_transfer record in the
587  *              file transfer object. Goes for both uploads and downloads.
588  */
589 void finish_transfer(struct ftran * const f)
590 {
591         numeric(f->owner, 226, "Transfer complete.");
592         time(&(f->owner->last_transfer));
593
594 #if WANT_XFERLOG
595         if (!f->dir_listing) {
596                 write_xferlog(f);
597         }
598 #endif
599
600         destroy_ftran(f);
601 #if WANT_FULLSCREEN
602         update_display(first_conn);
603 #endif
604 }
605
606 /*
607  * process_all_sendfiles():
608  *              Sends data to all clients that are ready to receive it.
609  *              Also checks for data connections that are newly-connected,
610  *              and handler xferlog entries for the files that are finished.
611  */
612 #if HAVE_POLL
613 int process_all_sendfiles(const int num_ac)
614 #else
615 int process_all_sendfiles(fd_set * const active_clients, const int num_ac)
616 #endif
617 {
618         struct ftran *f = NULL, *next = first_ftran->next_ftran;
619         int checked_through = 0;
620         struct sockaddr tempaddr;
621         int tempaddr_len = sizeof(tempaddr);
622  
623         while (next != NULL && checked_through < num_ac) {
624                 f = next;
625                 next = f->next_ftran;
626
627 #if HAVE_UPLOAD
628                 if (f->upload == 1 && fds[f->sock].revents & POLLHUP) {
629                         finish_transfer(f);
630                         continue;
631                 }
632 #endif
633
634 #if HAVE_POLL
635                 if (fds[f->sock].revents & (POLLERR|POLLNVAL|POLLHUP)) {
636                         destroy_ftran(f);
637                         continue;
638                 }
639 #endif
640
641                 /* state = 2: incoming PASV, state >3: send file */
642 #if HAVE_POLL
643                 if ((f->state < 2) || (f->state == 3) || (fds[f->sock].revents & (POLLIN|POLLOUT)) == 0) {
644 #else
645                 if ((f->state < 2) || (f->state == 3) || !FD_ISSET(f->sock, active_clients)) {
646 #endif
647                         continue;
648                 }
649
650                 checked_through++;
651
652 #if HAVE_POLL
653                 /* Nothing is needed for the poll() version? */
654 #else
655                 FD_CLR(f->sock, active_clients);
656 #endif
657
658                 if (f->state == 2) {            /* incoming PASV */
659                         const unsigned int one = 1;
660                         const int tempsock = accept(f->sock, (struct sockaddr *)&tempaddr,
661                                                         &tempaddr_len);
662
663                         del_fd(f->sock);
664
665                         if (tempsock == -1) {
666                                 destroy_ftran(f);
667                                 continue;
668                         }
669
670                         f->sock = tempsock;
671                         ioctl(f->sock, FIONBIO, &one);
672                         init_file_transfer(f);
673 #if WANT_UPLOAD
674                         if (f->upload) continue;
675 #endif
676                 }
677                 if (f->state < 5) {
678                         init_file_transfer(f);
679 #if WANT_UPLOAD
680                         if (f->upload) continue;
681 #endif
682                 }
683
684                 /* for download, we send the first packets right away */
685 #if WANT_UPLOAD
686                 if (f->upload) {
687                         if (do_upload(f)) continue;
688                 } else
689 #endif
690                         if (do_download(f)) continue;
691
692                 /* do_{upload,download} returned 0, the transfer is complete */
693                 finish_transfer(f);
694 #if WANT_FULLSCREEN
695                 update_display(first_conn);
696 #endif
697         }
698
699         return checked_through;
700 }
701
702 #if WANT_UPLOAD
703 int do_upload(struct ftran *f)
704 {
705         char upload_buf[16384];
706         int size;
707 #if WANT_ASCII
708         /* keep buffer size small in ascii transfers 
709            to prevent process stalling while filtering
710            data on slower computers */
711
712         /* 
713          * This isn't a big problem, since we won't get
714          * packets this big anyway, the biggest I've seen
715          * was 12kB on 100mbit (but that was from a Windows
716          * machine), so I've reduced the buffer from 64 kB
717          * to 16 kB :-) --Steinar
718          */
719         const int maxlen = (f->ascii_mode == 1) ? 4096 : 16384;
720 #else
721         const int maxlen = 16384;
722 #endif
723
724         errno = 0;
725         size = recv(f->sock, upload_buf, maxlen, 0);
726         if (size >= 0) {
727                 f->pos += size;
728         }
729 #if WANT_ASCII
730         if (size > 0 && f->ascii_mode == 1) {
731                 size = ascii_uploadfilter(upload_buf, size);
732         }
733 #endif
734         if (size > 0 && (write(f->local_file, upload_buf, size) == size)) {
735                 return 1;
736         } else if (size == -1) {
737                 /* don't write xferlog... or? */
738                 numeric(f->owner, 426, strerror(errno));
739                 destroy_ftran(f);
740                 return 1;
741         }
742         return 0;
743
744 #endif
745
746 int do_download(struct ftran *f)
747 {
748 #if defined(TCP_CORK) && defined(SOL_TCP)
749         unsigned int zero = 0;
750 #endif
751         char *sendfrom_buf;
752         int bytes_to_send;
753         int more_to_send = 0;
754
755 #if !HAVE_MMAP
756         char buf[MAX_BLOCK_SIZE];
757 #endif
758 #if WANT_ASCII
759         char buf2[MAX_BLOCK_SIZE * 2];
760 #endif
761         int size;
762
763 #if HAVE_LINUX_SENDFILE
764         /*
765          * We handle the optimal case first, which is sendfile().
766          * Here we use a rather simplified sending `algorithm',
767          * leaving most of the quirks to the system calls.
768          */
769         if (sendfile_supported == 1 && f->dir_listing == 0) {
770                 int err;
771                 size = f->size - f->pos;
772
773                 if (size > f->block_size) size = f->block_size;
774                 if (size < 0) size = 0;
775
776 #ifdef TCP_CORK
777                 if (size != f->block_size) {
778                         setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
779                 }       
780 #endif
781
782                 err = sendfile(f->sock, f->local_file, &f->pos, size);
783                 return (f->pos < f->size) && (err > -1);
784         }
785 #endif
786
787 #if HAVE_MMAP
788         size = f->size - f->pos;
789
790         if (size > f->block_size) size = f->block_size;
791         if (size < 0) size = 0;
792
793         bytes_to_send = size;
794         sendfrom_buf = f->file_data + f->pos;
795 #else
796         bytes_to_send = read(f->local_file, buf, f->block_size);
797         sendfrom_buf = buf;
798 #endif
799
800         if (bytes_to_send == f->block_size) more_to_send = 1;
801
802 #if WANT_ASCII
803         if (f->ascii_mode == 1) {
804                 bytes_to_send = ascii_downloadfilter(sendfrom_buf,
805                                                      buf2, bytes_to_send);
806                 sendfrom_buf = buf2;
807         }
808 #endif /* WANT_ASCII */
809
810 #if defined(TCP_CORK) && defined(SOL_TCP)
811         /* if we believe this is the last packet, unset TCP_CORK */
812         if (more_to_send == 0) {
813                 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
814         }
815 #endif
816
817         size = send(f->sock, sendfrom_buf, bytes_to_send, 0);
818         if (size < bytes_to_send) more_to_send = 1;
819
820 #if WANT_ASCII
821         if (f->ascii_mode == 1 && size < bytes_to_send && size > 0) {
822                 size = ascii_findlength(sendfrom_buf, size);
823         }
824 #endif
825
826 #if HAVE_MMAP
827         if (size > 0) f->pos += size;
828 #endif
829
830         return more_to_send;
831 }
832
833 #if WANT_XFERLOG
834 void write_xferlog(struct ftran *f)
835 {
836         char temp[256];
837         time_t now = time(NULL);
838         struct tm *t = localtime(&now);
839
840         if (xferlog == NULL) return;
841
842         strftime(temp, 256, "%a %b %d %H:%M:%S %Y", t);
843 #if WANT_UPLOAD
844         fprintf(xferlog, "%s %u %s %lu %s b _ %c a %s ftp 0 * \n",
845 #else
846         fprintf(xferlog, "%s %u %s %lu %s b _ o a %s ftp 0 *\n",
847 #endif
848                 temp, (int)(difftime(now, f->tran_start)),
849                 inet_ntoa(f->sin.sin_addr), f->size,
850                 f->filename,
851 #if WANT_UPLOAD
852                 (f->upload) ? 'i' : 'o',
853 #endif
854                 f->owner->username);
855         fflush(xferlog);
856
857 #if 0
858         /* vim needs this to work properly :-( */
859         )
860 #endif
861 }
862 #endif
863
864 #if 0
865 /* Reallocate the buggers constantly */
866 void screw_clients()
867 {
868         struct conn *c = first_conn;
869         int maxloops = MAXCLIENTS;
870
871         while (c && c->next_conn) {
872                 struct conn *temp = malloc(sizeof(*temp));
873                 if (!temp) break;
874                 *temp = *(c->next_conn);
875                 if (temp->transfer) temp->transfer->owner = temp;
876                 memset(c->next_conn, 0, sizeof(struct conn));
877                 free(c->next_conn);
878                 temp->prev_conn = c;
879                 c->next_conn = temp;
880                 c = c->next_conn;
881                 maxloops--;
882                 assert(maxloops > 0);
883         }
884 }
885 #endif
886
887 /*
888  * main():      Main function. Does the initialization, and contains
889  *              the main server loop. Takes no command-line arguments
890  *              (see README for justification).
891  */
892 int main(void)
893 {
894         int server_sock;
895
896 #if HAVE_POLL
897         /* the sets are declared globally if we use poll() */
898 #else
899         fd_set fds, fds_send;
900 #endif
901
902         /*setlinebuf(stdout);*/
903         setvbuf(stdout, (char *)NULL, _IOLBF, 0); 
904
905         signal(SIGPIPE, SIG_IGN);
906
907         printf("BetaFTPD version %s, Copyright (C) 1999-2000 Steinar H. Gunderson\n", VERSION);
908         puts("BetaFTPD comes with ABSOLUTELY NO WARRANTY; for details see the file");
909         puts("COPYING. This is free software, and you are welcome to redistribute it");
910         puts("under certain conditions; again see the file COPYING for details.");
911         puts("");
912
913         /* we don't need stdin */
914         close(0);
915
916 #if HAVE_POLL
917         {
918                 int i;
919                 for (i = 0; i < FD_MAX; i++) {
920                         fds[i].fd = -1;
921                         fds[i].events = 0;
922                 }
923         }
924 #else
925         FD_ZERO(&master_fds);
926         FD_ZERO(&master_send_fds);
927 #endif
928
929         server_sock = create_server_socket();
930
931 #if WANT_FULLSCREEN
932         printf("%cc", (char)27);        /* reset and clear the screen */
933 #endif
934
935         /* init dummy first connection */
936         first_conn = alloc_new_conn(-1);
937         first_ftran = alloc_new_ftran(0, NULL);
938 #if WANT_DCACHE
939         first_dcache = alloc_new_dcache();
940 #endif
941
942 #if WANT_XFERLOG
943 #if WANT_NONROOT
944 #warning No xferlog support for nonroot yet
945 #else
946         /* open xferlog */
947         xferlog = fopen("/var/log/xferlog", "r+");
948         if (xferlog == NULL) xferlog = fopen("/usr/adm/xferlog", "r+");
949
950         if (xferlog != NULL) {
951                  fseek(xferlog, 0L, SEEK_END);
952         }
953 #endif
954 #endif
955
956 #if WANT_FORK
957         switch (fork()) {
958         case -1:
959                 perror("fork()");
960                 puts("fork() failed, exiting");
961                 exit(0);
962         case 0:
963                 break;
964         default:
965                 puts("BetaFTPD forked into the background");
966                 exit(0);
967         }
968 #else
969         puts("BetaFTPD active");
970 #endif
971
972         /* set timeout alarm here (after the fork) */
973         alarm(60);
974         signal(SIGALRM, handle_alarm);
975
976 #if HAVE_LINUX_SENDFILE
977         /* check that sendfile() is really implemented (same check as configure does) */
978         {
979                 int out_fd = 1, in_fd = 0;
980                 off_t offset = 0;
981                 size_t size = 1024;
982
983                 errno = 0;
984                 sendfile(out_fd, in_fd, &offset, size);
985                 if (errno == ENOSYS) sendfile_supported = 0;
986         }
987 #endif
988
989         for ( ;; ) {
990                 int i;
991 #ifndef HAVE_POLL
992                 struct timeval timeout;
993 #endif
994
995                 /*screw_clients();       //look for memory errors */
996
997 #if WANT_FULLSCREEN
998                 update_display(first_conn);
999 #endif
1000
1001 #if HAVE_POLL
1002                 i = poll(fds, highest_fds + 1, 60000);
1003 #if 0
1004                 {
1005                         int j;
1006                         for (j=0; j<=highest_fds; j++) {
1007                                 if (fds[j].revents) printf("fds[%d].fd %d, .revents %x\n", j, fds[j].fd, fds[j].revents);
1008                         }
1009                 }
1010 #endif
1011 #else
1012                 /* reset fds (gets changed by select()) */
1013                 fds = master_fds;
1014                 fds_send = master_send_fds;
1015
1016                 /*
1017                  * wait up to 60 secs for any activity 
1018                  */
1019                 timeout.tv_sec = 60;
1020                 timeout.tv_usec = 0;
1021
1022                 i = select(FD_SETSIZE, &fds, &fds_send, NULL, &timeout);
1023 #endif
1024
1025                 if (i == -1) {
1026                         if (errno == EBADF) {
1027 #if !HAVE_POLL
1028                                 /* don't like this, but we have to */
1029                                 clear_bad_fds(&server_sock);
1030 #endif
1031                         } else if (errno != EINTR) {
1032 #if HAVE_POLL
1033                                 perror("poll()");
1034 #else
1035                                 perror("select()");
1036 #endif
1037                                 continue;
1038                         }
1039                 }
1040
1041 #if HAVE_POLL
1042                 /* fix an invalid server socket */
1043                 if (fds[server_sock].revents & POLLERR) {
1044                         del_fd(server_sock);
1045                         server_sock = create_server_socket();
1046                 }
1047 #endif
1048
1049                 /* remove any timed out sockets */
1050                 if (time_to_check) {
1051                         time_out_sockets();
1052 #if WANT_DCACHE
1053                         time_out_dcache();
1054 #endif
1055                         time_to_check = 0;
1056                 }
1057
1058                 if (i <= 0) continue;
1059
1060 #if HAVE_POLL
1061                 i -= process_all_sendfiles(i);
1062                 process_all_clients(i);
1063 #else
1064                 /* sends are given highest `priority' */
1065                 i -= process_all_sendfiles(&fds_send, i);
1066
1067                 /* incoming PASV connections and uploads */
1068                 i -= process_all_sendfiles(&fds, i);
1069
1070                 /*
1071                  * check the incoming PASV connections first, so
1072                  * process_all_clients() won't be confused.
1073                  */ 
1074                 process_all_clients(&fds, i);
1075 #endif
1076
1077 #if HAVE_POLL
1078                 if (fds[server_sock].revents & POLLIN) {
1079 #else
1080                 if (FD_ISSET(server_sock, &fds)) {
1081 #endif
1082                         accept_new_client(&server_sock);
1083                         i--;
1084                 }
1085         }
1086 }
1087
1088 /*
1089  * accept_new_client():
1090  *              Open a socket for the new client, say hello and put it in
1091  *              among the others.
1092  */
1093 void accept_new_client(int * const server_sock)
1094 {
1095         struct sockaddr_in tempaddr;
1096         int tempaddr_len = sizeof(tempaddr);
1097         const int tempsock = accept(*server_sock, (struct sockaddr *)&tempaddr, &tempaddr_len);
1098
1099         static int num_err = 0;
1100
1101         if (tempsock < 0) {
1102 #ifndef WANT_FORK
1103                 perror("accept()");
1104 #endif
1105                 close(tempsock);
1106                 if ((errno == EBADF || errno == EPIPE) && ++num_err >= 3) {
1107                         del_fd(*server_sock);
1108                         *server_sock = create_server_socket();
1109                 }
1110         } else {
1111                 struct conn * const c = alloc_new_conn(tempsock);
1112                 num_err = 0;
1113                 if (c != NULL) {
1114                         numeric(c, 220, "BetaFTPD " VERSION " ready.");
1115 #if WANT_STAT
1116                         memcpy(&(c->addr), &tempaddr, sizeof(struct sockaddr));
1117 #endif
1118                 }
1119         }
1120 }
1121
1122 /*
1123  * time_out_sockets():
1124  *              Times out any socket that has not had any transfer
1125  *              in the last 15 minutes (delay not customizable by FTP
1126  *              user -- you must change it in ftpd.h).
1127  *
1128  *              Note that RFC959 explicitly states that there are no
1129  *              `spontaneous' error replies, yet we have to do it to
1130  *              get the message through at all.
1131  *
1132  *              If we check this list for every accept() call, it's
1133  *              actually eating a lot of CPU time, so we only check
1134  *              it every minute. We used to do a time() call here,
1135  *              but we've changed to do use an alarm() call and set
1136  *              the time_to_check_flag in the SIGALRM handler.
1137  */
1138 RETSIGTYPE handle_alarm(int signum)
1139 {
1140         time_to_check = 1;
1141         alarm(60);
1142
1143         /* for libc5 */
1144         signal(SIGALRM, handle_alarm);
1145 }
1146
1147 void time_out_sockets()
1148 {
1149         struct conn *c = NULL, *next = first_conn->next_conn;
1150         time_t now = time(NULL);  
1151
1152         /* run through the linked list */
1153         while (next != NULL) {
1154                 c = next;
1155                 next = c->next_conn;
1156
1157                 if ((c->transfer == NULL || c->transfer->state != 5) &&
1158                     (now - c->last_transfer > TIMEOUT_SECS)) {
1159                         /* RFC violation? */
1160                         numeric(c, 421, "Timeout (%u minutes): Closing control connection.", TIMEOUT_SECS/60);
1161                         destroy_conn(c);
1162                 }
1163         }
1164 }
1165
1166 /*
1167  * remove_bytes():
1168  *              Remove some bytes from the incoming buffer. This gives
1169  *              room for new data on the control connection, and should
1170  *              be called when the code has finished using the data.
1171  *              (This is done automatically for all commands, so you
1172  *              normally need not worry about it.)
1173  */
1174 void remove_bytes(struct conn * const c, const int num)
1175 {
1176         if (c->buf_len <= num) {
1177                 c->buf_len = 0;
1178         } else {
1179                 c->buf_len -= num;
1180                 memmove(c->recv_buf, c->recv_buf + num, c->buf_len);
1181         }
1182 }
1183
1184 /*
1185  * numeric():   Sends a numeric FTP reply to the client. Note that
1186  *              you can use this command much the same way as you
1187  *              would use a printf() (with all the normal %s, %d,
1188  *              etc.), since it actually uses printf() internally.
1189  */
1190 void numeric(struct conn * const c, const int numeric, const char * const format, ...)
1191 {
1192         char buf[256], fmt[256];
1193         va_list args;
1194         int i, err;
1195
1196         snprintf(fmt, 256, "%03u %s\r\n", numeric, format);
1197
1198         va_start(args, format);
1199         i = vsnprintf(buf, 256, fmt, args);
1200         va_end(args);
1201
1202         err = send(c->sock, buf, i, 0);
1203         if (err == -1 && errno == EPIPE) {
1204                 destroy_conn(c);
1205         }
1206 }
1207
1208 /*
1209  * init_file_transfer():
1210  *              Initiate a data connection for sending. This does not open
1211  *              any files etc., just does whatever is needed for the socket,
1212  *              if needed. It does, however, send the 150 reply to the client,
1213  *              and mmap()s if needed.
1214  *
1215  *              Linux systems (others?) define SOL_TCP right away, which saves us
1216  *              some grief and code size. Perhaps using getprotoent() is the `right'
1217  *              way, but it's bigger :-) (Optionally, we could figure it out at
1218  *              configure time, of course...)
1219  *
1220  *              For optimal speed, we use the Linux 2.2.x-only TCP_CORK flag if
1221  *              possible. Note that this is only defined in the first `arm' --
1222  *              we silently assume that Linux is the only OS supporting this
1223  *              flag. This might be an over-generalization, but I it looks like
1224  *              we'll have to depend on it other places as well, so we might
1225  *              just as well be evil here.
1226  */
1227 void init_file_transfer(struct ftran * const f)
1228 {
1229         struct linger ling;
1230         struct conn * const c = f->owner;
1231         const int mode = IPTOS_THROUGHPUT, zero = 0, one = 1;
1232         struct stat buf;
1233         int events;
1234
1235 #ifdef SOL_TCP
1236         /* we want max throughput */
1237         setsockopt(f->sock, SOL_IP, IP_TOS, (void *)&mode, sizeof(mode));
1238         setsockopt(f->sock, SOL_TCP, TCP_NODELAY, (void *)&zero, sizeof(zero));
1239 #ifdef TCP_CORK
1240         setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&one, sizeof(one));
1241 #endif
1242 #else
1243         /* should these pointers be freed afterwards? */
1244         {
1245                 getprotoent();  /* legal? */
1246                 {
1247                         const struct protoent * const pe_ip  = getprotobyname("ip");
1248                         const struct protoent * const pe_tcp = getprotobyname("tcp");
1249                         setsockopt(f->sock, pe_ip->p_proto, IP_TOS, (void *)&mode, sizeof(mode));
1250                         setsockopt(f->sock, pe_tcp->p_proto, TCP_NODELAY, (void *)&zero, sizeof(zero));
1251                 }
1252                 endprotoent();
1253         }
1254 #endif
1255
1256         if (f->dir_listing) {
1257                 f->block_size = MAX_BLOCK_SIZE;
1258         } else {
1259 #if WANT_ASCII
1260                 f->ascii_mode = f->owner->ascii_mode;
1261 #endif
1262
1263                 /* find the preferred block size */
1264                 f->block_size = MAX_BLOCK_SIZE;
1265                 if (fstat(f->local_file, &buf) != -1 &&
1266                     buf.st_blksize < MAX_BLOCK_SIZE) {
1267                         f->block_size = buf.st_blksize;
1268                 }
1269         }
1270
1271         f->state = 5;
1272
1273         events = POLLOUT;
1274 #if WANT_UPLOAD
1275         if (f->upload) {
1276                 events = POLLIN;
1277         }
1278 #endif /* WANT_UPLOAD */
1279
1280         TRAP_ERROR(add_fd(f->sock, events), 500, return);
1281
1282         ling.l_onoff = 0;
1283         ling.l_linger = 0;
1284         setsockopt(f->sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
1285
1286 #if !HAVE_POLL && WANT_UPLOAD
1287         /*
1288          * if we let an upload socket stay in master_send_fds, we would
1289          * get data that would fool us into closing the socket... (sigh)
1290          */
1291         if (f->upload) {
1292                 FD_CLR(f->sock, &master_send_fds);
1293                 FD_SET(f->sock, &master_fds);
1294         }
1295 #endif
1296
1297         time(&(f->owner->last_transfer));
1298         
1299         if (f->dir_listing) {
1300                 /* include size? */
1301                 numeric(f->owner, 150, "Opening ASCII mode data connection for directory listing.");
1302         } else {
1303                 /*
1304                  * slightly kludged -- perhaps we should kill the second arm,
1305                  * at the expense of code size? Or perhaps we could collapse
1306                  * the two possible replies into one?
1307                  */
1308 #if WANT_ASCII
1309                 if (f->ascii_mode
1310 #if WANT_UPLOAD
1311                         || f->upload
1312 #endif /* WANT_UPLOAD */
1313                 ) {
1314                         numeric(f->owner, 150, "Opening %s mode data connection for '%s'",
1315                                 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename);
1316                 } else {
1317                         numeric(f->owner, 150, "Opening %s mode data connection for '%s' (%u bytes)",
1318                                 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename,
1319                                 f->size); 
1320                 }
1321 #else /* !WANT_ASCII */
1322 #if WANT_UPLOAD
1323                 if (f->upload) {
1324                         numeric(f->owner, 150, "Opening BINARY mode data connection for '%s'", f->filename);
1325                 } else
1326 #endif /* WANT_UPLOAD */
1327                         numeric(f->owner, 150, "Opening BINARY mode data connection for '%s' (%u bytes)", f->filename, f->size);
1328 #endif /* !WANT_ASCII */
1329         }
1330
1331         /*
1332          * This section _could_ in theory be more optimized, but it's
1333          * much easier this way, and hopefully, the compiler will be
1334          * intelligent enough to optimize most of this away. The idea
1335          * is, some modes _require_ use of mmap (or not). The preferred
1336          * thing is using mmap() when we don't have sendfile(), and not
1337          * using mmap() when we have sendfile().
1338          */
1339 #if HAVE_MMAP
1340         if (f->dir_listing == 0) {
1341 #if HAVE_LINUX_SENDFILE
1342                 int do_mmap = (sendfile_supported) ? 0 : 1;
1343 #else
1344                 int do_mmap = 1;
1345 #endif
1346 #if WANT_ASCII
1347                 if (f->ascii_mode == 1) do_mmap = 1;
1348 #endif
1349 #if WANT_UPLOAD
1350                 if (f->upload == 1) do_mmap = 0;
1351 #endif
1352  
1353                 if (do_mmap == 1) {
1354                         f->file_data = mmap(NULL, f->size, PROT_READ, MAP_SHARED, f->local_file, 0);
1355                         if (f->file_data == MAP_FAILED) f->file_data = NULL;
1356                 } else {
1357                         f->file_data = NULL;
1358                 }
1359                 f->pos = f->owner->rest_pos;
1360         }
1361 #else /* !HAVE_MMAP */
1362         lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1363 #endif
1364 }
1365
1366 /*
1367  * create_server_socket():
1368  *              Create and bind a server socket, that we can use to
1369  *              listen to new clients on.
1370  */
1371 int create_server_socket()
1372 {
1373         int server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1374         const unsigned int one = 1;
1375         struct sockaddr_in addr;
1376         int err;
1377         
1378         /*
1379          * In the `perfect' world, if an address was in use, we could
1380          * just wait for the kernel to clear everything up, and everybody
1381          * would be happy. But when you just found out your server socket
1382          * was invalid, it has to be `re-made', and 3000 users are trying
1383          * to access your fileserver, I think it's nice that it comes
1384          * up right away... hence this option.
1385          */
1386         setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1387         ioctl(server_sock, FIONBIO, &one);      /* just in case */
1388
1389         addr.sin_family = AF_INET;
1390         addr.sin_addr.s_addr = INADDR_ANY;
1391         addr.sin_port = htons(FTP_PORT);
1392
1393         do {
1394                 err = bind(server_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
1395
1396                 if (err == -1) {
1397                         perror("bind()");
1398                 
1399                         /* try to recover from recoverable errors... */
1400                         if (errno == ENOMEM || errno == EADDRINUSE) {
1401                                 puts("Waiting 1 sec before trying again...");
1402                                 sleep(1);
1403                         } else {
1404                                 puts("Giving up.");
1405                                 exit(1); 
1406                         }
1407                 }
1408         } while (err == -1);
1409
1410         listen(server_sock, 20);
1411
1412         err = add_fd(server_sock, POLLIN);
1413         if (err) {
1414                 perror("add_fd");
1415                 return -1;
1416         }
1417
1418         return server_sock;
1419 }
1420
1421 #if !HAVE_POLL
1422 /*
1423  * clear_bad_fds():
1424  *              Try to find invalid socket descriptors, and clean them.
1425  *              The methods used are rather UGLY, but I can't think of
1426  *              any good way of checking e.g. server_sock without
1427  *              doing anything to it :-(
1428  *
1429  *              poll() is able to do this in a much cleaner way, which 
1430  *              we use if we use poll(). That checking isn't done here,
1431  *              though.
1432  */
1433 void clear_bad_fds(int * const server_sock)
1434 {
1435         {
1436                 fd_set fds;
1437                 struct timeval tv = { 0, 0 };
1438
1439                 FD_ZERO(&fds);
1440                 FD_SET(*server_sock, &fds); 
1441                 if (select(*server_sock, &fds, NULL, NULL, &tv) == -1) {
1442                         FD_CLR(*server_sock, &master_fds);
1443                         close(*server_sock);
1444                         *server_sock = create_server_socket();
1445                 }
1446         }
1447
1448         /* could do this (conn, ftran) in any order */
1449         {
1450                 struct conn *c = NULL, *next = first_conn->next_conn;
1451         
1452                 /* run through the linked list */
1453                 while (next != NULL) {
1454                         char buf[1];
1455
1456                         c = next;
1457                         next = c->next_conn;
1458
1459                         if (read(c->sock, &buf, 0) == -1 &&
1460                             errno == EBADF) {
1461                                 destroy_conn(c);
1462                         }
1463                 }
1464         }
1465
1466         {
1467                 struct ftran *f = NULL, *next = first_ftran->next_ftran;
1468         
1469                 while (next != NULL) {
1470                         char buf[1];
1471
1472                         f = next;
1473                         next = f->next_ftran;
1474
1475                         if (read(f->sock, &buf, 0) == -1 &&
1476                             errno == EBADF) {
1477                                 destroy_ftran(f);
1478                         }
1479                 }
1480         }       
1481 }
1482 #endif
1483
1484 #if WANT_MESSAGE
1485 /*
1486  * dump_file(): Dumps a file on the control connection. Used for
1487  *              welcome messages and the likes. Note that outbuf
1488  *              is so big, to prevent any crashing from users creating
1489  *              weird .message files (like 1024 LFs)... The size of
1490  *              the file is limited to 1024 bytes (by truncation).
1491  */
1492 void dump_file(struct conn * const c, const int num, const char * const filename)
1493 {
1494         char buf[1024], outbuf[5121];
1495         char *ptr = outbuf + 4;
1496         int i, j = -1;
1497
1498         const int dumpfile = open(filename, O_RDONLY);
1499         if (dumpfile == -1) return;
1500
1501         i = read(dumpfile, buf, 1024);
1502         if (i <= 0) {
1503                 close(dumpfile);
1504                 return;
1505         }
1506
1507         sprintf(outbuf, "%03u-", num);
1508         while (++j < i) {
1509                 *ptr++ = buf[j];
1510                 if (buf[j] == '\n') {
1511                         sprintf(ptr, "%03u-", num);
1512                         ptr += 4;
1513                 }
1514         }
1515         *ptr++ = '\n';
1516
1517         send(c->sock, outbuf, ptr - outbuf, 0);
1518         close(dumpfile);
1519 }
1520
1521
1522 /*
1523  * list_readme():
1524  *              Lists all README file in the current (ie. OS current)
1525  *              directory, in a 250- message.
1526  */
1527 void list_readmes(struct conn * const c)
1528 {
1529         glob_t pglob;
1530         const time_t now = time(NULL);
1531         int i;
1532
1533         if (glob("README*", 0, NULL, &pglob) != 0) return;
1534
1535         for (i = 0; i < pglob.gl_pathc; i++) {
1536                 struct stat buf;
1537                 char str[256];
1538                 char *tm;
1539
1540                 if (stat(pglob.gl_pathv[i], &buf) == -1) continue;
1541
1542                 /* remove trailing LF */
1543                 tm = ctime(&buf.st_mtime);
1544                 tm[strlen(tm) - 1] = 0;
1545
1546                 snprintf(str, 256, "250-Please read the file %s\r\n"
1547                                    "250-\tIt was last modified %s - %ld days ago\r\n",
1548                         pglob.gl_pathv[i], tm,
1549                         (now - buf.st_mtime) / 86400);
1550                 send(c->sock, str, strlen(str), 0);
1551         }
1552         globfree(&pglob);
1553 }
1554 #endif
1555