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