1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #if 0
33 #ifndef lint
34 static char copyright[] =
35 "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
37 #endif /* not lint */
38 #endif
39
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94";
43 #endif
44 #endif /* not lint */
45
46 #include <sys/cdefs.h>
47 /*
48 * FTP server.
49 */
50 #include <sys/param.h>
51 #include <sys/ioctl.h>
52 #include <sys/mman.h>
53 #include <sys/socket.h>
54 #include <sys/stat.h>
55 #include <sys/time.h>
56 #include <sys/wait.h>
57
58 #include <netinet/in.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/ip.h>
61 #include <netinet/tcp.h>
62
63 #define FTP_NAMES
64 #include <arpa/ftp.h>
65 #include <arpa/inet.h>
66 #include <arpa/telnet.h>
67
68 #include <ctype.h>
69 #include <dirent.h>
70 #include <err.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <glob.h>
74 #include <limits.h>
75 #include <netdb.h>
76 #include <pwd.h>
77 #include <grp.h>
78 #include <signal.h>
79 #include <stdint.h>
80 #include <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <syslog.h>
84 #include <time.h>
85 #include <unistd.h>
86 #include <libutil.h>
87 #ifdef LOGIN_CAP
88 #include <login_cap.h>
89 #endif
90
91 #ifdef USE_PAM
92 #include <security/pam_appl.h>
93 #endif
94
95 #include "blacklist_client.h"
96 #include "pathnames.h"
97 #include "extern.h"
98
99 #include <stdarg.h>
100
101 static char version[] = "Version 6.00LS";
102 #undef main
103
104 union sockunion ctrl_addr;
105 union sockunion data_source;
106 union sockunion data_dest;
107 union sockunion his_addr;
108 union sockunion pasv_addr;
109
110 int daemon_mode;
111 int data;
112 int dataport;
113 int hostinfo = 1; /* print host-specific info in messages */
114 int logged_in;
115 struct passwd *pw;
116 char *homedir;
117 int ftpdebug;
118 int timeout = 900; /* timeout after 15 minutes of inactivity */
119 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
120 int logging;
121 int restricted_data_ports = 1;
122 int paranoid = 1; /* be extra careful about security */
123 int anon_only = 0; /* Only anonymous ftp allowed */
124 int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */
125 int guest;
126 int dochroot;
127 char *chrootdir;
128 int dowtmp = 1;
129 int stats;
130 int statfd = -1;
131 int type;
132 int form;
133 int stru; /* avoid C keyword */
134 int mode;
135 int usedefault = 1; /* for data transfers */
136 int pdata = -1; /* for passive mode */
137 int readonly = 0; /* Server is in readonly mode. */
138 int noepsv = 0; /* EPSV command is disabled. */
139 int noretr = 0; /* RETR command is disabled. */
140 int noguestretr = 0; /* RETR command is disabled for anon users. */
141 int noguestmkd = 0; /* MKD command is disabled for anon users. */
142 int noguestmod = 1; /* anon users may not modify existing files. */
143 int use_blacklist = 0;
144
145 off_t file_size;
146 off_t byte_count;
147 #if !defined(CMASK) || CMASK == 0
148 #undef CMASK
149 #define CMASK 027
150 #endif
151 int defumask = CMASK; /* default umask value */
152 char tmpline[7];
153 char *hostname;
154 int epsvall = 0;
155
156 #ifdef VIRTUAL_HOSTING
157 char *ftpuser;
158
159 static struct ftphost {
160 struct ftphost *next;
161 struct addrinfo *hostinfo;
162 char *hostname;
163 char *anonuser;
164 char *statfile;
165 char *welcome;
166 char *loginmsg;
167 } *thishost, *firsthost;
168
169 #endif
170 char remotehost[NI_MAXHOST];
171 char *ident = NULL;
172
173 static char wtmpid[20];
174
175 #ifdef USE_PAM
176 static int auth_pam(struct passwd**, const char*);
177 pam_handle_t *pamh = NULL;
178 #endif
179
180 char *pid_file = NULL; /* means default location to pidfile(3) */
181
182 /*
183 * Limit number of pathnames that glob can return.
184 * A limit of 0 indicates the number of pathnames is unlimited.
185 */
186 #define MAXGLOBARGS 16384
187 #
188
189 /*
190 * Timeout intervals for retrying connections
191 * to hosts that don't accept PORT cmds. This
192 * is a kludge, but given the problems with TCP...
193 */
194 #define SWAITMAX 90 /* wait at most 90 seconds */
195 #define SWAITINT 5 /* interval between retries */
196
197 int swaitmax = SWAITMAX;
198 int swaitint = SWAITINT;
199
200 #ifdef SETPROCTITLE
201 char proctitle[LINE_MAX]; /* initial part of title */
202 #endif /* SETPROCTITLE */
203
204 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
205 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
206 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
207
208 static volatile sig_atomic_t recvurg;
209 static int transflag; /* NB: for debugging only */
210
211 #define STARTXFER flagxfer(1)
212 #define ENDXFER flagxfer(0)
213
214 #define START_UNSAFE maskurg(1)
215 #define END_UNSAFE maskurg(0)
216
217 /* It's OK to put an `else' clause after this macro. */
218 #define CHECKOOB(action) \
219 if (recvurg) { \
220 recvurg = 0; \
221 if (myoob()) { \
222 ENDXFER; \
223 action; \
224 } \
225 }
226
227 #ifdef VIRTUAL_HOSTING
228 static void inithosts(int);
229 static void selecthost(union sockunion *);
230 #endif
231 static void ack(char *);
232 static void sigurg(int);
233 static void maskurg(int);
234 static void flagxfer(int);
235 static int myoob(void);
236 static int checkuser(char *, char *, int, char **, int *);
237 static FILE *dataconn(char *, off_t, char *);
238 static void dolog(struct sockaddr *);
239 static void end_login(void);
240 static FILE *getdatasock(char *);
241 static int guniquefd(char *, char **);
242 static void lostconn(int);
243 static void sigquit(int);
244 static int receive_data(FILE *, FILE *);
245 static int send_data(FILE *, FILE *, size_t, off_t, int);
246 static struct passwd *
247 sgetpwnam(char *);
248 static char *sgetsave(char *);
249 static void reapchild(int);
250 static void appendf(char **, char *, ...) __printflike(2, 3);
251 static void logcmd(char *, char *, char *, off_t);
252 static void logxfer(char *, off_t, time_t);
253 static char *doublequote(char *);
254 static int *socksetup(int, char *, const char *);
255
256 int
main(int argc,char * argv[],char ** envp)257 main(int argc, char *argv[], char **envp)
258 {
259 socklen_t addrlen;
260 int ch, on = 1, tos, s = STDIN_FILENO;
261 char *cp, line[LINE_MAX];
262 FILE *fd;
263 char *bindname = NULL;
264 const char *bindport = "ftp";
265 int family = AF_UNSPEC;
266 struct sigaction sa;
267
268 tzset(); /* in case no timezone database in ~ftp */
269 sigemptyset(&sa.sa_mask);
270 sa.sa_flags = SA_RESTART;
271
272 /*
273 * Prevent diagnostic messages from appearing on stderr.
274 * We run as a daemon or from inetd; in both cases, there's
275 * more reason in logging to syslog.
276 */
277 (void) freopen(_PATH_DEVNULL, "w", stderr);
278 opterr = 0;
279
280 /*
281 * LOG_NDELAY sets up the logging connection immediately,
282 * necessary for anonymous ftp's that chroot and can't do it later.
283 */
284 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
285
286 while ((ch = getopt(argc, argv,
287 "468a:ABdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) {
288 switch (ch) {
289 case '4':
290 family = (family == AF_INET6) ? AF_UNSPEC : AF_INET;
291 break;
292
293 case '6':
294 family = (family == AF_INET) ? AF_UNSPEC : AF_INET6;
295 break;
296
297 case '8':
298 assumeutf8 = 1;
299 break;
300
301 case 'a':
302 bindname = optarg;
303 break;
304
305 case 'A':
306 anon_only = 1;
307 break;
308
309 case 'B':
310 #ifdef USE_BLACKLIST
311 use_blacklist = 1;
312 #else
313 syslog(LOG_WARNING, "not compiled with USE_BLACKLIST support");
314 #endif
315 break;
316
317 case 'd':
318 ftpdebug++;
319 break;
320
321 case 'D':
322 daemon_mode++;
323 break;
324
325 case 'E':
326 noepsv = 1;
327 break;
328
329 case 'h':
330 hostinfo = 0;
331 break;
332
333 case 'l':
334 logging++; /* > 1 == extra logging */
335 break;
336
337 case 'm':
338 noguestmod = 0;
339 break;
340
341 case 'M':
342 noguestmkd = 1;
343 break;
344
345 case 'o':
346 noretr = 1;
347 break;
348
349 case 'O':
350 noguestretr = 1;
351 break;
352
353 case 'p':
354 pid_file = optarg;
355 break;
356
357 case 'P':
358 bindport = optarg;
359 break;
360
361 case 'r':
362 readonly = 1;
363 break;
364
365 case 'R':
366 paranoid = 0;
367 break;
368
369 case 'S':
370 stats++;
371 break;
372
373 case 't':
374 timeout = atoi(optarg);
375 if (maxtimeout < timeout)
376 maxtimeout = timeout;
377 break;
378
379 case 'T':
380 maxtimeout = atoi(optarg);
381 if (timeout > maxtimeout)
382 timeout = maxtimeout;
383 break;
384
385 case 'u':
386 {
387 long val = 0;
388
389 val = strtol(optarg, &optarg, 8);
390 if (*optarg != '\0' || val < 0)
391 syslog(LOG_WARNING, "bad value for -u");
392 else
393 defumask = val;
394 break;
395 }
396 case 'U':
397 restricted_data_ports = 0;
398 break;
399
400 case 'v':
401 ftpdebug++;
402 break;
403
404 case 'W':
405 dowtmp = 0;
406 break;
407
408 default:
409 syslog(LOG_WARNING, "unknown flag -%c ignored", optopt);
410 break;
411 }
412 }
413
414 /* handle filesize limit gracefully */
415 sa.sa_handler = SIG_IGN;
416 (void)sigaction(SIGXFSZ, &sa, NULL);
417
418 if (daemon_mode) {
419 int *ctl_sock, fd, maxfd = -1, nfds, i;
420 fd_set defreadfds, readfds;
421 pid_t pid;
422 struct pidfh *pfh;
423
424 if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) {
425 if (errno == EEXIST) {
426 syslog(LOG_ERR, "%s already running, pid %d",
427 getprogname(), (int)pid);
428 exit(1);
429 }
430 syslog(LOG_WARNING, "pidfile_open: %m");
431 }
432
433 /*
434 * Detach from parent.
435 */
436 if (daemon(1, 1) < 0) {
437 syslog(LOG_ERR, "failed to become a daemon");
438 exit(1);
439 }
440
441 if (pfh != NULL && pidfile_write(pfh) == -1)
442 syslog(LOG_WARNING, "pidfile_write: %m");
443
444 sa.sa_handler = reapchild;
445 (void)sigaction(SIGCHLD, &sa, NULL);
446
447 #ifdef VIRTUAL_HOSTING
448 inithosts(family);
449 #endif
450
451 /*
452 * Open a socket, bind it to the FTP port, and start
453 * listening.
454 */
455 ctl_sock = socksetup(family, bindname, bindport);
456 if (ctl_sock == NULL)
457 exit(1);
458
459 FD_ZERO(&defreadfds);
460 for (i = 1; i <= *ctl_sock; i++) {
461 FD_SET(ctl_sock[i], &defreadfds);
462 if (listen(ctl_sock[i], 32) < 0) {
463 syslog(LOG_ERR, "control listen: %m");
464 exit(1);
465 }
466 if (maxfd < ctl_sock[i])
467 maxfd = ctl_sock[i];
468 }
469
470 /*
471 * Loop forever accepting connection requests and forking off
472 * children to handle them.
473 */
474 while (1) {
475 FD_COPY(&defreadfds, &readfds);
476 nfds = select(maxfd + 1, &readfds, NULL, NULL, 0);
477 if (nfds <= 0) {
478 if (nfds < 0 && errno != EINTR)
479 syslog(LOG_WARNING, "select: %m");
480 continue;
481 }
482
483 pid = -1;
484 for (i = 1; i <= *ctl_sock; i++)
485 if (FD_ISSET(ctl_sock[i], &readfds)) {
486 addrlen = sizeof(his_addr);
487 fd = accept(ctl_sock[i],
488 (struct sockaddr *)&his_addr,
489 &addrlen);
490 if (fd == -1) {
491 syslog(LOG_WARNING,
492 "accept: %m");
493 continue;
494 }
495 switch (pid = fork()) {
496 case 0:
497 /* child */
498 (void) dup2(fd, s);
499 (void) dup2(fd, STDOUT_FILENO);
500 (void) close(fd);
501 for (i = 1; i <= *ctl_sock; i++)
502 close(ctl_sock[i]);
503 if (pfh != NULL)
504 pidfile_close(pfh);
505 goto gotchild;
506 case -1:
507 syslog(LOG_WARNING, "fork: %m");
508 /* FALLTHROUGH */
509 default:
510 close(fd);
511 }
512 }
513 }
514 } else {
515 addrlen = sizeof(his_addr);
516 if (getpeername(s, (struct sockaddr *)&his_addr, &addrlen) < 0) {
517 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
518 exit(1);
519 }
520
521 #ifdef VIRTUAL_HOSTING
522 if (his_addr.su_family == AF_INET6 &&
523 IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))
524 family = AF_INET;
525 else
526 family = his_addr.su_family;
527 inithosts(family);
528 #endif
529 }
530
531 gotchild:
532 sa.sa_handler = SIG_DFL;
533 (void)sigaction(SIGCHLD, &sa, NULL);
534
535 sa.sa_handler = sigurg;
536 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
537 (void)sigaction(SIGURG, &sa, NULL);
538
539 sigfillset(&sa.sa_mask); /* block all signals in handler */
540 sa.sa_flags = SA_RESTART;
541 sa.sa_handler = sigquit;
542 (void)sigaction(SIGHUP, &sa, NULL);
543 (void)sigaction(SIGINT, &sa, NULL);
544 (void)sigaction(SIGQUIT, &sa, NULL);
545 (void)sigaction(SIGTERM, &sa, NULL);
546
547 sa.sa_handler = lostconn;
548 (void)sigaction(SIGPIPE, &sa, NULL);
549
550 addrlen = sizeof(ctrl_addr);
551 if (getsockname(s, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
552 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
553 exit(1);
554 }
555 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
556 #ifdef VIRTUAL_HOSTING
557 /* select our identity from virtual host table */
558 selecthost(&ctrl_addr);
559 #endif
560 #ifdef IP_TOS
561 if (ctrl_addr.su_family == AF_INET)
562 {
563 tos = IPTOS_LOWDELAY;
564 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
565 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
566 }
567 #endif
568 /*
569 * Disable Nagle on the control channel so that we don't have to wait
570 * for peer's ACK before issuing our next reply.
571 */
572 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
573 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
574
575 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
576
577 (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid());
578
579 /* Try to handle urgent data inline */
580 #ifdef SO_OOBINLINE
581 if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
582 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
583 #endif
584
585 #ifdef F_SETOWN
586 if (fcntl(s, F_SETOWN, getpid()) == -1)
587 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
588 #endif
589 dolog((struct sockaddr *)&his_addr);
590 /*
591 * Set up default state
592 */
593 data = -1;
594 type = TYPE_A;
595 form = FORM_N;
596 stru = STRU_F;
597 mode = MODE_S;
598 tmpline[0] = '\0';
599
600 /* If logins are disabled, print out the message. */
601 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
602 while (fgets(line, sizeof(line), fd) != NULL) {
603 if ((cp = strchr(line, '\n')) != NULL)
604 *cp = '\0';
605 lreply(530, "%s", line);
606 }
607 (void) fflush(stdout);
608 (void) fclose(fd);
609 reply(530, "System not available.");
610 exit(0);
611 }
612 #ifdef VIRTUAL_HOSTING
613 fd = fopen(thishost->welcome, "r");
614 #else
615 fd = fopen(_PATH_FTPWELCOME, "r");
616 #endif
617 if (fd != NULL) {
618 while (fgets(line, sizeof(line), fd) != NULL) {
619 if ((cp = strchr(line, '\n')) != NULL)
620 *cp = '\0';
621 lreply(220, "%s", line);
622 }
623 (void) fflush(stdout);
624 (void) fclose(fd);
625 /* reply(220,) must follow */
626 }
627 #ifndef VIRTUAL_HOSTING
628 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
629 fatalerror("Ran out of memory.");
630 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
631 hostname[0] = '\0';
632 hostname[MAXHOSTNAMELEN - 1] = '\0';
633 #endif
634 if (hostinfo)
635 reply(220, "%s FTP server (%s) ready.", hostname, version);
636 else
637 reply(220, "FTP server ready.");
638 BLACKLIST_INIT();
639 for (;;)
640 (void) yyparse();
641 /* NOTREACHED */
642 }
643
644 static void
lostconn(int signo)645 lostconn(int signo)
646 {
647
648 if (ftpdebug)
649 syslog(LOG_DEBUG, "lost connection");
650 dologout(1);
651 }
652
653 static void
sigquit(int signo)654 sigquit(int signo)
655 {
656
657 syslog(LOG_ERR, "got signal %d", signo);
658 dologout(1);
659 }
660
661 #ifdef VIRTUAL_HOSTING
662 /*
663 * read in virtual host tables (if they exist)
664 */
665
666 static void
inithosts(int family)667 inithosts(int family)
668 {
669 int insert;
670 size_t len;
671 FILE *fp;
672 char *cp, *mp, *line;
673 char *hostname;
674 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
675 struct ftphost *hrp, *lhrp;
676 struct addrinfo hints, *res, *ai;
677
678 /*
679 * Fill in the default host information
680 */
681 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
682 fatalerror("Ran out of memory.");
683 if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0)
684 hostname[0] = '\0';
685 hostname[MAXHOSTNAMELEN - 1] = '\0';
686 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
687 fatalerror("Ran out of memory.");
688 hrp->hostname = hostname;
689 hrp->hostinfo = NULL;
690
691 memset(&hints, 0, sizeof(hints));
692 hints.ai_flags = AI_PASSIVE;
693 hints.ai_family = family;
694 hints.ai_socktype = SOCK_STREAM;
695 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
696 hrp->hostinfo = res;
697 hrp->statfile = _PATH_FTPDSTATFILE;
698 hrp->welcome = _PATH_FTPWELCOME;
699 hrp->loginmsg = _PATH_FTPLOGINMESG;
700 hrp->anonuser = "ftp";
701 hrp->next = NULL;
702 thishost = firsthost = lhrp = hrp;
703 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
704 int addrsize, gothost;
705 void *addr;
706 struct hostent *hp;
707
708 while ((line = fgetln(fp, &len)) != NULL) {
709 int i, hp_error;
710
711 /* skip comments */
712 if (line[0] == '#')
713 continue;
714 if (line[len - 1] == '\n') {
715 line[len - 1] = '\0';
716 mp = NULL;
717 } else {
718 if ((mp = malloc(len + 1)) == NULL)
719 fatalerror("Ran out of memory.");
720 memcpy(mp, line, len);
721 mp[len] = '\0';
722 line = mp;
723 }
724 cp = strtok(line, " \t");
725 /* skip empty lines */
726 if (cp == NULL)
727 goto nextline;
728 vhost = cp;
729
730 /* set defaults */
731 anonuser = "ftp";
732 statfile = _PATH_FTPDSTATFILE;
733 welcome = _PATH_FTPWELCOME;
734 loginmsg = _PATH_FTPLOGINMESG;
735
736 /*
737 * Preparse the line so we can use its info
738 * for all the addresses associated with
739 * the virtual host name.
740 * Field 0, the virtual host name, is special:
741 * it's already parsed off and will be strdup'ed
742 * later, after we know its canonical form.
743 */
744 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
745 if (*cp != '-' && (cp = strdup(cp)))
746 switch (i) {
747 case 1: /* anon user permissions */
748 anonuser = cp;
749 break;
750 case 2: /* statistics file */
751 statfile = cp;
752 break;
753 case 3: /* welcome message */
754 welcome = cp;
755 break;
756 case 4: /* login message */
757 loginmsg = cp;
758 break;
759 default: /* programming error */
760 abort();
761 /* NOTREACHED */
762 }
763
764 hints.ai_flags = AI_PASSIVE;
765 hints.ai_family = family;
766 hints.ai_socktype = SOCK_STREAM;
767 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
768 goto nextline;
769 for (ai = res; ai != NULL && ai->ai_addr != NULL;
770 ai = ai->ai_next) {
771
772 gothost = 0;
773 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
774 struct addrinfo *hi;
775
776 for (hi = hrp->hostinfo; hi != NULL;
777 hi = hi->ai_next)
778 if (hi->ai_addrlen == ai->ai_addrlen &&
779 memcmp(hi->ai_addr,
780 ai->ai_addr,
781 ai->ai_addr->sa_len) == 0) {
782 gothost++;
783 break;
784 }
785 if (gothost)
786 break;
787 }
788 if (hrp == NULL) {
789 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
790 goto nextline;
791 hrp->hostname = NULL;
792 insert = 1;
793 } else {
794 if (hrp->hostinfo && hrp->hostinfo != res)
795 freeaddrinfo(hrp->hostinfo);
796 insert = 0; /* host already in the chain */
797 }
798 hrp->hostinfo = res;
799
800 /*
801 * determine hostname to use.
802 * force defined name if there is a valid alias
803 * otherwise fallback to primary hostname
804 */
805 /* XXX: getaddrinfo() can't do alias check */
806 switch(hrp->hostinfo->ai_family) {
807 case AF_INET:
808 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
809 addrsize = sizeof(struct in_addr);
810 break;
811 case AF_INET6:
812 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
813 addrsize = sizeof(struct in6_addr);
814 break;
815 default:
816 /* should not reach here */
817 freeaddrinfo(hrp->hostinfo);
818 if (insert)
819 free(hrp); /*not in chain, can free*/
820 else
821 hrp->hostinfo = NULL; /*mark as blank*/
822 goto nextline;
823 /* NOTREACHED */
824 }
825 if ((hp = getipnodebyaddr(addr, addrsize,
826 hrp->hostinfo->ai_family,
827 &hp_error)) != NULL) {
828 if (strcmp(vhost, hp->h_name) != 0) {
829 if (hp->h_aliases == NULL)
830 vhost = hp->h_name;
831 else {
832 i = 0;
833 while (hp->h_aliases[i] &&
834 strcmp(vhost, hp->h_aliases[i]) != 0)
835 ++i;
836 if (hp->h_aliases[i] == NULL)
837 vhost = hp->h_name;
838 }
839 }
840 }
841 if (hrp->hostname &&
842 strcmp(hrp->hostname, vhost) != 0) {
843 free(hrp->hostname);
844 hrp->hostname = NULL;
845 }
846 if (hrp->hostname == NULL &&
847 (hrp->hostname = strdup(vhost)) == NULL) {
848 freeaddrinfo(hrp->hostinfo);
849 hrp->hostinfo = NULL; /* mark as blank */
850 if (hp)
851 freehostent(hp);
852 goto nextline;
853 }
854 hrp->anonuser = anonuser;
855 hrp->statfile = statfile;
856 hrp->welcome = welcome;
857 hrp->loginmsg = loginmsg;
858 if (insert) {
859 hrp->next = NULL;
860 lhrp->next = hrp;
861 lhrp = hrp;
862 }
863 if (hp)
864 freehostent(hp);
865 }
866 nextline:
867 if (mp)
868 free(mp);
869 }
870 (void) fclose(fp);
871 }
872 }
873
874 static void
selecthost(union sockunion * su)875 selecthost(union sockunion *su)
876 {
877 struct ftphost *hrp;
878 u_int16_t port;
879 #ifdef INET6
880 struct in6_addr *mapped_in6 = NULL;
881 #endif
882 struct addrinfo *hi;
883
884 #ifdef INET6
885 /*
886 * XXX IPv4 mapped IPv6 addr consideraton,
887 * specified in rfc2373.
888 */
889 if (su->su_family == AF_INET6 &&
890 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
891 mapped_in6 = &su->su_sin6.sin6_addr;
892 #endif
893
894 hrp = thishost = firsthost; /* default */
895 port = su->su_port;
896 su->su_port = 0;
897 while (hrp != NULL) {
898 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
899 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
900 thishost = hrp;
901 goto found;
902 }
903 #ifdef INET6
904 /* XXX IPv4 mapped IPv6 addr consideraton */
905 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
906 (memcmp(&mapped_in6->s6_addr[12],
907 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
908 sizeof(struct in_addr)) == 0)) {
909 thishost = hrp;
910 goto found;
911 }
912 #endif
913 }
914 hrp = hrp->next;
915 }
916 found:
917 su->su_port = port;
918 /* setup static variables as appropriate */
919 hostname = thishost->hostname;
920 ftpuser = thishost->anonuser;
921 }
922 #endif
923
924 /*
925 * Helper function for sgetpwnam().
926 */
927 static char *
sgetsave(char * s)928 sgetsave(char *s)
929 {
930 char *new = malloc(strlen(s) + 1);
931
932 if (new == NULL) {
933 reply(421, "Ran out of memory.");
934 dologout(1);
935 /* NOTREACHED */
936 }
937 (void) strcpy(new, s);
938 return (new);
939 }
940
941 /*
942 * Save the result of a getpwnam. Used for USER command, since
943 * the data returned must not be clobbered by any other command
944 * (e.g., globbing).
945 * NB: The data returned by sgetpwnam() will remain valid until
946 * the next call to this function. Its difference from getpwnam()
947 * is that sgetpwnam() is known to be called from ftpd code only.
948 */
949 static struct passwd *
sgetpwnam(char * name)950 sgetpwnam(char *name)
951 {
952 static struct passwd save;
953 struct passwd *p;
954
955 if ((p = getpwnam(name)) == NULL)
956 return (p);
957 if (save.pw_name) {
958 free(save.pw_name);
959 free(save.pw_passwd);
960 free(save.pw_class);
961 free(save.pw_gecos);
962 free(save.pw_dir);
963 free(save.pw_shell);
964 }
965 save = *p;
966 save.pw_name = sgetsave(p->pw_name);
967 save.pw_passwd = sgetsave(p->pw_passwd);
968 save.pw_class = sgetsave(p->pw_class);
969 save.pw_gecos = sgetsave(p->pw_gecos);
970 save.pw_dir = sgetsave(p->pw_dir);
971 save.pw_shell = sgetsave(p->pw_shell);
972 return (&save);
973 }
974
975 static int login_attempts; /* number of failed login attempts */
976 static int askpasswd; /* had user command, ask for passwd */
977 static char curname[MAXLOGNAME]; /* current USER name */
978
979 /*
980 * USER command.
981 * Sets global passwd pointer pw if named account exists and is acceptable;
982 * sets askpasswd if a PASS command is expected. If logged in previously,
983 * need to reset state. If name is "ftp" or "anonymous", the name is not in
984 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
985 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
986 * requesting login privileges. Disallow anyone who does not have a standard
987 * shell as returned by getusershell(). Disallow anyone mentioned in the file
988 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
989 */
990 void
user(char * name)991 user(char *name)
992 {
993 int ecode;
994 char *cp, *shell;
995
996 if (logged_in) {
997 if (guest) {
998 reply(530, "Can't change user from guest login.");
999 return;
1000 } else if (dochroot) {
1001 reply(530, "Can't change user from chroot user.");
1002 return;
1003 }
1004 end_login();
1005 }
1006
1007 guest = 0;
1008 #ifdef VIRTUAL_HOSTING
1009 pw = sgetpwnam(thishost->anonuser);
1010 #else
1011 pw = sgetpwnam("ftp");
1012 #endif
1013 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1014 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) ||
1015 (ecode != 0 && ecode != ENOENT))
1016 reply(530, "User %s access denied.", name);
1017 else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) ||
1018 (ecode != 0 && ecode != ENOENT))
1019 reply(530, "User %s access denied.", name);
1020 else if (pw != NULL) {
1021 guest = 1;
1022 askpasswd = 1;
1023 reply(331,
1024 "Guest login ok, send your email address as password.");
1025 } else
1026 reply(530, "User %s unknown.", name);
1027 if (!askpasswd && logging)
1028 syslog(LOG_NOTICE,
1029 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1030 return;
1031 }
1032 if (anon_only != 0) {
1033 reply(530, "Sorry, only anonymous ftp allowed.");
1034 return;
1035 }
1036
1037 if ((pw = sgetpwnam(name))) {
1038 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1039 shell = _PATH_BSHELL;
1040 setusershell();
1041 while ((cp = getusershell()) != NULL)
1042 if (strcmp(cp, shell) == 0)
1043 break;
1044 endusershell();
1045
1046 if (cp == NULL ||
1047 (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) ||
1048 (ecode != 0 && ecode != ENOENT))) {
1049 reply(530, "User %s access denied.", name);
1050 if (logging)
1051 syslog(LOG_NOTICE,
1052 "FTP LOGIN REFUSED FROM %s, %s",
1053 remotehost, name);
1054 pw = NULL;
1055 return;
1056 }
1057 }
1058 if (logging)
1059 strlcpy(curname, name, sizeof(curname));
1060
1061 reply(331, "Password required for %s.", name);
1062 askpasswd = 1;
1063 /*
1064 * Delay before reading passwd after first failed
1065 * attempt to slow down passwd-guessing programs.
1066 */
1067 if (login_attempts)
1068 sleep(login_attempts);
1069 }
1070
1071 /*
1072 * Check if a user is in the file "fname",
1073 * return a pointer to a malloc'd string with the rest
1074 * of the matching line in "residue" if not NULL.
1075 */
1076 static int
checkuser(char * fname,char * name,int pwset,char ** residue,int * ecode)1077 checkuser(char *fname, char *name, int pwset, char **residue, int *ecode)
1078 {
1079 FILE *fd;
1080 int found = 0;
1081 size_t len;
1082 char *line, *mp, *p;
1083
1084 if (ecode != NULL)
1085 *ecode = 0;
1086 if ((fd = fopen(fname, "r")) != NULL) {
1087 while (!found && (line = fgetln(fd, &len)) != NULL) {
1088 /* skip comments */
1089 if (line[0] == '#')
1090 continue;
1091 if (line[len - 1] == '\n') {
1092 line[len - 1] = '\0';
1093 mp = NULL;
1094 } else {
1095 if ((mp = malloc(len + 1)) == NULL)
1096 fatalerror("Ran out of memory.");
1097 memcpy(mp, line, len);
1098 mp[len] = '\0';
1099 line = mp;
1100 }
1101 /* avoid possible leading and trailing whitespace */
1102 p = strtok(line, " \t");
1103 /* skip empty lines */
1104 if (p == NULL)
1105 goto nextline;
1106 /*
1107 * if first chr is '@', check group membership
1108 */
1109 if (p[0] == '@') {
1110 int i = 0;
1111 struct group *grp;
1112
1113 if (p[1] == '\0') /* single @ matches anyone */
1114 found = 1;
1115 else {
1116 if ((grp = getgrnam(p+1)) == NULL)
1117 goto nextline;
1118 /*
1119 * Check user's default group
1120 */
1121 if (pwset && grp->gr_gid == pw->pw_gid)
1122 found = 1;
1123 /*
1124 * Check supplementary groups
1125 */
1126 while (!found && grp->gr_mem[i])
1127 found = strcmp(name,
1128 grp->gr_mem[i++])
1129 == 0;
1130 }
1131 }
1132 /*
1133 * Otherwise, just check for username match
1134 */
1135 else
1136 found = strcmp(p, name) == 0;
1137 /*
1138 * Save the rest of line to "residue" if matched
1139 */
1140 if (found && residue) {
1141 if ((p = strtok(NULL, "")) != NULL)
1142 p += strspn(p, " \t");
1143 if (p && *p) {
1144 if ((*residue = strdup(p)) == NULL)
1145 fatalerror("Ran out of memory.");
1146 } else
1147 *residue = NULL;
1148 }
1149 nextline:
1150 if (mp)
1151 free(mp);
1152 }
1153 (void) fclose(fd);
1154 } else if (ecode != NULL)
1155 *ecode = errno;
1156 return (found);
1157 }
1158
1159 /*
1160 * Terminate login as previous user, if any, resetting state;
1161 * used when USER command is given or login fails.
1162 */
1163 static void
end_login(void)1164 end_login(void)
1165 {
1166 #ifdef USE_PAM
1167 int e;
1168 #endif
1169
1170 (void) seteuid(0);
1171 #ifdef LOGIN_CAP
1172 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
1173 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
1174 LOGIN_SETENV));
1175 #endif
1176 if (logged_in && dowtmp)
1177 ftpd_logwtmp(wtmpid, NULL, NULL);
1178 pw = NULL;
1179 #ifdef USE_PAM
1180 if (pamh) {
1181 if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS)
1182 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1183 if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS)
1184 syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e));
1185 if ((e = pam_end(pamh, e)) != PAM_SUCCESS)
1186 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1187 pamh = NULL;
1188 }
1189 #endif
1190 logged_in = 0;
1191 guest = 0;
1192 dochroot = 0;
1193 }
1194
1195 #ifdef USE_PAM
1196
1197 /*
1198 * the following code is stolen from imap-uw PAM authentication module and
1199 * login.c
1200 */
1201 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1202
1203 struct cred_t {
1204 const char *uname; /* user name */
1205 const char *pass; /* password */
1206 };
1207 typedef struct cred_t cred_t;
1208
1209 static int
auth_conv(int num_msg,const struct pam_message ** msg,struct pam_response ** resp,void * appdata)1210 auth_conv(int num_msg, const struct pam_message **msg,
1211 struct pam_response **resp, void *appdata)
1212 {
1213 int i;
1214 cred_t *cred = (cred_t *) appdata;
1215 struct pam_response *reply;
1216
1217 reply = calloc(num_msg, sizeof *reply);
1218 if (reply == NULL)
1219 return PAM_BUF_ERR;
1220
1221 for (i = 0; i < num_msg; i++) {
1222 switch (msg[i]->msg_style) {
1223 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1224 reply[i].resp_retcode = PAM_SUCCESS;
1225 reply[i].resp = COPY_STRING(cred->uname);
1226 /* PAM frees resp. */
1227 break;
1228 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1229 reply[i].resp_retcode = PAM_SUCCESS;
1230 reply[i].resp = COPY_STRING(cred->pass);
1231 /* PAM frees resp. */
1232 break;
1233 case PAM_TEXT_INFO:
1234 case PAM_ERROR_MSG:
1235 reply[i].resp_retcode = PAM_SUCCESS;
1236 reply[i].resp = NULL;
1237 break;
1238 default: /* unknown message style */
1239 free(reply);
1240 return PAM_CONV_ERR;
1241 }
1242 }
1243
1244 *resp = reply;
1245 return PAM_SUCCESS;
1246 }
1247
1248 /*
1249 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1250 * authenticated, or 1 if not authenticated. If some sort of PAM system
1251 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1252 * function returns -1. This can be used as an indication that we should
1253 * fall back to a different authentication mechanism.
1254 */
1255 static int
auth_pam(struct passwd ** ppw,const char * pass)1256 auth_pam(struct passwd **ppw, const char *pass)
1257 {
1258 const char *tmpl_user;
1259 const void *item;
1260 int rval;
1261 int e;
1262 cred_t auth_cred = { (*ppw)->pw_name, pass };
1263 struct pam_conv conv = { &auth_conv, &auth_cred };
1264
1265 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1266 if (e != PAM_SUCCESS) {
1267 /*
1268 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1269 * if context creation has failed in the first place.
1270 */
1271 syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e));
1272 return -1;
1273 }
1274
1275 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1276 if (e != PAM_SUCCESS) {
1277 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1278 pam_strerror(pamh, e));
1279 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1280 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1281 }
1282 pamh = NULL;
1283 return -1;
1284 }
1285
1286 e = pam_authenticate(pamh, 0);
1287 switch (e) {
1288 case PAM_SUCCESS:
1289 /*
1290 * With PAM we support the concept of a "template"
1291 * user. The user enters a login name which is
1292 * authenticated by PAM, usually via a remote service
1293 * such as RADIUS or TACACS+. If authentication
1294 * succeeds, a different but related "template" name
1295 * is used for setting the credentials, shell, and
1296 * home directory. The name the user enters need only
1297 * exist on the remote authentication server, but the
1298 * template name must be present in the local password
1299 * database.
1300 *
1301 * This is supported by two various mechanisms in the
1302 * individual modules. However, from the application's
1303 * point of view, the template user is always passed
1304 * back as a changed value of the PAM_USER item.
1305 */
1306 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1307 PAM_SUCCESS) {
1308 tmpl_user = (const char *) item;
1309 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1310 *ppw = getpwnam(tmpl_user);
1311 } else
1312 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1313 pam_strerror(pamh, e));
1314 rval = 0;
1315 break;
1316
1317 case PAM_AUTH_ERR:
1318 case PAM_USER_UNKNOWN:
1319 case PAM_MAXTRIES:
1320 rval = 1;
1321 break;
1322
1323 default:
1324 syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e));
1325 rval = -1;
1326 break;
1327 }
1328
1329 if (rval == 0) {
1330 e = pam_acct_mgmt(pamh, 0);
1331 if (e != PAM_SUCCESS) {
1332 syslog(LOG_ERR, "pam_acct_mgmt: %s",
1333 pam_strerror(pamh, e));
1334 rval = 1;
1335 }
1336 }
1337
1338 if (rval != 0) {
1339 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1340 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1341 }
1342 pamh = NULL;
1343 }
1344 return rval;
1345 }
1346
1347 #endif /* USE_PAM */
1348
1349 void
pass(char * passwd)1350 pass(char *passwd)
1351 {
1352 int rval, ecode;
1353 FILE *fd;
1354 #ifdef LOGIN_CAP
1355 login_cap_t *lc = NULL;
1356 #endif
1357 #ifdef USE_PAM
1358 int e;
1359 #endif
1360 char *residue = NULL;
1361 char *xpasswd;
1362
1363 if (logged_in || askpasswd == 0) {
1364 reply(503, "Login with USER first.");
1365 return;
1366 }
1367 askpasswd = 0;
1368 if (!guest) { /* "ftp" is only account allowed no password */
1369 if (pw == NULL) {
1370 rval = 1; /* failure below */
1371 goto skip;
1372 }
1373 #ifdef USE_PAM
1374 rval = auth_pam(&pw, passwd);
1375 if (rval >= 0) {
1376 goto skip;
1377 }
1378 #endif
1379 xpasswd = crypt(passwd, pw->pw_passwd);
1380 if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0')
1381 xpasswd = ":";
1382 rval = strcmp(pw->pw_passwd, xpasswd);
1383 if (pw->pw_expire && time(NULL) >= pw->pw_expire)
1384 rval = 1; /* failure */
1385 skip:
1386 /*
1387 * If rval == 1, the user failed the authentication check
1388 * above. If rval == 0, either PAM or local authentication
1389 * succeeded.
1390 */
1391 if (rval) {
1392 reply(530, "Login incorrect.");
1393 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, STDIN_FILENO, "Login incorrect");
1394 if (logging) {
1395 syslog(LOG_NOTICE,
1396 "FTP LOGIN FAILED FROM %s",
1397 remotehost);
1398 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1399 "FTP LOGIN FAILED FROM %s, %s",
1400 remotehost, curname);
1401 }
1402 pw = NULL;
1403 if (login_attempts++ >= 5) {
1404 syslog(LOG_NOTICE,
1405 "repeated login failures from %s",
1406 remotehost);
1407 exit(0);
1408 }
1409 return;
1410 } else {
1411 BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, STDIN_FILENO, "Login successful");
1412 }
1413 }
1414 login_attempts = 0; /* this time successful */
1415 if (setegid(pw->pw_gid) < 0) {
1416 reply(550, "Can't set gid.");
1417 return;
1418 }
1419 /* May be overridden by login.conf */
1420 (void) umask(defumask);
1421 #ifdef LOGIN_CAP
1422 if ((lc = login_getpwclass(pw)) != NULL) {
1423 char remote_ip[NI_MAXHOST];
1424
1425 if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1426 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1427 NI_NUMERICHOST))
1428 *remote_ip = 0;
1429 remote_ip[sizeof(remote_ip) - 1] = 0;
1430 if (!auth_hostok(lc, remotehost, remote_ip)) {
1431 syslog(LOG_INFO|LOG_AUTH,
1432 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1433 pw->pw_name);
1434 reply(530, "Permission denied.");
1435 pw = NULL;
1436 return;
1437 }
1438 if (!auth_timeok(lc, time(NULL))) {
1439 reply(530, "Login not available right now.");
1440 pw = NULL;
1441 return;
1442 }
1443 }
1444 setusercontext(lc, pw, 0, LOGIN_SETALL &
1445 ~(LOGIN_SETRESOURCES | LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV));
1446 #else
1447 setlogin(pw->pw_name);
1448 (void) initgroups(pw->pw_name, pw->pw_gid);
1449 #endif
1450
1451 #ifdef USE_PAM
1452 if (pamh) {
1453 if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) {
1454 syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e));
1455 } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) {
1456 syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e));
1457 }
1458 }
1459 #endif
1460
1461 dochroot =
1462 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode)
1463 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1464 || login_getcapbool(lc, "ftp-chroot", 0)
1465 #endif
1466 ;
1467 /*
1468 * It is possible that checkuser() failed to open the chroot file.
1469 * If this is the case, report that logins are un-available, since we
1470 * have no way of checking whether or not the user should be chrooted.
1471 * We ignore ENOENT since it is not required that this file be present.
1472 */
1473 if (ecode != 0 && ecode != ENOENT) {
1474 reply(530, "Login not available right now.");
1475 return;
1476 }
1477 chrootdir = NULL;
1478
1479 /* Disable wtmp logging when chrooting. */
1480 if (dochroot || guest)
1481 dowtmp = 0;
1482 if (dowtmp)
1483 ftpd_logwtmp(wtmpid, pw->pw_name,
1484 (struct sockaddr *)&his_addr);
1485 logged_in = 1;
1486
1487 #ifdef LOGIN_CAP
1488 setusercontext(lc, pw, 0, LOGIN_SETRESOURCES);
1489 #endif
1490
1491 if (guest && stats && statfd < 0) {
1492 #ifdef VIRTUAL_HOSTING
1493 statfd = open(thishost->statfile, O_WRONLY|O_APPEND);
1494 #else
1495 statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND);
1496 #endif
1497 if (statfd < 0)
1498 stats = 0;
1499 }
1500
1501 /*
1502 * For a chrooted local user,
1503 * a) see whether ftpchroot(5) specifies a chroot directory,
1504 * b) extract the directory pathname from the line,
1505 * c) expand it to the absolute pathname if necessary.
1506 */
1507 if (dochroot && residue &&
1508 (chrootdir = strtok(residue, " \t")) != NULL) {
1509 if (chrootdir[0] != '/')
1510 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1511 else
1512 chrootdir = strdup(chrootdir); /* make it permanent */
1513 if (chrootdir == NULL)
1514 fatalerror("Ran out of memory.");
1515 }
1516 if (guest || dochroot) {
1517 /*
1518 * If no chroot directory set yet, use the login directory.
1519 * Copy it so it can be modified while pw->pw_dir stays intact.
1520 */
1521 if (chrootdir == NULL &&
1522 (chrootdir = strdup(pw->pw_dir)) == NULL)
1523 fatalerror("Ran out of memory.");
1524 /*
1525 * Check for the "/chroot/./home" syntax,
1526 * separate the chroot and home directory pathnames.
1527 */
1528 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1529 *(homedir++) = '\0'; /* wipe '/' */
1530 homedir++; /* skip '.' */
1531 } else {
1532 /*
1533 * We MUST do a chdir() after the chroot. Otherwise
1534 * the old current directory will be accessible as "."
1535 * outside the new root!
1536 */
1537 homedir = "/";
1538 }
1539 /*
1540 * Finally, do chroot()
1541 */
1542 if (chroot(chrootdir) < 0) {
1543 reply(550, "Can't change root.");
1544 goto bad;
1545 }
1546 __FreeBSD_libc_enter_restricted_mode();
1547 } else /* real user w/o chroot */
1548 homedir = pw->pw_dir;
1549 /*
1550 * Set euid *before* doing chdir() so
1551 * a) the user won't be carried to a directory that he couldn't reach
1552 * on his own due to no permission to upper path components,
1553 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1554 * (uid 0 has no root power over NFS if not mapped explicitly.)
1555 */
1556 if (seteuid(pw->pw_uid) < 0) {
1557 if (guest || dochroot) {
1558 fatalerror("Can't set uid.");
1559 } else {
1560 reply(550, "Can't set uid.");
1561 goto bad;
1562 }
1563 }
1564 /*
1565 * Do not allow the session to live if we're chroot()'ed and chdir()
1566 * fails. Otherwise the chroot jail can be escaped.
1567 */
1568 if (chdir(homedir) < 0) {
1569 if (guest || dochroot) {
1570 fatalerror("Can't change to base directory.");
1571 } else {
1572 if (chdir("/") < 0) {
1573 reply(550, "Root is inaccessible.");
1574 goto bad;
1575 }
1576 lreply(230, "No directory! Logging in with home=/.");
1577 }
1578 }
1579
1580 /*
1581 * Display a login message, if it exists.
1582 * N.B. reply(230,) must follow the message.
1583 */
1584 #ifdef VIRTUAL_HOSTING
1585 fd = fopen(thishost->loginmsg, "r");
1586 #else
1587 fd = fopen(_PATH_FTPLOGINMESG, "r");
1588 #endif
1589 if (fd != NULL) {
1590 char *cp, line[LINE_MAX];
1591
1592 while (fgets(line, sizeof(line), fd) != NULL) {
1593 if ((cp = strchr(line, '\n')) != NULL)
1594 *cp = '\0';
1595 lreply(230, "%s", line);
1596 }
1597 (void) fflush(stdout);
1598 (void) fclose(fd);
1599 }
1600 if (guest) {
1601 if (ident != NULL)
1602 free(ident);
1603 ident = strdup(passwd);
1604 if (ident == NULL)
1605 fatalerror("Ran out of memory.");
1606
1607 reply(230, "Guest login ok, access restrictions apply.");
1608 #ifdef SETPROCTITLE
1609 #ifdef VIRTUAL_HOSTING
1610 if (thishost != firsthost)
1611 snprintf(proctitle, sizeof(proctitle),
1612 "%s: anonymous(%s)/%s", remotehost, hostname,
1613 passwd);
1614 else
1615 #endif
1616 snprintf(proctitle, sizeof(proctitle),
1617 "%s: anonymous/%s", remotehost, passwd);
1618 setproctitle("%s", proctitle);
1619 #endif /* SETPROCTITLE */
1620 if (logging)
1621 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1622 remotehost, passwd);
1623 } else {
1624 if (dochroot)
1625 reply(230, "User %s logged in, "
1626 "access restrictions apply.", pw->pw_name);
1627 else
1628 reply(230, "User %s logged in.", pw->pw_name);
1629
1630 #ifdef SETPROCTITLE
1631 snprintf(proctitle, sizeof(proctitle),
1632 "%s: user/%s", remotehost, pw->pw_name);
1633 setproctitle("%s", proctitle);
1634 #endif /* SETPROCTITLE */
1635 if (logging)
1636 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1637 remotehost, pw->pw_name);
1638 }
1639 if (logging && (guest || dochroot))
1640 syslog(LOG_INFO, "session root changed to %s", chrootdir);
1641 #ifdef LOGIN_CAP
1642 login_close(lc);
1643 #endif
1644 if (residue)
1645 free(residue);
1646 return;
1647 bad:
1648 /* Forget all about it... */
1649 #ifdef LOGIN_CAP
1650 login_close(lc);
1651 #endif
1652 if (residue)
1653 free(residue);
1654 end_login();
1655 }
1656
1657 void
retrieve(char * cmd,char * name)1658 retrieve(char *cmd, char *name)
1659 {
1660 FILE *fin, *dout;
1661 struct stat st;
1662 int (*closefunc)(FILE *);
1663 time_t start;
1664 char line[BUFSIZ];
1665
1666 if (cmd == 0) {
1667 fin = fopen(name, "r"), closefunc = fclose;
1668 st.st_size = 0;
1669 } else {
1670 (void) snprintf(line, sizeof(line), cmd, name);
1671 name = line;
1672 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1673 st.st_size = -1;
1674 st.st_blksize = BUFSIZ;
1675 }
1676 if (fin == NULL) {
1677 if (errno != 0) {
1678 perror_reply(550, name);
1679 if (cmd == 0) {
1680 LOGCMD("get", name);
1681 }
1682 }
1683 return;
1684 }
1685 byte_count = -1;
1686 if (cmd == 0) {
1687 if (fstat(fileno(fin), &st) < 0) {
1688 perror_reply(550, name);
1689 goto done;
1690 }
1691 if (!S_ISREG(st.st_mode)) {
1692 /*
1693 * Never sending a raw directory is a workaround
1694 * for buggy clients that will attempt to RETR
1695 * a directory before listing it, e.g., Mozilla.
1696 * Preventing a guest from getting irregular files
1697 * is a simple security measure.
1698 */
1699 if (S_ISDIR(st.st_mode) || guest) {
1700 reply(550, "%s: not a plain file.", name);
1701 goto done;
1702 }
1703 st.st_size = -1;
1704 /* st.st_blksize is set for all descriptor types */
1705 }
1706 }
1707 if (restart_point) {
1708 if (type == TYPE_A) {
1709 off_t i, n;
1710 int c;
1711
1712 n = restart_point;
1713 i = 0;
1714 while (i++ < n) {
1715 if ((c=getc(fin)) == EOF) {
1716 perror_reply(550, name);
1717 goto done;
1718 }
1719 if (c == '\n')
1720 i++;
1721 }
1722 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1723 perror_reply(550, name);
1724 goto done;
1725 }
1726 }
1727 dout = dataconn(name, st.st_size, "w");
1728 if (dout == NULL)
1729 goto done;
1730 time(&start);
1731 send_data(fin, dout, st.st_blksize, st.st_size,
1732 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1733 if (cmd == 0 && guest && stats && byte_count > 0)
1734 logxfer(name, byte_count, start);
1735 (void) fclose(dout);
1736 data = -1;
1737 pdata = -1;
1738 done:
1739 if (cmd == 0)
1740 LOGBYTES("get", name, byte_count);
1741 (*closefunc)(fin);
1742 }
1743
1744 void
store(char * name,char * mode,int unique)1745 store(char *name, char *mode, int unique)
1746 {
1747 int fd;
1748 FILE *fout, *din;
1749 int (*closefunc)(FILE *);
1750
1751 if (*mode == 'a') { /* APPE */
1752 if (unique) {
1753 /* Programming error */
1754 syslog(LOG_ERR, "Internal: unique flag to APPE");
1755 unique = 0;
1756 }
1757 if (guest && noguestmod) {
1758 reply(550, "Appending to existing file denied.");
1759 goto err;
1760 }
1761 restart_point = 0; /* not affected by preceding REST */
1762 }
1763 if (unique) /* STOU overrides REST */
1764 restart_point = 0;
1765 if (guest && noguestmod) {
1766 if (restart_point) { /* guest STOR w/REST */
1767 reply(550, "Modifying existing file denied.");
1768 goto err;
1769 } else /* treat guest STOR as STOU */
1770 unique = 1;
1771 }
1772
1773 if (restart_point)
1774 mode = "r+"; /* so ASCII manual seek can work */
1775 if (unique) {
1776 if ((fd = guniquefd(name, &name)) < 0)
1777 goto err;
1778 fout = fdopen(fd, mode);
1779 } else
1780 fout = fopen(name, mode);
1781 closefunc = fclose;
1782 if (fout == NULL) {
1783 perror_reply(553, name);
1784 goto err;
1785 }
1786 byte_count = -1;
1787 if (restart_point) {
1788 if (type == TYPE_A) {
1789 off_t i, n;
1790 int c;
1791
1792 n = restart_point;
1793 i = 0;
1794 while (i++ < n) {
1795 if ((c=getc(fout)) == EOF) {
1796 perror_reply(550, name);
1797 goto done;
1798 }
1799 if (c == '\n')
1800 i++;
1801 }
1802 /*
1803 * We must do this seek to "current" position
1804 * because we are changing from reading to
1805 * writing.
1806 */
1807 if (fseeko(fout, 0, SEEK_CUR) < 0) {
1808 perror_reply(550, name);
1809 goto done;
1810 }
1811 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1812 perror_reply(550, name);
1813 goto done;
1814 }
1815 }
1816 din = dataconn(name, -1, "r");
1817 if (din == NULL)
1818 goto done;
1819 if (receive_data(din, fout) == 0) {
1820 if (unique)
1821 reply(226, "Transfer complete (unique file name:%s).",
1822 name);
1823 else
1824 reply(226, "Transfer complete.");
1825 }
1826 (void) fclose(din);
1827 data = -1;
1828 pdata = -1;
1829 done:
1830 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1831 (*closefunc)(fout);
1832 return;
1833 err:
1834 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1835 return;
1836 }
1837
1838 static FILE *
getdatasock(char * mode)1839 getdatasock(char *mode)
1840 {
1841 int on = 1, s, t, tries;
1842
1843 if (data >= 0)
1844 return (fdopen(data, mode));
1845
1846 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1847 if (s < 0)
1848 goto bad;
1849 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1850 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1851 /* anchor socket to avoid multi-homing problems */
1852 data_source = ctrl_addr;
1853 data_source.su_port = htons(dataport);
1854 (void) seteuid(0);
1855 for (tries = 1; ; tries++) {
1856 /*
1857 * We should loop here since it's possible that
1858 * another ftpd instance has passed this point and is
1859 * trying to open a data connection in active mode now.
1860 * Until the other connection is opened, we'll be getting
1861 * EADDRINUSE because no SOCK_STREAM sockets in the system
1862 * can share both local and remote addresses, localIP:20
1863 * and *:* in this case.
1864 */
1865 if (bind(s, (struct sockaddr *)&data_source,
1866 data_source.su_len) >= 0)
1867 break;
1868 if (errno != EADDRINUSE || tries > 10)
1869 goto bad;
1870 sleep(tries);
1871 }
1872 (void) seteuid(pw->pw_uid);
1873 #ifdef IP_TOS
1874 if (data_source.su_family == AF_INET)
1875 {
1876 on = IPTOS_THROUGHPUT;
1877 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1878 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1879 }
1880 #endif
1881 #ifdef TCP_NOPUSH
1882 /*
1883 * Turn off push flag to keep sender TCP from sending short packets
1884 * at the boundaries of each write().
1885 */
1886 on = 1;
1887 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1888 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1889 #endif
1890 return (fdopen(s, mode));
1891 bad:
1892 /* Return the real value of errno (close may change it) */
1893 t = errno;
1894 (void) seteuid(pw->pw_uid);
1895 (void) close(s);
1896 errno = t;
1897 return (NULL);
1898 }
1899
1900 static FILE *
dataconn(char * name,off_t size,char * mode)1901 dataconn(char *name, off_t size, char *mode)
1902 {
1903 char sizebuf[32];
1904 FILE *file;
1905 int retry = 0, tos, conerrno;
1906
1907 file_size = size;
1908 byte_count = 0;
1909 if (size != -1)
1910 (void) snprintf(sizebuf, sizeof(sizebuf),
1911 " (%jd bytes)", (intmax_t)size);
1912 else
1913 *sizebuf = '\0';
1914 if (pdata >= 0) {
1915 union sockunion from;
1916 socklen_t fromlen = ctrl_addr.su_len;
1917 int flags, s;
1918 struct timeval timeout;
1919 fd_set set;
1920
1921 FD_ZERO(&set);
1922 FD_SET(pdata, &set);
1923
1924 timeout.tv_usec = 0;
1925 timeout.tv_sec = 120;
1926
1927 /*
1928 * Granted a socket is in the blocking I/O mode,
1929 * accept() will block after a successful select()
1930 * if the selected connection dies in between.
1931 * Therefore set the non-blocking I/O flag here.
1932 */
1933 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1934 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1935 goto pdata_err;
1936 if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 ||
1937 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1938 goto pdata_err;
1939 (void) close(pdata);
1940 pdata = s;
1941 /*
1942 * Unset the inherited non-blocking I/O flag
1943 * on the child socket so stdio can work on it.
1944 */
1945 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1946 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1947 goto pdata_err;
1948 #ifdef IP_TOS
1949 if (from.su_family == AF_INET)
1950 {
1951 tos = IPTOS_THROUGHPUT;
1952 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1953 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1954 }
1955 #endif
1956 reply(150, "Opening %s mode data connection for '%s'%s.",
1957 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1958 return (fdopen(pdata, mode));
1959 pdata_err:
1960 reply(425, "Can't open data connection.");
1961 (void) close(pdata);
1962 pdata = -1;
1963 return (NULL);
1964 }
1965 if (data >= 0) {
1966 reply(125, "Using existing data connection for '%s'%s.",
1967 name, sizebuf);
1968 usedefault = 1;
1969 return (fdopen(data, mode));
1970 }
1971 if (usedefault)
1972 data_dest = his_addr;
1973 usedefault = 1;
1974 do {
1975 file = getdatasock(mode);
1976 if (file == NULL) {
1977 char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV];
1978
1979 if (getnameinfo((struct sockaddr *)&data_source,
1980 data_source.su_len,
1981 hostbuf, sizeof(hostbuf) - 1,
1982 portbuf, sizeof(portbuf) - 1,
1983 NI_NUMERICHOST|NI_NUMERICSERV))
1984 *hostbuf = *portbuf = 0;
1985 hostbuf[sizeof(hostbuf) - 1] = 0;
1986 portbuf[sizeof(portbuf) - 1] = 0;
1987 reply(425, "Can't create data socket (%s,%s): %s.",
1988 hostbuf, portbuf, strerror(errno));
1989 return (NULL);
1990 }
1991 data = fileno(file);
1992 conerrno = 0;
1993 if (connect(data, (struct sockaddr *)&data_dest,
1994 data_dest.su_len) == 0)
1995 break;
1996 conerrno = errno;
1997 (void) fclose(file);
1998 data = -1;
1999 if (conerrno == EADDRINUSE) {
2000 sleep(swaitint);
2001 retry += swaitint;
2002 } else {
2003 break;
2004 }
2005 } while (retry <= swaitmax);
2006 if (conerrno != 0) {
2007 reply(425, "Can't build data connection: %s.",
2008 strerror(conerrno));
2009 return (NULL);
2010 }
2011 reply(150, "Opening %s mode data connection for '%s'%s.",
2012 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
2013 return (file);
2014 }
2015
2016 /*
2017 * A helper macro to avoid code duplication
2018 * in send_data() and receive_data().
2019 *
2020 * XXX We have to block SIGURG during putc() because BSD stdio
2021 * is unable to restart interrupted write operations and hence
2022 * the entire buffer contents will be lost as soon as a write()
2023 * call indicates EINTR to stdio.
2024 */
2025 #define FTPD_PUTC(ch, file, label) \
2026 do { \
2027 int ret; \
2028 \
2029 do { \
2030 START_UNSAFE; \
2031 ret = putc((ch), (file)); \
2032 END_UNSAFE; \
2033 CHECKOOB(return (-1)) \
2034 else if (ferror(file)) \
2035 goto label; \
2036 clearerr(file); \
2037 } while (ret == EOF); \
2038 } while (0)
2039
2040 /*
2041 * Transfer the contents of "instr" to "outstr" peer using the appropriate
2042 * encapsulation of the data subject to Mode, Structure, and Type.
2043 *
2044 * NB: Form isn't handled.
2045 */
2046 static int
send_data(FILE * instr,FILE * outstr,size_t blksize,off_t filesize,int isreg)2047 send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg)
2048 {
2049 int c, cp, filefd, netfd;
2050 char *buf;
2051
2052 STARTXFER;
2053
2054 switch (type) {
2055
2056 case TYPE_A:
2057 cp = EOF;
2058 for (;;) {
2059 c = getc(instr);
2060 CHECKOOB(return (-1))
2061 else if (c == EOF && ferror(instr))
2062 goto file_err;
2063 if (c == EOF) {
2064 if (ferror(instr)) { /* resume after OOB */
2065 clearerr(instr);
2066 continue;
2067 }
2068 if (feof(instr)) /* EOF */
2069 break;
2070 syslog(LOG_ERR, "Internal: impossible condition"
2071 " on file after getc()");
2072 goto file_err;
2073 }
2074 if (c == '\n' && cp != '\r') {
2075 FTPD_PUTC('\r', outstr, data_err);
2076 byte_count++;
2077 }
2078 FTPD_PUTC(c, outstr, data_err);
2079 byte_count++;
2080 cp = c;
2081 }
2082 #ifdef notyet /* BSD stdio isn't ready for that */
2083 while (fflush(outstr) == EOF) {
2084 CHECKOOB(return (-1))
2085 else
2086 goto data_err;
2087 clearerr(outstr);
2088 }
2089 ENDXFER;
2090 #else
2091 ENDXFER;
2092 if (fflush(outstr) == EOF)
2093 goto data_err;
2094 #endif
2095 reply(226, "Transfer complete.");
2096 return (0);
2097
2098 case TYPE_I:
2099 case TYPE_L:
2100 /*
2101 * isreg is only set if we are not doing restart and we
2102 * are sending a regular file
2103 */
2104 netfd = fileno(outstr);
2105 filefd = fileno(instr);
2106
2107 if (isreg) {
2108 char *msg = "Transfer complete.";
2109 off_t cnt, offset;
2110 int err;
2111
2112 cnt = offset = 0;
2113
2114 while (filesize > 0) {
2115 err = sendfile(filefd, netfd, offset, 0,
2116 NULL, &cnt, 0);
2117 /*
2118 * Calculate byte_count before OOB processing.
2119 * It can be used in myoob() later.
2120 */
2121 byte_count += cnt;
2122 offset += cnt;
2123 filesize -= cnt;
2124 CHECKOOB(return (-1))
2125 else if (err == -1) {
2126 if (errno != EINTR &&
2127 cnt == 0 && offset == 0)
2128 goto oldway;
2129 goto data_err;
2130 }
2131 if (err == -1) /* resume after OOB */
2132 continue;
2133 /*
2134 * We hit the EOF prematurely.
2135 * Perhaps the file was externally truncated.
2136 */
2137 if (cnt == 0) {
2138 msg = "Transfer finished due to "
2139 "premature end of file.";
2140 break;
2141 }
2142 }
2143 ENDXFER;
2144 reply(226, "%s", msg);
2145 return (0);
2146 }
2147
2148 oldway:
2149 if ((buf = malloc(blksize)) == NULL) {
2150 ENDXFER;
2151 reply(451, "Ran out of memory.");
2152 return (-1);
2153 }
2154
2155 for (;;) {
2156 int cnt, len;
2157 char *bp;
2158
2159 cnt = read(filefd, buf, blksize);
2160 CHECKOOB(free(buf); return (-1))
2161 else if (cnt < 0) {
2162 free(buf);
2163 goto file_err;
2164 }
2165 if (cnt < 0) /* resume after OOB */
2166 continue;
2167 if (cnt == 0) /* EOF */
2168 break;
2169 for (len = cnt, bp = buf; len > 0;) {
2170 cnt = write(netfd, bp, len);
2171 CHECKOOB(free(buf); return (-1))
2172 else if (cnt < 0) {
2173 free(buf);
2174 goto data_err;
2175 }
2176 if (cnt <= 0)
2177 continue;
2178 len -= cnt;
2179 bp += cnt;
2180 byte_count += cnt;
2181 }
2182 }
2183 ENDXFER;
2184 free(buf);
2185 reply(226, "Transfer complete.");
2186 return (0);
2187 default:
2188 ENDXFER;
2189 reply(550, "Unimplemented TYPE %d in send_data.", type);
2190 return (-1);
2191 }
2192
2193 data_err:
2194 ENDXFER;
2195 perror_reply(426, "Data connection");
2196 return (-1);
2197
2198 file_err:
2199 ENDXFER;
2200 perror_reply(551, "Error on input file");
2201 return (-1);
2202 }
2203
2204 /*
2205 * Transfer data from peer to "outstr" using the appropriate encapulation of
2206 * the data subject to Mode, Structure, and Type.
2207 *
2208 * N.B.: Form isn't handled.
2209 */
2210 static int
receive_data(FILE * instr,FILE * outstr)2211 receive_data(FILE *instr, FILE *outstr)
2212 {
2213 int c, cp;
2214 int bare_lfs = 0;
2215
2216 STARTXFER;
2217
2218 switch (type) {
2219
2220 case TYPE_I:
2221 case TYPE_L:
2222 for (;;) {
2223 int cnt, len;
2224 char *bp;
2225 char buf[BUFSIZ];
2226
2227 cnt = read(fileno(instr), buf, sizeof(buf));
2228 CHECKOOB(return (-1))
2229 else if (cnt < 0)
2230 goto data_err;
2231 if (cnt < 0) /* resume after OOB */
2232 continue;
2233 if (cnt == 0) /* EOF */
2234 break;
2235 for (len = cnt, bp = buf; len > 0;) {
2236 cnt = write(fileno(outstr), bp, len);
2237 CHECKOOB(return (-1))
2238 else if (cnt < 0)
2239 goto file_err;
2240 if (cnt <= 0)
2241 continue;
2242 len -= cnt;
2243 bp += cnt;
2244 byte_count += cnt;
2245 }
2246 }
2247 ENDXFER;
2248 return (0);
2249
2250 case TYPE_E:
2251 ENDXFER;
2252 reply(553, "TYPE E not implemented.");
2253 return (-1);
2254
2255 case TYPE_A:
2256 cp = EOF;
2257 for (;;) {
2258 c = getc(instr);
2259 CHECKOOB(return (-1))
2260 else if (c == EOF && ferror(instr))
2261 goto data_err;
2262 if (c == EOF && ferror(instr)) { /* resume after OOB */
2263 clearerr(instr);
2264 continue;
2265 }
2266
2267 if (cp == '\r') {
2268 if (c != '\n')
2269 FTPD_PUTC('\r', outstr, file_err);
2270 } else
2271 if (c == '\n')
2272 bare_lfs++;
2273 if (c == '\r') {
2274 byte_count++;
2275 cp = c;
2276 continue;
2277 }
2278
2279 /* Check for EOF here in order not to lose last \r. */
2280 if (c == EOF) {
2281 if (feof(instr)) /* EOF */
2282 break;
2283 syslog(LOG_ERR, "Internal: impossible condition"
2284 " on data stream after getc()");
2285 goto data_err;
2286 }
2287
2288 byte_count++;
2289 FTPD_PUTC(c, outstr, file_err);
2290 cp = c;
2291 }
2292 #ifdef notyet /* BSD stdio isn't ready for that */
2293 while (fflush(outstr) == EOF) {
2294 CHECKOOB(return (-1))
2295 else
2296 goto file_err;
2297 clearerr(outstr);
2298 }
2299 ENDXFER;
2300 #else
2301 ENDXFER;
2302 if (fflush(outstr) == EOF)
2303 goto file_err;
2304 #endif
2305 if (bare_lfs) {
2306 lreply(226,
2307 "WARNING! %d bare linefeeds received in ASCII mode.",
2308 bare_lfs);
2309 (void)printf(" File may not have transferred correctly.\r\n");
2310 }
2311 return (0);
2312 default:
2313 ENDXFER;
2314 reply(550, "Unimplemented TYPE %d in receive_data.", type);
2315 return (-1);
2316 }
2317
2318 data_err:
2319 ENDXFER;
2320 perror_reply(426, "Data connection");
2321 return (-1);
2322
2323 file_err:
2324 ENDXFER;
2325 perror_reply(452, "Error writing to file");
2326 return (-1);
2327 }
2328
2329 void
statfilecmd(char * filename)2330 statfilecmd(char *filename)
2331 {
2332 FILE *fin;
2333 int atstart;
2334 int c, code;
2335 char line[LINE_MAX];
2336 struct stat st;
2337
2338 code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213;
2339 (void)snprintf(line, sizeof(line), _PATH_LS " -lA %s", filename);
2340 fin = ftpd_popen(line, "r");
2341 if (fin == NULL) {
2342 perror_reply(551, filename);
2343 return;
2344 }
2345 lreply(code, "Status of %s:", filename);
2346 atstart = 1;
2347 while ((c = getc(fin)) != EOF) {
2348 if (c == '\n') {
2349 if (ferror(stdout)){
2350 perror_reply(421, "Control connection");
2351 (void) ftpd_pclose(fin);
2352 dologout(1);
2353 /* NOTREACHED */
2354 }
2355 if (ferror(fin)) {
2356 perror_reply(551, filename);
2357 (void) ftpd_pclose(fin);
2358 return;
2359 }
2360 (void) putc('\r', stdout);
2361 }
2362 /*
2363 * RFC 959 says neutral text should be prepended before
2364 * a leading 3-digit number followed by whitespace, but
2365 * many ftp clients can be confused by any leading digits,
2366 * as a matter of fact.
2367 */
2368 if (atstart && isdigit(c))
2369 (void) putc(' ', stdout);
2370 (void) putc(c, stdout);
2371 atstart = (c == '\n');
2372 }
2373 (void) ftpd_pclose(fin);
2374 reply(code, "End of status.");
2375 }
2376
2377 void
statcmd(void)2378 statcmd(void)
2379 {
2380 union sockunion *su;
2381 u_char *a, *p;
2382 char hname[NI_MAXHOST];
2383 int ispassive;
2384
2385 if (hostinfo) {
2386 lreply(211, "%s FTP server status:", hostname);
2387 printf(" %s\r\n", version);
2388 } else
2389 lreply(211, "FTP server status:");
2390 printf(" Connected to %s", remotehost);
2391 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2392 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2393 hname[sizeof(hname) - 1] = 0;
2394 if (strcmp(hname, remotehost) != 0)
2395 printf(" (%s)", hname);
2396 }
2397 printf("\r\n");
2398 if (logged_in) {
2399 if (guest)
2400 printf(" Logged in anonymously\r\n");
2401 else
2402 printf(" Logged in as %s\r\n", pw->pw_name);
2403 } else if (askpasswd)
2404 printf(" Waiting for password\r\n");
2405 else
2406 printf(" Waiting for user name\r\n");
2407 printf(" TYPE: %s", typenames[type]);
2408 if (type == TYPE_A || type == TYPE_E)
2409 printf(", FORM: %s", formnames[form]);
2410 if (type == TYPE_L)
2411 #if CHAR_BIT == 8
2412 printf(" %d", CHAR_BIT);
2413 #else
2414 printf(" %d", bytesize); /* need definition! */
2415 #endif
2416 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2417 strunames[stru], modenames[mode]);
2418 if (data != -1)
2419 printf(" Data connection open\r\n");
2420 else if (pdata != -1) {
2421 ispassive = 1;
2422 su = &pasv_addr;
2423 goto printaddr;
2424 } else if (usedefault == 0) {
2425 ispassive = 0;
2426 su = &data_dest;
2427 printaddr:
2428 #define UC(b) (((int) b) & 0xff)
2429 if (epsvall) {
2430 printf(" EPSV only mode (EPSV ALL)\r\n");
2431 goto epsvonly;
2432 }
2433
2434 /* PORT/PASV */
2435 if (su->su_family == AF_INET) {
2436 a = (u_char *) &su->su_sin.sin_addr;
2437 p = (u_char *) &su->su_sin.sin_port;
2438 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2439 ispassive ? "PASV" : "PORT",
2440 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2441 UC(p[0]), UC(p[1]));
2442 }
2443
2444 /* LPRT/LPSV */
2445 {
2446 int alen, af, i;
2447
2448 switch (su->su_family) {
2449 case AF_INET:
2450 a = (u_char *) &su->su_sin.sin_addr;
2451 p = (u_char *) &su->su_sin.sin_port;
2452 alen = sizeof(su->su_sin.sin_addr);
2453 af = 4;
2454 break;
2455 case AF_INET6:
2456 a = (u_char *) &su->su_sin6.sin6_addr;
2457 p = (u_char *) &su->su_sin6.sin6_port;
2458 alen = sizeof(su->su_sin6.sin6_addr);
2459 af = 6;
2460 break;
2461 default:
2462 af = 0;
2463 break;
2464 }
2465 if (af) {
2466 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2467 af, alen);
2468 for (i = 0; i < alen; i++)
2469 printf("%d,", UC(a[i]));
2470 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2471 }
2472 }
2473
2474 epsvonly:;
2475 /* EPRT/EPSV */
2476 {
2477 int af;
2478
2479 switch (su->su_family) {
2480 case AF_INET:
2481 af = 1;
2482 break;
2483 case AF_INET6:
2484 af = 2;
2485 break;
2486 default:
2487 af = 0;
2488 break;
2489 }
2490 if (af) {
2491 union sockunion tmp;
2492
2493 tmp = *su;
2494 if (tmp.su_family == AF_INET6)
2495 tmp.su_sin6.sin6_scope_id = 0;
2496 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2497 hname, sizeof(hname) - 1, NULL, 0,
2498 NI_NUMERICHOST)) {
2499 hname[sizeof(hname) - 1] = 0;
2500 printf(" %s |%d|%s|%d|\r\n",
2501 ispassive ? "EPSV" : "EPRT",
2502 af, hname, htons(tmp.su_port));
2503 }
2504 }
2505 }
2506 #undef UC
2507 } else
2508 printf(" No data connection\r\n");
2509 reply(211, "End of status.");
2510 }
2511
2512 void
fatalerror(char * s)2513 fatalerror(char *s)
2514 {
2515
2516 reply(451, "Error in server: %s", s);
2517 reply(221, "Closing connection due to server error.");
2518 dologout(0);
2519 /* NOTREACHED */
2520 }
2521
2522 void
reply(int n,const char * fmt,...)2523 reply(int n, const char *fmt, ...)
2524 {
2525 va_list ap;
2526
2527 (void)printf("%d ", n);
2528 va_start(ap, fmt);
2529 (void)vprintf(fmt, ap);
2530 va_end(ap);
2531 (void)printf("\r\n");
2532 (void)fflush(stdout);
2533 if (ftpdebug) {
2534 syslog(LOG_DEBUG, "<--- %d ", n);
2535 va_start(ap, fmt);
2536 vsyslog(LOG_DEBUG, fmt, ap);
2537 va_end(ap);
2538 }
2539 }
2540
2541 void
lreply(int n,const char * fmt,...)2542 lreply(int n, const char *fmt, ...)
2543 {
2544 va_list ap;
2545
2546 (void)printf("%d- ", n);
2547 va_start(ap, fmt);
2548 (void)vprintf(fmt, ap);
2549 va_end(ap);
2550 (void)printf("\r\n");
2551 (void)fflush(stdout);
2552 if (ftpdebug) {
2553 syslog(LOG_DEBUG, "<--- %d- ", n);
2554 va_start(ap, fmt);
2555 vsyslog(LOG_DEBUG, fmt, ap);
2556 va_end(ap);
2557 }
2558 }
2559
2560 static void
ack(char * s)2561 ack(char *s)
2562 {
2563
2564 reply(250, "%s command successful.", s);
2565 }
2566
2567 void
nack(char * s)2568 nack(char *s)
2569 {
2570
2571 reply(502, "%s command not implemented.", s);
2572 }
2573
2574 /* ARGSUSED */
2575 void
yyerror(char * s)2576 yyerror(char *s)
2577 {
2578 char *cp;
2579
2580 if ((cp = strchr(cbuf,'\n')))
2581 *cp = '\0';
2582 reply(500, "%s: command not understood.", cbuf);
2583 }
2584
2585 void
delete(char * name)2586 delete(char *name)
2587 {
2588 struct stat st;
2589
2590 LOGCMD("delete", name);
2591 if (lstat(name, &st) < 0) {
2592 perror_reply(550, name);
2593 return;
2594 }
2595 if (S_ISDIR(st.st_mode)) {
2596 if (rmdir(name) < 0) {
2597 perror_reply(550, name);
2598 return;
2599 }
2600 goto done;
2601 }
2602 if (guest && noguestmod) {
2603 reply(550, "Operation not permitted.");
2604 return;
2605 }
2606 if (unlink(name) < 0) {
2607 perror_reply(550, name);
2608 return;
2609 }
2610 done:
2611 ack("DELE");
2612 }
2613
2614 void
cwd(char * path)2615 cwd(char *path)
2616 {
2617
2618 if (chdir(path) < 0)
2619 perror_reply(550, path);
2620 else
2621 ack("CWD");
2622 }
2623
2624 void
makedir(char * name)2625 makedir(char *name)
2626 {
2627 char *s;
2628
2629 LOGCMD("mkdir", name);
2630 if (guest && noguestmkd)
2631 reply(550, "Operation not permitted.");
2632 else if (mkdir(name, 0777) < 0)
2633 perror_reply(550, name);
2634 else {
2635 if ((s = doublequote(name)) == NULL)
2636 fatalerror("Ran out of memory.");
2637 reply(257, "\"%s\" directory created.", s);
2638 free(s);
2639 }
2640 }
2641
2642 void
removedir(char * name)2643 removedir(char *name)
2644 {
2645
2646 LOGCMD("rmdir", name);
2647 if (rmdir(name) < 0)
2648 perror_reply(550, name);
2649 else
2650 ack("RMD");
2651 }
2652
2653 void
pwd(void)2654 pwd(void)
2655 {
2656 char *s, path[MAXPATHLEN + 1];
2657
2658 if (getcwd(path, sizeof(path)) == NULL)
2659 perror_reply(550, "Get current directory");
2660 else {
2661 if ((s = doublequote(path)) == NULL)
2662 fatalerror("Ran out of memory.");
2663 reply(257, "\"%s\" is current directory.", s);
2664 free(s);
2665 }
2666 }
2667
2668 char *
renamefrom(char * name)2669 renamefrom(char *name)
2670 {
2671 struct stat st;
2672
2673 if (guest && noguestmod) {
2674 reply(550, "Operation not permitted.");
2675 return (NULL);
2676 }
2677 if (lstat(name, &st) < 0) {
2678 perror_reply(550, name);
2679 return (NULL);
2680 }
2681 reply(350, "File exists, ready for destination name.");
2682 return (name);
2683 }
2684
2685 void
renamecmd(char * from,char * to)2686 renamecmd(char *from, char *to)
2687 {
2688 struct stat st;
2689
2690 LOGCMD2("rename", from, to);
2691
2692 if (guest && (stat(to, &st) == 0)) {
2693 reply(550, "%s: permission denied.", to);
2694 return;
2695 }
2696
2697 if (rename(from, to) < 0)
2698 perror_reply(550, "rename");
2699 else
2700 ack("RNTO");
2701 }
2702
2703 static void
dolog(struct sockaddr * who)2704 dolog(struct sockaddr *who)
2705 {
2706 char who_name[NI_MAXHOST];
2707
2708 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2709 remotehost[sizeof(remotehost) - 1] = 0;
2710 if (getnameinfo(who, who->sa_len,
2711 who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST))
2712 *who_name = 0;
2713 who_name[sizeof(who_name) - 1] = 0;
2714
2715 #ifdef SETPROCTITLE
2716 #ifdef VIRTUAL_HOSTING
2717 if (thishost != firsthost)
2718 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2719 remotehost, hostname);
2720 else
2721 #endif
2722 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2723 remotehost);
2724 setproctitle("%s", proctitle);
2725 #endif /* SETPROCTITLE */
2726
2727 if (logging) {
2728 #ifdef VIRTUAL_HOSTING
2729 if (thishost != firsthost)
2730 syslog(LOG_INFO, "connection from %s (%s) to %s",
2731 remotehost, who_name, hostname);
2732 else
2733 #endif
2734 syslog(LOG_INFO, "connection from %s (%s)",
2735 remotehost, who_name);
2736 }
2737 }
2738
2739 /*
2740 * Record logout in wtmp file
2741 * and exit with supplied status.
2742 */
2743 void
dologout(int status)2744 dologout(int status)
2745 {
2746
2747 if (logged_in && dowtmp) {
2748 (void) seteuid(0);
2749 #ifdef LOGIN_CAP
2750 setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN |
2751 LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH |
2752 LOGIN_SETENV));
2753 #endif
2754 ftpd_logwtmp(wtmpid, NULL, NULL);
2755 }
2756 /* beware of flushing buffers after a SIGPIPE */
2757 _exit(status);
2758 }
2759
2760 static void
sigurg(int signo)2761 sigurg(int signo)
2762 {
2763
2764 recvurg = 1;
2765 }
2766
2767 static void
maskurg(int flag)2768 maskurg(int flag)
2769 {
2770 int oerrno;
2771 sigset_t sset;
2772
2773 if (!transflag) {
2774 syslog(LOG_ERR, "Internal: maskurg() while no transfer");
2775 return;
2776 }
2777 oerrno = errno;
2778 sigemptyset(&sset);
2779 sigaddset(&sset, SIGURG);
2780 sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL);
2781 errno = oerrno;
2782 }
2783
2784 static void
flagxfer(int flag)2785 flagxfer(int flag)
2786 {
2787
2788 if (flag) {
2789 if (transflag)
2790 syslog(LOG_ERR, "Internal: flagxfer(1): "
2791 "transfer already under way");
2792 transflag = 1;
2793 maskurg(0);
2794 recvurg = 0;
2795 } else {
2796 if (!transflag)
2797 syslog(LOG_ERR, "Internal: flagxfer(0): "
2798 "no active transfer");
2799 maskurg(1);
2800 transflag = 0;
2801 }
2802 }
2803
2804 /*
2805 * Returns 0 if OK to resume or -1 if abort requested.
2806 */
2807 static int
myoob(void)2808 myoob(void)
2809 {
2810 char *cp;
2811 int ret;
2812
2813 if (!transflag) {
2814 syslog(LOG_ERR, "Internal: myoob() while no transfer");
2815 return (0);
2816 }
2817 cp = tmpline;
2818 ret = get_line(cp, 7, stdin);
2819 if (ret == -1) {
2820 reply(221, "You could at least say goodbye.");
2821 dologout(0);
2822 } else if (ret == -2) {
2823 /* Ignore truncated command. */
2824 return (0);
2825 }
2826 upper(cp);
2827 if (strcmp(cp, "ABOR\r\n") == 0) {
2828 tmpline[0] = '\0';
2829 reply(426, "Transfer aborted. Data connection closed.");
2830 reply(226, "Abort successful.");
2831 return (-1);
2832 }
2833 if (strcmp(cp, "STAT\r\n") == 0) {
2834 tmpline[0] = '\0';
2835 if (file_size != -1)
2836 reply(213, "Status: %jd of %jd bytes transferred.",
2837 (intmax_t)byte_count, (intmax_t)file_size);
2838 else
2839 reply(213, "Status: %jd bytes transferred.",
2840 (intmax_t)byte_count);
2841 }
2842 return (0);
2843 }
2844
2845 /*
2846 * Note: a response of 425 is not mentioned as a possible response to
2847 * the PASV command in RFC959. However, it has been blessed as
2848 * a legitimate response by Jon Postel in a telephone conversation
2849 * with Rick Adams on 25 Jan 89.
2850 */
2851 void
passive(void)2852 passive(void)
2853 {
2854 socklen_t len;
2855 int on;
2856 char *p, *a;
2857
2858 if (pdata >= 0) /* close old port if one set */
2859 close(pdata);
2860
2861 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2862 if (pdata < 0) {
2863 perror_reply(425, "Can't open passive connection");
2864 return;
2865 }
2866 on = 1;
2867 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2868 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2869
2870 (void) seteuid(0);
2871
2872 #ifdef IP_PORTRANGE
2873 if (ctrl_addr.su_family == AF_INET) {
2874 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2875 : IP_PORTRANGE_DEFAULT;
2876
2877 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2878 &on, sizeof(on)) < 0)
2879 goto pasv_error;
2880 }
2881 #endif
2882 #ifdef IPV6_PORTRANGE
2883 if (ctrl_addr.su_family == AF_INET6) {
2884 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2885 : IPV6_PORTRANGE_DEFAULT;
2886
2887 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2888 &on, sizeof(on)) < 0)
2889 goto pasv_error;
2890 }
2891 #endif
2892
2893 pasv_addr = ctrl_addr;
2894 pasv_addr.su_port = 0;
2895 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2896 goto pasv_error;
2897
2898 (void) seteuid(pw->pw_uid);
2899
2900 len = sizeof(pasv_addr);
2901 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2902 goto pasv_error;
2903 if (listen(pdata, 1) < 0)
2904 goto pasv_error;
2905 if (pasv_addr.su_family == AF_INET)
2906 a = (char *) &pasv_addr.su_sin.sin_addr;
2907 else if (pasv_addr.su_family == AF_INET6 &&
2908 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2909 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2910 else
2911 goto pasv_error;
2912
2913 p = (char *) &pasv_addr.su_port;
2914
2915 #define UC(b) (((int) b) & 0xff)
2916
2917 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2918 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2919 return;
2920
2921 pasv_error:
2922 (void) seteuid(pw->pw_uid);
2923 (void) close(pdata);
2924 pdata = -1;
2925 perror_reply(425, "Can't open passive connection");
2926 return;
2927 }
2928
2929 /*
2930 * Long Passive defined in RFC 1639.
2931 * 228 Entering Long Passive Mode
2932 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2933 */
2934
2935 void
long_passive(char * cmd,int pf)2936 long_passive(char *cmd, int pf)
2937 {
2938 socklen_t len;
2939 int on;
2940 char *p, *a;
2941
2942 if (pdata >= 0) /* close old port if one set */
2943 close(pdata);
2944
2945 if (pf != PF_UNSPEC) {
2946 if (ctrl_addr.su_family != pf) {
2947 switch (ctrl_addr.su_family) {
2948 case AF_INET:
2949 pf = 1;
2950 break;
2951 case AF_INET6:
2952 pf = 2;
2953 break;
2954 default:
2955 pf = 0;
2956 break;
2957 }
2958 /*
2959 * XXX
2960 * only EPRT/EPSV ready clients will understand this
2961 */
2962 if (strcmp(cmd, "EPSV") == 0 && pf) {
2963 reply(522, "Network protocol mismatch, "
2964 "use (%d)", pf);
2965 } else
2966 reply(501, "Network protocol mismatch."); /*XXX*/
2967
2968 return;
2969 }
2970 }
2971
2972 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2973 if (pdata < 0) {
2974 perror_reply(425, "Can't open passive connection");
2975 return;
2976 }
2977 on = 1;
2978 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2979 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2980
2981 (void) seteuid(0);
2982
2983 pasv_addr = ctrl_addr;
2984 pasv_addr.su_port = 0;
2985 len = pasv_addr.su_len;
2986
2987 #ifdef IP_PORTRANGE
2988 if (ctrl_addr.su_family == AF_INET) {
2989 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2990 : IP_PORTRANGE_DEFAULT;
2991
2992 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2993 &on, sizeof(on)) < 0)
2994 goto pasv_error;
2995 }
2996 #endif
2997 #ifdef IPV6_PORTRANGE
2998 if (ctrl_addr.su_family == AF_INET6) {
2999 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
3000 : IPV6_PORTRANGE_DEFAULT;
3001
3002 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
3003 &on, sizeof(on)) < 0)
3004 goto pasv_error;
3005 }
3006 #endif
3007
3008 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
3009 goto pasv_error;
3010
3011 (void) seteuid(pw->pw_uid);
3012
3013 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
3014 goto pasv_error;
3015 if (listen(pdata, 1) < 0)
3016 goto pasv_error;
3017
3018 #define UC(b) (((int) b) & 0xff)
3019
3020 if (strcmp(cmd, "LPSV") == 0) {
3021 p = (char *)&pasv_addr.su_port;
3022 switch (pasv_addr.su_family) {
3023 case AF_INET:
3024 a = (char *) &pasv_addr.su_sin.sin_addr;
3025 v4_reply:
3026 reply(228,
3027 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3028 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3029 2, UC(p[0]), UC(p[1]));
3030 return;
3031 case AF_INET6:
3032 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
3033 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
3034 goto v4_reply;
3035 }
3036 a = (char *) &pasv_addr.su_sin6.sin6_addr;
3037 reply(228,
3038 "Entering Long Passive Mode "
3039 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3040 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
3041 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
3042 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
3043 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
3044 2, UC(p[0]), UC(p[1]));
3045 return;
3046 }
3047 } else if (strcmp(cmd, "EPSV") == 0) {
3048 switch (pasv_addr.su_family) {
3049 case AF_INET:
3050 case AF_INET6:
3051 reply(229, "Entering Extended Passive Mode (|||%d|)",
3052 ntohs(pasv_addr.su_port));
3053 return;
3054 }
3055 } else {
3056 /* more proper error code? */
3057 }
3058
3059 pasv_error:
3060 (void) seteuid(pw->pw_uid);
3061 (void) close(pdata);
3062 pdata = -1;
3063 perror_reply(425, "Can't open passive connection");
3064 return;
3065 }
3066
3067 /*
3068 * Generate unique name for file with basename "local"
3069 * and open the file in order to avoid possible races.
3070 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3071 * Return descriptor to the file, set "name" to its name.
3072 *
3073 * Generates failure reply on error.
3074 */
3075 static int
guniquefd(char * local,char ** name)3076 guniquefd(char *local, char **name)
3077 {
3078 static char new[MAXPATHLEN];
3079 struct stat st;
3080 char *cp;
3081 int count;
3082 int fd;
3083
3084 cp = strrchr(local, '/');
3085 if (cp)
3086 *cp = '\0';
3087 if (stat(cp ? local : ".", &st) < 0) {
3088 perror_reply(553, cp ? local : ".");
3089 return (-1);
3090 }
3091 if (cp) {
3092 /*
3093 * Let not overwrite dirname with counter suffix.
3094 * -4 is for /nn\0
3095 * In this extreme case dot won't be put in front of suffix.
3096 */
3097 if (strlen(local) > sizeof(new) - 4) {
3098 reply(553, "Pathname too long.");
3099 return (-1);
3100 }
3101 *cp = '/';
3102 }
3103 /* -4 is for the .nn<null> we put on the end below */
3104 (void) snprintf(new, sizeof(new) - 4, "%s", local);
3105 cp = new + strlen(new);
3106 /*
3107 * Don't generate dotfile unless requested explicitly.
3108 * This covers the case when basename gets truncated off
3109 * by buffer size.
3110 */
3111 if (cp > new && cp[-1] != '/')
3112 *cp++ = '.';
3113 for (count = 0; count < 100; count++) {
3114 /* At count 0 try unmodified name */
3115 if (count)
3116 (void)sprintf(cp, "%d", count);
3117 if ((fd = open(count ? new : local,
3118 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
3119 *name = count ? new : local;
3120 return (fd);
3121 }
3122 if (errno != EEXIST) {
3123 perror_reply(553, count ? new : local);
3124 return (-1);
3125 }
3126 }
3127 reply(452, "Unique file name cannot be created.");
3128 return (-1);
3129 }
3130
3131 /*
3132 * Format and send reply containing system error number.
3133 */
3134 void
perror_reply(int code,char * string)3135 perror_reply(int code, char *string)
3136 {
3137
3138 reply(code, "%s: %s.", string, strerror(errno));
3139 }
3140
3141 static char *onefile[] = {
3142 "",
3143 0
3144 };
3145
3146 void
send_file_list(char * whichf)3147 send_file_list(char *whichf)
3148 {
3149 struct stat st;
3150 DIR *dirp = NULL;
3151 struct dirent *dir;
3152 FILE *dout = NULL;
3153 char **dirlist, *dirname;
3154 int simple = 0;
3155 int freeglob = 0;
3156 glob_t gl;
3157
3158 if (strpbrk(whichf, "~{[*?") != NULL) {
3159 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
3160
3161 memset(&gl, 0, sizeof(gl));
3162 gl.gl_matchc = MAXGLOBARGS;
3163 flags |= GLOB_LIMIT;
3164 freeglob = 1;
3165 if (glob(whichf, flags, 0, &gl)) {
3166 reply(550, "No matching files found.");
3167 goto out;
3168 } else if (gl.gl_pathc == 0) {
3169 errno = ENOENT;
3170 perror_reply(550, whichf);
3171 goto out;
3172 }
3173 dirlist = gl.gl_pathv;
3174 } else {
3175 onefile[0] = whichf;
3176 dirlist = onefile;
3177 simple = 1;
3178 }
3179
3180 while ((dirname = *dirlist++)) {
3181 if (stat(dirname, &st) < 0) {
3182 /*
3183 * If user typed "ls -l", etc, and the client
3184 * used NLST, do what the user meant.
3185 */
3186 if (dirname[0] == '-' && *dirlist == NULL &&
3187 dout == NULL)
3188 retrieve(_PATH_LS " %s", dirname);
3189 else
3190 perror_reply(550, whichf);
3191 goto out;
3192 }
3193
3194 if (S_ISREG(st.st_mode)) {
3195 if (dout == NULL) {
3196 dout = dataconn("file list", -1, "w");
3197 if (dout == NULL)
3198 goto out;
3199 STARTXFER;
3200 }
3201 START_UNSAFE;
3202 fprintf(dout, "%s%s\n", dirname,
3203 type == TYPE_A ? "\r" : "");
3204 END_UNSAFE;
3205 if (ferror(dout))
3206 goto data_err;
3207 byte_count += strlen(dirname) +
3208 (type == TYPE_A ? 2 : 1);
3209 CHECKOOB(goto abrt);
3210 continue;
3211 } else if (!S_ISDIR(st.st_mode))
3212 continue;
3213
3214 if ((dirp = opendir(dirname)) == NULL)
3215 continue;
3216
3217 while ((dir = readdir(dirp)) != NULL) {
3218 char nbuf[MAXPATHLEN];
3219
3220 CHECKOOB(goto abrt);
3221
3222 if (dir->d_name[0] == '.' && dir->d_namlen == 1)
3223 continue;
3224 if (dir->d_name[0] == '.' && dir->d_name[1] == '.' &&
3225 dir->d_namlen == 2)
3226 continue;
3227
3228 snprintf(nbuf, sizeof(nbuf),
3229 "%s/%s", dirname, dir->d_name);
3230
3231 /*
3232 * We have to do a stat to insure it's
3233 * not a directory or special file.
3234 */
3235 if (simple || (stat(nbuf, &st) == 0 &&
3236 S_ISREG(st.st_mode))) {
3237 if (dout == NULL) {
3238 dout = dataconn("file list", -1, "w");
3239 if (dout == NULL)
3240 goto out;
3241 STARTXFER;
3242 }
3243 START_UNSAFE;
3244 if (nbuf[0] == '.' && nbuf[1] == '/')
3245 fprintf(dout, "%s%s\n", &nbuf[2],
3246 type == TYPE_A ? "\r" : "");
3247 else
3248 fprintf(dout, "%s%s\n", nbuf,
3249 type == TYPE_A ? "\r" : "");
3250 END_UNSAFE;
3251 if (ferror(dout))
3252 goto data_err;
3253 byte_count += strlen(nbuf) +
3254 (type == TYPE_A ? 2 : 1);
3255 CHECKOOB(goto abrt);
3256 }
3257 }
3258 (void) closedir(dirp);
3259 dirp = NULL;
3260 }
3261
3262 if (dout == NULL)
3263 reply(550, "No files found.");
3264 else if (ferror(dout))
3265 data_err: perror_reply(550, "Data connection");
3266 else
3267 reply(226, "Transfer complete.");
3268 out:
3269 if (dout) {
3270 ENDXFER;
3271 abrt:
3272 (void) fclose(dout);
3273 data = -1;
3274 pdata = -1;
3275 }
3276 if (dirp)
3277 (void) closedir(dirp);
3278 if (freeglob) {
3279 freeglob = 0;
3280 globfree(&gl);
3281 }
3282 }
3283
3284 void
reapchild(int signo)3285 reapchild(int signo)
3286 {
3287 while (waitpid(-1, NULL, WNOHANG) > 0);
3288 }
3289
3290 static void
appendf(char ** strp,char * fmt,...)3291 appendf(char **strp, char *fmt, ...)
3292 {
3293 va_list ap;
3294 char *ostr, *p;
3295
3296 va_start(ap, fmt);
3297 vasprintf(&p, fmt, ap);
3298 va_end(ap);
3299 if (p == NULL)
3300 fatalerror("Ran out of memory.");
3301 if (*strp == NULL)
3302 *strp = p;
3303 else {
3304 ostr = *strp;
3305 asprintf(strp, "%s%s", ostr, p);
3306 if (*strp == NULL)
3307 fatalerror("Ran out of memory.");
3308 free(ostr);
3309 }
3310 }
3311
3312 static void
logcmd(char * cmd,char * file1,char * file2,off_t cnt)3313 logcmd(char *cmd, char *file1, char *file2, off_t cnt)
3314 {
3315 char *msg = NULL;
3316 char wd[MAXPATHLEN + 1];
3317
3318 if (logging <= 1)
3319 return;
3320
3321 if (getcwd(wd, sizeof(wd) - 1) == NULL)
3322 strcpy(wd, strerror(errno));
3323
3324 appendf(&msg, "%s", cmd);
3325 if (file1)
3326 appendf(&msg, " %s", file1);
3327 if (file2)
3328 appendf(&msg, " %s", file2);
3329 if (cnt >= 0)
3330 appendf(&msg, " = %jd bytes", (intmax_t)cnt);
3331 appendf(&msg, " (wd: %s", wd);
3332 if (guest || dochroot)
3333 appendf(&msg, "; chrooted");
3334 appendf(&msg, ")");
3335 syslog(LOG_INFO, "%s", msg);
3336 free(msg);
3337 }
3338
3339 static void
logxfer(char * name,off_t size,time_t start)3340 logxfer(char *name, off_t size, time_t start)
3341 {
3342 char buf[MAXPATHLEN + 1024];
3343 char path[MAXPATHLEN + 1];
3344 time_t now;
3345
3346 if (statfd >= 0) {
3347 time(&now);
3348 if (realpath(name, path) == NULL) {
3349 syslog(LOG_NOTICE, "realpath failed on %s: %m", path);
3350 return;
3351 }
3352 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n",
3353 ctime(&now)+4, ident, remotehost,
3354 path, (intmax_t)size,
3355 (long)(now - start + (now == start)));
3356 write(statfd, buf, strlen(buf));
3357 }
3358 }
3359
3360 static char *
doublequote(char * s)3361 doublequote(char *s)
3362 {
3363 int n;
3364 char *p, *s2;
3365
3366 for (p = s, n = 0; *p; p++)
3367 if (*p == '"')
3368 n++;
3369
3370 if ((s2 = malloc(p - s + n + 1)) == NULL)
3371 return (NULL);
3372
3373 for (p = s2; *s; s++, p++) {
3374 if ((*p = *s) == '"')
3375 *(++p) = '"';
3376 }
3377 *p = '\0';
3378
3379 return (s2);
3380 }
3381
3382 /* setup server socket for specified address family */
3383 /* if af is PF_UNSPEC more than one socket may be returned */
3384 /* the returned list is dynamically allocated, so caller needs to free it */
3385 static int *
socksetup(int af,char * bindname,const char * bindport)3386 socksetup(int af, char *bindname, const char *bindport)
3387 {
3388 struct addrinfo hints, *res, *r;
3389 int error, maxs, *s, *socks;
3390 const int on = 1;
3391
3392 memset(&hints, 0, sizeof(hints));
3393 hints.ai_flags = AI_PASSIVE;
3394 hints.ai_family = af;
3395 hints.ai_socktype = SOCK_STREAM;
3396 error = getaddrinfo(bindname, bindport, &hints, &res);
3397 if (error) {
3398 syslog(LOG_ERR, "%s", gai_strerror(error));
3399 if (error == EAI_SYSTEM)
3400 syslog(LOG_ERR, "%s", strerror(errno));
3401 return NULL;
3402 }
3403
3404 /* Count max number of sockets we may open */
3405 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3406 ;
3407 socks = malloc((maxs + 1) * sizeof(int));
3408 if (!socks) {
3409 freeaddrinfo(res);
3410 syslog(LOG_ERR, "couldn't allocate memory for sockets");
3411 return NULL;
3412 }
3413
3414 *socks = 0; /* num of sockets counter at start of array */
3415 s = socks + 1;
3416 for (r = res; r; r = r->ai_next) {
3417 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3418 if (*s < 0) {
3419 syslog(LOG_DEBUG, "control socket: %m");
3420 continue;
3421 }
3422 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
3423 &on, sizeof(on)) < 0)
3424 syslog(LOG_WARNING,
3425 "control setsockopt (SO_REUSEADDR): %m");
3426 if (r->ai_family == AF_INET6) {
3427 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
3428 &on, sizeof(on)) < 0)
3429 syslog(LOG_WARNING,
3430 "control setsockopt (IPV6_V6ONLY): %m");
3431 }
3432 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
3433 syslog(LOG_DEBUG, "control bind: %m");
3434 close(*s);
3435 continue;
3436 }
3437 (*socks)++;
3438 s++;
3439 }
3440
3441 if (res)
3442 freeaddrinfo(res);
3443
3444 if (*socks == 0) {
3445 syslog(LOG_ERR, "control socket: Couldn't bind to any socket");
3446 free(socks);
3447 return NULL;
3448 }
3449 return(socks);
3450 }
3451