source: rtems/cpukit/telnetd/telnetd.c @ ba3e987e

4.104.115
Last change on this file since ba3e987e was 10b83e6, checked in by Ralf Corsepius <ralf.corsepius@…>, on 11/13/09 at 11:57:52

2009-11-13 Ralf Corsépius <ralf.corsepius@…>

  • telnetd/telnetd.c (telnetd_dflt_spawn): Adjust prototype.
  • Property mode set to 100644
File size: 12.1 KB
Line 
1/***********************************************************/
2/*
3 *
4 *  The telnet DAEMON
5 *
6 *  Author: 17,may 2001
7 *
8 *   WORK: fernando.ruiz@ctv.es
9 *   HOME: correo@fernando-ruiz.com
10 *
11 * After start the net you can start this daemon.
12 * It uses the previously inited pseudo-terminales (pty.c)
13 * getting a new terminal with getpty(). This function
14 * gives a terminal name passing a opened socket like parameter.
15 *
16 * With register_telnetd() you add a new command in the shell to start
17 * this daemon interactively. (Login in /dev/console of course)
18 *
19 * Sorry but OOB is not still implemented. (This is the first version)
20 *
21 * Till Straumann <strauman@slac.stanford.edu>
22 *  - made the 'shell' interface more generic, i.e. it is now
23 *    possible to have 'telnetd' run an arbitrary 'shell'
24 *    program.
25 *
26 * Copyright (c) 2009 embedded brains GmbH and others.
27 *
28 * embedded brains GmbH
29 * Obere Lagerstr. 30
30 * D-82178 Puchheim
31 * Germany
32 * <rtems@embedded-brains.de>
33 *
34 * The license and distribution terms for this file may be
35 * found in the file LICENSE in this distribution or at
36 * http://www.rtems.com/license/LICENSE.
37 *
38 * $Id$
39 */
40
41#ifdef HAVE_CONFIG_H
42#include "config.h"
43#endif
44
45#include <rtems.h>
46#include <rtems/error.h>
47#include <rtems/pty.h>
48#include <rtems/shell.h>
49#include <rtems/telnetd.h>
50#include <rtems/bspIo.h>
51#include <sys/socket.h>
52#include <netinet/in.h>
53#include <arpa/inet.h>
54#include <unistd.h>
55#include <stdlib.h>
56#include <stdio.h>
57#include <assert.h>
58#include <string.h>
59#include <syslog.h>
60
61#include <rtems/userenv.h>
62#include <rtems/error.h>
63#include <rtems/rtems_bsdnet.h>
64
65#define PARANOIA
66
67extern char *telnet_get_pty(int socket);
68extern int   telnet_pty_initialize(void);
69
70struct shell_args {
71  char *devname;
72  void *arg;
73  char  peername[16];
74  char  delete_myself;
75};
76
77typedef union uni_sa {
78  struct sockaddr_in sin;
79  struct sockaddr     sa;
80} uni_sa;
81
82static int sockpeername(int sock, char *buf, int bufsz);
83
84rtems_id telnetd_dflt_spawn(
85  const char *name,
86  unsigned priority,
87  unsigned stackSize,
88  void (*fn)(void*),
89  void *fnarg
90);
91
92/***********************************************************/
93static rtems_id telnetd_task_id = RTEMS_ID_NONE;
94
95rtems_id (*telnetd_spawn_task)(
96  const char *,
97  unsigned,
98  unsigned,
99  void (*)(void*),
100  void *
101) = telnetd_dflt_spawn;
102
103static char *grab_a_Connection(
104  int des_socket,
105  uni_sa *srv,
106  char *peername,
107  int sz
108)
109{
110  char *rval = 0;
111#if 0
112  socklen_t size_adr = sizeof(srv->sin);
113#else
114  /* 4.6 doesn't have socklen_t */
115  uint32_t size_adr = sizeof(srv->sin);
116#endif
117  int acp_sock;
118
119  acp_sock = accept(des_socket,&srv->sa,&size_adr);
120
121  if (acp_sock<0) {
122    perror("telnetd:accept");
123    goto bailout;
124  };
125
126  if ( !(rval=telnet_get_pty(acp_sock)) ) {
127    syslog( LOG_DAEMON | LOG_ERR, "telnetd: unable to obtain PTY");
128    /* NOTE: failing 'do_get_pty()' closed the socket */
129    goto bailout;
130  }
131
132  if (sockpeername(acp_sock, peername, sz))
133    strncpy(peername, "<UNKNOWN>", sz);
134
135#ifdef PARANOIA
136  syslog(LOG_DAEMON | LOG_INFO,
137      "telnetd: accepted connection from %s on %s",
138      peername,
139      rval);
140#endif
141
142bailout:
143
144  return rval;
145}
146
147
148static void release_a_Connection(char *devname, char *peername, FILE **pstd, int n)
149{
150
151#ifdef PARANOIA
152  syslog( LOG_DAEMON | LOG_INFO,
153      "telnetd: releasing connection from %s on %s",
154      peername,
155      devname );
156#endif
157
158  while (--n>=0)
159    if (pstd[n]) fclose(pstd[n]);
160
161}
162
163static int sockpeername(int sock, char *buf, int bufsz)
164{
165  uni_sa peer;
166  int    rval = sock < 0;
167#if 0
168  socklen_t len  = sizeof(peer.sin);
169#else
170  /* 4.6 doesn't have socklen_t */
171  uint32_t len  = sizeof(peer.sin);
172#endif
173
174  if ( !rval )
175    rval = getpeername(sock, &peer.sa, &len);
176
177  if ( !rval )
178    rval = !inet_ntop( AF_INET, &peer.sin.sin_addr, buf, bufsz );
179
180  return rval;
181}
182
183static void
184spawned_shell(void *arg);
185
186/***********************************************************/
187static void
188rtems_task_telnetd(void *task_argument)
189{
190  int                des_socket;
191  uni_sa             srv;
192  char              *devname;
193  char               peername[16];
194  int                i=1;
195  int                size_adr;
196  struct shell_args *arg = NULL;
197
198  if ((des_socket=socket(PF_INET,SOCK_STREAM,0))<0) {
199    perror("telnetd:socket");
200    telnetd_task_id = RTEMS_ID_NONE;
201    rtems_task_delete(RTEMS_SELF);
202  };
203  setsockopt(des_socket,SOL_SOCKET,SO_KEEPALIVE,&i,sizeof(i));
204
205  memset(&srv,0,sizeof(srv));
206  srv.sin.sin_family=AF_INET;
207  srv.sin.sin_port=htons(23);
208  size_adr=sizeof(srv.sin);
209  if ((bind(des_socket,&srv.sa,size_adr))<0) {
210    perror("telnetd:bind");
211    close(des_socket);
212    telnetd_task_id = RTEMS_ID_NONE;
213    rtems_task_delete(RTEMS_SELF);
214  };
215  if ((listen(des_socket,5))<0) {
216    perror("telnetd:listen");
217          close(des_socket);
218    telnetd_task_id = RTEMS_ID_NONE;
219    rtems_task_delete(RTEMS_SELF);
220  };
221
222  /* we don't redirect stdio as this probably
223   * was started from the console anyways..
224   */
225  do {
226    if (rtems_telnetd_config.keep_stdio) {
227      bool start = true;
228      char device_name [32];
229
230      ttyname_r( 1, device_name, sizeof( device_name));
231      if (rtems_telnetd_config.login_check != NULL) {
232        start = rtems_shell_login_prompt(
233          stdin,
234          stderr,
235          device_name,
236          rtems_telnetd_config.login_check
237        );
238      }
239      if (start) {
240        rtems_telnetd_config.command( device_name, arg->arg);
241      } else {
242        syslog(
243          LOG_AUTHPRIV | LOG_WARNING,
244          "telnetd: to many wrong passwords entered from %s",
245          device_name
246        );
247      }
248    } else {
249      devname = grab_a_Connection(des_socket, &srv, peername, sizeof(peername));
250
251      if ( !devname ) {
252        /* if something went wrong, sleep for some time */
253        sleep(10);
254        continue;
255      }
256
257      arg = malloc( sizeof(*arg) );
258
259      arg->devname = devname;
260      arg->arg = rtems_telnetd_config.arg;
261      strncpy(arg->peername, peername, sizeof(arg->peername));
262
263      telnetd_task_id = telnetd_spawn_task(
264        devname,
265        rtems_telnetd_config.priority,
266        rtems_telnetd_config.stack_size,
267        spawned_shell,
268        arg
269      );
270      if (telnetd_task_id == RTEMS_ID_NONE) {
271        FILE *dummy;
272
273        if ( telnetd_spawn_task != telnetd_dflt_spawn ) {
274          fprintf(stderr,"Telnetd: Unable to spawn child task\n");
275        }
276
277        /* hmm - the pty driver slot can only be
278         * released by opening and subsequently
279         * closing the PTY - this also closes
280         * the underlying socket. So we mock up
281         * a stream...
282         */
283
284        if ( !(dummy=fopen(devname,"r+")) )
285          perror("Unable to dummy open the pty, losing a slot :-(");
286        release_a_Connection(devname, peername, &dummy, 1);
287        free(arg);
288        sleep(2); /* don't accept connections too fast */
289      }
290    }
291  } while(1);
292
293  /* TODO: how to free the connection semaphore? But then -
294   *       stopping the daemon is probably only needed during
295   *       development/debugging.
296   *       Finalizer code should collect all the connection semaphore
297   *       counts and eventually clean up...
298   */
299  close(des_socket);
300  telnetd_task_id = RTEMS_ID_NONE;
301}
302
303rtems_status_code rtems_telnetd_initialize( void)
304{
305  if (telnetd_task_id != RTEMS_ID_NONE) {
306    fprintf(stderr, "telnetd already started\n");
307    return RTEMS_RESOURCE_IN_USE;
308  }
309
310  if (rtems_telnetd_config.command == NULL) {
311    fprintf(stderr, "telnetd setup with invalid command\n");
312    return RTEMS_IO_ERROR;
313  }
314
315  if ( !telnet_pty_initialize() ) {
316    fprintf(stderr, "telnetd cannot initialize PTY driver\n");
317    return RTEMS_IO_ERROR;
318  }
319
320  /* Check priority */
321  if (rtems_telnetd_config.priority <= 0) {
322    rtems_telnetd_config.priority = rtems_bsdnet_config.network_task_priority;
323  }
324  if (rtems_telnetd_config.priority < 2) {
325    rtems_telnetd_config.priority = 100;
326  }
327
328  /* Check stack size */
329  if (rtems_telnetd_config.stack_size <= 0) {
330    rtems_telnetd_config.stack_size = (size_t)32 * 1024;
331  }
332
333  /* Spawn task */
334  telnetd_task_id = telnetd_spawn_task(
335    "TNTD",
336    rtems_telnetd_config.priority,
337    RTEMS_MINIMUM_STACK_SIZE,
338    rtems_task_telnetd,
339    0
340  );
341  if (telnetd_task_id == RTEMS_ID_NONE) {
342    return RTEMS_IO_ERROR;
343  }
344
345  /* Print status */
346  if (!rtems_telnetd_config.keep_stdio) {
347    fprintf(
348      stderr,
349      "telnetd started with stacksize = %u and priority = %d\n",
350      (unsigned) rtems_telnetd_config.stack_size,
351      (unsigned) rtems_telnetd_config.priority
352    );
353  }
354
355  return RTEMS_SUCCESSFUL;
356}
357
358/* utility wrapper */
359static void
360spawned_shell(void *targ)
361{
362  rtems_status_code    sc;
363  FILE                *nstd[3]={0};
364  FILE                *ostd[3]={ stdin, stdout, stderr };
365  int                  i=0;
366  struct shell_args  *arg = targ;
367  bool login_failed = false;
368  bool start = true;
369
370  sc=rtems_libio_set_private_env();
371
372  /* newlib hack/workaround. Before we change stdin/out/err we must make
373         * sure the internal data are initialized (fileno(stdout) has this sideeffect).
374   * This should probably be done from RTEMS' libc support layer...
375   * (T.S., newlibc-1.13; 2005/10)
376         */
377
378  fileno(stdout);
379
380  if (RTEMS_SUCCESSFUL != sc) {
381    rtems_error(sc,"rtems_libio_set_private_env");
382    goto cleanup;
383  }
384
385  /* redirect stdio */
386  for (i=0; i<3; i++) {
387    if ( !(nstd[i]=fopen(arg->devname,"r+")) ) {
388      perror("unable to open stdio");
389      goto cleanup;
390    }
391  }
392
393  stdin  = nstd[0];
394  stdout = nstd[1];
395  stderr = nstd[2];
396
397  #if 0
398    printk("STDOUT is now %x (%x) (FD %i/%i)\n",
399           stdout,nstd[1],fileno(stdout),fileno(nstd[1]));
400    printf("hello\n");
401    write(fileno(stdout),"hellofd\n",8);
402  #endif
403
404  /* call their routine */
405  if (rtems_telnetd_config.login_check != NULL) {
406    start = rtems_shell_login_prompt(
407      stdin,
408      stderr,
409      arg->devname,
410      rtems_telnetd_config.login_check
411    );
412    login_failed = !start;
413  }
414  if (start) {
415    rtems_telnetd_config.command( arg->devname, arg->arg);
416  }
417
418  stdin  = ostd[0];
419  stdout = ostd[1];
420  stderr = ostd[2];
421
422  if (login_failed) {
423    syslog(
424      LOG_AUTHPRIV | LOG_WARNING,
425      "telnetd: to many wrong passwords entered from %s",
426      arg->peername
427    );
428  }
429
430cleanup:
431  release_a_Connection(arg->devname, arg->peername, nstd, i);
432  free(arg);
433}
434
435struct wrap_delete_args {
436  void (*t)(void *);
437  void           *a;
438};
439
440static rtems_task
441wrap_delete(rtems_task_argument arg)
442{
443  struct wrap_delete_args     *pwa = (struct wrap_delete_args *)arg;
444  register void              (*t)(void *) = pwa->t;
445  register void               *a   = pwa->a;
446
447  /* free argument before calling function (which may never return if
448   * they choose to delete themselves)
449   */
450  free(pwa);
451  t(a);
452  rtems_task_delete(RTEMS_SELF);
453}
454
455rtems_id
456telnetd_dflt_spawn(const char *name, unsigned int priority, unsigned int stackSize, void (*fn)(void *), void* fnarg)
457{
458  rtems_status_code        sc;
459  rtems_id                 task_id = RTEMS_ID_NONE;
460  char                     nm[4] = {'X','X','X','X' };
461  struct wrap_delete_args *pwa = malloc(sizeof(*pwa));
462
463  strncpy(nm, name, 4);
464
465  if ( !pwa ) {
466    perror("Telnetd: no memory\n");
467    return RTEMS_ID_NONE;
468  }
469
470  pwa->t = fn;
471  pwa->a = fnarg;
472
473  if ((sc=rtems_task_create(
474    rtems_build_name(nm[0], nm[1], nm[2], nm[3]),
475      (rtems_task_priority)priority,
476      stackSize,
477      RTEMS_DEFAULT_MODES,
478      RTEMS_DEFAULT_ATTRIBUTES | RTEMS_FLOATING_POINT,
479      &task_id)) ||
480    (sc=rtems_task_start(
481      task_id,
482      wrap_delete,
483      (rtems_task_argument)pwa))) {
484        free(pwa);
485        rtems_error(sc,"Telnetd: spawning task failed");
486        return RTEMS_ID_NONE;
487  }
488  return task_id;
489}
490
491/* convenience routines for CEXP (retrieve stdio descriptors
492 * from reent structure)
493 */
494#ifdef stdin
495static __inline__ FILE *
496_stdin(void)  { return stdin; }
497#undef stdin
498FILE *stdin(void)  { return _stdin(); }
499#endif
500#ifdef stdout
501static __inline__ FILE *
502_stdout(void) { return stdout; }
503#undef stdout
504FILE *stdout(void) { return _stdout(); }
505#endif
506#ifdef stderr
507static __inline__ FILE *
508_stderr(void) { return stderr; }
509#undef stderr
510FILE *stderr(void) { return _stderr(); }
511#endif
512
513/* MUST NOT USE stdin & friends below here !!!!!!!!!!!!! */
Note: See TracBrowser for help on using the repository browser.