]> git.sesse.net Git - betaftpd/blob - cmds.c
Fixed a problem where the server might segfault if there was an error occuring while...
[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 }
1083
1084 /*
1085  * cmd_list():  Handles the LIST command (directory listing). Does a
1086  *              long listing (of type `ls -l'). The listing work is
1087  *              done by do_listing(), below.
1088  */
1089 void cmd_list(struct conn * const c)
1090 {
1091         struct list_options lo;
1092
1093         lo.recursive = 0;
1094         lo.long_listing = 1;
1095         lo.classify = 0;
1096
1097         do_listing(c, &lo);
1098 }
1099
1100 /*
1101  * cmd_nlst():  Handles the NLST command (plain directory listing).
1102  *              Does a plain listing (no dates etc.), unless overridden
1103  *              by the `-l' or `-L' flag (case insensitivity because most
1104  *              FTP clients don't have a clue about what they send out). 
1105  *              The listing work is done by do_listing(), below.
1106  */     
1107 void cmd_nlst(struct conn * const c)
1108 {
1109         struct list_options lo;
1110
1111         lo.recursive = 0;
1112         lo.long_listing = 0;
1113         lo.classify = 0;
1114
1115         do_listing(c, &lo);
1116 }
1117
1118 /*
1119  * do_listing():
1120  *              Prepares any listing buffers, temp files, etc., before
1121  *              pushing the work one step further :-)
1122  *
1123  *              If the directory listing cache is enabled, the cache
1124  *              is checked first, to see if we still have a valid entry.
1125  */
1126 void do_listing(struct conn * const c, struct list_options * const lo)
1127 {
1128         int i;
1129         char *ptr;
1130 #if HAVE_MMAP
1131         int size;
1132 #endif
1133         struct ftran * const f = c->transfer;
1134
1135 #if WANT_DCACHE
1136         char cwd[256];
1137 #endif
1138
1139 #if WANT_NONROOT
1140 #warning No nonroot checking for list_core() yet
1141 #endif
1142
1143         i = prepare_for_listing(c, &ptr, lo);
1144         if (i == -1) {
1145                 destroy_ftran(c->transfer);
1146                 return;
1147         }
1148
1149 #if WANT_DCACHE
1150         getcwd(cwd, 256);
1151 #endif
1152
1153 #if HAVE_MMAP
1154         strcpy(f->filename, "(directory listing)");
1155 #endif
1156
1157 #if WANT_DCACHE
1158         {
1159                 struct dcache *d = find_dcache(cwd, ptr, lo);
1160                 if (d != NULL) {
1161                         d->use_count++;
1162                         f->dir_cache = d;
1163                         f->file_data = d->dir_data;
1164                         f->size = d->dir_size;
1165                         f->dir_listing = 1;
1166                         f->pos = 0;
1167
1168                         prepare_for_transfer(f);
1169                         return;
1170                 }
1171         }
1172 #endif
1173
1174 #if HAVE_MMAP
1175         {
1176                 int num_files = get_num_files(c, ptr, lo);
1177                 if (num_files == -1) return;
1178
1179                 size = num_files * 160;
1180                 f->file_data = malloc(size + 1);
1181                 TRAP_ERROR(f->file_data == NULL, 550, return);
1182                 list_core(c, ptr, "", lo, size, 0);
1183         }
1184 #else
1185         list_core(c, ptr, "", lo);
1186 #endif
1187
1188 #if WANT_DCACHE
1189         populate_dcache(f, cwd, ptr, lo);
1190 #endif
1191
1192 #if HAVE_MMAP
1193         f->pos = 0;
1194 #endif
1195         prepare_for_transfer(f);
1196 }
1197
1198 /*
1199  * get_num_files():
1200  *              Get the number of files in PATHNAME (optionally matching
1201  *              a pattern). Note that c is needed for TRAP_ERROR.
1202  */
1203 int get_num_files(struct conn * const c, const char * const pathname,
1204                    struct list_options * const lo)
1205 {
1206         int num_files;
1207         glob_t pglob;
1208
1209         /*
1210          * glob() fails to set errno correctly, so we simply guess on
1211          * `permission denied'... The others are far less likely to happen.
1212          */
1213         switch (glob(pathname, 0, NULL, &pglob)) {
1214 #ifdef GLOB_NOMATCH
1215         case GLOB_NOMATCH:
1216                 return 0;
1217 #endif
1218         case 0:
1219                 num_files = pglob.gl_pathc;
1220                 break;
1221         default:
1222                 numeric(c, 550, strerror(EACCES));
1223                 return -1;
1224         }
1225
1226         if (lo->recursive) {
1227                 int i;
1228                 for (i = 0; i < pglob.gl_pathc; i++) {
1229                         char *temp = pglob.gl_pathv[i];
1230                         struct stat buf;
1231
1232                         lstat(temp, &buf);
1233                         if (S_ISDIR(buf.st_mode)) {
1234                                 chdir(temp);
1235                                 num_files += get_num_files(c, "*", lo);
1236                                 chdir("..");
1237                         }
1238                 }
1239         }
1240
1241         globfree(&pglob);
1242
1243         return num_files;
1244 }
1245
1246 /*
1247  * list_core(): Enumerate all the files in PATHNAME, and formats them
1248  *              according to list_options (calling format functions if
1249  *              required).
1250  *
1251  *              Note that we don't do any realloc() yet, so if your
1252  *              _average_ file name length is over a certain size (a little
1253  *              under 80 for long listings, and a little under 160 for
1254  *              short listings), the list will be truncated. Fix...
1255  *
1256  *              The return value only makes sense if mmap()'ing, since it
1257  *              returns the number of bytes written into the buffer.
1258  *
1259  *              This function is rather long.
1260  */
1261 int list_core(struct conn * const c, const char * const pathname,
1262               char * const disp_pathname, struct list_options * const lo
1263 #if HAVE_MMAP
1264                 , const int size, int pos
1265 #endif
1266                 )
1267 {
1268         int i;
1269         glob_t pglob;
1270         struct ftran * const f = c->transfer;
1271
1272         /*
1273          * glob() fails to set errno correctly, so we simply guess on
1274          * `permission denied'... The others are far less likely to happen.
1275          */
1276         switch (glob(pathname, GLOB_MARK, NULL, &pglob)) {
1277         case 0:
1278 #ifdef GLOB_NOMATCH
1279         case GLOB_NOMATCH:
1280 #endif
1281                 break;          /* note: break, not return */
1282         default:
1283                 numeric(c, 550, strerror(EACCES));
1284 #if HAVE_MMAP
1285                 return pos;
1286 #else
1287                 return 0;
1288 #endif
1289         }
1290
1291         if (lo->recursive) {
1292                 if (disp_pathname[0] == '\0') {
1293                         mwrite(".:\r\n", 4);
1294                 } else {
1295                         char temp[1024];
1296                         int i;
1297
1298                         snprintf(temp, 1024, "%s:\r\n", disp_pathname);
1299                         i = strlen(temp);
1300                         mwrite(temp, i);
1301                 }
1302         }
1303         if (lo->long_listing) {
1304                 /* FIX: we may get too high total number if we are running nonroot! */
1305                 struct stat buf;
1306                 long unsigned int total = 0;
1307                 char temp[1024];
1308
1309                 for (i = 0; i < pglob.gl_pathc; i++) {
1310                         if (lstat(pglob.gl_pathv[i], &buf) != -1) {
1311                                 total += buf.st_blocks;
1312                         }
1313                 }
1314                 snprintf(temp, 1024, "total %lu\r\n", total >> 1);
1315                 i = strlen(temp);
1316                 mwrite(temp, i);
1317         }
1318
1319         for (i = 0; i < pglob.gl_pathc; i++) {
1320                 char * const temp = pglob.gl_pathv[i];
1321                 char buf[2048];
1322
1323                 /* strip `/' away from the pathname -- add it later if -F */
1324                 {
1325                         int len = strlen(temp);
1326                         if (temp[len - 1] == '/') {
1327                                 temp[len - 1] = '\0';
1328                         }
1329                 }
1330
1331                 if (lo->long_listing) {
1332                         if (long_listing(buf, temp, lo->classify) == 0) continue;
1333                 } else {
1334                         strcpy(buf, temp);
1335                         if (lo->classify) {
1336                                 struct stat statbuf;
1337
1338                                 if (lstat(buf, &statbuf) != -1) {
1339                                         const int len = strlen(buf);
1340
1341                                         buf[len] = classify(statbuf.st_mode);
1342                                         buf[len + 1] = 0;
1343                                 }
1344                         }
1345                 }
1346
1347                 mwrite(buf, strlen(buf));
1348                 mwrite("\r\n", 2);
1349         }
1350
1351         /*
1352          * If recursion is on, dive into any subdirectories now -- note
1353          * that each entry is stat()'ed twice, hopefully the OS will manage,
1354          * and we've got our own dcache anyways -- this could be fixed at
1355          * the expense of some memory, consider for later inclusion.
1356          */
1357         if (lo->recursive) {
1358                 for (i = 0; i < pglob.gl_pathc; i++) {
1359                         struct stat buf;
1360                         const char * const temp = pglob.gl_pathv[i];
1361
1362                         /* don't dive into `.' or `..' */
1363                         if (lstat(temp, &buf) != -1 && S_ISDIR(buf.st_mode) &&
1364                                 (temp[0] != '.' || (temp[1] != '.' && temp[1] != '\0'))) {
1365                                 char tmp2[1024];
1366
1367                                 mwrite("\r\n", 2);
1368
1369                                 /* attach the pathname to the end of the displayed path */
1370                                 if (disp_pathname[0] == '\0') {
1371                                         snprintf(tmp2, 1024, "%s", temp);
1372                                 } else {
1373                                         snprintf(tmp2, 1024, "%s/%s", disp_pathname, temp);
1374                                 }
1375
1376                                 chdir(temp);
1377                                 pos = list_core(c, "*", tmp2, lo, 
1378 #if HAVE_MMAP
1379                                         size, pos);
1380 #endif
1381                                 chdir("..");
1382                         }
1383                 }
1384         }
1385
1386 #if HAVE_MMAP
1387         f->size = pos;
1388 #else
1389         lseek(f->local_file, 0, SEEK_SET);
1390 #endif
1391
1392         globfree(&pglob);
1393 #if HAVE_MMAP
1394         return pos;
1395 #else
1396         return 0;
1397 #endif
1398 }
1399
1400 /*
1401  * cmd_noop():  Handles the NOOP command. Does nothing, doesn't even
1402  *              reset the timeout.
1403  */
1404 void cmd_noop(struct conn * const c)
1405 {
1406         numeric(c, 200, "NOOP command successful.");
1407 }
1408
1409 /*
1410  * cmd_syst():  Handles the SYST command. Returns the system identification.
1411  */
1412 void cmd_syst(struct conn * const c)
1413 {
1414         numeric(c, 215, "UNIX Type: L%u", NBBY);
1415 }
1416
1417 /*
1418  * cmd_type():  Handles the TYPE command.
1419  */
1420 void cmd_type(struct conn * const c)
1421 {
1422 #if WANT_ASCII
1423         c->recv_buf[0] &= (255-32);     /* convert to upper case */
1424         if (c->recv_buf[0] == 'A') {
1425                 c->ascii_mode = 1;
1426                 numeric(c, 200, "Type is ASCII.");
1427         } else if (c->recv_buf[0] == 'I') {
1428                 c->ascii_mode = 0;
1429                 numeric(c, 200, "Type is IMAGE.");
1430         } else {
1431                 numeric(c, 504, "Unknown type.");
1432         }
1433 #else
1434         numeric(c, 200, "TYPE ignored (always I)");
1435 #endif
1436 }
1437
1438 /*
1439  * cmd_mode():  Handles the MODE command. Only stream mode is supported.
1440  */
1441 void cmd_mode(struct conn * const c)
1442 {
1443         c->recv_buf[0] &= (255-32);     /* convert to upper case */
1444         if (c->recv_buf[0] == 'S') {
1445                 numeric(c, 200, "Mode is STREAM.");
1446         } else {
1447                 numeric(c, 504, "Unknown mode.");
1448         }
1449 }
1450
1451 /*
1452  * cmd_stru():  Handles the STRU command. Only file mode is supported.
1453  */
1454 void cmd_stru(struct conn * const c)
1455 {
1456         c->recv_buf[0] &= (255-32);     /* convert to upper case */
1457         if (c->recv_buf[0] == 'F') {
1458                 numeric(c, 200, "Structure is FILE.");
1459         } else {
1460                 numeric(c, 504, "Unknown structure.");
1461         }
1462 }
1463
1464 /*
1465  * cmd_help():  Handle the HELP command. I'm sorry, but I'm unwilling
1466  *              to use a lot of space to explain the RFCs in such a message,
1467  *              and BetaFTPD doesn't have any special things that should
1468  *              be noted anywhere. Thus, this message is close to empty. I
1469  *              feel that a 5xx entry would have been better, but that is
1470  *              disallowed.
1471  *
1472  *              As with ACCT, this command is supposed to be executed from
1473  *              everywhere, so we have to run without setuid. I don't like
1474  *              it, but at the same time I have to idea what could go
1475  *              wrong...
1476  *
1477  *              Perhaps I should make this message sound a little less
1478  *              like an error, since the error code is intended for helpful
1479  *              messages? :-)
1480  */
1481 void cmd_help(struct conn * const c)
1482 {
1483         numeric(c, 414, "Sorry, no detailed help; use standard FTP commands.");
1484 }
1485
1486 /*
1487  * cmd_quit():  Handles the QUIT command, which shuts down the control
1488  *              and data sockets.
1489  */
1490 void cmd_quit(struct conn * const c)
1491 {
1492         numeric(c, 221, "Have a nice day!");
1493         c->free_me = 1;
1494 }
1495
1496 /*
1497  * cmd_rein():  Handle the REIN command, which does close to a full reset
1498  *              of the connection. Much of the code here is intentionally
1499  *              copied directly from alloc_new_conn() -- perhaps we should
1500  *              modularize this?
1501  */
1502 void cmd_rein(struct conn * const c)
1503 {
1504         destroy_ftran(c->transfer);
1505         c->buf_len = c->auth = c->rest_pos = 0;
1506
1507         /* equals: strcpy(c->curr_dir, "/") ; strcpy(c->last_cmd, ""); */
1508         c->curr_dir[0] = '/';
1509 #if WANT_FULLSCREEN
1510         c->curr_dir[1] = c->last_cmd[0] = '\0';
1511 #else
1512         c->curr_dir[1] = '\0';
1513 #endif
1514
1515         time(&(c->last_transfer));
1516         numeric(c, 220, "BetaFTPD " VERSION " ready.");
1517 }
1518
1519 #if DOING_PROFILING
1520 /*
1521  * cmd_exit():  Handles the EXIT command, my own `extension' to the
1522  *              FTP protocol... IMPORTANT: Only to be used for profiling
1523  *              purposes!! (It's needed to get some profiling data out
1524  *              of the server after compiling it with -pg, since such data
1525  *              is only written on a clear exit()). Any user (even those
1526  *              not logged in) can issue an EXIT, and make the server shut
1527  *              down without clearing any sockets etc. In other words:
1528  *              Don't use it on a production site.
1529  */
1530 void cmd_exit(struct conn * const c)
1531 {
1532         while (first_conn->next_conn)
1533                 destroy_conn(first_conn->next_conn);
1534         exit(0);
1535 }
1536 #endif
1537
1538 /*
1539  * parse_command():
1540  *              Gets a command from c->recv_buf, determines which command
1541  *              it is, sets proper effective user-ID and calls the command
1542  *              handler. Finally, it cleans up.
1543  *
1544  *              To me, this command seems optimizable, but I'm not really
1545  *              sure where :-)
1546  */
1547 void parse_command(struct conn *c)
1548 {
1549         int cmlen;
1550         const struct handler *h = handler_table;        /* first entry */
1551
1552         if (c == NULL) return;
1553
1554         /* strip any leading non-ASCII characters (including CR/LFs) */
1555         while (c->buf_len > 0 && (c->recv_buf[0] < 'a' || c->recv_buf[0] > 'z')
1556                               && (c->recv_buf[0] < 'A' || c->recv_buf[0] > 'Z')) {
1557                 remove_bytes(c, 1);             /* not good */
1558         }
1559
1560         /* scan, searching for CR or LF */      
1561         cmlen = strcspn(c->recv_buf, "\r\n");
1562         if (cmlen >= c->buf_len) return;
1563
1564 #if WANT_FULLSCREEN
1565         strncpy(c->last_cmd, c->recv_buf, cmlen);
1566         c->last_cmd[cmlen] = 0;
1567 #endif
1568
1569         do {
1570                 if ((cmlen >= (strlen(h->cmd_name) + h->add_cmlen)) &&
1571                     (strncasecmp(c->recv_buf, h->cmd_name, strlen(h->cmd_name)) == 0)) {
1572                         if (c->auth < h->min_auth) {
1573                                 numeric(c, 503, "Please login with USER and PASS.");
1574                                 while (c->recv_buf[0] != '\n') remove_bytes(c, 1);
1575                         } else {
1576                                 char schar;
1577
1578 #if !WANT_NONROOT
1579                                 if (h->do_setuid) {
1580                                         setegid(c->gid);
1581                                         seteuid(c->uid);
1582                                 } else {
1583                                         seteuid(getuid());
1584                                         setegid(getgid());
1585                                 }
1586 #endif
1587
1588                                 remove_bytes(c, strlen(h->cmd_name));
1589                                 cmlen -= strlen(h->cmd_name);
1590                                 while (c->recv_buf[0] == ' ') {
1591                                         remove_bytes(c, 1);
1592                                         cmlen--;
1593                                 }
1594
1595                                 schar = c->recv_buf[cmlen];
1596                                 c->recv_buf[cmlen] = 0;
1597                                 
1598                                 message_buf[0] = '\0';
1599                                 h->callback(c);
1600                                 if (message_buf[0] != '\0') {
1601                                         /* send any feedback we might have */
1602                                         int err = send(c->sock, message_buf, strlen(message_buf), 0);
1603                                         if (err == -1 && errno == EPIPE) {
1604                                                 c->free_me = 1;
1605                                         }
1606                                 }       
1607                                 
1608                                 if (c->free_me) {
1609                                         destroy_conn(c);
1610                                 } else {
1611                                         c->recv_buf[cmlen] = schar;
1612 #if !WANT_NONROOT
1613                                         if (h->do_setuid) {
1614                                                 seteuid(getuid());
1615                                                 setegid(getgid());
1616                                         }
1617 #endif
1618                                         remove_bytes(c, cmlen);
1619                                 }
1620                         }
1621                         return;
1622                 }
1623         } while ((++h)->callback != NULL);
1624
1625         numeric(c, 500, "Sorry, no such command.");
1626         remove_bytes(c, cmlen); 
1627 }
1628
1629 /*
1630  * prepare_for_transfer():
1631  *              Prepares an ftran object for a file transfer, setting
1632  *              file size, opening sockets etc.
1633  *
1634  *              nonroot notice: prepare_for_transfer() assumes all access
1635  *              checks are already done.
1636  */
1637 void prepare_for_transfer(struct ftran *f)
1638 {
1639 #if WANT_NONROOT
1640 #warning No nonroot checking for prepare_for_transfer() yet
1641 #endif
1642
1643 #if HAVE_MMAP
1644         /* mmap doesn't make temp files for dir listings */
1645         if (!f->dir_listing) {
1646 #endif
1647
1648                 f->size = lseek(f->local_file, 0, SEEK_END);
1649                 errno = 0;
1650 #if WANT_UPLOAD
1651                 if (f->upload == 0 || f->append == 0 || f->owner->rest_pos != 0)
1652 #endif 
1653                         lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1654 #if HAVE_MMAP
1655         }
1656 #endif
1657         
1658         if (f->state == 1) {            /* PASV connection */
1659                 f->state = 2;           /* waiting */
1660         } else if (f->state == 3) {     /* PORT connection */
1661                 f->state = 4;
1662                 connect(f->sock, (struct sockaddr *)&f->sin, sizeof(f->sin));
1663                 add_fd(f->sock, POLLOUT);
1664         }
1665         time(&(f->tran_start));
1666 }
1667
1668 /*
1669  * decode_mode():
1670  *              Takes a mode_t argument (from a `struct stat'), and
1671  *              returns the proper dirlist letter for that type.
1672  *
1673  *              Note: S_IFLNK seems to be broken, or perhaps I just have
1674  *              missed something (S_IFLNK is always set for all *files* on
1675  *              my glibc 2.0.111 system).
1676  *
1677  *              The most common cases are put first, for speed :-)
1678  */
1679 char decode_mode(mode_t mode) {
1680         if (S_ISREG(mode))  return '-';
1681         if (S_ISDIR(mode))  return 'd';
1682         if (S_ISLNK(mode))  return 'l';
1683         if (S_ISBLK(mode))  return 'b';
1684         if (S_ISCHR(mode))  return 'c';
1685         if (S_ISSOCK(mode)) return 's';
1686         if (S_ISFIFO(mode))  return 'f';
1687
1688         return '-';
1689 }
1690
1691 /*
1692  * translate_path():
1693  *              Take an FTP path, do all neccessary root_dir checks,
1694  *              change to the correct directory and return the proper
1695  *              file name to open/stat/whatever. The path returned is
1696  *              relative to the current directory (NOT absolute). chdir()
1697  *              in any way will `destroy' this argument.
1698  *
1699  *              Note that `path' will be _changed_, and used as a return pointer
1700  *              base. Do not attempt to free the result from this function --
1701  *              if you need to, free path instead.
1702  */
1703 char *translate_path(struct conn * const c, char * const path)
1704 {
1705         char *ptr = NULL;
1706
1707         /* chdir to the right dir, then chop it off */
1708         chdir(c->curr_dir);
1709
1710         ptr = strrchr(path, '/');
1711         if (ptr != NULL) {
1712                 char save_char = ptr[0];
1713                 ptr[0] = 0;
1714
1715                 if (do_chdir(c, path) == -1) {
1716                         return NULL;
1717                 }
1718                 ptr[0] = save_char;
1719                 ptr++;
1720         } else {
1721                 ptr = path;
1722         }
1723         return ptr;
1724 }
1725
1726 /*
1727  * do_openfile():
1728  *              Opens the file PATH with access parameters FLAGS, translating
1729  *              paths and checking permissions as neccessary. Generally, this
1730  *              should be used whenever you need an open().
1731  *
1732  *              The parameters might be a bit confusing. To clarify them a bit:
1733  *              c:              IN/OUT (will be changed)
1734  *              path:           IN (but _will_ be changed)
1735  *              filename:       OUT
1736  *              flags:          IN
1737  *              check_perm:     IN
1738  */
1739 int do_openfile(struct conn * const c, char * const path,
1740                 char * const filename, const int flags
1741 #if WANT_NONROOT
1742                 , const int check_permission
1743 #endif
1744 )
1745 {
1746         char *ptr;
1747         struct stat buf;
1748
1749 #if WANT_NONROOT
1750         if (nr_check_permission(c->uid, path, check_permission, 0, NULL) == -1) {
1751                 return -1;
1752         }
1753 #endif
1754
1755         ptr = translate_path(c, c->recv_buf);
1756         if (ptr == NULL) return -1;
1757
1758 #if WANT_UPLOAD
1759         if ((flags & O_CREAT) == 0) {
1760 #endif
1761                 TRAP_ERROR(stat(ptr, &buf) == -1, 550, return -2);
1762                 if (!S_ISREG(buf.st_mode)) {
1763                         numeric(c, 550, "Not a plain file.", ptr);
1764                         return -2;
1765                 }
1766 #if WANT_UPLOAD
1767         }
1768 #endif
1769
1770         if (filename != NULL) { /* filename should always be != NULL */
1771                 strcpy(filename, ptr);
1772         }
1773         return open(ptr, flags, 0666);
1774 }
1775
1776 /*
1777  * prepare_for_listing():
1778  *              Parse list options, put them back into the list_options
1779  *              structure lo, and make temporary room for the list.
1780  */
1781 int prepare_for_listing(struct conn * const c, char ** const ptr,
1782                         struct list_options * const lo)
1783 {
1784 #if !HAVE_MMAP
1785         char *tfname;
1786 #endif
1787         struct ftran *f = c->transfer;
1788         char *tmp;
1789         char *optr = NULL, *fptr = NULL; 
1790 #if WANT_NONROOT
1791         char chd[512];
1792 #endif
1793
1794 #if WANT_NONROOT
1795 #warning No nonroot checking for prepare_for_listing() yet
1796 #endif
1797
1798         if ((f == NULL) || ((f->state != 1) && (f->state != 3))) {
1799                 numeric(c, 425, "No data connection set up; please use PASV or PORT.");
1800                 return -1;
1801         }
1802
1803         /*
1804          * A little parameter scanning is required here. There can only
1805          * be two parts: the directory name, and any options. We'll find
1806          * any options first.
1807          */
1808         if (c->recv_buf[0] == '-') {
1809                 optr = c->recv_buf;
1810         } else {
1811                 optr = strstr(c->recv_buf, " -");
1812         }
1813
1814         /* Then see if there are any options to parse. */
1815         if (optr != NULL) {
1816                 while (*++optr) {
1817                         switch (*optr & (255-32)) {     /* uppercase */
1818                         case 'R':       /* actually case sensitive... */
1819                                 lo->recursive = 1;
1820                                 break;
1821                         case 'L':
1822                                 lo->long_listing = 1;
1823                                 break;
1824                         case 'F':
1825                                 lo->classify = 1;
1826                                 break;
1827                         case '\0':
1828                                 fptr = optr + 1;
1829                                 *(optr--) = 0;
1830                                 break;
1831                         default:
1832                                 break;
1833                         }
1834                 }
1835         } else {
1836                 fptr = c->recv_buf;
1837         }
1838
1839         /* then we chdir to the dir in fptr (if any) */
1840         tmp = fptr ? strrchr(fptr, '/') : NULL;
1841         if (tmp != NULL) {
1842                 tmp[0] = 0;
1843                 if (do_chdir(c, fptr) == -1) return -1;
1844                 fptr = tmp + 1;
1845         } else {
1846                 /* current directory */
1847                 TRAP_ERROR(chdir(c->curr_dir) == -1, 550, return -1);
1848         }
1849
1850         /* if no argument, choose all files */
1851         if (fptr == NULL || fptr[0] == 0) {
1852                 fptr = "*";
1853         } else {
1854                 /* we need to check if the last part is a directory (no -d switch) */
1855                 struct stat buf;
1856                 if (stat(fptr, &buf) == 0 && S_ISDIR(buf.st_mode)) {
1857                         TRAP_ERROR(chdir(fptr) == -1, 550, return -1);
1858                         fptr = "*";
1859                 }
1860         }
1861         *ptr = fptr;
1862
1863 #if WANT_NONROOT
1864         getcwd(chd, 512);
1865         if (nr_check_permission(c->uid, chd, 4, 1, NULL) == -1) {
1866                 numeric(c, 550, "Permission denied");
1867                 return -1;
1868         }
1869 #endif
1870
1871 #if !HAVE_MMAP
1872         tfname = tempnam(NULL, "ftp");
1873
1874 #if WANT_NONROOT
1875         if (tfname == NULL) tfname = tempnam("/", "ftp");
1876 #endif
1877
1878         TRAP_ERROR(tfname == NULL, 550, return -1);
1879         strcpy(f->filename, tfname);
1880         free(tfname);
1881
1882         f->local_file = open(f->filename, O_RDWR | O_CREAT | O_TRUNC, 0666);
1883         TRAP_ERROR(f->local_file == -1, 550, return -1);
1884 #endif
1885         f->dir_listing = 1;
1886 #if WANT_UPLOAD
1887         f->upload = 0;
1888 #endif
1889
1890         return 0;
1891 }
1892
1893 /*
1894  * classify():  Takes a mode_t argument (from `struct stat'), and returns
1895  *              the parameter to be used in an `ls -F'-style listing.
1896  */
1897 char classify(const mode_t mode)
1898 {
1899         if (S_ISREG(mode)) {
1900                 if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
1901                         return '*';
1902                 } else {
1903                         return '\0';
1904                 }
1905         }
1906         if (S_ISDIR(mode)) return '/';
1907         if (S_ISLNK(mode)) return '@';
1908         if (S_ISSOCK(mode)) return '=';
1909         if (S_ISFIFO(mode)) return '|';
1910         return '\0'; 
1911 }