lsh.c 33.5 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
2
/* lsh.c
 *
3
 * Client main program.
4
 *
5
 */
6
7
8

/* lsh, an implementation of the ssh protocol
 *
Niels Möller's avatar
Niels Möller committed
9
 * Copyright (C) 1998, 1999, 2000, 2005 Niels Möller
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * 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
J.H.M. Dassen's avatar
J.H.M. Dassen committed
23
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Niels Möller's avatar
Niels Möller committed
24
25
 */

26
27
28
29
30
31
32
33
34
#if HAVE_CONFIG_H
#include "config.h"
#endif

#include <assert.h>
#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
Niels Möller's avatar
Niels Möller committed
35
#include <string.h>
36
37
38
39
40
41

#include <fcntl.h>

#include <sys/types.h>
#include <sys/stat.h>

42
43
44
45
#include "nettle/sexp.h"
/* For struct spki_iterator */
#include "spki/parse.h"

Niels Möller's avatar
Niels Möller committed
46
#include "alist.h"
47
#include "arglist.h"
Niels Möller's avatar
Niels Möller committed
48
#include "atoms.h"
49
#include "channel.h"
50
#include "charset.h"
Niels Möller's avatar
Niels Möller committed
51
#include "client.h"
52
#include "compress.h"
Niels Möller's avatar
Niels Möller committed
53
#include "crypto.h"
54
#include "environ.h"
Niels Möller's avatar
Niels Möller committed
55
#include "format.h"
56
#include "interact.h"
57
#include "gateway.h"
58
#include "lsh_string.h"
59
#include "pidfile.h"
Niels Möller's avatar
Niels Möller committed
60
#include "reaper.h"
61
62
#include "sexp.h"
#include "ssh.h"
63
#include "ssh_write.h"
64
#include "tcpforward.h"
65
#include "version.h"
Niels Möller's avatar
Niels Möller committed
66
#include "werror.h"
Niels Möller's avatar
Niels Möller committed
67
#include "xalloc.h"
Niels Möller's avatar
Niels Möller committed
68

69
#include "lsh_argp.h"
70

71
72
#include "lsh.c.x"

73
74
75
#define DEFAULT_ESCAPE_CHAR '~'
#define DEFAULT_SOCKS_PORT 1080

76
77
78
79
80
81
82
83
/* Flow control status: If the buffer for writing to the transport
   layer gets full, we stop reading on all channels, and we stop
   reading from all gateways. FIXME: Missing pieces:

   1. If a channel is somewhere in the opening handshake when we
      detect the transport buffer getting full, it is not signalled to
      stop, and might start generating data when the handshake is
      finished.
Niels Möller's avatar
Niels Möller committed
84

85
*/
86

87

88
/* Block size for stdout and stderr buffers */
Niels Möller's avatar
Niels Möller committed
89
90
#define BLOCK_SIZE 32768

91
92
93
94
/* Window size for the session channel
 *
 * NOTE: Large windows seem to trig a bug in sshd2. */
#define WINDOW_SIZE 10000
95

96
97
98
/* GABA:
   (class
     (name lsh_options)
99
     (super werror_config)
100
101
     (vars
       (home . "const char *")
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
       ; -1 means default.
       (escape . int)
       
       (exit_code . "int *")

       (not . int)
       (port . "const char *")
       (target . "const char *")

       (local_user . "char *")
       (user . "char *")

       (with_remote_peers . int)
       
       ; -1 means default behaviour
       (with_pty . int)

       (with_x11 . int)
       
       ; Session modifiers
       (stdin_file . "const char *")
       (stdout_file . "const char *")
       (stderr_file . "const char *")

       ; True if the process's stdin or pty (respectively) has been used. 
       (used_stdin . int)
       (used_pty . int)

131
       (detach . int)
132
133
       ; Should -B write the pid to stdout?
       (write_pid . int)
134
135
       (pid_file . "const char *")

136
137
138
139
140
141
142
143
       ; True if the client should detach when a session closes (useful for gateways)
       (detach_end . int)

       ; Inhibit actions, used to not create actions from environment parsing.
       (inhibit_actions . int)

       (start_shell . int)
       (remote_forward . int)
144
       (x11_forward . int)
145
146
       (actions struct object_queue)

147
148
149
150
151
152
153
154
       ; 0 means no, 1 means yes, -1 means use if available.
       (use_gateway . int)
       ; 0 means no, 1 means yes, -1 means start if not already available.
       (start_gateway . int)
       (stop_gateway . int)

       (gateway object local_info)

155
156
157
158
159
       (transport_args . "struct arglist")

       ; Resources that are created during argument parsing. These should be adopted
       ; by the connection once it is up and running.
       (resources object resource_list)))
160
161
162
163
*/


static struct lsh_options *
164
make_options(int *exit_code)
165
166
{
  NEW(lsh_options, self);
167
  const char *home = getenv(ENV_HOME);
168
  const char *transport_program;
169

170
  init_werror_config(&self->super);
171

Niels Möller's avatar
Niels Möller committed
172
  self->home = home;
173

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
  self->escape = -1;

  self->exit_code = exit_code;

  self->not = 0;
  self->port = NULL;
  self->target = NULL;

  USER_NAME_FROM_ENV(self->user);
  self->local_user = self->user;

  self->with_remote_peers = 0;
  self->with_pty = -1;
  self->with_x11 = 0;

  self->stdin_file = NULL;
  self->stdout_file = NULL;
  self->stderr_file = NULL;

  self->used_stdin = 0;
  self->used_pty = 0;

196
  self->detach = 0;
197
198
  self->detach_end = 0;
  self->write_pid = 0;
199
  self->pid_file = NULL;
200
201

  self->start_shell = 1;
202
  self->x11_forward = 0;
203
204
205
206
207
208
  self->remote_forward = 0;

  self->inhibit_actions = 0;

  object_queue_init(&self->actions);

209
210
211
212
  self->use_gateway = -1;
  self->start_gateway = 0;
  self->stop_gateway = 0;
  self->gateway = NULL;
213

214
215
216
217
218
  arglist_init(&self->transport_args);

  /* Set argv[0] */
  GET_FILE_ENV(transport_program, LSH_TRANSPORT);
  arglist_push(&self->transport_args, transport_program);
219
220
221
222

  self->resources = make_resource_list();
  gc_global(&self->resources->super);

Niels Möller's avatar
Niels Möller committed
223
  return self;
224
225
}

226
227
static void
add_action(struct lsh_options *options,
228
	   struct client_connection_action *action)
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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
{
  assert(action);
  object_queue_add_tail(&options->actions, &action->super);
}

/* Create a session object. stdout and stderr are shared (although
 * with independent lsh_fd objects). stdin can be used by only one
 * session. */
static struct client_session *
make_client_session(struct lsh_options *options,
		    struct object_list *session_actions)
{
  int in;
  int out;
  int err;
  
  int is_tty = 0;
  struct client_session *session;
  
  struct escape_info *escape = NULL;
#if 0
  struct lsh_callback *detach_cb = NULL;
#endif
  debug("lsh.c: Setting up stdin\n");

  if (options->stdin_file)
    in = open(options->stdin_file, O_RDONLY);
      
  else
    {
      if (options->used_stdin)
	in = open("/dev/null", O_RDONLY);
      else 
	{
	  in = STDIN_FILENO;
	  is_tty = isatty(STDIN_FILENO);
	  
	  options->used_stdin = 1;
	}
    }

  if (in < 0)
    {
272
      werror("Can't open stdin: %e.\n", errno);
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
      return NULL;
    }

  /* Attach the escape char handler, if appropriate. */
  if (options->escape > 0)
    {
      verbose("Enabling explicit escape character `%pc'\n",
	      options->escape);
      escape = make_client_escape(options->escape);
    }
  else if ( (options->escape < 0) && is_tty)
    {
      verbose("Enabling default escape character `%pc'\n",
	      DEFAULT_ESCAPE_CHAR);
      escape = make_client_escape(DEFAULT_ESCAPE_CHAR);
    }
  
  debug("lsh.c: Setting up stdout\n");

  if (options->stdout_file)
    /* FIXME: Use O_TRUNC too? */
    out = open(options->stdout_file, O_WRONLY | O_CREAT, 0666);
  else
    out = STDOUT_FILENO;

  if (out < 0)
    {
300
      werror("Can't open stdout: %e.\n", errno);
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
      close(in);
      return NULL;
    }

  debug("lsh.c: Setting up stderr\n");
  
  if (options->stderr_file)
    /* FIXME: Use O_TRUNC too? */
    err = open(options->stderr_file, O_WRONLY | O_CREAT, 0666);
  else
    err = STDERR_FILENO;

  if (err < 0) 
    {
      werror("Can't open stderr!\n");
      return NULL;
    }

#if 0
  if (options->detach_end) /* Detach? */
    detach_cb = make_detach_callback(options->exit_code);  
#endif

  /* Clear options */
  options->stdin_file = options->stdout_file = options->stderr_file = NULL;

  session = make_client_session_channel(in, out, err,
					session_actions,
					escape,
					WINDOW_SIZE,
					options->exit_code);
  
#if 0
  if (options->detach_end)
    {
      remember_resource(session->resources, make_detach_resource(detach_cb));
      options->detach_end = 0;
    }
#endif

  /* The channel won't get registered in anywhere else until later, so
   * we must register it here to be able to clean up properly if the
   * connection fails early. */
  remember_resource(options->resources, &session->super.super);
  
  return session;
}

static struct client_session_action *
maybe_pty(struct lsh_options *options, int default_pty)
{
#if WITH_PTY_SUPPORT
  int with_pty = options->with_pty;
  if (with_pty < 0)
    with_pty = default_pty;

  if (with_pty && !options->used_pty)
    {
      options->used_pty = 1;
      
361
362
      if (interact_is_tty())
	return &client_request_pty;
363
364
      else
	/* FIXME: Try allocating a remote pty even if we don't have a
365
	   pty locally? I think lsh-1.x and 2.x did that. */
366
367
368
369
370
371
	werror("No tty available.\n");
    }
#endif
  return NULL;
}

372
373
374
375
376
377
378
379
static struct client_session_action *
maybe_x11(struct lsh_options *options)
{  
  if (options->with_x11)
    {
      char *display = getenv(ENV_DISPLAY);
      struct client_session_action *action = NULL;

380
381
      /* FIXME: Make single_connection feature configurable. Should be
	 enabled by default for exec. */
382
      if (display)
383
	action = make_x11_action(display, 0);
384
385
386
387
388
389
390
391
392
393
394

      if (action)
	options->x11_forward = 1;
      else
	werror("Can't find any local X11 display to forward.\n");

      return action;
    }
  return NULL;
}

395
/* Create an interactive session */
396
static struct client_connection_action *
397
398
399
client_shell_session(struct lsh_options *options)
{  
  struct client_session_action *pty = maybe_pty(options, 1);
400
401
  struct client_session_action *x11 = maybe_x11(options);
  struct object_list *session_actions = alloc_object_list(1 + !!pty + !!x11);
402
403
404
405
  unsigned i = 0;

  if (pty)
    LIST(session_actions)[i++] = &pty->super;
406
407
408
  if (x11)
    LIST(session_actions)[i++] = &x11->super;

409
410
411
412
  LIST(session_actions)[i++] = &client_request_shell.super;

  assert(i == LIST_LENGTH(session_actions));
  
413
  return make_open_session_action(
414
415
416
417
	   &make_client_session(options, session_actions)->super);
}

/* Create a session for a subsystem */
418
static struct client_connection_action *
419
420
421
422
423
424
425
client_subsystem_session(struct lsh_options *options,
			 struct lsh_string *subsystem)
{
  struct object_list *session_actions
    = make_object_list(1, make_subsystem_action(subsystem),
		       -1);

426
  return make_open_session_action(
427
428
429
430
	   &make_client_session(options, session_actions)->super);
}

/* Create a session executing a command line */
431
static struct client_connection_action *
432
433
434
435
client_command_session(struct lsh_options *options,
		       struct lsh_string *command)
{
  struct client_session_action *pty = maybe_pty(options, 0);
436
437
  struct client_session_action *x11 = maybe_x11(options);
  struct object_list *session_actions = alloc_object_list(1 + !!pty + !!x11);
438
439
440
441
  unsigned i = 0;

  if (pty)
    LIST(session_actions)[i++] = &pty->super;
442
443
  if (x11)
    LIST(session_actions)[i++] = &x11->super;
444
445
446
447

  LIST(session_actions)[i++] = &make_exec_action(command)->super;

  assert(i == LIST_LENGTH(session_actions));
448
  return make_open_session_action(
449
450
451
	   &make_client_session(options, session_actions)->super);
}

452
453
/* Option parsing */

454
const char *argp_program_version = "lsh (" PACKAGE_STRING ")";
455
456
457

const char *argp_program_bug_address = BUG_ADDRESS;

458
459
enum {
  ARG_NOT = 0x400,
460

461
462
463
464
  OPT_PUBLICKEY = 0x201,
  OPT_SLOPPY,
  OPT_STRICT,
  OPT_HOST_DB,
465
  OPT_HOST_DB_UPDATE,
Niels Möller's avatar
Niels Möller committed
466

467
468
  OPT_DH,
  OPT_SRP,
469

470
  OPT_HOSTKEY_ALGORITHM,
471
  OPT_KEX_ALGORITHM,
472
473
474
475
476
477
478
479
480
481
482

  OPT_STDIN,
  OPT_STDOUT,
  OPT_STDERR,
 
  OPT_SUBSYSTEM,
  OPT_DETACH,
 
  OPT_ASKPASS,
 
  OPT_WRITE_PID,
483
  OPT_PID_FILE,
484

485
486
487
488
  OPT_USE_GATEWAY,
  OPT_START_GATEWAY,
  OPT_STOP_GATEWAY
};
489

490
491
492
493
static const struct argp_option
main_options[] =
{
  /* Name, key, arg-name, flags, doc, group */
494
495
496
497
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
541
542
543
544
545
546
547
548
  { "port", 'p', "PORT", 0, "Connect to this port.", 0 },
  { "user", 'l', "NAME", 0, "Login as this user.", 0 },
  { "askpass", OPT_ASKPASS, "Program", 0,
    "Program to use for reading passwords. "
    "Should be an absolute filename.", 0 },
  { NULL, 0, NULL, 0, "Actions:", 0 },

  { "forward-local-port", 'L', "LOCAL-PORT:TARGET-HOST:TARGET-PORT", 0,
    "Forward TCP/IP connections at a local port", 0 },
  { "forward-socks", 'D', "PORT", OPTION_ARG_OPTIONAL, "Enable socks dynamic forwarding", 0 },
  { "forward-remote-port", 'R', "REMOTE-PORT:TARGET-HOST:TARGET-PORT", 0,
    "Forward TCP/IP connections at a remote port", 0 },
  { "nop", 'N', NULL, 0, "No operation (suppresses the default action, "
    "which is to spawn a remote shell)", 0 },
  { "background", 'B', NULL, 0, "Put process into the background. Implies -N.", 0 },
  { "execute", 'E', "COMMAND", 0, "Execute a command on the remote machine", 0 },
  { "shell", 'S', NULL, 0, "Spawn a remote shell", 0 },
  { "subsystem", OPT_SUBSYSTEM, "SUBSYSTEM-NAME", 0,
#if WITH_PTY_SUPPORT 
    "Connect to given subsystem. Implies --no-pty.",
#else
    "Connect to given subsystem.",
#endif
    0 },

  { NULL, 0, NULL, 0, "Universal not:", 0 },
  { "no", 'n', NULL, 0, "Inverts the effect of the next modifier", 0 },

  { NULL, 0, NULL, 0, "Modifiers that apply to port forwarding:", 0 },
  { "remote-peers", 'g', NULL, 0, "Allow remote access to forwarded ports", 0 },
  { "no-remote-peers", 'g' | ARG_NOT, NULL, 0, 
    "Disallow remote access to forwarded ports (default).", 0 },

  { NULL, 0, NULL, 0, "Modifiers that apply to remote execution:", 0 },
  { "stdin", OPT_STDIN, "Filename", 0, "Redirect stdin", 0},
  { "no-stdin", OPT_STDIN | ARG_NOT, NULL, 0, "Redirect stdin from /dev/null", 0}, 
  { "stdout", OPT_STDOUT, "Filename", 0, "Redirect stdout", 0},
  { "no-stdout", OPT_STDOUT | ARG_NOT, NULL, 0, "Redirect stdout to /dev/null", 0}, 
  { "stderr", OPT_STDERR, "Filename", 0, "Redirect stderr", 0},
  { "no-stderr", OPT_STDERR | ARG_NOT, NULL, 0, "Redirect stderr to /dev/null", 0}, 

  { "detach", OPT_DETACH, NULL, 0, "Detach from terminal at session end.", 0},
  { "no-detach", OPT_DETACH | ARG_NOT, NULL, 0, "Do not detach session at end," 
    " wait for all open channels (default).", 0},

#if WITH_PTY_SUPPORT
  { "pty", 't', NULL, 0, "Request a remote pty (default).", 0 },
  { "no-pty", 't' | ARG_NOT, NULL, 0, "Don't request a remote pty.", 0 },
#endif /* WITH_PTY_SUPPORT */
#if WITH_X11_FORWARD
  { "x11-forward", 'x', NULL, 0, "Enable X11 forwarding.", 0 },
  { "no-x11-forward", 'x' | ARG_NOT, NULL, 0,
    "Disable X11 forwarding (default).", 0 },
#endif

549
550
551
552
553
554
555
556
557
558
  /* Gateway options */
  { NULL, 0, NULL, 0, "Gateway options:", 0 },
  { "use-gateway", OPT_USE_GATEWAY, NULL, 0,
    "Always use a local gateway", 0 },
  { "no-use-gateway", OPT_USE_GATEWAY | ARG_NOT, NULL, 0,
    "Never use a local gateway", 0 },
  { "gateway", 'G', NULL, 0,
    "If no gateway is running, start a new one.", 0 },
  { "start-gateway", OPT_START_GATEWAY, NULL, 0,
    "Stop any existing gateway, and start a new one.", 0 },
559
  { "stop-gateway", OPT_STOP_GATEWAY, NULL, 0,
560
561
    "Stop any existing gateway. Disables all other actions.", 0 },

562
563
564
565
566
  { NULL, 0, NULL, 0, "Miscellaneous options:", 0 },
  { "escape-char", 'e', "Character", 0, "Escape char. `none' means disable. "
    "Default is to use `~' if we have a tty, otherwise none.", 0 },
  { "write-pid", OPT_WRITE_PID, NULL, 0, "Make -B write the pid of the backgrounded "
    "process to stdout.", 0 },
567
  { "pid-file", OPT_PID_FILE, "FILE", 0, "Make -B create a pid file.", 0},
568

569
  /* Options passed on to lsh-transport. */  
Balázs Scheidler's avatar
Balázs Scheidler committed
570
  { "identity", 'i',  "Identity key", 0, "Use this key to authenticate.", 0 },
571
#if 0
572
573
574
  { "publickey", OPT_PUBLICKEY, NULL, 0,
    "Try publickey user authentication (default).", 0 },
  { "no-publickey", OPT_PUBLICKEY | ARG_NOT, NULL, 0,
575
    "Don't try publickey user authentication.", 0 },
576
#endif
577
  { "host-db", OPT_HOST_DB, "Filename", 0, "By default, ~/.lsh/host-acls", 0},
578
579
580
581
  { "sloppy-host-authentication", OPT_SLOPPY, NULL, 0,
    "Allow untrusted hostkeys.", 0 },
  { "strict-host-authentication", OPT_STRICT, NULL, 0,
    "Never, never, ever trust an unknown hostkey. (default)", 0 },
582
  { "host-db-update", OPT_HOST_DB_UPDATE, "Filename", 0,
583
584
585
    "File that ACLs for new keys are appended to. "
    "The default is ~/.lsh/host-acls.", 0 },
  { "capture-to", 0, NULL, OPTION_ALIAS | OPTION_HIDDEN, NULL, 0 },
586
#if 0
587
588
589
590
591
#if WITH_SRP
  { "srp-keyexchange", OPT_SRP, NULL, 0, "Enable experimental SRP support.", 0 },
  { "no-srp-keyexchange", OPT_SRP | ARG_NOT, NULL, 0, "Disable experimental SRP support (default).", 0 },
#endif /* WITH_SRP */

592
593
594
  { "dh-keyexchange", OPT_DH, NULL, 0,
    "Enable DH support (default, unless SRP is being used).", 0 },

595
  { "no-dh-keyexchange", OPT_DH | ARG_NOT, NULL, 0, "Disable DH support.", 0 },
Niels Möller's avatar
Niels Möller committed
596
#endif
597

598
599
600
601
602
  { "crypto", 'c', "ALGORITHM", 0, "", 0 },
  { "compression", 'z', "ALGORITHM", OPTION_ARG_OPTIONAL,
    "Enable compression. Default algorithm is zlib.", 0 },
  { "mac", 'm', "ALGORITHM", 0, "Select MAC algorithm", 0 },
  { "hostkey-algorithm", OPT_HOSTKEY_ALGORITHM, "ALGORITHM", 0,
603
    "Select host authentication algorithm.", 0 },
604
605
606
  { "kex-algorithm", OPT_KEX_ALGORITHM, "ALGORITHM", 0,
    "Select key exchange algorithm.", 0 },
  /* FIXME: Pass on --list-algorithms. */
607
608
609
610
611
612
613
  { NULL, 0, NULL, 0, NULL, 0 }
};


static const struct argp_child
main_argp_children[] =
{
614
  { &werror_argp, 0, "", 0 },
615
616
617
  { NULL, 0, NULL, 0}
};

618
static int
619
parse_arg_unsigned(const char *arg, unsigned long *n, char terminator)
620
621
622
623
624
625
{
  char *end;
  if (*arg == 0)
    return 0;

  *n = strtoul(arg, &end, 0);
626
  return *end == terminator;
627
628
629
}

/* Parse the argument for -R and -L */
630
631
632
static struct address_info *
parse_forward_arg(const char *arg,
		  unsigned long *listen_port)
633
634
{
  const char *host;
635
636
637
  uint32_t host_length;

  unsigned long target_port;
638
639
640
641
  char *sep;
  
  sep = strchr(arg, ':');
  if (!sep)
642
    return NULL;
643

644
  if (!parse_arg_unsigned(arg, listen_port, ':'))
645
646
647
648
    return 0;
  
  host = sep + 1;

649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
  if (host[0] == '[')
    {
      /* Optional brackets, to support IPv6 literal ip addresses. */
      host++;
      sep = strchr(host, ']');
      if (!sep || sep[1] != ':')
	return NULL;

      host_length = sep - host;
      sep ++;
    }
  else
    {
      sep = strchr(host, ':');
      if (!sep)
	return NULL;
665

666
667
      host_length = sep - host;
    }
668

669
  if (!parse_arg_unsigned(sep + 1, &target_port, '\0'))
670
    return NULL;
671
672
673

  return make_address_info(ssh_format("%ls", host_length, host),
			   target_port);
674
675
}

676
677
#define CASE_ARG(opt, attr, none)		\
  case opt:					\
678
    if (self->not)				\
679
      {						\
680
        self->not = 0;				\
681
682
683
684
685
686
687
688
689
						\
      case opt | ARG_NOT:			\
        self->attr = none;			\
        break;					\
      }						\
      						\
    self->attr = arg;				\
    break

690
691
#define CASE_FLAG(opt, flag)			\
  case opt:					\
692
    if (self->not)				\
693
      {						\
694
        self->not = 0;				\
695
696
697
698
699
700
						\
      case opt | ARG_NOT:			\
        self->flag = 0;				\
        break;					\
      }						\
      						\
701
702
    self->flag = 1;				\
    break
703

704
705
706
707
708
709
710
711
712
713
static error_t
main_argp_parser(int key, char *arg, struct argp_state *state)
{
  CAST(lsh_options, self, state->input);
  
  switch(key)
    {
    default:
      return ARGP_ERR_UNKNOWN;
    case ARGP_KEY_INIT:
714
      state->child_inputs[0] = &self->super;
715
      break;
716
      
717
718
719
720
721
    case ARGP_KEY_NO_ARGS:
      argp_usage(state);
      break;
    case ARGP_KEY_ARG:
      if (!state->arg_num)
722
723
724
725
726
727
728
729
730
731
732
733
	{
	  /* Support user@host notation */
	  char *at = strchr(arg, '@');
	  if (at)
	    {
	      self->target = at + 1;
	      *at = '\0';
	      self->user = arg;
	    }
	  else
	    self->target = arg;
	}
734
735
736
737
738
739
740
741
742
743
744
745
746
      else
	/* Let the next case parse it.  */
	return ARGP_ERR_UNKNOWN;

      break;
    case ARGP_KEY_ARGS:
      add_action
	(self,
	 client_command_session
	 (self, client_rebuild_command_line(state->argc - state->next,
					    state->argv + state->next)));
      self->start_shell = 0;
      break;
747
    case ARGP_KEY_END:
748
      if (self->inhibit_actions)
749
750
	break;

751
752
753
      if (!werror_init(&self->super))
	argp_failure(state, EXIT_FAILURE, errno, "Failed to open log file");

754
755
756
757
758
      if (!self->home)
	{
	  argp_error(state, "No home directory. Please set HOME in the environment.");
	  break;
	}
759
760
761
762
763
764
765

      if (self->start_gateway > 0 && self->use_gateway > 0)
	{
	  argp_error(state, "--start-gateway and --use-gateway are "
		     "mutually exclusive.");
	  break;
	}
766
767
      /* We can't add the gateway action immediately when the -G
       * option is encountered, as we need the name and port of the
768
       * remote machine (self->remote) first.
769
770
771
       */

      if (self->start_gateway || self->stop_gateway || self->use_gateway)
772
	{
773
	  if (!self->local_user)
774
	    {
775
776
777
	      argp_error(state, "You have to set LOGNAME in the environment, "
			 " if you want to use the gateway feature.");
	      break;
778
	    }
779
780
781
	  self->gateway = make_gateway_address(self->local_user,
					       self->user,
					       self->target);
782

783
	  if (!self->gateway)
784
	    {
785
786
	      argp_error(state, "Local or remote user name, or the target host name, are too "
			 "strange for the gateway socket name construction.");
787
	      break;
788
	    }
789
	}
790

791
792
793
794
      /* Add shell action */
      if (self->start_shell)
	add_action(self, client_shell_session(self));

795
796
      if (object_queue_is_empty(&self->actions)
	  && !self->stop_gateway && !self->start_gateway)
797
798
799
800
	{
	  argp_error(state, "No actions given.");
	  break;
	}
801

802
803
804
805
806
807
808
809
810
811
812
      break;

    case 'p':
      self->port = arg;
      break;

    case 'l':
      self->user = arg;
      break;

    case OPT_ASKPASS:
813
814
815
816
      arglist_push(&self->transport_args, "--askpass");
      arglist_push(&self->transport_args, arg);
      
      interact_set_askpass(arg);      
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
      break;
      
    case 'e':
      if (arg[0] && !arg[1])
	/* A single char argument */
	self->escape = arg[0];
      else if (!strcasecmp(arg, "none"))
	self->escape = 0;
      else
	argp_error(state, "Invalid escape char: `%s'. "
		   "You must use a single character or `none'.", arg);
      break;

    case 'E':
      add_action(self,
832
		 client_command_session(self, make_string(arg)));
833
834
835
836
837
838
839
      break;

    case 'S':
      add_action(self, client_shell_session(self));
      break;

    case OPT_SUBSYSTEM:
840
      add_action(self, client_subsystem_session(self, make_string(arg)));
841
842
843
844
845
846
847
848
849
850
851
852

      self->start_shell = 0;
#if WITH_PTY_SUPPORT
      self->with_pty = 0;
#endif
      break;

    case 'L':
      {
	unsigned long listen_port;
	struct address_info *target;

853
854
	target = parse_forward_arg(arg, &listen_port);
	if (!target)
855
856
857
	  argp_error(state, "Invalid forward specification `%s'.", arg);

	add_action(self, forward_local_port
858
859
		   (make_address_info(make_string(self->with_remote_peers
						  ? "" : "localhost"),
860
861
862
863
864
865
866
				      listen_port),
		    target));
	break;
      }      

    case 'D':
      {
867
	unsigned long socks_port = DEFAULT_SOCKS_PORT;
868
869
870
871
872
873
	if (arg)
	  {
	    if (!parse_arg_unsigned(arg, &socks_port, '\0')
		|| socks_port > 0xffff)
	      argp_error(state, "Invalid port number `%s' for socks.", arg);
	  }
874
875
876
877

	add_action(self, make_socks_server
		   (make_address_info((self->with_remote_peers
				       ? NULL
878
				       : make_string("localhost")),
879
880
881
882
883
884
885
886
887
888
				      socks_port)));
	break;
      }

    case 'N':
      self->start_shell = 0;
      break;

    case 'B':
      self->start_shell = 0;
889
      self->detach = 1;
890
      break;
891

892
893
894
895
896
    case 'R':
      {
	unsigned long listen_port;
	struct address_info *target;

897
898
	target = parse_forward_arg(arg, &listen_port);
	if (!target)
899
900
	  argp_error(state, "Invalid forward specification '%s'.", arg);

901
902
	/* RFC 4254 specifies that "" means all interfaces and
	   "localhost" means all local interfaces. */
903
904
	add_action(self, forward_remote_port
		   (make_address_info((self->with_remote_peers
905
906
				       ? make_string("")
				       : make_string("localhost")),
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
				      listen_port),
		    target));

	self->remote_forward = 1;
	break;
      }

    CASE_FLAG('g', with_remote_peers);

#if WITH_PTY_SUPPORT
    CASE_FLAG('t', with_pty);
#endif /* WITH_PTY_SUPPORT */

#if WITH_X11_FORWARD
    CASE_FLAG('x', with_x11);
#endif

    CASE_FLAG(OPT_DETACH, detach_end);
    CASE_FLAG(OPT_WRITE_PID, write_pid);
926
927
928
929
930
931

    case OPT_PID_FILE:
      self->pid_file = arg;
      self->write_pid = 1;
      break;

932
933
934
935
    CASE_ARG(OPT_STDIN, stdin_file, "/dev/null");
    CASE_ARG(OPT_STDOUT, stdout_file, "/dev/null"); 
    CASE_ARG(OPT_STDERR, stderr_file, "/dev/null");

Balázs Scheidler's avatar
Balázs Scheidler committed
936
    case 'i':
937
938
      arglist_push(&self->transport_args, "--identity");
      arglist_push(&self->transport_args, arg);
939
      break;
Niels Möller's avatar
Niels Möller committed
940

941
942
#if 0
      CASE_FLAG(OPT_PUBLICKEY, with_publickey);
943
#endif
Niels Möller's avatar
Niels Möller committed
944
    case OPT_HOST_DB:
945
946
      arglist_push(&self->transport_args, "--host-db");
      arglist_push(&self->transport_args, arg);
Niels Möller's avatar
Niels Möller committed
947
      break;
948

949
    case OPT_SLOPPY:
950
      arglist_push(&self->transport_args, "--sloppy-host-authentication");
951
952
953
      break;

    case OPT_STRICT:
954
      arglist_push(&self->transport_args, "--strict-host-authentication");
955
956
      break;

957
    case OPT_HOST_DB_UPDATE:
958
      arglist_push(&self->transport_args, "--host-db-update");
959
960
961
962
963
964
      arglist_push(&self->transport_args, arg);
      break;

    case 'c':
      arglist_push(&self->transport_args, "-c");
      arglist_push(&self->transport_args, arg);
965
      break;
966

967
968
969
970
971
972
973
974
975
976
977
978
    case 'm':
      arglist_push(&self->transport_args, "-m");
      arglist_push(&self->transport_args, arg);
      break;

    case 'z':
      if (!arg)
	arglist_push(&self->transport_args, "-z");
      else
	arglist_push_optarg(&self->transport_args, "-z", arg);
      break;

979
980
981
982
983
984
985
986
987
988
    case OPT_HOSTKEY_ALGORITHM:
      arglist_push(&self->transport_args, "--hostkey-algorithm");
      arglist_push(&self->transport_args, arg);
      break;

    case OPT_KEX_ALGORITHM:
      arglist_push(&self->transport_args, "--kex-algorithm");
      arglist_push(&self->transport_args, arg);
      break;
      
989
#if 0
990
991
    CASE_FLAG(OPT_DH, with_dh_keyexchange);
    CASE_FLAG(OPT_SRP, with_srp_keyexchange);
Niels Möller's avatar
Niels Möller committed
992
#endif
993

994
995
996
    CASE_FLAG(OPT_USE_GATEWAY, use_gateway);

    case 'G':
997
998
999
      /* FIXME: It would be desirable to have this option also imply
	 that lsh is backgrounded when the primary actions are
	 completed. */
1000
      self->start_gateway = -1;