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