io.c 41.4 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
/* io.c
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 *
 * $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
J.H.M. Dassen's avatar
J.H.M. Dassen committed
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Niels Möller's avatar
Niels Möller committed
22
23
 */

24
#include "io.h"
25
26

#include "format.h"
27
28
29
#include "werror.h"
#include "xalloc.h"

Niels Möller's avatar
Niels Möller committed
30
31
32
#include <assert.h>
#include <string.h>

33
#if HAVE_UNISTD_H
Niels Möller's avatar
Niels Möller committed
34
#include <unistd.h>
35
#endif
36
37

#ifdef HAVE_POLL
38
39
40
41
42
# if HAVE_POLL_H
#  include <poll.h>
# elif HAVE_SYS_POLL_H
#  include <sys/poll.h>
# endif
43
#else
44
# include "jpoll.h"
45
46
#endif

47
48
#include <oop.h>

49
50
51
52
53
54
55
/* Workaround for some version of FreeBSD. */
#ifdef POLLRDNORM
# define MY_POLLIN (POLLIN | POLLRDNORM)
#else /* !POLLRDNORM */
# define MY_POLLIN POLLIN
#endif /* !POLLRDNORM */

Niels Möller's avatar
Niels Möller committed
56
57
58
59
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
60
#include <sys/un.h>
Niels Möller's avatar
Niels Möller committed
61
#include <arpa/inet.h>
62
#include <signal.h>
63
64
#include <sys/stat.h>

Niels Möller's avatar
Niels Möller committed
65

66
#define GABA_DEFINE
67
#include "io.h.x"
68
#undef GABA_DEFINE
69
70
71

#include "io.c.x"

72
73
/* Glue to liboop */

74
/* Because of signal handlers, there can be only one oop object. */
75
76
static oop_source_sys *global_oop_sys = NULL;
static oop_source *source = NULL;
77

78
79
void
io_init(void)
80
{
81
82
83
84
85
86
87
88
89
90
91
92
93
  struct sigaction pipe;
  memset(&pipe, 0, sizeof(pipe));

  pipe.sa_handler = SIG_IGN;
  sigemptyset(&pipe.sa_mask);
  pipe.sa_flags = 0;
  
  if (sigaction(SIGPIPE, &pipe, NULL) < 0)
    fatal("Failed to ignore SIGPIPE.\n");

  assert(!global_oop_sys);
  global_oop_sys = oop_sys_new();
  if (!global_oop_sys)
94
    fatal("Failed to initialize liboop.\n");
95
96

  source = oop_sys_source(global_oop_sys);
97
98
}

99
void
100
io_final(void)
101
{
102
103
  gc_final();
  
104
  /* There mustn't be any outstanding callbacks left. */
105
106
107
108
109
110
111
112
  oop_sys_delete(global_oop_sys);
  global_oop_sys = NULL;
  source = NULL;
}

void
io_run(void)
{
113
  void *res = oop_sys_run(global_oop_sys);
114

115
116
117
118
119
120
121
  /* FIXME: OOP_ERROR is not defined in liboop-0.7. Upgrade, and then
   * enable this check. */
#if 0
  if (res == OOP_ERROR)
    werror("oop_sys_run (errno = %i):  %z\n",
	   errno, STRERROR(errno));
#endif
122
  trace("io_run: Exiting\n");
123
124
125
}


126
/* OOP Callbacks */
127
static void *
128
lsh_oop_signal_callback(oop_source *s UNUSED, int sig, void *data)
129
130
131
{
  CAST(lsh_signal_handler, self, (struct lsh_object *) data);

132
  trace("lsh_oop_signal_callback: Signal %i, handler: %t\n",
133
	sig, self->action);
134
  
135
136
  assert(sig == self->signum);
  
137
  LSH_CALLBACK(self->action);
138

139
  return OOP_CONTINUE;
140
141
142
}

static void
143
lsh_oop_register_signal(struct lsh_signal_handler *handler)
144
{
145
146
147
  trace("lsh_oop_register_signal: signal: %i, handler: %t\n",
	handler->signum, handler);
  
148
  if (handler->super.alive)
149
    source->on_signal(source, handler->signum, lsh_oop_signal_callback, handler);
150
151
}

152
static void
153
lsh_oop_cancel_signal(struct lsh_signal_handler *handler)
154
{
155
156
  trace("lsh_oop_cancel_signal: signal: %i, handler: %t\n",
	handler->signum, handler);
157

158
159
  if (handler->super.alive)
    source->cancel_signal(source, handler->signum, lsh_oop_signal_callback, handler);
160
}
161
162

static void *
163
lsh_oop_fd_read_callback(oop_source *s UNUSED, int fileno, oop_event event, void *data)
164
165
166
167
{
  CAST(lsh_fd, fd, (struct lsh_object *) data);

  assert(fileno == fd->fd);
168
169
  assert(event == OOP_READ);
  assert(fd->super.alive);
170

171
  trace("lsh_oop_fd_read_callback: fd %i: %z\n",
172
173
174
	fd->fd, fd->label);

  FD_READ(fd);
175

176
  return OOP_CONTINUE;
177
178
}

179
180
void
lsh_oop_register_read_fd(struct lsh_fd *fd)
181
{
182
183
184
  trace("lsh_oop_register_read_fd: fd: %i, %z\n",
	fd->fd, fd->label);
  
185
  if (fd->super.alive && !fd->want_read)
186
187
188
189
190
191
    {
      assert(fd->read);
      
      source->on_fd(source, fd->fd, OOP_READ, lsh_oop_fd_read_callback, fd);
      fd->want_read = 1;
    }
192
193
}

194
195
196
void
lsh_oop_cancel_read_fd(struct lsh_fd *fd)
{
197
198
199
  trace("lsh_oop_cancel_read_fd: fd: %i, %z\n",
	fd->fd, fd->label);
  
200
201
202
203
204
205
  if (fd->super.alive)
    {
      source->cancel_fd(source, fd->fd, OOP_READ);
      fd->want_read = 0;
    }
}
206
207

static void *
208
lsh_oop_fd_write_callback(oop_source *s UNUSED, int fileno, oop_event event, void *data)
209
{
210
  CAST(lsh_fd, fd, (struct lsh_object *) data);
211

212
  assert(fileno == fd->fd);
213
  assert(event == OOP_WRITE);
214
215
  assert(fd->super.alive);
  
216
  trace("lsh_oop_fd_write_callback: fd %i: %z\n",
217
	fd->fd, fd->label);
218

219
  FD_WRITE(fd);
220

221
  return OOP_CONTINUE;
222
223
}

224
225
void
lsh_oop_register_write_fd(struct lsh_fd *fd)
226
{
227
228
229
  trace("lsh_oop_register_write_fd: fd: %i, %z\n",
	fd->fd, fd->label);
  
230
  if (fd->super.alive && !fd->want_write)
231
232
233
234
235
236
237
    {
      assert(fd->write);
      
      source->on_fd(source, fd->fd, OOP_WRITE, lsh_oop_fd_write_callback, fd);
      fd->want_write = 1;
    }
}
238

239
240
void
lsh_oop_cancel_write_fd(struct lsh_fd *fd)
241
{
242
243
244
  trace("lsh_oop_cancel_write_fd: fd: %i, %z\n",
	fd->fd, fd->label);

245
246
247
248
249
  if (fd->super.alive)
    {
      source->cancel_fd(source, fd->fd, OOP_WRITE);
      fd->want_write = 0;
    }
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
281
282
283
static void *
lsh_oop_time_callback(oop_source *source UNUSED,
                      struct timeval time UNUSED, void *data)
{
  CAST(lsh_callout, callout, (struct lsh_object *) data);

  assert(callout->super.alive);

  trace("lsh_oop_time_callback: action: %t\n",
        callout->action);
  
  callout->super.alive = 0;

  LSH_CALLBACK(callout->action);

  return OOP_CONTINUE;
}

static void
lsh_oop_register_callout(struct lsh_callout *callout)
{
  if (callout->super.alive)
    source->on_time(source, OOP_TIME_NOW, lsh_oop_time_callback, callout);
}

static void
lsh_oop_cancel_callout(struct lsh_callout *callout)
{
  if (callout->super.alive)
    source->cancel_time(source, OOP_TIME_NOW, lsh_oop_time_callback, callout);
}

284

285
286
287
288
289
290
/* Calls trigged by a signal handler. */
/* GABA:
   (class
     (name lsh_signal_handler)
     (super resource)
     (vars
291
       (signum . int)
292
293
294
295
296
297
298
299
300
301
302
303
       (action object lsh_callback)))
*/

/* Scheduled calls. FIXME: For now, no scheduling in time. */
/* GABA:
   (class
     (name lsh_callout)
     (super resource)
     (vars
       (action object lsh_callback)))
*/

304

305
306
307
308
309
310
311
static void
do_kill_signal_handler(struct resource *s)
{
  CAST(lsh_signal_handler, self, s);

  if (self->super.alive)
    {
312
      lsh_oop_cancel_signal(self);
313
314
315
316
      self->super.alive = 0;
    }
}

317
struct resource *
318
io_signal_handler(int signum,
319
320
321
		  struct lsh_callback *action)
{
  NEW(lsh_signal_handler, handler);
322
323

  init_resource(&handler->super, do_kill_signal_handler);
324

325
  handler->signum = signum;
326
327
  handler->action = action;

328
  lsh_oop_register_signal(handler);
329
  gc_global(&handler->super);
330
331
332
333
  
  return &handler->super;
}

334
335
336
337
338
339
340
341
342
343
344
345
static void
do_kill_callout(struct resource *s)
{
  CAST(lsh_callout, self, s);

  if (self->super.alive)
    {
      lsh_oop_cancel_callout(self);
      self->super.alive = 0;
    }
}

346
347
/* Delays not implemented. */
struct resource *
348
io_callout(struct lsh_callback *action)
349
{
350
  NEW(lsh_callout, self);
351
  init_resource(&self->super, do_kill_callout);
352

353
  self->action = action;
354

355
356
  lsh_oop_register_callout(self);
  
357
358
  gc_global(&self->super);
  return &self->super;
359
}
Niels Möller's avatar
Niels Möller committed
360
361
362

/* Read-related callbacks */

363
364
365
static void
do_buffered_read(struct io_callback *s,
		 struct lsh_fd *fd)
Niels Möller's avatar
Niels Möller committed
366
367
368
{
  CAST(io_buffered_read, self, s);
  UINT8 *buffer = alloca(self->buffer_size);
369
370
371
  int res;

  assert(fd->want_read);   
372

373
#if 0
374
  /* If hanged_up is set, pretend that read returned 0 */
375
  res = fd->hanged_up ? 0 : read(fd->fd, buffer, self->buffer_size);
376
#endif
Niels Möller's avatar
Niels Möller committed
377

378
  res = read(fd->fd, buffer, self->buffer_size);
379
  
Niels Möller's avatar
Niels Möller committed
380
381
382
383
384
385
386
387
388
  if (res < 0)
    switch(errno)
      {
      case EINTR:
	break;
      case EWOULDBLOCK:
	werror("io.c: read_callback: Unexpected EWOULDBLOCK\n");
	break;
      case EPIPE:
389
	/* Getting EPIPE from read seems strange, but appearantly
390
391
	 * it happens sometimes. */
	werror("Unexpected EPIPE.\n");
Niels Möller's avatar
Niels Möller committed
392
      default:
Niels Möller's avatar
Niels Möller committed
393
394
395
	EXCEPTION_RAISE(fd->e, 
			make_io_exception(EXC_IO_READ, fd,
					  errno, NULL));
396
397
398
	/* Close the fd, unless it has a write callback. */
	close_fd_read(fd);
	
Niels Möller's avatar
Niels Möller committed
399
400
401
402
403
404
	break;
      }
  else if (res > 0)
    {
      UINT32 left = res;
    
405
      while (fd->super.alive && fd->read && left)
Niels Möller's avatar
Niels Möller committed
406
407
	{
	  UINT32 done;
Niels Möller's avatar
Niels Möller committed
408

409
	  /* NOTE: What to do if want_read is false? To improve the
410
	   * connection_lock mechanism, it must be possible to
411
412
	   * temporarily stop reading, which means that fd->want_read
	   * has to be cleared.
413
414
415
416
417
418
419
420
421
422
423
	   *
	   * But when doing this, we have to keep the data that we
	   * have read, some of which is buffered here, on the stack,
	   * and the rest inside the read-handler.
	   *
	   * There are two alternatives: Save our buffer here, or
	   * continue looping, letting the read-handler process it
	   * into packets. In the latter case, the ssh_connection
	   * could keep a queue of waiting packets, but it would still
	   * have to clear the want_read flag, to prevent that queue
	   * from growing arbitrarily large.
424
	   *
425
	   * We now go with the second alternative. */
426

427
	  assert(self->handler);
Niels Möller's avatar
Niels Möller committed
428
429

	  /* NOTE: This call may replace self->handler */
Niels Möller's avatar
Niels Möller committed
430
	  done = READ_HANDLER(self->handler, left, buffer);
431
	  
Niels Möller's avatar
Niels Möller committed
432
433
	  buffer += done;
	  left -= done;
434

435
436
437
	  if (!fd->want_read)
	    debug("do_buffered_read: want_read = 0; handler needs a pause.\n");
	  
438
439
440
441
	  if (fd->want_read && !self->handler)
	    {
	      werror("do_buffered_read: Handler disappeared! Ignoring %i bytes\n",
		     left);
442
	      lsh_oop_cancel_read_fd(fd);
443
444
	      return;
	    }
Niels Möller's avatar
Niels Möller committed
445
446
447
	}

      if (left)
448
	verbose("read_buffered: fd died, %i buffered bytes discarded\n",
Niels Möller's avatar
Niels Möller committed
449
450
451
		left);
    }
  else
452
453
454
455
456
457
458
    {
      /* We have read EOF. Pass available == 0 to the handler */
      assert(fd->super.alive);
      assert(fd->read);
      assert(fd->want_read);
      assert(self->handler);

Niels Möller's avatar
Niels Möller committed
459
460
      /* Close the fd, unless it has a write callback. */
      close_fd_read(fd);
461
      
462
463
464
      READ_HANDLER(self->handler, 0, NULL);
    }
	
Niels Möller's avatar
Niels Möller committed
465
466
}

467
struct io_callback *
Niels Möller's avatar
Niels Möller committed
468
469
470
471
472
make_buffered_read(UINT32 buffer_size,
		   struct read_handler *handler)
{
  NEW(io_buffered_read, self);

473
  self->super.f = do_buffered_read;
Niels Möller's avatar
Niels Möller committed
474
475
476
477
478
479
  self->buffer_size = buffer_size;
  self->handler = handler;

  return &self->super;
}

480
481
482
static void
do_consuming_read(struct io_callback *c,
		  struct lsh_fd *fd)
Niels Möller's avatar
Niels Möller committed
483
{
484
  CAST_SUBTYPE(io_consuming_read, self, c);
Niels Möller's avatar
Niels Möller committed
485
486
  UINT32 wanted = READ_QUERY(self);

487
488
489
490
  assert(fd->want_read);
  
  if (!wanted)
    {
491
      lsh_oop_cancel_read_fd(fd);
492
    }
Niels Möller's avatar
Niels Möller committed
493
494
495
496
497
498
  else
    {
      struct lsh_string *s = lsh_string_alloc(wanted);
      int res = read(fd->fd, s->data, wanted);

      if (res < 0)
499
500
501
502
503
504
505
506
507
508
509
510
511
	{
	  switch(errno)
	    {
	    case EINTR:
	      break;
	    case EWOULDBLOCK:
	      werror("io.c: read_consume: Unexpected EWOULDBLOCK\n");
	      break;
	    case EPIPE:
	      /* FIXME: I don't understand why reading should return
	       * EPIPE, but it happens occasionally under linux. Perhaps
	       * we should treat it as EOF instead? */
	      werror("io.c: read_consume: Unexpected EPIPE.\n");
512
	      /* Fall through */
513
514
515
516
517
518
519
520
	    default:
	      EXCEPTION_RAISE(fd->e, 
			      make_io_exception(EXC_IO_READ,
						fd, errno, NULL));
	      break;
	    }
	  lsh_string_free(s);
	}
Niels Möller's avatar
Niels Möller committed
521
522
523
      else if (res > 0)
	{
	  s->length = res;
524
	  A_WRITE(self->consumer, s);
Niels Möller's avatar
Niels Möller committed
525
526
	}
      else
527
	{
528
	  lsh_string_free(s);
529

Niels Möller's avatar
Niels Möller committed
530
	  /* Close the fd, unless it has a write callback. */
531
	  A_WRITE(self->consumer, NULL);
532
	  close_fd_read(fd);
533
	}
Niels Möller's avatar
Niels Möller committed
534
535
536
537
538
539
540
541
    }
}

/* NOTE: Doesn't initialize the query field. That should be done in
 * the subclass's constructor. */
void init_consuming_read(struct io_consuming_read *self,
			 struct abstract_write *consumer)
{
542
  self->super.f = do_consuming_read;
Niels Möller's avatar
Niels Möller committed
543
544
  self->consumer = consumer;
}
545

546

Niels Möller's avatar
Niels Möller committed
547
/* Write related callbacks */
548
549
550
static void
do_write_callback(struct io_callback *s UNUSED,
		  struct lsh_fd *fd)
Niels Möller's avatar
Niels Möller committed
551
{
552
  /* CAST(io_write_callback, self, s); */
553
554
555
  assert(fd->super.alive);
  
  if (!write_buffer_pre_write(fd->write_buffer))
556
    {
557
558
559
560
561
      /* Buffer is empty */
      if (fd->write_buffer->closed)
	close_fd(fd);
      else
	lsh_oop_cancel_write_fd(fd);
562
    }
563
564
565
566
567
568
569
570
  else
    {
      UINT32 size;
      int res;

      size = MIN(fd->write_buffer->end - fd->write_buffer->start,
		 fd->write_buffer->block_size);
      assert(size);
Niels Möller's avatar
Niels Möller committed
571
  
572
573
574
575
576
577
578
579
580
581
582
583
584
      res = write(fd->fd,
		  fd->write_buffer->buffer + fd->write_buffer->start,
		  size);
      if (!res)
	fatal("Closed?");
      if (res < 0)
	switch(errno)
	  {
	  case EINTR:
	  case EAGAIN:
	    break;
	  case EPIPE:
	    debug("io.c: Broken pipe.\n");
Niels Möller's avatar
Niels Möller committed
585
	
586
587
588
589
590
591
	    /* Fall through */
	  default:
	    werror("io.c: write failed, %z\n", STRERROR(errno));
	    EXCEPTION_RAISE(fd->e,
			    make_io_exception(EXC_IO_WRITE, fd, errno, NULL));
	    close_fd(fd);
Niels Möller's avatar
Niels Möller committed
592
	
593
594
595
596
597
598
	    break;
	  }
      else
	write_buffer_consume(fd->write_buffer, res);
    }
}
599

600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
static struct io_callback io_write_callback =
{ STATIC_HEADER, do_write_callback };


struct listen_value *
make_listen_value(struct lsh_fd *fd,
		  struct address_info *peer)
{
  NEW(listen_value, self);

  self->fd = fd;
  self->peer = peer;

  return self;
}

Niels Möller's avatar
Niels Möller committed
616
617
618

/* Listen callback */

619
620
621
622
623
624
625
626
627
/* GABA:
   (class
     (name io_listen_callback)
     (super io_callback)
     (vars
       (c object command_continuation)
       (e object exception_handler)))
*/

Niels Möller's avatar
Niels Möller committed
628
static void
629
do_listen_callback(struct io_callback *s,
Niels Möller's avatar
Niels Möller committed
630
		   struct lsh_fd *fd)
Niels Möller's avatar
Niels Möller committed
631
{
632
  CAST(io_listen_callback, self, s);
633
634
635
636
637
638

#if WITH_IPV6
  struct sockaddr_storage peer;
#else
  struct sockaddr peer;
#endif
639
640

  socklen_t addr_len = sizeof(peer);
Niels Möller's avatar
Niels Möller committed
641
  int conn;
642

Niels Möller's avatar
Niels Möller committed
643
644
645
  conn = accept(fd->fd,
		(struct sockaddr *) &peer, &addr_len);
  if (conn < 0)
646
    {
647
      werror("io.c: accept failed, %z", STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
648
      return;
649
    }
650
  trace("io.c: accept on fd %i\n", conn);
651
  COMMAND_RETURN(self->c,
652
		 make_listen_value(make_lsh_fd(conn, "accepted socket", self->e),
653
654
				   sockaddr2info(addr_len,
						 (struct sockaddr *) &peer)));
Niels Möller's avatar
Niels Möller committed
655
}
656

657
struct io_callback *
658
make_listen_callback(struct command_continuation *c,
659
660
661
662
663
664
665
666
667
		     struct exception_handler *e)
{
  NEW(io_listen_callback, self);
  self->super.f = do_listen_callback;
  self->c = c;
  self->e = e;
  
  return &self->super;
}
Niels Möller's avatar
Niels Möller committed
668

Niels Möller's avatar
Niels Möller committed
669
670
/* Connect callback */

671
672
673
674
675
676
677
678
679
680
681
/* GABA:
   (class
     (name io_connect_callback)
     (super io_callback)
     (vars
       (c object command_continuation)))
*/

static void
do_connect_callback(struct io_callback *s,
		    struct lsh_fd *fd)
Niels Möller's avatar
Niels Möller committed
682
{
683
  CAST(io_connect_callback, self, s);
684
  int socket_error;
685
  socklen_t len = sizeof(socket_error);
686
  
687
  /* Check if the connection was successful */
688
689
  if ((getsockopt(fd->fd, SOL_SOCKET, SO_ERROR,
		  (char *) &socket_error, &len) < 0)
690
      || socket_error)
691
    {
692
      trace("io.c: connect_callback: Connect on fd %i failed.\n", fd->fd);
Niels Möller's avatar
Niels Möller committed
693
      EXCEPTION_RAISE(fd->e,
694
		      make_io_exception(EXC_IO_CONNECT, fd, 0, "connect failed."));
695
      close_fd(fd);
696
697
    }
  else
Niels Möller's avatar
Niels Möller committed
698
    {
699
      trace("io.c: connect_callback: fd %i connected.\n", fd->fd);
700
      fd->write = NULL;
701
      lsh_oop_cancel_write_fd(fd);
702
      fd->label = "connected socket";
703
      COMMAND_RETURN(self->c, fd);
704
    }
705
706
707
708
709
710
711
712
713
714
715
}

static struct io_callback *
make_connect_callback(struct command_continuation *c)
{
  NEW(io_connect_callback, self);

  self->super.f = do_connect_callback;
  self->c = c;

  return &self->super;
716
717
}

718

Niels Möller's avatar
Niels Möller committed
719
/* This function is called if a connection this file somehow depends
720
721
722
723
724
725
726
727
 * on disappears. For instance, the connection may have spawned a
 * child process, and this file may be the stdin of that process. */

/* To kill a file, mark it for closing and the backend will do the work. */
static void do_kill_fd(struct resource *r)
{
  CAST_SUBTYPE(lsh_fd, fd, r);

Niels Möller's avatar
Niels Möller committed
728
729
  /* We use close_fd_nicely, so that any data in the write buffer is
   * flushed before the fd is closed. */
730
  if (r->alive)
731
    close_fd_nicely(fd);
732
733
}

734
735
736
737
738
739
740
741
742
743
/* Closes the file on i/o errors, and passes the exception on */

static void
do_exc_io_handler(struct exception_handler *self,
		  const struct exception *x)
{
  if (x->type & EXC_IO)
    {
      CAST_SUBTYPE(io_exception, e, x);

744
      if (e->fd)
745
	close_fd(e->fd);
746
747
748
749
750
    }
  EXCEPTION_RAISE(self->parent, x);
  return;
}

751

752
/* These functions are used by werror and friends */
Niels Möller's avatar
Niels Möller committed
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

/* For fd:s in blocking mode. */
const struct exception *
write_raw(int fd, UINT32 length, const UINT8 *data)
{
  while(length)
    {
      int written = write(fd, data, length);

      if (written < 0)
	switch(errno)
	  {
	  case EINTR:
	  case EAGAIN:
	    continue;
	  default:
	    return make_io_exception(EXC_IO_BLOCKING_WRITE,
				     NULL, errno, NULL);
	  }
      
      length -= written;
      data += written;
    }
  return NULL;
}

const struct exception *
write_raw_with_poll(int fd, UINT32 length, const UINT8 *data)
{
  while(length)
    {
      struct pollfd pfd;
      int res;
      int written;
      
      pfd.fd = fd;
      pfd.events = POLLOUT;

      res = poll(&pfd, 1, -1);

      if (res < 0)
	switch(errno)
	  {
	  case EINTR:
	  case EAGAIN:
	    continue;
	  default:
	    return make_io_exception(EXC_IO_BLOCKING_WRITE,
				     NULL, errno, NULL);
	  }
      
      written = write(fd, data, length);

      if (written < 0)
	switch(errno)
	  {
	  case EINTR:
	  case EAGAIN:
	    continue;
	  default:
	    return make_io_exception(EXC_IO_BLOCKING_WRITE,
				     NULL, errno, NULL);
	  }
      
      length -= written;
      data += written;
    }
  return NULL;
}

823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
/* For fd:s in blocking mode. */
const struct exception *
read_raw(int fd, UINT32 length, UINT8 *data)
{
  while(length)
    {
      int done = read(fd, data, length);

      if (done < 0)
	switch(errno)
	  {
	  case EINTR:
	  case EAGAIN:
	    continue;
	  default:
	    return make_io_exception(EXC_IO_BLOCKING_READ,
				     NULL, errno, NULL);
	  }
      else if (done == 0)
	{
	  /* EOF. */
	  /* FIXME: Indicate the amount of data read, somehow. */
	  return make_io_exception(EXC_IO_BLOCKING_READ,
				   NULL, 0, NULL);
	}
	
      length -= done;
      data += done;
    }
  return NULL;
}
Niels Möller's avatar
Niels Möller committed
854
855
856

/* Network utility functions */

857
/* Converts a string port number or service name to a port number.
858
859
 * Returns the port number in _host_ byte order, or 0 if lookup
 * fails. */
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880

int get_portno(const char *service, const char *protocol)
{
  if (service == NULL)
    return 0;
  else
    {
      char *end;
      long portno;

      portno = strtol(service, &end, 10);
      if (portno > 0
	  &&  portno <= 65535
	  &&  end != service
	  &&  *end == '\0')
	  return portno;
      else
	{
	  struct servent * serv;

	  serv = getservbyname(service, protocol);
881
882
	  if (!serv)
	    return 0;
883
884
885
886
887
888
	  return ntohs(serv->s_port);
	}
    }
}


889
890
891
892
893
/* If def != 0, use that value as a fallback if the lookup fails. */
struct address_info *
make_address_info_c(const char *host,
		    const char *port,
		    int def)
894
895
{
  int portno = get_portno(port, "tcp");
896
897
898
899
900
901
  if (!portno)
    portno = def;

  if (!portno)
    return NULL;

902
903
904
905
906
  else
    {
      NEW(address_info, info);
      
      info->port = portno;
907
      info->ip = host ? ssh_format("%lz", host) : NULL;
908
909
910
911
      
      return info;
    }
}
912

913
914
struct address_info *
make_address_info(struct lsh_string *host, UINT32 port)
915
916
917
918
919
920
921
922
{
  NEW(address_info, info);

  info->port = port; /* htons(port); */
  info->ip = host;
  return info;
}

923
924
925
struct address_info *
sockaddr2info(size_t addr_len UNUSED,
	      struct sockaddr *addr)
926
{
927
  NEW(address_info, info);
928
929
930
931
932
933
934
  
  switch(addr->sa_family)
    {
    case AF_INET:
      {
	struct sockaddr_in *in = (struct sockaddr_in *) addr;
	UINT32 ip = ntohl(in->sin_addr.s_addr);
935
	info->port = ntohs(in->sin_port);
936
937
938
939
940
	info->ip = ssh_format("%di.%di.%di.%di",
			      (ip >> 24) & 0xff,
			      (ip >> 16) & 0xff,
			      (ip >> 8) & 0xff,
			      ip & 0xff);
941
942
	return info;
      }
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
#if WITH_IPV6
    case AF_INET6:
      {
	struct sockaddr_in6 *in = (struct sockaddr_in6 *) addr;
	UINT8 *ip = in->sin6_addr.s6_addr;
	info->port = ntohs(in->sin6_port);
	info->ip = ssh_format("%xi:%xi:%xi:%xi:%xi:%xi:%xi:%xi",
			      (ip[0]  << 8) | ip[1],
			      (ip[2]  << 8) | ip[3],
			      (ip[4]  << 8) | ip[5],
			      (ip[6]  << 8) | ip[7],
			      (ip[8]  << 8) | ip[9],
			      (ip[10] << 8) | ip[11],
			      (ip[12] << 8) | ip[13],
			      (ip[14] << 8) | ip[15]);
	return info;
      }
960
#endif
961
962
963
964
    case AF_UNIX:
      /* Silently return NULL. This happens when a gateway client
       * connects. */
      return NULL;
965
    default:
966
      werror("io.c: sockaddr2info: Unsupported address family.\n");
967
      return NULL;
968
969
    }
}
970

971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
#if HAVE_GETADDRINFO
static struct addrinfo *
choose_address(struct addrinfo *list,
	       const int *preference)
{
  int i;
  for (i = 0; preference[i]; i++)
    {
      struct addrinfo *p;
      for (p = list; p; p = p->ai_next)
	if (preference[i] == p->ai_family)
	  return p;
    }
  return NULL;
}
#endif /* HAVE_GETADDRINFO */

/* FIXME: Perhaps this function should be changed to return a list of
 * sockaddr:s? */
990
991
992
struct sockaddr *
address_info2sockaddr(socklen_t *length,
		      struct address_info *a,
993
994
		      /* Preferred address families. Zero-terminated array. */
		      const int *preference,
995
		      int lookup)
996
{
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
  char *host;

  if (a->ip)
    {
      host = alloca(a->ip->length + 1);
  
      memcpy(host, a->ip->data, a->ip->length);
      host[a->ip->length] = '\0';
    }
  else
    host = NULL;
1008

Niels Möller's avatar
Niels Möller committed
1009
1010
  /* Some systems have getaddrinfo, but still doesn't implement all of
   * RFC 2553 */
1011
1012
#if defined(HAVE_GETADDRINFO) && \
    defined(HAVE_GAI_STRERROR) && defined(HAVE_AI_NUMERICHOST)
1013
1014
1015
  {
    struct addrinfo hints;
    struct addrinfo *list;
1016
    struct addrinfo *chosen;
1017
    struct sockaddr *res;
1018
1019
1020
1021
1022
1023
1024
    const int default_preference
#if WITH_IPV6
      [3] = { AF_INET6, AF_INET }
#else
      [2] = { AF_INET, 0 }
#endif      
      ;
1025
1026
1027
    int err;
    /* FIXME: It seems ugly to have to convert the port number to a
     * string. */
1028
    struct lsh_string *service = ssh_format("%di", a->port);
1029
1030
1031
1032
1033
1034
1035
1036
1037

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    if (!lookup)
      hints.ai_flags |= AI_NUMERICHOST;
    
1038
    err = getaddrinfo(host, lsh_get_cstring(service), &hints, &list);
1039
1040
1041
1042
    lsh_string_free(service);

    if (err)
      {
1043
	debug("address_info2sockaddr: getaddrinfo failed (err = %i): %z\n",
1044
1045
1046
1047
	      err, gai_strerror(err));
	return NULL;
      }

1048
1049
1050
1051
1052
1053
1054
1055
1056
    chosen = choose_address(list,
			    preference ? preference : default_preference);
    if (!chosen)
      {
	freeaddrinfo(list);
	return NULL;
      }
    
    *length = chosen->ai_addrlen;
1057
1058
    
    res = lsh_space_alloc(*length);
1059
    memcpy(res, chosen->ai_addr, *length);
1060
1061
1062
1063
    freeaddrinfo(list);

    return res;
  }
1064
1065
1066
#else
/* !(defined(HAVE_GETADDRINFO) &&
     defined(HAVE_GAI_STRERROR) && defined(HAVE_AI_NUMERICHOST) */ 
1067
1068

#if WITH_IPV6
1069
#error IPv6 enabled, but getaddrinfo and friends were not found. 
1070
#endif
1071

1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
  if (a->ip && memchr(a->ip->data, ':', a->ip->length))
    {
      debug("address_info2sockaddr: Literal IPv6 used. Failing.\n");
      return NULL;
    }
  else
    {
      struct sockaddr_in *addr;
      NEW_SPACE(addr);

      *length = sizeof(*addr);
      addr->sin_port = htons(a->port);
1084
1085
1086

      /* Use IPv4 only */
      addr->sin_family = AF_INET;
1087
1088
    
      if (!host)
1089
1090
	/* Any interface */
	addr->sin_addr.s_addr = INADDR_ANY;
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121

      else
	{
	  /* First check for numerical ip-number */
#if HAVE_INET_ATON
	  if (!inet_aton(host, &addr->sin_addr))
#else /* !HAVE_INET_ATON */
	    /* NOTE: It is wrong to work with ((unsigned long int) -1)
	     * directly, as this breaks Linux/Alpha systems. But
	     * INADDR_NONE isn't portable. That's what inet_aton is for;
	     * see the GNU libc documentation. */
# ifndef INADDR_NONE
# define INADDR_NONE ((unsigned long int) -1)
# endif /* !INADDR_NONE */
	  addr->sin_addr.s_addr = inet_addr(host);
	  if (addr->sin_addr.s_addr == INADDR_NONE)
#endif  /* !HAVE_INET_ATON */
	    {
	      struct hostent *hp;

	      if (! (lookup 
		     && (hp = gethostbyname(host))
		     && (hp->h_addrtype == AF_INET)))
		{
		  lsh_space_free(addr);
		  return NULL;
		}

	      memcpy(&addr->sin_addr, hp->h_addr, hp->h_length);
	    }
	}
1122
      return (struct sockaddr *) addr;
1123
1124
1125
1126
    }
#endif /* !HAVE_GETADDRINFO */  
}

1127

Niels Möller's avatar
Niels Möller committed
1128
1129
void io_set_nonblocking(int fd)
{
1130
1131
1132
1133
1134
1135
1136
  int old = fcntl(fd, F_GETFL);

  if (old < 0)
    fatal("io_set_nonblocking: fcntl(F_GETFL) failed, %z", STRERROR(errno));
  
  if (fcntl(fd, F_SETFL, old | O_NONBLOCK) < 0)
    fatal("io_set_nonblocking: fcntl(F_SETFL) failed, %z", STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
1137
1138
}

1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
void io_set_blocking(int fd)
{
  int old = fcntl(fd, F_GETFL);

  if (old < 0)
    fatal("io_set_blocking: fcntl(F_GETFL) failed, %z", STRERROR(errno));
  
  if (fcntl(fd, F_SETFL, old & ~O_NONBLOCK) < 0)
    fatal("io_set_blocking: fcntl(F_SETFL) failed, %z", STRERROR(errno));
}

1150
1151
void io_set_close_on_exec(int fd)
{
1152
1153
1154
1155
1156
1157
1158
1159
1160
  /* NOTE: There's only one documented flag bit, so reading the old
   * value should be redundant. */
  
  int old = fcntl(fd, F_GETFD);

  if (old < 0)
    fatal("io_set_nonblocking: fcntl(F_GETFD) failed, %z", STRERROR(errno));
  
  if (fcntl(fd, F_SETFD, old | 1) < 0)
1161
    fatal("Can't set close-on-exec flag for fd %i: %z\n",
1162
	  fd, STRERROR(errno));
1163
1164
}

Niels Möller's avatar
Niels Möller committed
1165

1166
1167
1168
1169
1170
1171
1172
1173
1174
/* ALL file descripters handled by the backend should use non-blocking mode,
 * and have the close-on-exec flag set. */

void io_init_fd(int fd)
{
  io_set_nonblocking(fd);
  io_set_close_on_exec(fd);
}

1175
struct lsh_fd *
1176
make_lsh_fd(int fd, const char *label,
1177
1178
	    struct exception_handler *e)
{
1179
  NEW(lsh_fd, self);
1180
1181
1182

  io_init_fd(fd);

1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
  init_resource(&self->super, do_kill_fd);

  self->fd = fd;
  self->label = label;
  
  self->e = make_exception_handler(do_exc_io_handler, e, HANDLER_CONTEXT);
  
  self->close_callback = NULL;

  self->want_read = 0;
  self->read = NULL;

  self->want_write = 0;
  self->write = NULL;

  gc_global(&self->super);
  return self;
1200
1201
}

Niels Möller's avatar
Niels Möller committed
1202
/* Some code is taken from Thomas Bellman's tcputils. */
1203
struct lsh_fd *
1204
io_connect(struct sockaddr *remote,
1205
	   socklen_t remote_length,
1206
	   struct command_continuation *c,
1207
	   struct exception_handler *e)
Niels Möller's avatar
Niels Möller committed
1208
{
1209
  int s = socket(remote->sa_family, SOCK_STREAM, 0);
1210
  struct lsh_fd *fd;
Niels Möller's avatar
Niels Möller committed
1211
  
1212
1213
  if (s<0)
    return NULL;
Niels Möller's avatar
Niels Möller committed
1214

1215
  trace("io.c: Connecting using fd %i\n", s);
1216
  
1217
  io_init_fd(s);
Niels Möller's avatar
Niels Möller committed
1218

1219
#if 0
1220
1221
1222
1223
1224
1225
1226
  if (local  &&  bind(s, (struct sockaddr *)local, sizeof *local) < 0)
    {
      int saved_errno = errno;
      close(s);
      errno = saved_errno;
      return NULL;
    }
1227
1228
1229
#endif
  
  if ( (connect(s, remote, remote_length) < 0)
1230
1231
1232
1233
1234
1235
1236
1237
       && (errno != EINPROGRESS) )       
    {
      int saved_errno = errno;
      close(s);
      errno = saved_errno;
      return NULL;
    }

1238