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