2 * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)ftpd.c 8.4 (Berkeley) 4/16/94
30 * $FreeBSD: src/libexec/ftpd/ftpd.c,v 1.213 2008/12/23 01:23:09 cperciva Exp $
36 #include <sys/param.h>
37 #include <sys/ioctl.h>
39 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
47 #include <netinet/tcp.h>
51 #include <arpa/inet.h>
52 #include <arpa/telnet.h>
75 #include <login_cap.h>
79 #include <security/pam_appl.h>
82 #include "pathnames.h"
88 static char version
[] = "Version 6.00LS";
91 extern off_t restart_point
;
94 union sockunion ctrl_addr
;
95 union sockunion data_source
;
96 union sockunion data_dest
;
97 union sockunion his_addr
;
98 union sockunion pasv_addr
;
103 int hostinfo
= 1; /* print host-specific info in messages */
108 int timeout
= 900; /* timeout after 15 minutes of inactivity */
109 int maxtimeout
= 7200;/* don't allow idle time to be set beyond 2 hours */
111 int restricted_data_ports
= 1;
112 int paranoid
= 1; /* be extra careful about security */
113 int anon_only
= 0; /* Only anonymous ftp allowed */
114 int assumeutf8
= 0; /* Assume that server file names are in UTF-8 */
123 int stru
; /* avoid C keyword */
125 int usedefault
= 1; /* for data transfers */
126 int pdata
= -1; /* for passive mode */
127 int readonly
= 0; /* Server is in readonly mode. */
128 int noepsv
= 0; /* EPSV command is disabled. */
129 int noretr
= 0; /* RETR command is disabled. */
130 int noguestretr
= 0; /* RETR command is disabled for anon users. */
131 int noguestmkd
= 0; /* MKD command is disabled for anon users. */
132 int noguestmod
= 1; /* anon users may not modify existing files. */
136 #if !defined(CMASK) || CMASK == 0
140 int defumask
= CMASK
; /* default umask value */
145 #ifdef VIRTUAL_HOSTING
148 static struct ftphost
{
149 struct ftphost
*next
;
150 struct addrinfo
*hostinfo
;
156 } *thishost
, *firsthost
;
159 char remotehost
[NI_MAXHOST
];
162 static char ttyline
[20];
163 char *tty
= ttyline
; /* for klogin */
166 static int auth_pam(struct passwd
**, const char*);
167 pam_handle_t
*pamh
= NULL
;
170 static struct opie opiedata
;
171 static char opieprompt
[OPIE_CHALLENGE_MAX
+1];
174 char *pid_file
= NULL
; /* means default location to pidfile(3) */
177 * Limit number of pathnames that glob can return.
178 * A limit of 0 indicates the number of pathnames is unlimited.
180 #define MAXGLOBARGS 16384
184 * Timeout intervals for retrying connections
185 * to hosts that don't accept PORT cmds. This
186 * is a kludge, but given the problems with TCP...
188 #define SWAITMAX 90 /* wait at most 90 seconds */
189 #define SWAITINT 5 /* interval between retries */
191 int swaitmax
= SWAITMAX
;
192 int swaitint
= SWAITINT
;
195 char proctitle
[LINE_MAX
]; /* initial part of title */
196 #endif /* SETPROCTITLE */
198 #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1)
199 #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1)
200 #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt))
202 static volatile sig_atomic_t recvurg
;
203 static int transflag
; /* NB: for debugging only */
205 #define STARTXFER flagxfer(1)
206 #define ENDXFER flagxfer(0)
208 #define START_UNSAFE maskurg(1)
209 #define END_UNSAFE maskurg(0)
211 /* It's OK to put an `else' clause after this macro. */
212 #define CHECKOOB(action) \
221 #ifdef VIRTUAL_HOSTING
222 static void inithosts(int);
223 static void selecthost(union sockunion
*);
225 static void ack(char *);
226 static void sigurg(int);
227 static void maskurg(int);
228 static void flagxfer(int);
229 static int myoob(void);
230 static int checkuser(char *, char *, int, char **);
231 static FILE *dataconn(char *, off_t
, char *);
232 static void dolog(struct sockaddr
*);
233 static void end_login(void);
234 static FILE *getdatasock(char *);
235 static int guniquefd(char *, char **);
236 static void lostconn(int);
237 static void sigquit(int);
238 static int receive_data(FILE *, FILE *);
239 static int send_data(FILE *, FILE *, size_t, off_t
, int);
240 static struct passwd
*
242 static char *sgetsave(char *);
243 static void reapchild(int);
244 static void appendf(char **, char *, ...) __printflike(2, 3);
245 static void logcmd(char *, char *, char *, off_t
);
246 static void logxfer(char *, off_t
, time_t);
247 static char *doublequote(char *);
248 static int *socksetup(int, char *, const char *);
251 main(int argc
, char *argv
[])
255 char *cp
, line
[LINE_MAX
];
257 char *bindname
= NULL
;
258 const char *bindport
= "ftp";
259 int family
= AF_UNSPEC
;
262 tzset(); /* in case no timezone database in ~ftp */
263 sigemptyset(&sa
.sa_mask
);
264 sa
.sa_flags
= SA_RESTART
;
267 * Prevent diagnostic messages from appearing on stderr.
268 * We run as a daemon or from inetd; in both cases, there's
269 * more reason in logging to syslog.
271 freopen(_PATH_DEVNULL
, "w", stderr
);
275 * LOG_NDELAY sets up the logging connection immediately,
276 * necessary for anonymous ftp's that chroot and can't do it later.
278 openlog("ftpd", LOG_PID
| LOG_NDELAY
, LOG_FTP
);
280 while ((ch
= getopt(argc
, argv
,
281 "468a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
284 family
= (family
== AF_INET6
) ? AF_UNSPEC
: AF_INET
;
288 family
= (family
== AF_INET
) ? AF_UNSPEC
: AF_INET6
;
324 logging
++; /* > 1 == extra logging */
364 timeout
= atoi(optarg
);
365 if (maxtimeout
< timeout
)
366 maxtimeout
= timeout
;
370 maxtimeout
= atoi(optarg
);
371 if (timeout
> maxtimeout
)
372 timeout
= maxtimeout
;
379 val
= strtol(optarg
, &optarg
, 8);
380 if (*optarg
!= '\0' || val
< 0)
381 syslog(LOG_WARNING
, "bad value for -u");
387 restricted_data_ports
= 0;
399 syslog(LOG_WARNING
, "unknown flag -%c ignored", optopt
);
405 int *ctl_sock
, fd
, maxfd
= -1, nfds
, i
;
406 fd_set defreadfds
, readfds
;
410 if ((pfh
= pidfile_open(pid_file
, 0600, &pid
)) == NULL
) {
411 if (errno
== EEXIST
) {
412 syslog(LOG_ERR
, "%s already running, pid %d",
413 getprogname(), (int)pid
);
416 syslog(LOG_WARNING
, "pidfile_open: %m");
420 * Detach from parent.
422 if (daemon(1, 1) < 0) {
423 syslog(LOG_ERR
, "failed to become a daemon");
427 if (pfh
!= NULL
&& pidfile_write(pfh
) == -1)
428 syslog(LOG_WARNING
, "pidfile_write: %m");
430 sa
.sa_handler
= reapchild
;
431 sigaction(SIGCHLD
, &sa
, NULL
);
433 #ifdef VIRTUAL_HOSTING
438 * Open a socket, bind it to the FTP port, and start
441 ctl_sock
= socksetup(family
, bindname
, bindport
);
442 if (ctl_sock
== NULL
)
445 FD_ZERO(&defreadfds
);
446 for (i
= 1; i
<= *ctl_sock
; i
++) {
447 FD_SET(ctl_sock
[i
], &defreadfds
);
448 if (listen(ctl_sock
[i
], 32) < 0) {
449 syslog(LOG_ERR
, "control listen: %m");
452 if (maxfd
< ctl_sock
[i
])
457 * Loop forever accepting connection requests and forking off
458 * children to handle them.
461 FD_COPY(&defreadfds
, &readfds
);
462 nfds
= select(maxfd
+ 1, &readfds
, NULL
, NULL
, 0);
464 if (nfds
< 0 && errno
!= EINTR
)
465 syslog(LOG_WARNING
, "select: %m");
470 for (i
= 1; i
<= *ctl_sock
; i
++)
471 if (FD_ISSET(ctl_sock
[i
], &readfds
)) {
472 addrlen
= sizeof(his_addr
);
473 fd
= accept(ctl_sock
[i
],
474 (struct sockaddr
*)&his_addr
,
481 switch (pid
= fork()) {
487 for (i
= 1; i
<= *ctl_sock
; i
++)
493 syslog(LOG_WARNING
, "fork: %m");
501 addrlen
= sizeof(his_addr
);
502 if (getpeername(0, (struct sockaddr
*)&his_addr
, &addrlen
) < 0) {
503 syslog(LOG_ERR
, "getpeername (%s): %m",argv
[0]);
507 #ifdef VIRTUAL_HOSTING
508 if (his_addr
.su_family
== AF_INET6
&&
509 IN6_IS_ADDR_V4MAPPED(&his_addr
.su_sin6
.sin6_addr
))
512 family
= his_addr
.su_family
;
518 sa
.sa_handler
= SIG_DFL
;
519 sigaction(SIGCHLD
, &sa
, NULL
);
521 sa
.sa_handler
= sigurg
;
522 sa
.sa_flags
= 0; /* don't restart syscalls for SIGURG */
523 sigaction(SIGURG
, &sa
, NULL
);
525 sigfillset(&sa
.sa_mask
); /* block all signals in handler */
526 sa
.sa_flags
= SA_RESTART
;
527 sa
.sa_handler
= sigquit
;
528 sigaction(SIGHUP
, &sa
, NULL
);
529 sigaction(SIGINT
, &sa
, NULL
);
530 sigaction(SIGQUIT
, &sa
, NULL
);
531 sigaction(SIGTERM
, &sa
, NULL
);
533 sa
.sa_handler
= lostconn
;
534 sigaction(SIGPIPE
, &sa
, NULL
);
536 addrlen
= sizeof(ctrl_addr
);
537 if (getsockname(0, (struct sockaddr
*)&ctrl_addr
, &addrlen
) < 0) {
538 syslog(LOG_ERR
, "getsockname (%s): %m",argv
[0]);
541 dataport
= ntohs(ctrl_addr
.su_port
) - 1; /* as per RFC 959 */
542 #ifdef VIRTUAL_HOSTING
543 /* select our identity from virtual host table */
544 selecthost(&ctrl_addr
);
547 if (ctrl_addr
.su_family
== AF_INET
)
549 tos
= IPTOS_LOWDELAY
;
550 if (setsockopt(0, IPPROTO_IP
, IP_TOS
, &tos
, sizeof(int)) < 0)
551 syslog(LOG_WARNING
, "control setsockopt (IP_TOS): %m");
555 * Disable Nagle on the control channel so that we don't have to wait
556 * for peer's ACK before issuing our next reply.
558 if (setsockopt(0, IPPROTO_TCP
, TCP_NODELAY
, &on
, sizeof(on
)) < 0)
559 syslog(LOG_WARNING
, "control setsockopt (TCP_NODELAY): %m");
561 data_source
.su_port
= htons(ntohs(ctrl_addr
.su_port
) - 1);
563 /* set this here so klogin can use it... */
564 snprintf(ttyline
, sizeof(ttyline
), "ftp%d", getpid());
566 /* Try to handle urgent data inline */
568 if (setsockopt(0, SOL_SOCKET
, SO_OOBINLINE
, &on
, sizeof(on
)) < 0)
569 syslog(LOG_WARNING
, "control setsockopt (SO_OOBINLINE): %m");
573 if (fcntl(fileno(stdin
), F_SETOWN
, getpid()) == -1)
574 syslog(LOG_ERR
, "fcntl F_SETOWN: %m");
576 dolog((struct sockaddr
*)&his_addr
);
578 * Set up default state
587 /* If logins are disabled, print out the message. */
588 if ((fd
= fopen(_PATH_NOLOGIN
,"r")) != NULL
) {
589 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
590 if ((cp
= strchr(line
, '\n')) != NULL
)
592 lreply(530, "%s", line
);
596 reply(530, "System not available.");
599 #ifdef VIRTUAL_HOSTING
600 fd
= fopen(thishost
->welcome
, "r");
602 fd
= fopen(_PATH_FTPWELCOME
, "r");
605 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
606 if ((cp
= strchr(line
, '\n')) != NULL
)
608 lreply(220, "%s", line
);
612 /* reply(220,) must follow */
614 #ifndef VIRTUAL_HOSTING
615 if (hostname
== NULL
) {
616 if ((hostname
= malloc(MAXHOSTNAMELEN
)) == NULL
)
617 fatalerror("Ran out of memory.");
618 if (gethostname(hostname
, MAXHOSTNAMELEN
- 1) < 0)
620 hostname
[MAXHOSTNAMELEN
- 1] = '\0';
624 reply(220, "%s FTP server (%s) ready.", hostname
, version
);
626 reply(220, "FTP server ready.");
637 syslog(LOG_DEBUG
, "lost connection");
645 syslog(LOG_ERR
, "got signal %d", signo
);
649 #ifdef VIRTUAL_HOSTING
651 * read in virtual host tables (if they exist)
655 inithosts(int family
)
660 char *cp
, *mp
, *line
;
661 char *vhost
, *anonuser
, *statfile
, *welcome
, *loginmsg
;
662 struct ftphost
*hrp
, *lhrp
;
663 struct addrinfo hints
, *res
, *ai
;
666 * Fill in the default host information
668 if (hostname
== NULL
) {
669 if ((hostname
= malloc(MAXHOSTNAMELEN
)) == NULL
)
670 fatalerror("Ran out of memory.");
671 if (gethostname(hostname
, MAXHOSTNAMELEN
- 1) < 0)
673 hostname
[MAXHOSTNAMELEN
- 1] = '\0';
675 if ((hrp
= malloc(sizeof(struct ftphost
))) == NULL
)
676 fatalerror("Ran out of memory.");
677 hrp
->hostname
= hostname
;
678 hrp
->hostinfo
= NULL
;
680 memset(&hints
, 0, sizeof(hints
));
681 hints
.ai_flags
= AI_PASSIVE
;
682 hints
.ai_family
= family
;
683 hints
.ai_socktype
= SOCK_STREAM
;
684 if (getaddrinfo(hrp
->hostname
, NULL
, &hints
, &res
) == 0)
686 hrp
->statfile
= _PATH_FTPDSTATFILE
;
687 hrp
->welcome
= _PATH_FTPWELCOME
;
688 hrp
->loginmsg
= _PATH_FTPLOGINMESG
;
689 hrp
->anonuser
= "ftp";
691 thishost
= firsthost
= lhrp
= hrp
;
692 if ((fp
= fopen(_PATH_FTPHOSTS
, "r")) != NULL
) {
693 int addrsize
, gothost
;
697 while ((line
= fgetln(fp
, &len
)) != NULL
) {
703 if (line
[len
- 1] == '\n') {
704 line
[len
- 1] = '\0';
707 if ((mp
= malloc(len
+ 1)) == NULL
)
708 fatalerror("Ran out of memory.");
709 memcpy(mp
, line
, len
);
713 cp
= strtok(line
, " \t");
714 /* skip empty lines */
721 statfile
= _PATH_FTPDSTATFILE
;
722 welcome
= _PATH_FTPWELCOME
;
723 loginmsg
= _PATH_FTPLOGINMESG
;
726 * Preparse the line so we can use its info
727 * for all the addresses associated with
728 * the virtual host name.
729 * Field 0, the virtual host name, is special:
730 * it's already parsed off and will be strdup'ed
731 * later, after we know its canonical form.
733 for (i
= 1; i
< 5 && (cp
= strtok(NULL
, " \t")); i
++)
734 if (*cp
!= '-' && (cp
= strdup(cp
)))
736 case 1: /* anon user permissions */
739 case 2: /* statistics file */
742 case 3: /* welcome message */
745 case 4: /* login message */
748 default: /* programming error */
753 hints
.ai_flags
= AI_PASSIVE
;
754 hints
.ai_family
= family
;
755 hints
.ai_socktype
= SOCK_STREAM
;
756 if (getaddrinfo(vhost
, NULL
, &hints
, &res
) != 0)
758 for (ai
= res
; ai
!= NULL
&& ai
->ai_addr
!= NULL
;
762 for (hrp
= firsthost
; hrp
!= NULL
; hrp
= hrp
->next
) {
765 for (hi
= hrp
->hostinfo
; hi
!= NULL
;
767 if (hi
->ai_addrlen
== ai
->ai_addrlen
&&
770 ai
->ai_addr
->sa_len
) == 0) {
778 if ((hrp
= malloc(sizeof(struct ftphost
))) == NULL
)
780 hrp
->hostname
= NULL
;
783 if (hrp
->hostinfo
&& hrp
->hostinfo
!= res
)
784 freeaddrinfo(hrp
->hostinfo
);
785 insert
= 0; /* host already in the chain */
790 * determine hostname to use.
791 * force defined name if there is a valid alias
792 * otherwise fallback to primary hostname
794 /* XXX: getaddrinfo() can't do alias check */
795 switch(hrp
->hostinfo
->ai_family
) {
797 addr
= &((struct sockaddr_in
*)hrp
->hostinfo
->ai_addr
)->sin_addr
;
798 addrsize
= sizeof(struct in_addr
);
801 addr
= &((struct sockaddr_in6
*)hrp
->hostinfo
->ai_addr
)->sin6_addr
;
802 addrsize
= sizeof(struct in6_addr
);
805 /* should not reach here */
806 freeaddrinfo(hrp
->hostinfo
);
808 free(hrp
); /*not in chain, can free*/
810 hrp
->hostinfo
= NULL
; /*mark as blank*/
814 if ((hp
= getipnodebyaddr(addr
, addrsize
,
815 hrp
->hostinfo
->ai_family
,
816 &hp_error
)) != NULL
) {
817 if (strcmp(vhost
, hp
->h_name
) != 0) {
818 if (hp
->h_aliases
== NULL
)
822 while (hp
->h_aliases
[i
] &&
823 strcmp(vhost
, hp
->h_aliases
[i
]) != 0)
825 if (hp
->h_aliases
[i
] == NULL
)
831 strcmp(hrp
->hostname
, vhost
) != 0) {
833 hrp
->hostname
= NULL
;
835 if (hrp
->hostname
== NULL
&&
836 (hrp
->hostname
= strdup(vhost
)) == NULL
) {
837 freeaddrinfo(hrp
->hostinfo
);
838 hrp
->hostinfo
= NULL
; /* mark as blank */
843 hrp
->anonuser
= anonuser
;
844 hrp
->statfile
= statfile
;
845 hrp
->welcome
= welcome
;
846 hrp
->loginmsg
= loginmsg
;
864 selecthost(union sockunion
*su
)
869 struct in6_addr
*mapped_in6
= NULL
;
875 * XXX IPv4 mapped IPv6 addr consideraton,
876 * specified in rfc2373.
878 if (su
->su_family
== AF_INET6
&&
879 IN6_IS_ADDR_V4MAPPED(&su
->su_sin6
.sin6_addr
))
880 mapped_in6
= &su
->su_sin6
.sin6_addr
;
883 hrp
= thishost
= firsthost
; /* default */
886 while (hrp
!= NULL
) {
887 for (hi
= hrp
->hostinfo
; hi
!= NULL
; hi
= hi
->ai_next
) {
888 if (memcmp(su
, hi
->ai_addr
, hi
->ai_addrlen
) == 0) {
893 /* XXX IPv4 mapped IPv6 addr consideraton */
894 if (hi
->ai_addr
->sa_family
== AF_INET
&& mapped_in6
!= NULL
&&
895 (memcmp(&mapped_in6
->s6_addr
[12],
896 &((struct sockaddr_in
*)hi
->ai_addr
)->sin_addr
,
897 sizeof(struct in_addr
)) == 0)) {
907 /* setup static variables as appropriate */
908 hostname
= thishost
->hostname
;
909 ftpuser
= thishost
->anonuser
;
914 * Helper function for sgetpwnam().
919 char *new = malloc(strlen(s
) + 1);
922 reply(421, "Ran out of memory.");
931 * Save the result of a getpwnam. Used for USER command, since
932 * the data returned must not be clobbered by any other command
934 * NB: The data returned by sgetpwnam() will remain valid until
935 * the next call to this function. Its difference from getpwnam()
936 * is that sgetpwnam() is known to be called from ftpd code only.
938 static struct passwd
*
939 sgetpwnam(char *name
)
941 static struct passwd save
;
944 if ((p
= getpwnam(name
)) == NULL
)
948 free(save
.pw_passwd
);
954 save
.pw_name
= sgetsave(p
->pw_name
);
955 save
.pw_passwd
= sgetsave(p
->pw_passwd
);
956 save
.pw_gecos
= sgetsave(p
->pw_gecos
);
957 save
.pw_dir
= sgetsave(p
->pw_dir
);
958 save
.pw_shell
= sgetsave(p
->pw_shell
);
962 static int login_attempts
; /* number of failed login attempts */
963 static int askpasswd
; /* had user command, ask for passwd */
964 static char curname
[MAXLOGNAME
]; /* current USER name */
968 * Sets global passwd pointer pw if named account exists and is acceptable;
969 * sets askpasswd if a PASS command is expected. If logged in previously,
970 * need to reset state. If name is "ftp" or "anonymous", the name is not in
971 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
972 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
973 * requesting login privileges. Disallow anyone who does not have a standard
974 * shell as returned by getusershell(). Disallow anyone mentioned in the file
975 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
984 reply(530, "Can't change user from guest login.");
986 } else if (dochroot
) {
987 reply(530, "Can't change user from chroot user.");
994 #ifdef VIRTUAL_HOSTING
995 pw
= sgetpwnam(thishost
->anonuser
);
997 pw
= sgetpwnam("ftp");
999 if (strcmp(name
, "ftp") == 0 || strcmp(name
, "anonymous") == 0) {
1000 if (checkuser(_PATH_FTPUSERS
, "ftp", 0, NULL
) ||
1001 checkuser(_PATH_FTPUSERS
, "anonymous", 0, NULL
))
1002 reply(530, "User %s access denied.", name
);
1003 else if (pw
!= NULL
) {
1007 "Guest login ok, send your email address as password.");
1009 reply(530, "User %s unknown.", name
);
1010 if (!askpasswd
&& logging
)
1012 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost
);
1015 if (anon_only
!= 0) {
1016 reply(530, "Sorry, only anonymous ftp allowed.");
1020 if ((pw
= sgetpwnam(name
))) {
1021 if ((shell
= pw
->pw_shell
) == NULL
|| *shell
== 0)
1022 shell
= _PATH_BSHELL
;
1024 while ((cp
= getusershell()) != NULL
)
1025 if (strcmp(cp
, shell
) == 0)
1029 if (cp
== NULL
|| checkuser(_PATH_FTPUSERS
, name
, 1, NULL
)) {
1030 reply(530, "User %s access denied.", name
);
1033 "FTP LOGIN REFUSED FROM %s, %s",
1040 strncpy(curname
, name
, sizeof(curname
)-1);
1044 /* XXX Kluge! The conversation mechanism needs to be fixed. */
1046 if (opiechallenge(&opiedata
, name
, opieprompt
) == 0) {
1047 pwok
= (pw
!= NULL
) &&
1048 opieaccessfile(remotehost
) &&
1049 opiealways(pw
->pw_dir
);
1050 reply(331, "Response to %s %s for %s.",
1051 opieprompt
, pwok
? "requested" : "required", name
);
1054 reply(331, "Password required for %s.", name
);
1058 * Delay before reading passwd after first failed
1059 * attempt to slow down passwd-guessing programs.
1062 sleep(login_attempts
);
1066 * Check if a user is in the file "fname",
1067 * return a pointer to a malloc'd string with the rest
1068 * of the matching line in "residue" if not NULL.
1071 checkuser(char *fname
, char *name
, int pwset
, char **residue
)
1076 char *line
, *mp
, *p
;
1078 if ((fd
= fopen(fname
, "r")) != NULL
) {
1079 while (!found
&& (line
= fgetln(fd
, &len
)) != NULL
) {
1083 if (line
[len
- 1] == '\n') {
1084 line
[len
- 1] = '\0';
1087 if ((mp
= malloc(len
+ 1)) == NULL
)
1088 fatalerror("Ran out of memory.");
1089 memcpy(mp
, line
, len
);
1093 /* avoid possible leading and trailing whitespace */
1094 p
= strtok(line
, " \t");
1095 /* skip empty lines */
1099 * if first chr is '@', check group membership
1105 if (p
[1] == '\0') /* single @ matches anyone */
1108 if ((grp
= getgrnam(p
+1)) == NULL
)
1111 * Check user's default group
1113 if (pwset
&& grp
->gr_gid
== pw
->pw_gid
)
1116 * Check supplementary groups
1118 while (!found
&& grp
->gr_mem
[i
])
1119 found
= strcmp(name
,
1125 * Otherwise, just check for username match
1128 found
= strcmp(p
, name
) == 0;
1130 * Save the rest of line to "residue" if matched
1132 if (found
&& residue
) {
1133 if ((p
= strtok(NULL
, "")) != NULL
)
1134 p
+= strspn(p
, " \t");
1136 if ((*residue
= strdup(p
)) == NULL
)
1137 fatalerror("Ran out of memory.");
1151 * Terminate login as previous user, if any, resetting state;
1152 * used when USER command is given or login fails.
1162 if (logged_in
&& dowtmp
)
1163 ftpd_logwtmp(ttyline
, "", NULL
);
1166 /* XXX Missing LOGIN_SETMAC */
1167 setusercontext(NULL
, getpwuid(0), 0,
1168 LOGIN_SETPRIORITY
|LOGIN_SETRESOURCES
|LOGIN_SETUMASK
);
1172 if ((e
= pam_setcred(pamh
, PAM_DELETE_CRED
)) != PAM_SUCCESS
)
1173 syslog(LOG_ERR
, "pam_setcred: %s", pam_strerror(pamh
, e
));
1174 if ((e
= pam_close_session(pamh
,0)) != PAM_SUCCESS
)
1175 syslog(LOG_ERR
, "pam_close_session: %s", pam_strerror(pamh
, e
));
1176 if ((e
= pam_end(pamh
, e
)) != PAM_SUCCESS
)
1177 syslog(LOG_ERR
, "pam_end: %s", pam_strerror(pamh
, e
));
1189 * the following code is stolen from imap-uw PAM authentication module and
1192 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1195 const char *uname
; /* user name */
1196 const char *pass
; /* password */
1198 typedef struct cred_t cred_t
;
1201 auth_conv(int num_msg
, const struct pam_message
**msg
,
1202 struct pam_response
**resp
, void *appdata
)
1205 cred_t
*cred
= (cred_t
*) appdata
;
1206 struct pam_response
*reply
;
1208 reply
= calloc(num_msg
, sizeof *reply
);
1212 for (i
= 0; i
< num_msg
; i
++) {
1213 switch (msg
[i
]->msg_style
) {
1214 case PAM_PROMPT_ECHO_ON
: /* assume want user name */
1215 reply
[i
].resp_retcode
= PAM_SUCCESS
;
1216 reply
[i
].resp
= COPY_STRING(cred
->uname
);
1217 /* PAM frees resp. */
1219 case PAM_PROMPT_ECHO_OFF
: /* assume want password */
1220 reply
[i
].resp_retcode
= PAM_SUCCESS
;
1221 reply
[i
].resp
= COPY_STRING(cred
->pass
);
1222 /* PAM frees resp. */
1226 reply
[i
].resp_retcode
= PAM_SUCCESS
;
1227 reply
[i
].resp
= NULL
;
1229 default: /* unknown message style */
1231 return PAM_CONV_ERR
;
1240 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1241 * authenticated, or 1 if not authenticated. If some sort of PAM system
1242 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1243 * function returns -1. This can be used as an indication that we should
1244 * fall back to a different authentication mechanism.
1247 auth_pam(struct passwd
**ppw
, const char *pass
)
1249 const char *tmpl_user
;
1253 cred_t auth_cred
= { (*ppw
)->pw_name
, pass
};
1254 struct pam_conv conv
= { &auth_conv
, &auth_cred
};
1256 e
= pam_start("ftpd", (*ppw
)->pw_name
, &conv
, &pamh
);
1257 if (e
!= PAM_SUCCESS
) {
1259 * In OpenPAM, it's OK to pass NULL to pam_strerror()
1260 * if context creation has failed in the first place.
1262 syslog(LOG_ERR
, "pam_start: %s", pam_strerror(NULL
, e
));
1266 e
= pam_set_item(pamh
, PAM_RHOST
, remotehost
);
1267 if (e
!= PAM_SUCCESS
) {
1268 syslog(LOG_ERR
, "pam_set_item(PAM_RHOST): %s",
1269 pam_strerror(pamh
, e
));
1270 if ((e
= pam_end(pamh
, e
)) != PAM_SUCCESS
) {
1271 syslog(LOG_ERR
, "pam_end: %s", pam_strerror(pamh
, e
));
1277 e
= pam_authenticate(pamh
, 0);
1281 * With PAM we support the concept of a "template"
1282 * user. The user enters a login name which is
1283 * authenticated by PAM, usually via a remote service
1284 * such as RADIUS or TACACS+. If authentication
1285 * succeeds, a different but related "template" name
1286 * is used for setting the credentials, shell, and
1287 * home directory. The name the user enters need only
1288 * exist on the remote authentication server, but the
1289 * template name must be present in the local password
1292 * This is supported by two various mechanisms in the
1293 * individual modules. However, from the application's
1294 * point of view, the template user is always passed
1295 * back as a changed value of the PAM_USER item.
1297 if ((e
= pam_get_item(pamh
, PAM_USER
, &item
)) ==
1299 tmpl_user
= (const char *) item
;
1300 if (strcmp((*ppw
)->pw_name
, tmpl_user
) != 0)
1301 *ppw
= getpwnam(tmpl_user
);
1303 syslog(LOG_ERR
, "Couldn't get PAM_USER: %s",
1304 pam_strerror(pamh
, e
));
1309 case PAM_USER_UNKNOWN
:
1315 syslog(LOG_ERR
, "pam_authenticate: %s", pam_strerror(pamh
, e
));
1321 e
= pam_acct_mgmt(pamh
, 0);
1322 if (e
!= PAM_SUCCESS
) {
1323 syslog(LOG_ERR
, "pam_acct_mgmt: %s",
1324 pam_strerror(pamh
, e
));
1330 if ((e
= pam_end(pamh
, e
)) != PAM_SUCCESS
) {
1331 syslog(LOG_ERR
, "pam_end: %s", pam_strerror(pamh
, e
));
1338 #endif /* USE_PAM */
1346 login_cap_t
*lc
= NULL
;
1351 char *residue
= NULL
;
1354 if (logged_in
|| askpasswd
== 0) {
1355 reply(503, "Login with USER first.");
1359 if (!guest
) { /* "ftp" is only account allowed no password */
1361 rval
= 1; /* failure below */
1365 rval
= auth_pam(&pw
, passwd
);
1371 if (opieverify(&opiedata
, passwd
) == 0)
1372 xpasswd
= pw
->pw_passwd
;
1374 xpasswd
= crypt(passwd
, pw
->pw_passwd
);
1375 if (passwd
[0] == '\0' && pw
->pw_passwd
[0] != '\0')
1381 rval
= strcmp(pw
->pw_passwd
, xpasswd
);
1382 if (pw
->pw_expire
&& time(NULL
) >= pw
->pw_expire
)
1383 rval
= 1; /* failure */
1386 * If rval == 1, the user failed the authentication check
1387 * above. If rval == 0, either PAM or local authentication
1391 reply(530, "Login incorrect.");
1394 "FTP LOGIN FAILED FROM %s",
1396 syslog(LOG_AUTHPRIV
| LOG_NOTICE
,
1397 "FTP LOGIN FAILED FROM %s, %s",
1398 remotehost
, curname
);
1401 if (login_attempts
++ >= 5) {
1403 "repeated login failures from %s",
1410 login_attempts
= 0; /* this time successful */
1411 if (setegid(pw
->pw_gid
) < 0) {
1412 reply(550, "Can't set gid.");
1415 /* May be overridden by login.conf */
1418 if ((lc
= login_getpwclass(pw
)) != NULL
) {
1419 char remote_ip
[NI_MAXHOST
];
1421 if (getnameinfo((struct sockaddr
*)&his_addr
, his_addr
.su_len
,
1422 remote_ip
, sizeof(remote_ip
) - 1, NULL
, 0,
1425 remote_ip
[sizeof(remote_ip
) - 1] = 0;
1426 if (!auth_hostok(lc
, remotehost
, remote_ip
)) {
1427 syslog(LOG_INFO
|LOG_AUTH
,
1428 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1430 reply(530, "Permission denied.");
1434 if (!auth_timeok(lc
, time(NULL
))) {
1435 reply(530, "Login not available right now.");
1440 /* XXX Missing LOGIN_SETMAC */
1441 setusercontext(lc
, pw
, 0,
1442 LOGIN_SETLOGIN
|LOGIN_SETGROUP
|LOGIN_SETPRIORITY
|
1443 LOGIN_SETRESOURCES
|LOGIN_SETUMASK
);
1445 setlogin(pw
->pw_name
);
1446 initgroups(pw
->pw_name
, pw
->pw_gid
);
1451 if ((e
= pam_open_session(pamh
, 0)) != PAM_SUCCESS
) {
1452 syslog(LOG_ERR
, "pam_open_session: %s", pam_strerror(pamh
, e
));
1453 } else if ((e
= pam_setcred(pamh
, PAM_ESTABLISH_CRED
)) != PAM_SUCCESS
) {
1454 syslog(LOG_ERR
, "pam_setcred: %s", pam_strerror(pamh
, e
));
1459 /* open wtmp before chroot */
1461 ftpd_logwtmp(ttyline
, pw
->pw_name
,
1462 (struct sockaddr
*)&his_addr
);
1465 if (guest
&& stats
&& statfd
< 0)
1466 #ifdef VIRTUAL_HOSTING
1467 statfd
= open(thishost
->statfile
, O_WRONLY
|O_APPEND
);
1469 statfd
= open(_PATH_FTPDSTATFILE
, O_WRONLY
|O_APPEND
);
1475 checkuser(_PATH_FTPCHROOT
, pw
->pw_name
, 1, &residue
)
1476 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1477 || login_getcapbool(lc
, "ftp-chroot", 0)
1482 * For a chrooted local user,
1483 * a) see whether ftpchroot(5) specifies a chroot directory,
1484 * b) extract the directory pathname from the line,
1485 * c) expand it to the absolute pathname if necessary.
1487 if (dochroot
&& residue
&&
1488 (chrootdir
= strtok(residue
, " \t")) != NULL
) {
1489 if (chrootdir
[0] != '/')
1490 asprintf(&chrootdir
, "%s/%s", pw
->pw_dir
, chrootdir
);
1492 chrootdir
= strdup(chrootdir
); /* make it permanent */
1493 if (chrootdir
== NULL
)
1494 fatalerror("Ran out of memory.");
1496 if (guest
|| dochroot
) {
1498 * If no chroot directory set yet, use the login directory.
1499 * Copy it so it can be modified while pw->pw_dir stays intact.
1501 if (chrootdir
== NULL
&&
1502 (chrootdir
= strdup(pw
->pw_dir
)) == NULL
)
1503 fatalerror("Ran out of memory.");
1505 * Check for the "/chroot/./home" syntax,
1506 * separate the chroot and home directory pathnames.
1508 if ((homedir
= strstr(chrootdir
, "/./")) != NULL
) {
1509 *(homedir
++) = '\0'; /* wipe '/' */
1510 homedir
++; /* skip '.' */
1513 * We MUST do a chdir() after the chroot. Otherwise
1514 * the old current directory will be accessible as "."
1515 * outside the new root!
1520 * Finally, do chroot()
1522 if (chroot(chrootdir
) < 0) {
1523 reply(550, "Can't change root.");
1526 } else /* real user w/o chroot */
1527 homedir
= pw
->pw_dir
;
1529 * Set euid *before* doing chdir() so
1530 * a) the user won't be carried to a directory that he couldn't reach
1531 * on his own due to no permission to upper path components,
1532 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1533 * (uid 0 has no root power over NFS if not mapped explicitly.)
1535 if (seteuid(pw
->pw_uid
) < 0) {
1536 reply(550, "Can't set uid.");
1539 if (chdir(homedir
) < 0) {
1540 if (guest
|| dochroot
) {
1541 reply(550, "Can't change to base directory.");
1544 if (chdir("/") < 0) {
1545 reply(550, "Root is inaccessible.");
1548 lreply(230, "No directory! Logging in with home=/.");
1553 * Display a login message, if it exists.
1554 * N.B. reply(230,) must follow the message.
1556 #ifdef VIRTUAL_HOSTING
1557 fd
= fopen(thishost
->loginmsg
, "r");
1559 fd
= fopen(_PATH_FTPLOGINMESG
, "r");
1562 char *cp
, line
[LINE_MAX
];
1564 while (fgets(line
, sizeof(line
), fd
) != NULL
) {
1565 if ((cp
= strchr(line
, '\n')) != NULL
)
1567 lreply(230, "%s", line
);
1575 ident
= strdup(passwd
);
1577 fatalerror("Ran out of memory.");
1579 reply(230, "Guest login ok, access restrictions apply.");
1581 #ifdef VIRTUAL_HOSTING
1582 if (thishost
!= firsthost
)
1583 snprintf(proctitle
, sizeof(proctitle
),
1584 "%s: anonymous(%s)/%s", remotehost
, hostname
,
1588 snprintf(proctitle
, sizeof(proctitle
),
1589 "%s: anonymous/%s", remotehost
, passwd
);
1590 setproctitle("%s", proctitle
);
1591 #endif /* SETPROCTITLE */
1593 syslog(LOG_INFO
, "ANONYMOUS FTP LOGIN FROM %s, %s",
1594 remotehost
, passwd
);
1597 reply(230, "User %s logged in, "
1598 "access restrictions apply.", pw
->pw_name
);
1600 reply(230, "User %s logged in.", pw
->pw_name
);
1603 snprintf(proctitle
, sizeof(proctitle
),
1604 "%s: user/%s", remotehost
, pw
->pw_name
);
1605 setproctitle("%s", proctitle
);
1606 #endif /* SETPROCTITLE */
1608 syslog(LOG_INFO
, "FTP LOGIN FROM %s as %s",
1609 remotehost
, pw
->pw_name
);
1611 if (logging
&& (guest
|| dochroot
))
1612 syslog(LOG_INFO
, "session root changed to %s", chrootdir
);
1620 /* Forget all about it... */
1630 retrieve(char *cmd
, char *name
)
1634 int (*closefunc
)(FILE *);
1638 fin
= fopen(name
, "r"), closefunc
= fclose
;
1643 snprintf(line
, sizeof(line
), cmd
, name
), name
= line
;
1644 fin
= ftpd_popen(line
, "r"), closefunc
= ftpd_pclose
;
1646 st
.st_blksize
= BUFSIZ
;
1650 perror_reply(550, name
);
1652 LOGCMD("get", name
);
1659 if (fstat(fileno(fin
), &st
) < 0) {
1660 perror_reply(550, name
);
1663 if (!S_ISREG(st
.st_mode
)) {
1665 * Never sending a raw directory is a workaround
1666 * for buggy clients that will attempt to RETR
1667 * a directory before listing it, e.g., Mozilla.
1668 * Preventing a guest from getting irregular files
1669 * is a simple security measure.
1671 if (S_ISDIR(st
.st_mode
) || guest
) {
1672 reply(550, "%s: not a plain file.", name
);
1676 /* st.st_blksize is set for all descriptor types */
1679 if (restart_point
) {
1680 if (type
== TYPE_A
) {
1687 if ((c
=getc(fin
)) == EOF
) {
1688 perror_reply(550, name
);
1694 } else if (lseek(fileno(fin
), restart_point
, L_SET
) < 0) {
1695 perror_reply(550, name
);
1699 dout
= dataconn(name
, st
.st_size
, "w");
1703 send_data(fin
, dout
, st
.st_blksize
, st
.st_size
,
1704 restart_point
== 0 && cmd
== NULL
&& S_ISREG(st
.st_mode
));
1705 if (cmd
== NULL
&& guest
&& stats
&& byte_count
> 0)
1706 logxfer(name
, byte_count
, start
);
1712 LOGBYTES("get", name
, byte_count
);
1717 store(char *name
, char *mode
, int unique
)
1721 int (*closefunc
)(FILE *);
1723 if (*mode
== 'a') { /* APPE */
1725 /* Programming error */
1726 syslog(LOG_ERR
, "Internal: unique flag to APPE");
1729 if (guest
&& noguestmod
) {
1730 reply(550, "Appending to existing file denied.");
1733 restart_point
= 0; /* not affected by preceding REST */
1735 if (unique
) /* STOU overrides REST */
1737 if (guest
&& noguestmod
) {
1738 if (restart_point
) { /* guest STOR w/REST */
1739 reply(550, "Modifying existing file denied.");
1741 } else /* treat guest STOR as STOU */
1746 mode
= "r+"; /* so ASCII manual seek can work */
1748 if ((fd
= guniquefd(name
, &name
)) < 0)
1750 fout
= fdopen(fd
, mode
);
1752 fout
= fopen(name
, mode
);
1755 perror_reply(553, name
);
1759 if (restart_point
) {
1760 if (type
== TYPE_A
) {
1767 if ((c
=getc(fout
)) == EOF
) {
1768 perror_reply(550, name
);
1775 * We must do this seek to "current" position
1776 * because we are changing from reading to
1779 if (fseeko(fout
, 0, SEEK_CUR
) < 0) {
1780 perror_reply(550, name
);
1783 } else if (lseek(fileno(fout
), restart_point
, L_SET
) < 0) {
1784 perror_reply(550, name
);
1788 din
= dataconn(name
, -1, "r");
1791 if (receive_data(din
, fout
) == 0) {
1793 reply(226, "Transfer complete (unique file name:%s).",
1796 reply(226, "Transfer complete.");
1802 LOGBYTES(*mode
== 'a' ? "append" : "put", name
, byte_count
);
1806 LOGCMD(*mode
== 'a' ? "append" : "put" , name
);
1811 getdatasock(char *mode
)
1813 int on
= 1, s
, t
, tries
;
1816 return (fdopen(data
, mode
));
1818 s
= socket(data_dest
.su_family
, SOCK_STREAM
, 0);
1821 if (setsockopt(s
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) < 0)
1822 syslog(LOG_WARNING
, "data setsockopt (SO_REUSEADDR): %m");
1823 /* anchor socket to avoid multi-homing problems */
1824 data_source
= ctrl_addr
;
1825 data_source
.su_port
= htons(dataport
);
1827 for (tries
= 1; ; tries
++) {
1829 * We should loop here since it's possible that
1830 * another ftpd instance has passed this point and is
1831 * trying to open a data connection in active mode now.
1832 * Until the other connection is opened, we'll be getting
1833 * EADDRINUSE because no SOCK_STREAM sockets in the system
1834 * can share both local and remote addresses, localIP:20
1835 * and *:* in this case.
1837 if (bind(s
, (struct sockaddr
*)&data_source
,
1838 data_source
.su_len
) >= 0)
1840 if (errno
!= EADDRINUSE
|| tries
> 10)
1844 seteuid(pw
->pw_uid
);
1846 if (data_source
.su_family
== AF_INET
)
1848 on
= IPTOS_THROUGHPUT
;
1849 if (setsockopt(s
, IPPROTO_IP
, IP_TOS
, &on
, sizeof(int)) < 0)
1850 syslog(LOG_WARNING
, "data setsockopt (IP_TOS): %m");
1855 * Turn off push flag to keep sender TCP from sending short packets
1856 * at the boundaries of each write().
1859 if (setsockopt(s
, IPPROTO_TCP
, TCP_NOPUSH
, &on
, sizeof on
) < 0)
1860 syslog(LOG_WARNING
, "data setsockopt (TCP_NOPUSH): %m");
1862 return (fdopen(s
, mode
));
1864 /* Return the real value of errno (close may change it) */
1866 seteuid(pw
->pw_uid
);
1873 dataconn(char *name
, off_t size
, char *mode
)
1877 int retry
= 0, tos
, conerrno
;
1882 snprintf(sizebuf
, sizeof(sizebuf
),
1883 " (%jd bytes)", (intmax_t)size
);
1887 union sockunion from
;
1888 socklen_t fromlen
= ctrl_addr
.su_len
;
1890 struct timeval timeout
;
1894 FD_SET(pdata
, &set
);
1896 timeout
.tv_usec
= 0;
1897 timeout
.tv_sec
= 120;
1900 * Granted a socket is in the blocking I/O mode,
1901 * accept() will block after a successful select()
1902 * if the selected connection dies in between.
1903 * Therefore set the non-blocking I/O flag here.
1905 if ((flags
= fcntl(pdata
, F_GETFL
, 0)) == -1 ||
1906 fcntl(pdata
, F_SETFL
, flags
| O_NONBLOCK
) == -1)
1908 if (select(pdata
+1, &set
, NULL
, NULL
, &timeout
) <= 0 ||
1909 (s
= accept(pdata
, (struct sockaddr
*) &from
, &fromlen
)) < 0)
1914 * Unset the inherited non-blocking I/O flag
1915 * on the child socket so stdio can work on it.
1917 if ((flags
= fcntl(pdata
, F_GETFL
, 0)) == -1 ||
1918 fcntl(pdata
, F_SETFL
, flags
& ~O_NONBLOCK
) == -1)
1921 if (from
.su_family
== AF_INET
)
1923 tos
= IPTOS_THROUGHPUT
;
1924 if (setsockopt(s
, IPPROTO_IP
, IP_TOS
, &tos
, sizeof(int)) < 0)
1925 syslog(LOG_WARNING
, "pdata setsockopt (IP_TOS): %m");
1928 reply(150, "Opening %s mode data connection for '%s'%s.",
1929 type
== TYPE_A
? "ASCII" : "BINARY", name
, sizebuf
);
1930 return (fdopen(pdata
, mode
));
1932 reply(425, "Can't open data connection.");
1938 reply(125, "Using existing data connection for '%s'%s.",
1941 return (fdopen(data
, mode
));
1944 data_dest
= his_addr
;
1947 file
= getdatasock(mode
);
1949 char hostbuf
[NI_MAXHOST
], portbuf
[NI_MAXSERV
];
1951 if (getnameinfo((struct sockaddr
*)&data_source
,
1953 hostbuf
, sizeof(hostbuf
) - 1,
1954 portbuf
, sizeof(portbuf
) - 1,
1955 NI_NUMERICHOST
|NI_NUMERICSERV
))
1956 *hostbuf
= *portbuf
= 0;
1957 hostbuf
[sizeof(hostbuf
) - 1] = 0;
1958 portbuf
[sizeof(portbuf
) - 1] = 0;
1959 reply(425, "Can't create data socket (%s,%s): %s.",
1960 hostbuf
, portbuf
, strerror(errno
));
1963 data
= fileno(file
);
1965 if (connect(data
, (struct sockaddr
*)&data_dest
,
1966 data_dest
.su_len
) == 0)
1971 if (conerrno
== EADDRINUSE
) {
1977 } while (retry
<= swaitmax
);
1978 if (conerrno
!= 0) {
1979 reply(425, "Can't build data connection: %s.",
1980 strerror(conerrno
));
1983 reply(150, "Opening %s mode data connection for '%s'%s.",
1984 type
== TYPE_A
? "ASCII" : "BINARY", name
, sizebuf
);
1989 * A helper macro to avoid code duplication
1990 * in send_data() and receive_data().
1992 * XXX We have to block SIGURG during putc() because BSD stdio
1993 * is unable to restart interrupted write operations and hence
1994 * the entire buffer contents will be lost as soon as a write()
1995 * call indicates EINTR to stdio.
1997 #define FTPD_PUTC(ch, file, label) \
2003 ret = putc((ch), (file)); \
2005 CHECKOOB(return (-1)) \
2006 else if (ferror(file)) \
2009 } while (ret == EOF); \
2013 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
2014 * encapsulation of the data subject to Mode, Structure, and Type.
2016 * NB: Form isn't handled.
2019 send_data(FILE *instr
, FILE *outstr
, size_t blksize
, off_t filesize
, int isreg
)
2021 int c
, cp
, filefd
, netfd
;
2032 CHECKOOB(return (-1))
2033 else if (c
== EOF
&& ferror(instr
))
2036 if (ferror(instr
)) { /* resume after OOB */
2040 if (feof(instr
)) /* EOF */
2042 syslog(LOG_ERR
, "Internal: impossible condition"
2043 " on file after getc()");
2046 if (c
== '\n' && cp
!= '\r') {
2047 FTPD_PUTC('\r', outstr
, data_err
);
2050 FTPD_PUTC(c
, outstr
, data_err
);
2054 #ifdef notyet /* BSD stdio isn't ready for that */
2055 while (fflush(outstr
) == EOF
) {
2056 CHECKOOB(return (-1))
2064 if (fflush(outstr
) == EOF
)
2067 reply(226, "Transfer complete.");
2073 * isreg is only set if we are not doing restart and we
2074 * are sending a regular file
2076 netfd
= fileno(outstr
);
2077 filefd
= fileno(instr
);
2080 char *msg
= "Transfer complete.";
2086 while (filesize
> 0) {
2087 err
= sendfile(filefd
, netfd
, offset
, 0,
2090 * Calculate byte_count before OOB processing.
2091 * It can be used in myoob() later.
2096 CHECKOOB(return (-1))
2097 else if (err
== -1) {
2098 if (errno
!= EINTR
&&
2099 cnt
== 0 && offset
== 0)
2103 if (err
== -1) /* resume after OOB */
2106 * We hit the EOF prematurely.
2107 * Perhaps the file was externally truncated.
2110 msg
= "Transfer finished due to "
2111 "premature end of file.";
2116 reply(226, "%s", msg
);
2121 if ((buf
= malloc(blksize
)) == NULL
) {
2123 reply(451, "Ran out of memory.");
2131 cnt
= read(filefd
, buf
, blksize
);
2132 CHECKOOB(free(buf
); return (-1))
2137 if (cnt
< 0) /* resume after OOB */
2139 if (cnt
== 0) /* EOF */
2141 for (len
= cnt
, bp
= buf
; len
> 0;) {
2142 cnt
= write(netfd
, bp
, len
);
2143 CHECKOOB(free(buf
); return (-1))
2157 reply(226, "Transfer complete.");
2161 reply(550, "Unimplemented TYPE %d in send_data.", type
);
2167 perror_reply(426, "Data connection");
2172 perror_reply(551, "Error on input file");
2177 * Transfer data from peer to "outstr" using the appropriate encapulation of
2178 * the data subject to Mode, Structure, and Type.
2180 * N.B.: Form isn't handled.
2183 receive_data(FILE *instr
, FILE *outstr
)
2199 cnt
= read(fileno(instr
), buf
, sizeof(buf
));
2200 CHECKOOB(return (-1))
2203 if (cnt
< 0) /* resume after OOB */
2205 if (cnt
== 0) /* EOF */
2207 for (len
= cnt
, bp
= buf
; len
> 0;) {
2208 cnt
= write(fileno(outstr
), bp
, len
);
2209 CHECKOOB(return (-1))
2224 reply(553, "TYPE E not implemented.");
2231 CHECKOOB(return (-1))
2232 else if (c
== EOF
&& ferror(instr
))
2234 if (c
== EOF
&& ferror(instr
)) { /* resume after OOB */
2241 FTPD_PUTC('\r', outstr
, file_err
);
2251 /* Check for EOF here in order not to lose last \r. */
2253 if (feof(instr
)) /* EOF */
2255 syslog(LOG_ERR
, "Internal: impossible condition"
2256 " on data stream after getc()");
2261 FTPD_PUTC(c
, outstr
, file_err
);
2264 #ifdef notyet /* BSD stdio isn't ready for that */
2265 while (fflush(outstr
) == EOF
) {
2266 CHECKOOB(return (-1))
2274 if (fflush(outstr
) == EOF
)
2279 "WARNING! %d bare linefeeds received in ASCII mode.",
2281 printf(" File may not have transferred correctly.\r\n");
2286 reply(550, "Unimplemented TYPE %d in receive_data.", type
);
2292 perror_reply(426, "Data connection");
2297 perror_reply(452, "Error writing to file");
2302 statfilecmd(char *filename
)
2307 char line
[LINE_MAX
];
2310 code
= lstat(filename
, &st
) == 0 && S_ISDIR(st
.st_mode
) ? 212 : 213;
2311 snprintf(line
, sizeof(line
), _PATH_LS
" -lgA %s", filename
);
2312 fin
= ftpd_popen(line
, "r");
2313 lreply(code
, "Status of %s:", filename
);
2315 while ((c
= getc(fin
)) != EOF
) {
2317 if (ferror(stdout
)){
2318 perror_reply(421, "Control connection");
2324 perror_reply(551, filename
);
2331 * RFC 959 says neutral text should be prepended before
2332 * a leading 3-digit number followed by whitespace, but
2333 * many ftp clients can be confused by any leading digits,
2334 * as a matter of fact.
2336 if (atstart
&& isdigit(c
))
2339 atstart
= (c
== '\n');
2342 reply(code
, "End of status.");
2348 union sockunion
*su
;
2350 char hname
[NI_MAXHOST
];
2354 lreply(211, "%s FTP server status:", hostname
);
2355 printf(" %s\r\n", version
);
2357 lreply(211, "FTP server status:");
2358 printf(" Connected to %s", remotehost
);
2359 if (!getnameinfo((struct sockaddr
*)&his_addr
, his_addr
.su_len
,
2360 hname
, sizeof(hname
) - 1, NULL
, 0, NI_NUMERICHOST
)) {
2361 hname
[sizeof(hname
) - 1] = 0;
2362 if (strcmp(hname
, remotehost
) != 0)
2363 printf(" (%s)", hname
);
2368 printf(" Logged in anonymously\r\n");
2370 printf(" Logged in as %s\r\n", pw
->pw_name
);
2371 } else if (askpasswd
)
2372 printf(" Waiting for password\r\n");
2374 printf(" Waiting for user name\r\n");
2375 printf(" TYPE: %s", typenames
[type
]);
2376 if (type
== TYPE_A
|| type
== TYPE_E
)
2377 printf(", FORM: %s", formnames
[form
]);
2380 printf(" %d", CHAR_BIT
);
2382 printf(" %d", bytesize
); /* need definition! */
2384 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2385 strunames
[stru
], modenames
[mode
]);
2387 printf(" Data connection open\r\n");
2388 else if (pdata
!= -1) {
2392 } else if (usedefault
== 0) {
2396 #define UC(b) (((int) b) & 0xff)
2398 printf(" EPSV only mode (EPSV ALL)\r\n");
2403 if (su
->su_family
== AF_INET
) {
2404 a
= (u_char
*) &su
->su_sin
.sin_addr
;
2405 p
= (u_char
*) &su
->su_sin
.sin_port
;
2406 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2407 ispassive
? "PASV" : "PORT",
2408 UC(a
[0]), UC(a
[1]), UC(a
[2]), UC(a
[3]),
2409 UC(p
[0]), UC(p
[1]));
2416 switch (su
->su_family
) {
2418 a
= (u_char
*) &su
->su_sin
.sin_addr
;
2419 p
= (u_char
*) &su
->su_sin
.sin_port
;
2420 alen
= sizeof(su
->su_sin
.sin_addr
);
2424 a
= (u_char
*) &su
->su_sin6
.sin6_addr
;
2425 p
= (u_char
*) &su
->su_sin6
.sin6_port
;
2426 alen
= sizeof(su
->su_sin6
.sin6_addr
);
2434 printf(" %s (%d,%d,", ispassive
? "LPSV" : "LPRT",
2436 for (i
= 0; i
< alen
; i
++)
2437 printf("%d,", UC(a
[i
]));
2438 printf("%d,%d,%d)\r\n", 2, UC(p
[0]), UC(p
[1]));
2447 switch (su
->su_family
) {
2459 union sockunion tmp
;
2462 if (tmp
.su_family
== AF_INET6
)
2463 tmp
.su_sin6
.sin6_scope_id
= 0;
2464 if (!getnameinfo((struct sockaddr
*)&tmp
, tmp
.su_len
,
2465 hname
, sizeof(hname
) - 1, NULL
, 0,
2467 hname
[sizeof(hname
) - 1] = 0;
2468 printf(" %s |%d|%s|%d|\r\n",
2469 ispassive
? "EPSV" : "EPRT",
2470 af
, hname
, htons(tmp
.su_port
));
2476 printf(" No data connection\r\n");
2477 reply(211, "End of status.");
2484 reply(451, "Error in server: %s", s
);
2485 reply(221, "Closing connection due to server error.");
2491 reply(int n
, const char *fmt
, ...)
2502 syslog(LOG_DEBUG
, "<--- %d ", n
);
2504 vsyslog(LOG_DEBUG
, fmt
, ap
);
2510 lreply(int n
, const char *fmt
, ...)
2521 syslog(LOG_DEBUG
, "<--- %d- ", n
);
2523 vsyslog(LOG_DEBUG
, fmt
, ap
);
2532 reply(250, "%s command successful.", s
);
2539 reply(502, "%s command not implemented.", s
);
2548 if ((cp
= strchr(cbuf
,'\n')))
2550 reply(500, "%s: command not understood.", cbuf
);
2558 LOGCMD("delete", name
);
2559 if (lstat(name
, &st
) < 0) {
2560 perror_reply(550, name
);
2563 if (S_ISDIR(st
.st_mode
)) {
2564 if (rmdir(name
) < 0) {
2565 perror_reply(550, name
);
2570 if (guest
&& noguestmod
) {
2571 reply(550, "Operation not permitted.");
2574 if (unlink(name
) < 0) {
2575 perror_reply(550, name
);
2586 if (chdir(path
) < 0)
2587 perror_reply(550, path
);
2597 LOGCMD("mkdir", name
);
2598 if (guest
&& noguestmkd
)
2599 reply(550, "Operation not permitted.");
2600 else if (mkdir(name
, 0777) < 0)
2601 perror_reply(550, name
);
2603 if ((s
= doublequote(name
)) == NULL
)
2604 fatalerror("Ran out of memory.");
2605 reply(257, "\"%s\" directory created.", s
);
2611 removedir(char *name
)
2614 LOGCMD("rmdir", name
);
2615 if (rmdir(name
) < 0)
2616 perror_reply(550, name
);
2624 char *s
, path
[MAXPATHLEN
+ 1];
2626 if (getcwd(path
, sizeof(path
)) == NULL
)
2627 perror_reply(550, "Get current directory");
2629 if ((s
= doublequote(path
)) == NULL
)
2630 fatalerror("Ran out of memory.");
2631 reply(257, "\"%s\" is current directory.", s
);
2637 renamefrom(char *name
)
2641 if (guest
&& noguestmod
) {
2642 reply(550, "Operation not permitted.");
2645 if (lstat(name
, &st
) < 0) {
2646 perror_reply(550, name
);
2649 reply(350, "File exists, ready for destination name.");
2654 renamecmd(char *from
, char *to
)
2658 LOGCMD2("rename", from
, to
);
2660 if (guest
&& (stat(to
, &st
) == 0)) {
2661 reply(550, "%s: permission denied.", to
);
2665 if (rename(from
, to
) < 0)
2666 perror_reply(550, "rename");
2672 dolog(struct sockaddr
*who
)
2674 char who_name
[NI_MAXHOST
];
2676 realhostname_sa(remotehost
, sizeof(remotehost
) - 1, who
, who
->sa_len
);
2677 remotehost
[sizeof(remotehost
) - 1] = 0;
2678 if (getnameinfo(who
, who
->sa_len
,
2679 who_name
, sizeof(who_name
) - 1, NULL
, 0, NI_NUMERICHOST
))
2681 who_name
[sizeof(who_name
) - 1] = 0;
2684 #ifdef VIRTUAL_HOSTING
2685 if (thishost
!= firsthost
)
2686 snprintf(proctitle
, sizeof(proctitle
), "%s: connected (to %s)",
2687 remotehost
, hostname
);
2690 snprintf(proctitle
, sizeof(proctitle
), "%s: connected",
2692 setproctitle("%s", proctitle
);
2693 #endif /* SETPROCTITLE */
2696 #ifdef VIRTUAL_HOSTING
2697 if (thishost
!= firsthost
)
2698 syslog(LOG_INFO
, "connection from %s (%s) to %s",
2699 remotehost
, who_name
, hostname
);
2702 syslog(LOG_INFO
, "connection from %s (%s)",
2703 remotehost
, who_name
);
2708 * Record logout in wtmp file
2709 * and exit with supplied status.
2712 dologout(int status
)
2715 if (logged_in
&& dowtmp
) {
2717 ftpd_logwtmp(ttyline
, "", NULL
);
2719 /* beware of flushing buffers after a SIGPIPE */
2737 syslog(LOG_ERR
, "Internal: maskurg() while no transfer");
2742 sigaddset(&sset
, SIGURG
);
2743 sigprocmask(flag
? SIG_BLOCK
: SIG_UNBLOCK
, &sset
, NULL
);
2753 syslog(LOG_ERR
, "Internal: flagxfer(1): "
2754 "transfer already under way");
2760 syslog(LOG_ERR
, "Internal: flagxfer(0): "
2761 "no active transfer");
2768 * Returns 0 if OK to resume or -1 if abort requested.
2777 syslog(LOG_ERR
, "Internal: myoob() while no transfer");
2781 ret
= get_line(cp
, 7, stdin
);
2783 reply(221, "You could at least say goodbye.");
2785 } else if (ret
== -2) {
2786 /* Ignore truncated command. */
2790 if (strcmp(cp
, "ABOR\r\n") == 0) {
2792 reply(426, "Transfer aborted. Data connection closed.");
2793 reply(226, "Abort successful.");
2796 if (strcmp(cp
, "STAT\r\n") == 0) {
2798 if (file_size
!= -1)
2799 reply(213, "Status: %jd of %jd bytes transferred.",
2800 (intmax_t)byte_count
, (intmax_t)file_size
);
2802 reply(213, "Status: %jd bytes transferred.",
2803 (intmax_t)byte_count
);
2809 * Note: a response of 425 is not mentioned as a possible response to
2810 * the PASV command in RFC959. However, it has been blessed as
2811 * a legitimate response by Jon Postel in a telephone conversation
2812 * with Rick Adams on 25 Jan 89.
2821 if (pdata
>= 0) /* close old port if one set */
2824 pdata
= socket(ctrl_addr
.su_family
, SOCK_STREAM
, 0);
2826 perror_reply(425, "Can't open passive connection");
2830 if (setsockopt(pdata
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) < 0)
2831 syslog(LOG_WARNING
, "pdata setsockopt (SO_REUSEADDR): %m");
2836 if (ctrl_addr
.su_family
== AF_INET
) {
2837 on
= restricted_data_ports
? IP_PORTRANGE_HIGH
2838 : IP_PORTRANGE_DEFAULT
;
2840 if (setsockopt(pdata
, IPPROTO_IP
, IP_PORTRANGE
,
2841 &on
, sizeof(on
)) < 0)
2845 #ifdef IPV6_PORTRANGE
2846 if (ctrl_addr
.su_family
== AF_INET6
) {
2847 on
= restricted_data_ports
? IPV6_PORTRANGE_HIGH
2848 : IPV6_PORTRANGE_DEFAULT
;
2850 if (setsockopt(pdata
, IPPROTO_IPV6
, IPV6_PORTRANGE
,
2851 &on
, sizeof(on
)) < 0)
2856 pasv_addr
= ctrl_addr
;
2857 pasv_addr
.su_port
= 0;
2858 if (bind(pdata
, (struct sockaddr
*)&pasv_addr
, pasv_addr
.su_len
) < 0)
2861 seteuid(pw
->pw_uid
);
2863 len
= sizeof(pasv_addr
);
2864 if (getsockname(pdata
, (struct sockaddr
*) &pasv_addr
, &len
) < 0)
2866 if (listen(pdata
, 1) < 0)
2868 if (pasv_addr
.su_family
== AF_INET
)
2869 a
= (char *) &pasv_addr
.su_sin
.sin_addr
;
2870 else if (pasv_addr
.su_family
== AF_INET6
&&
2871 IN6_IS_ADDR_V4MAPPED(&pasv_addr
.su_sin6
.sin6_addr
))
2872 a
= (char *) &pasv_addr
.su_sin6
.sin6_addr
.s6_addr
[12];
2876 p
= (char *) &pasv_addr
.su_port
;
2878 #define UC(b) (((int) b) & 0xff)
2880 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a
[0]),
2881 UC(a
[1]), UC(a
[2]), UC(a
[3]), UC(p
[0]), UC(p
[1]));
2885 seteuid(pw
->pw_uid
);
2888 perror_reply(425, "Can't open passive connection");
2893 * Long Passive defined in RFC 1639.
2894 * 228 Entering Long Passive Mode
2895 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2899 long_passive(char *cmd
, int pf
)
2905 if (pdata
>= 0) /* close old port if one set */
2908 if (pf
!= PF_UNSPEC
) {
2909 if (ctrl_addr
.su_family
!= pf
) {
2910 switch (ctrl_addr
.su_family
) {
2923 * only EPRT/EPSV ready clients will understand this
2925 if (strcmp(cmd
, "EPSV") == 0 && pf
) {
2926 reply(522, "Network protocol mismatch, "
2929 reply(501, "Network protocol mismatch."); /*XXX*/
2935 pdata
= socket(ctrl_addr
.su_family
, SOCK_STREAM
, 0);
2937 perror_reply(425, "Can't open passive connection");
2941 if (setsockopt(pdata
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) < 0)
2942 syslog(LOG_WARNING
, "pdata setsockopt (SO_REUSEADDR): %m");
2946 pasv_addr
= ctrl_addr
;
2947 pasv_addr
.su_port
= 0;
2948 len
= pasv_addr
.su_len
;
2951 if (ctrl_addr
.su_family
== AF_INET
) {
2952 on
= restricted_data_ports
? IP_PORTRANGE_HIGH
2953 : IP_PORTRANGE_DEFAULT
;
2955 if (setsockopt(pdata
, IPPROTO_IP
, IP_PORTRANGE
,
2956 &on
, sizeof(on
)) < 0)
2960 #ifdef IPV6_PORTRANGE
2961 if (ctrl_addr
.su_family
== AF_INET6
) {
2962 on
= restricted_data_ports
? IPV6_PORTRANGE_HIGH
2963 : IPV6_PORTRANGE_DEFAULT
;
2965 if (setsockopt(pdata
, IPPROTO_IPV6
, IPV6_PORTRANGE
,
2966 &on
, sizeof(on
)) < 0)
2971 if (bind(pdata
, (struct sockaddr
*)&pasv_addr
, len
) < 0)
2974 seteuid(pw
->pw_uid
);
2976 if (getsockname(pdata
, (struct sockaddr
*) &pasv_addr
, &len
) < 0)
2978 if (listen(pdata
, 1) < 0)
2981 #define UC(b) (((int) b) & 0xff)
2983 if (strcmp(cmd
, "LPSV") == 0) {
2984 p
= (char *)&pasv_addr
.su_port
;
2985 switch (pasv_addr
.su_family
) {
2987 a
= (char *) &pasv_addr
.su_sin
.sin_addr
;
2990 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2991 4, 4, UC(a
[0]), UC(a
[1]), UC(a
[2]), UC(a
[3]),
2992 2, UC(p
[0]), UC(p
[1]));
2995 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr
.su_sin6
.sin6_addr
)) {
2996 a
= (char *) &pasv_addr
.su_sin6
.sin6_addr
.s6_addr
[12];
2999 a
= (char *) &pasv_addr
.su_sin6
.sin6_addr
;
3001 "Entering Long Passive Mode "
3002 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
3003 6, 16, UC(a
[0]), UC(a
[1]), UC(a
[2]), UC(a
[3]),
3004 UC(a
[4]), UC(a
[5]), UC(a
[6]), UC(a
[7]),
3005 UC(a
[8]), UC(a
[9]), UC(a
[10]), UC(a
[11]),
3006 UC(a
[12]), UC(a
[13]), UC(a
[14]), UC(a
[15]),
3007 2, UC(p
[0]), UC(p
[1]));
3010 } else if (strcmp(cmd
, "EPSV") == 0) {
3011 switch (pasv_addr
.su_family
) {
3014 reply(229, "Entering Extended Passive Mode (|||%d|)",
3015 ntohs(pasv_addr
.su_port
));
3019 /* more proper error code? */
3023 seteuid(pw
->pw_uid
);
3026 perror_reply(425, "Can't open passive connection");
3031 * Generate unique name for file with basename "local"
3032 * and open the file in order to avoid possible races.
3033 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
3034 * Return descriptor to the file, set "name" to its name.
3036 * Generates failure reply on error.
3039 guniquefd(char *local
, char **name
)
3041 static char new[MAXPATHLEN
];
3047 cp
= strrchr(local
, '/');
3050 if (stat(cp
? local
: ".", &st
) < 0) {
3051 perror_reply(553, cp
? local
: ".");
3056 * Let not overwrite dirname with counter suffix.
3058 * In this extreme case dot won't be put in front of suffix.
3060 if (strlen(local
) > sizeof(new) - 4) {
3061 reply(553, "Pathname too long.");
3066 /* -4 is for the .nn<null> we put on the end below */
3067 snprintf(new, sizeof(new) - 4, "%s", local
);
3068 cp
= new + strlen(new);
3070 * Don't generate dotfile unless requested explicitly.
3071 * This covers the case when basename gets truncated off
3074 if (cp
> new && cp
[-1] != '/')
3076 for (count
= 0; count
< 100; count
++) {
3077 /* At count 0 try unmodified name */
3079 sprintf(cp
, "%d", count
);
3080 if ((fd
= open(count
? new : local
,
3081 O_RDWR
| O_CREAT
| O_EXCL
, 0666)) >= 0) {
3082 *name
= count
? new : local
;
3085 if (errno
!= EEXIST
) {
3086 perror_reply(553, count
? new : local
);
3090 reply(452, "Unique file name cannot be created.");
3095 * Format and send reply containing system error number.
3098 perror_reply(int code
, char *string
)
3101 reply(code
, "%s: %s.", string
, strerror(errno
));
3104 static char *onefile
[] = {
3110 send_file_list(char *whichf
)
3116 char **dirlist
, *dirname
;
3121 if (strpbrk(whichf
, "~{[*?") != NULL
) {
3122 int flags
= GLOB_BRACE
|GLOB_NOCHECK
|GLOB_TILDE
;
3124 memset(&gl
, 0, sizeof(gl
));
3125 gl
.gl_matchc
= MAXGLOBARGS
;
3126 /*flags |= GLOB_LIMIT;*/
3128 if (glob(whichf
, flags
, 0, &gl
)) {
3129 reply(550, "No matching files found.");
3131 } else if (gl
.gl_pathc
== 0) {
3133 perror_reply(550, whichf
);
3136 dirlist
= gl
.gl_pathv
;
3138 onefile
[0] = whichf
;
3143 while ((dirname
= *dirlist
++)) {
3144 if (stat(dirname
, &st
) < 0) {
3146 * If user typed "ls -l", etc, and the client
3147 * used NLST, do what the user meant.
3149 if (dirname
[0] == '-' && *dirlist
== NULL
&&
3151 retrieve(_PATH_LS
" %s", dirname
);
3153 perror_reply(550, whichf
);
3157 if (S_ISREG(st
.st_mode
)) {
3159 dout
= dataconn("file list", -1, "w");
3165 fprintf(dout
, "%s%s\n", dirname
,
3166 type
== TYPE_A
? "\r" : "");
3170 byte_count
+= strlen(dirname
) +
3171 (type
== TYPE_A
? 2 : 1);
3172 CHECKOOB(goto abrt
);
3174 } else if (!S_ISDIR(st
.st_mode
))
3177 if ((dirp
= opendir(dirname
)) == NULL
)
3180 while ((dir
= readdir(dirp
)) != NULL
) {
3181 char nbuf
[MAXPATHLEN
];
3183 CHECKOOB(goto abrt
);
3185 if (strcmp(dir
->d_name
, ".") == 0)
3187 if (strcmp(dir
->d_name
, "..") == 0)
3190 snprintf(nbuf
, sizeof(nbuf
),
3191 "%s/%s", dirname
, dir
->d_name
);
3194 * We have to do a stat to insure it's
3195 * not a directory or special file.
3197 if (simple
|| (stat(nbuf
, &st
) == 0 &&
3198 S_ISREG(st
.st_mode
))) {
3200 dout
= dataconn("file list", -1, "w");
3206 if (nbuf
[0] == '.' && nbuf
[1] == '/')
3207 fprintf(dout
, "%s%s\n", &nbuf
[2],
3208 type
== TYPE_A
? "\r" : "");
3210 fprintf(dout
, "%s%s\n", nbuf
,
3211 type
== TYPE_A
? "\r" : "");
3215 byte_count
+= strlen(nbuf
) +
3216 (type
== TYPE_A
? 2 : 1);
3217 CHECKOOB(goto abrt
);
3225 reply(550, "No files found.");
3226 else if (ferror(dout
))
3227 data_err
: perror_reply(550, "Data connection");
3229 reply(226, "Transfer complete.");
3247 reapchild(int signo
)
3249 while (waitpid(-1, NULL
, WNOHANG
) > 0);
3253 appendf(char **strp
, char *fmt
, ...)
3259 vasprintf(&p
, fmt
, ap
);
3262 fatalerror("Ran out of memory.");
3267 asprintf(strp
, "%s%s", ostr
, p
);
3269 fatalerror("Ran out of memory.");
3275 logcmd(char *cmd
, char *file1
, char *file2
, off_t cnt
)
3278 char wd
[MAXPATHLEN
+ 1];
3283 if (getcwd(wd
, sizeof(wd
) - 1) == NULL
)
3284 strcpy(wd
, strerror(errno
));
3286 appendf(&msg
, "%s", cmd
);
3288 appendf(&msg
, " %s", file1
);
3290 appendf(&msg
, " %s", file2
);
3292 appendf(&msg
, " = %jd bytes", (intmax_t)cnt
);
3293 appendf(&msg
, " (wd: %s", wd
);
3294 if (guest
|| dochroot
)
3295 appendf(&msg
, "; chrooted");
3297 syslog(LOG_INFO
, "%s", msg
);
3302 logxfer(char *name
, off_t size
, time_t start
)
3304 char buf
[MAXPATHLEN
+ 1024];
3305 char path
[MAXPATHLEN
+ 1];
3310 if (realpath(name
, path
) == NULL
) {
3311 syslog(LOG_NOTICE
, "realpath failed on %s: %m", path
);
3314 snprintf(buf
, sizeof(buf
), "%.20s!%s!%s!%s!%jd!%ld\n",
3315 ctime(&now
)+4, ident
, remotehost
,
3316 path
, (intmax_t)size
,
3317 (long)(now
- start
+ (now
== start
)));
3318 write(statfd
, buf
, strlen(buf
));
3323 doublequote(char *s
)
3328 for (p
= s
, n
= 0; *p
; p
++)
3332 if ((s2
= malloc(p
- s
+ n
+ 1)) == NULL
)
3335 for (p
= s2
; *s
; s
++, p
++) {
3336 if ((*p
= *s
) == '"')
3344 /* setup server socket for specified address family */
3345 /* if af is PF_UNSPEC more than one socket may be returned */
3346 /* the returned list is dynamically allocated, so caller needs to free it */
3348 socksetup(int af
, char *bindname
, const char *bindport
)
3350 struct addrinfo hints
, *res
, *r
;
3351 int error
, maxs
, *s
, *socks
;
3354 memset(&hints
, 0, sizeof(hints
));
3355 hints
.ai_flags
= AI_PASSIVE
;
3356 hints
.ai_family
= af
;
3357 hints
.ai_socktype
= SOCK_STREAM
;
3358 error
= getaddrinfo(bindname
, bindport
, &hints
, &res
);
3360 syslog(LOG_ERR
, "%s", gai_strerror(error
));
3361 if (error
== EAI_SYSTEM
)
3362 syslog(LOG_ERR
, "%s", strerror(errno
));
3366 /* Count max number of sockets we may open */
3367 for (maxs
= 0, r
= res
; r
; r
= r
->ai_next
, maxs
++)
3369 socks
= malloc((maxs
+ 1) * sizeof(int));
3372 syslog(LOG_ERR
, "couldn't allocate memory for sockets");
3376 *socks
= 0; /* num of sockets counter at start of array */
3378 for (r
= res
; r
; r
= r
->ai_next
) {
3379 *s
= socket(r
->ai_family
, r
->ai_socktype
, r
->ai_protocol
);
3381 syslog(LOG_DEBUG
, "control socket: %m");
3384 if (setsockopt(*s
, SOL_SOCKET
, SO_REUSEADDR
,
3385 &on
, sizeof(on
)) < 0)
3387 "control setsockopt (SO_REUSEADDR): %m");
3388 if (r
->ai_family
== AF_INET6
) {
3389 if (setsockopt(*s
, IPPROTO_IPV6
, IPV6_V6ONLY
,
3390 &on
, sizeof(on
)) < 0)
3392 "control setsockopt (IPV6_V6ONLY): %m");
3394 if (bind(*s
, r
->ai_addr
, r
->ai_addrlen
) < 0) {
3395 syslog(LOG_DEBUG
, "control bind: %m");
3407 syslog(LOG_ERR
, "control socket: Couldn't bind to any socket");