Port EST driver from NetBSD, as it has better support for newer CPUs
[dragonfly.git] / libexec / ftpd / ftpd.c
blob960de72381fc688991d9a6f04638b9db0dbf8dda
1 /*
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
7 * are met:
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
31 * SUCH DAMAGE.
33 * @(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 The Regents of the University of California. All rights reserved.
34 * @(#)ftpd.c 8.4 (Berkeley) 4/16/94
37 #if 0
38 static const char rcsid[] =
39 "$FreeBSD: src/libexec/ftpd/ftpd.c,v 1.62.2.48 2003/02/14 12:42:42 yar Exp $";
40 "$DragonFly: src/libexec/ftpd/ftpd.c,v 1.7 2005/10/28 18:06:57 joerg Exp $";
41 #endif /* not lint */
44 * FTP server.
46 #include <sys/param.h>
47 #include <sys/ioctl.h>
48 #include <sys/mman.h>
49 #include <sys/socket.h>
50 #include <sys/stat.h>
51 #include <sys/time.h>
52 #include <sys/wait.h>
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
57 #include <netinet/tcp.h>
59 #define FTP_NAMES
60 #include <arpa/ftp.h>
61 #include <arpa/inet.h>
62 #include <arpa/telnet.h>
64 #include <ctype.h>
65 #include <dirent.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <glob.h>
70 #include <limits.h>
71 #include <netdb.h>
72 #include <pwd.h>
73 #include <grp.h>
74 #include <signal.h>
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <syslog.h>
79 #include <time.h>
80 #include <unistd.h>
81 #include <libutil.h>
82 #ifdef LOGIN_CAP
83 #include <login_cap.h>
84 #endif
86 #ifdef SKEY
87 #include <skey.h>
88 #endif
90 #if !defined(NOPAM)
91 #include <security/pam_appl.h>
92 #endif
94 #include "pathnames.h"
95 #include "extern.h"
97 #if __STDC__
98 #include <stdarg.h>
99 #else
100 #include <varargs.h>
101 #endif
103 static char version[] = "Version 6.00LS";
104 #undef main
106 extern off_t restart_point;
107 extern char cbuf[];
109 union sockunion server_addr;
110 union sockunion ctrl_addr;
111 union sockunion data_source;
112 union sockunion data_dest;
113 union sockunion his_addr;
114 union sockunion pasv_addr;
116 int daemon_mode;
117 int data;
118 int dataport;
119 int hostinfo = 1; /* print host-specific info in messages */
120 int logged_in;
121 struct passwd *pw;
122 char *homedir;
123 int ftpdebug;
124 int timeout = 900; /* timeout after 15 minutes of inactivity */
125 int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */
126 int logging;
127 int restricted_data_ports = 1;
128 int paranoid = 1; /* be extra careful about security */
129 int anon_only = 0; /* Only anonymous ftp allowed */
130 int guest;
131 int dochroot;
132 int dowtmp = 1;
133 int stats;
134 int statfd = -1;
135 int type;
136 int form;
137 int stru; /* avoid C keyword */
138 int mode;
139 int usedefault = 1; /* for data transfers */
140 int pdata = -1; /* for passive mode */
141 int readonly=0; /* Server is in readonly mode. */
142 int noepsv=0; /* EPSV command is disabled. */
143 int noretr=0; /* RETR command is disabled. */
144 int noguestretr=0; /* RETR command is disabled for anon users. */
145 int noguestmkd=0; /* MKD command is disabled for anon users. */
146 int noguestmod=1; /* anon users may not modify existing files. */
148 static volatile sig_atomic_t recvurg;
149 sig_atomic_t transflag;
150 off_t file_size;
151 off_t byte_count;
152 #if !defined(CMASK) || CMASK == 0
153 #undef CMASK
154 #define CMASK 027
155 #endif
156 int defumask = CMASK; /* default umask value */
157 char tmpline[7];
158 char *hostname;
159 int epsvall = 0;
161 #ifdef VIRTUAL_HOSTING
162 char *ftpuser;
164 static struct ftphost {
165 struct ftphost *next;
166 struct addrinfo *hostinfo;
167 char *hostname;
168 char *anonuser;
169 char *statfile;
170 char *welcome;
171 char *loginmsg;
172 } *thishost, *firsthost;
174 #endif
175 char remotehost[MAXHOSTNAMELEN];
176 char *ident = NULL;
178 static char ttyline[20];
179 char *tty = ttyline; /* for klogin */
181 #if !defined(NOPAM)
182 static int auth_pam (struct passwd**, const char*);
183 #endif
185 char *pid_file = NULL;
188 * Limit number of pathnames that glob can return.
189 * A limit of 0 indicates the number of pathnames is unlimited.
191 #define MAXGLOBARGS 16384
195 * Timeout intervals for retrying connections
196 * to hosts that don't accept PORT cmds. This
197 * is a kludge, but given the problems with TCP...
199 #define SWAITMAX 90 /* wait at most 90 seconds */
200 #define SWAITINT 5 /* interval between retries */
202 int swaitmax = SWAITMAX;
203 int swaitint = SWAITINT;
205 #ifdef SETPROCTITLE
206 #ifdef OLD_SETPROCTITLE
207 char **Argv = NULL; /* pointer to argument vector */
208 char *LastArgv = NULL; /* end of argv */
209 #endif /* OLD_SETPROCTITLE */
210 char proctitle[LINE_MAX]; /* initial part of title */
211 #endif /* SETPROCTITLE */
213 #ifdef SKEY
214 int pwok = 0;
215 #endif
217 #define LOGCMD(cmd, file) \
218 if (logging > 1) \
219 syslog(LOG_INFO,"%s %s%s", cmd, \
220 *(file) == '/' ? "" : curdir(), file);
221 #define LOGCMD2(cmd, file1, file2) \
222 if (logging > 1) \
223 syslog(LOG_INFO,"%s %s%s %s%s", cmd, \
224 *(file1) == '/' ? "" : curdir(), file1, \
225 *(file2) == '/' ? "" : curdir(), file2);
226 #define LOGBYTES(cmd, file, cnt) \
227 if (logging > 1) { \
228 if (cnt == (off_t)-1) \
229 syslog(LOG_INFO,"%s %s%s", cmd, \
230 *(file) == '/' ? "" : curdir(), file); \
231 else \
232 syslog(LOG_INFO, "%s %s%s = %qd bytes", \
233 cmd, (*(file) == '/') ? "" : curdir(), file, cnt); \
236 #ifdef VIRTUAL_HOSTING
237 static void inithosts (void);
238 static void selecthost (union sockunion *);
239 #endif
240 static void ack (char *);
241 static void sigurg (int);
242 static void myoob (void);
243 static int checkuser (char *, char *, int, char **);
244 static FILE *dataconn (char *, off_t, char *);
245 static void dolog (struct sockaddr *);
246 static char *curdir (void);
247 static void end_login (void);
248 static FILE *getdatasock (char *);
249 static int guniquefd (char *, char **);
250 static void lostconn (int);
251 static void sigquit (int);
252 static int receive_data (FILE *, FILE *);
253 static int send_data (FILE *, FILE *, off_t, off_t, int);
254 static struct passwd *
255 sgetpwnam (char *);
256 static char *sgetsave (char *);
257 static void reapchild (int);
258 static void logxfer (char *, off_t, time_t);
259 static char *doublequote (char *);
261 static char *
262 curdir()
264 static char path[MAXPATHLEN+1+1]; /* path + '/' + '\0' */
266 if (getcwd(path, sizeof(path)-2) == NULL)
267 return ("");
268 if (path[1] != '\0') /* special case for root dir. */
269 strcat(path, "/");
270 /* For guest account, skip / since it's chrooted */
271 return (guest ? path+1 : path);
275 main(argc, argv, envp)
276 int argc;
277 char *argv[];
278 char **envp;
280 int addrlen, ch, on = 1, tos;
281 char *cp, line[LINE_MAX];
282 FILE *fd;
283 int error;
284 char *bindname = NULL;
285 const char *bindport = "ftp";
286 int family = AF_UNSPEC;
287 int enable_v4 = 0;
288 struct sigaction sa;
290 tzset(); /* in case no timezone database in ~ftp */
291 sigemptyset(&sa.sa_mask);
292 sa.sa_flags = SA_RESTART;
294 #ifdef OLD_SETPROCTITLE
296 * Save start and extent of argv for setproctitle.
298 Argv = argv;
299 while (*envp)
300 envp++;
301 LastArgv = envp[-1] + strlen(envp[-1]);
302 #endif /* OLD_SETPROCTITLE */
305 while ((ch = getopt(argc, argv,
306 "46a:AdDEH:hlmMoOp:P:rRSt:T:u:UvW")) != -1) {
307 switch (ch) {
308 case '4':
309 enable_v4 = 1;
310 if (family == AF_UNSPEC)
311 family = AF_INET;
312 break;
314 case '6':
315 family = AF_INET6;
316 break;
318 case 'a':
319 bindname = optarg;
320 break;
322 case 'A':
323 anon_only = 1;
324 break;
326 case 'd':
327 ftpdebug++;
328 break;
330 case 'D':
331 daemon_mode++;
332 break;
334 case 'E':
335 noepsv = 1;
336 break;
338 case 'h':
339 hostinfo = 0;
340 break;
342 case 'H':
343 hostname = optarg;
344 break;
346 case 'l':
347 logging++; /* > 1 == extra logging */
348 break;
350 case 'm':
351 noguestmod = 0;
352 break;
354 case 'M':
355 noguestmkd = 1;
356 break;
358 case 'o':
359 noretr = 1;
360 break;
362 case 'O':
363 noguestretr = 1;
364 break;
366 case 'p':
367 pid_file = optarg;
368 break;
370 case 'P':
371 bindport = optarg;
372 break;
374 case 'r':
375 readonly = 1;
376 break;
378 case 'R':
379 paranoid = 0;
380 break;
382 case 'S':
383 stats++;
384 break;
386 case 't':
387 timeout = atoi(optarg);
388 if (maxtimeout < timeout)
389 maxtimeout = timeout;
390 break;
392 case 'T':
393 maxtimeout = atoi(optarg);
394 if (timeout > maxtimeout)
395 timeout = maxtimeout;
396 break;
398 case 'u':
400 long val = 0;
402 val = strtol(optarg, &optarg, 8);
403 if (*optarg != '\0' || val < 0)
404 warnx("bad value for -u");
405 else
406 defumask = val;
407 break;
409 case 'U':
410 restricted_data_ports = 0;
411 break;
413 case 'v':
414 ftpdebug++;
415 break;
417 case 'W':
418 dowtmp = 0;
419 break;
421 default:
422 warnx("unknown flag -%c ignored", optopt);
423 break;
427 #ifdef VIRTUAL_HOSTING
428 inithosts();
429 #endif
430 (void) freopen(_PATH_DEVNULL, "w", stderr);
433 * LOG_NDELAY sets up the logging connection immediately,
434 * necessary for anonymous ftp's that chroot and can't do it later.
436 openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
438 if (daemon_mode) {
439 int ctl_sock, fd;
440 struct addrinfo hints, *res;
443 * Detach from parent.
445 if (daemon(1, 1) < 0) {
446 syslog(LOG_ERR, "failed to become a daemon");
447 exit(1);
449 sa.sa_handler = reapchild;
450 (void)sigaction(SIGCHLD, &sa, NULL);
451 /* init bind_sa */
452 memset(&hints, 0, sizeof(hints));
454 hints.ai_family = family == AF_UNSPEC ? AF_INET : family;
455 hints.ai_socktype = SOCK_STREAM;
456 hints.ai_protocol = 0;
457 hints.ai_flags = AI_PASSIVE;
458 error = getaddrinfo(bindname, bindport, &hints, &res);
459 if (error) {
460 if (family == AF_UNSPEC) {
461 hints.ai_family = AF_UNSPEC;
462 error = getaddrinfo(bindname, bindport, &hints,
463 &res);
466 if (error) {
467 syslog(LOG_ERR, "%s", gai_strerror(error));
468 if (error == EAI_SYSTEM)
469 syslog(LOG_ERR, "%s", strerror(errno));
470 exit(1);
472 if (res->ai_addr == NULL) {
473 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
474 exit(1);
475 } else
476 family = res->ai_addr->sa_family;
478 * Open a socket, bind it to the FTP port, and start
479 * listening.
481 ctl_sock = socket(family, SOCK_STREAM, 0);
482 if (ctl_sock < 0) {
483 syslog(LOG_ERR, "control socket: %m");
484 exit(1);
486 if (setsockopt(ctl_sock, SOL_SOCKET, SO_REUSEADDR,
487 &on, sizeof(on)) < 0)
488 syslog(LOG_WARNING,
489 "control setsockopt (SO_REUSEADDR): %m");
490 if (family == AF_INET6 && enable_v4 == 0) {
491 if (setsockopt(ctl_sock, IPPROTO_IPV6, IPV6_V6ONLY,
492 &on, sizeof (on)) < 0)
493 syslog(LOG_WARNING,
494 "control setsockopt (IPV6_V6ONLY): %m");
496 memcpy(&server_addr, res->ai_addr, res->ai_addr->sa_len);
497 if (bind(ctl_sock, (struct sockaddr *)&server_addr,
498 server_addr.su_len) < 0) {
499 syslog(LOG_ERR, "control bind: %m");
500 exit(1);
502 if (listen(ctl_sock, 32) < 0) {
503 syslog(LOG_ERR, "control listen: %m");
504 exit(1);
507 * Atomically write process ID
509 if (pid_file)
511 int fd;
512 char buf[20];
514 fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC
515 | O_NONBLOCK | O_EXLOCK, 0644);
516 if (fd < 0) {
517 if (errno == EAGAIN)
518 errx(1, "%s: file locked", pid_file);
519 else
520 err(1, "%s", pid_file);
522 snprintf(buf, sizeof(buf),
523 "%lu\n", (unsigned long) getpid());
524 if (write(fd, buf, strlen(buf)) < 0)
525 err(1, "%s: write", pid_file);
526 /* Leave the pid file open and locked */
529 * Loop forever accepting connection requests and forking off
530 * children to handle them.
532 while (1) {
533 addrlen = server_addr.su_len;
534 fd = accept(ctl_sock, (struct sockaddr *)&his_addr, &addrlen);
536 if (fd >= 0) {
537 if (fork() == 0) {
538 /* child */
539 (void) dup2(fd, 0);
540 (void) dup2(fd, 1);
541 close(ctl_sock);
542 break;
544 close(fd);
547 } else {
548 addrlen = sizeof(his_addr);
549 if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) {
550 syslog(LOG_ERR, "getpeername (%s): %m",argv[0]);
551 exit(1);
555 sa.sa_handler = SIG_DFL;
556 (void)sigaction(SIGCHLD, &sa, NULL);
558 sa.sa_handler = sigurg;
559 sa.sa_flags = 0; /* don't restart syscalls for SIGURG */
560 (void)sigaction(SIGURG, &sa, NULL);
562 sigfillset(&sa.sa_mask); /* block all signals in handler */
563 sa.sa_flags = SA_RESTART;
564 sa.sa_handler = sigquit;
565 (void)sigaction(SIGHUP, &sa, NULL);
566 (void)sigaction(SIGINT, &sa, NULL);
567 (void)sigaction(SIGQUIT, &sa, NULL);
568 (void)sigaction(SIGTERM, &sa, NULL);
570 sa.sa_handler = lostconn;
571 (void)sigaction(SIGPIPE, &sa, NULL);
573 addrlen = sizeof(ctrl_addr);
574 if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) {
575 syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
576 exit(1);
578 dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */
579 #ifdef VIRTUAL_HOSTING
580 /* select our identity from virtual host table */
581 selecthost(&ctrl_addr);
582 #endif
583 #ifdef IP_TOS
584 if (ctrl_addr.su_family == AF_INET)
586 tos = IPTOS_LOWDELAY;
587 if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
588 syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m");
590 #endif
592 * Disable Nagle on the control channel so that we don't have to wait
593 * for peer's ACK before issuing our next reply.
595 if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
596 syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m");
598 data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1);
600 /* set this here so klogin can use it... */
601 (void)snprintf(ttyline, sizeof(ttyline), "ftp%d", getpid());
603 /* Try to handle urgent data inline */
604 #ifdef SO_OOBINLINE
605 if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0)
606 syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m");
607 #endif
609 #ifdef F_SETOWN
610 if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1)
611 syslog(LOG_ERR, "fcntl F_SETOWN: %m");
612 #endif
613 dolog((struct sockaddr *)&his_addr);
615 * Set up default state
617 data = -1;
618 type = TYPE_A;
619 form = FORM_N;
620 stru = STRU_F;
621 mode = MODE_S;
622 tmpline[0] = '\0';
624 /* If logins are disabled, print out the message. */
625 if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) {
626 while (fgets(line, sizeof(line), fd) != NULL) {
627 if ((cp = strchr(line, '\n')) != NULL)
628 *cp = '\0';
629 lreply(530, "%s", line);
631 (void) fflush(stdout);
632 (void) fclose(fd);
633 reply(530, "System not available.");
634 exit(0);
636 #ifdef VIRTUAL_HOSTING
637 if ((fd = fopen(thishost->welcome, "r")) != NULL) {
638 #else
639 if ((fd = fopen(_PATH_FTPWELCOME, "r")) != NULL) {
640 #endif
641 while (fgets(line, sizeof(line), fd) != NULL) {
642 if ((cp = strchr(line, '\n')) != NULL)
643 *cp = '\0';
644 lreply(220, "%s", line);
646 (void) fflush(stdout);
647 (void) fclose(fd);
648 /* reply(220,) must follow */
650 #ifndef VIRTUAL_HOSTING
651 if (hostname == NULL) {
652 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
653 fatalerror("Ran out of memory.");
654 gethostname(hostname, MAXHOSTNAMELEN - 1);
655 hostname[MAXHOSTNAMELEN - 1] = '\0';
657 #endif
658 if (hostinfo)
659 reply(220, "%s FTP server (%s) ready.", hostname, version);
660 else
661 reply(220, "FTP server ready.");
662 for (;;)
663 (void) yyparse();
664 /* NOTREACHED */
667 static void
668 lostconn(signo)
669 int signo;
672 if (ftpdebug)
673 syslog(LOG_DEBUG, "lost connection");
674 dologout(1);
677 static void
678 sigquit(signo)
679 int signo;
682 syslog(LOG_ERR, "got signal %d", signo);
683 dologout(1);
686 #ifdef VIRTUAL_HOSTING
688 * read in virtual host tables (if they exist)
691 static void
692 inithosts()
694 int insert;
695 size_t len;
696 FILE *fp;
697 char *cp, *mp, *line;
698 char *vhost, *anonuser, *statfile, *welcome, *loginmsg;
699 struct ftphost *hrp, *lhrp;
700 struct addrinfo hints, *res, *ai;
703 * Fill in the default host information
705 if (hostname == NULL) {
706 if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL)
707 fatalerror("Ran out of memory.");
708 if (gethostname(hostname, MAXHOSTNAMELEN) < 0)
709 hostname[0] = '\0';
710 hostname[MAXHOSTNAMELEN - 1] = '\0';
712 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
713 fatalerror("Ran out of memory.");
714 hrp->hostname = hostname;
715 hrp->hostinfo = NULL;
717 memset(&hints, 0, sizeof(hints));
718 hints.ai_flags = AI_CANONNAME;
719 hints.ai_family = AF_UNSPEC;
720 if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0)
721 hrp->hostinfo = res;
722 hrp->statfile = _PATH_FTPDSTATFILE;
723 hrp->welcome = _PATH_FTPWELCOME;
724 hrp->loginmsg = _PATH_FTPLOGINMESG;
725 hrp->anonuser = "ftp";
726 hrp->next = NULL;
727 thishost = firsthost = lhrp = hrp;
728 if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) {
729 int addrsize, gothost;
730 void *addr;
731 struct hostent *hp;
733 while ((line = fgetln(fp, &len)) != NULL) {
734 int i, hp_error;
736 /* skip comments */
737 if (line[0] == '#')
738 continue;
739 if (line[len - 1] == '\n') {
740 line[len - 1] = '\0';
741 mp = NULL;
742 } else {
743 if ((mp = malloc(len + 1)) == NULL)
744 fatalerror("Ran out of memory.");
745 memcpy(mp, line, len);
746 mp[len] = '\0';
747 line = mp;
749 cp = strtok(line, " \t");
750 /* skip empty lines */
751 if (cp == NULL)
752 goto nextline;
753 vhost = cp;
755 /* set defaults */
756 anonuser = "ftp";
757 statfile = _PATH_FTPDSTATFILE;
758 welcome = _PATH_FTPWELCOME;
759 loginmsg = _PATH_FTPLOGINMESG;
762 * Preparse the line so we can use its info
763 * for all the addresses associated with
764 * the virtual host name.
765 * Field 0, the virtual host name, is special:
766 * it's already parsed off and will be strdup'ed
767 * later, after we know its canonical form.
769 for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++)
770 if (*cp != '-' && (cp = strdup(cp)))
771 switch (i) {
772 case 1: /* anon user permissions */
773 anonuser = cp;
774 break;
775 case 2: /* statistics file */
776 statfile = cp;
777 break;
778 case 3: /* welcome message */
779 welcome = cp;
780 break;
781 case 4: /* login message */
782 loginmsg = cp;
783 break;
784 default: /* programming error */
785 abort();
786 /* NOTREACHED */
789 hints.ai_flags = 0;
790 hints.ai_family = AF_UNSPEC;
791 hints.ai_flags = AI_PASSIVE;
792 if (getaddrinfo(vhost, NULL, &hints, &res) != 0)
793 goto nextline;
794 for (ai = res; ai != NULL && ai->ai_addr != NULL;
795 ai = ai->ai_next) {
797 gothost = 0;
798 for (hrp = firsthost; hrp != NULL; hrp = hrp->next) {
799 struct addrinfo *hi;
801 for (hi = hrp->hostinfo; hi != NULL;
802 hi = hi->ai_next)
803 if (hi->ai_addrlen == ai->ai_addrlen &&
804 memcmp(hi->ai_addr,
805 ai->ai_addr,
806 ai->ai_addr->sa_len) == 0) {
807 gothost++;
808 break;
810 if (gothost)
811 break;
813 if (hrp == NULL) {
814 if ((hrp = malloc(sizeof(struct ftphost))) == NULL)
815 goto nextline;
816 hrp->hostname = NULL;
817 insert = 1;
818 } else {
819 if (hrp->hostinfo && hrp->hostinfo != res)
820 freeaddrinfo(hrp->hostinfo);
821 insert = 0; /* host already in the chain */
823 hrp->hostinfo = res;
826 * determine hostname to use.
827 * force defined name if there is a valid alias
828 * otherwise fallback to primary hostname
830 /* XXX: getaddrinfo() can't do alias check */
831 switch(hrp->hostinfo->ai_family) {
832 case AF_INET:
833 addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr;
834 addrsize = sizeof(struct in_addr);
835 break;
836 case AF_INET6:
837 addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr;
838 addrsize = sizeof(struct in6_addr);
839 break;
840 default:
841 /* should not reach here */
842 freeaddrinfo(hrp->hostinfo);
843 if (insert)
844 free(hrp); /*not in chain, can free*/
845 else
846 hrp->hostinfo = NULL; /*mark as blank*/
847 goto nextline;
848 /* NOTREACHED */
850 if ((hp = getipnodebyaddr(addr, addrsize,
851 hrp->hostinfo->ai_family,
852 &hp_error)) != NULL) {
853 if (strcmp(vhost, hp->h_name) != 0) {
854 if (hp->h_aliases == NULL)
855 vhost = hp->h_name;
856 else {
857 i = 0;
858 while (hp->h_aliases[i] &&
859 strcmp(vhost, hp->h_aliases[i]) != 0)
860 ++i;
861 if (hp->h_aliases[i] == NULL)
862 vhost = hp->h_name;
866 if (hrp->hostname &&
867 strcmp(hrp->hostname, vhost) != 0) {
868 free(hrp->hostname);
869 hrp->hostname = NULL;
871 if (hrp->hostname == NULL &&
872 (hrp->hostname = strdup(vhost)) == NULL) {
873 freeaddrinfo(hrp->hostinfo);
874 hrp->hostinfo = NULL; /* mark as blank */
875 if (hp)
876 freehostent(hp);
877 goto nextline;
879 hrp->anonuser = anonuser;
880 hrp->statfile = statfile;
881 hrp->welcome = welcome;
882 hrp->loginmsg = loginmsg;
883 if (insert) {
884 hrp->next = NULL;
885 lhrp->next = hrp;
886 lhrp = hrp;
888 if (hp)
889 freehostent(hp);
891 nextline:
892 if (mp)
893 free(mp);
895 (void) fclose(fp);
899 static void
900 selecthost(su)
901 union sockunion *su;
903 struct ftphost *hrp;
904 u_int16_t port;
905 #ifdef INET6
906 struct in6_addr *mapped_in6 = NULL;
907 #endif
908 struct addrinfo *hi;
910 #ifdef INET6
912 * XXX IPv4 mapped IPv6 addr consideraton,
913 * specified in rfc2373.
915 if (su->su_family == AF_INET6 &&
916 IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr))
917 mapped_in6 = &su->su_sin6.sin6_addr;
918 #endif
920 hrp = thishost = firsthost; /* default */
921 port = su->su_port;
922 su->su_port = 0;
923 while (hrp != NULL) {
924 for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) {
925 if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) {
926 thishost = hrp;
927 break;
929 #ifdef INET6
930 /* XXX IPv4 mapped IPv6 addr consideraton */
931 if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL &&
932 (memcmp(&mapped_in6->s6_addr[12],
933 &((struct sockaddr_in *)hi->ai_addr)->sin_addr,
934 sizeof(struct in_addr)) == 0)) {
935 thishost = hrp;
936 break;
938 #endif
940 hrp = hrp->next;
942 su->su_port = port;
943 /* setup static variables as appropriate */
944 hostname = thishost->hostname;
945 ftpuser = thishost->anonuser;
947 #endif
950 * Helper function for sgetpwnam().
952 static char *
953 sgetsave(s)
954 char *s;
956 char *new = malloc((unsigned) strlen(s) + 1);
958 if (new == NULL) {
959 perror_reply(421, "Local resource failure: malloc");
960 dologout(1);
961 /* NOTREACHED */
963 (void) strcpy(new, s);
964 return (new);
968 * Save the result of a getpwnam. Used for USER command, since
969 * the data returned must not be clobbered by any other command
970 * (e.g., globbing).
972 static struct passwd *
973 sgetpwnam(name)
974 char *name;
976 static struct passwd save;
977 struct passwd *p;
979 if ((p = getpwnam(name)) == NULL)
980 return (p);
981 if (save.pw_name) {
982 free(save.pw_name);
983 free(save.pw_passwd);
984 free(save.pw_gecos);
985 free(save.pw_dir);
986 free(save.pw_shell);
988 save = *p;
989 save.pw_name = sgetsave(p->pw_name);
990 save.pw_passwd = sgetsave(p->pw_passwd);
991 save.pw_gecos = sgetsave(p->pw_gecos);
992 save.pw_dir = sgetsave(p->pw_dir);
993 save.pw_shell = sgetsave(p->pw_shell);
994 return (&save);
997 static int login_attempts; /* number of failed login attempts */
998 static int askpasswd; /* had user command, ask for passwd */
999 static char curname[MAXLOGNAME]; /* current USER name */
1002 * USER command.
1003 * Sets global passwd pointer pw if named account exists and is acceptable;
1004 * sets askpasswd if a PASS command is expected. If logged in previously,
1005 * need to reset state. If name is "ftp" or "anonymous", the name is not in
1006 * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return.
1007 * If account doesn't exist, ask for passwd anyway. Otherwise, check user
1008 * requesting login privileges. Disallow anyone who does not have a standard
1009 * shell as returned by getusershell(). Disallow anyone mentioned in the file
1010 * _PATH_FTPUSERS to allow people such as root and uucp to be avoided.
1012 void
1013 user(name)
1014 char *name;
1016 char *cp, *shell;
1018 if (logged_in) {
1019 if (guest) {
1020 reply(530, "Can't change user from guest login.");
1021 return;
1022 } else if (dochroot) {
1023 reply(530, "Can't change user from chroot user.");
1024 return;
1026 end_login();
1029 guest = 0;
1030 if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) {
1031 if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL) ||
1032 checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL))
1033 reply(530, "User %s access denied.", name);
1034 #ifdef VIRTUAL_HOSTING
1035 else if ((pw = sgetpwnam(thishost->anonuser)) != NULL) {
1036 #else
1037 else if ((pw = sgetpwnam("ftp")) != NULL) {
1038 #endif
1039 guest = 1;
1040 askpasswd = 1;
1041 reply(331,
1042 "Guest login ok, send your email address as password.");
1043 } else
1044 reply(530, "User %s unknown.", name);
1045 if (!askpasswd && logging)
1046 syslog(LOG_NOTICE,
1047 "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost);
1048 return;
1050 if (anon_only != 0) {
1051 reply(530, "Sorry, only anonymous ftp allowed.");
1052 return;
1055 if ((pw = sgetpwnam(name))) {
1056 if ((shell = pw->pw_shell) == NULL || *shell == 0)
1057 shell = _PATH_BSHELL;
1058 while ((cp = getusershell()) != NULL)
1059 if (strcmp(cp, shell) == 0)
1060 break;
1061 endusershell();
1063 if (cp == NULL || checkuser(_PATH_FTPUSERS, name, 1, NULL)) {
1064 reply(530, "User %s access denied.", name);
1065 if (logging)
1066 syslog(LOG_NOTICE,
1067 "FTP LOGIN REFUSED FROM %s, %s",
1068 remotehost, name);
1069 pw = (struct passwd *) NULL;
1070 return;
1073 if (logging)
1074 strncpy(curname, name, sizeof(curname)-1);
1075 #ifdef SKEY
1076 pwok = skeyaccess(name, NULL, remotehost, remotehost);
1077 reply(331, "%s", skey_challenge(name, pw, pwok));
1078 #else
1079 reply(331, "Password required for %s.", name);
1080 #endif
1081 askpasswd = 1;
1083 * Delay before reading passwd after first failed
1084 * attempt to slow down passwd-guessing programs.
1086 if (login_attempts)
1087 sleep((unsigned) login_attempts);
1091 * Check if a user is in the file "fname",
1092 * return a pointer to a malloc'd string with the rest
1093 * of the matching line in "residue" if not NULL.
1095 static int
1096 checkuser(fname, name, pwset, residue)
1097 char *fname;
1098 char *name;
1099 int pwset;
1100 char **residue;
1102 FILE *fd;
1103 int found = 0;
1104 size_t len;
1105 char *line, *mp, *p;
1107 if ((fd = fopen(fname, "r")) != NULL) {
1108 while (!found && (line = fgetln(fd, &len)) != NULL) {
1109 /* skip comments */
1110 if (line[0] == '#')
1111 continue;
1112 if (line[len - 1] == '\n') {
1113 line[len - 1] = '\0';
1114 mp = NULL;
1115 } else {
1116 if ((mp = malloc(len + 1)) == NULL)
1117 fatalerror("Ran out of memory.");
1118 memcpy(mp, line, len);
1119 mp[len] = '\0';
1120 line = mp;
1122 /* avoid possible leading and trailing whitespace */
1123 p = strtok(line, " \t");
1124 /* skip empty lines */
1125 if (p == NULL)
1126 goto nextline;
1128 * if first chr is '@', check group membership
1130 if (p[0] == '@') {
1131 int i = 0;
1132 struct group *grp;
1134 if (p[1] == '\0') /* single @ matches anyone */
1135 found = 1;
1136 else {
1137 if ((grp = getgrnam(p+1)) == NULL)
1138 goto nextline;
1140 * Check user's default group
1142 if (pwset && grp->gr_gid == pw->pw_gid)
1143 found = 1;
1145 * Check supplementary groups
1147 while (!found && grp->gr_mem[i])
1148 found = strcmp(name,
1149 grp->gr_mem[i++])
1150 == 0;
1154 * Otherwise, just check for username match
1156 else
1157 found = strcmp(p, name) == 0;
1159 * Save the rest of line to "residue" if matched
1161 if (found && residue) {
1162 if ((p = strtok(NULL, "")) != NULL)
1163 p += strspn(p, " \t");
1164 if (p && *p) {
1165 if ((*residue = strdup(p)) == NULL)
1166 fatalerror("Ran out of memory.");
1167 } else
1168 *residue = NULL;
1170 nextline:
1171 if (mp)
1172 free(mp);
1174 (void) fclose(fd);
1176 return (found);
1180 * Terminate login as previous user, if any, resetting state;
1181 * used when USER command is given or login fails.
1183 static void
1184 end_login()
1187 (void) seteuid((uid_t)0);
1188 if (logged_in && dowtmp)
1189 ftpd_logwtmp(ttyline, "", NULL);
1190 pw = NULL;
1191 #ifdef LOGIN_CAP
1192 setusercontext(NULL, getpwuid(0), (uid_t)0,
1193 LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1194 #endif
1195 logged_in = 0;
1196 guest = 0;
1197 dochroot = 0;
1200 #if !defined(NOPAM)
1203 * the following code is stolen from imap-uw PAM authentication module and
1204 * login.c
1206 #define COPY_STRING(s) (s ? strdup(s) : NULL)
1208 struct cred_t {
1209 const char *uname; /* user name */
1210 const char *pass; /* password */
1212 typedef struct cred_t cred_t;
1214 static int
1215 auth_conv(int num_msg, const struct pam_message **msg,
1216 struct pam_response **resp, void *appdata)
1218 int i;
1219 cred_t *cred = (cred_t *) appdata;
1220 struct pam_response *reply =
1221 malloc(sizeof(struct pam_response) * num_msg);
1223 for (i = 0; i < num_msg; i++) {
1224 switch (msg[i]->msg_style) {
1225 case PAM_PROMPT_ECHO_ON: /* assume want user name */
1226 reply[i].resp_retcode = PAM_SUCCESS;
1227 reply[i].resp = COPY_STRING(cred->uname);
1228 /* PAM frees resp. */
1229 break;
1230 case PAM_PROMPT_ECHO_OFF: /* assume want password */
1231 reply[i].resp_retcode = PAM_SUCCESS;
1232 reply[i].resp = COPY_STRING(cred->pass);
1233 /* PAM frees resp. */
1234 break;
1235 case PAM_TEXT_INFO:
1236 case PAM_ERROR_MSG:
1237 reply[i].resp_retcode = PAM_SUCCESS;
1238 reply[i].resp = NULL;
1239 break;
1240 default: /* unknown message style */
1241 free(reply);
1242 return PAM_CONV_ERR;
1246 *resp = reply;
1247 return PAM_SUCCESS;
1251 * Attempt to authenticate the user using PAM. Returns 0 if the user is
1252 * authenticated, or 1 if not authenticated. If some sort of PAM system
1253 * error occurs (e.g., the "/etc/pam.conf" file is missing) then this
1254 * function returns -1. This can be used as an indication that we should
1255 * fall back to a different authentication mechanism.
1257 static int
1258 auth_pam(struct passwd **ppw, const char *pass)
1260 pam_handle_t *pamh = NULL;
1261 const char *tmpl_user;
1262 const void *item;
1263 int rval;
1264 int e;
1265 cred_t auth_cred = { (*ppw)->pw_name, pass };
1266 struct pam_conv conv = { &auth_conv, &auth_cred };
1268 e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh);
1269 if (e != PAM_SUCCESS) {
1270 syslog(LOG_ERR, "pam_start: %s", pam_strerror(pamh, e));
1271 return -1;
1274 e = pam_set_item(pamh, PAM_RHOST, remotehost);
1275 if (e != PAM_SUCCESS) {
1276 syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s",
1277 pam_strerror(pamh, e));
1278 return -1;
1281 e = pam_authenticate(pamh, 0);
1282 switch (e) {
1283 case PAM_SUCCESS:
1285 * With PAM we support the concept of a "template"
1286 * user. The user enters a login name which is
1287 * authenticated by PAM, usually via a remote service
1288 * such as RADIUS or TACACS+. If authentication
1289 * succeeds, a different but related "template" name
1290 * is used for setting the credentials, shell, and
1291 * home directory. The name the user enters need only
1292 * exist on the remote authentication server, but the
1293 * template name must be present in the local password
1294 * database.
1296 * This is supported by two various mechanisms in the
1297 * individual modules. However, from the application's
1298 * point of view, the template user is always passed
1299 * back as a changed value of the PAM_USER item.
1301 if ((e = pam_get_item(pamh, PAM_USER, &item)) ==
1302 PAM_SUCCESS) {
1303 tmpl_user = (const char *) item;
1304 if (strcmp((*ppw)->pw_name, tmpl_user) != 0)
1305 *ppw = getpwnam(tmpl_user);
1306 } else
1307 syslog(LOG_ERR, "Couldn't get PAM_USER: %s",
1308 pam_strerror(pamh, e));
1309 rval = 0;
1310 break;
1312 case PAM_AUTH_ERR:
1313 case PAM_USER_UNKNOWN:
1314 case PAM_MAXTRIES:
1315 rval = 1;
1316 break;
1318 default:
1319 syslog(LOG_ERR, "auth_pam: %s", pam_strerror(pamh, e));
1320 rval = -1;
1321 break;
1324 if ((e = pam_end(pamh, e)) != PAM_SUCCESS) {
1325 syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e));
1326 rval = -1;
1328 return rval;
1331 #endif /* !defined(NOPAM) */
1333 void
1334 pass(passwd)
1335 char *passwd;
1337 int rval;
1338 FILE *fd;
1339 #ifdef LOGIN_CAP
1340 login_cap_t *lc = NULL;
1341 #endif
1342 char *chrootdir;
1343 char *residue = NULL;
1345 if (logged_in || askpasswd == 0) {
1346 reply(503, "Login with USER first.");
1347 return;
1349 askpasswd = 0;
1350 if (!guest) { /* "ftp" is only account allowed no password */
1351 if (pw == NULL) {
1352 rval = 1; /* failure below */
1353 goto skip;
1355 #if !defined(NOPAM)
1356 rval = auth_pam(&pw, passwd);
1357 if (rval >= 0)
1358 goto skip;
1359 #endif
1360 #ifdef SKEY
1361 if (pwok)
1362 rval = strcmp(pw->pw_passwd,
1363 crypt(passwd, pw->pw_passwd));
1364 if (rval)
1365 rval = strcmp(pw->pw_passwd,
1366 skey_crypt(passwd, pw->pw_passwd, pw, pwok));
1367 #else
1368 rval = strcmp(pw->pw_passwd, crypt(passwd, pw->pw_passwd));
1369 #endif
1370 /* The strcmp does not catch null passwords! */
1371 if (*pw->pw_passwd == '\0' ||
1372 (pw->pw_expire && time(NULL) >= pw->pw_expire))
1373 rval = 1; /* failure */
1374 skip:
1376 * If rval == 1, the user failed the authentication check
1377 * above. If rval == 0, either PAM or local authentication
1378 * succeeded.
1380 if (rval) {
1381 reply(530, "Login incorrect.");
1382 if (logging) {
1383 syslog(LOG_NOTICE,
1384 "FTP LOGIN FAILED FROM %s",
1385 remotehost);
1386 syslog(LOG_AUTHPRIV | LOG_NOTICE,
1387 "FTP LOGIN FAILED FROM %s, %s",
1388 remotehost, curname);
1390 pw = NULL;
1391 if (login_attempts++ >= 5) {
1392 syslog(LOG_NOTICE,
1393 "repeated login failures from %s",
1394 remotehost);
1395 exit(0);
1397 return;
1400 #ifdef SKEY
1401 pwok = 0;
1402 #endif
1403 login_attempts = 0; /* this time successful */
1404 if (setegid((gid_t)pw->pw_gid) < 0) {
1405 reply(550, "Can't set gid.");
1406 return;
1408 /* May be overridden by login.conf */
1409 (void) umask(defumask);
1410 #ifdef LOGIN_CAP
1411 if ((lc = login_getpwclass(pw)) != NULL) {
1412 char remote_ip[MAXHOSTNAMELEN];
1414 getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
1415 remote_ip, sizeof(remote_ip) - 1, NULL, 0,
1416 NI_NUMERICHOST);
1417 remote_ip[sizeof(remote_ip) - 1] = 0;
1418 if (!auth_hostok(lc, remotehost, remote_ip)) {
1419 syslog(LOG_INFO|LOG_AUTH,
1420 "FTP LOGIN FAILED (HOST) as %s: permission denied.",
1421 pw->pw_name);
1422 reply(530, "Permission denied.\n");
1423 pw = NULL;
1424 return;
1426 if (!auth_timeok(lc, time(NULL))) {
1427 reply(530, "Login not available right now.\n");
1428 pw = NULL;
1429 return;
1432 setusercontext(lc, pw, (uid_t)0,
1433 LOGIN_SETLOGIN|LOGIN_SETGROUP|LOGIN_SETPRIORITY|
1434 LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1435 #else
1436 setlogin(pw->pw_name);
1437 (void) initgroups(pw->pw_name, pw->pw_gid);
1438 #endif
1440 /* open wtmp before chroot */
1441 if (dowtmp)
1442 ftpd_logwtmp(ttyline, pw->pw_name,
1443 (struct sockaddr *)&his_addr);
1444 logged_in = 1;
1446 if (guest && stats && statfd < 0)
1447 #ifdef VIRTUAL_HOSTING
1448 if ((statfd = open(thishost->statfile, O_WRONLY|O_APPEND)) < 0)
1449 #else
1450 if ((statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND)) < 0)
1451 #endif
1452 stats = 0;
1454 dochroot =
1455 checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue)
1456 #ifdef LOGIN_CAP /* Allow login.conf configuration as well */
1457 || login_getcapbool(lc, "ftp-chroot", 0)
1458 #endif
1460 chrootdir = NULL;
1462 * For a chrooted local user,
1463 * a) see whether ftpchroot(5) specifies a chroot directory,
1464 * b) extract the directory pathname from the line,
1465 * c) expand it to the absolute pathname if necessary.
1467 if (dochroot && residue &&
1468 (chrootdir = strtok(residue, " \t")) != NULL &&
1469 chrootdir[0] != '/') {
1470 asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir);
1471 if (chrootdir == NULL)
1472 fatalerror("Ran out of memory.");
1474 if (guest || dochroot) {
1476 * If no chroot directory set yet, use the login directory.
1477 * Copy it so it can be modified while pw->pw_dir stays intact.
1479 if (chrootdir == NULL &&
1480 (chrootdir = strdup(pw->pw_dir)) == NULL)
1481 fatalerror("Ran out of memory.");
1483 * Check for the "/chroot/./home" syntax,
1484 * separate the chroot and home directory pathnames.
1486 if ((homedir = strstr(chrootdir, "/./")) != NULL) {
1487 *(homedir++) = '\0'; /* wipe '/' */
1488 homedir++; /* skip '.' */
1489 /* so chrootdir can be freed later */
1490 if ((homedir = strdup(homedir)) == NULL)
1491 fatalerror("Ran out of memory.");
1492 } else {
1494 * We MUST do a chdir() after the chroot. Otherwise
1495 * the old current directory will be accessible as "."
1496 * outside the new root!
1498 homedir = "/";
1501 * Finally, do chroot()
1503 if (chroot(chrootdir) < 0) {
1504 reply(550, "Can't change root.");
1505 goto bad;
1507 } else /* real user w/o chroot */
1508 homedir = pw->pw_dir;
1510 * Set euid *before* doing chdir() so
1511 * a) the user won't be carried to a directory that he couldn't reach
1512 * on his own due to no permission to upper path components,
1513 * b) NFS mounted homedirs w/restrictive permissions will be accessible
1514 * (uid 0 has no root power over NFS if not mapped explicitly.)
1516 if (seteuid((uid_t)pw->pw_uid) < 0) {
1517 reply(550, "Can't set uid.");
1518 goto bad;
1520 if (chdir(homedir) < 0) {
1521 if (guest || dochroot) {
1522 reply(550, "Can't change to base directory.");
1523 goto bad;
1524 } else {
1525 if (chdir("/") < 0) {
1526 reply(550, "Root is inaccessible.");
1527 goto bad;
1529 lreply(230, "No directory! Logging in with home=/");
1534 * Display a login message, if it exists.
1535 * N.B. reply(230,) must follow the message.
1537 #ifdef VIRTUAL_HOSTING
1538 if ((fd = fopen(thishost->loginmsg, "r")) != NULL) {
1539 #else
1540 if ((fd = fopen(_PATH_FTPLOGINMESG, "r")) != NULL) {
1541 #endif
1542 char *cp, line[LINE_MAX];
1544 while (fgets(line, sizeof(line), fd) != NULL) {
1545 if ((cp = strchr(line, '\n')) != NULL)
1546 *cp = '\0';
1547 lreply(230, "%s", line);
1549 (void) fflush(stdout);
1550 (void) fclose(fd);
1552 if (guest) {
1553 if (ident != NULL)
1554 free(ident);
1555 ident = strdup(passwd);
1556 if (ident == NULL)
1557 fatalerror("Ran out of memory.");
1559 reply(230, "Guest login ok, access restrictions apply.");
1560 #ifdef SETPROCTITLE
1561 #ifdef VIRTUAL_HOSTING
1562 if (thishost != firsthost)
1563 snprintf(proctitle, sizeof(proctitle),
1564 "%s: anonymous(%s)/%s", remotehost, hostname,
1565 passwd);
1566 else
1567 #endif
1568 snprintf(proctitle, sizeof(proctitle),
1569 "%s: anonymous/%s", remotehost, passwd);
1570 setproctitle("%s", proctitle);
1571 #endif /* SETPROCTITLE */
1572 if (logging)
1573 syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s",
1574 remotehost, passwd);
1575 } else {
1576 if (dochroot)
1577 reply(230, "User %s logged in, "
1578 "access restrictions apply.", pw->pw_name);
1579 else
1580 reply(230, "User %s logged in.", pw->pw_name);
1582 #ifdef SETPROCTITLE
1583 snprintf(proctitle, sizeof(proctitle),
1584 "%s: user/%s", remotehost, pw->pw_name);
1585 setproctitle("%s", proctitle);
1586 #endif /* SETPROCTITLE */
1587 if (logging)
1588 syslog(LOG_INFO, "FTP LOGIN FROM %s as %s",
1589 remotehost, pw->pw_name);
1591 #ifdef LOGIN_CAP
1592 login_close(lc);
1593 #endif
1594 if (chrootdir)
1595 free(chrootdir);
1596 if (residue)
1597 free(residue);
1598 return;
1599 bad:
1600 /* Forget all about it... */
1601 #ifdef LOGIN_CAP
1602 login_close(lc);
1603 #endif
1604 if (chrootdir)
1605 free(chrootdir);
1606 if (residue)
1607 free(residue);
1608 end_login();
1611 void
1612 retrieve(cmd, name)
1613 char *cmd, *name;
1615 FILE *fin, *dout;
1616 struct stat st;
1617 int (*closefunc) (FILE *);
1618 time_t start;
1620 if (cmd == 0) {
1621 fin = fopen(name, "r"), closefunc = fclose;
1622 st.st_size = 0;
1623 } else {
1624 char line[BUFSIZ];
1626 (void) snprintf(line, sizeof(line), cmd, name), name = line;
1627 fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose;
1628 st.st_size = -1;
1629 st.st_blksize = BUFSIZ;
1631 if (fin == NULL) {
1632 if (errno != 0) {
1633 perror_reply(550, name);
1634 if (cmd == 0) {
1635 LOGCMD("get", name);
1638 return;
1640 byte_count = -1;
1641 if (cmd == 0) {
1642 if (fstat(fileno(fin), &st) < 0) {
1643 perror_reply(550, name);
1644 goto done;
1646 if (!S_ISREG(st.st_mode)) {
1647 if (guest) {
1648 reply(550, "%s: not a plain file.", name);
1649 goto done;
1651 st.st_size = -1;
1652 /* st.st_blksize is set for all descriptor types */
1655 if (restart_point) {
1656 if (type == TYPE_A) {
1657 off_t i, n;
1658 int c;
1660 n = restart_point;
1661 i = 0;
1662 while (i++ < n) {
1663 if ((c=getc(fin)) == EOF) {
1664 perror_reply(550, name);
1665 goto done;
1667 if (c == '\n')
1668 i++;
1670 } else if (lseek(fileno(fin), restart_point, L_SET) < 0) {
1671 perror_reply(550, name);
1672 goto done;
1675 dout = dataconn(name, st.st_size, "w");
1676 if (dout == NULL)
1677 goto done;
1678 time(&start);
1679 send_data(fin, dout, st.st_blksize, st.st_size,
1680 restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode));
1681 if (cmd == 0 && guest && stats)
1682 logxfer(name, st.st_size, start);
1683 (void) fclose(dout);
1684 data = -1;
1685 pdata = -1;
1686 done:
1687 if (cmd == 0)
1688 LOGBYTES("get", name, byte_count);
1689 (*closefunc)(fin);
1692 void
1693 store(name, mode, unique)
1694 char *name, *mode;
1695 int unique;
1697 int fd;
1698 FILE *fout, *din;
1699 int (*closefunc) (FILE *);
1701 if (*mode == 'a') { /* APPE */
1702 if (unique) {
1703 /* Programming error */
1704 syslog(LOG_ERR, "Internal: unique flag to APPE");
1705 unique = 0;
1707 if (guest && noguestmod) {
1708 reply(550, "Appending to existing file denied");
1709 goto err;
1711 restart_point = 0; /* not affected by preceding REST */
1713 if (unique) /* STOU overrides REST */
1714 restart_point = 0;
1715 if (guest && noguestmod) {
1716 if (restart_point) { /* guest STOR w/REST */
1717 reply(550, "Modifying existing file denied");
1718 goto err;
1719 } else /* treat guest STOR as STOU */
1720 unique = 1;
1723 if (restart_point)
1724 mode = "r+"; /* so ASCII manual seek can work */
1725 if (unique) {
1726 if ((fd = guniquefd(name, &name)) < 0)
1727 goto err;
1728 fout = fdopen(fd, mode);
1729 } else
1730 fout = fopen(name, mode);
1731 closefunc = fclose;
1732 if (fout == NULL) {
1733 perror_reply(553, name);
1734 goto err;
1736 byte_count = -1;
1737 if (restart_point) {
1738 if (type == TYPE_A) {
1739 off_t i, n;
1740 int c;
1742 n = restart_point;
1743 i = 0;
1744 while (i++ < n) {
1745 if ((c=getc(fout)) == EOF) {
1746 perror_reply(550, name);
1747 goto done;
1749 if (c == '\n')
1750 i++;
1753 * We must do this seek to "current" position
1754 * because we are changing from reading to
1755 * writing.
1757 if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
1758 perror_reply(550, name);
1759 goto done;
1761 } else if (lseek(fileno(fout), restart_point, L_SET) < 0) {
1762 perror_reply(550, name);
1763 goto done;
1766 din = dataconn(name, (off_t)-1, "r");
1767 if (din == NULL)
1768 goto done;
1769 if (receive_data(din, fout) == 0) {
1770 if (unique)
1771 reply(226, "Transfer complete (unique file name:%s).",
1772 name);
1773 else
1774 reply(226, "Transfer complete.");
1776 (void) fclose(din);
1777 data = -1;
1778 pdata = -1;
1779 done:
1780 LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count);
1781 (*closefunc)(fout);
1782 return;
1783 err:
1784 LOGCMD(*mode == 'a' ? "append" : "put" , name);
1785 return;
1788 static FILE *
1789 getdatasock(mode)
1790 char *mode;
1792 int on = 1, s, t, tries;
1794 if (data >= 0)
1795 return (fdopen(data, mode));
1797 s = socket(data_dest.su_family, SOCK_STREAM, 0);
1798 if (s < 0)
1799 goto bad;
1800 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
1801 syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m");
1802 /* anchor socket to avoid multi-homing problems */
1803 data_source = ctrl_addr;
1804 data_source.su_port = htons(dataport);
1805 (void) seteuid((uid_t)0);
1806 for (tries = 1; ; tries++) {
1807 if (bind(s, (struct sockaddr *)&data_source,
1808 data_source.su_len) >= 0)
1809 break;
1810 if (errno != EADDRINUSE || tries > 10)
1811 goto bad;
1812 sleep(tries);
1814 (void) seteuid((uid_t)pw->pw_uid);
1815 #ifdef IP_TOS
1816 if (data_source.su_family == AF_INET)
1818 on = IPTOS_THROUGHPUT;
1819 if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0)
1820 syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m");
1822 #endif
1823 #ifdef TCP_NOPUSH
1825 * Turn off push flag to keep sender TCP from sending short packets
1826 * at the boundaries of each write(). Should probably do a SO_SNDBUF
1827 * to set the send buffer size as well, but that may not be desirable
1828 * in heavy-load situations.
1830 on = 1;
1831 if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0)
1832 syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m");
1833 #endif
1834 #ifdef SO_SNDBUF
1835 on = 65536;
1836 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &on, sizeof on) < 0)
1837 syslog(LOG_WARNING, "data setsockopt (SO_SNDBUF): %m");
1838 #endif
1840 return (fdopen(s, mode));
1841 bad:
1842 /* Return the real value of errno (close may change it) */
1843 t = errno;
1844 (void) seteuid((uid_t)pw->pw_uid);
1845 (void) close(s);
1846 errno = t;
1847 return (NULL);
1850 static FILE *
1851 dataconn(name, size, mode)
1852 char *name;
1853 off_t size;
1854 char *mode;
1856 char sizebuf[32];
1857 FILE *file;
1858 int retry = 0, tos, conerrno;
1860 file_size = size;
1861 byte_count = 0;
1862 if (size != (off_t) -1)
1863 (void) snprintf(sizebuf, sizeof(sizebuf), " (%qd bytes)", size);
1864 else
1865 *sizebuf = '\0';
1866 if (pdata >= 0) {
1867 union sockunion from;
1868 int flags;
1869 int s, fromlen = ctrl_addr.su_len;
1870 struct timeval timeout;
1871 fd_set set;
1873 FD_ZERO(&set);
1874 FD_SET(pdata, &set);
1876 timeout.tv_usec = 0;
1877 timeout.tv_sec = 120;
1880 * Granted a socket is in the blocking I/O mode,
1881 * accept() will block after a successful select()
1882 * if the selected connection dies in between.
1883 * Therefore set the non-blocking I/O flag here.
1885 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1886 fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1)
1887 goto pdata_err;
1888 if (select(pdata+1, &set, (fd_set *) 0, (fd_set *) 0, &timeout) <= 0 ||
1889 (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0)
1890 goto pdata_err;
1891 (void) close(pdata);
1892 pdata = s;
1894 * Unset the inherited non-blocking I/O flag
1895 * on the child socket so stdio can work on it.
1897 if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 ||
1898 fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1)
1899 goto pdata_err;
1900 #ifdef IP_TOS
1901 if (from.su_family == AF_INET)
1903 tos = IPTOS_THROUGHPUT;
1904 if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
1905 syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m");
1907 #endif
1908 reply(150, "Opening %s mode data connection for '%s'%s.",
1909 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1910 return (fdopen(pdata, mode));
1911 pdata_err:
1912 reply(425, "Can't open data connection.");
1913 (void) close(pdata);
1914 pdata = -1;
1915 return (NULL);
1917 if (data >= 0) {
1918 reply(125, "Using existing data connection for '%s'%s.",
1919 name, sizebuf);
1920 usedefault = 1;
1921 return (fdopen(data, mode));
1923 if (usedefault)
1924 data_dest = his_addr;
1925 usedefault = 1;
1926 do {
1927 file = getdatasock(mode);
1928 if (file == NULL) {
1929 char hostbuf[BUFSIZ], portbuf[BUFSIZ];
1930 getnameinfo((struct sockaddr *)&data_source,
1931 data_source.su_len, hostbuf, sizeof(hostbuf) - 1,
1932 portbuf, sizeof(portbuf),
1933 NI_NUMERICHOST|NI_NUMERICSERV);
1934 reply(425, "Can't create data socket (%s,%s): %s.",
1935 hostbuf, portbuf, strerror(errno));
1936 return (NULL);
1938 data = fileno(file);
1939 conerrno = 0;
1940 if (connect(data, (struct sockaddr *)&data_dest,
1941 data_dest.su_len) == 0)
1942 break;
1943 conerrno = errno;
1944 (void) fclose(file);
1945 data = -1;
1946 if (conerrno == EADDRINUSE) {
1947 sleep((unsigned) swaitint);
1948 retry += swaitint;
1949 } else {
1950 break;
1952 } while (retry <= swaitmax);
1953 if (conerrno != 0) {
1954 perror_reply(425, "Can't build data connection");
1955 return (NULL);
1957 reply(150, "Opening %s mode data connection for '%s'%s.",
1958 type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
1959 return (file);
1963 * Tranfer the contents of "instr" to "outstr" peer using the appropriate
1964 * encapsulation of the data subject to Mode, Structure, and Type.
1966 * NB: Form isn't handled.
1968 static int
1969 send_data(instr, outstr, blksize, filesize, isreg)
1970 FILE *instr, *outstr;
1971 off_t blksize;
1972 off_t filesize;
1973 int isreg;
1975 int c, filefd, netfd;
1976 char *buf;
1977 off_t cnt;
1979 transflag++;
1980 switch (type) {
1982 case TYPE_A:
1983 while ((c = getc(instr)) != EOF) {
1984 if (recvurg)
1985 goto got_oob;
1986 byte_count++;
1987 if (c == '\n') {
1988 if (ferror(outstr))
1989 goto data_err;
1990 (void) putc('\r', outstr);
1992 (void) putc(c, outstr);
1994 if (recvurg)
1995 goto got_oob;
1996 fflush(outstr);
1997 transflag = 0;
1998 if (ferror(instr))
1999 goto file_err;
2000 if (ferror(outstr))
2001 goto data_err;
2002 reply(226, "Transfer complete.");
2003 return (0);
2005 case TYPE_I:
2006 case TYPE_L:
2008 * isreg is only set if we are not doing restart and we
2009 * are sending a regular file
2011 netfd = fileno(outstr);
2012 filefd = fileno(instr);
2014 if (isreg) {
2016 off_t offset;
2017 int err;
2019 err = cnt = offset = 0;
2021 while (err != -1 && filesize > 0) {
2022 err = sendfile(filefd, netfd, offset, 0,
2023 (struct sf_hdtr *) NULL, &cnt, 0);
2025 * Calculate byte_count before OOB processing.
2026 * It can be used in myoob() later.
2028 byte_count += cnt;
2029 if (recvurg)
2030 goto got_oob;
2031 offset += cnt;
2032 filesize -= cnt;
2034 if (err == -1) {
2035 if (!cnt)
2036 goto oldway;
2038 goto data_err;
2042 transflag = 0;
2043 reply(226, "Transfer complete.");
2044 return (0);
2047 oldway:
2048 if ((buf = malloc((u_int)blksize)) == NULL) {
2049 transflag = 0;
2050 perror_reply(451, "Local resource failure: malloc");
2051 return (-1);
2054 while ((cnt = read(filefd, buf, (u_int)blksize)) > 0 &&
2055 write(netfd, buf, cnt) == cnt)
2056 byte_count += cnt;
2057 transflag = 0;
2058 (void)free(buf);
2059 if (cnt != 0) {
2060 if (cnt < 0)
2061 goto file_err;
2062 goto data_err;
2064 reply(226, "Transfer complete.");
2065 return (0);
2066 default:
2067 transflag = 0;
2068 reply(550, "Unimplemented TYPE %d in send_data", type);
2069 return (-1);
2072 data_err:
2073 transflag = 0;
2074 perror_reply(426, "Data connection");
2075 return (-1);
2077 file_err:
2078 transflag = 0;
2079 perror_reply(551, "Error on input file");
2080 return (-1);
2082 got_oob:
2083 myoob();
2084 recvurg = 0;
2085 transflag = 0;
2086 return (-1);
2090 * Transfer data from peer to "outstr" using the appropriate encapulation of
2091 * the data subject to Mode, Structure, and Type.
2093 * N.B.: Form isn't handled.
2095 static int
2096 receive_data(instr, outstr)
2097 FILE *instr, *outstr;
2099 int c;
2100 int cnt, bare_lfs;
2101 char buf[BUFSIZ];
2103 transflag++;
2104 bare_lfs = 0;
2106 switch (type) {
2108 case TYPE_I:
2109 case TYPE_L:
2110 while ((cnt = read(fileno(instr), buf, sizeof(buf))) > 0) {
2111 if (recvurg)
2112 goto got_oob;
2113 if (write(fileno(outstr), buf, cnt) != cnt)
2114 goto file_err;
2115 byte_count += cnt;
2117 if (recvurg)
2118 goto got_oob;
2119 if (cnt < 0)
2120 goto data_err;
2121 transflag = 0;
2122 return (0);
2124 case TYPE_E:
2125 reply(553, "TYPE E not implemented.");
2126 transflag = 0;
2127 return (-1);
2129 case TYPE_A:
2130 while ((c = getc(instr)) != EOF) {
2131 if (recvurg)
2132 goto got_oob;
2133 byte_count++;
2134 if (c == '\n')
2135 bare_lfs++;
2136 while (c == '\r') {
2137 if (ferror(outstr))
2138 goto data_err;
2139 if ((c = getc(instr)) != '\n') {
2140 (void) putc ('\r', outstr);
2141 if (c == '\0' || c == EOF)
2142 goto contin2;
2145 (void) putc(c, outstr);
2146 contin2: ;
2148 if (recvurg)
2149 goto got_oob;
2150 fflush(outstr);
2151 if (ferror(instr))
2152 goto data_err;
2153 if (ferror(outstr))
2154 goto file_err;
2155 transflag = 0;
2156 if (bare_lfs) {
2157 lreply(226,
2158 "WARNING! %d bare linefeeds received in ASCII mode",
2159 bare_lfs);
2160 (void)printf(" File may not have transferred correctly.\r\n");
2162 return (0);
2163 default:
2164 reply(550, "Unimplemented TYPE %d in receive_data", type);
2165 transflag = 0;
2166 return (-1);
2169 data_err:
2170 transflag = 0;
2171 perror_reply(426, "Data Connection");
2172 return (-1);
2174 file_err:
2175 transflag = 0;
2176 perror_reply(452, "Error writing file");
2177 return (-1);
2179 got_oob:
2180 myoob();
2181 recvurg = 0;
2182 transflag = 0;
2183 return (-1);
2186 void
2187 statfilecmd(filename)
2188 char *filename;
2190 FILE *fin;
2191 int atstart;
2192 int c;
2193 char line[LINE_MAX];
2195 (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename);
2196 fin = ftpd_popen(line, "r");
2197 lreply(211, "status of %s:", filename);
2198 atstart = 1;
2199 while ((c = getc(fin)) != EOF) {
2200 if (c == '\n') {
2201 if (ferror(stdout)){
2202 perror_reply(421, "control connection");
2203 (void) ftpd_pclose(fin);
2204 dologout(1);
2205 /* NOTREACHED */
2207 if (ferror(fin)) {
2208 perror_reply(551, filename);
2209 (void) ftpd_pclose(fin);
2210 return;
2212 (void) putc('\r', stdout);
2215 * RFC 959 says neutral text should be prepended before
2216 * a leading 3-digit number followed by whitespace, but
2217 * many ftp clients can be confused by any leading digits,
2218 * as a matter of fact.
2220 if (atstart && isdigit(c))
2221 (void) putc(' ', stdout);
2222 (void) putc(c, stdout);
2223 atstart = (c == '\n');
2225 (void) ftpd_pclose(fin);
2226 reply(211, "End of Status");
2229 void
2230 statcmd()
2232 union sockunion *su;
2233 u_char *a, *p;
2234 char hname[NI_MAXHOST];
2235 int ispassive;
2237 if (hostinfo) {
2238 lreply(211, "%s FTP server status:", hostname);
2239 printf(" %s\r\n", version);
2240 } else
2241 lreply(211, "FTP server status:");
2242 printf(" Connected to %s", remotehost);
2243 if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len,
2244 hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) {
2245 if (strcmp(hname, remotehost) != 0)
2246 printf(" (%s)", hname);
2248 printf("\r\n");
2249 if (logged_in) {
2250 if (guest)
2251 printf(" Logged in anonymously\r\n");
2252 else
2253 printf(" Logged in as %s\r\n", pw->pw_name);
2254 } else if (askpasswd)
2255 printf(" Waiting for password\r\n");
2256 else
2257 printf(" Waiting for user name\r\n");
2258 printf(" TYPE: %s", typenames[type]);
2259 if (type == TYPE_A || type == TYPE_E)
2260 printf(", FORM: %s", formnames[form]);
2261 if (type == TYPE_L)
2262 #if NBBY == 8
2263 printf(" %d", NBBY);
2264 #else
2265 printf(" %d", bytesize); /* need definition! */
2266 #endif
2267 printf("; STRUcture: %s; transfer MODE: %s\r\n",
2268 strunames[stru], modenames[mode]);
2269 if (data != -1)
2270 printf(" Data connection open\r\n");
2271 else if (pdata != -1) {
2272 ispassive = 1;
2273 su = &pasv_addr;
2274 goto printaddr;
2275 } else if (usedefault == 0) {
2276 ispassive = 0;
2277 su = &data_dest;
2278 printaddr:
2279 #define UC(b) (((int) b) & 0xff)
2280 if (epsvall) {
2281 printf(" EPSV only mode (EPSV ALL)\r\n");
2282 goto epsvonly;
2285 /* PORT/PASV */
2286 if (su->su_family == AF_INET) {
2287 a = (u_char *) &su->su_sin.sin_addr;
2288 p = (u_char *) &su->su_sin.sin_port;
2289 printf(" %s (%d,%d,%d,%d,%d,%d)\r\n",
2290 ispassive ? "PASV" : "PORT",
2291 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2292 UC(p[0]), UC(p[1]));
2295 /* LPRT/LPSV */
2297 int alen, af, i;
2299 switch (su->su_family) {
2300 case AF_INET:
2301 a = (u_char *) &su->su_sin.sin_addr;
2302 p = (u_char *) &su->su_sin.sin_port;
2303 alen = sizeof(su->su_sin.sin_addr);
2304 af = 4;
2305 break;
2306 case AF_INET6:
2307 a = (u_char *) &su->su_sin6.sin6_addr;
2308 p = (u_char *) &su->su_sin6.sin6_port;
2309 alen = sizeof(su->su_sin6.sin6_addr);
2310 af = 6;
2311 break;
2312 default:
2313 af = 0;
2314 break;
2316 if (af) {
2317 printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT",
2318 af, alen);
2319 for (i = 0; i < alen; i++)
2320 printf("%d,", UC(a[i]));
2321 printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1]));
2325 epsvonly:;
2326 /* EPRT/EPSV */
2328 int af;
2330 switch (su->su_family) {
2331 case AF_INET:
2332 af = 1;
2333 break;
2334 case AF_INET6:
2335 af = 2;
2336 break;
2337 default:
2338 af = 0;
2339 break;
2341 if (af) {
2342 union sockunion tmp;
2344 tmp = *su;
2345 if (tmp.su_family == AF_INET6)
2346 tmp.su_sin6.sin6_scope_id = 0;
2347 if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len,
2348 hname, sizeof(hname) - 1, NULL, 0,
2349 NI_NUMERICHOST)) {
2350 printf(" %s |%d|%s|%d|\r\n",
2351 ispassive ? "EPSV" : "EPRT",
2352 af, hname, htons(tmp.su_port));
2356 #undef UC
2357 } else
2358 printf(" No data connection\r\n");
2359 reply(211, "End of status");
2362 void
2363 fatalerror(s)
2364 char *s;
2367 reply(451, "Error in server: %s\n", s);
2368 reply(221, "Closing connection due to server error.");
2369 dologout(0);
2370 /* NOTREACHED */
2373 void
2374 #if __STDC__
2375 reply(int n, const char *fmt, ...)
2376 #else
2377 reply(n, fmt, va_alist)
2378 int n;
2379 char *fmt;
2380 va_dcl
2381 #endif
2383 va_list ap;
2384 #if __STDC__
2385 va_start(ap, fmt);
2386 #else
2387 va_start(ap);
2388 #endif
2389 (void)printf("%d ", n);
2390 (void)vprintf(fmt, ap);
2391 (void)printf("\r\n");
2392 (void)fflush(stdout);
2393 if (ftpdebug) {
2394 syslog(LOG_DEBUG, "<--- %d ", n);
2395 vsyslog(LOG_DEBUG, fmt, ap);
2399 void
2400 #if __STDC__
2401 lreply(int n, const char *fmt, ...)
2402 #else
2403 lreply(n, fmt, va_alist)
2404 int n;
2405 char *fmt;
2406 va_dcl
2407 #endif
2409 va_list ap;
2410 #if __STDC__
2411 va_start(ap, fmt);
2412 #else
2413 va_start(ap);
2414 #endif
2415 (void)printf("%d- ", n);
2416 (void)vprintf(fmt, ap);
2417 (void)printf("\r\n");
2418 (void)fflush(stdout);
2419 if (ftpdebug) {
2420 syslog(LOG_DEBUG, "<--- %d- ", n);
2421 vsyslog(LOG_DEBUG, fmt, ap);
2425 static void
2426 ack(s)
2427 char *s;
2430 reply(250, "%s command successful.", s);
2433 void
2434 nack(s)
2435 char *s;
2438 reply(502, "%s command not implemented.", s);
2441 /* ARGSUSED */
2442 void
2443 yyerror(s)
2444 char *s;
2446 char *cp;
2448 if ((cp = strchr(cbuf,'\n')))
2449 *cp = '\0';
2450 reply(500, "'%s': command not understood.", cbuf);
2453 void
2454 delete(name)
2455 char *name;
2457 struct stat st;
2459 LOGCMD("delete", name);
2460 if (lstat(name, &st) < 0) {
2461 perror_reply(550, name);
2462 return;
2464 if ((st.st_mode&S_IFMT) == S_IFDIR) {
2465 if (rmdir(name) < 0) {
2466 perror_reply(550, name);
2467 return;
2469 goto done;
2471 if (unlink(name) < 0) {
2472 perror_reply(550, name);
2473 return;
2475 done:
2476 ack("DELE");
2479 void
2480 cwd(path)
2481 char *path;
2484 if (chdir(path) < 0)
2485 perror_reply(550, path);
2486 else
2487 ack("CWD");
2490 void
2491 makedir(name)
2492 char *name;
2494 char *s;
2496 LOGCMD("mkdir", name);
2497 if (guest && noguestmkd)
2498 reply(550, "%s: permission denied", name);
2499 else if (mkdir(name, 0777) < 0)
2500 perror_reply(550, name);
2501 else {
2502 if ((s = doublequote(name)) == NULL)
2503 fatalerror("Ran out of memory.");
2504 reply(257, "\"%s\" directory created.", s);
2505 free(s);
2509 void
2510 removedir(name)
2511 char *name;
2514 LOGCMD("rmdir", name);
2515 if (rmdir(name) < 0)
2516 perror_reply(550, name);
2517 else
2518 ack("RMD");
2521 void
2522 pwd()
2524 char *s, path[MAXPATHLEN + 1];
2526 if (getwd(path) == (char *)NULL)
2527 reply(550, "%s.", path);
2528 else {
2529 if ((s = doublequote(path)) == NULL)
2530 fatalerror("Ran out of memory.");
2531 reply(257, "\"%s\" is current directory.", s);
2532 free(s);
2536 char *
2537 renamefrom(name)
2538 char *name;
2540 struct stat st;
2542 if (lstat(name, &st) < 0) {
2543 perror_reply(550, name);
2544 return ((char *)0);
2546 reply(350, "File exists, ready for destination name");
2547 return (name);
2550 void
2551 renamecmd(from, to)
2552 char *from, *to;
2554 struct stat st;
2556 LOGCMD2("rename", from, to);
2558 if (guest && (stat(to, &st) == 0)) {
2559 reply(550, "%s: permission denied", to);
2560 return;
2563 if (rename(from, to) < 0)
2564 perror_reply(550, "rename");
2565 else
2566 ack("RNTO");
2569 static void
2570 dolog(who)
2571 struct sockaddr *who;
2573 int error;
2575 realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len);
2577 #ifdef SETPROCTITLE
2578 #ifdef VIRTUAL_HOSTING
2579 if (thishost != firsthost)
2580 snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)",
2581 remotehost, hostname);
2582 else
2583 #endif
2584 snprintf(proctitle, sizeof(proctitle), "%s: connected",
2585 remotehost);
2586 setproctitle("%s", proctitle);
2587 #endif /* SETPROCTITLE */
2589 if (logging) {
2590 #ifdef VIRTUAL_HOSTING
2591 if (thishost != firsthost)
2592 syslog(LOG_INFO, "connection from %s (to %s)",
2593 remotehost, hostname);
2594 else
2595 #endif
2597 char who_name[MAXHOSTNAMELEN];
2599 error = getnameinfo(who, who->sa_len,
2600 who_name, sizeof(who_name) - 1,
2601 NULL, 0, NI_NUMERICHOST);
2602 syslog(LOG_INFO, "connection from %s (%s)", remotehost,
2603 error == 0 ? who_name : "");
2609 * Record logout in wtmp file
2610 * and exit with supplied status.
2612 void
2613 dologout(status)
2614 int status;
2617 * Prevent reception of SIGURG from resulting in a resumption
2618 * back to the main program loop.
2620 transflag = 0;
2622 if (logged_in && dowtmp) {
2623 (void) seteuid((uid_t)0);
2624 ftpd_logwtmp(ttyline, "", NULL);
2626 /* beware of flushing buffers after a SIGPIPE */
2627 _exit(status);
2630 static void
2631 sigurg(signo)
2632 int signo;
2635 recvurg = 1;
2638 static void
2639 myoob()
2641 char *cp;
2643 /* only process if transfer occurring */
2644 if (!transflag)
2645 return;
2646 cp = tmpline;
2647 if (getline(cp, 7, stdin) == NULL) {
2648 reply(221, "You could at least say goodbye.");
2649 dologout(0);
2651 upper(cp);
2652 if (strcmp(cp, "ABOR\r\n") == 0) {
2653 tmpline[0] = '\0';
2654 reply(426, "Transfer aborted. Data connection closed.");
2655 reply(226, "Abort successful");
2657 if (strcmp(cp, "STAT\r\n") == 0) {
2658 tmpline[0] = '\0';
2659 if (file_size != (off_t) -1)
2660 reply(213, "Status: %qd of %qd bytes transferred",
2661 byte_count, file_size);
2662 else
2663 reply(213, "Status: %qd bytes transferred", byte_count);
2668 * Note: a response of 425 is not mentioned as a possible response to
2669 * the PASV command in RFC959. However, it has been blessed as
2670 * a legitimate response by Jon Postel in a telephone conversation
2671 * with Rick Adams on 25 Jan 89.
2673 void
2674 passive()
2676 int len, on;
2677 char *p, *a;
2679 if (pdata >= 0) /* close old port if one set */
2680 close(pdata);
2682 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2683 if (pdata < 0) {
2684 perror_reply(425, "Can't open passive connection");
2685 return;
2687 on = 1;
2688 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2689 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2691 (void) seteuid((uid_t)0);
2693 #ifdef IP_PORTRANGE
2694 if (ctrl_addr.su_family == AF_INET) {
2695 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2696 : IP_PORTRANGE_DEFAULT;
2698 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2699 &on, sizeof(on)) < 0)
2700 goto pasv_error;
2702 #endif
2703 #ifdef IPV6_PORTRANGE
2704 if (ctrl_addr.su_family == AF_INET6) {
2705 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2706 : IPV6_PORTRANGE_DEFAULT;
2708 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2709 &on, sizeof(on)) < 0)
2710 goto pasv_error;
2712 #endif
2714 pasv_addr = ctrl_addr;
2715 pasv_addr.su_port = 0;
2716 if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0)
2717 goto pasv_error;
2719 (void) seteuid((uid_t)pw->pw_uid);
2721 len = sizeof(pasv_addr);
2722 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2723 goto pasv_error;
2724 if (listen(pdata, 1) < 0)
2725 goto pasv_error;
2726 if (pasv_addr.su_family == AF_INET)
2727 a = (char *) &pasv_addr.su_sin.sin_addr;
2728 else if (pasv_addr.su_family == AF_INET6 &&
2729 IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr))
2730 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2731 else
2732 goto pasv_error;
2734 p = (char *) &pasv_addr.su_port;
2736 #define UC(b) (((int) b) & 0xff)
2738 reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]),
2739 UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1]));
2740 return;
2742 pasv_error:
2743 (void) seteuid((uid_t)pw->pw_uid);
2744 (void) close(pdata);
2745 pdata = -1;
2746 perror_reply(425, "Can't open passive connection");
2747 return;
2751 * Long Passive defined in RFC 1639.
2752 * 228 Entering Long Passive Mode
2753 * (af, hal, h1, h2, h3,..., pal, p1, p2...)
2756 void
2757 long_passive(cmd, pf)
2758 char *cmd;
2759 int pf;
2761 int len, on;
2762 char *p, *a;
2764 if (pdata >= 0) /* close old port if one set */
2765 close(pdata);
2767 if (pf != PF_UNSPEC) {
2768 if (ctrl_addr.su_family != pf) {
2769 switch (ctrl_addr.su_family) {
2770 case AF_INET:
2771 pf = 1;
2772 break;
2773 case AF_INET6:
2774 pf = 2;
2775 break;
2776 default:
2777 pf = 0;
2778 break;
2781 * XXX
2782 * only EPRT/EPSV ready clients will understand this
2784 if (strcmp(cmd, "EPSV") == 0 && pf) {
2785 reply(522, "Network protocol mismatch, "
2786 "use (%d)", pf);
2787 } else
2788 reply(501, "Network protocol mismatch"); /*XXX*/
2790 return;
2794 pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0);
2795 if (pdata < 0) {
2796 perror_reply(425, "Can't open passive connection");
2797 return;
2799 on = 1;
2800 if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
2801 syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m");
2803 (void) seteuid((uid_t)0);
2805 pasv_addr = ctrl_addr;
2806 pasv_addr.su_port = 0;
2807 len = pasv_addr.su_len;
2809 #ifdef IP_PORTRANGE
2810 if (ctrl_addr.su_family == AF_INET) {
2811 on = restricted_data_ports ? IP_PORTRANGE_HIGH
2812 : IP_PORTRANGE_DEFAULT;
2814 if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE,
2815 &on, sizeof(on)) < 0)
2816 goto pasv_error;
2818 #endif
2819 #ifdef IPV6_PORTRANGE
2820 if (ctrl_addr.su_family == AF_INET6) {
2821 on = restricted_data_ports ? IPV6_PORTRANGE_HIGH
2822 : IPV6_PORTRANGE_DEFAULT;
2824 if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE,
2825 &on, sizeof(on)) < 0)
2826 goto pasv_error;
2828 #endif
2830 if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0)
2831 goto pasv_error;
2833 (void) seteuid((uid_t)pw->pw_uid);
2835 if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0)
2836 goto pasv_error;
2837 if (listen(pdata, 1) < 0)
2838 goto pasv_error;
2840 #define UC(b) (((int) b) & 0xff)
2842 if (strcmp(cmd, "LPSV") == 0) {
2843 p = (char *)&pasv_addr.su_port;
2844 switch (pasv_addr.su_family) {
2845 case AF_INET:
2846 a = (char *) &pasv_addr.su_sin.sin_addr;
2847 v4_reply:
2848 reply(228,
2849 "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2850 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2851 2, UC(p[0]), UC(p[1]));
2852 return;
2853 case AF_INET6:
2854 if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) {
2855 a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12];
2856 goto v4_reply;
2858 a = (char *) &pasv_addr.su_sin6.sin6_addr;
2859 reply(228,
2860 "Entering Long Passive Mode "
2861 "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)",
2862 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
2863 UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]),
2864 UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]),
2865 UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]),
2866 2, UC(p[0]), UC(p[1]));
2867 return;
2869 } else if (strcmp(cmd, "EPSV") == 0) {
2870 switch (pasv_addr.su_family) {
2871 case AF_INET:
2872 case AF_INET6:
2873 reply(229, "Entering Extended Passive Mode (|||%d|)",
2874 ntohs(pasv_addr.su_port));
2875 return;
2877 } else {
2878 /* more proper error code? */
2881 pasv_error:
2882 (void) seteuid((uid_t)pw->pw_uid);
2883 (void) close(pdata);
2884 pdata = -1;
2885 perror_reply(425, "Can't open passive connection");
2886 return;
2890 * Generate unique name for file with basename "local"
2891 * and open the file in order to avoid possible races.
2892 * Try "local" first, then "local.1", "local.2" etc, up to "local.99".
2893 * Return descriptor to the file, set "name" to its name.
2895 * Generates failure reply on error.
2897 static int
2898 guniquefd(local, name)
2899 char *local;
2900 char **name;
2902 static char new[MAXPATHLEN];
2903 struct stat st;
2904 char *cp;
2905 int count;
2906 int fd;
2908 cp = strrchr(local, '/');
2909 if (cp)
2910 *cp = '\0';
2911 if (stat(cp ? local : ".", &st) < 0) {
2912 perror_reply(553, cp ? local : ".");
2913 return (-1);
2915 if (cp) {
2917 * Let not overwrite dirname with counter suffix.
2918 * -4 is for /nn\0
2919 * In this extreme case dot won't be put in front of suffix.
2921 if (strlen(local) > sizeof(new) - 4) {
2922 reply(553, "Pathname too long");
2923 return (-1);
2925 *cp = '/';
2927 /* -4 is for the .nn<null> we put on the end below */
2928 (void) snprintf(new, sizeof(new) - 4, "%s", local);
2929 cp = new + strlen(new);
2931 * Don't generate dotfile unless requested explicitly.
2932 * This covers the case when basename gets truncated off
2933 * by buffer size.
2935 if (cp > new && cp[-1] != '/')
2936 *cp++ = '.';
2937 for (count = 0; count < 100; count++) {
2938 /* At count 0 try unmodified name */
2939 if (count)
2940 (void)sprintf(cp, "%d", count);
2941 if ((fd = open(count ? new : local,
2942 O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) {
2943 *name = count ? new : local;
2944 return (fd);
2946 if (errno != EEXIST) {
2947 perror_reply(553, count ? new : local);
2948 return (-1);
2951 reply(452, "Unique file name cannot be created.");
2952 return (-1);
2956 * Format and send reply containing system error number.
2958 void
2959 perror_reply(code, string)
2960 int code;
2961 char *string;
2964 reply(code, "%s: %s.", string, strerror(errno));
2967 static char *onefile[] = {
2972 void
2973 send_file_list(whichf)
2974 char *whichf;
2976 struct stat st;
2977 DIR *dirp = NULL;
2978 struct dirent *dir;
2979 FILE *dout = NULL;
2980 char **dirlist, *dirname;
2981 int simple = 0;
2982 int freeglob = 0;
2983 glob_t gl;
2985 if (strpbrk(whichf, "~{[*?") != NULL) {
2986 int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_QUOTE|GLOB_TILDE;
2988 memset(&gl, 0, sizeof(gl));
2989 gl.gl_matchc = MAXGLOBARGS;
2990 flags |= GLOB_LIMIT;
2991 freeglob = 1;
2992 if (glob(whichf, flags, 0, &gl)) {
2993 reply(550, "not found");
2994 goto out;
2995 } else if (gl.gl_pathc == 0) {
2996 errno = ENOENT;
2997 perror_reply(550, whichf);
2998 goto out;
3000 dirlist = gl.gl_pathv;
3001 } else {
3002 onefile[0] = whichf;
3003 dirlist = onefile;
3004 simple = 1;
3007 while ((dirname = *dirlist++)) {
3008 if (stat(dirname, &st) < 0) {
3010 * If user typed "ls -l", etc, and the client
3011 * used NLST, do what the user meant.
3013 if (dirname[0] == '-' && *dirlist == NULL &&
3014 transflag == 0) {
3015 retrieve(_PATH_LS " %s", dirname);
3016 goto out;
3018 perror_reply(550, whichf);
3019 if (dout != NULL) {
3020 (void) fclose(dout);
3021 transflag = 0;
3022 data = -1;
3023 pdata = -1;
3025 goto out;
3028 if (S_ISREG(st.st_mode)) {
3029 if (dout == NULL) {
3030 dout = dataconn("file list", (off_t)-1, "w");
3031 if (dout == NULL)
3032 goto out;
3033 transflag++;
3035 fprintf(dout, "%s%s\n", dirname,
3036 type == TYPE_A ? "\r" : "");
3037 byte_count += strlen(dirname) + 1;
3038 continue;
3039 } else if (!S_ISDIR(st.st_mode))
3040 continue;
3042 if ((dirp = opendir(dirname)) == NULL)
3043 continue;
3045 while ((dir = readdir(dirp)) != NULL) {
3046 char nbuf[MAXPATHLEN];
3048 if (recvurg) {
3049 myoob();
3050 recvurg = 0;
3051 transflag = 0;
3052 goto out;
3055 if (strcmp(dir->d_name, ".") == 0)
3056 continue;
3057 if (strcmp(dir->d_name, "..") == 0)
3058 continue;
3060 snprintf(nbuf, sizeof(nbuf),
3061 "%s/%s", dirname, dir->d_name);
3064 * We have to do a stat to insure it's
3065 * not a directory or special file.
3067 if (simple || (stat(nbuf, &st) == 0 &&
3068 S_ISREG(st.st_mode))) {
3069 if (dout == NULL) {
3070 dout = dataconn("file list", (off_t)-1,
3071 "w");
3072 if (dout == NULL)
3073 goto out;
3074 transflag++;
3076 if (nbuf[0] == '.' && nbuf[1] == '/')
3077 fprintf(dout, "%s%s\n", &nbuf[2],
3078 type == TYPE_A ? "\r" : "");
3079 else
3080 fprintf(dout, "%s%s\n", nbuf,
3081 type == TYPE_A ? "\r" : "");
3082 byte_count += strlen(nbuf) + 1;
3085 (void) closedir(dirp);
3088 if (dout == NULL)
3089 reply(550, "No files found.");
3090 else if (ferror(dout) != 0)
3091 perror_reply(550, "Data connection");
3092 else
3093 reply(226, "Transfer complete.");
3095 transflag = 0;
3096 if (dout != NULL)
3097 (void) fclose(dout);
3098 data = -1;
3099 pdata = -1;
3100 out:
3101 if (freeglob) {
3102 freeglob = 0;
3103 globfree(&gl);
3107 void
3108 reapchild(signo)
3109 int signo;
3111 while (wait3(NULL, WNOHANG, NULL) > 0);
3114 #ifdef OLD_SETPROCTITLE
3116 * Clobber argv so ps will show what we're doing. (Stolen from sendmail.)
3117 * Warning, since this is usually started from inetd.conf, it often doesn't
3118 * have much of an environment or arglist to overwrite.
3120 void
3121 #if __STDC__
3122 setproctitle(const char *fmt, ...)
3123 #else
3124 setproctitle(fmt, va_alist)
3125 char *fmt;
3126 va_dcl
3127 #endif
3129 int i;
3130 va_list ap;
3131 char *p, *bp, ch;
3132 char buf[LINE_MAX];
3134 #if __STDC__
3135 va_start(ap, fmt);
3136 #else
3137 va_start(ap);
3138 #endif
3139 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
3141 /* make ps print our process name */
3142 p = Argv[0];
3143 *p++ = '-';
3145 i = strlen(buf);
3146 if (i > LastArgv - p - 2) {
3147 i = LastArgv - p - 2;
3148 buf[i] = '\0';
3150 bp = buf;
3151 while (ch = *bp++)
3152 if (ch != '\n' && ch != '\r')
3153 *p++ = ch;
3154 while (p < LastArgv)
3155 *p++ = ' ';
3157 #endif /* OLD_SETPROCTITLE */
3159 static void
3160 logxfer(name, size, start)
3161 char *name;
3162 off_t size;
3163 time_t start;
3165 char buf[1024];
3166 char path[MAXPATHLEN + 1];
3167 time_t now;
3169 if (statfd >= 0 && getwd(path) != NULL) {
3170 time(&now);
3171 snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s/%s!%qd!%ld\n",
3172 ctime(&now)+4, ident, remotehost,
3173 path, name, (long long)size,
3174 (long)(now - start + (now == start)));
3175 write(statfd, buf, strlen(buf));
3179 static char *
3180 doublequote(s)
3181 char *s;
3183 int n;
3184 char *p, *s2;
3186 for (p = s, n = 0; *p; p++)
3187 if (*p == '"')
3188 n++;
3190 if ((s2 = malloc(p - s + n + 1)) == NULL)
3191 return (NULL);
3193 for (p = s2; *s; s++, p++) {
3194 if ((*p = *s) == '"')
3195 *(++p) = '"';
3197 *p = '\0';
3199 return (s2);