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
33 * $FreeBSD: src/crypto/kerberosIV/appl/ftp/ftpd/ftpd.c,v 1.5.2.2 2001/03/04 12:52:41 markm Exp $
37 #include "ftpd_locl.h"
43 RCSID("$Id: ftpd.c,v 1.131.2.4 2000/09/26 09:30:26 assar Exp $");
45 static char version[] = "Version 6.00";
47 extern off_t restart_point;
50 struct sockaddr_storage ctrl_addr_ss;
51 struct sockaddr *ctrl_addr = (struct sockaddr *)&ctrl_addr_ss;
53 struct sockaddr_storage data_source_ss;
54 struct sockaddr *data_source = (struct sockaddr *)&data_source_ss;
56 struct sockaddr_storage data_dest_ss;
57 struct sockaddr *data_dest = (struct sockaddr *)&data_dest_ss;
59 struct sockaddr_storage his_addr_ss;
60 struct sockaddr *his_addr = (struct sockaddr *)&his_addr_ss;
62 struct sockaddr_storage pasv_addr_ss;
63 struct sockaddr *pasv_addr = (struct sockaddr *)&pasv_addr_ss;
66 jmp_buf errcatch, urgcatch;
71 int ftpd_timeout = 900; /* timeout after 15 minutes of inactivity */
72 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
78 int stru; /* avoid C keyword */
80 int usedefault = 1; /* for data transfers */
81 int pdata = -1; /* for passive mode */
85 #if !defined(CMASK) || CMASK == 0
89 int defumask = CMASK; /* default umask value */
90 int guest_umask = 0777; /* Paranoia for anonymous users */
92 char hostname[MaxHostNameLen];
93 char remotehost[MaxHostNameLen];
94 static char ttyline[20];
96 #define AUTH_PLAIN (1 << 0) /* allow sending passwords */
97 #define AUTH_OTP (1 << 1) /* passwords are one-time */
98 #define AUTH_FTP (1 << 2) /* allow anonymous login */
100 static int auth_level = 0; /* Only allow kerberos login by default */
103 * Timeout intervals for retrying connections
104 * to hosts that don't accept PORT cmds. This
105 * is a kludge, but given the problems with TCP...
107 #define SWAITMAX 90 /* wait at most 90 seconds */
108 #define SWAITINT 5 /* interval between retries */
110 int swaitmax = SWAITMAX;
111 int swaitint = SWAITINT;
113 #ifdef HAVE_SETPROCTITLE
114 char proctitle[BUFSIZ]; /* initial part of title */
115 #endif /* HAVE_SETPROCTITLE */
117 #define LOGCMD(cmd, file) \
119 syslog(LOG_INFO,"%s %s%s", cmd, \
120 *(file) == '/' ? "" : curdir(), file);
121 #define LOGCMD2(cmd, file1, file2) \
123 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
124 *(file1) == '/' ? "" : curdir(), file1, \
125 *(file2) == '/' ? "" : curdir(), file2);
126 #define LOGBYTES(cmd, file, cnt) \
128 if (cnt == (off_t)-1) \
129 syslog(LOG_INFO,"%s %s%s", cmd, \
130 *(file) == '/' ? "" : curdir(), file); \
132 syslog(LOG_INFO, "%s %s%s = %ld bytes", \
133 cmd, (*(file) == '/') ? "" : curdir(), file, (long)cnt); \
136 static void ack (char *);
137 static void myoob (int);
138 static int checkuser (char *, char *);
139 static int checkaccess (char *);
140 static FILE *dataconn (const char *, off_t, const char *);
141 static void dolog (struct sockaddr *);
142 static void end_login (void);
143 static FILE *getdatasock (const char *);
144 static char *gunique (char *);
145 static RETSIGTYPE lostconn (int);
146 static int receive_data (FILE *, FILE *);
147 static void send_data (FILE *, FILE *);
148 static struct passwd * sgetpwnam (char *);
153 static char path[MaxPathLen+1]; /* path + '/' + '\0' */
155 if (getcwd(path, sizeof(path)-1) == NULL)
157 if (path[1] != '\0') /* special case for root dir. */
158 strlcat(path, "/", sizeof(path));
159 /* For guest account, skip / since it's chrooted */
160 return (guest ? path+1 : path);
164 #define LINE_MAX 1024
168 parse_auth_level(char *str)
174 for(p = strtok_r(str, ",", &foo);
176 p = strtok_r(NULL, ",", &foo)) {
177 if(strcmp(p, "user") == 0)
180 else if(strcmp(p, "otp") == 0)
181 ret |= AUTH_PLAIN|AUTH_OTP;
183 else if(strcmp(p, "ftp") == 0 ||
184 strcmp(p, "safe") == 0)
186 else if(strcmp(p, "plain") == 0)
188 else if(strcmp(p, "none") == 0)
189 ret |= AUTH_PLAIN|AUTH_FTP;
191 warnx("bad value for -a: `%s'", p);
197 * Print usage and die.
200 static int interactive_flag;
201 static char *guest_umask_string;
202 static char *port_string;
203 static char *umask_string;
204 static char *auth_string;
206 int use_builtin_ls = -1;
208 static int help_flag;
209 static int version_flag;
211 struct getargs args[] = {
212 { NULL, 'a', arg_string, &auth_string, "required authentication" },
213 { NULL, 'i', arg_flag, &interactive_flag, "don't assume stdin is a socket" },
214 { NULL, 'p', arg_string, &port_string, "what port to listen to" },
215 { NULL, 'g', arg_string, &guest_umask_string, "umask for guest logins" },
216 { NULL, 'l', arg_counter, &logging, "log more stuff", "" },
217 { NULL, 't', arg_integer, &ftpd_timeout, "initial timeout" },
218 { NULL, 'T', arg_integer, &maxtimeout, "max timeout" },
219 { NULL, 'u', arg_string, &umask_string, "umask for user logins" },
220 { NULL, 'd', arg_flag, &debug, "enable debugging" },
221 { NULL, 'v', arg_flag, &debug, "enable debugging" },
222 { "builtin-ls", 'B', arg_flag, &use_builtin_ls, "use built-in ls to list files" },
223 { "version", 0, arg_flag, &version_flag },
224 { "help", 'h', arg_flag, &help_flag }
227 static int num_args = sizeof(args) / sizeof(args[0]);
232 arg_printusage(args, num_args, NULL, "");
236 /* output contents of a file */
238 show_file(const char *file, int code)
243 f = fopen(file, "r");
246 while(fgets(buf, sizeof(buf), f)){
247 buf[strcspn(buf, "\r\n")] = '\0';
248 lreply(code, "%s", buf);
255 main(int argc, char **argv)
257 int addrlen, on = 1, tos;
258 char *cp, line[LINE_MAX];
266 /* detach from any tickets and tokens */
269 snprintf(tkfile, sizeof(tkfile),
270 "/tmp/ftp_%u", (unsigned)getpid());
271 krb_set_tkt_string(tkfile);
276 if(getarg(args, num_args, argc, argv, &optind))
288 auth_level = parse_auth_level(auth_string);
293 if(guest_umask_string) {
294 val = strtol(guest_umask_string, &p, 8);
295 if (*p != '\0' || val < 0)
296 warnx("bad value for -g");
301 val = strtol(umask_string, &p, 8);
302 if (*p != '\0' || val < 0)
303 warnx("bad value for -u");
309 sp = getservbyname(port_string, "tcp");
313 if(isdigit(port_string[0]))
314 port = htons(atoi(port_string));
316 warnx("bad value for -p");
318 sp = getservbyname("ftp", "tcp");
325 if (maxtimeout < ftpd_timeout)
326 maxtimeout = ftpd_timeout;
329 if (ftpd_timeout > maxtimeout)
330 ftpd_timeout = maxtimeout;
338 * LOG_NDELAY sets up the logging connection immediately,
339 * necessary for anonymous ftp's that chroot and can't do it later.
341 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
342 addrlen = sizeof(his_addr_ss);
343 if (getpeername(STDIN_FILENO, his_addr, &addrlen) < 0) {
344 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
347 addrlen = sizeof(ctrl_addr_ss);
348 if (getsockname(STDIN_FILENO, ctrl_addr, &addrlen) < 0) {
349 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
352 #if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
353 tos = IPTOS_LOWDELAY;
354 if (setsockopt(STDIN_FILENO, IPPROTO_IP, IP_TOS,
355 (void *)&tos, sizeof(int)) < 0)
356 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
358 data_source->sa_family = ctrl_addr->sa_family;
359 socket_set_port (data_source,
360 htons(ntohs(socket_get_port(ctrl_addr)) - 1));
362 /* set this here so it can be put in wtmp */
363 snprintf(ttyline, sizeof(ttyline), "ftp%u", (unsigned)getpid());
366 /* freopen(_PATH_DEVNULL, "w", stderr); */
367 signal(SIGPIPE, lostconn);
368 signal(SIGCHLD, SIG_IGN);
370 if (signal(SIGURG, myoob) == SIG_ERR)
371 syslog(LOG_ERR, "signal: %m");
374 /* Try to handle urgent data inline */
375 #if defined(SO_OOBINLINE) && defined(HAVE_SETSOCKOPT)
376 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, (void *)&on,
378 syslog(LOG_ERR, "setsockopt: %m");
382 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
383 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
387 * Set up default state
396 /* If logins are disabled, print out the message. */
397 if(show_file(_PATH_NOLOGIN, 530) == 0) {
398 reply(530, "System not available.");
401 show_file(_PATH_FTPWELCOME, 220);
402 /* reply(220,) must follow */
403 gethostname(hostname, sizeof(hostname));
405 reply(220, "%s FTP server (%s"
412 ") ready.", hostname, version
432 syslog(LOG_DEBUG, "lost connection");
437 * Helper function for sgetpwnam().
442 char *new = strdup(s);
445 perror_reply(421, "Local resource failure: malloc");
453 * Save the result of a getpwnam. Used for USER command, since
454 * the data returned must not be clobbered by any other command
457 static struct passwd *
458 sgetpwnam(char *name)
460 static struct passwd save;
463 if ((p = k_getpwnam(name)) == NULL)
467 free(save.pw_passwd);
473 save.pw_name = sgetsave(p->pw_name);
474 save.pw_passwd = sgetsave(p->pw_passwd);
475 save.pw_gecos = sgetsave(p->pw_gecos);
476 save.pw_dir = sgetsave(p->pw_dir);
477 save.pw_shell = sgetsave(p->pw_shell);
481 static int login_attempts; /* number of failed login attempts */
482 static int askpasswd; /* had user command, ask for passwd */
483 static char curname[10]; /* current USER name */
490 * Sets global passwd pointer pw if named account exists and is acceptable;
491 * sets askpasswd if a PASS command is expected. If logged in previously,
492 * need to reset state. If name is "ftp" or "anonymous", the name is not in
493 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
494 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
495 * requesting login privileges. Disallow anyone who does not have a standard
496 * shell as returned by getusershell(). Disallow anyone mentioned in the file
497 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
504 if(auth_level == 0 && !sec_complete){
505 reply(530, "No login allowed without authorization.");
511 reply(530, "Can't change user from guest login.");
513 } else if (dochroot) {
514 reply(530, "Can't change user from chroot user.");
521 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
522 if ((auth_level & AUTH_FTP) == 0 ||
523 checkaccess("ftp") ||
524 checkaccess("anonymous"))
525 reply(530, "User %s access denied.", name);
526 else if ((pw = sgetpwnam("ftp")) != NULL) {
528 defumask = guest_umask; /* paranoia for incoming */
530 reply(331, "Guest login ok, type your name as password.");
532 reply(530, "User %s unknown.", name);
533 if (!askpasswd && logging) {
536 if (inet_ntop (his_addr->sa_family,
537 socket_get_address(his_addr),
538 data_addr, sizeof(data_addr)) == NULL)
539 strlcpy (data_addr, "unknown address",
543 "ANONYMOUS FTP LOGIN REFUSED FROM %s(%s)",
544 remotehost, data_addr);
548 if((auth_level & AUTH_PLAIN) == 0 && !sec_complete){
549 reply(530, "Only authorized and anonymous login allowed.");
552 if ((pw = sgetpwnam(name))) {
553 if ((shell = pw->pw_shell) == NULL || *shell == 0)
554 shell = _PATH_BSHELL;
555 while ((cp = getusershell()) != NULL)
556 if (strcmp(cp, shell) == 0)
560 if (cp == NULL || checkaccess(name)) {
561 reply(530, "User %s access denied.", name);
565 if (inet_ntop (his_addr->sa_family,
566 socket_get_address(his_addr),
568 sizeof(data_addr)) == NULL)
574 "FTP LOGIN REFUSED FROM %s(%s), %s",
579 pw = (struct passwd *) NULL;
584 strlcpy(curname, name, sizeof(curname));
586 if(sec_userok(name) == 0)
589 reply(530, "User %s access denied.", name);
594 if (otp_challenge(&otp_ctx, name, ss, sizeof(ss)) == 0) {
595 reply(331, "Password %s for %s required.",
600 if ((auth_level & AUTH_OTP) == 0) {
601 reply(331, "Password required for %s.", name);
607 if ((s = otp_error (&otp_ctx)) != NULL)
608 lreply(530, "OTP: %s", s);
611 "Only authorized, anonymous"
620 * Delay before reading passwd after first failed
621 * attempt to slow down passwd-guessing programs.
624 sleep(login_attempts);
628 * Check if a user is in the file "fname"
631 checkuser(char *fname, char *name)
635 char *p, line[BUFSIZ];
637 if ((fd = fopen(fname, "r")) != NULL) {
638 while (fgets(line, sizeof(line), fd) != NULL)
639 if ((p = strchr(line, '\n')) != NULL) {
643 if (strcmp(line, name) == 0) {
655 * Determine whether a user has access, based on information in
656 * _PATH_FTPUSERS. The users are listed one per line, with `allow'
657 * or `deny' after the username. If anything other than `allow', or
658 * just nothing, is given after the username, `deny' is assumed.
660 * If the user is not found in the file, but the pseudo-user `*' is,
661 * the permission is taken from that line.
663 * This preserves the old semantics where if a user was listed in the
664 * file he was denied, otherwise he was allowed.
666 * Return 1 if the user is denied, or 0 if he is allowed. */
669 match(const char *pattern, const char *string)
671 return fnmatch(pattern, string, FNM_NOESCAPE);
675 checkaccess(char *name)
678 #define NOT_ALLOWED 1
680 int allowed = ALLOWED;
681 char *user, *perm, line[BUFSIZ];
684 fd = fopen(_PATH_FTPUSERS, "r");
689 while (fgets(line, sizeof(line), fd) != NULL) {
691 user = strtok_r(line, " \t\n", &foo);
692 if (user == NULL || user[0] == '#')
694 perm = strtok_r(NULL, " \t\n", &foo);
695 if (match(user, name) == 0){
696 if(perm && strcmp(perm, "allow") == 0)
699 allowed = NOT_ALLOWED;
710 int do_login(int code, char *passwd)
713 login_attempts = 0; /* this time successful */
714 if (setegid((gid_t)pw->pw_gid) < 0) {
715 reply(550, "Can't set gid.");
718 initgroups(pw->pw_name, pw->pw_gid);
720 /* open wtmp before chroot */
721 ftpd_logwtmp(ttyline, pw->pw_name, remotehost);
724 dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name);
727 * We MUST do a chdir() after the chroot. Otherwise
728 * the old current directory will be accessible as "."
729 * outside the new root!
731 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
732 reply(550, "Can't set guest privileges.");
735 } else if (dochroot) {
736 if (chroot(pw->pw_dir) < 0 || chdir("/") < 0) {
737 reply(550, "Can't change root.");
740 } else if (chdir(pw->pw_dir) < 0) {
741 if (chdir("/") < 0) {
742 reply(530, "User %s: can't change directory to %s.",
743 pw->pw_name, pw->pw_dir);
746 lreply(code, "No directory! Logging in with home=/");
748 if (seteuid((uid_t)pw->pw_uid) < 0) {
749 reply(550, "Can't set uid.");
753 if(use_builtin_ls == -1) {
755 /* if /bin/ls exist and is a regular file, use it, otherwise
757 if(stat("/bin/ls", &st) == 0 &&
765 * Display a login message, if it exists.
766 * N.B. reply(code,) must follow the message.
768 show_file(_PATH_FTPLOGINMESG, code);
769 if(show_file(_PATH_ISSUE_NET, code) != 0)
770 show_file(_PATH_ISSUE, code);
772 reply(code, "Guest login ok, access restrictions apply.");
773 #ifdef HAVE_SETPROCTITLE
774 snprintf (proctitle, sizeof(proctitle),
778 setproctitle("%s", proctitle);
779 #endif /* HAVE_SETPROCTITLE */
783 if (inet_ntop (his_addr->sa_family,
784 socket_get_address(his_addr),
785 data_addr, sizeof(data_addr)) == NULL)
786 strlcpy (data_addr, "unknown address",
789 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s(%s), %s",
795 reply(code, "User %s logged in.", pw->pw_name);
796 #ifdef HAVE_SETPROCTITLE
797 snprintf(proctitle, sizeof(proctitle), "%s: %s", remotehost, pw->pw_name);
798 setproctitle("%s", proctitle);
799 #endif /* HAVE_SETPROCTITLE */
803 if (inet_ntop (his_addr->sa_family,
804 socket_get_address(his_addr),
805 data_addr, sizeof(data_addr)) == NULL)
806 strlcpy (data_addr, "unknown address",
809 syslog(LOG_INFO, "FTP LOGIN FROM %s(%s) as %s",
820 * Terminate login as previous user, if any, resetting state;
821 * used when USER command is given or login fails.
829 ftpd_logwtmp(ttyline, "", "");
841 /* some clients insists on sending a password */
842 if (logged_in && askpasswd == 0){
843 reply(230, "Dumpucko!");
847 if (logged_in || askpasswd == 0) {
848 reply(503, "Login with USER first.");
853 if (!guest) { /* "ftp" is only account allowed no password */
855 rval = 1; /* failure below */
857 else if (otp_verify_user (&otp_ctx, passwd) == 0) {
861 else if((auth_level & AUTH_OTP) == 0) {
863 char realm[REALM_SZ];
864 if((rval = krb_get_lrealm(realm, 1)) == KSUCCESS)
865 rval = krb_verify_user(pw->pw_name,
868 KRB_VERIFY_SECURE, NULL);
869 if (rval == KSUCCESS ) {
870 chown (tkt_string(), pw->pw_uid, pw->pw_gid);
875 rval = unix_verify_user(pw->pw_name, passwd);
880 if ((s = otp_error(&otp_ctx)) != NULL)
881 lreply(530, "OTP: %s", s);
884 memset (passwd, 0, strlen(passwd));
887 * If rval == 1, the user failed the authentication
888 * check above. If rval == 0, either Kerberos or
889 * local authentication succeeded.
894 if (inet_ntop (his_addr->sa_family,
895 socket_get_address(his_addr),
896 data_addr, sizeof(data_addr)) == NULL)
897 strlcpy (data_addr, "unknown address",
900 reply(530, "Login incorrect.");
903 "FTP LOGIN FAILED FROM %s(%s), %s",
908 if (login_attempts++ >= 5) {
910 "repeated login failures from %s(%s)",
918 if(!do_login(230, passwd))
921 /* Forget all about it... */
926 retrieve(const char *cmd, char *name)
928 FILE *fin = NULL, *dout;
930 int (*closefunc) (FILE *);
935 fin = fopen(name, "r");
939 int save_errno = errno;
945 {".tar", "/bin/gtar cPf - %s", NULL},
946 {".tar.gz", "/bin/gtar zcPf - %s", NULL},
947 {".tar.Z", "/bin/gtar ZcPf - %s", NULL},
948 {".gz", "/bin/gzip -c -- %s", "/bin/gzip -c -d -- %s"},
949 {".Z", "/bin/compress -c -- %s", "/bin/uncompress -c -- %s"},
953 for(p = cmds; p->ext; p++){
954 char *tail = name + strlen(name) - strlen(p->ext);
957 if(strcmp(tail, p->ext) == 0 &&
959 access(name, R_OK) == 0){
960 snprintf (line, sizeof(line), p->cmd, name);
965 if (p->rev_cmd != NULL) {
968 asprintf(&ext, "%s%s", name, p->ext);
970 if (access(ext, R_OK) == 0) {
971 snprintf (line, sizeof(line),
982 fin = ftpd_popen(line, "r", 0, 0);
983 closefunc = ftpd_pclose;
990 snprintf(line, sizeof(line), cmd, name);
992 fin = ftpd_popen(line, "r", 1, 0);
993 closefunc = ftpd_pclose;
998 perror_reply(550, name);
1000 LOGCMD("get", name);
1007 if(fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
1008 reply(550, "%s: not a plain file.", name);
1012 if (restart_point) {
1013 if (type == TYPE_A) {
1020 if ((c=getc(fin)) == EOF) {
1021 perror_reply(550, name);
1027 } else if (lseek(fileno(fin), restart_point, SEEK_SET) < 0) {
1028 perror_reply(550, name);
1032 dout = dataconn(name, st.st_size, "w");
1035 set_buffer_size(fileno(dout), 0);
1036 send_data(fin, dout);
1042 LOGBYTES("get", name, byte_count);
1046 /* filename sanity check */
1049 filename_check(char *filename)
1051 static const char good_chars[] = "+-=_,.";
1054 p = strrchr(filename, '/');
1062 while(*p && (isalnum(*p) || strchr(good_chars, *p)))
1067 lreply(553, "\"%s\" is an illegal filename.", filename);
1068 lreply(553, "The filename must start with an alphanumeric "
1069 "character and must only");
1070 reply(553, "consist of alphanumeric characters or any of the following: %s",
1076 do_store(char *name, char *mode, int unique)
1080 int (*closefunc) (FILE *);
1082 if(guest && filename_check(name))
1084 if (unique && stat(name, &st) == 0 &&
1085 (name = gunique(name)) == NULL) {
1086 LOGCMD(*mode == 'w' ? "put" : "append", name);
1092 fout = fopen(name, mode);
1095 perror_reply(553, name);
1096 LOGCMD(*mode == 'w' ? "put" : "append", name);
1100 if (restart_point) {
1101 if (type == TYPE_A) {
1108 if ((c=getc(fout)) == EOF) {
1109 perror_reply(550, name);
1116 * We must do this seek to "current" position
1117 * because we are changing from reading to
1120 if (fseek(fout, 0L, SEEK_CUR) < 0) {
1121 perror_reply(550, name);
1124 } else if (lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
1125 perror_reply(550, name);
1129 din = dataconn(name, (off_t)-1, "r");
1132 set_buffer_size(fileno(din), 1);
1133 if (receive_data(din, fout) == 0) {
1135 reply(226, "Transfer complete (unique file name:%s).",
1138 reply(226, "Transfer complete.");
1144 LOGBYTES(*mode == 'w' ? "put" : "append", name, byte_count);
1149 getdatasock(const char *mode)
1154 return (fdopen(data, mode));
1156 s = socket(ctrl_addr->sa_family, SOCK_STREAM, 0);
1159 socket_set_reuseaddr (s, 1);
1160 /* anchor socket to avoid multi-homing problems */
1161 socket_set_address_and_port (data_source,
1162 socket_get_address (ctrl_addr),
1163 socket_get_port (data_source));
1165 for (tries = 1; ; tries++) {
1166 if (bind(s, data_source,
1167 socket_sockaddr_size (data_source)) >= 0)
1169 if (errno != EADDRINUSE || tries > 10)
1173 seteuid(pw->pw_uid);
1174 #ifdef IPTOS_THROUGHPUT
1175 socket_set_tos (s, IPTOS_THROUGHPUT);
1177 return (fdopen(s, mode));
1179 /* Return the real value of errno (close may change it) */
1181 seteuid((uid_t)pw->pw_uid);
1188 dataconn(const char *name, off_t size, const char *mode)
1197 snprintf(sizebuf, sizeof(sizebuf), " (%ld bytes)", (long)size);
1201 struct sockaddr_storage from_ss;
1202 struct sockaddr *from = (struct sockaddr *)&from_ss;
1204 int fromlen = sizeof(from_ss);
1206 s = accept(pdata, from, &fromlen);
1208 reply(425, "Can't open data connection.");
1215 #if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
1217 int tos = IPTOS_THROUGHPUT;
1219 setsockopt(s, IPPROTO_IP, IP_TOS, (void *)&tos,
1223 reply(150, "Opening %s mode data connection for '%s'%s.",
1224 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1225 return (fdopen(pdata, mode));
1228 reply(125, "Using existing data connection for '%s'%s.",
1231 return (fdopen(data, mode));
1234 data_dest = his_addr;
1236 file = getdatasock(mode);
1238 char data_addr[256];
1240 if (inet_ntop (data_source->sa_family,
1241 socket_get_address(data_source),
1242 data_addr, sizeof(data_addr)) == NULL)
1243 strlcpy (data_addr, "unknown address",
1246 reply(425, "Can't create data socket (%s,%d): %s.",
1248 socket_get_port (data_source),
1252 data = fileno(file);
1253 while (connect(data, data_dest,
1254 socket_sockaddr_size(data_dest)) < 0) {
1255 if (errno == EADDRINUSE && retry < swaitmax) {
1260 perror_reply(425, "Can't build data connection");
1265 reply(150, "Opening %s mode data connection for '%s'%s.",
1266 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1271 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1272 * encapsulation of the data subject * to Mode, Structure, and Type.
1274 * NB: Form isn't handled.
1277 send_data(FILE *instr, FILE *outstr)
1279 int c, cnt, filefd, netfd;
1281 static size_t bufsize;
1284 if (setjmp(urgcatch)) {
1291 while ((c = getc(instr)) != EOF) {
1294 sec_putc('\r', outstr);
1295 sec_putc(c, outstr);
1303 reply(226, "Transfer complete.");
1308 #if defined(HAVE_MMAP) && !defined(NO_MMAP)
1310 #define MAP_FAILED (-1)
1315 int in = fileno(instr);
1316 if(fstat(in, &st) == 0 && S_ISREG(st.st_mode)
1317 && st.st_size > 0) {
1319 * mmap zero bytes has potential of loosing, don't do it.
1321 chunk = mmap(0, st.st_size, PROT_READ,
1323 if((void *)chunk != (void *)MAP_FAILED) {
1324 cnt = st.st_size - restart_point;
1325 sec_write(fileno(outstr), chunk + restart_point, cnt);
1326 if (munmap(chunk, st.st_size) < 0)
1338 netfd = fileno(outstr);
1339 filefd = fileno(instr);
1340 buf = alloc_buffer (buf, &bufsize,
1341 fstat(filefd, &st) >= 0 ? &st : NULL);
1344 perror_reply(451, "Local resource failure: malloc");
1347 while ((cnt = read(filefd, buf, bufsize)) > 0 &&
1348 sec_write(netfd, buf, cnt) == cnt)
1350 sec_fflush(outstr); /* to end an encrypted stream */
1358 reply(226, "Transfer complete.");
1362 reply(550, "Unimplemented TYPE %d in send_data", type);
1368 perror_reply(426, "Data connection");
1373 perror_reply(551, "Error on input file");
1377 * Transfer data from peer to "outstr" using the appropriate encapulation of
1378 * the data subject to Mode, Structure, and Type.
1380 * N.B.: Form isn't handled.
1383 receive_data(FILE *instr, FILE *outstr)
1385 int cnt, bare_lfs = 0;
1387 static size_t bufsize;
1391 if (setjmp(urgcatch)) {
1396 buf = alloc_buffer (buf, &bufsize,
1397 fstat(fileno(outstr), &st) >= 0 ? &st : NULL);
1400 perror_reply(451, "Local resource failure: malloc");
1408 while ((cnt = sec_read(fileno(instr), buf, bufsize)) > 0) {
1409 if (write(fileno(outstr), buf, cnt) != cnt)
1419 reply(553, "TYPE E not implemented.");
1427 while ((cnt = sec_read(fileno(instr),
1429 bufsize - cr_flag)) > 0){
1433 for(p = buf, q = buf; p < buf + cnt;) {
1437 if(p == buf + cnt - 1){
1441 }else if(p[1] == '\n'){
1449 fwrite(buf, q - buf, 1, outstr);
1462 lreply(226, "WARNING! %d bare linefeeds received in ASCII mode\r\n"
1463 " File may not have transferred correctly.\r\n",
1469 reply(550, "Unimplemented TYPE %d in receive_data", type);
1476 perror_reply(426, "Data Connection");
1481 perror_reply(452, "Error writing file");
1486 statfilecmd(char *filename)
1490 char line[LINE_MAX];
1492 snprintf(line, sizeof(line), "/bin/ls -la -- %s", filename);
1493 fin = ftpd_popen(line, "r", 1, 0);
1494 lreply(211, "status of %s:", filename);
1495 while ((c = getc(fin)) != EOF) {
1497 if (ferror(stdout)){
1498 perror_reply(421, "control connection");
1504 perror_reply(551, filename);
1513 reply(211, "End of Status");
1520 struct sockaddr_in *sin;
1523 lreply(211, "%s FTP server (%s) status:", hostname, version);
1524 printf(" %s\r\n", version);
1525 printf(" Connected to %s", remotehost);
1526 if (!isdigit(remotehost[0]))
1527 printf(" (%s)", inet_ntoa(his_addr.sin_addr));
1531 printf(" Logged in anonymously\r\n");
1533 printf(" Logged in as %s\r\n", pw->pw_name);
1534 } else if (askpasswd)
1535 printf(" Waiting for password\r\n");
1537 printf(" Waiting for user name\r\n");
1538 printf(" TYPE: %s", typenames[type]);
1539 if (type == TYPE_A || type == TYPE_E)
1540 printf(", FORM: %s", formnames[form]);
1543 printf(" %d", NBBY);
1545 printf(" %d", bytesize); /* need definition! */
1547 printf("; STRUcture: %s; transfer MODE: %s\r\n",
1548 strunames[stru], modenames[mode]);
1550 printf(" Data connection open\r\n");
1551 else if (pdata != -1) {
1552 printf(" in Passive mode");
1555 } else if (usedefault == 0) {
1559 a = (u_char *) &sin->sin_addr;
1560 p = (u_char *) &sin->sin_port;
1561 #define UC(b) (((int) b) & 0xff)
1562 printf(" (%d,%d,%d,%d,%d,%d)\r\n", UC(a[0]),
1563 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1566 printf(" No data connection\r\n");
1568 reply(211, "End of status");
1575 reply(451, "Error in server: %s\n", s);
1576 reply(221, "Closing connection due to server error.");
1582 int_reply(int, char *, const char *, va_list)
1584 __attribute__ ((format (printf, 3, 0)))
1589 int_reply(int n, char *c, const char *fmt, va_list ap)
1595 snprintf(p, sizeof(buf), "%d%s", n, c);
1598 vsnprintf(p, sizeof(buf) - strlen(p), fmt, ap);
1600 snprintf(p, sizeof(buf) - strlen(p), "\r\n");
1602 sec_fprintf(stdout, "%s", buf);
1605 syslog(LOG_DEBUG, "<--- %s- ", buf);
1609 reply(int n, const char *fmt, ...)
1613 int_reply(n, " ", fmt, ap);
1614 delete_ftp_command();
1619 lreply(int n, const char *fmt, ...)
1623 int_reply(n, "-", fmt, ap);
1628 nreply(const char *fmt, ...)
1632 int_reply(0, NULL, fmt, ap);
1640 reply(250, "%s command successful.", s);
1647 reply(502, "%s command not implemented.", s);
1656 if ((cp = strchr(cbuf,'\n')))
1658 reply(500, "'%s': command not understood.", cbuf);
1662 do_delete(char *name)
1666 LOGCMD("delete", name);
1667 if (stat(name, &st) < 0) {
1668 perror_reply(550, name);
1671 if ((st.st_mode&S_IFMT) == S_IFDIR) {
1672 if (rmdir(name) < 0) {
1673 perror_reply(550, name);
1678 if (unlink(name) < 0) {
1679 perror_reply(550, name);
1690 if (chdir(path) < 0)
1691 perror_reply(550, path);
1700 LOGCMD("mkdir", name);
1701 if(guest && filename_check(name))
1703 if (mkdir(name, 0777) < 0)
1704 perror_reply(550, name);
1707 chmod(name, 0700); /* guest has umask 777 */
1708 reply(257, "MKD command successful.");
1713 removedir(char *name)
1716 LOGCMD("rmdir", name);
1717 if (rmdir(name) < 0)
1718 perror_reply(550, name);
1726 char path[MaxPathLen];
1729 /* SunOS has a broken getcwd that does popen(pwd) (!!!), this
1730 * failes miserably when running chroot
1732 ret = getcwd(path, sizeof(path));
1734 reply(550, "%s.", strerror(errno));
1736 reply(257, "\"%s\" is current directory.", path);
1740 renamefrom(char *name)
1744 if (stat(name, &st) < 0) {
1745 perror_reply(550, name);
1748 reply(350, "File exists, ready for destination name");
1753 renamecmd(char *from, char *to)
1756 LOGCMD2("rename", from, to);
1757 if(guest && filename_check(to))
1759 if (rename(from, to) < 0)
1760 perror_reply(550, "rename");
1766 dolog(struct sockaddr *sa)
1768 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
1770 inaddr2str (sin->sin_addr, remotehost, sizeof(remotehost));
1771 #ifdef HAVE_SETPROCTITLE
1772 snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost);
1773 setproctitle("%s", proctitle);
1774 #endif /* HAVE_SETPROCTITLE */
1777 char data_addr[256];
1779 if (inet_ntop (his_addr->sa_family,
1780 socket_get_address(his_addr),
1781 data_addr, sizeof(data_addr)) == NULL)
1782 strlcpy (data_addr, "unknown address",
1786 syslog(LOG_INFO, "connection from %s(%s)",
1793 * Record logout in wtmp file
1794 * and exit with supplied status.
1797 dologout(int status)
1802 ftpd_logwtmp(ttyline, "", "");
1807 /* beware of flushing buffers after a SIGPIPE */
1826 /* only process if transfer occurring */
1830 /* This is all XXX */
1832 /* if the command resulted in a new command,
1833 parse that as well */
1836 } while(ftp_command);
1841 if (ftpd_getline(cp, 7) == NULL) {
1842 reply(221, "You could at least say goodbye.");
1846 if (strcmp(cp, "ABOR\r\n") == 0) {
1848 reply(426, "Transfer aborted. Data connection closed.");
1849 reply(226, "Abort successful");
1850 longjmp(urgcatch, 1);
1852 if (strcmp(cp, "STAT\r\n") == 0) {
1853 if (file_size != (off_t) -1)
1854 reply(213, "Status: %ld of %ld bytes transferred",
1858 reply(213, "Status: %ld bytes transferred"
1865 * Note: a response of 425 is not mentioned as a possible response to
1866 * the PASV command in RFC959. However, it has been blessed as
1867 * a legitimate response by Jon Postel in a telephone conversation
1868 * with Rick Adams on 25 Jan 89.
1875 struct sockaddr_in *sin;
1877 if (ctrl_addr->sa_family != AF_INET) {
1879 "You cannot do PASV with something that's not IPv4");
1883 pdata = socket(ctrl_addr->sa_family, SOCK_STREAM, 0);
1885 perror_reply(425, "Can't open passive connection");
1888 pasv_addr->sa_family = ctrl_addr->sa_family;
1889 socket_set_address_and_port (pasv_addr,
1890 socket_get_address (ctrl_addr),
1893 if (bind(pdata, pasv_addr, socket_sockaddr_size (pasv_addr)) < 0) {
1894 seteuid(pw->pw_uid);
1897 seteuid(pw->pw_uid);
1898 len = sizeof(pasv_addr_ss);
1899 if (getsockname(pdata, pasv_addr, &len) < 0)
1901 if (listen(pdata, 1) < 0)
1903 sin = (struct sockaddr_in *)pasv_addr;
1904 a = (char *) &sin->sin_addr;
1905 p = (char *) &sin->sin_port;
1907 #define UC(b) (((int) b) & 0xff)
1909 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
1910 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
1916 perror_reply(425, "Can't open passive connection");
1925 pdata = socket(ctrl_addr->sa_family, SOCK_STREAM, 0);
1927 perror_reply(425, "Can't open passive connection");
1930 pasv_addr->sa_family = ctrl_addr->sa_family;
1931 socket_set_address_and_port (pasv_addr,
1932 socket_get_address (ctrl_addr),
1935 if (bind(pdata, pasv_addr, socket_sockaddr_size (pasv_addr)) < 0) {
1936 seteuid(pw->pw_uid);
1939 seteuid(pw->pw_uid);
1940 len = sizeof(pasv_addr_ss);
1941 if (getsockname(pdata, pasv_addr, &len) < 0)
1943 if (listen(pdata, 1) < 0)
1946 reply(229, "Entering Extended Passive Mode (|||%d|)",
1947 ntohs(socket_get_port (pasv_addr)));
1953 perror_reply(425, "Can't open passive connection");
1974 reply(500, "Bad syntax in EPRT");
1977 af = strtol (str, &end, 0);
1978 if (af == 0 || *end != sep) {
1979 reply(500, "Bad syntax in EPRT");
1986 data_dest->sa_family = AF_INET6;
1990 data_dest->sa_family = AF_INET;
1993 reply(522, "Network protocol %d not supported, use (1"
2000 end = strchr (str, sep);
2002 reply(500, "Bad syntax in EPRT");
2006 ret = inet_pton (data_dest->sa_family, str,
2007 socket_get_address (data_dest));
2010 reply(500, "Bad address syntax in EPRT");
2014 port = strtol (str, &end, 0);
2015 if (port == 0 || *end != sep) {
2016 reply(500, "Bad port syntax in EPRT");
2019 socket_set_port (data_dest, htons(port));
2020 reply(200, "EPRT command successful.");
2024 * Generate unique name for file with basename "local".
2025 * The file named "local" is already known to exist.
2026 * Generates failure reply on error.
2029 gunique(char *local)
2031 static char new[MaxPathLen];
2036 cp = strrchr(local, '/');
2039 if (stat(cp ? local : ".", &st) < 0) {
2040 perror_reply(553, cp ? local : ".");
2045 for (count = 1; count < 100; count++) {
2046 snprintf (new, sizeof(new), "%s.%d", local, count);
2047 if (stat(new, &st) < 0)
2050 reply(452, "Unique file name cannot be created.");
2055 * Format and send reply containing system error number.
2058 perror_reply(int code, const char *string)
2060 reply(code, "%s: %s.", string, strerror(errno));
2063 static char *onefile[] = {
2069 list_file(char *file)
2071 if(use_builtin_ls) {
2073 dout = dataconn(file, -1, "w");
2076 set_buffer_size(fileno(dout), 0);
2077 builtin_ls(dout, file);
2078 reply(226, "Transfer complete.");
2084 const char *cmd = "/bin/ls -lA -- %s";
2086 const char *cmd = "/bin/ls -la -- %s";
2088 retrieve(cmd, file);
2093 send_file_list(char *whichf)
2099 char **dirlist, *dirname;
2103 char buf[MaxPathLen];
2105 if (strpbrk(whichf, "~{[*?") != NULL) {
2106 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2108 memset(&gl, 0, sizeof(gl));
2110 if (glob(whichf, flags, 0, &gl)) {
2111 reply(550, "not found");
2113 } else if (gl.gl_pathc == 0) {
2115 perror_reply(550, whichf);
2118 dirlist = gl.gl_pathv;
2120 onefile[0] = whichf;
2125 if (setjmp(urgcatch)) {
2129 while ((dirname = *dirlist++)) {
2130 if (stat(dirname, &st) < 0) {
2132 * If user typed "ls -l", etc, and the client
2133 * used NLST, do what the user meant.
2135 if (dirname[0] == '-' && *dirlist == NULL &&
2140 perror_reply(550, whichf);
2150 if (S_ISREG(st.st_mode)) {
2152 dout = dataconn("file list", (off_t)-1, "w");
2157 snprintf(buf, sizeof(buf), "%s%s\n", dirname,
2158 type == TYPE_A ? "\r" : "");
2159 sec_write(fileno(dout), buf, strlen(buf));
2160 byte_count += strlen(dirname) + 1;
2162 } else if (!S_ISDIR(st.st_mode))
2165 if ((dirp = opendir(dirname)) == NULL)
2168 while ((dir = readdir(dirp)) != NULL) {
2169 char nbuf[MaxPathLen];
2171 if (!strcmp(dir->d_name, "."))
2173 if (!strcmp(dir->d_name, ".."))
2176 snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname, dir->d_name);
2179 * We have to do a stat to insure it's
2180 * not a directory or special file.
2182 if (simple || (stat(nbuf, &st) == 0 &&
2183 S_ISREG(st.st_mode))) {
2185 dout = dataconn("file list", (off_t)-1, "w");
2190 if(strncmp(nbuf, "./", 2) == 0)
2191 snprintf(buf, sizeof(buf), "%s%s\n", nbuf +2,
2192 type == TYPE_A ? "\r" : "");
2194 snprintf(buf, sizeof(buf), "%s%s\n", nbuf,
2195 type == TYPE_A ? "\r" : "");
2196 sec_write(fileno(dout), buf, strlen(buf));
2197 byte_count += strlen(nbuf) + 1;
2203 reply(550, "No files found.");
2204 else if (ferror(dout) != 0)
2205 perror_reply(550, "Data connection");
2207 reply(226, "Transfer complete.");
2211 sec_write(fileno(dout), buf, 0); /* XXX flush */
2231 snprintf(line, sizeof(line),
2232 "/bin/locate -d %s -- %s",
2233 ftp_rooted("/etc/locatedb"),
2235 f = ftpd_popen(line, "r", 1, 1);
2237 perror_reply(550, "/bin/locate");
2240 lreply(200, "Output from find.");
2241 while(fgets(line, sizeof(line), f)){
2242 if(line[strlen(line)-1] == '\n')
2243 line[strlen(line)-1] = 0;