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. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include "ftpd_locl.h"
41 RCSID("$Id: ftpd.c,v 1.161 2002/02/28 15:50:14 joda Exp $");
43 static char version[] = "Version 6.00";
45 extern off_t restart_point;
48 struct sockaddr_storage ctrl_addr_ss;
49 struct sockaddr *ctrl_addr = (struct sockaddr *)&ctrl_addr_ss;
51 struct sockaddr_storage data_source_ss;
52 struct sockaddr *data_source = (struct sockaddr *)&data_source_ss;
54 struct sockaddr_storage data_dest_ss;
55 struct sockaddr *data_dest = (struct sockaddr *)&data_dest_ss;
57 struct sockaddr_storage his_addr_ss;
58 struct sockaddr *his_addr = (struct sockaddr *)&his_addr_ss;
60 struct sockaddr_storage pasv_addr_ss;
61 struct sockaddr *pasv_addr = (struct sockaddr *)&pasv_addr_ss;
64 jmp_buf errcatch, urgcatch;
69 int ftpd_timeout = 900; /* timeout after 15 minutes of inactivity */
70 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
71 int restricted_data_ports = 1;
77 int stru; /* avoid C keyword */
79 int usedefault = 1; /* for data transfers */
80 int pdata = -1; /* for passive mode */
84 #if !defined(CMASK) || CMASK == 0
88 int defumask = CMASK; /* default umask value */
89 int guest_umask = 0777; /* Paranoia for anonymous users */
91 char hostname[MaxHostNameLen];
92 char remotehost[MaxHostNameLen];
93 static char ttyline[20];
95 #define AUTH_PLAIN (1 << 0) /* allow sending passwords */
96 #define AUTH_OTP (1 << 1) /* passwords are one-time */
97 #define AUTH_FTP (1 << 2) /* allow anonymous login */
99 static int auth_level = 0; /* Only allow kerberos login by default */
102 * Timeout intervals for retrying connections
103 * to hosts that don't accept PORT cmds. This
104 * is a kludge, but given the problems with TCP...
106 #define SWAITMAX 90 /* wait at most 90 seconds */
107 #define SWAITINT 5 /* interval between retries */
109 int swaitmax = SWAITMAX;
110 int swaitint = SWAITINT;
112 #ifdef HAVE_SETPROCTITLE
113 char proctitle[BUFSIZ]; /* initial part of title */
114 #endif /* HAVE_SETPROCTITLE */
116 #define LOGCMD(cmd, file) \
118 syslog(LOG_INFO,"%s %s%s", cmd, \
119 *(file) == '/' ? "" : curdir(), file);
120 #define LOGCMD2(cmd, file1, file2) \
122 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
123 *(file1) == '/' ? "" : curdir(), file1, \
124 *(file2) == '/' ? "" : curdir(), file2);
125 #define LOGBYTES(cmd, file, cnt) \
127 if (cnt == (off_t)-1) \
128 syslog(LOG_INFO,"%s %s%s", cmd, \
129 *(file) == '/' ? "" : curdir(), file); \
131 syslog(LOG_INFO, "%s %s%s = %ld bytes", \
132 cmd, (*(file) == '/') ? "" : curdir(), file, (long)cnt); \
135 static void ack (char *);
136 static void myoob (int);
137 static int checkuser (char *, char *);
138 static int checkaccess (char *);
139 static FILE *dataconn (const char *, off_t, const char *);
140 static void dolog (struct sockaddr *sa, int len);
141 static void end_login (void);
142 static FILE *getdatasock (const char *);
143 static char *gunique (char *);
144 static RETSIGTYPE lostconn (int);
145 static int receive_data (FILE *, FILE *);
146 static void send_data (FILE *, FILE *);
147 static struct passwd * sgetpwnam (char *);
152 static char path[MaxPathLen+1]; /* path + '/' + '\0' */
154 if (getcwd(path, sizeof(path)-1) == NULL)
156 if (path[1] != '\0') /* special case for root dir. */
157 strlcat(path, "/", sizeof(path));
158 /* For guest account, skip / since it's chrooted */
159 return (guest ? path+1 : path);
163 #define LINE_MAX 1024
167 parse_auth_level(char *str)
173 for(p = strtok_r(str, ",", &foo);
175 p = strtok_r(NULL, ",", &foo)) {
176 if(strcmp(p, "user") == 0)
179 else if(strcmp(p, "otp") == 0)
180 ret |= AUTH_PLAIN|AUTH_OTP;
182 else if(strcmp(p, "ftp") == 0 ||
183 strcmp(p, "safe") == 0)
185 else if(strcmp(p, "plain") == 0)
187 else if(strcmp(p, "none") == 0)
188 ret |= AUTH_PLAIN|AUTH_FTP;
190 warnx("bad value for -a: `%s'", p);
196 * Print usage and die.
199 static int interactive_flag;
200 static char *guest_umask_string;
201 static char *port_string;
202 static char *umask_string;
203 static char *auth_string;
205 int use_builtin_ls = -1;
207 static int help_flag;
208 static int version_flag;
210 static const char *good_chars = "+-=_,.";
212 struct getargs args[] = {
213 { NULL, 'a', arg_string, &auth_string, "required authentication" },
214 { NULL, 'i', arg_flag, &interactive_flag, "don't assume stdin is a socket" },
215 { NULL, 'p', arg_string, &port_string, "what port to listen to" },
216 { NULL, 'g', arg_string, &guest_umask_string, "umask for guest logins" },
217 { NULL, 'l', arg_counter, &logging, "log more stuff", "" },
218 { NULL, 't', arg_integer, &ftpd_timeout, "initial timeout" },
219 { NULL, 'T', arg_integer, &maxtimeout, "max timeout" },
220 { NULL, 'u', arg_string, &umask_string, "umask for user logins" },
221 { NULL, 'U', arg_negative_flag, &restricted_data_ports, "don't use high data ports" },
222 { NULL, 'd', arg_flag, &debug, "enable debugging" },
223 { NULL, 'v', arg_flag, &debug, "enable debugging" },
224 { "builtin-ls", 'B', arg_flag, &use_builtin_ls, "use built-in ls to list files" },
225 { "good-chars", 0, arg_string, &good_chars, "allowed anonymous upload filename chars" },
226 { "version", 0, arg_flag, &version_flag },
227 { "help", 'h', arg_flag, &help_flag }
230 static int num_args = sizeof(args) / sizeof(args[0]);
235 arg_printusage(args, num_args, NULL, "");
239 /* output contents of a file */
241 show_file(const char *file, int code)
246 f = fopen(file, "r");
249 while(fgets(buf, sizeof(buf), f)){
250 buf[strcspn(buf, "\r\n")] = '\0';
251 lreply(code, "%s", buf);
258 main(int argc, char **argv)
260 socklen_t his_addr_len, ctrl_addr_len;
267 setprogname (argv[0]);
269 /* detach from any tickets and tokens */
273 snprintf(tkfile, sizeof(tkfile),
274 "/tmp/ftp_%u", (unsigned)getpid());
275 krb_set_tkt_string(tkfile);
277 #if defined(KRB4) && defined(KRB5)
283 if(getarg(args, num_args, argc, argv, &optind))
295 auth_level = parse_auth_level(auth_string);
300 if(guest_umask_string) {
301 val = strtol(guest_umask_string, &p, 8);
302 if (*p != '\0' || val < 0)
303 warnx("bad value for -g");
308 val = strtol(umask_string, &p, 8);
309 if (*p != '\0' || val < 0)
310 warnx("bad value for -u");
315 sp = getservbyname("ftp", "tcp");
321 sp = getservbyname(port_string, "tcp");
325 if(isdigit(port_string[0]))
326 port = htons(atoi(port_string));
328 warnx("bad value for -p");
331 if (maxtimeout < ftpd_timeout)
332 maxtimeout = ftpd_timeout;
335 if (ftpd_timeout > maxtimeout)
336 ftpd_timeout = maxtimeout;
343 * LOG_NDELAY sets up the logging connection immediately,
344 * necessary for anonymous ftp's that chroot and can't do it later.
346 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
347 his_addr_len = sizeof(his_addr_ss);
348 if (getpeername(STDIN_FILENO, his_addr, &his_addr_len) < 0) {
349 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
352 ctrl_addr_len = sizeof(ctrl_addr_ss);
353 if (getsockname(STDIN_FILENO, ctrl_addr, &ctrl_addr_len) < 0) {
354 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
357 #if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
359 int tos = IPTOS_LOWDELAY;
361 if (setsockopt(STDIN_FILENO, IPPROTO_IP, IP_TOS,
362 (void *)&tos, sizeof(int)) < 0)
363 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
366 data_source->sa_family = ctrl_addr->sa_family;
367 socket_set_port (data_source,
368 htons(ntohs(socket_get_port(ctrl_addr)) - 1));
370 /* set this here so it can be put in wtmp */
371 snprintf(ttyline, sizeof(ttyline), "ftp%u", (unsigned)getpid());
374 /* freopen(_PATH_DEVNULL, "w", stderr); */
375 signal(SIGPIPE, lostconn);
376 signal(SIGCHLD, SIG_IGN);
378 if (signal(SIGURG, myoob) == SIG_ERR)
379 syslog(LOG_ERR, "signal: %m");
382 /* Try to handle urgent data inline */
383 #if defined(SO_OOBINLINE) && defined(HAVE_SETSOCKOPT)
384 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (void *)&on,
386 syslog(LOG_ERR, "setsockopt: %m");
390 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
391 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
393 dolog(his_addr, his_addr_len);
395 * Set up default state
404 /* If logins are disabled, print out the message. */
405 if(show_file(_PATH_NOLOGIN, 530) == 0) {
406 reply(530, "System not available.");
409 show_file(_PATH_FTPWELCOME, 220);
410 /* reply(220,) must follow */
411 gethostname(hostname, sizeof(hostname));
413 reply(220, "%s FTP server (%s"
420 ") ready.", hostname, version
440 syslog(LOG_DEBUG, "lost connection");
445 * Helper function for sgetpwnam().
450 char *new = strdup(s);
453 perror_reply(421, "Local resource failure: malloc");
461 * Save the result of a getpwnam. Used for USER command, since
462 * the data returned must not be clobbered by any other command
465 static struct passwd *
466 sgetpwnam(char *name)
468 static struct passwd save;
471 if ((p = k_getpwnam(name)) == NULL)
475 free(save.pw_passwd);
481 save.pw_name = sgetsave(p->pw_name);
482 save.pw_passwd = sgetsave(p->pw_passwd);
483 save.pw_gecos = sgetsave(p->pw_gecos);
484 save.pw_dir = sgetsave(p->pw_dir);
485 save.pw_shell = sgetsave(p->pw_shell);
489 static int login_attempts; /* number of failed login attempts */
490 static int askpasswd; /* had user command, ask for passwd */
491 static char curname[10]; /* current USER name */
498 * Sets global passwd pointer pw if named account exists and is acceptable;
499 * sets askpasswd if a PASS command is expected. If logged in previously,
500 * need to reset state. If name is "ftp" or "anonymous", the name is not in
501 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
502 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
503 * requesting login privileges. Disallow anyone who does not have a standard
504 * shell as returned by getusershell(). Disallow anyone mentioned in the file
505 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
512 if(auth_level == 0 && !sec_complete){
513 reply(530, "No login allowed without authorization.");
519 reply(530, "Can't change user from guest login.");
521 } else if (dochroot) {
522 reply(530, "Can't change user from chroot user.");
529 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
530 if ((auth_level & AUTH_FTP) == 0 ||
531 checkaccess("ftp") ||
532 checkaccess("anonymous"))
533 reply(530, "User %s access denied.", name);
534 else if ((pw = sgetpwnam("ftp")) != NULL) {
536 defumask = guest_umask; /* paranoia for incoming */
538 reply(331, "Guest login ok, type your name as password.");
540 reply(530, "User %s unknown.", name);
541 if (!askpasswd && logging) {
544 if (inet_ntop (his_addr->sa_family,
545 socket_get_address(his_addr),
546 data_addr, sizeof(data_addr)) == NULL)
547 strlcpy (data_addr, "unknown address",
551 "ANONYMOUS FTP LOGIN REFUSED FROM %s(%s)",
552 remotehost, data_addr);
556 if((auth_level & AUTH_PLAIN) == 0 && !sec_complete){
557 reply(530, "Only authorized and anonymous login allowed.");
560 if ((pw = sgetpwnam(name))) {
561 if ((shell = pw->pw_shell) == NULL || *shell == 0)
562 shell = _PATH_BSHELL;
563 while ((cp = getusershell()) != NULL)
564 if (strcmp(cp, shell) == 0)
568 if (cp == NULL || checkaccess(name)) {
569 reply(530, "User %s access denied.", name);
573 if (inet_ntop (his_addr->sa_family,
574 socket_get_address(his_addr),
576 sizeof(data_addr)) == NULL)
582 "FTP LOGIN REFUSED FROM %s(%s), %s",
587 pw = (struct passwd *) NULL;
592 strlcpy(curname, name, sizeof(curname));
594 if(sec_userok(name) == 0)
597 reply(530, "User %s access denied.", name);
602 if (otp_challenge(&otp_ctx, name, ss, sizeof(ss)) == 0) {
603 reply(331, "Password %s for %s required.",
608 if ((auth_level & AUTH_OTP) == 0) {
609 reply(331, "Password required for %s.", name);
615 if ((s = otp_error (&otp_ctx)) != NULL)
616 lreply(530, "OTP: %s", s);
619 "Only authorized, anonymous"
628 * Delay before reading passwd after first failed
629 * attempt to slow down passwd-guessing programs.
632 sleep(login_attempts);
636 * Check if a user is in the file "fname"
639 checkuser(char *fname, char *name)
643 char *p, line[BUFSIZ];
645 if ((fd = fopen(fname, "r")) != NULL) {
646 while (fgets(line, sizeof(line), fd) != NULL)
647 if ((p = strchr(line, '\n')) != NULL) {
651 if (strcmp(line, name) == 0) {
663 * Determine whether a user has access, based on information in
664 * _PATH_FTPUSERS. The users are listed one per line, with `allow'
665 * or `deny' after the username. If anything other than `allow', or
666 * just nothing, is given after the username, `deny' is assumed.
668 * If the user is not found in the file, but the pseudo-user `*' is,
669 * the permission is taken from that line.
671 * This preserves the old semantics where if a user was listed in the
672 * file he was denied, otherwise he was allowed.
674 * Return 1 if the user is denied, or 0 if he is allowed. */
677 match(const char *pattern, const char *string)
679 return fnmatch(pattern, string, FNM_NOESCAPE);
683 checkaccess(char *name)
686 #define NOT_ALLOWED 1
688 int allowed = ALLOWED;
689 char *user, *perm, line[BUFSIZ];
692 fd = fopen(_PATH_FTPUSERS, "r");
697 while (fgets(line, sizeof(line), fd) != NULL) {
699 user = strtok_r(line, " \t\n", &foo);
700 if (user == NULL || user[0] == '#')
702 perm = strtok_r(NULL, " \t\n", &foo);
703 if (match(user, name) == 0){
704 if(perm && strcmp(perm, "allow") == 0)
707 allowed = NOT_ALLOWED;
718 int do_login(int code, char *passwd)
720 login_attempts = 0; /* this time successful */
721 if (setegid((gid_t)pw->pw_gid) < 0) {
722 reply(550, "Can't set gid.");
725 initgroups(pw->pw_name, pw->pw_gid);
727 /* open wtmp before chroot */
728 ftpd_logwtmp(ttyline, pw->pw_name, remotehost);
731 dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name);
734 * We MUST do a chdir() after the chroot. Otherwise
735 * the old current directory will be accessible as "."
736 * outside the new root!
738 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
739 reply(550, "Can't set guest privileges.");
742 } else if (dochroot) {
743 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
744 reply(550, "Can't change root.");
747 } else if (chdir(pw->pw_dir) < 0) {
748 if (chdir("/") < 0) {
749 reply(530, "User %s: can't change directory to %s.",
750 pw->pw_name, pw->pw_dir);
753 lreply(code, "No directory! Logging in with home=/");
755 if (seteuid((uid_t)pw->pw_uid) < 0) {
756 reply(550, "Can't set uid.");
760 if(use_builtin_ls == -1) {
762 /* if /bin/ls exist and is a regular file, use it, otherwise
764 if(stat("/bin/ls", &st) == 0 &&
772 * Display a login message, if it exists.
773 * N.B. reply(code,) must follow the message.
775 show_file(_PATH_FTPLOGINMESG, code);
776 if(show_file(_PATH_ISSUE_NET, code) != 0)
777 show_file(_PATH_ISSUE, code);
779 reply(code, "Guest login ok, access restrictions apply.");
780 #ifdef HAVE_SETPROCTITLE
781 snprintf (proctitle, sizeof(proctitle),
785 setproctitle("%s", proctitle);
786 #endif /* HAVE_SETPROCTITLE */
790 if (inet_ntop (his_addr->sa_family,
791 socket_get_address(his_addr),
792 data_addr, sizeof(data_addr)) == NULL)
793 strlcpy (data_addr, "unknown address",
796 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s(%s), %s",
802 reply(code, "User %s logged in.", pw->pw_name);
803 #ifdef HAVE_SETPROCTITLE
804 snprintf(proctitle, sizeof(proctitle), "%s: %s", remotehost, pw->pw_name);
805 setproctitle("%s", proctitle);
806 #endif /* HAVE_SETPROCTITLE */
810 if (inet_ntop (his_addr->sa_family,
811 socket_get_address(his_addr),
812 data_addr, sizeof(data_addr)) == NULL)
813 strlcpy (data_addr, "unknown address",
816 syslog(LOG_INFO, "FTP LOGIN FROM %s(%s) as %s",
827 * Terminate login as previous user, if any, resetting state;
828 * used when USER command is given or login fails.
836 ftpd_logwtmp(ttyline, "", "");
845 krb5_verify(struct passwd *pwd, char *passwd)
847 krb5_context context;
849 krb5_principal princ;
852 ret = krb5_init_context(&context);
856 ret = krb5_parse_name(context, pwd->pw_name, &princ);
858 krb5_free_context(context);
861 ret = krb5_cc_gen_new(context, &krb5_mcc_ops, &id);
863 krb5_free_principal(context, princ);
864 krb5_free_context(context);
867 ret = krb5_verify_user(context,
873 krb5_free_principal(context, princ);
877 krb5_afslog_uid_home(context, id,NULL, NULL,pwd->pw_uid, pwd->pw_dir);
880 krb5_cc_destroy(context, id);
881 krb5_free_context (context);
893 /* some clients insists on sending a password */
894 if (logged_in && askpasswd == 0){
895 reply(230, "Password not necessary");
899 if (logged_in || askpasswd == 0) {
900 reply(503, "Login with USER first.");
905 if (!guest) { /* "ftp" is only account allowed no password */
907 rval = 1; /* failure below */
909 else if (otp_verify_user (&otp_ctx, passwd) == 0) {
913 else if((auth_level & AUTH_OTP) == 0) {
915 rval = krb5_verify(pw, passwd);
919 char realm[REALM_SZ];
920 if((rval = krb_get_lrealm(realm, 1)) == KSUCCESS)
921 rval = krb_verify_user(pw->pw_name,
924 KRB_VERIFY_SECURE, NULL);
925 if (rval == KSUCCESS ) {
926 chown (tkt_string(), pw->pw_uid, pw->pw_gid);
933 rval = unix_verify_user(pw->pw_name, passwd);
938 if ((s = otp_error(&otp_ctx)) != NULL)
939 lreply(530, "OTP: %s", s);
942 memset (passwd, 0, strlen(passwd));
945 * If rval == 1, the user failed the authentication
946 * check above. If rval == 0, either Kerberos or
947 * local authentication succeeded.
952 if (inet_ntop (his_addr->sa_family,
953 socket_get_address(his_addr),
954 data_addr, sizeof(data_addr)) == NULL)
955 strlcpy (data_addr, "unknown address",
958 reply(530, "Login incorrect.");
961 "FTP LOGIN FAILED FROM %s(%s), %s",
966 if (login_attempts++ >= 5) {
968 "repeated login failures from %s(%s)",
976 if(!do_login(230, passwd))
979 /* Forget all about it... */
984 retrieve(const char *cmd, char *name)
986 FILE *fin = NULL, *dout;
988 int (*closefunc) (FILE *);
993 fin = fopen(name, "r");
997 int save_errno = errno;
1001 const char *rev_cmd;
1003 {".tar", "/bin/gtar cPf - %s", NULL},
1004 {".tar.gz", "/bin/gtar zcPf - %s", NULL},
1005 {".tar.Z", "/bin/gtar ZcPf - %s", NULL},
1006 {".gz", "/bin/gzip -c -- %s", "/bin/gzip -c -d -- %s"},
1007 {".Z", "/bin/compress -c -- %s", "/bin/uncompress -c -- %s"},
1011 for(p = cmds; p->ext; p++){
1012 char *tail = name + strlen(name) - strlen(p->ext);
1015 if(strcmp(tail, p->ext) == 0 &&
1017 access(name, R_OK) == 0){
1018 snprintf (line, sizeof(line), p->cmd, name);
1023 if (p->rev_cmd != NULL) {
1026 asprintf(&ext, "%s%s", name, p->ext);
1028 if (access(ext, R_OK) == 0) {
1029 snprintf (line, sizeof(line),
1040 fin = ftpd_popen(line, "r", 0, 0);
1041 closefunc = ftpd_pclose;
1048 snprintf(line, sizeof(line), cmd, name);
1050 fin = ftpd_popen(line, "r", 1, 0);
1051 closefunc = ftpd_pclose;
1056 perror_reply(550, name);
1058 LOGCMD("get", name);
1065 if(fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
1066 reply(550, "%s: not a plain file.", name);
1070 if (restart_point) {
1071 if (type == TYPE_A) {
1078 if ((c=getc(fin)) == EOF) {
1079 perror_reply(550, name);
1085 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1086 perror_reply(550, name);
1090 dout = dataconn(name, st.st_size, "w");
1093 set_buffer_size(fileno(dout), 0);
1094 send_data(fin, dout);
1100 LOGBYTES("get", name, byte_count);
1104 /* filename sanity check */
1107 filename_check(char *filename)
1111 p = strrchr(filename, '/');
1119 while(*p && (isalnum(*p) || strchr(good_chars, *p)))
1124 lreply(553, "\"%s\" is not an acceptable filename.", filename);
1125 lreply(553, "The filename must start with an alphanumeric "
1126 "character and must only");
1127 reply(553, "consist of alphanumeric characters or any of the following: %s",
1133 do_store(char *name, char *mode, int unique)
1137 int (*closefunc) (FILE *);
1139 if(guest && filename_check(name))
1141 if (unique && stat(name, &st) == 0 &&
1142 (name = gunique(name)) == NULL) {
1143 LOGCMD(*mode == 'w' ? "put" : "append", name);
1149 fout = fopen(name, mode);
1152 perror_reply(553, name);
1153 LOGCMD(*mode == 'w' ? "put" : "append", name);
1157 if (restart_point) {
1158 if (type == TYPE_A) {
1165 if ((c=getc(fout)) == EOF) {
1166 perror_reply(550, name);
1173 * We must do this seek to "current" position
1174 * because we are changing from reading to
1177 if (fseek(fout, 0L, SEEK_CUR) < 0) {
1178 perror_reply(550, name);
1181 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1182 perror_reply(550, name);
1186 din = dataconn(name, (off_t)-1, "r");
1189 set_buffer_size(fileno(din), 1);
1190 if (receive_data(din, fout) == 0) {
1191 if((*closefunc)(fout) < 0)
1192 perror_reply(552, name);
1195 reply(226, "Transfer complete (unique file name:%s).",
1198 reply(226, "Transfer complete.");
1206 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1210 getdatasock(const char *mode)
1215 return (fdopen(data, mode));
1217 s = socket(ctrl_addr->sa_family, SOCK_STREAM, 0);
1220 socket_set_reuseaddr (s, 1);
1221 /* anchor socket to avoid multi-homing problems */
1222 socket_set_address_and_port (data_source,
1223 socket_get_address (ctrl_addr),
1224 socket_get_port (data_source));
1226 for (tries = 1; ; tries++) {
1227 if (bind(s, data_source,
1228 socket_sockaddr_size (data_source)) >= 0)
1230 if (errno != EADDRINUSE || tries > 10)
1234 seteuid(pw->pw_uid);
1235 #ifdef IPTOS_THROUGHPUT
1236 socket_set_tos (s, IPTOS_THROUGHPUT);
1238 return (fdopen(s, mode));
1240 /* Return the real value of errno (close may change it) */
1242 seteuid((uid_t)pw->pw_uid);
1249 accept_with_timeout(int socket,
1250 struct sockaddr *address,
1251 size_t *address_len,
1252 struct timeval *timeout)
1257 FD_SET(socket, &rfd);
1258 ret = select(socket + 1, &rfd, NULL, NULL, timeout);
1265 return accept(socket, address, address_len);
1269 dataconn(const char *name, off_t size, const char *mode)
1278 snprintf(sizebuf, sizeof(sizebuf), " (%ld bytes)", (long)size);
1282 struct sockaddr_storage from_ss;
1283 struct sockaddr *from = (struct sockaddr *)&from_ss;
1284 struct timeval timeout;
1286 socklen_t fromlen = sizeof(from_ss);
1288 timeout.tv_sec = 15;
1289 timeout.tv_usec = 0;
1290 s = accept_with_timeout(pdata, from, &fromlen, &timeout);
1292 reply(425, "Can't open data connection.");
1299 #if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
1301 int tos = IPTOS_THROUGHPUT;
1303 setsockopt(s, IPPROTO_IP, IP_TOS, (void *)&tos,
1307 reply(150, "Opening %s mode data connection for '%s'%s.",
1308 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1309 return (fdopen(pdata, mode));
1312 reply(125, "Using existing data connection for '%s'%s.",
1315 return (fdopen(data, mode));
1318 data_dest = his_addr;
1320 file = getdatasock(mode);
1322 char data_addr[256];
1324 if (inet_ntop (data_source->sa_family,
1325 socket_get_address(data_source),
1326 data_addr, sizeof(data_addr)) == NULL)
1327 strlcpy (data_addr, "unknown address",
1330 reply(425, "Can't create data socket (%s,%d): %s.",
1332 socket_get_port (data_source),
1336 data = fileno(file);
1337 while (connect(data, data_dest,
1338 socket_sockaddr_size(data_dest)) < 0) {
1339 if (errno == EADDRINUSE && retry < swaitmax) {
1344 perror_reply(425, "Can't build data connection");
1349 reply(150, "Opening %s mode data connection for '%s'%s.",
1350 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1355 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1356 * encapsulation of the data subject * to Mode, Structure, and Type.
1358 * NB: Form isn't handled.
1361 send_data(FILE *instr, FILE *outstr)
1363 int c, cnt, filefd, netfd;
1365 static size_t bufsize;
1368 if (setjmp(urgcatch)) {
1375 while ((c = getc(instr)) != EOF) {
1378 sec_putc('\r', outstr);
1379 sec_putc(c, outstr);
1387 reply(226, "Transfer complete.");
1392 #if defined(HAVE_MMAP) && !defined(NO_MMAP)
1394 #define MAP_FAILED (-1)
1399 int in = fileno(instr);
1400 if(fstat(in, &st) == 0 && S_ISREG(st.st_mode)
1401 && st.st_size > 0) {
1403 * mmap zero bytes has potential of loosing, don't do it.
1405 chunk = mmap(0, st.st_size, PROT_READ,
1407 if((void *)chunk != (void *)MAP_FAILED) {
1408 cnt = st.st_size - restart_point;
1409 sec_write(fileno(outstr), chunk + restart_point, cnt);
1410 if (munmap(chunk, st.st_size) < 0)
1422 netfd = fileno(outstr);
1423 filefd = fileno(instr);
1424 buf = alloc_buffer (buf, &bufsize,
1425 fstat(filefd, &st) >= 0 ? &st : NULL);
1428 perror_reply(451, "Local resource failure: malloc");
1431 while ((cnt = read(filefd, buf, bufsize)) > 0 &&
1432 sec_write(netfd, buf, cnt) == cnt)
1434 sec_fflush(outstr); /* to end an encrypted stream */
1442 reply(226, "Transfer complete.");
1446 reply(550, "Unimplemented TYPE %d in send_data", type);
1452 perror_reply(426, "Data connection");
1457 perror_reply(551, "Error on input file");
1461 * Transfer data from peer to "outstr" using the appropriate encapulation of
1462 * the data subject to Mode, Structure, and Type.
1464 * N.B.: Form isn't handled.
1467 receive_data(FILE *instr, FILE *outstr)
1469 int cnt, bare_lfs = 0;
1471 static size_t bufsize;
1475 if (setjmp(urgcatch)) {
1480 buf = alloc_buffer (buf, &bufsize,
1481 fstat(fileno(outstr), &st) >= 0 ? &st : NULL);
1484 perror_reply(451, "Local resource failure: malloc");
1492 while ((cnt = sec_read(fileno(instr), buf, bufsize)) > 0) {
1493 if (write(fileno(outstr), buf, cnt) != cnt)
1503 reply(553, "TYPE E not implemented.");
1511 while ((cnt = sec_read(fileno(instr),
1513 bufsize - cr_flag)) > 0){
1517 for(p = buf, q = buf; p < buf + cnt;) {
1521 if(p == buf + cnt - 1){
1525 }else if(p[1] == '\n'){
1533 fwrite(buf, q - buf, 1, outstr);
1546 lreply(226, "WARNING! %d bare linefeeds received in ASCII mode\r\n"
1547 " File may not have transferred correctly.\r\n",
1553 reply(550, "Unimplemented TYPE %d in receive_data", type);
1560 perror_reply(426, "Data Connection");
1565 perror_reply(452, "Error writing file");
1570 statfilecmd(char *filename)
1574 char line[LINE_MAX];
1576 snprintf(line, sizeof(line), "/bin/ls -la -- %s", filename);
1577 fin = ftpd_popen(line, "r", 1, 0);
1578 lreply(211, "status of %s:", filename);
1579 while ((c = getc(fin)) != EOF) {
1581 if (ferror(stdout)){
1582 perror_reply(421, "control connection");
1588 perror_reply(551, filename);
1597 reply(211, "End of Status");
1604 struct sockaddr_in *sin;
1607 lreply(211, "%s FTP server (%s) status:", hostname, version);
1608 printf(" %s\r\n", version);
1609 printf(" Connected to %s", remotehost);
1610 if (!isdigit(remotehost[0]))
1611 printf(" (%s)", inet_ntoa(his_addr.sin_addr));
1615 printf(" Logged in anonymously\r\n");
1617 printf(" Logged in as %s\r\n", pw->pw_name);
1618 } else if (askpasswd)
1619 printf(" Waiting for password\r\n");
1621 printf(" Waiting for user name\r\n");
1622 printf(" TYPE: %s", typenames[type]);
1623 if (type == TYPE_A || type == TYPE_E)
1624 printf(", FORM: %s", formnames[form]);
1627 printf(" %d", NBBY);
1629 printf(" %d", bytesize); /* need definition! */
1631 printf("; STRUcture: %s; transfer MODE: %s\r\n",
1632 strunames[stru], modenames[mode]);
1634 printf(" Data connection open\r\n");
1635 else if (pdata != -1) {
1636 printf(" in Passive mode");
1639 } else if (usedefault == 0) {
1643 a = (u_char *) &sin->sin_addr;
1644 p = (u_char *) &sin->sin_port;
1645 #define UC(b) (((int) b) & 0xff)
1646 printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1647 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1650 printf(" No data connection\r\n");
1652 reply(211, "End of status");
1659 reply(451, "Error in server: %s\n", s);
1660 reply(221, "Closing connection due to server error.");
1666 int_reply(int, char *, const char *, va_list)
1668 __attribute__ ((format (printf, 3, 0)))
1673 int_reply(int n, char *c, const char *fmt, va_list ap)
1679 snprintf(p, sizeof(buf), "%d%s", n, c);
1682 vsnprintf(p, sizeof(buf) - strlen(p), fmt, ap);
1684 snprintf(p, sizeof(buf) - strlen(p), "\r\n");
1686 sec_fprintf(stdout, "%s", buf);
1689 syslog(LOG_DEBUG, "<--- %s- ", buf);
1693 reply(int n, const char *fmt, ...)
1697 int_reply(n, " ", fmt, ap);
1698 delete_ftp_command();
1703 lreply(int n, const char *fmt, ...)
1707 int_reply(n, "-", fmt, ap);
1712 nreply(const char *fmt, ...)
1716 int_reply(0, NULL, fmt, ap);
1724 reply(250, "%s command successful.", s);
1731 reply(502, "%s command not implemented.", s);
1740 if ((cp = strchr(cbuf,'\n')))
1742 reply(500, "'%s': command not understood.", cbuf);
1746 do_delete(char *name)
1750 LOGCMD("delete", name);
1751 if (stat(name, &st) < 0) {
1752 perror_reply(550, name);
1755 if ((st.st_mode&S_IFMT) == S_IFDIR) {
1756 if (rmdir(name) < 0) {
1757 perror_reply(550, name);
1762 if (unlink(name) < 0) {
1763 perror_reply(550, name);
1774 if (chdir(path) < 0)
1775 perror_reply(550, path);
1784 LOGCMD("mkdir", name);
1785 if(guest && filename_check(name))
1787 if (mkdir(name, 0777) < 0)
1788 perror_reply(550, name);
1791 chmod(name, 0700); /* guest has umask 777 */
1792 reply(257, "MKD command successful.");
1797 removedir(char *name)
1800 LOGCMD("rmdir", name);
1801 if (rmdir(name) < 0)
1802 perror_reply(550, name);
1810 char path[MaxPathLen];
1813 /* SunOS has a broken getcwd that does popen(pwd) (!!!), this
1814 * failes miserably when running chroot
1816 ret = getcwd(path, sizeof(path));
1818 reply(550, "%s.", strerror(errno));
1820 reply(257, "\"%s\" is current directory.", path);
1824 renamefrom(char *name)
1828 if (stat(name, &st) < 0) {
1829 perror_reply(550, name);
1832 reply(350, "File exists, ready for destination name");
1837 renamecmd(char *from, char *to)
1840 LOGCMD2("rename", from, to);
1841 if(guest && filename_check(to))
1843 if (rename(from, to) < 0)
1844 perror_reply(550, "rename");
1850 dolog(struct sockaddr *sa, int len)
1852 getnameinfo_verified (sa, len, remotehost, sizeof(remotehost),
1854 #ifdef HAVE_SETPROCTITLE
1855 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1856 setproctitle("%s", proctitle);
1857 #endif /* HAVE_SETPROCTITLE */
1860 char data_addr[256];
1862 if (inet_ntop (his_addr->sa_family,
1863 socket_get_address(his_addr),
1864 data_addr, sizeof(data_addr)) == NULL)
1865 strlcpy (data_addr, "unknown address",
1869 syslog(LOG_INFO, "connection from %s(%s)",
1876 * Record logout in wtmp file
1877 * and exit with supplied status.
1880 dologout(int status)
1885 ftpd_logwtmp(ttyline, "", "");
1890 /* beware of flushing buffers after a SIGPIPE */
1909 /* only process if transfer occurring */
1913 /* This is all XXX */
1915 /* if the command resulted in a new command,
1916 parse that as well */
1919 } while(ftp_command);
1924 if (ftpd_getline(cp, 7) == NULL) {
1925 reply(221, "You could at least say goodbye.");
1929 if (strcmp(cp, "ABOR\r\n") == 0) {
1931 reply(426, "Transfer aborted. Data connection closed.");
1932 reply(226, "Abort successful");
1933 longjmp(urgcatch, 1);
1935 if (strcmp(cp, "STAT\r\n") == 0) {
1936 if (file_size != (off_t) -1)
1937 reply(213, "Status: %ld of %ld bytes transferred",
1941 reply(213, "Status: %ld bytes transferred"
1948 * Note: a response of 425 is not mentioned as a possible response to
1949 * the PASV command in RFC959. However, it has been blessed as
1950 * a legitimate response by Jon Postel in a telephone conversation
1951 * with Rick Adams on 25 Jan 89.
1958 struct sockaddr_in *sin;
1960 if (ctrl_addr->sa_family != AF_INET) {
1962 "You cannot do PASV with something that's not IPv4");
1969 pdata = socket(ctrl_addr->sa_family, SOCK_STREAM, 0);
1971 perror_reply(425, "Can't open passive connection");
1974 pasv_addr->sa_family = ctrl_addr->sa_family;
1975 socket_set_address_and_port (pasv_addr,
1976 socket_get_address (ctrl_addr),
1978 socket_set_portrange(pdata, restricted_data_ports,
1979 pasv_addr->sa_family);
1981 if (bind(pdata, pasv_addr, socket_sockaddr_size (pasv_addr)) < 0) {
1982 seteuid(pw->pw_uid);
1985 seteuid(pw->pw_uid);
1986 len = sizeof(pasv_addr_ss);
1987 if (getsockname(pdata, pasv_addr, &len) < 0)
1989 if (listen(pdata, 1) < 0)
1991 sin = (struct sockaddr_in *)pasv_addr;
1992 a = (char *) &sin->sin_addr;
1993 p = (char *) &sin->sin_port;
1995 #define UC(b) (((int) b) & 0xff)
1997 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1998 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2004 perror_reply(425, "Can't open passive connection");
2013 pdata = socket(ctrl_addr->sa_family, SOCK_STREAM, 0);
2015 perror_reply(425, "Can't open passive connection");
2018 pasv_addr->sa_family = ctrl_addr->sa_family;
2019 socket_set_address_and_port (pasv_addr,
2020 socket_get_address (ctrl_addr),
2022 socket_set_portrange(pdata, restricted_data_ports,
2023 pasv_addr->sa_family);
2025 if (bind(pdata, pasv_addr, socket_sockaddr_size (pasv_addr)) < 0) {
2026 seteuid(pw->pw_uid);
2029 seteuid(pw->pw_uid);
2030 len = sizeof(pasv_addr_ss);
2031 if (getsockname(pdata, pasv_addr, &len) < 0)
2033 if (listen(pdata, 1) < 0)
2036 reply(229, "Entering Extended Passive Mode (|||%d|)",
2037 ntohs(socket_get_port (pasv_addr)));
2043 perror_reply(425, "Can't open passive connection");
2064 reply(500, "Bad syntax in EPRT");
2067 af = strtol (str, &end, 0);
2068 if (af == 0 || *end != sep) {
2069 reply(500, "Bad syntax in EPRT");
2076 data_dest->sa_family = AF_INET6;
2080 data_dest->sa_family = AF_INET;
2083 reply(522, "Network protocol %d not supported, use (1"
2090 end = strchr (str, sep);
2092 reply(500, "Bad syntax in EPRT");
2096 ret = inet_pton (data_dest->sa_family, str,
2097 socket_get_address (data_dest));
2100 reply(500, "Bad address syntax in EPRT");
2104 port = strtol (str, &end, 0);
2105 if (port == 0 || *end != sep) {
2106 reply(500, "Bad port syntax in EPRT");
2109 socket_set_port (data_dest, htons(port));
2110 reply(200, "EPRT command successful.");
2114 * Generate unique name for file with basename "local".
2115 * The file named "local" is already known to exist.
2116 * Generates failure reply on error.
2119 gunique(char *local)
2121 static char new[MaxPathLen];
2126 cp = strrchr(local, '/');
2129 if (stat(cp ? local : ".", &st) < 0) {
2130 perror_reply(553, cp ? local : ".");
2135 for (count = 1; count < 100; count++) {
2136 snprintf (new, sizeof(new), "%s.%d", local, count);
2137 if (stat(new, &st) < 0)
2140 reply(452, "Unique file name cannot be created.");
2145 * Format and send reply containing system error number.
2148 perror_reply(int code, const char *string)
2150 reply(code, "%s: %s.", string, strerror(errno));
2153 static char *onefile[] = {
2159 list_file(char *file)
2161 if(use_builtin_ls) {
2163 dout = dataconn(file, -1, "w");
2166 set_buffer_size(fileno(dout), 0);
2167 if(builtin_ls(dout, file) == 0)
2168 reply(226, "Transfer complete.");
2170 reply(451, "Requested action aborted. Local error in processing.");
2176 const char *cmd = "/bin/ls -lA %s";
2178 const char *cmd = "/bin/ls -la %s";
2180 retrieve(cmd, file);
2185 send_file_list(char *whichf)
2191 char **dirlist, *dirname;
2195 char buf[MaxPathLen];
2197 if (strpbrk(whichf, "~{[*?") != NULL) {
2198 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE|
2206 memset(&gl, 0, sizeof(gl));
2208 if (glob(whichf, flags, 0, &gl)) {
2209 reply(550, "not found");
2211 } else if (gl.gl_pathc == 0) {
2213 perror_reply(550, whichf);
2216 dirlist = gl.gl_pathv;
2218 onefile[0] = whichf;
2223 if (setjmp(urgcatch)) {
2227 while ((dirname = *dirlist++)) {
2228 if (stat(dirname, &st) < 0) {
2230 * If user typed "ls -l", etc, and the client
2231 * used NLST, do what the user meant.
2233 if (dirname[0] == '-' && *dirlist == NULL &&
2238 perror_reply(550, whichf);
2248 if (S_ISREG(st.st_mode)) {
2250 dout = dataconn("file list", (off_t)-1, "w");
2255 snprintf(buf, sizeof(buf), "%s%s\n", dirname,
2256 type == TYPE_A ? "\r" : "");
2257 sec_write(fileno(dout), buf, strlen(buf));
2258 byte_count += strlen(dirname) + 1;
2260 } else if (!S_ISDIR(st.st_mode))
2263 if ((dirp = opendir(dirname)) == NULL)
2266 while ((dir = readdir(dirp)) != NULL) {
2267 char nbuf[MaxPathLen];
2269 if (!strcmp(dir->d_name, "."))
2271 if (!strcmp(dir->d_name, ".."))
2274 snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname, dir->d_name);
2277 * We have to do a stat to insure it's
2278 * not a directory or special file.
2280 if (simple || (stat(nbuf, &st) == 0 &&
2281 S_ISREG(st.st_mode))) {
2283 dout = dataconn("file list", (off_t)-1, "w");
2288 if(strncmp(nbuf, "./", 2) == 0)
2289 snprintf(buf, sizeof(buf), "%s%s\n", nbuf +2,
2290 type == TYPE_A ? "\r" : "");
2292 snprintf(buf, sizeof(buf), "%s%s\n", nbuf,
2293 type == TYPE_A ? "\r" : "");
2294 sec_write(fileno(dout), buf, strlen(buf));
2295 byte_count += strlen(nbuf) + 1;
2301 reply(550, "No files found.");
2302 else if (ferror(dout) != 0)
2303 perror_reply(550, "Data connection");
2305 reply(226, "Transfer complete.");
2309 sec_write(fileno(dout), buf, 0); /* XXX flush */
2329 snprintf(line, sizeof(line),
2330 "/bin/locate -d %s -- %s",
2331 ftp_rooted("/etc/locatedb"),
2333 f = ftpd_popen(line, "r", 1, 1);
2335 perror_reply(550, "/bin/locate");
2338 lreply(200, "Output from find.");
2339 while(fgets(line, sizeof(line), f)){
2340 if(line[strlen(line)-1] == '\n')
2341 line[strlen(line)-1] = 0;