1 /* cmds.c: BetaFTPD command handlers
2 Copyright (C) 1999-2000 Steinar H. Gunderson
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.
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.
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.
29 #include <sys/types.h>
85 #include <sys/ioctl.h>
93 #include <sys/param.h>
101 #include <sys/conf.h>
109 #include <sys/filio.h>
113 #include <sys/poll.h>
138 extern struct conn *first_conn;
140 extern struct dcache *first_dcache;
144 extern struct pollfd fds[];
146 extern fd_set master_fds, master_send_fds;
151 char add_cmlen; /* =1 if the command takes an argument */
152 void (*callback)(struct conn * const);
155 char do_setuid; /* =1 if root is not *really* needed */
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 },
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 },
198 { "stor ", 1, cmd_stor, 3 DO_SETUID },
199 { "appe ", 1, cmd_appe, 3 DO_SETUID },
202 #warning Use DOING_PROFILING with caution, and NEVER on a production server! :-)
203 { "exit", 0, cmd_exit, 0 NO_SETUID },
205 { "" , 0, NULL, 0 NO_SETUID }
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 :-)
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.
217 int do_chdir(struct conn * const c, const char * const newd)
219 char chd[512], temp[512];
221 TRAP_ERROR(chdir(c->curr_dir) == -1, 550, return -1);
223 /* handle `absolute' paths */
224 if (newd[0] == '/' || newd[0] == '\0') {
225 strcpy(temp, c->root_dir);
228 * is this the root directory? if not, remove the trailing `/'
229 * and concatenate the new directory on
231 if (newd[1] != '\0' && newd[0] != '\0') {
232 temp[strlen(temp) - 1] = 0;
240 if (nr_check_permission(c->uid, temp, 1, 1, NULL) == -1) {
241 numeric(c, 550, "Permission denied");
246 TRAP_ERROR(chdir(temp) == -1, 550, return -1);
249 if (chd[strlen(chd) - 1] != '/') {
253 if (strncmp(chd, c->root_dir, strlen(c->root_dir)) != 0) {
254 numeric(c, 550, "No such file or directory.");
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...
266 void cmd_user(struct conn * const c)
268 strncpy(c->username, c->recv_buf, 16);
271 if (strcasecmp(c->username, "anonymous") == 0) {
272 strcpy(c->username, "ftp");
274 if (strcasecmp(c->username, "ftp") == 0) {
275 numeric(c, 331, "Login OK, send password (your e-mail).");
278 numeric(c, 331, "Password required for %s.", c->username);
284 * cmd_pass(): Handles the PASS command, and checks the password.
285 * This function is rather long and complicated, mostly
286 * because there are so many ways of doing users
287 * (including my nonroot system) out there... And we
288 * don't even support PAM or real shadow passwords (with
291 void cmd_pass(struct conn * const c)
294 c->auth = nr_userinfo(c->username, &c->uid, c->curr_dir, c->root_dir,
296 #else /* !WANT_NONROOT */
297 #if WANT_SHADOW && HAVE_SHADOW_H
302 p = getpwnam(c->username);
303 #if WANT_SHADOW && HAVE_SHADOW_H
304 s = getspnam(c->username);
312 strncpy(c->curr_dir, p->pw_dir, 254);
313 c->curr_dir[254] = 0;
317 if (c->curr_dir[strlen(c->curr_dir) - 1] != '/') {
318 strcat(c->curr_dir, "/");
320 strcpy(c->root_dir, c->curr_dir);
322 } else if (c->auth != 0) {
323 strcpy(c->root_dir, "/");
324 if (strcmp(crypt(c->recv_buf, p->pw_passwd), p->pw_passwd) != 0
325 #if WANT_SHADOW && HAVE_SHADOW_H
326 && (s == NULL || strcmp(crypt(c->recv_buf, s->sp_pwdp), s->sp_pwdp) != 0)
334 #endif /* !WANT_NONROOT */
336 /* root should not be allowed to FTP */
341 numeric(c, 530, "Login incorrect.");
345 dump_file(c, 230, "welcome.msg");
347 /* Have a different message for anonymous users? */
348 numeric(c, 230, "User logged in.");
353 * cmd_acct(): Handle (ignore) the ACCT command. I don't see how we
354 * could make use of this command... wu-ftpd doesn't, either.
355 * However, wu-ftpd (at least the version I have here) uses
356 * 502, which isn't a legal error code according to RFC959.
357 * 202, on the other hand, is, and seems to be applicable.
359 * I'm unsure if this one should require setuid or not, but
360 * I feel that the RFC959 intention is having it _before_
361 * USER/PASS. Therefore, this one runs with root privilegies :-)
363 void cmd_acct(struct conn * const c)
365 numeric(c, 202, "ACCT ignored OK -- not applicable on this system.");
369 * cmd_port(): Handles the PORT command, and sets up the data socket.
370 * Making a brief uid=0 (root) appearance (to bind the socket) --
371 * I feel it's safer that way (instead of running as root
372 * the whole way), in case there are some weird overflows
375 void cmd_port(struct conn * const c)
377 short int a0, a1, a2, a3, p0, p1;
380 struct sockaddr_in sin;
382 if ((c->transfer != NULL) && (c->transfer->state >= 4)) {
383 numeric(c, 500, "Sorry, only one transfer at a time.");
387 sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
388 TRAP_ERROR(sock == -1, 500, return);
390 destroy_ftran(c->transfer);
391 c->transfer = f = alloc_new_ftran(sock, c);
393 i = sscanf(c->recv_buf, "%3hu,%3hu,%3hu,%3hu,%3hu,%3hu", &a0, &a1, &a2, &a3, &p0, &p1);
395 numeric(c, 501, "Parse error.");
400 /* bind to own address, port 20 (FTP data) */
402 err = getsockname(c->sock, (struct sockaddr *)&sin, &tmp);
403 TRAP_ERROR(err == -1, 500, return);
404 sin.sin_port = FTP_PORT - 1;
406 numeric(c, 200, "PORT command OK.");
408 /* note that bind() might well fail, so we don't error check */
410 /* need root privilegies for a short while */
414 bind(sock, (struct sockaddr *)&sin, sizeof(sin));
420 f->sin.sin_family = AF_INET;
421 f->sin.sin_addr.s_addr = htonl(
422 ((unsigned char)(a0) << 24) +
423 ((unsigned char)(a1) << 16) +
424 ((unsigned char)(a2) << 8) +
425 ((unsigned char)(a3) ));
426 f->sin.sin_port = htons(
427 ((unsigned char)(p0) << 8) +
428 ((unsigned char)(p1) ));
433 ioctl(f->sock, FIONBIO, &one);
438 * cmd_pasv(): Handles the PASV command, and sets up the data socket.
439 * Uses port numbers > 1024, since it doesn't run as root.
441 void cmd_pasv(struct conn * const c)
445 unsigned int one = 1;
446 struct sockaddr_in addr;
448 if ((c->transfer != NULL) && (c->transfer->state >= 4)) {
449 numeric(c, 503, "Sorry, only one transfer at once.");
452 destroy_ftran(c->transfer);
454 sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
455 TRAP_ERROR(sock == -1, 500, return);
456 err = add_fd(sock, POLLIN);
457 TRAP_ERROR(err != 0, 501, return);
459 c->transfer = f = alloc_new_ftran(sock, c);
461 ioctl(sock, FIONBIO, &one);
465 err = getsockname(c->sock, (struct sockaddr *)&addr, &tmp);
466 TRAP_ERROR(err == -1, 500, return);
468 addr.sin_port = 0; /* let the system choose */
469 err = bind(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr));
470 TRAP_ERROR(err == -1, 500, return);
473 err = getsockname(sock, (struct sockaddr *)&addr, &tmp);
474 TRAP_ERROR(err == -1, 500, return);
476 err = listen(f->sock, 1);
477 TRAP_ERROR(err == -1, 500, return);
480 numeric(c, 227, "Entering passive mode (%u,%u,%u,%u,%u,%u)",
481 (htonl(addr.sin_addr.s_addr) & 0xff000000) >> 24,
482 (htonl(addr.sin_addr.s_addr) & 0x00ff0000) >> 16,
483 (htonl(addr.sin_addr.s_addr) & 0x0000ff00) >> 8,
484 (htonl(addr.sin_addr.s_addr) & 0x000000ff),
485 (htons(addr.sin_port) & 0xff00) >> 8,
486 (htons(addr.sin_port) & 0x00ff));
490 * cmd_pwd(): Handles PWD command (print working directory).
492 * Note that if somebody contacts you with the message `the server
493 * says curr_dir() is outside root_dir()', you should fix your
494 * /betaftpd.users file, if you use nonroot. If not, it's a bug.
495 * Try to get it _reproducible_, and mail it to me.
497 void cmd_pwd(struct conn * const c)
499 char temp[512], *cdir = NULL;
501 cdir = do_pwd(c, temp, c->curr_dir);
503 numeric(c, 257, "\"%s\" is current working directory.", cdir);
508 * do_pwd(): Translates an absolute path to a path suitable for viewing
509 * to the user (ie. removes the root_dir, and removes a trailing
510 * slash if it exists). Note that the retbuf is only used as a
511 * storage place -- the pointer to the right place within retbuf
514 char *do_pwd(struct conn * const c, char * const retbuf, const char * const dir)
520 if (strncmp(retbuf, c->root_dir, strlen(c->root_dir)) != 0) {
521 numeric(c, 550, "curr_dir is outside root_dir, please contact site administrator.");
525 cdir = retbuf + strlen(c->root_dir) - 1;
526 if (cdir[strlen(cdir) - 1] == '/' && strlen(cdir) > 1) {
527 cdir[strlen(cdir) - 1] = 0;
528 } else if (strlen(cdir) == 0) {
536 * cmd_cwd(): Handles CWD command (change working directory). Uses
537 * cmd_cwd_internal() (see below).
539 void cmd_cwd(struct conn * const c)
541 cmd_cwd_internal(c, c->recv_buf);
545 * cmd_cdup(): Handles a CDUP command (identical to `CWD ..'). Note that
546 * RFC959 gives two different response codes (250 and 200) --
547 * 250 is the same as CWD gives, which sounds logical to me.
548 * wu-ftpd uses it as well.
550 * Note that using a CDUP to try to get outside root_dir returns
551 * an error, instead of just staying in the root directory (as
552 * the OS and thus wu-ftpd does).
554 void cmd_cdup(struct conn * const c)
556 cmd_cwd_internal(c, "..");
560 * cmd_cwd_internal():
561 * Does the work for CWD and CDUP (modularized to save some
562 * space and have clearer code). Mostly, it just uses do_chdir(),
563 * and sees where that takes us. It adds a trailing slash if needed.
565 void cmd_cwd_internal(struct conn * const c, const char * const newd)
567 if (do_chdir(c, newd) != -1) {
570 getcwd(c->curr_dir, 254);
571 i = strlen(c->curr_dir);
572 if (c->curr_dir[i - 1] != '/') {
573 c->curr_dir[i++] = '/';
574 c->curr_dir[i] = '\0';
578 dump_file(c, 250, ".message");
582 numeric(c, 250, "CWD successful.");
587 * cmd_rest(): Handles the REST command. All it does is tell the file
588 * sending functions to start at the correct number. We should
589 * perhaps add some better error checking to this?
591 void cmd_rest(struct conn * const c)
593 c->rest_pos = abs(atoi(c->recv_buf));
594 numeric(c, 350, "Setting resume at %u bytes.", c->rest_pos);
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.
604 void cmd_retr(struct conn * const c)
606 struct ftran *f = c->transfer;
608 if ((f == NULL) || ((f->state != 1) && (f->state != 3))) {
609 numeric(c, 425, "No data connection set up; please use PASV or PORT.");
614 if ((c->rest_pos > 0) && (c->ascii_mode == 1)) {
615 numeric(c, 500, "Cannot resume while in ASCII mode.");
620 f->local_file = do_openfile(c, c->recv_buf, f->filename, O_RDONLY
627 if (f->local_file == -1) {
628 numeric(f->owner, 550, strerror(errno));
630 } else if (f->local_file == -2) {
637 prepare_for_transfer(f);
643 * cmd_stor(): Handles the STOR command (upload file). Pushes the
644 * work down to do_store(), below.
646 void cmd_stor(struct conn * const c)
652 * cmd_appe(): Handles the APPE command (append to file). Pushes
653 * the work down to do_store(), below.
655 void cmd_appe(struct conn * const c)
661 * do_store(): Initiate an upload. Most of the comments to do_retr()
662 * (above) apply to this one as well.
664 void do_store(struct conn * const c, const int append)
666 struct ftran *f = c->transfer;
668 if ((f == NULL) || ((f->state != 1) && (f->state != 3))) {
669 numeric(c, 425, "No data connection set up; please use PASV or PORT.");
674 if ((c->rest_pos > 0) && (c->ascii_mode == 1)) {
675 numeric(c, 500, "Cannot resume while in ASCII mode.");
680 f->local_file = do_openfile(c, c->recv_buf, f->filename, O_WRONLY |
681 O_CREAT | ((append || c->rest_pos > 0) ? 0 : O_TRUNC)
688 if (f->local_file == -1) {
689 numeric(f->owner, 550, strerror(errno));
690 } else if (f->local_file == -2) {
696 f->ascii_mode = c->ascii_mode;
698 prepare_for_transfer(f);
701 #endif /* WANT_UPLOAD */
704 * cmd_size(): Handle the SIZE command -- returns the size of a
705 * file. Note that this command is not part of RFC959,
706 * and thus there is no clear specification (except
707 * for some ftpext documents, which we try to follow
708 * as closely as we can). BetaFTPD deviates from wu-ftpd
709 * in that it lets you check the `size' of directories
710 * as well (instead of giving 550). This is _not_ the
711 * size of all the files in the directory, rather how
712 * much space the directory inode uses.
714 void cmd_size(struct conn * const c)
718 numeric(c, 550, "SIZE not available in ASCII mode.");
723 const char * const fname = translate_path(c, c->recv_buf);
726 TRAP_ERROR(fname == NULL || lstat(fname, &buf) == -1, 550, return);
728 numeric(c, 213, "%lu", (unsigned long)(buf.st_size));
733 * cmd_mdtm(): Handle the MDTM command -- returns the modification
734 * date/time of a file. See the comments on cmd_size(),
737 void cmd_mdtm(struct conn * const c)
739 const char * const fname = translate_path(c, c->recv_buf);
743 TRAP_ERROR(fname == NULL || lstat(fname, &buf) == -1, 550, return);
745 m = gmtime(&(buf.st_mtime)); /* at least wu-ftpd does it in GMT */
746 numeric(c, 213, "%u%02u%02u%02u%02u%02u", m->tm_year + 1900,
747 m->tm_mon + 1, m->tm_mday, m->tm_hour, m->tm_min, m->tm_sec);
751 * cmd_abor(): Handle the ABOR command (abort a file transfer). This should
752 * be clean enough, but isn't tested extensively.
754 void cmd_abor(struct conn * const c)
756 if (c->transfer != NULL) {
757 numeric(c, 426, "File transfer aborted.");
758 destroy_ftran(c->transfer);
760 numeric(c, 226, "ABOR command processed OK.");
764 * cmd_dele(): Handle the DELE command (delete a file).
766 void cmd_dele(struct conn * const c)
768 const char * const fname = translate_path(c, c->recv_buf);
770 TRAP_ERROR(fname == NULL || unlink(fname) == -1, 550, return);
771 numeric(c, 250, "File deleted OK.");
775 * cmd_rnfr(): Handle the RNFR command (take a filename to rename from).
777 void cmd_rnfr(struct conn * const c)
779 const char * const fname = translate_path(c, c->recv_buf);
783 c->rename_from[0] = '\0';
784 if (fname == NULL) return;
787 snprintf(c->rename_from, 256, "%s/%s", cwd, fname);
789 /* Just check that the file exists. */
790 TRAP_ERROR(lstat(c->rename_from, &buf) == -1, 550, c->rename_from[0] = '\0'; return);
792 numeric(c, 350, "File exists, send RNTO.");
796 * cmd_rnto(): Handle the RNTO command (do the actual renaming).
798 void cmd_rnto(struct conn * const c)
800 const char * const fname = translate_path(c, c->recv_buf);
802 if (fname == NULL) return;
803 if (c->rename_from[0] == '\0') {
804 numeric(c, 503, "Please send RNFR first.");
808 TRAP_ERROR(rename(c->rename_from, fname) == -1, 550, c->rename_from[0] = '\0'; return);
809 c->rename_from[0] = '\0';
811 numeric(c, 250, "File renamed successfully.");
815 * cmd_mkd(): Handle the MKD/XMKD command (create a new directory).
816 * RFC959 is not clear on the error codes for this command --
817 * one place, 521 is cited as the correct error, but is
818 * mentioned nowhere else. Different FTP servers differ here
819 * as well. Thus, I've followed what appears to be the intention
820 * (having `analogous' errors with STOR), and use 550 instead.
822 * Making directories is probably the topic covered most
823 * extensively by RFC959 (and in the most confusing way as
824 * well). I try to follow the conventions, but it isn't always
825 * easy :-) (This code isn't quite easy to understand, because
826 * temp2 is used twice, in two different roles.)
828 void cmd_mkd(struct conn * const c)
830 const char * const fname = translate_path(c, c->recv_buf);
831 char temp[512], temp2[1024], *cdir;
834 TRAP_ERROR(fname == NULL || mkdir(fname, 0755) == -1, 550, return);
838 cdir = do_pwd(c, temp, temp2);
840 if (do_pwd == NULL) return;
842 /* double the quotes in the output */
843 for (i = 0, j = 0; i <= strlen(cdir); i++, j++) {
845 if (cdir[i] == '"') {
849 numeric(c, 257, "\"%s\" created.", temp2);
853 * cmd_rmd(): Handle the RMD/XRMD command. Works just like DELE, only for
856 void cmd_rmd(struct conn * const c)
858 const char * const fname = translate_path(c, c->recv_buf);
860 TRAP_ERROR(fname == NULL || rmdir(fname) == -1, 550, return);
861 numeric(c, 250, "Directory deleted.");
865 * cmd_allo(): Handle the ALLO command. The command does not do anything, except
866 * sit around and play compliant. Some Windows FTP servers (Serv-U,
867 * for instance), verifies that there is enough space on the disk,
868 * but since we have no idea on what the filesystem will be stored on,
869 * we just ignore the command.
871 * We could theoretically use this information to give more information
872 * to the full-screen mode, but close to no FTP clients send this
873 * command, and it would touch too much code.
875 void cmd_allo(struct conn * const c)
877 numeric(c, 202, "No storage allocation necessary.");
881 * cmd_stat(): Handle the STAT command. Please see README for more details.
882 * Note that this command is run with euid=root, since it has
883 * to be able to run before USER.
885 * Note that we need to bypass numeric(), to get a multi-line
889 char conn_state[5][27] = {
891 "Waiting for e-mail address",
892 "Waiting for password",
894 "Logged in", /* non-anonymous */
897 char ftran_state[6][42] = {
899 "Decided PASV address/port",
900 "Waiting on PASV socket",
901 "Got PORT address/port",
902 "Connecting on PORT address/port",
903 "Transferring file (or connecting on PORT)"
907 void cmd_stat(struct conn * const c)
912 struct ftran *f = c->transfer;
914 snprintf(buf, 1024, "211- FTP server status:\r\n"
915 " BetaFTPD version " VERSION " (http://members.xoom.com/sneeze/betaftpd.html)\r\n"
916 " Connected to %s\r\n"
917 " Control connection state: %s\r\n"
919 " TYPE: %s; STRUcture: File; transfer MODE: Stream\r\n"
921 " TYPE: Image; STRUcture: File; transfer MODE: Stream\r\n"
923 " Data connection state: %s\r\n"
924 "211 End of status\r\n",
925 inet_ntoa(((struct sockaddr_in *)(&(c->addr)))->sin_addr),
928 (c->ascii_mode == 1) ? "ASCII, FORM: Nonprint" : "Image",
930 (f) ? ftran_state[f->state] : ftran_state[0]);
934 err = send(c->sock, buf, i, 0);
935 if (err == -1 && errno == EPIPE) {
939 numeric(c, 502, "STAT command disabled for security reasons.");
945 * _mwrite(): This define is for mmap-listing. It works as a write()
946 * (not in parameter, but in function), and is used in
947 * cmd_list() and cmd_nlst() only.
949 * Note that this function returns the new position in the
950 * `file'. The caller is expected to send this information
951 * back in `pos' at the next call to _mwrite().
953 int _mwrite(const char * const buf, const struct ftran * const f,
954 const int pos, const int count, const int size)
956 if (pos + count >= size) return size; /* out of space */
957 memcpy(f->file_data + pos, buf, count);
963 * mwrite: This is a short_hand define, making calls to _mwrite() very
964 * similiar to calls to write(). It works both with and without
968 #define mwrite(buf, count) pos = _mwrite((buf), (f), (pos), (count), (size));
970 #define mwrite(buf, count) write(f->local_file, buf, count);
975 * Formats output in `ls -l' style. It returns one line for the
976 * file PATHNAME, and returns it in retbuf. Setting do_classify
977 * to nonzero has the same effect as `ls -F'.
979 * This command is so long, because simply there is so much to
980 * be done. GNU ls has some extra functions, but it's close to
983 int long_listing(char * const retbuf, const char * const pathname, const int do_classify)
986 char newd[512], temp[1026];
990 char username[17], groupname[17];
993 year = localtime(&now)->tm_year;
1000 if (lstat(pathname, &buf) == -1) return 0;
1003 strcpy(username, nr_get_uname(buf.st_uid));
1004 strcpy(groupname, nr_get_gname(buf.st_gid));
1006 p = getpwuid(buf.st_uid);
1008 strncpy(username, p->pw_name, 16);
1011 snprintf(username, 16, "%u", buf.st_uid);
1014 g = getgrgid(buf.st_gid);
1016 strncpy(groupname, g->gr_name, 16);
1019 snprintf(groupname, 16, "%u", buf.st_gid);
1025 * This POSIX approximation is based on GNU ls code (and obfuscated
1026 * a bit...), to be compatible with `real' ls implementations.
1028 t = localtime(&(buf.st_mtime));
1029 strftime(newd, 512, ((now > buf.st_mtime + 6L * 30L * 24L * 60L * 60L) ||
1030 (now < buf.st_mtime - 60L * 60L))
1031 ? "%b %e %Y" : "%b %e %H:%M", t);
1037 if (nr_check_permission(0, pathname, 0, (S_ISDIR(buf.st_mode)), rights) == -1) {
1038 /* no permission to even see this file */
1042 snprintf(temp, 1024, "%c%s %3u %-8s %-8s %8lu %12s %s\r\n",
1044 snprintf(temp, 1024, "%c%c%c%c%c%c%c%c%c%c %3u %-8s %-8s %8lu %12s %s",
1046 decode_mode(buf.st_mode),
1050 (buf.st_mode & S_IRUSR) ? 'r' : '-',
1051 (buf.st_mode & S_IWUSR) ? 'w' : '-',
1052 (buf.st_mode & S_IXUSR) ? ((buf.st_mode & S_ISUID) ? 's' : 'x') : '-',
1053 (buf.st_mode & S_IRGRP) ? 'r' : '-',
1054 (buf.st_mode & S_IWGRP) ? 'w' : '-',
1055 (buf.st_mode & S_IXGRP) ? ((buf.st_mode & S_ISGID) ? 's' : 'x') : '-',
1056 (buf.st_mode & S_IROTH) ? 'r' : '-',
1057 (buf.st_mode & S_IWOTH) ? 'w' : '-',
1058 (buf.st_mode & S_IXOTH) ? ((buf.st_mode & S_ISVTX) ? 't' : 'x') : '-',
1060 buf.st_nlink, username, groupname,
1061 (unsigned long)(buf.st_size), newd, pathname);
1066 * vim needs this extra character for some reason... It's too
1067 * bad I'll have to do it this way, but syntax colouring
1068 * that works properly is almost a `must' for me :-)
1073 /* add an extra classification `sign' if we got -F */
1075 int len = strlen(temp);
1076 temp[len] = classify(buf.st_mode);
1077 temp[len + 1] = '\0';
1081 strcpy(retbuf, temp);
1085 * cmd_list(): Handles the LIST command (directory listing). Does a
1086 * long listing (of type `ls -l'). The listing work is
1087 * done by do_listing(), below.
1089 void cmd_list(struct conn * const c)
1091 struct list_options lo;
1094 lo.long_listing = 1;
1101 * cmd_nlst(): Handles the NLST command (plain directory listing).
1102 * Does a plain listing (no dates etc.), unless overridden
1103 * by the `-l' or `-L' flag (case insensitivity because most
1104 * FTP clients don't have a clue about what they send out).
1105 * The listing work is done by do_listing(), below.
1107 void cmd_nlst(struct conn * const c)
1109 struct list_options lo;
1112 lo.long_listing = 0;
1120 * Prepares any listing buffers, temp files, etc., before
1121 * pushing the work one step further :-)
1123 * If the directory listing cache is enabled, the cache
1124 * is checked first, to see if we still have a valid entry.
1126 void do_listing(struct conn * const c, struct list_options * const lo)
1133 struct ftran * const f = c->transfer;
1140 #warning No nonroot checking for list_core() yet
1143 i = prepare_for_listing(c, &ptr, lo);
1145 destroy_ftran(c->transfer);
1154 strcpy(f->filename, "(directory listing)");
1159 struct dcache *d = find_dcache(cwd, ptr, lo);
1163 f->file_data = d->dir_data;
1164 f->size = d->dir_size;
1168 prepare_for_transfer(f);
1176 int num_files = get_num_files(c, ptr, lo);
1177 if (num_files == -1) return;
1179 size = num_files * 160;
1180 f->file_data = malloc(size + 1);
1181 TRAP_ERROR(f->file_data == NULL, 550, return);
1182 list_core(c, ptr, "", lo, size, 0);
1185 list_core(c, ptr, "", lo);
1189 populate_dcache(f, cwd, ptr, lo);
1195 prepare_for_transfer(f);
1200 * Get the number of files in PATHNAME (optionally matching
1201 * a pattern). Note that c is needed for TRAP_ERROR.
1203 int get_num_files(struct conn * const c, const char * const pathname,
1204 struct list_options * const lo)
1210 * glob() fails to set errno correctly, so we simply guess on
1211 * `permission denied'... The others are far less likely to happen.
1213 switch (glob(pathname, 0, NULL, &pglob)) {
1219 num_files = pglob.gl_pathc;
1222 numeric(c, 550, strerror(EACCES));
1226 if (lo->recursive) {
1228 for (i = 0; i < pglob.gl_pathc; i++) {
1229 char *temp = pglob.gl_pathv[i];
1233 if (S_ISDIR(buf.st_mode)) {
1235 num_files += get_num_files(c, "*", lo);
1247 * list_core(): Enumerate all the files in PATHNAME, and formats them
1248 * according to list_options (calling format functions if
1251 * Note that we don't do any realloc() yet, so if your
1252 * _average_ file name length is over a certain size (a little
1253 * under 80 for long listings, and a little under 160 for
1254 * short listings), the list will be truncated. Fix...
1256 * The return value only makes sense if mmap()'ing, since it
1257 * returns the number of bytes written into the buffer.
1259 * This function is rather long.
1261 int list_core(struct conn * const c, const char * const pathname,
1262 char * const disp_pathname, struct list_options * const lo
1264 , const int size, int pos
1270 struct ftran * const f = c->transfer;
1273 * glob() fails to set errno correctly, so we simply guess on
1274 * `permission denied'... The others are far less likely to happen.
1276 switch (glob(pathname, GLOB_MARK, NULL, &pglob)) {
1281 break; /* note: break, not return */
1283 numeric(c, 550, strerror(EACCES));
1291 if (lo->recursive) {
1292 if (disp_pathname[0] == '\0') {
1293 mwrite(".:\r\n", 4);
1298 snprintf(temp, 1024, "%s:\r\n", disp_pathname);
1303 if (lo->long_listing) {
1304 /* FIX: we may get too high total number if we are running nonroot! */
1306 long unsigned int total = 0;
1309 for (i = 0; i < pglob.gl_pathc; i++) {
1310 if (lstat(pglob.gl_pathv[i], &buf) != -1) {
1311 total += buf.st_blocks;
1314 snprintf(temp, 1024, "total %lu\r\n", total >> 1);
1319 for (i = 0; i < pglob.gl_pathc; i++) {
1320 char * const temp = pglob.gl_pathv[i];
1323 /* strip `/' away from the pathname -- add it later if -F */
1325 int len = strlen(temp);
1326 if (temp[len - 1] == '/') {
1327 temp[len - 1] = '\0';
1331 if (lo->long_listing) {
1332 if (long_listing(buf, temp, lo->classify) == 0) continue;
1336 struct stat statbuf;
1338 if (lstat(buf, &statbuf) != -1) {
1339 const int len = strlen(buf);
1341 buf[len] = classify(statbuf.st_mode);
1347 mwrite(buf, strlen(buf));
1352 * If recursion is on, dive into any subdirectories now -- note
1353 * that each entry is stat()'ed twice, hopefully the OS will manage,
1354 * and we've got our own dcache anyways -- this could be fixed at
1355 * the expense of some memory, consider for later inclusion.
1357 if (lo->recursive) {
1358 for (i = 0; i < pglob.gl_pathc; i++) {
1360 const char * const temp = pglob.gl_pathv[i];
1362 /* don't dive into `.' or `..' */
1363 if (lstat(temp, &buf) != -1 && S_ISDIR(buf.st_mode) &&
1364 (temp[0] != '.' || (temp[1] != '.' && temp[1] != '\0'))) {
1369 /* attach the pathname to the end of the displayed path */
1370 if (disp_pathname[0] == '\0') {
1371 snprintf(tmp2, 1024, "%s", temp);
1373 snprintf(tmp2, 1024, "%s/%s", disp_pathname, temp);
1377 pos = list_core(c, "*", tmp2, lo,
1389 lseek(f->local_file, 0, SEEK_SET);
1401 * cmd_noop(): Handles the NOOP command. Does nothing, doesn't even
1402 * reset the timeout.
1404 void cmd_noop(struct conn * const c)
1406 numeric(c, 200, "NOOP command successful.");
1410 * cmd_syst(): Handles the SYST command. Returns the system identification.
1412 void cmd_syst(struct conn * const c)
1414 numeric(c, 215, "UNIX Type: L%u", NBBY);
1418 * cmd_type(): Handles the TYPE command.
1420 void cmd_type(struct conn * const c)
1423 c->recv_buf[0] &= (255-32); /* convert to upper case */
1424 if (c->recv_buf[0] == 'A') {
1426 numeric(c, 200, "Type is ASCII.");
1427 } else if (c->recv_buf[0] == 'I') {
1429 numeric(c, 200, "Type is IMAGE.");
1431 numeric(c, 504, "Unknown type.");
1434 numeric(c, 200, "TYPE ignored (always I)");
1439 * cmd_mode(): Handles the MODE command. Only stream mode is supported.
1441 void cmd_mode(struct conn * const c)
1443 c->recv_buf[0] &= (255-32); /* convert to upper case */
1444 if (c->recv_buf[0] == 'S') {
1445 numeric(c, 200, "Mode is STREAM.");
1447 numeric(c, 504, "Unknown mode.");
1452 * cmd_stru(): Handles the STRU command. Only file mode is supported.
1454 void cmd_stru(struct conn * const c)
1456 c->recv_buf[0] &= (255-32); /* convert to upper case */
1457 if (c->recv_buf[0] == 'F') {
1458 numeric(c, 200, "Structure is FILE.");
1460 numeric(c, 504, "Unknown structure.");
1465 * cmd_help(): Handle the HELP command. I'm sorry, but I'm unwilling
1466 * to use a lot of space to explain the RFCs in such a message,
1467 * and BetaFTPD doesn't have any special things that should
1468 * be noted anywhere. Thus, this message is close to empty. I
1469 * feel that a 5xx entry would have been better, but that is
1472 * As with ACCT, this command is supposed to be executed from
1473 * everywhere, so we have to run without setuid. I don't like
1474 * it, but at the same time I have to idea what could go
1477 * Perhaps I should make this message sound a little less
1478 * like an error, since the error code is intended for helpful
1481 void cmd_help(struct conn * const c)
1483 numeric(c, 414, "Sorry, no detailed help; use standard FTP commands.");
1487 * cmd_quit(): Handles the QUIT command, which shuts down the control
1490 void cmd_quit(struct conn * const c)
1492 numeric(c, 221, "Have a nice day!");
1497 * cmd_rein(): Handle the REIN command, which does close to a full reset
1498 * of the connection. Much of the code here is intentionally
1499 * copied directly from alloc_new_conn() -- perhaps we should
1502 void cmd_rein(struct conn * const c)
1504 destroy_ftran(c->transfer);
1505 c->buf_len = c->auth = c->rest_pos = 0;
1507 /* equals: strcpy(c->curr_dir, "/") ; strcpy(c->last_cmd, ""); */
1508 c->curr_dir[0] = '/';
1510 c->curr_dir[1] = c->last_cmd[0] = '\0';
1512 c->curr_dir[1] = '\0';
1515 time(&(c->last_transfer));
1516 numeric(c, 220, "BetaFTPD " VERSION " ready.");
1521 * cmd_exit(): Handles the EXIT command, my own `extension' to the
1522 * FTP protocol... IMPORTANT: Only to be used for profiling
1523 * purposes!! (It's needed to get some profiling data out
1524 * of the server after compiling it with -pg, since such data
1525 * is only written on a clear exit()). Any user (even those
1526 * not logged in) can issue an EXIT, and make the server shut
1527 * down without clearing any sockets etc. In other words:
1528 * Don't use it on a production site.
1530 void cmd_exit(struct conn * const c)
1532 while (first_conn->next_conn)
1533 destroy_conn(first_conn->next_conn);
1540 * Gets a command from c->recv_buf, determines which command
1541 * it is, sets proper effective user-ID and calls the command
1542 * handler. Finally, it cleans up.
1544 * To me, this command seems optimizable, but I'm not really
1547 void parse_command(struct conn *c)
1550 const struct handler *h = handler_table; /* first entry */
1552 if (c == NULL) return;
1554 /* strip any leading non-ASCII characters (including CR/LFs) */
1555 while (c->buf_len > 0 && (c->recv_buf[0] < 'a' || c->recv_buf[0] > 'z')
1556 && (c->recv_buf[0] < 'A' || c->recv_buf[0] > 'Z')) {
1557 remove_bytes(c, 1); /* not good */
1560 /* scan, searching for CR or LF */
1561 cmlen = strcspn(c->recv_buf, "\r\n");
1562 if (cmlen >= c->buf_len) return;
1565 strncpy(c->last_cmd, c->recv_buf, cmlen);
1566 c->last_cmd[cmlen] = 0;
1570 if ((cmlen >= (strlen(h->cmd_name) + h->add_cmlen)) &&
1571 (strncasecmp(c->recv_buf, h->cmd_name, strlen(h->cmd_name)) == 0)) {
1572 if (c->auth < h->min_auth) {
1573 numeric(c, 503, "Please login with USER and PASS.");
1574 while (c->recv_buf[0] != '\n') remove_bytes(c, 1);
1588 remove_bytes(c, strlen(h->cmd_name));
1589 cmlen -= strlen(h->cmd_name);
1590 while (c->recv_buf[0] == ' ') {
1595 schar = c->recv_buf[cmlen];
1596 c->recv_buf[cmlen] = 0;
1598 message_buf[0] = '\0';
1600 if (message_buf[0] != '\0') {
1601 /* send any feedback we might have */
1602 int err = send(c->sock, message_buf, strlen(message_buf), 0);
1603 if (err == -1 && errno == EPIPE) {
1611 c->recv_buf[cmlen] = schar;
1618 remove_bytes(c, cmlen);
1623 } while ((++h)->callback != NULL);
1625 numeric(c, 500, "Sorry, no such command.");
1626 remove_bytes(c, cmlen);
1630 * prepare_for_transfer():
1631 * Prepares an ftran object for a file transfer, setting
1632 * file size, opening sockets etc.
1634 * nonroot notice: prepare_for_transfer() assumes all access
1635 * checks are already done.
1637 void prepare_for_transfer(struct ftran *f)
1640 #warning No nonroot checking for prepare_for_transfer() yet
1644 /* mmap doesn't make temp files for dir listings */
1645 if (!f->dir_listing) {
1648 f->size = lseek(f->local_file, 0, SEEK_END);
1651 if (f->upload == 0 || f->append == 0 || f->owner->rest_pos != 0)
1653 lseek(f->local_file, f->owner->rest_pos, SEEK_SET);
1658 if (f->state == 1) { /* PASV connection */
1659 f->state = 2; /* waiting */
1660 } else if (f->state == 3) { /* PORT connection */
1662 connect(f->sock, (struct sockaddr *)&f->sin, sizeof(f->sin));
1663 add_fd(f->sock, POLLOUT);
1665 time(&(f->tran_start));
1670 * Takes a mode_t argument (from a `struct stat'), and
1671 * returns the proper dirlist letter for that type.
1673 * Note: S_IFLNK seems to be broken, or perhaps I just have
1674 * missed something (S_IFLNK is always set for all *files* on
1675 * my glibc 2.0.111 system).
1677 * The most common cases are put first, for speed :-)
1679 char decode_mode(mode_t mode) {
1680 if (S_ISREG(mode)) return '-';
1681 if (S_ISDIR(mode)) return 'd';
1682 if (S_ISLNK(mode)) return 'l';
1683 if (S_ISBLK(mode)) return 'b';
1684 if (S_ISCHR(mode)) return 'c';
1685 if (S_ISSOCK(mode)) return 's';
1686 if (S_ISFIFO(mode)) return 'f';
1693 * Take an FTP path, do all neccessary root_dir checks,
1694 * change to the correct directory and return the proper
1695 * file name to open/stat/whatever. The path returned is
1696 * relative to the current directory (NOT absolute). chdir()
1697 * in any way will `destroy' this argument.
1699 * Note that `path' will be _changed_, and used as a return pointer
1700 * base. Do not attempt to free the result from this function --
1701 * if you need to, free path instead.
1703 char *translate_path(struct conn * const c, char * const path)
1707 /* chdir to the right dir, then chop it off */
1710 ptr = strrchr(path, '/');
1712 char save_char = ptr[0];
1715 if (do_chdir(c, path) == -1) {
1728 * Opens the file PATH with access parameters FLAGS, translating
1729 * paths and checking permissions as neccessary. Generally, this
1730 * should be used whenever you need an open().
1732 * The parameters might be a bit confusing. To clarify them a bit:
1733 * c: IN/OUT (will be changed)
1734 * path: IN (but _will_ be changed)
1739 int do_openfile(struct conn * const c, char * const path,
1740 char * const filename, const int flags
1742 , const int check_permission
1750 if (nr_check_permission(c->uid, path, check_permission, 0, NULL) == -1) {
1755 ptr = translate_path(c, c->recv_buf);
1756 if (ptr == NULL) return -1;
1759 if ((flags & O_CREAT) == 0) {
1761 TRAP_ERROR(stat(ptr, &buf) == -1, 550, return -2);
1762 if (!S_ISREG(buf.st_mode)) {
1763 numeric(c, 550, "Not a plain file.", ptr);
1770 if (filename != NULL) { /* filename should always be != NULL */
1771 strcpy(filename, ptr);
1773 return open(ptr, flags, 0666);
1777 * prepare_for_listing():
1778 * Parse list options, put them back into the list_options
1779 * structure lo, and make temporary room for the list.
1781 int prepare_for_listing(struct conn * const c, char ** const ptr,
1782 struct list_options * const lo)
1787 struct ftran *f = c->transfer;
1789 char *optr = NULL, *fptr = NULL;
1795 #warning No nonroot checking for prepare_for_listing() yet
1798 if ((f == NULL) || ((f->state != 1) && (f->state != 3))) {
1799 numeric(c, 425, "No data connection set up; please use PASV or PORT.");
1804 * A little parameter scanning is required here. There can only
1805 * be two parts: the directory name, and any options. We'll find
1806 * any options first.
1808 if (c->recv_buf[0] == '-') {
1811 optr = strstr(c->recv_buf, " -");
1814 /* Then see if there are any options to parse. */
1817 switch (*optr & (255-32)) { /* uppercase */
1818 case 'R': /* actually case sensitive... */
1822 lo->long_listing = 1;
1839 /* then we chdir to the dir in fptr (if any) */
1840 tmp = fptr ? strrchr(fptr, '/') : NULL;
1843 if (do_chdir(c, fptr) == -1) return -1;
1846 /* current directory */
1847 TRAP_ERROR(chdir(c->curr_dir) == -1, 550, return -1);
1850 /* if no argument, choose all files */
1851 if (fptr == NULL || fptr[0] == 0) {
1854 /* we need to check if the last part is a directory (no -d switch) */
1856 if (stat(fptr, &buf) == 0 && S_ISDIR(buf.st_mode)) {
1857 TRAP_ERROR(chdir(fptr) == -1, 550, return -1);
1865 if (nr_check_permission(c->uid, chd, 4, 1, NULL) == -1) {
1866 numeric(c, 550, "Permission denied");
1872 tfname = tempnam(NULL, "ftp");
1875 if (tfname == NULL) tfname = tempnam("/", "ftp");
1878 TRAP_ERROR(tfname == NULL, 550, return -1);
1879 strcpy(f->filename, tfname);
1882 f->local_file = open(f->filename, O_RDWR | O_CREAT | O_TRUNC, 0666);
1883 TRAP_ERROR(f->local_file == -1, 550, return -1);
1894 * classify(): Takes a mode_t argument (from `struct stat'), and returns
1895 * the parameter to be used in an `ls -F'-style listing.
1897 char classify(const mode_t mode)
1899 if (S_ISREG(mode)) {
1900 if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
1906 if (S_ISDIR(mode)) return '/';
1907 if (S_ISLNK(mode)) return '@';
1908 if (S_ISSOCK(mode)) return '=';
1909 if (S_ISFIFO(mode)) return '|';