]> git.sesse.net Git - betaftpd/blob - ftpd.c
2a84a715062c80c93f2d28cb93a976f95bc70a7b
[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         struct sockaddr tempaddr;
629         int tempaddr_len = sizeof(tempaddr);
630  
631         while (next != NULL && checked_through < num_ac) {
632                 f = next;
633                 next = f->next_ftran;
634
635 #if HAVE_UPLOAD
636                 if (f->upload == 1 && fds[f->sock].revents & POLLHUP) {
637                         finish_transfer(f);
638                         continue;
639                 }
640 #endif
641
642 #if HAVE_POLL
643                 if (fds[f->sock].revents & (POLLERR|POLLNVAL|POLLHUP)) {
644                         destroy_ftran(f);
645                         continue;
646                 }
647 #endif
648
649                 /* state = 2: incoming PASV, state >3: send file */
650 #if HAVE_POLL
651                 if ((f->state < 2) || (f->state == 3) || (fds[f->sock].revents & (POLLIN|POLLOUT)) == 0) {
652 #else
653                 if ((f->state < 2) || (f->state == 3) || !FD_ISSET(f->sock, active_clients)) {
654 #endif
655                         continue;
656                 }
657
658                 checked_through++;
659
660 #if HAVE_POLL
661                 /* Nothing is needed for the poll() version? */
662 #else
663                 FD_CLR(f->sock, active_clients);
664 #endif
665
666                 if (f->state == 2) {            /* incoming PASV */
667                         const unsigned int one = 1;
668                         const int tempsock = accept(f->sock, (struct sockaddr *)&tempaddr,
669                                                         &tempaddr_len);
670
671                         del_fd(f->sock);
672
673                         if (tempsock == -1) {
674                                 destroy_ftran(f);
675                                 continue;
676                         }
677
678                         f->sock = tempsock;
679                         ioctl(f->sock, FIONBIO, &one);
680                         init_file_transfer(f);
681 #if WANT_UPLOAD
682                         if (f->upload) continue;
683 #endif
684                 }
685                 if (f->state < 5) {
686                         init_file_transfer(f);
687 #if WANT_UPLOAD
688                         if (f->upload) continue;
689 #endif
690                 }
691
692                 /* for download, we send the first packets right away */
693 #if WANT_UPLOAD
694                 if (f->upload) {
695                         if (do_upload(f)) continue;
696                 } else
697 #endif
698                         if (do_download(f)) continue;
699
700                 /* do_{upload,download} returned 0, the transfer is complete */
701                 finish_transfer(f);
702 #if WANT_FULLSCREEN
703                 update_display(first_conn);
704 #endif
705         }
706
707         return checked_through;
708 }
709
710 #if WANT_UPLOAD
711 int do_upload(struct ftran *f)
712 {
713         char upload_buf[16384];
714         int size;
715 #if WANT_ASCII
716         /* keep buffer size small in ascii transfers 
717            to prevent process stalling while filtering
718            data on slower computers */
719
720         /* 
721          * This isn't a big problem, since we won't get
722          * packets this big anyway, the biggest I've seen
723          * was 12kB on 100mbit (but that was from a Windows
724          * machine), so I've reduced the buffer from 64 kB
725          * to 16 kB :-) --Steinar
726          */
727         const int maxlen = (f->ascii_mode == 1) ? 4096 : 16384;
728 #else
729         const int maxlen = 16384;
730 #endif
731
732         errno = 0;
733         size = recv(f->sock, upload_buf, maxlen, 0);
734         if (size >= 0) {
735                 f->pos += size;
736         }
737 #if WANT_ASCII
738         if (size > 0 && f->ascii_mode == 1) {
739                 size = ascii_uploadfilter(upload_buf, size);
740         }
741 #endif
742         if (size > 0 && (write(f->local_file, upload_buf, size) == size)) {
743                 return 1;
744         } else if (size == -1) {
745                 /* don't write xferlog... or? */
746                 numeric(f->owner, 426, strerror(errno));
747                 destroy_ftran(f);
748                 return 1;
749         }
750         return 0;
751
752 #endif
753
754 int do_download(struct ftran *f)
755 {
756 #if defined(TCP_CORK) && defined(SOL_TCP)
757         unsigned int zero = 0;
758 #endif
759         char *sendfrom_buf;
760         int bytes_to_send;
761         int more_to_send = 0;
762
763 #if !HAVE_MMAP
764         char buf[MAX_BLOCK_SIZE];
765 #endif
766 #if WANT_ASCII
767         char buf2[MAX_BLOCK_SIZE * 2];
768 #endif
769         int size;
770
771 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
772         /*
773          * We handle the optimal case first, which is sendfile().
774          * Here we use a rather simplified sending `algorithm',
775          * leaving most of the quirks to the system calls.
776          */
777         if (sendfile_supported == 1 && f->dir_listing == 0) {
778                 int err;
779                 size = f->size - f->pos;
780
781                 if (size > f->block_size) size = f->block_size;
782                 if (size < 0) size = 0;
783
784 #ifdef TCP_CORK
785                 if (size != f->block_size) {
786                         setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
787                 }       
788 #endif
789
790                 err = mysendfile(f->sock, f->local_file, &f->pos, size);
791                 return (f->pos < f->size) && (err > -1);
792         }
793 #endif
794
795 #if HAVE_MMAP
796         size = f->size - f->pos;
797
798         if (size > f->block_size) size = f->block_size;
799         if (size < 0) size = 0;
800
801         bytes_to_send = size;
802         sendfrom_buf = f->file_data + f->pos;
803 #else
804         bytes_to_send = read(f->local_file, buf, f->block_size);
805         sendfrom_buf = buf;
806 #endif
807
808         if (bytes_to_send == f->block_size) more_to_send = 1;
809
810 #if WANT_ASCII
811         if (f->ascii_mode == 1) {
812                 bytes_to_send = ascii_downloadfilter(sendfrom_buf,
813                                                      buf2, bytes_to_send);
814                 sendfrom_buf = buf2;
815         }
816 #endif /* WANT_ASCII */
817
818 #if defined(TCP_CORK) && defined(SOL_TCP)
819         /* if we believe this is the last packet, unset TCP_CORK */
820         if (more_to_send == 0) {
821                 setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&zero, sizeof(zero));
822         }
823 #endif
824
825         size = send(f->sock, sendfrom_buf, bytes_to_send, 0);
826         if (size < bytes_to_send) more_to_send = 1;
827
828 #if WANT_ASCII
829         if (f->ascii_mode == 1 && size < bytes_to_send && size > 0) {
830                 size = ascii_findlength(sendfrom_buf, size);
831         }
832 #endif
833
834 #if HAVE_MMAP
835         if (size > 0) f->pos += size;
836 #endif
837
838         return more_to_send;
839 }
840
841 #if WANT_XFERLOG
842 void write_xferlog(struct ftran *f)
843 {
844         char temp[256];
845         time_t now = time(NULL);
846         struct tm *t = localtime(&now);
847
848         if (xferlog == NULL) return;
849
850         strftime(temp, 256, "%a %b %d %H:%M:%S %Y", t);
851 #if WANT_UPLOAD
852         fprintf(xferlog, "%s %u %s %lu %s b _ %c a %s ftp 0 * \n",
853 #else
854         fprintf(xferlog, "%s %u %s %lu %s b _ o a %s ftp 0 *\n",
855 #endif
856                 temp, (int)(difftime(now, f->tran_start)),
857                 inet_ntoa(f->sin.sin_addr), f->size,
858                 f->filename,
859 #if WANT_UPLOAD
860                 (f->upload) ? 'i' : 'o',
861 #endif
862                 f->owner->username);
863         fflush(xferlog);
864
865 #if 0
866         /* vim needs this to work properly :-( */
867         )
868 #endif
869 }
870 #endif
871
872 #if 0
873 /* Reallocate the buggers constantly */
874 void screw_clients()
875 {
876         struct conn *c = first_conn;
877         int maxloops = MAXCLIENTS;
878
879         while (c && c->next_conn) {
880                 struct conn *temp = malloc(sizeof(*temp));
881                 if (!temp) break;
882                 *temp = *(c->next_conn);
883                 if (temp->transfer) temp->transfer->owner = temp;
884                 memset(c->next_conn, 0, sizeof(struct conn));
885                 free(c->next_conn);
886                 temp->prev_conn = c;
887                 c->next_conn = temp;
888                 c = c->next_conn;
889                 maxloops--;
890                 assert(maxloops > 0);
891         }
892 }
893 #endif
894
895 /*
896  * main():      Main function. Does the initialization, and contains
897  *              the main server loop. Takes no command-line arguments
898  *              (see README for justification).
899  */
900 int main(void)
901 {
902         int server_sock;
903
904 #if HAVE_POLL
905         /* the sets are declared globally if we use poll() */
906 #else
907         fd_set fds, fds_send;
908 #endif
909
910         /*setlinebuf(stdout);*/
911         setvbuf(stdout, (char *)NULL, _IOLBF, 0); 
912
913         signal(SIGPIPE, SIG_IGN);
914
915         printf("BetaFTPD version %s, Copyright (C) 1999-2000 Steinar H. Gunderson\n", VERSION);
916         puts("BetaFTPD comes with ABSOLUTELY NO WARRANTY; for details see the file");
917         puts("COPYING. This is free software, and you are welcome to redistribute it");
918         puts("under certain conditions; again see the file COPYING for details.");
919         puts("");
920
921         /* we don't need stdin */
922         close(0);
923
924 #if HAVE_POLL
925         {
926                 int i;
927                 for (i = 0; i < FD_MAX; i++) {
928                         fds[i].fd = -1;
929                         fds[i].events = 0;
930                 }
931         }
932 #else
933         FD_ZERO(&master_fds);
934         FD_ZERO(&master_send_fds);
935 #endif
936
937         server_sock = create_server_socket();
938
939 #if WANT_FULLSCREEN
940         printf("%cc", (char)27);        /* reset and clear the screen */
941 #endif
942
943         /* init dummy first connection */
944         first_conn = alloc_new_conn(-1);
945         first_ftran = alloc_new_ftran(0, NULL);
946 #if WANT_DCACHE
947         first_dcache = alloc_new_dcache();
948 #endif
949
950 #if WANT_XFERLOG
951 #if WANT_NONROOT
952 #warning No xferlog support for nonroot yet
953 #else
954         /* open xferlog */
955         xferlog = fopen("/var/log/xferlog", "r+");
956         if (xferlog == NULL) xferlog = fopen("/usr/adm/xferlog", "r+");
957
958         if (xferlog != NULL) {
959                  fseek(xferlog, 0L, SEEK_END);
960         }
961 #endif
962 #endif
963
964 #if WANT_FORK
965         switch (fork()) {
966         case -1:
967                 perror("fork()");
968                 puts("fork() failed, exiting");
969                 exit(0);
970         case 0:
971                 break;
972         default:
973                 puts("BetaFTPD forked into the background");
974                 exit(0);
975         }
976 #else
977         puts("BetaFTPD active");
978 #endif
979
980         /* set timeout alarm here (after the fork) */
981         alarm(60);
982         signal(SIGALRM, handle_alarm);
983
984 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
985         /* check that sendfile() is really implemented (same check as configure does) */
986         {
987                 int out_fd = 1, in_fd = 0;
988                 off_t offset = 0;
989                 size_t size = 1024;
990
991                 errno = 0;
992                 mysendfile(out_fd, in_fd, &offset, size);
993                 if (errno == ENOSYS) sendfile_supported = 0;
994         }
995 #endif
996
997         for ( ;; ) {
998                 int i;
999 #ifndef HAVE_POLL
1000                 struct timeval timeout;
1001 #endif
1002
1003                 /*screw_clients();       //look for memory errors */
1004
1005 #if WANT_FULLSCREEN
1006                 update_display(first_conn);
1007 #endif
1008
1009 #if HAVE_POLL
1010                 i = poll(fds, highest_fds + 1, 60000);
1011 #if 0
1012                 {
1013                         int j;
1014                         for (j=0; j<=highest_fds; j++) {
1015                                 if (fds[j].revents) printf("fds[%d].fd %d, .revents %x\n", j, fds[j].fd, fds[j].revents);
1016                         }
1017                 }
1018 #endif
1019 #else
1020                 /* reset fds (gets changed by select()) */
1021                 fds = master_fds;
1022                 fds_send = master_send_fds;
1023
1024                 /*
1025                  * wait up to 60 secs for any activity 
1026                  */
1027                 timeout.tv_sec = 60;
1028                 timeout.tv_usec = 0;
1029
1030                 i = select(FD_SETSIZE, &fds, &fds_send, NULL, &timeout);
1031 #endif
1032
1033                 if (i == -1) {
1034                         if (errno == EBADF) {
1035 #if !HAVE_POLL
1036                                 /* don't like this, but we have to */
1037                                 clear_bad_fds(&server_sock);
1038 #endif
1039                         } else if (errno != EINTR) {
1040 #if HAVE_POLL
1041                                 perror("poll()");
1042 #else
1043                                 perror("select()");
1044 #endif
1045                                 continue;
1046                         }
1047                 }
1048
1049 #if HAVE_POLL
1050                 /* fix an invalid server socket */
1051                 if (fds[server_sock].revents & POLLERR) {
1052                         del_fd(server_sock);
1053                         server_sock = create_server_socket();
1054                 }
1055 #endif
1056
1057                 /* remove any timed out sockets */
1058                 if (time_to_check) {
1059                         time_out_sockets();
1060 #if WANT_DCACHE
1061                         time_out_dcache();
1062 #endif
1063                         time_to_check = 0;
1064                 }
1065
1066                 if (i <= 0) continue;
1067
1068 #if HAVE_POLL
1069                 i -= process_all_sendfiles(i);
1070                 process_all_clients(i);
1071 #else
1072                 /* sends are given highest `priority' */
1073                 i -= process_all_sendfiles(&fds_send, i);
1074
1075                 /* incoming PASV connections and uploads */
1076                 i -= process_all_sendfiles(&fds, i);
1077
1078                 /*
1079                  * check the incoming PASV connections first, so
1080                  * process_all_clients() won't be confused.
1081                  */ 
1082                 process_all_clients(&fds, i);
1083 #endif
1084
1085 #if HAVE_POLL
1086                 if (fds[server_sock].revents & POLLIN) {
1087 #else
1088                 if (FD_ISSET(server_sock, &fds)) {
1089 #endif
1090                         accept_new_client(&server_sock);
1091                         i--;
1092                 }
1093         }
1094 }
1095
1096 /*
1097  * accept_new_client():
1098  *              Open a socket for the new client, say hello and put it in
1099  *              among the others.
1100  */
1101 void accept_new_client(int * const server_sock)
1102 {
1103         struct sockaddr_in tempaddr;
1104         int tempaddr_len = sizeof(tempaddr);
1105         const int tempsock = accept(*server_sock, (struct sockaddr *)&tempaddr, &tempaddr_len);
1106
1107         static int num_err = 0;
1108
1109         if (tempsock < 0) {
1110 #ifndef WANT_FORK
1111                 perror("accept()");
1112 #endif
1113                 close(tempsock);
1114                 if ((errno == EBADF || errno == EPIPE) && ++num_err >= 3) {
1115                         del_fd(*server_sock);
1116                         *server_sock = create_server_socket();
1117                 }
1118         } else {
1119                 struct conn * const c = alloc_new_conn(tempsock);
1120                 num_err = 0;
1121                 if (c != NULL) {
1122                         numeric(c, 220, "BetaFTPD " VERSION " ready.");
1123 #if WANT_STAT
1124                         memcpy(&(c->addr), &tempaddr, sizeof(struct sockaddr));
1125 #endif
1126                 }
1127         }
1128 }
1129
1130 /*
1131  * time_out_sockets():
1132  *              Times out any socket that has not had any transfer
1133  *              in the last 15 minutes (delay not customizable by FTP
1134  *              user -- you must change it in ftpd.h).
1135  *
1136  *              Note that RFC959 explicitly states that there are no
1137  *              `spontaneous' error replies, yet we have to do it to
1138  *              get the message through at all.
1139  *
1140  *              If we check this list for every accept() call, it's
1141  *              actually eating a lot of CPU time, so we only check
1142  *              it every minute. We used to do a time() call here,
1143  *              but we've changed to do use an alarm() call and set
1144  *              the time_to_check_flag in the SIGALRM handler.
1145  */
1146 RETSIGTYPE handle_alarm(int signum)
1147 {
1148         time_to_check = 1;
1149         alarm(60);
1150
1151         /* for libc5 */
1152         signal(SIGALRM, handle_alarm);
1153 }
1154
1155 void time_out_sockets()
1156 {
1157         struct conn *c = NULL, *next = first_conn->next_conn;
1158         time_t now = time(NULL);  
1159
1160         /* run through the linked list */
1161         while (next != NULL) {
1162                 c = next;
1163                 next = c->next_conn;
1164
1165                 if ((c->transfer == NULL || c->transfer->state != 5) &&
1166                     (now - c->last_transfer > TIMEOUT_SECS)) {
1167                         /* RFC violation? */
1168                         numeric(c, 421, "Timeout (%u minutes): Closing control connection.", TIMEOUT_SECS/60);
1169                         destroy_conn(c);
1170                 }
1171         }
1172 }
1173
1174 /*
1175  * remove_bytes():
1176  *              Remove some bytes from the incoming buffer. This gives
1177  *              room for new data on the control connection, and should
1178  *              be called when the code has finished using the data.
1179  *              (This is done automatically for all commands, so you
1180  *              normally need not worry about it.)
1181  */
1182 void remove_bytes(struct conn * const c, const int num)
1183 {
1184         if (c->buf_len <= num) {
1185                 c->buf_len = 0;
1186         } else {
1187                 c->buf_len -= num;
1188                 memmove(c->recv_buf, c->recv_buf + num, c->buf_len);
1189         }
1190 }
1191
1192 /*
1193  * numeric():   Sends a numeric FTP reply to the client. Note that
1194  *              you can use this command much the same way as you
1195  *              would use a printf() (with all the normal %s, %d,
1196  *              etc.), since it actually uses printf() internally.
1197  */
1198 void numeric(struct conn * const c, const int numeric, const char * const format, ...)
1199 {
1200         char buf[256], fmt[256];
1201         va_list args;
1202         int i, err;
1203
1204         snprintf(fmt, 256, "%03u %s\r\n", numeric, format);
1205
1206         va_start(args, format);
1207         i = vsnprintf(buf, 256, fmt, args);
1208         va_end(args);
1209
1210         err = send(c->sock, buf, i, 0);
1211         if (err == -1 && errno == EPIPE) {
1212                 destroy_conn(c);
1213         }
1214 }
1215
1216 /*
1217  * init_file_transfer():
1218  *              Initiate a data connection for sending. This does not open
1219  *              any files etc., just does whatever is needed for the socket,
1220  *              if needed. It does, however, send the 150 reply to the client,
1221  *              and mmap()s if needed.
1222  *
1223  *              Linux systems (others?) define SOL_TCP right away, which saves us
1224  *              some grief and code size. Perhaps using getprotoent() is the `right'
1225  *              way, but it's bigger :-) (Optionally, we could figure it out at
1226  *              configure time, of course...)
1227  *
1228  *              For optimal speed, we use the Linux 2.2.x-only TCP_CORK flag if
1229  *              possible. Note that this is only defined in the first `arm' --
1230  *              we silently assume that Linux is the only OS supporting this
1231  *              flag. This might be an over-generalization, but I it looks like
1232  *              we'll have to depend on it other places as well, so we might
1233  *              just as well be evil here.
1234  */
1235 void init_file_transfer(struct ftran * const f)
1236 {
1237         struct linger ling;
1238         struct conn * const c = f->owner;
1239         const int mode = IPTOS_THROUGHPUT, zero = 0, one = 1;
1240         struct stat buf;
1241         int events;
1242
1243 #ifdef SOL_TCP
1244         /* we want max throughput */
1245         setsockopt(f->sock, SOL_IP, IP_TOS, (void *)&mode, sizeof(mode));
1246         setsockopt(f->sock, SOL_TCP, TCP_NODELAY, (void *)&zero, sizeof(zero));
1247 #ifdef TCP_CORK
1248         setsockopt(f->sock, SOL_TCP, TCP_CORK, (void *)&one, sizeof(one));
1249 #endif
1250 #else
1251         /* should these pointers be freed afterwards? */
1252         {
1253                 getprotoent();  /* legal? */
1254                 {
1255                         const struct protoent * const pe_ip  = getprotobyname("ip");
1256                         const struct protoent * const pe_tcp = getprotobyname("tcp");
1257                         setsockopt(f->sock, pe_ip->p_proto, IP_TOS, (void *)&mode, sizeof(mode));
1258                         setsockopt(f->sock, pe_tcp->p_proto, TCP_NODELAY, (void *)&zero, sizeof(zero));
1259                 }
1260                 endprotoent();
1261         }
1262 #endif
1263
1264         if (f->dir_listing) {
1265                 f->block_size = MAX_BLOCK_SIZE;
1266         } else {
1267 #if WANT_ASCII
1268                 f->ascii_mode = f->owner->ascii_mode;
1269 #endif
1270
1271                 /* find the preferred block size */
1272                 f->block_size = MAX_BLOCK_SIZE;
1273                 if (fstat(f->local_file, &buf) != -1 &&
1274                     buf.st_blksize < MAX_BLOCK_SIZE) {
1275                         f->block_size = buf.st_blksize;
1276                 }
1277         }
1278
1279         f->state = 5;
1280
1281         events = POLLOUT;
1282 #if WANT_UPLOAD
1283         if (f->upload) {
1284                 events = POLLIN;
1285         }
1286 #endif /* WANT_UPLOAD */
1287
1288         TRAP_ERROR(add_fd(f->sock, events), 500, return);
1289
1290         ling.l_onoff = 0;
1291         ling.l_linger = 0;
1292         setsockopt(f->sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
1293
1294 #if !HAVE_POLL && WANT_UPLOAD
1295         /*
1296          * if we let an upload socket stay in master_send_fds, we would
1297          * get data that would fool us into closing the socket... (sigh)
1298          */
1299         if (f->upload) {
1300                 FD_CLR(f->sock, &master_send_fds);
1301                 FD_SET(f->sock, &master_fds);
1302         }
1303 #endif
1304
1305         time(&(f->owner->last_transfer));
1306         
1307         if (f->dir_listing) {
1308                 /* include size? */
1309                 numeric(f->owner, 150, "Opening ASCII mode data connection for directory listing.");
1310         } else {
1311                 /*
1312                  * slightly kludged -- perhaps we should kill the second arm,
1313                  * at the expense of code size? Or perhaps we could collapse
1314                  * the two possible replies into one?
1315                  */
1316 #if WANT_ASCII
1317                 if (f->ascii_mode
1318 #if WANT_UPLOAD
1319                         || f->upload
1320 #endif /* WANT_UPLOAD */
1321                 ) {
1322                         numeric(f->owner, 150, "Opening %s mode data connection for '%s'",
1323                                 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename);
1324                 } else {
1325                         numeric(f->owner, 150, "Opening %s mode data connection for '%s' (%u bytes)",
1326                                 (f->ascii_mode) ? "ASCII" : "BINARY", f->filename,
1327                                 f->size); 
1328                 }
1329 #else /* !WANT_ASCII */
1330 #if WANT_UPLOAD
1331                 if (f->upload) {
1332                         numeric(f->owner, 150, "Opening BINARY mode data connection for '%s'", f->filename);
1333                 } else
1334 #endif /* WANT_UPLOAD */
1335                         numeric(f->owner, 150, "Opening BINARY mode data connection for '%s' (%u bytes)", f->filename, f->size);
1336 #endif /* !WANT_ASCII */
1337         }
1338
1339         /*
1340          * This section _could_ in theory be more optimized, but it's
1341          * much easier this way, and hopefully, the compiler will be
1342          * intelligent enough to optimize most of this away. The idea
1343          * is, some modes _require_ use of mmap (or not). The preferred
1344          * thing is using mmap() when we don't have sendfile(), and not
1345          * using mmap() when we have sendfile().
1346          */
1347 #if HAVE_MMAP
1348         if (f->dir_listing == 0) {
1349 #if HAVE_LINUX_SENDFILE || HAVE_BSD_SENDFILE
1350                 int do_mmap = (sendfile_supported) ? 0 : 1;
1351 #else
1352                 int do_mmap = 1;
1353 #endif
1354 #if WANT_ASCII
1355                 if (f->ascii_mode == 1) do_mmap = 1;
1356 #endif
1357 #if WANT_UPLOAD
1358                 if (f->upload == 1) do_mmap = 0;
1359 #endif
1360  
1361                 if (do_mmap == 1) {
1362                         f->file_data = mmap(NULL, f->size, PROT_READ, MAP_SHARED, f->local_file, 0);
1363                         if (f->file_data == MAP_FAILED) f->file_data = NULL;
1364                 } else {
1365                         f->file_data = NULL;
1366                 }
1367                 f->pos = f->owner->rest_pos;
1368         }
1369 #else /* !HAVE_MMAP */
1370         lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1371 #endif
1372 }
1373
1374 /*
1375  * create_server_socket():
1376  *              Create and bind a server socket, that we can use to
1377  *              listen to new clients on.
1378  */
1379 int create_server_socket()
1380 {
1381         int server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1382         const unsigned int one = 1;
1383         struct sockaddr_in addr;
1384         int err;
1385         
1386         /*
1387          * In the `perfect' world, if an address was in use, we could
1388          * just wait for the kernel to clear everything up, and everybody
1389          * would be happy. But when you just found out your server socket
1390          * was invalid, it has to be `re-made', and 3000 users are trying
1391          * to access your fileserver, I think it's nice that it comes
1392          * up right away... hence this option.
1393          */
1394         setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
1395         ioctl(server_sock, FIONBIO, &one);      /* just in case */
1396
1397         addr.sin_family = AF_INET;
1398         addr.sin_addr.s_addr = INADDR_ANY;
1399         addr.sin_port = htons(FTP_PORT);
1400
1401         do {
1402                 err = bind(server_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
1403
1404                 if (err == -1) {
1405                         perror("bind()");
1406                 
1407                         /* try to recover from recoverable errors... */
1408                         if (errno == ENOMEM || errno == EADDRINUSE) {
1409                                 puts("Waiting 1 sec before trying again...");
1410                                 sleep(1);
1411                         } else {
1412                                 puts("Giving up.");
1413                                 exit(1); 
1414                         }
1415                 }
1416         } while (err == -1);
1417
1418         listen(server_sock, 20);
1419
1420         err = add_fd(server_sock, POLLIN);
1421         if (err) {
1422                 perror("add_fd");
1423                 return -1;
1424         }
1425
1426         return server_sock;
1427 }
1428
1429 #if !HAVE_POLL
1430 /*
1431  * clear_bad_fds():
1432  *              Try to find invalid socket descriptors, and clean them.
1433  *              The methods used are rather UGLY, but I can't think of
1434  *              any good way of checking e.g. server_sock without
1435  *              doing anything to it :-(
1436  *
1437  *              poll() is able to do this in a much cleaner way, which 
1438  *              we use if we use poll(). That checking isn't done here,
1439  *              though.
1440  */
1441 void clear_bad_fds(int * const server_sock)
1442 {
1443         {
1444                 fd_set fds;
1445                 struct timeval tv = { 0, 0 };
1446
1447                 FD_ZERO(&fds);
1448                 FD_SET(*server_sock, &fds); 
1449                 if (select(*server_sock, &fds, NULL, NULL, &tv) == -1) {
1450                         FD_CLR(*server_sock, &master_fds);
1451                         close(*server_sock);
1452                         *server_sock = create_server_socket();
1453                 }
1454         }
1455
1456         /* could do this (conn, ftran) in any order */
1457         {
1458                 struct conn *c = NULL, *next = first_conn->next_conn;
1459         
1460                 /* run through the linked list */
1461                 while (next != NULL) {
1462                         char buf[1];
1463
1464                         c = next;
1465                         next = c->next_conn;
1466
1467                         if (read(c->sock, &buf, 0) == -1 &&
1468                             errno == EBADF) {
1469                                 destroy_conn(c);
1470                         }
1471                 }
1472         }
1473
1474         {
1475                 struct ftran *f = NULL, *next = first_ftran->next_ftran;
1476         
1477                 while (next != NULL) {
1478                         char buf[1];
1479
1480                         f = next;
1481                         next = f->next_ftran;
1482
1483                         if (read(f->sock, &buf, 0) == -1 &&
1484                             errno == EBADF) {
1485                                 destroy_ftran(f);
1486                         }
1487                 }
1488         }       
1489 }
1490 #endif
1491
1492 #if HAVE_BSD_SENDFILE || HAVE_LINUX_SENDFILE
1493 int mysendfile(int sock, int fd, off_t *offset, size_t count)
1494 {
1495 #if HAVE_BSD_SENDFILE
1496         int err;
1497         off_t ssize = 0;
1498         
1499         err = sendfile(fd, sock, *offset, count, NULL, &ssize, 0);
1500         if (ssize > 0) *offset += ssize;
1501 #else /* !HAVE_BSD_SENDFILE */
1502 #if HAVE_LINUX_SENDFILE
1503         return sendfile(sock, fd, offset, count);
1504 #endif /* HAVE_LINUX_SENDFILE */
1505 #endif /* !HAVE_BSD_SENDFILE */
1506 }
1507 #endif /* HAVE_BSD_SENDFILE || HAVE_LINUX_SENDFILE */
1508
1509
1510 #if WANT_MESSAGE
1511 /*
1512  * dump_file(): Dumps a file on the control connection. Used for
1513  *              welcome messages and the likes. Note that outbuf
1514  *              is so big, to prevent any crashing from users creating
1515  *              weird .message files (like 1024 LFs)... The size of
1516  *              the file is limited to 1024 bytes (by truncation).
1517  */
1518 void dump_file(struct conn * const c, const int num, const char * const filename)
1519 {
1520         char buf[1024], outbuf[5121];
1521         char *ptr = outbuf + 4;
1522         int i, j = -1;
1523
1524         const int dumpfile = open(filename, O_RDONLY);
1525         if (dumpfile == -1) return;
1526
1527         i = read(dumpfile, buf, 1024);
1528         if (i <= 0) {
1529                 close(dumpfile);
1530                 return;
1531         }
1532
1533         sprintf(outbuf, "%03u-", num);
1534         while (++j < i) {
1535                 *ptr++ = buf[j];
1536                 if (buf[j] == '\n') {
1537                         sprintf(ptr, "%03u-", num);
1538                         ptr += 4;
1539                 }
1540         }
1541         *ptr++ = '\n';
1542
1543         send(c->sock, outbuf, ptr - outbuf, 0);
1544         close(dumpfile);
1545 }
1546
1547
1548 /*
1549  * list_readme():
1550  *              Lists all README file in the current (ie. OS current)
1551  *              directory, in a 250- message.
1552  */
1553 void list_readmes(struct conn * const c)
1554 {
1555         glob_t pglob;
1556         const time_t now = time(NULL);
1557         int i;
1558
1559         if (glob("README*", 0, NULL, &pglob) != 0) return;
1560
1561         for (i = 0; i < pglob.gl_pathc; i++) {
1562                 struct stat buf;
1563                 char str[256];
1564                 char *tm;
1565
1566                 if (stat(pglob.gl_pathv[i], &buf) == -1) continue;
1567
1568                 /* remove trailing LF */
1569                 tm = ctime(&buf.st_mtime);
1570                 tm[strlen(tm) - 1] = 0;
1571
1572                 snprintf(str, 256, "250-Please read the file %s\r\n"
1573                                    "250-\tIt was last modified %s - %ld days ago\r\n",
1574                         pglob.gl_pathv[i], tm,
1575                         (now - buf.st_mtime) / 86400);
1576                 send(c->sock, str, strlen(str), 0);
1577         }
1578         globfree(&pglob);
1579 }
1580 #endif
1581