]> git.sesse.net Git - betaftpd/blob - cmds.c
Fixed a security problem where the custom snprintf() would always be used. Thanks...
[betaftpd] / cmds.c
1 /*  cmds.c: BetaFTPD command handlers
2     Copyright (C) 1999-2000 Steinar H. Gunderson
3
4     This program is is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License, version 2 of the
6     License as published by the Free Software Foundation.
7
8     This program is distributed in the hope that it will be useful,
9     but WITHOUT ANY WARRANTY; without even the implied warranty of
10     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11     GNU General Public License for more details.
12
13     You should have received a copy of the GNU General Public License
14     along with this program; if not, write to the Free Software
15     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
16 */
17
18 #define _GNU_SOURCE
19
20 #if HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #if HAVE_STROPTS_H
25 #include <stropts.h>
26 #endif
27
28 #if HAVE_SYS_TYPES_H
29 #include <sys/types.h>
30 #endif
31  
32 #if HAVE_SYS_CONF_H
33 #include <sys/conf.h>
34 #endif
35
36 #if HAVE_DIRENT_H
37 #include <dirent.h>
38 #endif
39
40 #if HAVE_CRYPT_H
41 #include <crypt.h>
42 #endif
43
44 #if HAVE_ERRNO_H
45 #include <errno.h>
46 #endif
47
48 #if HAVE_GLOB_H
49 #include <glob.h>
50 #endif
51
52 #if HAVE_STDIO_H
53 #include <stdio.h>
54 #endif
55
56 #if HAVE_STDLIB_H
57 #include <stdlib.h>
58 #endif
59
60 #if HAVE_STRING_H
61 #include <string.h>
62 #endif
63
64 #if HAVE_STRINGS_H
65 #include <strings.h>
66 #endif
67
68 #if HAVE_UNISTD_H
69 #include <unistd.h>
70 #endif
71
72 #if HAVE_TIME_H
73 #include <time.h>
74 #endif
75
76 #if HAVE_FCNTL_H
77 #include <fcntl.h>
78 #endif
79
80 #if HAVE_GRP_H
81 #include <grp.h>
82 #endif
83
84 #if HAVE_SYS_IOCTL_H
85 #include <sys/ioctl.h>
86 #endif
87
88 #if HAVE_SYS_STAT_H
89 #include <sys/stat.h>
90 #endif
91
92 #if HAVE_SYS_PARAM_H
93 #include <sys/param.h>
94 #endif
95
96 #if HAVE_STROPTS_H
97 #include <stropts.h>
98 #endif
99
100 #if HAVE_SYS_CONF_H
101 #include <sys/conf.h>
102 #endif
103
104 #if HAVE_SHADOW_H
105 #include <shadow.h>
106 #endif
107
108 #if HAVE_SYS_FILIO_H
109 #include <sys/filio.h>
110 #endif
111
112 #if HAVE_SYS_POLL_H
113 #include <sys/poll.h>
114 #endif
115
116 #if WANT_NONROOT
117 #define NO_SETUID
118 #define DO_SETUID
119 #else
120 #define NO_SETUID ,0
121 #define DO_SETUID ,1
122 #endif
123
124 #ifndef NBBY
125 #define NBBY 8
126 #endif
127
128 #include <ftpd.h>
129 #include <cmds.h>
130 #include <nonroot.h>
131
132 #if WANT_DCACHE
133 #include <dcache.h>
134 #endif
135
136 #define lstat stat
137
138 extern struct conn *first_conn;
139 #if WANT_DCACHE
140 extern struct dcache *first_dcache;
141 #endif
142
143 #if HAVE_POLL
144 extern struct pollfd fds[];
145 #else
146 extern fd_set master_fds, master_send_fds;
147 #endif
148
149 struct handler {
150         char cmd_name[6];
151         char add_cmlen;         /* =1 if the command takes an argument */
152         void (*callback)(struct conn * const);
153         char min_auth;
154 #if !WANT_NONROOT
155         char do_setuid;         /* =1 if root is not *really* needed */
156 #endif
157 };
158
159 static const struct handler handler_table[] = {
160         { "user ", 1, cmd_user, 0       NO_SETUID },
161         { "pass ", 1, cmd_pass, 1       NO_SETUID },
162         { "retr ", 1, cmd_retr, 3       DO_SETUID },
163         { "acct ", 1, cmd_acct, 0       NO_SETUID },
164         { "port ", 1, cmd_port, 3       DO_SETUID },
165         { "pasv" , 0, cmd_pasv, 3       DO_SETUID },
166         { "pwd"  , 0, cmd_pwd,  3       DO_SETUID },
167         { "cwd " , 1, cmd_cwd,  3       DO_SETUID },
168         { "cdup" , 0, cmd_cdup, 3       DO_SETUID },
169         { "rest ", 1, cmd_rest, 3       DO_SETUID },
170         { "list" , 0, cmd_list, 3       DO_SETUID },
171         { "nlst" , 0, cmd_nlst, 3       DO_SETUID },
172         { "type ", 1, cmd_type, 3       DO_SETUID },
173         { "mode ", 1, cmd_mode, 3       DO_SETUID },
174         { "stru ", 1, cmd_stru, 3       DO_SETUID },
175         { "size ", 1, cmd_size, 3       DO_SETUID },
176         { "mdtm ", 1, cmd_mdtm, 3       DO_SETUID },
177         { "abor" , 0, cmd_abor, 3       DO_SETUID },
178         { "dele ", 1, cmd_dele, 3       DO_SETUID },
179         { "rnfr ", 1, cmd_rnfr, 3       DO_SETUID },
180         { "rnto ", 1, cmd_rnto, 3       DO_SETUID },
181         { "mkd " , 1, cmd_mkd,  3       DO_SETUID },
182         { "rmd " , 1, cmd_rmd,  3       DO_SETUID },
183         { "allo ", 1, cmd_allo, 3       DO_SETUID },
184         { "stat" , 0, cmd_stat, 0       NO_SETUID },
185         { "noop" , 0, cmd_noop, 0       DO_SETUID },
186         { "syst" , 0, cmd_syst, 0       DO_SETUID },
187         { "help" , 0, cmd_help, 0       NO_SETUID },
188         { "quit" , 0, cmd_quit, 0       DO_SETUID },
189         { "rein" , 0, cmd_rein, 0       DO_SETUID },
190
191         /* deprecated forms */
192         { "xcup" , 0, cmd_cdup, 3       DO_SETUID },
193         { "xcwd ", 1, cmd_cwd,  3       DO_SETUID },
194         { "xpwd" , 0, cmd_pwd,  3       DO_SETUID },
195         { "xmkd ", 1, cmd_mkd,  3       DO_SETUID },
196         { "xrmd ", 1, cmd_rmd,  3       DO_SETUID },
197 #if WANT_UPLOAD
198         { "stor ", 1, cmd_stor, 3       DO_SETUID },
199         { "appe ", 1, cmd_appe, 3       DO_SETUID },
200 #endif
201 #if DOING_PROFILING
202 #warning Use DOING_PROFILING with caution, and NEVER on a production server! :-)
203         { "exit",  0, cmd_exit, 0       NO_SETUID },
204 #endif
205         { ""    ,  0, NULL,     0       NO_SETUID }
206 };
207
208 /*
209  * do_chdir():  Does a chdir() to newd on c, staying inside the
210  *              limits of root_dir. Use this instead of a chdir() whenever
211  *              you can, and possibly even when you can't :-)
212  *
213  *              This command quirks around some problems in the rest of
214  *              the code (namely translate_path()), so a blank newdir is
215  *              interpreted as the root directory.
216  */
217 int do_chdir(struct conn * const c, const char * const newd)
218 {
219         char chd[512], temp[512];
220
221         TRAP_ERROR(chdir(c->curr_dir) == -1, 550, return -1);
222
223         /* handle `absolute' paths */
224         if (newd[0] == '/' || newd[0] == '\0') {
225                 strcpy(temp, c->root_dir);
226
227                 /*
228                  * is this the root directory? if not, remove the trailing `/'
229                  * and concatenate the new directory on
230                  */
231                 if (newd[1] != '\0' && newd[0] != '\0') {
232                         temp[strlen(temp) - 1] = 0;
233                         strcat(temp, newd);
234                 }
235         } else {
236                 strcpy(temp, newd);
237         }
238
239 #if WANT_NONROOT
240         if (nr_check_permission(c->uid, temp, 1, 1, NULL) == -1) {
241                 numeric(c, 550, "Permission denied");
242                 return -1;
243         }
244 #endif
245
246         TRAP_ERROR(chdir(temp) == -1, 550, return -1);
247
248         getcwd(chd, 254);
249         if (chd[strlen(chd) - 1] != '/') {
250                 strcat(chd, "/");
251         }
252
253         if (strncmp(chd, c->root_dir, strlen(c->root_dir)) != 0) {
254                 numeric(c, 550, "No such file or directory.");
255                 return -1;
256         }
257
258         return 0;
259 }
260
261 /*
262  * cmd_user():  Handles the USER command, and does most of the initial
263  *              authentication work. User names are limited to 16
264  *              characters, by force...
265  */
266 void cmd_user(struct conn * const c)
267 {
268         strncpy(c->username, c->recv_buf, 16);
269         c->username[16] = 0;
270
271         if (strcasecmp(c->username, "anonymous") == 0) {
272                 strcpy(c->username, "ftp");
273         }
274         if (strcasecmp(c->username, "ftp") == 0) {
275                 numeric(c, 331, "Login OK, send password (your e-mail).");
276                 c->auth = 1;
277         } else {
278                 numeric(c, 331, "Password required for %s.", c->username);
279                 c->auth = 2;
280         }
281 }
282
283 /*
284  * cmd_pass():  Handles the PASS command, and checks the password.
285  *              This function is rather long and complicated, mostly
286  *              because there are so many ways of doing users
287  *              (including my nonroot system) out there... And we
288  *              don't even support PAM or real shadow passwords (with
289  *              expiry etc) yet...
290  */
291 void cmd_pass(struct conn * const c)
292 {
293 #if WANT_NONROOT
294         c->auth = nr_userinfo(c->username, &c->uid, c->curr_dir, c->root_dir,
295                               c->recv_buf);
296 #else /* !WANT_NONROOT */
297 #if WANT_SHADOW && HAVE_SHADOW_H
298         struct spwd *s;
299 #endif
300         struct passwd *p;
301
302         p = getpwnam(c->username);
303 #if WANT_SHADOW && HAVE_SHADOW_H
304         s = getspnam(c->username);
305 #endif
306         
307         if (p == NULL) {
308                 c->auth = 0;
309         } else {
310                 c->uid = p->pw_uid;
311                 c->gid = p->pw_gid;
312                 strncpy(c->curr_dir, p->pw_dir, 254);
313                 c->curr_dir[254] = 0;
314         }
315
316         if (c->auth == 1) {
317                 if (c->curr_dir[strlen(c->curr_dir) - 1] != '/') {
318                         strcat(c->curr_dir, "/");
319                 }
320                 strcpy(c->root_dir, c->curr_dir);       
321                 c->auth = 3;
322         } else if (c->auth != 0) {
323                 strcpy(c->root_dir, "/");
324                 if (strcmp(crypt(c->recv_buf, p->pw_passwd), p->pw_passwd) != 0
325 #if WANT_SHADOW && HAVE_SHADOW_H
326                     && (s == NULL || strcmp(crypt(c->recv_buf, s->sp_pwdp), s->sp_pwdp) != 0)
327 #endif
328                 ) {
329                         c->auth = 0;
330                 } else {
331                         c->auth = 4;
332                 }
333         }
334 #endif /* !WANT_NONROOT */
335
336         /* root should not be allowed to FTP */
337         if (c->uid == 0) {
338                 c->auth = 0;
339         }
340         if (c->auth == 0) {
341                 numeric(c, 530, "Login incorrect.");
342         } else {
343 #if WANT_MESSAGE
344                 chdir(c->curr_dir);
345                 dump_file(c, 230, "welcome.msg");
346 #endif
347                 /* Have a different message for anonymous users? */
348                 numeric(c, 230, "User logged in.");
349         }
350 }
351
352 /*
353  * cmd_acct():  Handle (ignore) the ACCT command. I don't see how we
354  *              could make use of this command... wu-ftpd doesn't, either.
355  *              However, wu-ftpd (at least the version I have here) uses
356  *              502, which isn't a legal error code according to RFC959.
357  *              202, on the other hand, is, and seems to be applicable.
358  *
359  *              I'm unsure if this one should require setuid or not, but
360  *              I feel that the RFC959 intention is having it _before_
361  *              USER/PASS. Therefore, this one runs with root privilegies :-)
362  */
363 void cmd_acct(struct conn * const c)
364 {
365         numeric(c, 202, "ACCT ignored OK -- not applicable on this system.");
366 }
367
368 /*
369  * cmd_port():  Handles the PORT command, and sets up the data socket.
370  *              Making a brief uid=0 (root) appearance (to bind the socket) --
371  *              I feel it's safer that way (instead of running as root
372  *              the whole way), in case there are some weird overflows
373  *              somewhere.
374  */
375 void cmd_port(struct conn * const c)
376 {
377         short int a0, a1, a2, a3, p0, p1;
378         int i, sock, err;
379         struct ftran *f;
380         struct sockaddr_in sin;
381     
382         if ((c->transfer != NULL) && (c->transfer->state >= 4)) {
383                 numeric(c, 500, "Sorry, only one transfer at a time.");
384                 return;
385         }
386
387         sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
388         TRAP_ERROR(sock == -1, 500, return);
389
390         destroy_ftran(c->transfer);
391         c->transfer = f = alloc_new_ftran(sock, c);
392
393         i = sscanf(c->recv_buf, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1);
394         if (i < 6) {
395                 numeric(c, 501, "Parse error.");
396         } else {
397                 const int one = 1;
398                 int tmp;
399
400                 /* bind to own address, port 20 (FTP data) */
401                 tmp = sizeof(sin);
402                 err = getsockname(c->sock, (struct sockaddr *)&sin, &tmp);
403                 TRAP_ERROR(err == -1, 500, return);
404                 sin.sin_port = FTP_PORT - 1;
405
406                 numeric(c, 200, "PORT command OK.");
407
408                 /* note that bind() might well fail, so we don't error check */
409 #if !WANT_NONROOT
410                 /* need root privilegies for a short while */
411                 seteuid(getuid());
412                 setegid(getgid());
413 #endif
414                 bind(sock, (struct sockaddr *)&sin, sizeof(sin));
415 #if !WANT_NONROOT
416                 setegid(c->gid);
417                 seteuid(c->uid);
418 #endif
419
420                 f->sin.sin_family = AF_INET;
421                 f->sin.sin_addr.s_addr = htonl(
422                         ((unsigned char)(a0) << 24) +
423                         ((unsigned char)(a1) << 16) +
424                         ((unsigned char)(a2) <<  8) +
425                         ((unsigned char)(a3)      ));
426                 f->sin.sin_port = htons(
427                         ((unsigned char)(p0) << 8) +
428                         ((unsigned char)(p1)     ));
429                 f->sock = sock;
430                 f->state = 3;
431
432                 i = 1;          
433                 ioctl(f->sock, FIONBIO, &one);
434         }
435 }
436
437 /*
438  * cmd_pasv():  Handles the PASV command, and sets up the data socket.
439  *              Uses port numbers > 1024, since it doesn't run as root.
440  */
441 void cmd_pasv(struct conn * const c)
442 {
443         struct ftran *f;
444         int tmp, sock, err;
445         unsigned int one = 1;
446         struct sockaddr_in addr;
447
448         if ((c->transfer != NULL) && (c->transfer->state >= 4)) {
449                 numeric(c, 503, "Sorry, only one transfer at once.");
450                 return;
451         }
452         destroy_ftran(c->transfer);
453
454         sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
455         TRAP_ERROR(sock == -1, 500, return);
456         err = add_fd(sock, POLLIN);
457         TRAP_ERROR(err != 0, 501, return);
458
459         c->transfer = f = alloc_new_ftran(sock, c);
460
461         ioctl(sock, FIONBIO, &one);
462
463         /* setup socket */
464         tmp = sizeof(addr);
465         err = getsockname(c->sock, (struct sockaddr *)&addr, &tmp);
466         TRAP_ERROR(err == -1, 500, return);
467
468         addr.sin_port = 0;      /* let the system choose */
469         err = bind(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
470         TRAP_ERROR(err == -1, 500, return);
471
472         tmp = sizeof(addr);
473         err = getsockname(sock, (struct sockaddr *)&addr, &tmp);
474         TRAP_ERROR(err == -1, 500, return);
475
476         err = listen(f->sock, 1);
477         TRAP_ERROR(err == -1, 500, return);
478         f->state = 1;
479
480         numeric(c, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)",
481                 (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24,
482                 (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16,
483                 (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >>  8,
484                 (htonl(addr.sin_addr.s_addr) & 0x000000ff),
485                 (htons(addr.sin_port) & 0xff00) >> 8,
486                 (htons(addr.sin_port) & 0x00ff));
487 }
488
489 /*
490  * cmd_pwd():   Handles PWD command (print working directory).
491  *
492  *              Note that if somebody contacts you with the message `the server
493  *              says curr_dir() is outside root_dir()', you should fix your
494  *              /betaftpd.users file, if you use nonroot. If not, it's a bug.
495  *              Try to get it _reproducible_, and mail it to me.
496  */
497 void cmd_pwd(struct conn * const c)
498 {
499         char temp[512], *cdir = NULL;
500
501         cdir = do_pwd(c, temp, c->curr_dir);
502         if (cdir != NULL) {
503                 numeric(c, 257, "\"%s\" is current working directory.", cdir);
504         }
505 }
506
507 /*
508  * do_pwd():    Translates an absolute path to a path suitable for viewing
509  *              to the user (ie. removes the root_dir, and removes a trailing
510  *              slash if it exists). Note that the retbuf is only used as a
511  *              storage place -- the pointer to the right place within retbuf
512  *              is _returned_.
513  */
514 char *do_pwd(struct conn * const c, char * const retbuf, const char * const dir) 
515 {
516         char *cdir = NULL;
517
518         strcpy(retbuf, dir);
519
520         if (strncmp(retbuf, c->root_dir, strlen(c->root_dir)) != 0) {
521                 numeric(c, 550, "curr_dir is outside root_dir, please contact site administrator.");
522                 return NULL;
523         }
524
525         cdir = retbuf + strlen(c->root_dir) - 1;
526         if (cdir[strlen(cdir) - 1] == '/' && strlen(cdir) > 1) {
527                 cdir[strlen(cdir) - 1] = 0;
528         } else if (strlen(cdir) == 0) {
529                 strcpy(cdir, "/");
530         }       
531
532         return cdir;
533 }
534
535 /*
536  * cmd_cwd():   Handles CWD command (change working directory). Uses
537  *              cmd_cwd_internal() (see below).
538  */
539 void cmd_cwd(struct conn * const c)
540 {
541         cmd_cwd_internal(c, c->recv_buf);
542 }
543
544 /*
545  * cmd_cdup():  Handles a CDUP command (identical to `CWD ..'). Note that
546  *              RFC959 gives two different response codes (250 and 200) --
547  *              250 is the same as CWD gives, which sounds logical to me.
548  *              wu-ftpd uses it as well.
549  *
550  *              Note that using a CDUP to try to get outside root_dir returns
551  *              an error, instead of just staying in the root directory (as
552  *              the OS and thus wu-ftpd does).
553  */
554 void cmd_cdup(struct conn * const c)
555 {
556         cmd_cwd_internal(c, "..");
557 }
558
559 /*
560  * cmd_cwd_internal():
561  *              Does the work for CWD and CDUP (modularized to save some
562  *              space and have clearer code). Mostly, it just uses do_chdir(),
563  *              and sees where that takes us. It adds a trailing slash if needed.
564  */
565 void cmd_cwd_internal(struct conn * const c, const char * const newd)
566 {
567         if (do_chdir(c, newd) != -1) {
568                 int i;
569
570                 getcwd(c->curr_dir, 254);
571                 i = strlen(c->curr_dir);
572                 if (c->curr_dir[i - 1] != '/') {
573                         c->curr_dir[i++] = '/';
574                         c->curr_dir[i] = '\0';
575                 }
576
577 #if WANT_MESSAGE
578                 dump_file(c, 250, ".message");
579                 list_readmes(c);
580 #endif
581
582                 numeric(c, 250, "CWD successful.");
583         }
584 }
585
586 /*
587  * cmd_rest():  Handles the REST command. All it does is tell the file
588  *              sending functions to start at the correct number. We should
589  *              perhaps add some better error checking to this?
590  */
591 void cmd_rest(struct conn * const c)
592 {
593         c->rest_pos = abs(atoi(c->recv_buf));
594         numeric(c, 350, "Setting resume at %u bytes.", c->rest_pos);
595 }
596
597 /*
598  * cmd_retr():  Handles the RETR command. This command doesn't send the
599  *              file, but it opens it and tells the socket handling code
600  *              to check for activity on the data socket. When the
601  *              connection occurs (or succeeds, if we're using PORT mode),
602  *              the actual file transfer begins.
603  */
604 void cmd_retr(struct conn * const c)
605 {
606         struct ftran *f = c->transfer;
607
608         if ((f == NULL) || ((f->state != 1) && (f->state != 3))) {
609                 numeric(c, 425, "No data connection set up; please use PASV or PORT.");
610                 return;
611         }
612
613 #if WANT_ASCII
614         if ((c->rest_pos > 0) && (c->ascii_mode == 1)) {
615                 numeric(c, 500, "Cannot resume while in ASCII mode.");
616                 return;
617         }
618 #endif
619
620         f->local_file = do_openfile(c, c->recv_buf, f->filename, O_RDONLY
621 #if WANT_NONROOT
622                 , 4
623 #endif
624         );
625         f->dir_listing = 0;
626
627         if (f->local_file == -1) {
628                 numeric(f->owner, 550, strerror(errno));
629                 destroy_ftran(f);
630         } else if (f->local_file == -2) {
631                 f->local_file = -1;
632                 destroy_ftran(f);
633         } else {
634 #if WANT_UPLOAD
635                 f->upload = 0;
636 #endif
637                 prepare_for_transfer(f);
638         }
639 }
640
641 #if WANT_UPLOAD
642 /*
643  * cmd_stor():  Handles the STOR command (upload file). Pushes the
644  *              work down to do_store(), below.
645  */
646 void cmd_stor(struct conn * const c)
647 {
648         do_store(c, 0);
649 }
650
651 /*
652  * cmd_appe():  Handles the APPE command (append to file). Pushes
653  *              the work down to do_store(), below.
654  */
655 void cmd_appe(struct conn * const c)
656 {
657         do_store(c, 1);
658 }
659
660 /*
661  * do_store():  Initiate an upload. Most of the comments to do_retr()
662  *              (above) apply to this one as well.
663  */
664 void do_store(struct conn * const c, const int append)
665 {
666         struct ftran *f = c->transfer;
667
668         if ((f == NULL) || ((f->state != 1) && (f->state != 3))) {
669                 numeric(c, 425, "No data connection set up; please use PASV or PORT.");
670                 return;
671         }
672
673 #if WANT_ASCII
674         if ((c->rest_pos > 0) && (c->ascii_mode == 1)) {
675                 numeric(c, 500, "Cannot resume while in ASCII mode.");
676                 return;
677         }
678 #endif
679
680         f->local_file = do_openfile(c, c->recv_buf, f->filename, O_WRONLY |
681                 O_CREAT | ((append || c->rest_pos > 0) ? 0 : O_TRUNC)
682 #if WANT_NONROOT
683                 , 2
684 #endif
685         );
686         f->dir_listing = 0;
687
688         if (f->local_file == -1) {
689                 numeric(f->owner, 550, strerror(errno));
690         } else if (f->local_file == -2) {
691                 f->local_file = -1;
692         } else {
693                 f->upload = 1;
694                 f->append = append;
695 #if WANT_ASCII
696                 f->ascii_mode = c->ascii_mode;
697 #endif
698                 prepare_for_transfer(f);
699         }
700 }
701 #endif /* WANT_UPLOAD */
702
703 /*
704  * cmd_size():  Handle the SIZE command -- returns the size of a
705  *              file. Note that this command is not part of RFC959,
706  *              and thus there is no clear specification (except
707  *              for some ftpext documents, which we try to follow
708  *              as closely as we can). BetaFTPD deviates from wu-ftpd
709  *              in that it lets you check the `size' of directories
710  *              as well (instead of giving 550). This is _not_ the
711  *              size of all the files in the directory, rather how
712  *              much space the directory inode uses.
713  */
714 void cmd_size(struct conn * const c)
715 {
716 #if WANT_ASCII
717         if (c->ascii_mode) {
718                 numeric(c, 550, "SIZE not available in ASCII mode.");
719                 return;
720         }
721 #endif
722         {
723                 const char * const fname = translate_path(c, c->recv_buf);
724                 struct stat buf;
725         
726                 TRAP_ERROR(fname == NULL || lstat(fname, &buf) == -1, 550, return);
727         
728                 numeric(c, 213, "%lu", (unsigned long)(buf.st_size));
729         }
730 }
731
732 /*
733  * cmd_mdtm():  Handle the MDTM command -- returns the modification
734  *              date/time of a file. See the comments on cmd_size(),
735  *              above.
736  */
737 void cmd_mdtm(struct conn * const c)
738 {
739         const char * const fname = translate_path(c, c->recv_buf);
740         struct stat buf;
741         struct tm *m;
742
743         TRAP_ERROR(fname == NULL || lstat(fname, &buf) == -1, 550, return);
744
745         m = gmtime(&(buf.st_mtime));    /* at least wu-ftpd does it in GMT */
746         numeric(c, 213, "%u%02u%02u%02u%02u%02u", m->tm_year + 1900,
747                 m->tm_mon + 1, m->tm_mday, m->tm_hour, m->tm_min, m->tm_sec);
748 }
749
750 /*
751  * cmd_abor():  Handle the ABOR command (abort a file transfer). This should
752  *              be clean enough, but isn't tested extensively.
753  */
754 void cmd_abor(struct conn * const c)
755 {
756         if (c->transfer != NULL) {
757                 numeric(c, 426, "File transfer aborted.");
758                 destroy_ftran(c->transfer);
759         }
760         numeric(c, 226, "ABOR command processed OK.");
761 }
762
763 /*
764  * cmd_dele():  Handle the DELE command (delete a file).
765  */
766 void cmd_dele(struct conn * const c)
767 {
768         const char * const fname = translate_path(c, c->recv_buf);
769         
770         TRAP_ERROR(fname == NULL || unlink(fname) == -1, 550, return);
771         numeric(c, 250, "File deleted OK.");
772 }
773
774 /*
775  * cmd_rnfr():  Handle the RNFR command (take a filename to rename from).
776  */
777 void cmd_rnfr(struct conn * const c)
778 {
779         const char * const fname = translate_path(c, c->recv_buf);
780         char cwd[256];
781         struct stat buf;
782
783         c->rename_from[0] = '\0';
784         if (fname == NULL) return;
785         
786         getcwd(cwd, 256);
787         snprintf(c->rename_from, 256, "%s/%s", cwd, fname);
788
789         /* Just check that the file exists. */
790         TRAP_ERROR(lstat(c->rename_from, &buf) == -1, 550, c->rename_from[0] = '\0'; return);
791
792         numeric(c, 350, "File exists, send RNTO.");
793 }
794
795 /*
796  * cmd_rnto():  Handle the RNTO command (do the actual renaming).
797  */
798 void cmd_rnto(struct conn * const c)
799 {
800         const char * const fname = translate_path(c, c->recv_buf);
801
802         if (fname == NULL) return;
803         if (c->rename_from[0] == '\0') {
804                 numeric(c, 503, "Please send RNFR first.");
805                 return;
806         }
807
808         TRAP_ERROR(rename(c->rename_from, fname) == -1, 550, c->rename_from[0] = '\0'; return);
809         c->rename_from[0] = '\0';
810
811         numeric(c, 250, "File renamed successfully.");
812 }
813
814 /*
815  * cmd_mkd():   Handle the MKD/XMKD command (create a new directory).
816  *              RFC959 is not clear on the error codes for this command --
817  *              one place, 521 is cited as the correct error, but is
818  *              mentioned nowhere else. Different FTP servers differ here
819  *              as well. Thus, I've followed what appears to be the intention
820  *              (having `analogous' errors with STOR), and use 550 instead.
821  *
822  *              Making directories is probably the topic covered most
823  *              extensively by RFC959 (and in the most confusing way as
824  *              well). I try to follow the conventions, but it isn't always
825  *              easy :-) (This code isn't quite easy to understand, because
826  *              temp2 is used twice, in two different roles.)
827  */
828 void cmd_mkd(struct conn * const c)
829 {
830         const char * const fname = translate_path(c, c->recv_buf);
831         char temp[512], temp2[1024], *cdir;
832         int i, j;
833
834         TRAP_ERROR(fname == NULL || mkdir(fname, 0755) == -1, 550, return);
835
836         chdir(fname);
837         getcwd(temp2, 512);
838         cdir = do_pwd(c, temp, temp2);
839
840         if (do_pwd == NULL) return;
841         
842         /* double the quotes in the output */ 
843         for (i = 0, j = 0; i <= strlen(cdir); i++, j++) {
844                 temp2[j] = cdir[i];
845                 if (cdir[i] == '"') {
846                         temp2[++j] = '"';
847                 }
848         }
849         numeric(c, 257, "\"%s\" created.", temp2);
850 }
851
852 /*
853  * cmd_rmd():   Handle the RMD/XRMD command. Works just like DELE, only for
854  *              directories.
855  */
856 void cmd_rmd(struct conn * const c)
857 {
858         const char * const fname = translate_path(c, c->recv_buf);
859
860         TRAP_ERROR(fname == NULL || rmdir(fname) == -1, 550, return);
861         numeric(c, 250, "Directory deleted.");
862 }
863
864 /*
865  * cmd_allo():  Handle the ALLO command. The command does not do anything, except
866  *              sit around and play compliant. Some Windows FTP servers (Serv-U,
867  *              for instance), verifies that there is enough space on the disk,
868  *              but since we have no idea on what the filesystem will be stored on,
869  *              we just ignore the command.
870  *
871  *              We could theoretically use this information to give more information
872  *              to the full-screen mode, but close to no FTP clients send this
873  *              command, and it would touch too much code.
874  */
875 void cmd_allo(struct conn * const c)
876 {
877         numeric(c, 202, "No storage allocation necessary.");
878 }
879
880 /*
881  * cmd_stat():  Handle the STAT command. Please see README for more details.
882  *              Note that this command is run with euid=root, since it has
883  *              to be able to run before USER.
884  *
885  *              Note that we need to bypass numeric(), to get a multi-line
886  *              reply.
887  */
888 #if WANT_STAT
889 char conn_state[5][27] = {
890         "Not logged in",
891         "Waiting for e-mail address",
892         "Waiting for password",
893         "Logged in",
894         "Logged in",            /* non-anonymous */
895 };
896
897 char ftran_state[6][42] = {
898         "Not initialized",
899         "Decided PASV address/port",
900         "Waiting on PASV socket",
901         "Got PORT address/port",
902         "Connecting on PORT address/port",
903         "Transferring file (or connecting on PORT)"
904 };
905 #endif
906
907 void cmd_stat(struct conn * const c)
908
909 #if WANT_STAT
910         char buf[1024];
911         int i, err;
912         struct ftran *f = c->transfer;
913
914         snprintf(buf, 1024, "211- FTP server status:\r\n"
915                             "     BetaFTPD version " VERSION " (http://members.xoom.com/sneeze/betaftpd.html)\r\n"
916                             "     Connected to %s\r\n"
917                             "     Control connection state: %s\r\n"
918 #if WANT_ASCII
919                             "     TYPE: %s; STRUcture: File; transfer MODE: Stream\r\n"
920 #else
921                             "     TYPE: Image; STRUcture: File; transfer MODE: Stream\r\n"
922 #endif
923                             "     Data connection state: %s\r\n"
924                             "211 End of status\r\n",
925                                 inet_ntoa(((struct sockaddr_in *)(&(c->addr)))->sin_addr),
926                                 conn_state[c->auth],
927 #if WANT_ASCII
928                                 (c->ascii_mode == 1) ? "ASCII, FORM: Nonprint" : "Image",
929 #endif
930                                 (f) ? ftran_state[f->state] : ftran_state[0]);
931
932         i = strlen(buf);
933
934         err = send(c->sock, buf, i, 0);
935         if (err == -1 && errno == EPIPE) {
936                 this->free_me = 1;
937         }
938 #else
939         numeric(c, 502, "STAT command disabled for security reasons.");
940 #endif
941 }
942
943 #if HAVE_MMAP
944 /*
945  * _mwrite():   This define is for mmap-listing. It works as a write()
946  *              (not in parameter, but in function), and is used in
947  *              cmd_list() and cmd_nlst() only.
948  *
949  *              Note that this function returns the new position in the
950  *              `file'. The caller is expected to send this information
951  *              back in `pos' at the next call to _mwrite().
952  */
953 int _mwrite(const char * const buf, const struct ftran * const f,
954             const int pos, const int count, const int size)
955 {
956         if (pos + count >= size) return size;   /* out of space */
957         memcpy(f->file_data + pos, buf, count);
958         return pos + count;
959 }
960 #endif
961
962 /*
963  * mwrite:      This is a short_hand define, making calls to _mwrite() very
964  *              similiar to calls to write(). It works both with and without
965  *              mmap().
966  */
967 #if HAVE_MMAP
968 #define mwrite(buf, count) pos = _mwrite((buf), (f), (pos), (count), (size));
969 #else
970 #define mwrite(buf, count) write(f->local_file, buf, count);
971 #endif
972
973 /*
974  * long_listing():
975  *              Formats output in `ls -l' style. It returns one line for the
976  *              file PATHNAME, and returns it in retbuf. Setting do_classify
977  *              to nonzero has the same effect as `ls -F'.
978  *
979  *              This command is so long, because simply there is so much to
980  *              be done. GNU ls has some extra functions, but it's close to
981  *              3000 lines too...
982  */
983 int long_listing(char * const retbuf, const char * const pathname, const int do_classify)
984 {
985         int i, year;
986         char newd[512], temp[1026];
987         struct stat buf;
988         struct tm *t;
989         time_t now;
990         char username[17], groupname[17];
991
992         time(&now);
993         year = localtime(&now)->tm_year;
994         {
995 #if !WANT_NONROOT
996                 struct passwd *p;
997                 struct group *g;
998 #endif
999
1000                 if (lstat(pathname, &buf) == -1) return 0;
1001
1002 #if WANT_NONROOT
1003                 strcpy(username, nr_get_uname(buf.st_uid));
1004                 strcpy(groupname, nr_get_gname(buf.st_gid));
1005 #else
1006                 p = getpwuid(buf.st_uid);
1007                 if (p != NULL) {
1008                         strncpy(username, p->pw_name, 16);
1009                         username[16] = 0;
1010                 } else {
1011                         snprintf(username, 16, "%u", buf.st_uid);
1012                 }
1013
1014                 g = getgrgid(buf.st_gid);
1015                 if (g != NULL) {
1016                         strncpy(groupname, g->gr_name, 16);
1017                         groupname[16] = 0;
1018                 } else {
1019                         snprintf(groupname, 16, "%u", buf.st_gid);
1020                 }
1021 #endif
1022         }
1023
1024         /*
1025          * This POSIX approximation is based on GNU ls code (and obfuscated
1026          * a bit...), to be compatible with `real' ls implementations.
1027          */
1028         t = localtime(&(buf.st_mtime));
1029         strftime(newd, 512, ((now > buf.st_mtime + 6L * 30L * 24L * 60L * 60L) ||
1030                              (now < buf.st_mtime - 60L * 60L))
1031                         ? "%b %e  %Y" : "%b %e %H:%M", t);
1032
1033         {
1034 #if WANT_NONROOT
1035                 char rights[16];
1036
1037                 if (nr_check_permission(0, pathname, 0, (S_ISDIR(buf.st_mode)), rights) == -1) {
1038                         /* no permission to even see this file */
1039                         return 0;
1040                 }
1041
1042                 snprintf(temp, 1024, "%c%s %3u %-8s %-8s %8lu %12s %s\r\n",
1043 #else
1044                 snprintf(temp, 1024, "%c%c%c%c%c%c%c%c%c%c %3u %-8s %-8s %8lu %12s %s",
1045 #endif
1046                         decode_mode(buf.st_mode),
1047 #if WANT_NONROOT
1048                         rights,
1049 #else
1050                         (buf.st_mode & S_IRUSR) ? 'r' : '-', 
1051                         (buf.st_mode & S_IWUSR) ? 'w' : '-',
1052                         (buf.st_mode & S_IXUSR) ? ((buf.st_mode & S_ISUID) ? 's' : 'x') : '-',
1053                         (buf.st_mode & S_IRGRP) ? 'r' : '-',
1054                         (buf.st_mode & S_IWGRP) ? 'w' : '-',
1055                         (buf.st_mode & S_IXGRP) ? ((buf.st_mode & S_ISGID) ? 's' : 'x') : '-',
1056                         (buf.st_mode & S_IROTH) ? 'r' : '-',
1057                         (buf.st_mode & S_IWOTH) ? 'w' : '-',
1058                         (buf.st_mode & S_IXOTH) ? ((buf.st_mode & S_ISVTX) ? 't' : 'x') : '-',
1059 #endif
1060                         buf.st_nlink, username, groupname,
1061                         (unsigned long)(buf.st_size), newd, pathname);
1062                 i = strlen(temp);
1063         
1064 #if 0
1065                 /*
1066                  * vim needs this extra character for some reason... It's too 
1067                  * bad I'll have to do it this way, but syntax colouring
1068                  * that works properly is almost a `must' for me :-)
1069                  */
1070                 )
1071 #endif
1072  
1073                 /* add an extra classification `sign' if we got -F */
1074                 if (do_classify) {
1075                         int len = strlen(temp);
1076                         temp[len] = classify(buf.st_mode);
1077                         temp[len + 1] = '\0';
1078                 }
1079         }
1080
1081         strcpy(retbuf, temp);
1082         return 1;
1083 }
1084
1085 /*
1086  * cmd_list():  Handles the LIST command (directory listing). Does a
1087  *              long listing (of type `ls -l'). The listing work is
1088  *              done by do_listing(), below.
1089  */
1090 void cmd_list(struct conn * const c)
1091 {
1092         struct list_options lo;
1093
1094         lo.recursive = 0;
1095         lo.long_listing = 1;
1096         lo.classify = 0;
1097
1098         do_listing(c, &lo);
1099 }
1100
1101 /*
1102  * cmd_nlst():  Handles the NLST command (plain directory listing).
1103  *              Does a plain listing (no dates etc.), unless overridden
1104  *              by the `-l' or `-L' flag (case insensitivity because most
1105  *              FTP clients don't have a clue about what they send out). 
1106  *              The listing work is done by do_listing(), below.
1107  */     
1108 void cmd_nlst(struct conn * const c)
1109 {
1110         struct list_options lo;
1111
1112         lo.recursive = 0;
1113         lo.long_listing = 0;
1114         lo.classify = 0;
1115
1116         do_listing(c, &lo);
1117 }
1118
1119 /*
1120  * do_listing():
1121  *              Prepares any listing buffers, temp files, etc., before
1122  *              pushing the work one step further :-)
1123  *
1124  *              If the directory listing cache is enabled, the cache
1125  *              is checked first, to see if we still have a valid entry.
1126  */
1127 void do_listing(struct conn * const c, struct list_options * const lo)
1128 {
1129         int i;
1130         char *ptr;
1131 #if HAVE_MMAP
1132         int size;
1133 #endif
1134         struct ftran * const f = c->transfer;
1135
1136 #if WANT_DCACHE
1137         char cwd[256];
1138 #endif
1139
1140 #if WANT_NONROOT
1141 #warning No nonroot checking for list_core() yet
1142 #endif
1143
1144         i = prepare_for_listing(c, &ptr, lo);
1145         if (i == -1) {
1146                 destroy_ftran(c->transfer);
1147                 return;
1148         }
1149
1150 #if WANT_DCACHE
1151         getcwd(cwd, 256);
1152 #endif
1153
1154 #if HAVE_MMAP
1155         strcpy(f->filename, "(directory listing)");
1156 #endif
1157
1158 #if WANT_DCACHE
1159         {
1160                 struct dcache *d = find_dcache(cwd, ptr, lo);
1161                 if (d != NULL) {
1162                         d->use_count++;
1163                         f->dir_cache = d;
1164                         f->file_data = d->dir_data;
1165                         f->size = d->dir_size;
1166                         f->dir_listing = 1;
1167                         f->pos = 0;
1168
1169                         prepare_for_transfer(f);
1170                         return;
1171                 }
1172         }
1173 #endif
1174
1175 #if HAVE_MMAP
1176         {
1177                 int num_files = get_num_files(c, ptr, lo);
1178                 if (num_files == -1) return;
1179
1180                 size = num_files * 160;
1181                 f->file_data = malloc(size + 1);
1182                 TRAP_ERROR(f->file_data == NULL, 550, return);
1183                 list_core(c, ptr, "", lo, size, 0);
1184         }
1185 #else
1186         list_core(c, ptr, "", lo);
1187 #endif
1188
1189 #if WANT_DCACHE
1190         populate_dcache(f, cwd, ptr, lo);
1191 #endif
1192
1193 #if HAVE_MMAP
1194         f->pos = 0;
1195 #endif
1196         prepare_for_transfer(f);
1197 }
1198
1199 /*
1200  * get_num_files():
1201  *              Get the number of files in PATHNAME (optionally matching
1202  *              a pattern). Note that c is needed for TRAP_ERROR.
1203  */
1204 int get_num_files(struct conn * const c, const char * const pathname,
1205                    struct list_options * const lo)
1206 {
1207         int num_files;
1208         glob_t pglob;
1209
1210         /*
1211          * glob() fails to set errno correctly, so we simply guess on
1212          * `permission denied'... The others are far less likely to happen.
1213          */
1214         switch (glob(pathname, 0, NULL, &pglob)) {
1215 #ifdef GLOB_NOMATCH
1216         case GLOB_NOMATCH:
1217                 return 0;
1218 #endif
1219         case 0:
1220                 num_files = pglob.gl_pathc;
1221                 break;
1222         default:
1223                 numeric(c, 550, strerror(EACCES));
1224                 return -1;
1225         }
1226
1227         if (lo->recursive) {
1228                 int i;
1229                 for (i = 0; i < pglob.gl_pathc; i++) {
1230                         char *temp = pglob.gl_pathv[i];
1231                         struct stat buf;
1232
1233                         lstat(temp, &buf);
1234                         if (S_ISDIR(buf.st_mode)) {
1235                                 chdir(temp);
1236                                 num_files += get_num_files(c, "*", lo);
1237                                 chdir("..");
1238                         }
1239                 }
1240         }
1241
1242         globfree(&pglob);
1243
1244         return num_files;
1245 }
1246
1247 /*
1248  * list_core(): Enumerate all the files in PATHNAME, and formats them
1249  *              according to list_options (calling format functions if
1250  *              required).
1251  *
1252  *              Note that we don't do any realloc() yet, so if your
1253  *              _average_ file name length is over a certain size (a little
1254  *              under 80 for long listings, and a little under 160 for
1255  *              short listings), the list will be truncated. Fix...
1256  *
1257  *              The return value only makes sense if mmap()'ing, since it
1258  *              returns the number of bytes written into the buffer.
1259  *
1260  *              This function is rather long.
1261  */
1262 int list_core(struct conn * const c, const char * const pathname,
1263               char * const disp_pathname, struct list_options * const lo
1264 #if HAVE_MMAP
1265                 , const int size, int pos
1266 #endif
1267                 )
1268 {
1269         int i;
1270         glob_t pglob;
1271         struct ftran * const f = c->transfer;
1272
1273         /*
1274          * glob() fails to set errno correctly, so we simply guess on
1275          * `permission denied'... The others are far less likely to happen.
1276          */
1277         switch (glob(pathname, GLOB_MARK, NULL, &pglob)) {
1278         case 0:
1279 #ifdef GLOB_NOMATCH
1280         case GLOB_NOMATCH:
1281 #endif
1282                 break;          /* note: break, not return */
1283         default:
1284                 numeric(c, 550, strerror(EACCES));
1285 #if HAVE_MMAP
1286                 return pos;
1287 #else
1288                 return 0;
1289 #endif
1290         }
1291
1292         if (lo->recursive) {
1293                 if (disp_pathname[0] == '\0') {
1294                         mwrite(".:\r\n", 4);
1295                 } else {
1296                         char temp[1024];
1297                         int i;
1298
1299                         snprintf(temp, 1024, "%s:\r\n", disp_pathname);
1300                         i = strlen(temp);
1301                         mwrite(temp, i);
1302                 }
1303         }
1304         if (lo->long_listing) {
1305                 /* FIX: we may get too high total number if we are running nonroot! */
1306                 struct stat buf;
1307                 long unsigned int total = 0;
1308                 char temp[1024];
1309
1310                 for (i = 0; i < pglob.gl_pathc; i++) {
1311                         if (lstat(pglob.gl_pathv[i], &buf) != -1) {
1312                                 total += buf.st_blocks;
1313                         }
1314                 }
1315                 snprintf(temp, 1024, "total %lu\r\n", total >> 1);
1316                 i = strlen(temp);
1317                 mwrite(temp, i);
1318         }
1319
1320         for (i = 0; i < pglob.gl_pathc; i++) {
1321                 char * const temp = pglob.gl_pathv[i];
1322                 char buf[2048];
1323
1324                 /* strip `/' away from the pathname -- add it later if -F */
1325                 {
1326                         int len = strlen(temp);
1327                         if (temp[len - 1] == '/') {
1328                                 temp[len - 1] = '\0';
1329                         }
1330                 }
1331
1332                 if (lo->long_listing) {
1333                         if (long_listing(buf, temp, lo->classify) == 0) continue;
1334                 } else {
1335                         strcpy(buf, temp);
1336                         if (lo->classify) {
1337                                 struct stat statbuf;
1338
1339                                 if (lstat(buf, &statbuf) != -1) {
1340                                         const int len = strlen(buf);
1341
1342                                         buf[len] = classify(statbuf.st_mode);
1343                                         buf[len + 1] = 0;
1344                                 }
1345                         }
1346                 }
1347
1348                 mwrite(buf, strlen(buf));
1349                 mwrite("\r\n", 2);
1350         }
1351
1352         /*
1353          * If recursion is on, dive into any subdirectories now -- note
1354          * that each entry is stat()'ed twice, hopefully the OS will manage,
1355          * and we've got our own dcache anyways -- this could be fixed at
1356          * the expense of some memory, consider for later inclusion.
1357          */
1358         if (lo->recursive) {
1359                 for (i = 0; i < pglob.gl_pathc; i++) {
1360                         struct stat buf;
1361                         const char * const temp = pglob.gl_pathv[i];
1362
1363                         /* don't dive into `.' or `..' */
1364                         if (lstat(temp, &buf) != -1 && S_ISDIR(buf.st_mode) &&
1365                                 (temp[0] != '.' || (temp[1] != '.' && temp[1] != '\0'))) {
1366                                 char tmp2[1024];
1367
1368                                 mwrite("\r\n", 2);
1369
1370                                 /* attach the pathname to the end of the displayed path */
1371                                 if (disp_pathname[0] == '\0') {
1372                                         snprintf(tmp2, 1024, "%s", temp);
1373                                 } else {
1374                                         snprintf(tmp2, 1024, "%s/%s", disp_pathname, temp);
1375                                 }
1376
1377                                 chdir(temp);
1378                                 pos = list_core(c, "*", tmp2, lo, 
1379 #if HAVE_MMAP
1380                                         size, pos);
1381 #endif
1382                                 chdir("..");
1383                         }
1384                 }
1385         }
1386
1387 #if HAVE_MMAP
1388         f->size = pos;
1389 #else
1390         lseek(f->local_file, 0, SEEK_SET);
1391 #endif
1392
1393         globfree(&pglob);
1394 #if HAVE_MMAP
1395         return pos;
1396 #else
1397         return 0;
1398 #endif
1399 }
1400
1401 /*
1402  * cmd_noop():  Handles the NOOP command. Does nothing, doesn't even
1403  *              reset the timeout.
1404  */
1405 void cmd_noop(struct conn * const c)
1406 {
1407         numeric(c, 200, "NOOP command successful.");
1408 }
1409
1410 /*
1411  * cmd_syst():  Handles the SYST command. Returns the system identification.
1412  */
1413 void cmd_syst(struct conn * const c)
1414 {
1415         numeric(c, 215, "UNIX Type: L%u", NBBY);
1416 }
1417
1418 /*
1419  * cmd_type():  Handles the TYPE command.
1420  */
1421 void cmd_type(struct conn * const c)
1422 {
1423 #if WANT_ASCII
1424         c->recv_buf[0] &= (255-32);     /* convert to upper case */
1425         if (c->recv_buf[0] == 'A') {
1426                 c->ascii_mode = 1;
1427                 numeric(c, 200, "Type is ASCII.");
1428         } else if (c->recv_buf[0] == 'I') {
1429                 c->ascii_mode = 0;
1430                 numeric(c, 200, "Type is IMAGE.");
1431         } else {
1432                 numeric(c, 504, "Unknown type.");
1433         }
1434 #else
1435         numeric(c, 200, "TYPE ignored (always I)");
1436 #endif
1437 }
1438
1439 /*
1440  * cmd_mode():  Handles the MODE command. Only stream mode is supported.
1441  */
1442 void cmd_mode(struct conn * const c)
1443 {
1444         c->recv_buf[0] &= (255-32);     /* convert to upper case */
1445         if (c->recv_buf[0] == 'S') {
1446                 numeric(c, 200, "Mode is STREAM.");
1447         } else {
1448                 numeric(c, 504, "Unknown mode.");
1449         }
1450 }
1451
1452 /*
1453  * cmd_stru():  Handles the STRU command. Only file mode is supported.
1454  */
1455 void cmd_stru(struct conn * const c)
1456 {
1457         c->recv_buf[0] &= (255-32);     /* convert to upper case */
1458         if (c->recv_buf[0] == 'F') {
1459                 numeric(c, 200, "Structure is FILE.");
1460         } else {
1461                 numeric(c, 504, "Unknown structure.");
1462         }
1463 }
1464
1465 /*
1466  * cmd_help():  Handle the HELP command. I'm sorry, but I'm unwilling
1467  *              to use a lot of space to explain the RFCs in such a message,
1468  *              and BetaFTPD doesn't have any special things that should
1469  *              be noted anywhere. Thus, this message is close to empty. I
1470  *              feel that a 5xx entry would have been better, but that is
1471  *              disallowed.
1472  *
1473  *              As with ACCT, this command is supposed to be executed from
1474  *              everywhere, so we have to run without setuid. I don't like
1475  *              it, but at the same time I have to idea what could go
1476  *              wrong...
1477  *
1478  *              Perhaps I should make this message sound a little less
1479  *              like an error, since the error code is intended for helpful
1480  *              messages? :-)
1481  */
1482 void cmd_help(struct conn * const c)
1483 {
1484         numeric(c, 414, "Sorry, no detailed help; use standard FTP commands.");
1485 }
1486
1487 /*
1488  * cmd_quit():  Handles the QUIT command, which shuts down the control
1489  *              and data sockets.
1490  */
1491 void cmd_quit(struct conn * const c)
1492 {
1493         numeric(c, 221, "Have a nice day!");
1494         c->free_me = 1;
1495 }
1496
1497 /*
1498  * cmd_rein():  Handle the REIN command, which does close to a full reset
1499  *              of the connection. Much of the code here is intentionally
1500  *              copied directly from alloc_new_conn() -- perhaps we should
1501  *              modularize this?
1502  */
1503 void cmd_rein(struct conn * const c)
1504 {
1505         destroy_ftran(c->transfer);
1506         c->buf_len = c->auth = c->rest_pos = 0;
1507
1508         /* equals: strcpy(c->curr_dir, "/") ; strcpy(c->last_cmd, ""); */
1509         c->curr_dir[0] = '/';
1510 #if WANT_FULLSCREEN
1511         c->curr_dir[1] = c->last_cmd[0] = '\0';
1512 #else
1513         c->curr_dir[1] = '\0';
1514 #endif
1515
1516         time(&(c->last_transfer));
1517         numeric(c, 220, "BetaFTPD " VERSION " ready.");
1518 }
1519
1520 #if DOING_PROFILING
1521 /*
1522  * cmd_exit():  Handles the EXIT command, my own `extension' to the
1523  *              FTP protocol... IMPORTANT: Only to be used for profiling
1524  *              purposes!! (It's needed to get some profiling data out
1525  *              of the server after compiling it with -pg, since such data
1526  *              is only written on a clear exit()). Any user (even those
1527  *              not logged in) can issue an EXIT, and make the server shut
1528  *              down without clearing any sockets etc. In other words:
1529  *              Don't use it on a production site.
1530  */
1531 void cmd_exit(struct conn * const c)
1532 {
1533         while (first_conn->next_conn)
1534                 destroy_conn(first_conn->next_conn);
1535         exit(0);
1536 }
1537 #endif
1538
1539 /*
1540  * parse_command():
1541  *              Gets a command from c->recv_buf, determines which command
1542  *              it is, sets proper effective user-ID and calls the command
1543  *              handler. Finally, it cleans up.
1544  *
1545  *              To me, this command seems optimizable, but I'm not really
1546  *              sure where :-)
1547  */
1548 void parse_command(struct conn *c)
1549 {
1550         int cmlen;
1551         const struct handler *h = handler_table;        /* first entry */
1552
1553         if (c == NULL) return;
1554
1555         /* strip any leading non-ASCII characters (including CR/LFs) */
1556         while (c->buf_len > 0 && (c->recv_buf[0] < 'a' || c->recv_buf[0] > 'z')
1557                               && (c->recv_buf[0] < 'A' || c->recv_buf[0] > 'Z')) {
1558                 remove_bytes(c, 1);             /* not good */
1559         }
1560
1561         /* scan, searching for CR or LF */      
1562         cmlen = strcspn(c->recv_buf, "\r\n");
1563         if (cmlen >= c->buf_len) return;
1564
1565 #if WANT_FULLSCREEN
1566         strncpy(c->last_cmd, c->recv_buf, cmlen);
1567         c->last_cmd[cmlen] = 0;
1568 #endif
1569
1570         do {
1571                 if ((cmlen >= (strlen(h->cmd_name) + h->add_cmlen)) &&
1572                     (strncasecmp(c->recv_buf, h->cmd_name, strlen(h->cmd_name)) == 0)) {
1573                         if (c->auth < h->min_auth) {
1574                                 numeric(c, 503, "Please login with USER and PASS.");
1575                                 while (c->recv_buf[0] != '\n') remove_bytes(c, 1);
1576                         } else {
1577                                 char schar;
1578
1579 #if !WANT_NONROOT
1580                                 if (h->do_setuid) {
1581                                         setegid(c->gid);
1582                                         seteuid(c->uid);
1583                                 } else {
1584                                         seteuid(getuid());
1585                                         setegid(getgid());
1586                                 }
1587 #endif
1588
1589                                 remove_bytes(c, strlen(h->cmd_name));
1590                                 cmlen -= strlen(h->cmd_name);
1591                                 while (c->recv_buf[0] == ' ') {
1592                                         remove_bytes(c, 1);
1593                                         cmlen--;
1594                                 }
1595
1596                                 schar = c->recv_buf[cmlen];
1597                                 c->recv_buf[cmlen] = 0;
1598                                 
1599                                 message_buf[0] = '\0';
1600                                 h->callback(c);
1601                                 if (message_buf[0] != '\0') {
1602                                         /* send any feedback we might have */
1603                                         int err = send(c->sock, message_buf, strlen(message_buf), 0);
1604                                         if (err == -1 && errno == EPIPE) {
1605                                                 c->free_me = 1;
1606                                         }
1607                                 }       
1608                                 
1609                                 if (!c->free_me) {
1610                                         c->recv_buf[cmlen] = schar;
1611 #if !WANT_NONROOT
1612                                         if (h->do_setuid) {
1613                                                 seteuid(getuid());
1614                                                 setegid(getgid());
1615                                         }
1616 #endif
1617                                         remove_bytes(c, cmlen);
1618                                 }
1619                         }
1620                         return;
1621                 }
1622         } while ((++h)->callback != NULL);
1623
1624         remove_bytes(c, cmlen); 
1625         {
1626                 char error[] = "500 Sorry, no such command.\r\n";
1627                 if (send(c->sock, error, strlen(error), 0) == -1 && errno == EPIPE)
1628                         destroy_conn(c);
1629         }
1630 }
1631
1632 /*
1633  * prepare_for_transfer():
1634  *              Prepares an ftran object for a file transfer, setting
1635  *              file size, opening sockets etc.
1636  *
1637  *              nonroot notice: prepare_for_transfer() assumes all access
1638  *              checks are already done.
1639  */
1640 void prepare_for_transfer(struct ftran *f)
1641 {
1642 #if WANT_NONROOT
1643 #warning No nonroot checking for prepare_for_transfer() yet
1644 #endif
1645
1646 #if HAVE_MMAP
1647         /* mmap doesn't make temp files for dir listings */
1648         if (!f->dir_listing) {
1649 #endif
1650
1651                 f->size = lseek(f->local_file, 0, SEEK_END);
1652                 errno = 0;
1653 #if WANT_UPLOAD
1654                 if (f->upload == 0 || f->append == 0 || f->owner->rest_pos != 0)
1655 #endif 
1656                         lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1657 #if HAVE_MMAP
1658         }
1659 #endif
1660         
1661         if (f->state == 1) {            /* PASV connection */
1662                 f->state = 2;           /* waiting */
1663         } else if (f->state == 3) {     /* PORT connection */
1664                 f->state = 4;
1665                 connect(f->sock, (struct sockaddr *)&f->sin, sizeof(f->sin));
1666                 add_fd(f->sock, POLLOUT);
1667         }
1668         time(&(f->tran_start));
1669 }
1670
1671 /*
1672  * decode_mode():
1673  *              Takes a mode_t argument (from a `struct stat'), and
1674  *              returns the proper dirlist letter for that type.
1675  *
1676  *              Note: S_IFLNK seems to be broken, or perhaps I just have
1677  *              missed something (S_IFLNK is always set for all *files* on
1678  *              my glibc 2.0.111 system).
1679  *
1680  *              The most common cases are put first, for speed :-)
1681  */
1682 char decode_mode(mode_t mode) {
1683         if (S_ISREG(mode))  return '-';
1684         if (S_ISDIR(mode))  return 'd';
1685         if (S_ISLNK(mode))  return 'l';
1686         if (S_ISBLK(mode))  return 'b';
1687         if (S_ISCHR(mode))  return 'c';
1688         if (S_ISSOCK(mode)) return 's';
1689         if (S_ISFIFO(mode))  return 'f';
1690
1691         return '-';
1692 }
1693
1694 /*
1695  * translate_path():
1696  *              Take an FTP path, do all neccessary root_dir checks,
1697  *              change to the correct directory and return the proper
1698  *              file name to open/stat/whatever. The path returned is
1699  *              relative to the current directory (NOT absolute). chdir()
1700  *              in any way will `destroy' this argument.
1701  *
1702  *              Note that `path' will be _changed_, and used as a return pointer
1703  *              base. Do not attempt to free the result from this function --
1704  *              if you need to, free path instead.
1705  */
1706 char *translate_path(struct conn * const c, char * const path)
1707 {
1708         char *ptr = NULL;
1709
1710         /* chdir to the right dir, then chop it off */
1711         chdir(c->curr_dir);
1712
1713         ptr = strrchr(path, '/');
1714         if (ptr != NULL) {
1715                 char save_char = ptr[0];
1716                 ptr[0] = 0;
1717
1718                 if (do_chdir(c, path) == -1) {
1719                         return NULL;
1720                 }
1721                 ptr[0] = save_char;
1722                 ptr++;
1723         } else {
1724                 ptr = path;
1725         }
1726         return ptr;
1727 }
1728
1729 /*
1730  * do_openfile():
1731  *              Opens the file PATH with access parameters FLAGS, translating
1732  *              paths and checking permissions as neccessary. Generally, this
1733  *              should be used whenever you need an open().
1734  *
1735  *              The parameters might be a bit confusing. To clarify them a bit:
1736  *              c:              IN/OUT (will be changed)
1737  *              path:           IN (but _will_ be changed)
1738  *              filename:       OUT
1739  *              flags:          IN
1740  *              check_perm:     IN
1741  */
1742 int do_openfile(struct conn * const c, char * const path,
1743                 char * const filename, const int flags
1744 #if WANT_NONROOT
1745                 , const int check_permission
1746 #endif
1747 )
1748 {
1749         char *ptr;
1750         struct stat buf;
1751
1752 #if WANT_NONROOT
1753         if (nr_check_permission(c->uid, path, check_permission, 0, NULL) == -1) {
1754                 return -1;
1755         }
1756 #endif
1757
1758         ptr = translate_path(c, c->recv_buf);
1759         if (ptr == NULL) return -1;
1760
1761 #if WANT_UPLOAD
1762         if ((flags & O_CREAT) == 0) {
1763 #endif
1764                 TRAP_ERROR(stat(ptr, &buf) == -1, 550, return -2);
1765                 if (!S_ISREG(buf.st_mode)) {
1766                         numeric(c, 550, "Not a plain file.", ptr);
1767                         return -2;
1768                 }
1769 #if WANT_UPLOAD
1770         }
1771 #endif
1772
1773         if (filename != NULL) { /* filename should always be != NULL */
1774                 strcpy(filename, ptr);
1775         }
1776         return open(ptr, flags, 0666);
1777 }
1778
1779 /*
1780  * prepare_for_listing():
1781  *              Parse list options, put them back into the list_options
1782  *              structure lo, and make temporary room for the list.
1783  */
1784 int prepare_for_listing(struct conn * const c, char ** const ptr,
1785                         struct list_options * const lo)
1786 {
1787 #if !HAVE_MMAP
1788         char *tfname;
1789 #endif
1790         struct ftran *f = c->transfer;
1791         char *tmp;
1792         char *optr = NULL, *fptr = NULL; 
1793 #if WANT_NONROOT
1794         char chd[512];
1795 #endif
1796
1797 #if WANT_NONROOT
1798 #warning No nonroot checking for prepare_for_listing() yet
1799 #endif
1800
1801         if ((f == NULL) || ((f->state != 1) && (f->state != 3))) {
1802                 numeric(c, 425, "No data connection set up; please use PASV or PORT.");
1803                 return -1;
1804         }
1805
1806         /*
1807          * A little parameter scanning is required here. There can only
1808          * be two parts: the directory name, and any options. We'll find
1809          * any options first.
1810          */
1811         if (c->recv_buf[0] == '-') {
1812                 optr = c->recv_buf;
1813         } else {
1814                 optr = strstr(c->recv_buf, " -");
1815         }
1816
1817         /* Then see if there are any options to parse. */
1818         if (optr != NULL) {
1819                 while (*++optr) {
1820                         switch (*optr & (255-32)) {     /* uppercase */
1821                         case 'R':       /* actually case sensitive... */
1822                                 lo->recursive = 1;
1823                                 break;
1824                         case 'L':
1825                                 lo->long_listing = 1;
1826                                 break;
1827                         case 'F':
1828                                 lo->classify = 1;
1829                                 break;
1830                         case '\0':
1831                                 fptr = optr + 1;
1832                                 *(optr--) = 0;
1833                                 break;
1834                         default:
1835                                 break;
1836                         }
1837                 }
1838         } else {
1839                 fptr = c->recv_buf;
1840         }
1841
1842         /* then we chdir to the dir in fptr (if any) */
1843         tmp = fptr ? strrchr(fptr, '/') : NULL;
1844         if (tmp != NULL) {
1845                 tmp[0] = 0;
1846                 if (do_chdir(c, fptr) == -1) return -1;
1847                 fptr = tmp + 1;
1848         } else {
1849                 /* current directory */
1850                 TRAP_ERROR(chdir(c->curr_dir) == -1, 550, return -1);
1851         }
1852
1853         /* if no argument, choose all files */
1854         if (fptr == NULL || fptr[0] == 0) {
1855                 fptr = "*";
1856         } else {
1857                 /* we need to check if the last part is a directory (no -d switch) */
1858                 struct stat buf;
1859                 if (stat(fptr, &buf) == 0 && S_ISDIR(buf.st_mode)) {
1860                         TRAP_ERROR(chdir(fptr) == -1, 550, return -1);
1861                         fptr = "*";
1862                 }
1863         }
1864         *ptr = fptr;
1865
1866 #if WANT_NONROOT
1867         getcwd(chd, 512);
1868         if (nr_check_permission(c->uid, chd, 4, 1, NULL) == -1) {
1869                 numeric(c, 550, "Permission denied");
1870                 return -1;
1871         }
1872 #endif
1873
1874 #if !HAVE_MMAP
1875         tfname = tempnam(NULL, "ftp");
1876
1877 #if WANT_NONROOT
1878         if (tfname == NULL) tfname = tempnam("/", "ftp");
1879 #endif
1880
1881         TRAP_ERROR(tfname == NULL, 550, return -1);
1882         strcpy(f->filename, tfname);
1883         free(tfname);
1884
1885         f->local_file = open(f->filename, O_RDWR | O_CREAT | O_TRUNC, 0666);
1886         TRAP_ERROR(f->local_file == -1, 550, return -1);
1887 #endif
1888         f->dir_listing = 1;
1889 #if WANT_UPLOAD
1890         f->upload = 0;
1891 #endif
1892
1893         return 0;
1894 }
1895
1896 /*
1897  * classify():  Takes a mode_t argument (from `struct stat'), and returns
1898  *              the parameter to be used in an `ls -F'-style listing.
1899  */
1900 char classify(const mode_t mode)
1901 {
1902         if (S_ISREG(mode)) {
1903                 if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
1904                         return '*';
1905                 } else {
1906                         return '\0';
1907                 }
1908         }
1909         if (S_ISDIR(mode)) return '/';
1910         if (S_ISLNK(mode)) return '@';
1911         if (S_ISSOCK(mode)) return '=';
1912         if (S_ISFIFO(mode)) return '|';
1913         return '\0'; 
1914 }