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