server_session.c 24.7 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 lsh_user)
Niels Möller's avatar
Niels Möller committed
160

161
       (initial_window . UINT32)
Niels Möller's avatar
Niels Möller committed
162
163
164
165
166
167
168
169
170
171

       ; 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 
172
173
       (in object lsh_fd)
       (out object lsh_fd)
174
175
       ;; err may be NULL, if there's no separate stderr channel.
       ;; This happens if we use a pty, and the bash workaround
176
       (err object lsh_fd)))
Niels Möller's avatar
Niels Möller committed
177
178
179
*/

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

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

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

207
208
209
210
211
  /* FIXME: Perhaps it's better to just check the read pointers, and
   * not bother with the alive-flags? */
  if (session->out->super.alive)
    {
      assert(session->out->read);
212

213
214
215
216
      session->out->want_read = 1;
    }
  
  if (session->err && session->err->super.alive)
217
    {
218
      assert(session->err->read);
Niels Möller's avatar
Niels Möller committed
219
  
220
      session->err->want_read = 1;
221
    }
Niels Möller's avatar
Niels Möller committed
222
223
}

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

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

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

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

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

245
struct ssh_channel *
246
make_server_session(struct lsh_user *user,
247
		    UINT32 initial_window,
248
		    struct alist *request_types)
Niels Möller's avatar
Niels Möller committed
249
250
251
252
253
{
  NEW(server_session, self);

  init_channel(&self->super);

254
255
  self->initial_window = initial_window;

Niels Möller's avatar
Niels Möller committed
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
281
282
283
  /* 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
284
       (user object lsh_user)
Niels Möller's avatar
Niels Möller committed
285
286
287
       (session_requests object alist)))
*/

288
#define WINDOW_SIZE 10000
Niels Möller's avatar
Niels Möller committed
289

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

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

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

316
struct channel_open *
317
make_open_session(struct lsh_user *user,
318
		  struct alist *session_requests)
Niels Möller's avatar
Niels Möller committed
319
320
321
322
323
324
325
326
327
328
{
  NEW(open_session, closure);

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

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

       ; Requests specific to session channels 
339
340
       (session_requests object alist)))
*/
Niels Möller's avatar
Niels Möller committed
341
342

/* Start an authenticated ssh-connection service */
Niels Möller's avatar
Niels Möller committed
343
344
345
346
347
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
348
349
{
  CAST(server_connection_service, closure, s);
350
  CAST_SUBTYPE(lsh_user, user, x);
Niels Möller's avatar
Niels Möller committed
351
  
352
353
  werror("User %pS authenticated for ssh-connection service.\n",
	 user->name);
354
355
356

  /* 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
357
   * won't work as long as an alist doesn't consist of independent
358
   * cons-objects. */
Niels Möller's avatar
Niels Möller committed
359
  
Niels Möller's avatar
Niels Möller committed
360
  COMMAND_RETURN
361
362
363
    (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
364
  
Niels Möller's avatar
Niels Möller committed
365
366
}

367
368
369
370
/* 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
371
struct command *
372
make_server_connection_service(struct alist *session_requests)
Niels Möller's avatar
Niels Möller committed
373
374
375
376
377
378
379
380
381
382
383
384
385
{
  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",
386
				      STRSIGNAL(signal));
Niels Möller's avatar
Niels Möller committed
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
444
445
446
447
  
  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
448
449
450
      A_WRITE(channel->write,
	      (signaled
	       ? format_exit_signal(channel, core, value)
451
	       : format_exit(channel, value)) );
Niels Möller's avatar
Niels Möller committed
452
453
454

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

462
463
static struct exit_callback *
make_exit_shell(struct server_session *session)
Niels Möller's avatar
Niels Möller committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
{
  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)
    {
489
      werror("socketpair() failed: %z\n", STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
490
491
492
493
494
495
      return 0;
    }
  debug("Created socket pair. Using fd:s %i <-- %i\n", fds[0], fds[1]);

  if (SHUTDOWN(fds[0], SHUT_WR) < 0)
    {
496
      werror("shutdown(%i, SEND) failed: %z\n", fds[0], STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
497
498
499
500
      goto fail;
    }
  if (SHUTDOWN(fds[1], SHUT_RD) < 0)
    {
501
      werror("shutdown(%i, REC) failed: %z\n", fds[0], STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
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
541
542
543
544
    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;
}

545
546
#define BASH_WORKAROUND 1

Niels Möller's avatar
Niels Möller committed
547
548
549
550
551
552
553
554
555
556
557
558
559
#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);
560
561
  debug("\n");
  
Niels Möller's avatar
Niels Möller committed
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
  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) 
            {
578
579
580
581
582
583
584
585
586
#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
587
588
589
590
591
	      if (make_pipe(err))
		{
		  /* Success! */
		  return 1;
		}
592
#endif /* !BASH_WORKAROUND */
Niels Möller's avatar
Niels Möller committed
593
              saved_errno = errno;
594
	      
Niels Möller's avatar
Niels Möller committed
595
596
597
598
599
600
601
602
603
604
605
            }
	  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",
606
	     errno, STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
607
608
609
610
611
612
613
614
615
616
    }
  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 */

617
618
619
620
621
/* 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)
622
623
624
625
626
627
628
629
630
{
  int in[2];
  int out[2];
  int err[2];

  int using_pty = 0;
  
  if (session->process)
    /* Already spawned a shell or command */
631
    return -1;
632
633
634
635
636
637
638
639
  
  /* {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))
640
    return -1;
641
642
643
644
645
646
647
  {
    pid_t child;

    if (USER_FORK(session->user, &child))
      {
	if (child)
	  { /* Parent */
648
649
	    struct ssh_channel *channel = &session->super;
	    
650
	    debug("Parent process\n");
651
	    REAP(reap, child, make_exit_shell(session));
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
	  
	    /* 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
671
		= io_write(make_lsh_fd(backend, in[1],
672
673
674
675
676
677
678
679
680
681
				       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
682
		= io_read(make_lsh_fd(backend, out[0], io_exception_handler),
683
684
685
686
			  make_channel_read_data(channel),
			  read_close_callback);
	      session->err 
		= ( (err[0] != -1)
687
		    ? io_read(make_lsh_fd(backend, err[0], io_exception_handler),
688
689
690
691
692
693
			      make_channel_read_stderr(channel),
			      read_close_callback)
		    : NULL);
	    }
	
	    channel->receive = do_receive;
694
	    channel->send_adjust = do_send_adjust;
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
	    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);

714
	    return 1;
715
716
717
	  }
	else
	  { /* Child */
718
	    debug("spawn_process: Child process\n");
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
774
775
776
777
	    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]);

778
	    return 0;
779
780
781
782
783
784
785
786
787
788
789
790
	  }
      }
    /* 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]);
  }
791
  return -1;
792
793
}

794
795
796
static struct exception shell_request_failed =
STATIC_EXCEPTION(EXC_CHANNEL_REQUEST, "Shell request failed");

Niels Möller's avatar
Niels Möller committed
797
798
799
static void
do_spawn_shell(struct channel_request *c,
	       struct ssh_channel *channel,
800
801
802
803
804
805
	       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
806
807
{
  CAST(shell_request, closure, c);
808
  CAST(server_session, session, channel);
Niels Möller's avatar
Niels Möller committed
809
810

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

820
821
822
823
824
  switch (spawn_process(session, closure->backend, closure->reap))
    {
    case 1: /* Parent */
      /* NOTE: The return value is not used. */
      COMMAND_RETURN(s, channel);
825
      channel_start_receive(channel, session->initial_window);
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
      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
847

848
849
850
851
852
853
854
#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
855

856
857
858
859
860
861
862
863
864
865
866
867
868
#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
869

870
871
872
873
874
875
876
      break;
    default:
      fatal("Internal error!");
  }
 fail:
  EXCEPTION_RAISE(e, &shell_request_failed);
}
Niels Möller's avatar
Niels Möller committed
877

878
879
880
881
882
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
883

884
885
886
887
888
889
  closure->super.handler = do_spawn_shell;
  closure->backend = backend;
  closure->reap = reap;
  
  return &closure->super;
}
Niels Möller's avatar
Niels Möller committed
890

891
892
static struct exception exec_request_failed =
STATIC_EXCEPTION(EXC_CHANNEL_REQUEST, "Exec request failed");
893

894
895
896
897
898
899
900
901
902
903
904
905
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
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
  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);
934
      channel_start_receive(channel, session->initial_window);
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
      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
953
	  }
954
	assert(env_length <= MAX_ENV);
Niels Möller's avatar
Niels Möller committed
955
956
#undef MAX_ENV

957
	USER_EXEC(session->user, 0, argv, env_length, env);
958
	
959
960
961
962
	/* 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
963
      }
964
965
966
967
968
969
970
    case -1:
      /* fork() failed */
      lsh_string_free(command_line);

      break;
    default:
      fatal("Internal error!");
Niels Möller's avatar
Niels Möller committed
971
972
  }
 fail:
973
  EXCEPTION_RAISE(e, &shell_request_failed);
Niels Möller's avatar
Niels Möller committed
974
975
}

976
struct channel_request *
977
978
make_exec_handler(struct io_backend *backend,
		  struct reap *reap)
Niels Möller's avatar
Niels Möller committed
979
980
981
{
  NEW(shell_request, closure);

982
  closure->super.handler = do_spawn_exec;
Niels Möller's avatar
Niels Möller committed
983
984
985
986
987
988
989
  closure->backend = backend;
  closure->reap = reap;
  
  return &closure->super;
}

#if WITH_PTY_SUPPORT
990
991
992
993

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

Niels Möller's avatar
Niels Möller committed
994
/* pty_handler */
Niels Möller's avatar
Niels Möller committed
995
996
997
998
static void
do_alloc_pty(struct channel_request *c UNUSED,
	     struct ssh_channel *channel,
	     struct ssh_connection *connection UNUSED,
999
1000
	     UINT32 type UNUSED,
	     int want_reply UNUSED,