source: rtems-libbsd/rtemsbsd/ftpd/ftpd.c @ 8d4bab3

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 8d4bab3 was 57bfdf7, checked in by Sebastian Huber <sebastian.huber@…>, on 11/14/13 at 12:48:43

ftpd01: New test

  • Property mode set to 100644
File size: 51.8 KB
Line 
1/* FIXME: 1. Parse command is a hack.  We can do better.
2 *        2. OSV: hooks support seems to be bad, as it requires storing of
3 *           entire input file in memory.  Seem to be better to change it to
4 *           something more reasonable, like having
5 *           'hook_write(void const *buf, int count)' routine that will be
6 *           called multiple times while file is being received.
7 *        3. OSV: Remove hack with "/dev/null"?
8 *
9 *  FTP Server Daemon
10 *
11 *  Submitted by: Jake Janovetz <janovetz@tempest.ece.uiuc.edu>
12 *
13 *  Changed by:   Sergei Organov <osv@javad.ru> (OSV)
14 *                Arnout Vandecappelle <arnout@mind.be> (AV)
15 *                Sebastien Bourdeauducq <sebastien@milkymist.org> (MM)
16 *               
17 *
18 *  Changes:
19 *
20 *    2010-12-02        Sebastien Bourdeauducq <sebastien@milkymist.org>
21 *
22 *      * Support spaces in filenames
23 *
24 *    2010-04-29        Arnout Vandecappelle (Essensium/Mind) <arnout@mind.be>
25 *
26 *      * Added USER/PASS authentication.
27 *
28 *    2001-01-31        Sergei Organov <osv@javad.ru>
29 *
30 *      * Hacks with current dir and root dir removed in favor of new libio
31 *        support for task-local current and root directories.
32 *
33 *    2001-01-30        Sergei Organov <osv@javad.ru>
34 *
35 *      * Bug in `close_data_socket()' introduced by previous change fixed.
36 *      * `command_pasv()' changed to set timeout on socket we are listening on
37 *        and code fixed to don't close socket twice on error.
38 *      * `serr()' changed to clear `errno'.
39 *      * `data_socket()' changed to clear `errno' before `bind()'.
40 *      * `session()' changed to clear `errno' before processing session.
41 *
42 *    2001-01-29        Sergei Organov <osv@javad.ru>
43 *
44 *      * `close_data_socket()' fixed to close both active and passive sockets
45 *      * Initialize info->data_socket to -1 in `daemon()'
46 *      * Initialize `fname' to empty string  in `exec_command()'
47 *
48 *    2001-01-22        Sergei Organov <osv@javad.ru>
49 *
50 *      * Timeouts on sockets implemented. 'idle' field added to
51 *        configuration. No timeout by default to keep backward compatibility.
52 *        Note: SITE IDLE command not implemented yet.
53 *      * Basic global access control implemented. 'access' field added to
54 *        configuration. No access limitations by default to keep backward
55 *        compatibility.
56 *
57 *    2001-01-17        Sergei Organov <osv@javad.ru>
58 *
59 *      * Anchor data socket for active mode (using self IP and port 20.)
60 *      * Fixed default data port support (still not tested).
61 *      * Don't allow IP address different from originating host in
62 *        PORT command to improve security.
63 *      * Fixed bug in MDTM command.
64 *      * Check for correctness of parsing of argument in command_port().
65 *      * Fixed squeeze_path() to don't allow names like 'NAME/smth' where
66 *        'NAME' is not a directory.
67 *      * Command parsing a little bit improved: command names are now
68 *        converted to upper-case to be more compatible with RFC (command
69 *        names are not case-sensitive.)
70 *      * Reformat comments so that they have RTEMS look-and-feel.
71 *
72 *    2001-01-16        Sergei Organov <osv@javad.ru>
73 *
74 *      * Fixed DELE, SITE CHMOD, RMD, MKD broken by previous changes
75 *      * True ASCII mode implemented (doesn't work for hooks and /dev/null)
76 *      * Passive mode implemented, PASV command added.
77 *      * Default port for data connection could be used (untested, can't find
78 *        ftp client that doesn't send PORT command)
79 *      * SYST reply changed to UNIX, as former RTEMS isn't registered name.
80 *      * Reply codes reviewed and fixed.
81 *
82 *    2001-01-08        Sergei Organov <osv@javad.ru>
83 *
84 *      * use pool of pre-created threads to handle sessions
85 *      * LIST output now similar to what "/bin/ls -al" would output, thus
86 *        FTP clients could parse it.
87 *      * LIST NAME now works (both for files and directories)
88 *      * keep track of CWD for every session separately
89 *      * ability to specify root directory name in configuration table
90 *      * options sent in commands are ignored, thus LIST -al FILE works
91 *      * added support for NLST, CDUP and MDTM commands
92 *      * buffers are allocated on stack instead of heap where possible
93 *      * drop using of task notepad to pass parameters - use function
94 *        arguments instead
95 *      * various bug-fixes, e.g., use of PF_INET in socket() instead of
96 *        AF_INET, use snprintf() instead of sprintf() everywhere for safety,
97 *        etc.
98 */
99
100/*************************************************************************
101 *                                 ftpd.c
102 *************************************************************************
103 * Description:
104 *
105 *    This file contains the daemon which services requests that appear
106 *    on the FTP port.  This server is compatible with FTP, but it
107 *    also provides 'hooks' to make it usable in situations where files
108 *    are not used/necessary.  Once the server is started, it runs
109 *    forever.
110 *
111 *
112 *    Organization:
113 *
114 *       The FTP daemon is started upon boot along with a (configurable)
115 *       number of tasks to handle sessions.  It runs all the time and
116 *       waits for connections on the known FTP port (21).  When
117 *       a connection is made, it wakes-up a 'session' task.  That
118 *       session then interacts with the remote host.  When the session
119 *       is complete, the session task goes to sleep.  The daemon still
120 *       runs, however.
121 *
122 *
123 * Supported commands are:
124 *
125 * RETR xxx     - Sends a file from the client.
126 * STOR xxx     - Receives a file from the client.  xxx = filename.
127 * LIST xxx     - Sends a file list to the client.
128 * NLST xxx     - Sends a file list to the client.
129 * USER         - Does nothing.
130 * PASS         - Does nothing.
131 * SYST         - Replies with the system type (`RTEMS').
132 * DELE xxx     - Delete file xxx.
133 * MKD xxx      - Create directory xxx.
134 * RMD xxx      - Remove directory xxx.
135 * PWD          - Print working directory.
136 * CWD xxx      - Change working directory.
137 * CDUP         - Change to upper directory.
138 * SITE CHMOD xxx yyy - Change permissions on file yyy to xxx.
139 * PORT a,b,c,d,x,y   - Setup for a data port to IP address a.b.c.d
140 *                      and port (x*256 + y).
141 * MDTM xxx     - Send file modification date/time to the client.
142 *                xxx = filename.
143 * PASV         - Use passive mode data connection.
144 *
145 *
146 * The public routines contained in this file are:
147 *
148 *    rtems_initialize_ftpd - Initializes and starts the server daemon,
149 *                            then returns to its caller.
150 *
151 *------------------------------------------------------------------------
152 * Jake Janovetz
153 * University of Illinois
154 * 1406 West Green Street
155 * Urbana IL  61801
156 *************************************************************************
157 * Change History:
158 *  12/01/97   - Creation (JWJ)
159 *  2001-01-08 - Changes by OSV
160 *  2010-04-29 - Authentication added by AV
161 *************************************************************************/
162
163/*************************************************************************
164 * Meanings of first and second digits of reply codes:
165 *
166 * Reply:  Description:
167 *-------- --------------
168 *  1yz    Positive preliminary reply.  The action is being started but
169 *         expect another reply before sending another command.
170 *  2yz    Positive completion reply.  A new command can be sent.
171 *  3yz    Positive intermediate reply.  The command has been accepted
172 *         but another command must be sent.
173 *  4yz    Transient negative completion reply.  The requested action did
174 *         not take place, but the error condition is temporary so the
175 *         command can be reissued later.
176 *  5yz    Permanent negative completion reply.  The command was not
177 *         accepted and should not be retried.
178 *-------------------------------------------------------------------------
179 *  x0z    Syntax errors.
180 *  x1z    Information.
181 *  x2z    Connections.  Replies referring to the control or data
182 *         connections.
183 *  x3z    Authentication and accounting.  Replies for the login or
184 *         accounting commands.
185 *  x4z    Unspecified.
186 *  x5z    Filesystem status.
187 *************************************************************************/
188
189#if HAVE_CONFIG_H
190#include "config.h"
191#endif
192
193#include <stdio.h>
194#include <stdlib.h>
195#include <string.h>
196#include <unistd.h>
197#include <fcntl.h>
198#include <dirent.h>
199#include <errno.h>
200#include <ctype.h>
201#include <inttypes.h>
202
203#include <rtems.h>
204#include <rtems/rtems_bsdnet.h>
205#include <rtems/error.h>
206#include <rtems/libio.h>
207#include <rtems/userenv.h>
208#include <syslog.h>
209
210#include <sys/types.h>
211#include <sys/socket.h>
212#include <arpa/ftp.h>
213#include <netinet/in.h>
214
215#include <rtems/ftpd.h>
216
217
218#ifdef __GNUC__
219/* change to #if 1 to disable syslog entirely */
220#if 0
221#undef  syslog
222#define syslog(a, b, ...) while(0){}
223#endif
224#endif
225
226#define FTPD_SERVER_MESSAGE  "RTEMS FTP server (Version 1.1-JWJ) ready."
227
228#define FTPD_SYSTYPE "UNIX Type: L8"
229
230/* Seem to be unused */
231#if 0
232#define FTPD_WELCOME_MESSAGE \
233   "Welcome to the RTEMS FTP server.\n" \
234   "\n" \
235   "Login accepted.\n"
236#endif
237
238/* Event to be used by session tasks for waiting */
239enum
240{
241  FTPD_RTEMS_EVENT = RTEMS_EVENT_1
242};
243
244/* Configuration table */
245extern struct rtems_ftpd_configuration rtems_ftpd_configuration;
246
247/* this is not prototyped in strict ansi mode */
248FILE *fdopen (int fildes, const char *mode);
249
250/*SessionInfo structure.
251 *
252 * The following structure is allocated for each session.
253 */
254typedef struct
255{
256  struct sockaddr_in  ctrl_addr;   /* Control connection self address */
257  struct sockaddr_in  data_addr;   /* Data address set by PORT command */
258  struct sockaddr_in  def_addr;    /* Default address for data */
259  int                 use_default; /* 1 - use default address for data */
260  FILE                *ctrl_fp;    /* File pointer for control connection */
261  int                 ctrl_socket; /* Socket for ctrl connection */
262  int                 pasv_socket; /* Socket for PASV connection */
263  int                 data_socket; /* Socket for data connection */
264  int                 idle;        /* Timeout in seconds */
265  int                 xfer_mode;   /* Transfer mode (ASCII/binary) */
266  rtems_id            tid;         /* Task id */
267  char                *user;       /* user name (0 if not supplied) */
268  char                *pass;       /* password (0 if not supplied) */
269  bool                auth;        /* true if user/pass was valid, false if not or not supplied */
270} FTPD_SessionInfo_t;
271
272
273/*
274 * TaskPool structure.
275 */
276typedef struct
277{
278  FTPD_SessionInfo_t    *info;
279  FTPD_SessionInfo_t    **queue;
280  int                   count;
281  int                   head;
282  int                   tail;
283  rtems_id              mutex;
284  rtems_id              sem;
285} FTPD_TaskPool_t;
286
287/*
288 * Task pool instance.
289 */
290static FTPD_TaskPool_t task_pool;
291
292/*
293 * Root directory
294 */
295
296static char const* ftpd_root = "/";
297
298/*
299 * Default idle timeout for sockets in seconds.
300 */
301static int ftpd_timeout = 0;
302
303/*
304 * Global access flags.
305 */
306static int ftpd_access = 0;
307
308/*
309 * serr
310 *
311 * Return error string corresponding to current 'errno'.
312 *
313 */
314static char const*
315serr(void)
316{
317  int err = errno;
318  errno = 0;
319  return strerror(err);
320}
321
322/*
323 * Utility routines for access control.
324 *
325 */
326
327static int
328can_read(void)
329{
330  return (ftpd_access & FTPD_NO_READ) == 0;
331}
332
333static int
334can_write(void)
335{
336  return (ftpd_access & FTPD_NO_WRITE) == 0;
337}
338
339/*
340 * Task pool management routines
341 *
342 */
343
344
345/*
346 * task_pool_done
347 *
348 * Cleanup task pool.
349 *
350 * Input parameters:
351 *   count - number of entries in task pool to cleanup
352 *
353 * Output parameters:
354 *   NONE
355 *
356 */
357static void
358task_pool_done(int count)
359{
360  int i;
361  for(i = 0; i < count; ++i)
362    rtems_task_delete(task_pool.info[i].tid);
363  if(task_pool.info)
364    free(task_pool.info);
365  if(task_pool.queue)
366    free(task_pool.queue);
367  if(task_pool.mutex != (rtems_id)-1)
368    rtems_semaphore_delete(task_pool.mutex);
369  if(task_pool.sem != (rtems_id)-1)
370    rtems_semaphore_delete(task_pool.sem);
371  task_pool.info = 0;
372  task_pool.queue = 0;
373  task_pool.count = 0;
374  task_pool.sem = -1;
375  task_pool.mutex = -1;
376}
377
378/*
379 * task_pool_init
380 *
381 * Initialize task pool.
382 *
383 * Input parameters:
384 *   count    - number of entries in task pool to create
385 *   priority - priority tasks are started with
386 *
387 * Output parameters:
388 *   returns 1 on success, 0 on failure.
389 *
390 */
391static void session(rtems_task_argument arg); /* Forward declare */
392
393static int
394task_pool_init(int count, rtems_task_priority priority)
395{
396  int i;
397  rtems_status_code sc;
398  char id = 'a';
399
400  task_pool.count = 0;
401  task_pool.head = task_pool.tail = 0;
402  task_pool.mutex = (rtems_id)-1;
403  task_pool.sem   = (rtems_id)-1;
404
405  sc = rtems_semaphore_create(
406    rtems_build_name('F', 'T', 'P', 'M'),
407    1,
408    RTEMS_DEFAULT_ATTRIBUTES
409    | RTEMS_BINARY_SEMAPHORE
410    | RTEMS_INHERIT_PRIORITY
411    | RTEMS_PRIORITY,
412    RTEMS_NO_PRIORITY,
413    &task_pool.mutex);
414
415  if(sc == RTEMS_SUCCESSFUL)
416    sc = rtems_semaphore_create(
417      rtems_build_name('F', 'T', 'P', 'S'),
418      count,
419      RTEMS_DEFAULT_ATTRIBUTES,
420      RTEMS_NO_PRIORITY,
421      &task_pool.sem);
422
423  if(sc != RTEMS_SUCCESSFUL) {
424    task_pool_done(0);
425    syslog(LOG_ERR, "ftpd: Can not create semaphores");
426    return 0;
427  }
428
429  task_pool.info = (FTPD_SessionInfo_t*)
430    malloc(sizeof(FTPD_SessionInfo_t) * count);
431  task_pool.queue = (FTPD_SessionInfo_t**)
432    malloc(sizeof(FTPD_SessionInfo_t*) * count);
433  if (NULL == task_pool.info || NULL == task_pool.queue)
434  {
435    task_pool_done(0);
436    syslog(LOG_ERR, "ftpd: Not enough memory");
437    return 0;
438  }
439
440  for(i = 0; i < count; ++i)
441  {
442    FTPD_SessionInfo_t *info = &task_pool.info[i];
443    sc = rtems_task_create(rtems_build_name('F', 'T', 'P', id),
444      priority, FTPD_STACKSIZE,
445      RTEMS_PREEMPT | RTEMS_NO_TIMESLICE |
446      RTEMS_NO_ASR | RTEMS_INTERRUPT_LEVEL(0),
447      RTEMS_NO_FLOATING_POINT | RTEMS_LOCAL,
448      &info->tid);
449    if (sc == RTEMS_SUCCESSFUL)
450    {
451      sc = rtems_task_start(
452        info->tid, session, (rtems_task_argument)info);
453      if (sc != RTEMS_SUCCESSFUL)
454        task_pool_done(i);
455    }
456    else
457      task_pool_done(i + 1);
458    if (sc != RTEMS_SUCCESSFUL)
459    {
460      syslog(LOG_ERR, "ftpd: Could not create/start FTPD session: %s",
461        rtems_status_text(sc));
462      return 0;
463    }
464    task_pool.queue[i] = task_pool.info + i;
465    if (++id > 'z')
466      id = 'a';
467  }
468  task_pool.count = count;
469  return 1;
470}
471
472/*
473 * task_pool_obtain
474 *
475 * Obtain free task from task pool.
476 *
477 * Input parameters:
478 *   NONE
479 *
480 * Output parameters:
481 *   returns pointer to the corresponding SessionInfo structure on success,
482 *           NULL if there are no free tasks in the pool.
483 *
484 */
485static FTPD_SessionInfo_t*
486task_pool_obtain(void)
487{
488  FTPD_SessionInfo_t* info = 0;
489  rtems_status_code sc;
490  sc = rtems_semaphore_obtain(task_pool.sem, RTEMS_NO_WAIT, RTEMS_NO_TIMEOUT);
491  if (sc == RTEMS_SUCCESSFUL)
492  {
493    rtems_semaphore_obtain(task_pool.mutex, RTEMS_WAIT, RTEMS_NO_TIMEOUT);
494    info = task_pool.queue[task_pool.head];
495    if(++task_pool.head >= task_pool.count)
496      task_pool.head = 0;
497    rtems_semaphore_release(task_pool.mutex);
498  }
499  return info;
500}
501
502/*
503 * task_pool_release
504 *
505 * Return task obtained by 'obtain()' back to the task pool.
506 *
507 * Input parameters:
508 *   info  - pointer to corresponding SessionInfo structure.
509 *
510 * Output parameters:
511 *   NONE
512 *
513 */
514static void
515task_pool_release(FTPD_SessionInfo_t* info)
516{
517  rtems_semaphore_obtain(task_pool.mutex, RTEMS_WAIT, RTEMS_NO_TIMEOUT);
518  task_pool.queue[task_pool.tail] = info;
519  if(++task_pool.tail >= task_pool.count)
520    task_pool.tail = 0;
521  rtems_semaphore_release(task_pool.mutex);
522  rtems_semaphore_release(task_pool.sem);
523}
524
525/*
526 * End of task pool routines
527 */
528
529/*
530 * Function: send_reply
531 *
532 *
533 *    This procedure sends a reply to the client via the control
534 *    connection.
535 *
536 *
537 * Input parameters:
538 *   code  - 3-digit reply code.
539 *   text  - Reply text.
540 *
541 * Output parameters:
542 *   NONE
543 */
544static void
545send_reply(FTPD_SessionInfo_t  *info, int code, char *text)
546{
547  text = text != NULL ? text : "";
548  fprintf(info->ctrl_fp, "%d %.70s\r\n", code, text);
549  fflush(info->ctrl_fp);
550}
551
552
553/*
554 * close_socket
555 *
556 * Close socket.
557 *
558 * Input parameters:
559 *   s - socket descriptor.
560 *   seconds - number of seconds the timeout should be,
561 *             if >= 0 - infinite timeout (no timeout).
562 *
563 * Output parameters:
564 *   returns 1 on success, 0 on failure.
565 */
566static int
567set_socket_timeout(int s, int seconds)
568{
569  int res = 0;
570  struct timeval tv;
571  int len = sizeof(tv);
572
573  if(seconds < 0)
574    seconds = 0;
575  tv.tv_usec = 0;
576  tv.tv_sec  = seconds;
577  if(0 != setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, len))
578    syslog(LOG_ERR, "ftpd: Can't set send timeout on socket: %s.", serr());
579  else if(0 != setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, len))
580    syslog(LOG_ERR, "ftpd: Can't set receive timeout on socket: %s.", serr());
581  else
582    res = 1;
583  return res;
584}
585
586/*
587 * close_socket
588 *
589 * Close socket.
590 *
591 * Input parameters:
592 *   s - socket descriptor to be closed.
593 *
594 * Output parameters:
595 *   returns 1 on success, 0 on failure
596 */
597static int
598close_socket(int s)
599{
600  if (0 <= s)
601  {
602    if (0 != close(s))
603    {
604      shutdown(s, 2);
605      if (0 != close(s))
606        return 0;
607    }
608  }
609  return 1;
610}
611
612/*
613 * data_socket
614 *
615 * Create data socket for session.
616 *
617 * Input parameters:
618 *   info - corresponding SessionInfo structure
619 *
620 * Output parameters:
621 *   returns socket descriptor, or -1 if failure
622 *
623 */
624static int
625data_socket(FTPD_SessionInfo_t *info)
626{
627  int s = info->pasv_socket;
628  if(0 > s)
629  {
630    int on = 1;
631    s = socket(PF_INET, SOCK_STREAM, 0);
632    if(0 > s)
633      send_reply(info, 425, "Can't create data socket.");
634    else if(0 > setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))
635    {
636      close_socket(s);
637      s = -1;
638    }
639    else
640    {
641      struct sockaddr_in data_source;
642      int tries;
643
644      /* anchor socket to avoid multi-homing problems */
645      data_source = info->ctrl_addr;
646      data_source.sin_port = htons(20); /* ftp-data port */
647      for(tries = 1; tries < 10; ++tries)
648      {
649        errno = 0;
650        if(bind(s, (struct sockaddr *)&data_source, sizeof(data_source)) >= 0)
651          break;
652        if (errno != EADDRINUSE)
653          tries = 10;
654        else
655          rtems_task_wake_after(tries * 10);
656      }
657      if(tries >= 10)
658      {
659        send_reply(info, 425, "Can't bind data socket.");
660        close_socket(s);
661        s = -1;
662      }
663      else
664      {
665        struct sockaddr_in *data_dest =
666          (info->use_default) ? &info->def_addr : &info->data_addr;
667        if(0 > connect(s, (struct sockaddr *)data_dest, sizeof(*data_dest)))
668        {
669          send_reply(info, 425, "Can't connect data socket.");
670          close_socket(s);
671          s = -1;
672        }
673      }
674    }
675  }
676  info->data_socket = s;
677  info->use_default = 1;
678  if(s >= 0)
679    set_socket_timeout(s, info->idle);
680  return s;
681}
682
683/*
684 * close_data_socket
685 *
686 * Close data socket for session.
687 *
688 * Input parameters:
689 *   info - corresponding SessionInfo structure
690 *
691 * Output parameters:
692 *   NONE
693 *
694 */
695static void
696close_data_socket(FTPD_SessionInfo_t *info)
697{
698  /* As at most one data socket could be open simultaneously and in some cases
699     data_socket == pasv_socket, we select socket to close, then close it. */
700  int s = info->data_socket;
701  if(0 > s)
702    s = info->pasv_socket;
703  if(!close_socket(s))
704    syslog(LOG_ERR, "ftpd: Error closing data socket.");
705  info->data_socket = -1;
706  info->pasv_socket = -1;
707  info->use_default = 1;
708}
709
710/*
711 * close_stream
712 *
713 * Close control stream of session.
714 *
715 * Input parameters:
716 *   info - corresponding SessionInfo structure
717 *
718 * Output parameters:
719 *   NONE
720 *
721 */
722static void
723close_stream(FTPD_SessionInfo_t* info)
724{
725  if (NULL != info->ctrl_fp)
726  {
727    if (0 != fclose(info->ctrl_fp))
728    {
729      syslog(LOG_ERR, "ftpd: Could not close control stream: %s", serr());
730    }
731    else
732      info->ctrl_socket = -1;
733  }
734
735  if (!close_socket(info->ctrl_socket))
736    syslog(LOG_ERR, "ftpd: Could not close control socket: %s", serr());
737
738  info->ctrl_fp = NULL;
739  info->ctrl_socket = -1;
740}
741
742
743/*
744 * send_mode_reply
745 *
746 * Sends BINARY/ASCII reply string depending on current transfer mode.
747 *
748 * Input parameters:
749 *   info - corresponding SessionInfo structure
750 *
751 * Output parameters:
752 *   NONE
753 *
754 */
755static void
756send_mode_reply(FTPD_SessionInfo_t *info)
757{
758  if(info->xfer_mode == TYPE_I)
759    send_reply(info, 150, "Opening BINARY mode data connection.");
760  else
761    send_reply(info, 150, "Opening ASCII mode data connection.");
762}
763
764/*
765 * command_retrieve
766 *
767 * Perform the "RETR" command (send file to client).
768 *
769 * Input parameters:
770 *   info - corresponding SessionInfo structure
771 *   char *filename  - source filename.
772 *
773 * Output parameters:
774 *   NONE
775 *
776 */
777static void
778command_retrieve(FTPD_SessionInfo_t  *info, char const *filename)
779{
780  int                 s = -1;
781  int                 fd = -1;
782  char                buf[FTPD_DATASIZE];
783  struct stat         stat_buf;
784  int                 res = 0;
785
786  if(!can_read() || !info->auth)
787  {
788    send_reply(info, 550, "Access denied.");
789    return;
790  }
791
792  if (0 > (fd = open(filename, O_RDONLY)))
793  {
794    send_reply(info, 550, "Error opening file.");
795    return;
796  }
797
798  if (fstat(fd, &stat_buf) == 0 && S_ISDIR(stat_buf.st_mode))
799  {
800    if (-1 != fd)
801      close(fd);
802    send_reply(info, 550, "Is a directory.");
803    return;
804  }
805
806  send_mode_reply(info);
807
808  s = data_socket(info);
809
810  if (0 <= s)
811  {
812    int n = -1;
813
814    if(info->xfer_mode == TYPE_I)
815    {
816      while ((n = read(fd, buf, FTPD_DATASIZE)) > 0)
817      {
818        if(send(s, buf, n, 0) != n)
819          break;
820      }
821    }
822    else if (info->xfer_mode == TYPE_A)
823    {
824      int rest = 0;
825      while (rest == 0 && (n = read(fd, buf, FTPD_DATASIZE)) > 0)
826      {
827        char const* e = buf;
828        char const* b;
829        int i;
830        rest = n;
831        do
832        {
833          char lf = '\0';
834
835          b = e;
836          for(i = 0; i < rest; ++i, ++e)
837          {
838            if(*e == '\n')
839            {
840              lf = '\n';
841              break;
842            }
843          }
844          if(send(s, b, i, 0) != i)
845            break;
846          if(lf == '\n')
847          {
848            if(send(s, "\r\n", 2, 0) != 2)
849              break;
850            ++e;
851            ++i;
852          }
853        }
854        while((rest -= i) > 0);
855      }
856    }
857
858    if (0 == n)
859    {
860      if (0 == close(fd))
861      {
862        fd = -1;
863        res = 1;
864      }
865    }
866  }
867
868  if (-1 != fd)
869    close(fd);
870
871  if (0 == res)
872    send_reply(info, 451, "File read error.");
873  else
874    send_reply(info, 226, "Transfer complete.");
875
876  close_data_socket(info);
877
878  return;
879}
880
881
882/*
883 * discard
884 *
885 * Analog of `write' routine that just discards passed data
886 *
887 * Input parameters:
888 *   fd    - file descriptor (ignored)
889 *   buf   - data to write (ignored)
890 *   count - number of bytes in `buf'
891 *
892 * Output parameters:
893 *   returns `count'
894 *
895 */
896static ssize_t
897discard(int fd, void const* buf, size_t count)
898{
899  (void)fd;
900  (void)buf;
901  return count;
902}
903
904/*
905 * command_store
906 *
907 * Performs the "STOR" command (receive data from client).
908 *
909 * Input parameters:
910 *   info - corresponding SessionInfo structure
911 *   char *filename   - Destination filename.
912 *
913 * Output parameters:
914 *   NONE
915 */
916static void
917command_store(FTPD_SessionInfo_t *info, char const *filename)
918{
919  int                    s;
920  int                    n;
921  unsigned long          size = 0;
922  struct rtems_ftpd_hook *usehook = NULL;
923  char                   buf[FTPD_DATASIZE];
924  int                    res = 1;
925  int                    bare_lfs = 0;
926  int                    null = 0;
927  typedef ssize_t (*WriteProc)(int, void const*, size_t);
928  WriteProc              wrt = &write;
929
930  if(!can_write() || !info->auth)
931  {
932    send_reply(info, 550, "Access denied.");
933    return;
934  }
935
936  send_mode_reply(info);
937
938  s = data_socket(info);
939  if(0 > s)
940    return;
941
942  null = !strcmp("/dev/null", filename);
943  if (null)
944  {
945    /* File "/dev/null" just throws data away.
946     *  FIXME: this is hack.  Using `/dev/null' filesystem entry would be
947     *  better.
948     */
949    wrt = &discard;
950  }
951
952  if (!null && rtems_ftpd_configuration.hooks != NULL)
953  {
954
955    /* Search our list of hooks to see if we need to do something special. */
956    struct rtems_ftpd_hook *hook;
957    int i;
958
959    i = 0;
960    hook = &rtems_ftpd_configuration.hooks[i++];
961    while (hook->filename != NULL)
962    {
963      if (!strcmp(hook->filename, filename))
964      {
965        usehook = hook;
966        break;
967      }
968      hook = &rtems_ftpd_configuration.hooks[i++];
969    }
970  }
971
972  if (usehook != NULL)
973  {
974    /*
975     * OSV: FIXME: Small buffer could be used and hook routine
976     * called multiple times instead.  Alternatively, the support could be
977     * removed entirely in favor of configuring RTEMS pseudo-device with
978     * given name.
979     */
980
981    char                *bigBufr;
982    size_t filesize = rtems_ftpd_configuration.max_hook_filesize + 1;
983
984    /*
985     * Allocate space for our "file".
986     */
987    bigBufr = (char *)malloc(filesize);
988    if (bigBufr == NULL)
989    {
990      send_reply(info, 451, "Local resource failure: malloc.");
991      close_data_socket(info);
992      return;
993    }
994
995    /*
996     * Retrieve the file into our buffer space.
997     */
998    size = 0;
999    while ((n = recv(s, bigBufr + size, filesize - size, 0)) > 0)
1000    {
1001      size += n;
1002    }
1003    if (size >= filesize)
1004    {
1005      send_reply(info, 451, "File too long: buffer size exceeded.");
1006      free(bigBufr);
1007      close_data_socket(info);
1008      return;
1009    }
1010
1011    /*
1012     * Call our hook.
1013     */
1014    res = (usehook->hook_function)(bigBufr, size) == 0;
1015    free(bigBufr);
1016    if(!res)
1017    {
1018      send_reply(info, 451, "File processing failed.");
1019      close_data_socket(info);
1020      return;
1021    }
1022  }
1023  else
1024  {
1025    /* Data transfer to regular file or /dev/null. */
1026    int fd = 0;
1027
1028    if(!null)
1029      fd = creat(filename,
1030        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
1031
1032    if (0 > fd)
1033    {
1034      send_reply(info, 550, "Error creating file.");
1035      close_data_socket(info);
1036      return;
1037    }
1038
1039    if(info->xfer_mode == TYPE_I)
1040    {
1041      while ((n = recv(s, buf, FTPD_DATASIZE, 0)) > 0)
1042      {
1043        if (wrt(fd, buf, n) != n)
1044        {
1045          res = 0;
1046          break;
1047        }
1048      }
1049    }
1050    else if(info->xfer_mode == TYPE_A)
1051    {
1052      int rest = 0;
1053      int pended_cr = 0;
1054      while (res && rest == 0 && (n = recv(s, buf, FTPD_DATASIZE, 0)) > 0)
1055      {
1056        char const* e = buf;
1057        char const* b;
1058        int i;
1059
1060        rest = n;
1061        if(pended_cr && *e != '\n')
1062        {
1063          char const lf = '\r';
1064          pended_cr = 0;
1065          if(wrt(fd, &lf, 1) != 1)
1066          {
1067            res = 0;
1068            break;
1069          }
1070        }
1071        do
1072        {
1073          int count;
1074          int sub = 0;
1075
1076          b = e;
1077          for(i = 0; i < rest; ++i, ++e)
1078          {
1079            int pcr = pended_cr;
1080            pended_cr = 0;
1081            if(*e == '\r')
1082            {
1083              pended_cr = 1;
1084            }
1085            else if(*e == '\n')
1086            {
1087              if(pcr)
1088              {
1089                sub = 2;
1090                ++i;
1091                ++e;
1092                break;
1093              }
1094              ++bare_lfs;
1095            }
1096          }
1097          if(res == 0)
1098            break;
1099          count = i - sub - pended_cr;
1100          if(count > 0 && wrt(fd, b, count) != count)
1101          {
1102            res = 0;
1103            break;
1104          }
1105          if(sub == 2 && wrt(fd, e - 1, 1) != 1)
1106            res = 0;
1107        }
1108        while((rest -= i) > 0);
1109      }
1110    }
1111
1112    if (0 > close(fd) || res == 0)
1113    {
1114      send_reply(info, 452, "Error writing file.");
1115      close_data_socket(info);
1116      return;
1117    }
1118  }
1119
1120  if (bare_lfs > 0)
1121  {
1122    snprintf(buf, FTPD_BUFSIZE,
1123      "Transfer complete. WARNING! %d bare linefeeds received in ASCII mode.",
1124      bare_lfs);
1125    send_reply(info, 226, buf);
1126  }
1127  else
1128    send_reply(info, 226, "Transfer complete.");
1129  close_data_socket(info);
1130
1131}
1132
1133
1134/*
1135 * send_dirline
1136 *
1137 * Sends one line of LIST command reply corresponding to single file.
1138 *
1139 * Input parameters:
1140 *   s - socket descriptor to send data to
1141 *   wide - if 0, send only file name.  If not 0, send 'stat' info as well in
1142 *          "ls -l" format.
1143 *   curTime - current time
1144 *   path - path to be prepended to what is given by 'add'
1145 *   add  - path to be appended to what is given by 'path', the resulting path
1146 *          is then passed to 'stat()' routine
1147 *   name - file name to be reported in output
1148 *   buf  - buffer for temporary data
1149 *
1150 * Output parameters:
1151 *   returns 0 on failure, 1 on success
1152 *
1153 */
1154static int
1155send_dirline(int s, int wide, time_t curTime, char const* path,
1156  char const* add, char const* fname, char* buf)
1157{
1158  if(wide)
1159  {
1160    struct stat stat_buf;
1161
1162    int plen = strlen(path);
1163    int alen = strlen(add);
1164    if(plen == 0)
1165    {
1166      buf[plen++] = '/';
1167      buf[plen] = '\0';
1168    }
1169    else
1170    {
1171      strcpy(buf, path);
1172      if(alen > 0 && buf[plen - 1] != '/')
1173      {
1174        buf[plen++] = '/';
1175        if(plen >= FTPD_BUFSIZE)
1176          return 0;
1177        buf[plen] = '\0';
1178      }
1179    }
1180    if(plen + alen >= FTPD_BUFSIZE)
1181      return 0;
1182    strcpy(buf + plen, add);
1183
1184    if (stat(buf, &stat_buf) == 0)
1185    {
1186      int len;
1187      struct tm bt;
1188      time_t tf = stat_buf.st_mtime;
1189      enum { SIZE = 80 };
1190      time_t SIX_MONTHS = (365L*24L*60L*60L)/2L;
1191      char timeBuf[SIZE];
1192      gmtime_r(&tf, &bt);
1193      if(curTime > tf + SIX_MONTHS || tf > curTime + SIX_MONTHS)
1194        strftime (timeBuf, SIZE, "%b %d  %Y", &bt);
1195      else
1196        strftime (timeBuf, SIZE, "%b %d %H:%M", &bt);
1197
1198      len = snprintf(buf, FTPD_BUFSIZE,
1199        "%c%c%c%c%c%c%c%c%c%c  1 %5d %5d %11u %s %s\r\n",
1200        (S_ISLNK(stat_buf.st_mode)?('l'):
1201          (S_ISDIR(stat_buf.st_mode)?('d'):('-'))),
1202        (stat_buf.st_mode & S_IRUSR)?('r'):('-'),
1203        (stat_buf.st_mode & S_IWUSR)?('w'):('-'),
1204        (stat_buf.st_mode & S_IXUSR)?('x'):('-'),
1205        (stat_buf.st_mode & S_IRGRP)?('r'):('-'),
1206        (stat_buf.st_mode & S_IWGRP)?('w'):('-'),
1207        (stat_buf.st_mode & S_IXGRP)?('x'):('-'),
1208        (stat_buf.st_mode & S_IROTH)?('r'):('-'),
1209        (stat_buf.st_mode & S_IWOTH)?('w'):('-'),
1210        (stat_buf.st_mode & S_IXOTH)?('x'):('-'),
1211        (int)stat_buf.st_uid,
1212        (int)stat_buf.st_gid,
1213        (int)stat_buf.st_size,
1214        timeBuf,
1215        fname
1216      );
1217
1218      if(send(s, buf, len, 0) != len)
1219        return 0;
1220    }
1221  }
1222  else
1223  {
1224    int len = snprintf(buf, FTPD_BUFSIZE, "%s\r\n", fname);
1225    if(send(s, buf, len, 0) != len)
1226      return 0;
1227  }
1228  return 1;
1229}
1230
1231/*
1232 * command_list
1233 *
1234 * Send file list to client.
1235 *
1236 * Input parameters:
1237 *   info - corresponding SessionInfo structure
1238 *   char *fname  - File (or directory) to list.
1239 *
1240 * Output parameters:
1241 *   NONE
1242 */
1243static void
1244command_list(FTPD_SessionInfo_t *info, char const *fname, int wide)
1245{
1246  int                 s;
1247  DIR                 *dirp = 0;
1248  struct dirent       *dp = 0;
1249  struct stat         stat_buf;
1250  char                buf[FTPD_BUFSIZE];
1251  time_t curTime;
1252  int sc = 1;
1253
1254  if(!info->auth)
1255  {
1256    send_reply(info, 550, "Access denied.");
1257    return;
1258  }
1259
1260  send_reply(info, 150, "Opening ASCII mode data connection for LIST.");
1261
1262  s = data_socket(info);
1263  if(0 > s)
1264  {
1265    syslog(LOG_ERR, "ftpd: Error connecting to data socket.");
1266    return;
1267  }
1268
1269  if(fname[0] == '\0')
1270    fname = ".";
1271
1272  if (0 > stat(fname, &stat_buf))
1273  {
1274    snprintf(buf, FTPD_BUFSIZE,
1275      "%s: No such file or directory.\r\n", fname);
1276    send(s, buf, strlen(buf), 0);
1277  }
1278  else if (S_ISDIR(stat_buf.st_mode) && (NULL == (dirp = opendir(fname))))
1279  {
1280    snprintf(buf, FTPD_BUFSIZE,
1281      "%s: Can not open directory.\r\n", fname);
1282    send(s, buf, strlen(buf), 0);
1283  }
1284  else
1285  {
1286    time(&curTime);
1287    if(!dirp && *fname)
1288      sc = sc && send_dirline(s, wide, curTime, fname, "", fname, buf);
1289    else {
1290      /* FIXME: need "." and ".." only when '-a' option is given */
1291      sc = sc && send_dirline(s, wide, curTime, fname, "", ".", buf);
1292      sc = sc && send_dirline(s, wide, curTime, fname,
1293        (strcmp(fname, ftpd_root) ? ".." : ""), "..", buf);
1294      while (sc && (dp = readdir(dirp)) != NULL)
1295        sc = sc &&
1296          send_dirline(s, wide, curTime, fname, dp->d_name, dp->d_name, buf);
1297    }
1298  }
1299
1300  if(dirp)
1301    closedir(dirp);
1302  close_data_socket(info);
1303
1304  if(sc)
1305    send_reply(info, 226, "Transfer complete.");
1306  else
1307    send_reply(info, 426, "Connection aborted.");
1308}
1309
1310
1311/*
1312 * command_cwd
1313 *
1314 * Change current working directory.
1315 *
1316 * Input parameters:
1317 *   info - corresponding SessionInfo structure
1318 *   dir  - directory name passed in CWD command
1319 *
1320 * Output parameters:
1321 *   NONE
1322 *
1323 */
1324static void
1325command_cwd(FTPD_SessionInfo_t  *info, char *dir)
1326{
1327  if(!info->auth)
1328  {
1329    send_reply(info, 550, "Access denied.");
1330    return;
1331  }
1332
1333  if(chdir(dir) == 0)
1334    send_reply(info, 250, "CWD command successful.");
1335  else
1336    send_reply(info, 550, "CWD command failed.");
1337}
1338
1339
1340/*
1341 * command_pwd
1342 *
1343 * Send current working directory to client.
1344 *
1345 * Input parameters:
1346 *   info - corresponding SessionInfo structure
1347 *
1348 * Output parameters:
1349 *   NONE
1350 */
1351static void
1352command_pwd(FTPD_SessionInfo_t  *info)
1353{
1354  char buf[FTPD_BUFSIZE];
1355  char const* cwd;
1356  errno = 0;
1357  buf[0] = '"';
1358
1359  if(!info->auth)
1360  {
1361    send_reply(info, 550, "Access denied.");
1362    return;
1363  }
1364
1365  cwd = getcwd(buf + 1, FTPD_BUFSIZE - 4);
1366  if(cwd)
1367  {
1368    int len = strlen(cwd);
1369    static char const txt[] = "\" is the current directory.";
1370    int size = sizeof(txt);
1371    if(len + size + 1 >= FTPD_BUFSIZE)
1372      size = FTPD_BUFSIZE - len - 2;
1373    memcpy(buf + len + 1, txt, size);
1374    buf[len + size] = '\0';
1375    send_reply(info, 250, buf);
1376  }
1377  else {
1378    snprintf(buf, FTPD_BUFSIZE, "Error: %s.", serr());
1379    send_reply(info, 452, buf);
1380  }
1381}
1382
1383/*
1384 * command_mdtm
1385 *
1386 * Handle FTP MDTM command (send file modification time to client)/
1387 *
1388 * Input parameters:
1389 *   info - corresponding SessionInfo structure
1390 *   fname - file name passed in MDTM command
1391 *
1392 * Output parameters:
1393 *   info->cwd is set to new CWD value.
1394 */
1395static void
1396command_mdtm(FTPD_SessionInfo_t  *info, char const* fname)
1397{
1398  struct stat stbuf;
1399  char buf[FTPD_BUFSIZE];
1400
1401  if(!info->auth)
1402  {
1403    send_reply(info, 550, "Access denied.");
1404    return;
1405  }
1406
1407  if (0 > stat(fname, &stbuf))
1408  {
1409    snprintf(buf, FTPD_BUFSIZE, "%s: %s.", fname, serr());
1410    send_reply(info, 550, buf);
1411  }
1412  else
1413  {
1414    struct tm *t = gmtime(&stbuf.st_mtime);
1415    snprintf(buf, FTPD_BUFSIZE, "%04d%02d%02d%02d%02d%02d",
1416      1900 + t->tm_year,
1417      t->tm_mon+1, t->tm_mday,
1418      t->tm_hour, t->tm_min, t->tm_sec);
1419    send_reply(info, 213, buf);
1420  }
1421}
1422
1423static void
1424command_size(FTPD_SessionInfo_t *info, char const* fname)
1425{
1426  struct stat stbuf;
1427  char buf[FTPD_BUFSIZE];
1428
1429  if(!info->auth)
1430  {
1431    send_reply(info, 550, "Access denied.");
1432    return;
1433  }
1434
1435  if (info->xfer_mode != TYPE_I || 0 > stat(fname, &stbuf) || stbuf.st_size < 0)
1436  {
1437    send_reply(info, 550, "Could not get file size.");
1438  }
1439  else
1440  {
1441    snprintf(buf, FTPD_BUFSIZE, "%" PRIuMAX, (uintmax_t) stbuf.st_size);
1442    send_reply(info, 213, buf);
1443  }
1444}
1445
1446/*
1447 * command_port
1448 *
1449 * This procedure fills address for data connection given the IP address and
1450 * port of the remote machine.
1451 *
1452 * Input parameters:
1453 *   info - corresponding SessionInfo structure
1454 *   args - arguments to the "PORT" command.
1455 *
1456 * Output parameters:
1457 *   info->data_addr is set according to arguments of the PORT command.
1458 *   info->use_default is set to 0 on success, 1 on failure.
1459 */
1460static void
1461command_port(FTPD_SessionInfo_t *info, char const *args)
1462{
1463  enum { NUM_FIELDS = 6 };
1464  unsigned int a[NUM_FIELDS];
1465  int n;
1466
1467  close_data_socket(info);
1468
1469  n = sscanf(args, "%u,%u,%u,%u,%u,%u", a+0, a+1, a+2, a+3, a+4, a+5);
1470  if(NUM_FIELDS == n)
1471  {
1472    int i;
1473    union {
1474      uint8_t b[NUM_FIELDS];
1475      struct {
1476        uint32_t ip;
1477        uint16_t port;
1478      } u ;
1479    } ip_info;
1480
1481    for(i = 0; i < NUM_FIELDS; ++i)
1482    {
1483      if(a[i] > 255)
1484        break;
1485      ip_info.b[i] = (uint8_t)a[i];
1486    }
1487
1488    if(i == NUM_FIELDS)
1489    {
1490      /* Note: while it contradicts with RFC959, we don't allow PORT command
1491       * to specify IP address different than those of the originating client
1492       * for the sake of safety. */
1493      if (ip_info.u.ip == info->def_addr.sin_addr.s_addr)
1494      {
1495        info->data_addr.sin_addr.s_addr = ip_info.u.ip;
1496        info->data_addr.sin_port        = ip_info.u.port;
1497        info->data_addr.sin_family      = AF_INET;
1498        memset(info->data_addr.sin_zero, 0, sizeof(info->data_addr.sin_zero));
1499
1500        info->use_default = 0;
1501        send_reply(info, 200, "PORT command successful.");
1502        return; /* success */
1503      }
1504      else
1505      {
1506        send_reply(info, 425, "Address doesn't match peer's IP.");
1507        return;
1508      }
1509    }
1510  }
1511  send_reply(info, 501, "Syntax error.");
1512}
1513
1514
1515/*
1516 * command_pasv
1517 *
1518 * Handle FTP PASV command.
1519 * Open socket, listen for and accept connection on it.
1520 *
1521 * Input parameters:
1522 *   info - corresponding SessionInfo structure
1523 *
1524 * Output parameters:
1525 *   info->pasv_socket is set to the descriptor of the data socket
1526 */
1527static void
1528command_pasv(FTPD_SessionInfo_t *info)
1529{
1530  int s = -1;
1531  int err = 1;
1532
1533  close_data_socket(info);
1534
1535  s = socket(PF_INET, SOCK_STREAM, 0);
1536  if (s < 0)
1537    syslog(LOG_ERR, "ftpd: Error creating PASV socket: %s", serr());
1538  else
1539  {
1540    struct sockaddr_in addr;
1541    socklen_t addrLen = sizeof(addr);
1542
1543    addr = info->ctrl_addr;
1544    addr.sin_port = htons(0);
1545
1546    if (0 > bind(s, (struct sockaddr *)&addr, addrLen))
1547      syslog(LOG_ERR, "ftpd: Error binding PASV socket: %s", serr());
1548    else if (0 > listen(s, 1))
1549      syslog(LOG_ERR, "ftpd: Error listening on PASV socket: %s", serr());
1550    else if(set_socket_timeout(s, info->idle))
1551    {
1552      char buf[FTPD_BUFSIZE];
1553      unsigned char const *ip, *p;
1554
1555      getsockname(s, (struct sockaddr *)&addr, &addrLen);
1556      ip = (unsigned char const*)&(addr.sin_addr);
1557      p  = (unsigned char const*)&(addr.sin_port);
1558      snprintf(buf, FTPD_BUFSIZE, "Entering passive mode (%u,%u,%u,%u,%u,%u).",
1559        ip[0], ip[1], ip[2], ip[3], p[0], p[1]);
1560      send_reply(info, 227, buf);
1561
1562      info->pasv_socket = accept(s, (struct sockaddr *)&addr, &addrLen);
1563      if (0 > info->pasv_socket)
1564        syslog(LOG_ERR, "ftpd: Error accepting PASV connection: %s", serr());
1565      else
1566      {
1567        close_socket(s);
1568        s = -1;
1569        err = 0;
1570      }
1571    }
1572  }
1573  if(err)
1574  {
1575    /* (OSV) The note is from FreeBSD FTPD.
1576     * Note: a response of 425 is not mentioned as a possible response to
1577     * the PASV command in RFC959.  However, it has been blessed as a
1578     * legitimate response by Jon Postel in a telephone conversation
1579     * with Rick Adams on 25 Jan 89. */
1580    send_reply(info, 425, "Can't open passive connection.");
1581    close_socket(s);
1582  }
1583}
1584
1585
1586/*
1587 * skip_options
1588 *
1589 * Utility routine to skip options (if any) from input command.
1590 *
1591 * Input parameters:
1592 *   p  - pointer to pointer to command
1593 *
1594 * Output parameters:
1595 *   p  - is changed to point to first non-option argument
1596 */
1597static void
1598skip_options(char **p)
1599{
1600  char* buf = *p;
1601  char* last = NULL;
1602  while(1) {
1603    while(isspace((unsigned char)*buf))
1604      ++buf;
1605    if(*buf == '-') {
1606      if(*++buf == '-') { /* `--' should terminate options */
1607        if(isspace((unsigned char)*++buf)) {
1608          last = buf;
1609          do ++buf;
1610          while(isspace((unsigned char)*buf));
1611          break;
1612        }
1613      }
1614      while(*buf && !isspace((unsigned char)*buf))
1615        ++buf;
1616      last = buf;
1617    }
1618    else
1619      break;
1620  }
1621  if(last)
1622    *last = '\0';
1623  *p = buf;
1624}
1625
1626/*
1627 * split_command
1628 *
1629 * Split command into command itself, options, and arguments. Command itself
1630 * is converted to upper case.
1631 *
1632 * Input parameters:
1633 *   buf - initial command string
1634 *
1635 * Output parameter:
1636 *   buf  - is modified by inserting '\0' at ends of split entities
1637 *   cmd  - upper-cased command code
1638 *   opts - string containing all the options
1639 *   args - string containing all the arguments
1640 */
1641static void
1642split_command(char *buf, char **cmd, char **opts, char **args)
1643{
1644  char* eoc;
1645  char* p = buf;
1646  while(isspace((unsigned char)*p))
1647    ++p;
1648  *cmd = p;
1649  while(*p && !isspace((unsigned char)*p))
1650  {
1651    *p = toupper((unsigned char)*p);
1652    ++p;
1653  }
1654  eoc = p;
1655  if(*p)
1656    *p++ = '\0';
1657  while(isspace((unsigned char)*p))
1658    ++p;
1659  *opts = p;
1660  skip_options(&p);
1661  *args = p;
1662  if(*opts == p)
1663    *opts = eoc;
1664  while(*p && *p != '\r' && *p != '\n')
1665    ++p;
1666  if(*p)
1667    *p++ = '\0';
1668}
1669
1670/*
1671 * exec_command
1672 *
1673 * Parse and execute FTP command.
1674 *
1675 * FIXME: This section is somewhat of a hack.  We should have a better
1676 *        way to parse commands.
1677 *
1678 * Input parameters:
1679 *   info - corresponding SessionInfo structure
1680 *   cmd  - command to be executed (upper-case)
1681 *   args - arguments of the command
1682 *
1683 * Output parameters:
1684 *    NONE
1685 */
1686static void
1687exec_command(FTPD_SessionInfo_t *info, char* cmd, char* args)
1688{
1689  char fname[FTPD_BUFSIZE];
1690  int wrong_command = 0;
1691
1692  fname[0] = '\0';
1693
1694  if (!strcmp("PORT", cmd))
1695  {
1696    command_port(info, args);
1697  }
1698  else if (!strcmp("PASV", cmd))
1699  {
1700    command_pasv(info);
1701  }
1702  else if (!strcmp("RETR", cmd))
1703  {
1704    strncpy(fname, args, 254);
1705    command_retrieve(info, fname);
1706  }
1707  else if (!strcmp("STOR", cmd))
1708  {
1709    strncpy(fname, args, 254);
1710    command_store(info, fname);
1711  }
1712  else if (!strcmp("LIST", cmd))
1713  {
1714    strncpy(fname, args, 254);
1715    command_list(info, fname, 1);
1716  }
1717  else if (!strcmp("NLST", cmd))
1718  {
1719    strncpy(fname, args, 254);
1720    command_list(info, fname, 0);
1721  }
1722  else if (!strcmp("MDTM", cmd))
1723  {
1724    strncpy(fname, args, 254);
1725    command_mdtm(info, fname);
1726  }
1727  else if (!strcmp("SIZE", cmd))
1728  {
1729    strncpy(fname, args, 254);
1730    command_size(info, fname);
1731  }
1732  else if (!strcmp("SYST", cmd))
1733  {
1734    send_reply(info, 215, FTPD_SYSTYPE);
1735  }
1736  else if (!strcmp("TYPE", cmd))
1737  {
1738    if (args[0] == 'I')
1739    {
1740      info->xfer_mode = TYPE_I;
1741      send_reply(info, 200, "Type set to I.");
1742    }
1743    else if (args[0] == 'A')
1744    {
1745      info->xfer_mode = TYPE_A;
1746      send_reply(info, 200, "Type set to A.");
1747    }
1748    else
1749    {
1750      info->xfer_mode = TYPE_I;
1751      send_reply(info, 504, "Type not implemented.  Set to I.");
1752    }
1753  }
1754  else if (!strcmp("USER", cmd))
1755  {
1756    sscanf(args, "%254s", fname);
1757    if (info->user)
1758      free(info->user);
1759    if (info->pass)
1760      free(info->pass);
1761    info->pass = NULL;
1762    info->user = strdup(fname);
1763    if (rtems_ftpd_configuration.login &&
1764      !rtems_ftpd_configuration.login(info->user, NULL)) {
1765      info->auth = false;
1766      send_reply(info, 331, "User name okay, need password.");
1767    } else {
1768      info->auth = true;
1769      send_reply(info, 230, "User logged in.");
1770    }
1771  }
1772  else if (!strcmp("PASS", cmd))
1773  {
1774    sscanf(args, "%254s", fname);
1775    if (info->pass)
1776      free(info->pass);
1777    info->pass = strdup(fname);
1778    if (!info->user) {
1779      send_reply(info, 332, "Need account to log in");
1780    } else {
1781      if (rtems_ftpd_configuration.login &&
1782        !rtems_ftpd_configuration.login(info->user, info->pass)) {
1783        info->auth = false;
1784        send_reply(info, 530, "Not logged in.");
1785      } else {
1786        info->auth = true;
1787        send_reply(info, 230, "User logged in.");
1788      }
1789    }
1790  }
1791  else if (!strcmp("DELE", cmd))
1792  {
1793    if(!can_write() || !info->auth)
1794    {
1795      send_reply(info, 550, "Access denied.");
1796    }
1797    else if (
1798      strncpy(fname, args, 254) &&
1799      unlink(fname) == 0)
1800    {
1801      send_reply(info, 257, "DELE successful.");
1802    }
1803    else
1804    {
1805      send_reply(info, 550, "DELE failed.");
1806    }
1807  }
1808  else if (!strcmp("SITE", cmd))
1809  {
1810    char* opts;
1811    split_command(args, &cmd, &opts, &args);
1812    if(!strcmp("CHMOD", cmd))
1813    {
1814      int mask;
1815
1816      if(!can_write() || !info->auth)
1817      {
1818        send_reply(info, 550, "Access denied.");
1819      }
1820      else {
1821        char *c;
1822        c = strchr(args, ' ');
1823        if((c != NULL) && (sscanf(args, "%o", &mask) == 1) && strncpy(fname, c+1, 254)
1824          && (chmod(fname, (mode_t)mask) == 0))
1825          send_reply(info, 257, "CHMOD successful.");
1826        else
1827          send_reply(info, 550, "CHMOD failed.");
1828      }
1829    }
1830    else
1831      wrong_command = 1;
1832  }
1833  else if (!strcmp("RMD", cmd))
1834  {
1835    if(!can_write() || !info->auth)
1836    {
1837      send_reply(info, 550, "Access denied.");
1838    }
1839    else if (
1840      strncpy(fname, args, 254) &&
1841      rmdir(fname) == 0)
1842    {
1843      send_reply(info, 257, "RMD successful.");
1844    }
1845    else
1846    {
1847      send_reply(info, 550, "RMD failed.");
1848    }
1849  }
1850  else if (!strcmp("MKD", cmd))
1851  {
1852    if(!can_write() || !info->auth)
1853    {
1854      send_reply(info, 550, "Access denied.");
1855    }
1856    else if (
1857      strncpy(fname, args, 254) &&
1858      mkdir(fname, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
1859    {
1860      send_reply(info, 257, "MKD successful.");
1861    }
1862    else
1863    {
1864      send_reply(info, 550, "MKD failed.");
1865    }
1866  }
1867  else if (!strcmp("CWD", cmd))
1868  {
1869    strncpy(fname, args, 254);
1870    command_cwd(info, fname);
1871  }
1872  else if (!strcmp("CDUP", cmd))
1873  {
1874    command_cwd(info, "..");
1875  }
1876  else if (!strcmp("PWD", cmd))
1877  {
1878    command_pwd(info);
1879  }
1880  else
1881    wrong_command = 1;
1882
1883  if(wrong_command)
1884    send_reply(info, 500, "Command not understood.");
1885}
1886
1887
1888/*
1889 * session
1890 *
1891 * This task handles single session.  It is waked up when the FTP daemon gets a
1892 * service request from a remote machine.  Here, we watch for commands that
1893 * will come through the control connection.  These commands are then parsed
1894 * and executed until the connection is closed, either unintentionally or
1895 * intentionally with the "QUIT" command.
1896 *
1897 * Input parameters:
1898 *   arg - pointer to corresponding SessionInfo.
1899 *
1900 * Output parameters:
1901 *   NONE
1902 */
1903static void
1904session(rtems_task_argument arg)
1905{
1906  FTPD_SessionInfo_t  *const info = (FTPD_SessionInfo_t  *)arg;
1907  int chroot_made = 0;
1908
1909  rtems_libio_set_private_env();
1910
1911  /* chroot() can fail here because the directory may not exist yet. */
1912  chroot_made = chroot(ftpd_root) == 0;
1913
1914  while(1)
1915  {
1916    rtems_event_set set;
1917    int rv;
1918
1919    rtems_event_receive(FTPD_RTEMS_EVENT, RTEMS_EVENT_ANY, RTEMS_NO_TIMEOUT,
1920      &set);
1921
1922    chroot_made = chroot_made || chroot(ftpd_root) == 0;
1923
1924    rv = chroot_made ? chdir("/") : -1;
1925
1926    errno = 0;
1927
1928    if (rv == 0)
1929    {
1930      send_reply(info, 220, FTPD_SERVER_MESSAGE);
1931
1932      while (1)
1933      {
1934        char buf[FTPD_BUFSIZE];
1935        char *cmd, *opts, *args;
1936
1937        if (fgets(buf, FTPD_BUFSIZE, info->ctrl_fp) == NULL)
1938        {
1939          syslog(LOG_INFO, "ftpd: Connection aborted.");
1940          break;
1941        }
1942
1943        split_command(buf, &cmd, &opts, &args);
1944
1945        if (!strcmp("QUIT", cmd))
1946        {
1947          send_reply(info, 221, "Goodbye.");
1948          break;
1949        }
1950        else
1951        {
1952          exec_command(info, cmd, args);
1953        }
1954      }
1955    }
1956    else
1957    {
1958      send_reply(info, 421, "Service not available, closing control connection.");
1959    }
1960
1961    /*
1962     * Go back to the root directory.  A use case is to release a current
1963     * directory in a mounted file system on dynamic media, e.g. USB stick.
1964     * The return value can be ignored since the next session will try do the
1965     * operation again and an error check is performed in this case.
1966     */
1967    chdir("/");
1968
1969    /* Close connection and put ourselves back into the task pool. */
1970    close_data_socket(info);
1971    close_stream(info);
1972    free(info->user);
1973    free(info->pass);
1974    task_pool_release(info);
1975  }
1976}
1977
1978
1979/*
1980 * daemon
1981 *
1982 * This task runs forever.  It waits for service requests on the FTP port
1983 * (port 21 by default).  When a request is received, it opens a new session
1984 * to handle those requests until the connection is closed.
1985 *
1986 * Input parameters:
1987 *   NONE
1988 *
1989 * Output parameters:
1990 *   NONE
1991 */
1992static void
1993daemon(rtems_task_argument args __attribute__((unused)))
1994{
1995  int                 s;
1996  socklen_t           addrLen;
1997  struct sockaddr_in  addr;
1998  FTPD_SessionInfo_t  *info = NULL;
1999
2000
2001  s = socket(PF_INET, SOCK_STREAM, 0);
2002  if (s < 0)
2003    syslog(LOG_ERR, "ftpd: Error creating socket: %s", serr());
2004
2005  addr.sin_family      = AF_INET;
2006  addr.sin_port        = htons(rtems_ftpd_configuration.port);
2007  addr.sin_addr.s_addr = htonl(INADDR_ANY);
2008  memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
2009
2010  if (0 > bind(s, (struct sockaddr *)&addr, sizeof(addr)))
2011    syslog(LOG_ERR, "ftpd: Error binding control socket: %s", serr());
2012  else if (0 > listen(s, 1))
2013    syslog(LOG_ERR, "ftpd: Error listening on control socket: %s", serr());
2014  else while (1)
2015  {
2016    int ss;
2017    addrLen = sizeof(addr);
2018    ss = accept(s, (struct sockaddr *)&addr, &addrLen);
2019    if (0 > ss)
2020      syslog(LOG_ERR, "ftpd: Error accepting control connection: %s", serr());
2021    else if(!set_socket_timeout(ss, ftpd_timeout))
2022      close_socket(ss);
2023    else
2024    {
2025      info = task_pool_obtain();
2026      if (NULL == info)
2027      {
2028        close_socket(ss);
2029      }
2030      else
2031      {
2032        info->ctrl_socket = ss;
2033        if ((info->ctrl_fp = fdopen(info->ctrl_socket, "r+")) == NULL)
2034        {
2035          syslog(LOG_ERR, "ftpd: fdopen() on socket failed: %s", serr());
2036          close_stream(info);
2037          task_pool_release(info);
2038        }
2039        else
2040        {
2041          /* Initialize corresponding SessionInfo structure */
2042          info->def_addr = addr;
2043          if(0 > getsockname(ss, (struct sockaddr *)&addr, &addrLen))
2044          {
2045            syslog(LOG_ERR, "ftpd: getsockname(): %s", serr());
2046            close_stream(info);
2047            task_pool_release(info);
2048          }
2049          else
2050          {
2051            info->use_default = 1;
2052            info->ctrl_addr  = addr;
2053            info->pasv_socket = -1;
2054            info->data_socket = -1;
2055            info->xfer_mode   = TYPE_A;
2056            info->data_addr.sin_port =
2057              htons(ntohs(info->ctrl_addr.sin_port) - 1);
2058            info->idle = ftpd_timeout;
2059            info->user = NULL;
2060            info->pass = NULL;
2061            if (rtems_ftpd_configuration.login)
2062              info->auth = false;
2063            else
2064              info->auth = true;
2065            /* Wakeup the session task.  The task will call task_pool_release
2066               after it closes connection. */
2067            rtems_event_send(info->tid, FTPD_RTEMS_EVENT);
2068          }
2069        }
2070      }
2071    }
2072  }
2073  rtems_task_delete(RTEMS_SELF);
2074}
2075
2076
2077/*
2078 * rtems_ftpd_start
2079 *
2080 * Here, we start the FTPD task which waits for FTP requests and services
2081 * them.  This procedure returns to its caller once the task is started.
2082 *
2083 *
2084 * Input parameters:
2085 *
2086 * Output parameters:
2087 *    returns RTEMS_SUCCESSFUL on successful start of the daemon.
2088 */
2089int
2090rtems_initialize_ftpd(void)
2091{
2092  rtems_status_code   sc;
2093  rtems_id            tid;
2094  rtems_task_priority priority;
2095  int count;
2096
2097  if (rtems_ftpd_configuration.port == 0)
2098  {
2099    rtems_ftpd_configuration.port = FTPD_CONTROL_PORT;
2100  }
2101
2102  if (rtems_ftpd_configuration.priority == 0)
2103  {
2104    rtems_ftpd_configuration.priority = 40;
2105  }
2106  priority = rtems_ftpd_configuration.priority;
2107
2108  ftpd_timeout = rtems_ftpd_configuration.idle;
2109  if (ftpd_timeout < 0)
2110    ftpd_timeout = 0;
2111  rtems_ftpd_configuration.idle = ftpd_timeout;
2112
2113  ftpd_access = rtems_ftpd_configuration.access;
2114
2115  ftpd_root = "/";
2116  if ( rtems_ftpd_configuration.root &&
2117       rtems_ftpd_configuration.root[0] == '/' )
2118    ftpd_root = rtems_ftpd_configuration.root;
2119
2120  rtems_ftpd_configuration.root = ftpd_root;
2121
2122  if (rtems_ftpd_configuration.tasks_count <= 0)
2123    rtems_ftpd_configuration.tasks_count = 1;
2124  count = rtems_ftpd_configuration.tasks_count;
2125
2126  if (!task_pool_init(count, priority))
2127  {
2128    syslog(LOG_ERR, "ftpd: Could not initialize task pool.");
2129    return RTEMS_UNSATISFIED;
2130  }
2131
2132  sc = rtems_task_create(rtems_build_name('F', 'T', 'P', 'D'),
2133    priority, RTEMS_MINIMUM_STACK_SIZE,
2134    RTEMS_PREEMPT | RTEMS_NO_TIMESLICE | RTEMS_NO_ASR |
2135    RTEMS_INTERRUPT_LEVEL(0),
2136    RTEMS_NO_FLOATING_POINT | RTEMS_LOCAL,
2137    &tid);
2138
2139  if (sc == RTEMS_SUCCESSFUL)
2140  {
2141    sc = rtems_task_start(tid, daemon, 0);
2142    if (sc != RTEMS_SUCCESSFUL)
2143      rtems_task_delete(tid);
2144  }
2145
2146  if (sc != RTEMS_SUCCESSFUL)
2147  {
2148    task_pool_done(count);
2149    syslog(LOG_ERR, "ftpd: Could not create/start FTP daemon: %s",
2150      rtems_status_text(sc));
2151    return RTEMS_UNSATISFIED;
2152  }
2153
2154  syslog(LOG_INFO, "ftpd: FTP daemon started (%d session%s max)",
2155    count, ((count > 1) ? "s" : ""));
2156
2157  return RTEMS_SUCCESSFUL;
2158}
Note: See TracBrowser for help on using the repository browser.