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