server_session.c 24.6 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* server_session.c
 *
 * $Id$
 */

/* lsh, an implementation of the ssh protocol
 *
 * Copyright (C) 1998 Niels Mller
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "server_session.h"

27
#include "channel_commands.h"
Niels Möller's avatar
Niels Möller committed
28
#include "format.h"
29
#include "read_data.h"
Niels Möller's avatar
Niels Möller committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "server_pty.h"
#include "ssh.h"
#include "tcpforward.h"
#include "translate_signal.h"
#include "tty.h"
#include "werror.h"
#include "xalloc.h"

#include <errno.h>

/* For debug */
#include <signal.h>
#include <string.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <sys/types.h>
#include <sys/socket.h>
/* #include <pwd.h> */

#if HAVE_UTMP_H
#include <utmp.h>
#endif

#if HAVE_UTMPX_H
#include <utmpx.h>
#endif

/* Socket workround */
#ifndef SHUTDOWN_WORKS_WITH_UNIX_SOCKETS

/* There's an how++ missing in the af_unix shutdown implementation of
 * some linux versions. Try an ugly workaround. */
#ifdef linux

/* From src/linux/include/net/sock.h */
#define RCV_SHUTDOWN	1
#define SEND_SHUTDOWN	2

#undef SHUT_RD
#undef SHUT_WR
#undef SHUT_RD_WR

#define SHUT_RD RCV_SHUTDOWN
#define SHUT_WR SEND_SHUTDOWN
#define SHUT_RD_WR (RCV_SHUTDOWN | SEND_SHUTDOWN)

#else /* !linux */

/* Don't know how to work around the broken shutdown(). So disable it
 * completely. */

#define SHUTDOWN(fd, how) 0

#endif /* !linux */
#endif /* !SHUTDOWN_WORKS_WITH_UNIX_SOCKETS */

#ifndef SHUTDOWN
#define SHUTDOWN(fd, how) (shutdown((fd), (how)))
#endif

#ifndef SHUT_RD
#define SHUT_RD 0
#endif

#ifndef SHUT_WR
#define SHUT_WR 1
#endif

#ifndef SHUT_RD_WR
#define SHUT_RD_WR 2
#endif

#ifndef UT_NAMESIZE
#  define UT_NAMESIZE 8		/* FIXME: sane default value */
#endif

#include "server_session.c.x"

/* GABA:
   (class
     (name process_resource)
     (super resource)
     (vars
       (pid . pid_t)
       (signal . int)))
*/

static void do_kill_process(struct resource *r)
{
  CAST(process_resource, self, r);

  if (self->super.alive)
    {
      self->super.alive = 0;
      /* NOTE: This function only makes one attempt at killing the
       * process. An improvement would be to install a callout handler
       * which will kill -9 the process after a delay, if it hasn't died
       * voluntarily. */
      
      if (kill(self->pid, self->signal) < 0)
	{
	  werror("do_kill_process: kill() failed (errno = %i): %z\n",
134
		 errno, STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
	}
    }
}
          
struct resource *make_process_resource(pid_t pid, int signal)
{
  NEW(process_resource, self);
  self->super.alive = 1;

  self->pid = pid;
  self->signal = signal;

  self->super.kill = do_kill_process;

  return &self->super;
}

/* Session */
/* GABA:
   (class
     (name server_session)
     (super ssh_channel)
     (vars
       ; User information
159
       (user object user)
Niels Möller's avatar
Niels Möller committed
160
161
162
163
164
165
166
167
168
169
170
171
172

       ; Non-zero if a shell or command has been started. 
       ;; (running simple int)

       ; Resource to kill when the channel is closed. 
       (process object resource)

       ; pty
       (pty object pty_info)
       ; value of the TERM environment variable
       (term string)

       ; Child process's stdio 
173
174
       (in object lsh_fd)
       (out object lsh_fd)
175
176
       ;; err may be NULL, if there's no separate stderr channel.
       ;; This happens if we use a pty, and the bash workaround
177
       (err object lsh_fd)))
Niels Möller's avatar
Niels Möller committed
178
179
180
*/

/* Receive channel data */
Niels Möller's avatar
Niels Möller committed
181
182
183
static void
do_receive(struct ssh_channel *c,
	   int type, struct lsh_string *data)
Niels Möller's avatar
Niels Möller committed
184
185
186
187
188
189
{
  CAST(server_session, closure, c);

  switch(type)
    {
    case CHANNEL_DATA:
190
      A_WRITE(&closure->in->write_buffer->super, data);
Niels Möller's avatar
Niels Möller committed
191
      break;
Niels Möller's avatar
Niels Möller committed
192
193
194
    case CHANNEL_STDERR_DATA:
      werror("Ignoring unexpected stderr data.\n");
      lsh_string_free(data);
Niels Möller's avatar
Niels Möller committed
195
      break;
Niels Möller's avatar
Niels Möller committed
196
197
198
199
200
201
    default:
      fatal("Internal error!\n");
    }
}

/* We may send more data */
Niels Möller's avatar
Niels Möller committed
202
static void
203
204
do_send_adjust(struct ssh_channel *s,
	       UINT32 i UNUSED)
Niels Möller's avatar
Niels Möller committed
205
{
206
  CAST(server_session, session, s);
Niels Möller's avatar
Niels Möller committed
207

208
  assert(session->out->read);
Niels Möller's avatar
Niels Möller committed
209
  /* assert(session->out->handler); */
210

211
  session->out->want_read = 1;
212
213
214

  if (session->err)
    {
215
      assert(session->err->read);
Niels Möller's avatar
Niels Möller committed
216
      /* assert(session->err->handler); */
Niels Möller's avatar
Niels Möller committed
217
  
218
      session->err->want_read = 1;
219
    }
Niels Möller's avatar
Niels Möller committed
220
221
}

Niels Möller's avatar
Niels Möller committed
222
223
static void
do_eof(struct ssh_channel *channel)
Niels Möller's avatar
Niels Möller committed
224
225
226
{
  CAST(server_session, session, channel);

Niels Möller's avatar
Niels Möller committed
227
  write_buffer_close(session->in->write_buffer);
Niels Möller's avatar
Niels Möller committed
228
229
230

  if ( (channel->flags & CHANNEL_SENT_EOF)
       && (channel->flags & CHANNEL_CLOSE_AT_EOF))
Niels Möller's avatar
Niels Möller committed
231
    channel_close(channel);
Niels Möller's avatar
Niels Möller committed
232
233
}

Niels Möller's avatar
Niels Möller committed
234
235
static void
do_close(struct ssh_channel *c)
Niels Möller's avatar
Niels Möller committed
236
237
238
239
240
241
242
{
  CAST(server_session, session, c);

  if (session->process)
    KILL_RESOURCE(session->process);
}

243
244
245
246
struct ssh_channel *
make_server_session(struct user *user,
		    UINT32 max_window,
		    struct alist *request_types)
Niels Möller's avatar
Niels Möller committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
{
  NEW(server_session, self);

  init_channel(&self->super);

  self->super.max_window = max_window;
  /* We don't want to receive any data before we have forked some
   * process to receive it. */
  self->super.rec_window_size = 0;

  /* FIXME: Make maximum packet size configurable. */
  self->super.rec_max_packet = SSH_MAX_PACKET;

  self->super.request_types = request_types;

  self->super.close = do_close;
  
  self->user = user;

  self->process = NULL;
  
  self->in = NULL;
  self->out = NULL;
  self->err = NULL;
  
  return &self->super;
}


/* GABA:
   (class
     (name open_session)
     (super channel_open)
     (vars
281
       (user object user)
Niels Möller's avatar
Niels Möller committed
282
283
284
       (session_requests object alist)))
*/

285
#define WINDOW_SIZE 10000
Niels Möller's avatar
Niels Möller committed
286

Niels Möller's avatar
Niels Möller committed
287
288
289
static void
do_open_session(struct channel_open *s,
		struct ssh_connection *connection UNUSED,
290
		UINT32 type UNUSED,
291
		UINT32 max_packet UNUSED,
Niels Möller's avatar
Niels Möller committed
292
293
294
		struct simple_buffer *args,
		struct command_continuation *c,
		struct exception_handler *e)
Niels Möller's avatar
Niels Möller committed
295
{
296
  CAST(open_session, self, s);
Niels Möller's avatar
Niels Möller committed
297
298
299
300
301

  debug("server.c: do_open_session()\n");

  if (parse_eod(args))
    {
Niels Möller's avatar
Niels Möller committed
302
      COMMAND_RETURN(c,
303
304
		     make_server_session(self->user,
					 WINDOW_SIZE, self->session_requests));
Niels Möller's avatar
Niels Möller committed
305
306
307
    }
  else
    {
308
      PROTOCOL_ERROR(e, "trailing garbage in open message");
Niels Möller's avatar
Niels Möller committed
309
310
311
    }
}

312
313
314
struct channel_open *
make_open_session(struct user *user,
		  struct alist *session_requests)
Niels Möller's avatar
Niels Möller committed
315
316
317
318
319
320
321
322
323
324
{
  NEW(open_session, closure);

  closure->super.handler = do_open_session;
  closure->user = user;
  closure->session_requests = session_requests;
  
  return &closure->super;
}

325
326
/* A command taking two arguments: unix_user, connection,
 * returns the connection. */
Niels Möller's avatar
Niels Möller committed
327
328
329
330
331
/* GABA:
   (class
     (name server_connection_service)
     (super command)
     (vars
332
       ;; (global_requests object alist)
Niels Möller's avatar
Niels Möller committed
333
334

       ; Requests specific to session channels 
335
336
       (session_requests object alist)))
*/
Niels Möller's avatar
Niels Möller committed
337
338

/* Start an authenticated ssh-connection service */
Niels Möller's avatar
Niels Möller committed
339
340
341
342
343
static void
do_login(struct command *s,
	 struct lsh_object *x,
	 struct command_continuation *c,
	 struct exception_handler *e UNUSED)
Niels Möller's avatar
Niels Möller committed
344
345
{
  CAST(server_connection_service, closure, s);
346
  CAST_SUBTYPE(user, user, x);
Niels Möller's avatar
Niels Möller committed
347
  
348
349
  werror("User %pS authenticated for ssh-connection service.\n",
	 user->name);
350
351
352

  /* FIXME: It would be better to take one more alists as arguments,
   * and cons the ATOM_SESSION service at the head of it. But that
Niels Möller's avatar
Niels Möller committed
353
   * won't work as long as an alist doesn't consist of independent
354
   * cons-objects. */
Niels Möller's avatar
Niels Möller committed
355
  
Niels Möller's avatar
Niels Möller committed
356
  COMMAND_RETURN
357
358
359
    (c, make_install_fix_channel_open_handler
     (ATOM_SESSION, make_open_session(user,
				      closure->session_requests)));
Niels Möller's avatar
Niels Möller committed
360
  
Niels Möller's avatar
Niels Möller committed
361
362
}

363
364
365
366
/* FIXME: To make this more flexible, we need to have some argument
 * that lists (i) the channel types we want to support in
 * CHANNEL_OPEN, and (ii) for each channel type, the types of
 * channel_requests we want to support. */
Niels Möller's avatar
Niels Möller committed
367
struct command *
368
make_server_connection_service(struct alist *session_requests)
Niels Möller's avatar
Niels Möller committed
369
370
371
372
373
374
375
376
377
378
379
380
381
{
  NEW(server_connection_service, closure);

  closure->super.call = do_login;
  closure->session_requests = session_requests;

  return &closure->super;
}

struct lsh_string *format_exit_signal(struct ssh_channel *channel,
				      int core, int signal)
{
  struct lsh_string *msg = ssh_format("Process killed by %lz.\n",
382
				      STRSIGNAL(signal));
Niels Möller's avatar
Niels Möller committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
  
  return format_channel_request(ATOM_EXIT_SIGNAL,
				channel,
				0,
				"%i%c%fS%z",
				signal_local_to_network(signal),
				core,
				msg, "");
}

struct lsh_string *format_exit(struct ssh_channel *channel, int value)
{
  return format_channel_request(ATOM_EXIT_STATUS,
				channel,
				0,
				"%i", value);
}

/* GABA:
   (class
     (name exit_shell)
     (super exit_callback)
     (vars
       (session object server_session)))
*/

static void do_exit_shell(struct exit_callback *c, int signaled,
			  int core, int value)
{
  CAST(exit_shell, closure, c);
  struct server_session *session = closure->session;
  struct ssh_channel *channel = &session->super;
  
  CHECK_TYPE(server_session, session);

  if (! session->process->alive)
    {
      /* The process was killed by a the resource callback (most
       * likely because the connection died. Keep silent. */
      debug("do_exit_shell: Process already flagged as dead.\n");
      return;
    }
  
  /* No need to kill the process. */
  session->process->alive = 0;
  
  /* FIXME: Should we explicitly mark these files for closing? The
   * io-backend should notice EOF anyway. And the client should send
   * EOF when it receives news of the process's death, unless it
   * really wants to talk to any live children processes. */
#if 0
  close_fd(&session->in->super, 0);
  close_fd(session->out);
  close_fd(session->err);
#endif

  /* We close when we have both sent and received eof. */
  channel->flags |= CHANNEL_CLOSE_AT_EOF;
  
  if (!(channel->flags & CHANNEL_SENT_CLOSE))
    {
Niels Möller's avatar
Niels Möller committed
444
445
446
      A_WRITE(channel->write,
	      (signaled
	       ? format_exit_signal(channel, core, value)
447
	       : format_exit(channel, value)) );
Niels Möller's avatar
Niels Möller committed
448
449
450

      if ( (channel->flags & CHANNEL_SENT_EOF)
	   && (channel->flags & CHANNEL_RECEIVED_EOF))
Niels Möller's avatar
Niels Möller committed
451
452
	{
	  /* We have sent EOF already, so initiate close */
Niels Möller's avatar
Niels Möller committed
453
	  channel_close(channel);
Niels Möller's avatar
Niels Möller committed
454
455
456
457
	}
    }
}

458
459
static struct exit_callback *
make_exit_shell(struct server_session *session)
Niels Möller's avatar
Niels Möller committed
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
{
  NEW(exit_shell, self);

  self->super.exit = do_exit_shell;
  self->session = session;

  return &self->super;
}

/* GABA:
   (class
     (name shell_request)
     (super channel_request)
     (vars
       (backend object io_backend)
       (reap object reap)))
*/

/* Creates a one-way socket connection. Returns 1 on success, 0 on
 * failure. fds[0] is for reading, fds[1] for writing (like for the
 * pipe() system call). */
static int make_pipe(int *fds)
{
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0)
    {
485
      werror("socketpair() failed: %z\n", STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
486
487
488
489
490
491
      return 0;
    }
  debug("Created socket pair. Using fd:s %i <-- %i\n", fds[0], fds[1]);

  if (SHUTDOWN(fds[0], SHUT_WR) < 0)
    {
492
      werror("shutdown(%i, SEND) failed: %z\n", fds[0], STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
493
494
495
496
      goto fail;
    }
  if (SHUTDOWN(fds[1], SHUT_RD) < 0)
    {
497
      werror("shutdown(%i, REC) failed: %z\n", fds[0], STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
    fail:
      {
	int saved_errno = errno;

	close(fds[0]);
	close(fds[1]);

	errno = saved_errno;
	return 0;
      }
    }
  
  return 1;
}

static int make_pipes(int *in, int *out, int *err)
{
  int saved_errno;
  
  if (make_pipe(in))
    {
      if (make_pipe(out))
	{
	  if (make_pipe(err))
	    {
              return 1;
            }
	  saved_errno = errno;
          close(out[0]);
          close(out[1]);
        }
      else
	saved_errno = errno;
      close(in[0]);
      close(in[1]);
    }
  else
    saved_errno = errno;
  
  errno = saved_errno;
  return 0;
}

541
542
#define BASH_WORKAROUND 1

Niels Möller's avatar
Niels Möller committed
543
544
545
546
547
548
549
550
551
552
553
554
555
#if WITH_PTY_SUPPORT
static int make_pty(struct pty_info *pty, int *in, int *out, int *err)
{
  int saved_errno = 0;

  debug("make_pty... ");
  if (pty)
    debug("exists: \n"
	  "  alive = %i\n"
	  "  master = %i\n"
	  "  slave = %i\n"
	  "... ",
	  pty->super.alive, pty->master, pty->slave);
556
557
  debug("\n");
  
Niels Möller's avatar
Niels Möller committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
  if (pty && pty->super.alive)
    {
      debug("make_pty: Using allocated pty.\n");
      in[0] = pty->slave;
      in[1] = pty->master;

      /* Ownership of the fd:s passes on to some file objects. */
      pty->super.alive = 0;

      /* FIXME: It seems unnecessary to dup the fd:s here. But perhaps
       * having equal in and out fds may confuse the cleanup code, so
       * we leave it for now. */
      if ((out[0] = dup(pty->master)) != -1)
        {
          if ((out[1] = dup(pty->slave)) != -1) 
            {
574
575
576
577
578
579
580
581
582
#if BASH_WORKAROUND
	      /* Don't use a separate stderr channel; just dup the
	       * stdout pty to stderr. */
	      if ((err[1] = dup(pty->slave)) != -1)
                {
                  err[0] = -1;
                  return 1;
                } 
#else /* !BASH_WORKAROUND */
Niels Möller's avatar
Niels Möller committed
583
584
585
586
587
	      if (make_pipe(err))
		{
		  /* Success! */
		  return 1;
		}
588
#endif /* !BASH_WORKAROUND */
Niels Möller's avatar
Niels Möller committed
589
              saved_errno = errno;
590
	      
Niels Möller's avatar
Niels Möller committed
591
592
593
594
595
596
597
598
599
600
601
            }
	  else
	    saved_errno = errno;
	  close(out[0]);
	}
      else 
	saved_errno = errno;
      close(in[0]);
      close(in[1]);

      werror("make_pty: duping pty filedescriptors failed (errno = %i): %z\n",
602
	     errno, STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
603
604
605
606
607
608
609
610
611
612
    }
  errno = saved_errno;
  return 0;
}
#else /* !WITH_PTY_SUPPORT */
static int make_pty(struct pty_info *pty UNUSED,
		    int *in UNUSED, int *out UNUSED, int *err UNUSED)
{ return 0; }
#endif /* !WITH_PTY_SUPPORT */

613
614
615
616
617
/* Returns -1 on failure, 0 for child and +1 for parent */
static int
spawn_process(struct server_session *session,
	      struct io_backend *backend,
	      struct reap *reap)
618
619
620
621
622
623
624
625
626
{
  int in[2];
  int out[2];
  int err[2];

  int using_pty = 0;
  
  if (session->process)
    /* Already spawned a shell or command */
627
    return -1;
628
629
630
631
632
633
634
635
  
  /* {in|out|err}[0] is for reading,
   * {in|out|err}[1] for writing. */

  if (make_pty(session->pty, in, out, err))
    using_pty = 1;

  else if (!make_pipes(in, out, err))
636
    return -1;
637
638
639
640
641
642
643
  {
    pid_t child;

    if (USER_FORK(session->user, &child))
      {
	if (child)
	  { /* Parent */
644
645
	    struct ssh_channel *channel = &session->super;
	    
646
	    debug("Parent process\n");
647
	    REAP(reap, child, make_exit_shell(session));
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
	  
	    /* Close the child's fd:s */
	    close(in[0]);
	    close(out[1]);
	    close(err[1]);

	    {
	      /* Exception handlers */
	      struct exception_handler *io_exception_handler
		= make_channel_io_exception_handler(channel,
						    "lshd: Child stdio: ",
						    &default_exception_handler,
						    HANDLER_CONTEXT);

	      /* Close callback for stderr and stdout */
	      struct close_callback *read_close_callback
		= make_channel_read_close_callback(channel);

	      session->in
667
		= io_write(make_lsh_fd(backend, in[1],
668
669
670
671
672
673
674
675
676
677
				       io_exception_handler),
			   SSH_MAX_PACKET, NULL);
	  
	      /* Flow control */
	      session->in->write_buffer->report = &session->super.super;

	      /* FIXME: Should we really use the same exception handler,
	       * which will close the channel on read errors, or is it
	       * better to just send EOF on read errors? */
	      session->out
678
		= io_read(make_lsh_fd(backend, out[0], io_exception_handler),
679
680
681
682
			  make_channel_read_data(channel),
			  read_close_callback);
	      session->err 
		= ( (err[0] != -1)
683
		    ? io_read(make_lsh_fd(backend, err[0], io_exception_handler),
684
685
686
687
688
689
			      make_channel_read_stderr(channel),
			      read_close_callback)
		    : NULL);
	    }
	
	    channel->receive = do_receive;
690
	    channel->send_adjust = do_send_adjust;
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
	    channel->eof = do_eof;
	  
	    session->process
	      = make_process_resource(child, SIGHUP);

	    /* Make sure that the process and it's stdio is
	     * cleaned up if the channel or connection dies. */
	    REMEMBER_RESOURCE
	      (channel->resources, session->process);
	    /* FIXME: How to do this properly if in and out may use the
	     * same fd? */
	    REMEMBER_RESOURCE
	      (channel->resources, &session->in->super);
	    REMEMBER_RESOURCE
	      (channel->resources, &session->out->super);
	    if (session->err)
	      REMEMBER_RESOURCE
		(channel->resources, &session->err->super);

710
	    return 1;
711
712
713
	  }
	else
	  { /* Child */
714
	    debug("spawn_process: Child process\n");
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
	    assert(getuid() == session->user->uid);
	    
	    if (!USER_CHDIR_HOME(session->user))
	      {
		werror("Could not change to home (or root) directory!\n");
		_exit(EXIT_FAILURE);
	      }
	    
#if WITH_PTY_SUPPORT
	    if (using_pty)
	      {
		debug("lshd: server.c: Setting controlling tty...\n");
		if (!tty_setctty(session->pty))
		  {
		    debug("lshd: server.c: "
			  "Setting controlling tty... Failed!\n");
		    werror("lshd: Can't set controlling tty for child!\n");
		    _exit(EXIT_FAILURE);
		  }
		else
		  debug("lshd: server.c: Setting controlling tty... Ok.\n");
	      }
#endif /* WITH_PTY_SUPPORT */
	  
	    /* Close all descriptors but those used for
	     * communicationg with parent. We rely on the
	     * close-on-exec flag for all fd:s handled by the
	     * backend. */
	    
	    if (dup2(in[0], STDIN_FILENO) < 0)
	      {
		werror("Can't dup stdin!\n");
		_exit(EXIT_FAILURE);
	      }
	    close(in[0]);
	    close(in[1]);
	    
	    if (dup2(out[1], STDOUT_FILENO) < 0)
	      {
		werror("Can't dup stdout!\n");
		_exit(EXIT_FAILURE);
	      }
	    close(out[0]);
	    close(out[1]);

	    if (!dup_error_stream())
	      {
		werror("server_session: Failed to dup old stderr. Bye.\n");
		set_error_ignore();
	      }

	    if (dup2(err[1], STDERR_FILENO) < 0)
	      {
		werror("Can't dup stderr!\n");
		_exit(EXIT_FAILURE);
	      }
	    close(err[0]);
	    close(err[1]);

774
	    return 0;
775
776
777
778
779
780
781
782
783
784
785
786
	  }
      }
    /* fork() failed */
    /* Close and return channel_failure */

    close(err[0]);
    close(err[1]);
    close(out[0]);
    close(out[1]);
    close(in[0]);
    close(in[1]);
  }
787
  return -1;
788
789
}

790
791
792
static struct exception shell_request_failed =
STATIC_EXCEPTION(EXC_CHANNEL_REQUEST, "Shell request failed");

Niels Möller's avatar
Niels Möller committed
793
794
795
static void
do_spawn_shell(struct channel_request *c,
	       struct ssh_channel *channel,
796
797
798
799
800
801
	       struct ssh_connection *connection UNUSED,
	       UINT32 type UNUSED,
	       int want_reply UNUSED,
	       struct simple_buffer *args,
	       struct command_continuation *s,
	       struct exception_handler *e)
Niels Möller's avatar
Niels Möller committed
802
803
{
  CAST(shell_request, closure, c);
804
  CAST(server_session, session, channel);
Niels Möller's avatar
Niels Möller committed
805
806

  if (!parse_eod(args))
Niels Möller's avatar
Niels Möller committed
807
    {
808
      PROTOCOL_ERROR(e, "Invalid shell CHANNEL_REQUEST message.");
Niels Möller's avatar
Niels Möller committed
809
810
811
      return;
    }
    
Niels Möller's avatar
Niels Möller committed
812
813
814
815
  if (session->process)
    /* Already spawned a shell or command */
    goto fail;

816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
  switch (spawn_process(session, closure->backend, closure->reap))
    {
    case 1: /* Parent */
      /* NOTE: The return value is not used. */
      COMMAND_RETURN(s, channel);
      channel_start_receive(channel);
      return;
    case 0:
      { /* Child */
#define MAX_ENV 1
	/* No args, end the USER_EXEC method fills in argv[0]. */
	char *argv[] = { NULL, NULL };
	
	struct env_value env[MAX_ENV];
	int env_length = 0;
	
	debug("do_spawn_shell: Child process\n");
	assert(getuid() == session->user->uid);
	    	    
	if (session->term)
	  {
	    env[env_length].name ="TERM";
	    env[env_length].value = session->term;
	    env_length++;
	  }
	assert(env_length <= MAX_ENV);
#undef MAX_ENV
Niels Möller's avatar
Niels Möller committed
843

844
845
846
847
848
849
850
#if 1
	USER_EXEC(session->user, 1, argv, env_length, env);
	
	/* exec failed! */
	verbose("server_session: exec() failed (errno = %i): %z\n",
		errno, STRERROR(errno));
	_exit(EXIT_FAILURE);
Niels Möller's avatar
Niels Möller committed
851

852
853
854
855
856
857
858
859
860
861
862
863
864
#else
# define GREETING "Hello world!\n"
	if (write(STDOUT_FILENO, GREETING, strlen(GREETING)) < 0)
	  _exit(errno);
	kill(getuid(), SIGSTOP);
	if (write(STDOUT_FILENO, shell, strlen(shell)) < 0)
	  _exit(125);
	_exit(126);
# undef GREETING
#endif
      }
    case -1:
      /* fork() failed */
Niels Möller's avatar
Niels Möller committed
865

866
867
868
869
870
871
872
      break;
    default:
      fatal("Internal error!");
  }
 fail:
  EXCEPTION_RAISE(e, &shell_request_failed);
}
Niels Möller's avatar
Niels Möller committed
873

874
875
876
877
878
struct channel_request *
make_shell_handler(struct io_backend *backend,
		   struct reap *reap)
{
  NEW(shell_request, closure);
Niels Möller's avatar
Niels Möller committed
879

880
881
882
883
884
885
  closure->super.handler = do_spawn_shell;
  closure->backend = backend;
  closure->reap = reap;
  
  return &closure->super;
}
Niels Möller's avatar
Niels Möller committed
886

887
888
static struct exception exec_request_failed =
STATIC_EXCEPTION(EXC_CHANNEL_REQUEST, "Exec request failed");
889

890
891
892
893
894
895
896
897
898
899
900
901
static void
do_spawn_exec(struct channel_request *c,
	      struct ssh_channel *channel,
	      struct ssh_connection *connection UNUSED,
	      UINT32 type UNUSED,
	      int want_reply UNUSED,
	      struct simple_buffer *args,
	      struct command_continuation *s,
	      struct exception_handler *e)
{
  CAST(shell_request, closure, c);
  CAST(server_session, session, channel);
Niels Möller's avatar
Niels Möller committed
902

903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
  UINT32 command_len;
  UINT8 *command;

  struct lsh_string *command_line;
  
  if (!(parse_string(args, &command_len, &command)
	&& parse_eod(args)))
    {
      PROTOCOL_ERROR(e, "Invalid exec CHANNEL_REQUEST message.");
      return;
    }
    
  if (session->process)
    /* Already spawned a shell or command */
    goto fail;

  command_line = make_cstring_l(command_len, command);
  if (!command_line)
    EXCEPTION_RAISE(e, &exec_request_failed);
  else
    switch (spawn_process(session, closure->backend, closure->reap))
    {
    case 1: /* Parent */
      lsh_string_free(command_line);

      /* NOTE: The return value is not used. */
      COMMAND_RETURN(s, channel);
      channel_start_receive(channel);
      return;
    case 0:
      { /* Child */
#define MAX_ENV 1
	/* No args, end the USER_EXEC method fills in argv[0]. */
	char *argv[] = { NULL, "-c", command_line->data, NULL };
	
	struct env_value env[MAX_ENV];
	int env_length = 0;
	
	debug("do_spawn_shell: Child process\n");
	assert(getuid() == session->user->uid);
	    	    
	if (session->term)
	  {
	    env[env_length].name ="TERM";
	    env[env_length].value = session->term;
	    env_length++;
Niels Möller's avatar
Niels Möller committed
949
	  }
950
	assert(env_length <= MAX_ENV);
Niels Möller's avatar
Niels Möller committed
951
952
#undef MAX_ENV

953
	USER_EXEC(session->user, 3, argv, env_length, env);
954
	
955
956
957
958
	/* exec failed! */
	verbose("server_session: exec() failed (errno = %i): %z\n",
		errno, STRERROR(errno));
	_exit(EXIT_FAILURE);
Niels Möller's avatar
Niels Möller committed
959
      }
960
961
962
963
964
965
966
    case -1:
      /* fork() failed */
      lsh_string_free(command_line);

      break;
    default:
      fatal("Internal error!");
Niels Möller's avatar
Niels Möller committed
967
968
  }
 fail:
969
  EXCEPTION_RAISE(e, &shell_request_failed);
Niels Möller's avatar
Niels Möller committed
970
971
}

972
struct channel_request *
973
974
make_exec_handler(struct io_backend *backend,
		  struct reap *reap)
Niels Möller's avatar
Niels Möller committed
975
976
977
{
  NEW(shell_request, closure);

978
  closure->super.handler = do_spawn_exec;
Niels Möller's avatar
Niels Möller committed
979
980
981
982
983
984
985
  closure->backend = backend;
  closure->reap = reap;
  
  return &closure->super;
}

#if WITH_PTY_SUPPORT
986
987
988
989

static struct exception pty_request_failed =
STATIC_EXCEPTION(EXC_CHANNEL_REQUEST, "pty request failed");

Niels Möller's avatar
Niels Möller committed
990
/* pty_handler */
Niels Möller's avatar
Niels Möller committed
991
992
993
994
static void
do_alloc_pty(struct channel_request *c UNUSED,
	     struct ssh_channel *channel,
	     struct ssh_connection *connection UNUSED,
995
996
997
998
999
	     UINT32 type UNUSED,
	     int want_reply UNUSED,
	     struct simple_buffer *args,
	     struct command_continuation *s,
	     struct exception_handler *e)
Niels Möller's avatar
Niels Möller committed
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
{
  UINT32 width, height, width_p, height_p;
  UINT8 *mode;
  UINT32 mode_length;
  struct lsh_string *term = NULL;

  struct server_session *session = (struct server_session *) channel;

  verbose("Client requesting a tty...\n");
  
  /* The client may only request a tty once. */
  if (!session->pty &&
      (term = parse_string_copy(args)) &&
      parse_uint32(args, &width) &&
      parse_uint32(args, &height) &&
      parse_uint32(args, &width_p) &&
      parse_uint32(args, &height_p) &&
      parse_string(args, &mode_length, &mode) &&
      parse_eod(args))
    {
      struct pty_info *pty = make_pty_info();

1022
      if (pty_allocate(pty, session->user->uid))
Niels Möller's avatar
Niels Möller committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
        {
          struct termios ios;

          if (tty_getattr(pty->slave, &ios))
            {
	      pty->super.alive = 1;
              session->pty = pty;

	      /* Don't set TERM if the value is empty. */
	      if (!term->length)
		{
		  lsh_string_free(term);
1035
		  term = NULL;
Niels Möller's avatar
Niels Möller committed
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
		}
	      
              session->term = term;
              tty_decode_term_mode(&ios, mode_length, mode); 
	      
	      /* cfmakeraw(&ios); */
              if (tty_setattr(pty->slave, &ios) &&
                  tty_setwinsize(pty->slave,
				 width, height, width_p, height_p))
		{
1046
		  REMEMBER_RESOURCE(channel->resources, &pty->super);
Niels Möller's avatar
Niels Möller committed
1047
1048

		  verbose(" granted.\n");
1049
1050
		  COMMAND_RETURN(s, NULL);

Niels Möller's avatar
Niels Möller committed
1051
		  return;
Niels Möller's avatar
Niels Möller committed
1052
1053
1054
1055
1056
1057
1058
1059
1060
		}
	      else
		/* Close fd:s and mark the pty-struct as dead */
		KILL_RESOURCE(&pty->super);
            }
        }
      KILL(pty);
    }

Niels Möller's avatar
Niels Möller committed
1061
  verbose("Pty allocation failed.\n");
Niels Möller's avatar
Niels Möller committed
1062
  lsh_string_free(term);
Niels Möller's avatar
Niels Möller committed
1063

1064
  EXCEPTION_RAISE(e, &pty_request_failed);
Niels Möller's avatar
Niels Möller committed
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
}

struct channel_request *make_pty_handler(void)
{
  NEW(channel_request, self);

  self->handler = do_alloc_pty;

  return self;
}
#endif /* WITH_PTY_SUPPORT */