io.c 41.7 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
  assert(fd->want_read);

489
#if 0
490
  if (fd->hanged_up)
491
    {
492
      /* If hanged_up is set, pretend that read returned 0 */
Niels Möller's avatar
Niels Möller committed
493
      goto eof;
494
    }
495
#endif
496
497
498
  
  if (!wanted)
    {
499
      lsh_oop_cancel_read_fd(fd);
500
    }
Niels Möller's avatar
Niels Möller committed
501
502
503
504
505
506
  else
    {
      struct lsh_string *s = lsh_string_alloc(wanted);
      int res = read(fd->fd, s->data, wanted);

      if (res < 0)
507
508
509
510
511
512
513
514
515
516
517
518
519
	{
	  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");
520
	      /* Fall through */
521
522
523
524
525
526
527
528
	    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
529
530
531
      else if (res > 0)
	{
	  s->length = res;
532
	  A_WRITE(self->consumer, s);
Niels Möller's avatar
Niels Möller committed
533
534
	}
      else
535
	{
536
	  lsh_string_free(s);
Niels Möller's avatar
Niels Möller committed
537
538
	eof:
	  /* Close the fd, unless it has a write callback. */
539
	  A_WRITE(self->consumer, NULL);
540
	  close_fd_read(fd);
541
	}
Niels Möller's avatar
Niels Möller committed
542
543
544
545
546
547
548
549
    }
}

/* 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)
{
550
  self->super.f = do_consuming_read;
Niels Möller's avatar
Niels Möller committed
551
552
  self->consumer = consumer;
}
553

554

Niels Möller's avatar
Niels Möller committed
555
/* Write related callbacks */
556
557
558
static void
do_write_callback(struct io_callback *s UNUSED,
		  struct lsh_fd *fd)
Niels Möller's avatar
Niels Möller committed
559
{
560
  /* CAST(io_write_callback, self, s); */
Niels Möller's avatar
Niels Möller committed
561
562
  UINT32 size;
  int res;
563

564
  /* FIXME: Delete this useless indirection. */
565
566
567
568
  FD_PREPARE(fd);

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

604
605
606
607
608
609
610
611
612
613
static struct io_callback io_write_callback =
{ STATIC_HEADER, do_write_callback };

static void
do_write_prepare(struct lsh_fd *fd)
{
  assert(fd->write_buffer);

  if (! (fd->want_write = write_buffer_pre_write(fd->write_buffer))
      && fd->write_buffer->closed)
614
    close_fd(fd);
615
616
617
618
619
620
621
622
623
624
625
626
627
628
}

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
629
630
631

/* Listen callback */

632
633
634
635
636
637
638
639
640
/* 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
641
static void
642
do_listen_callback(struct io_callback *s,
Niels Möller's avatar
Niels Möller committed
643
		   struct lsh_fd *fd)
Niels Möller's avatar
Niels Möller committed
644
{
645
  CAST(io_listen_callback, self, s);
646
647
648
649
650
651

#if WITH_IPV6
  struct sockaddr_storage peer;
#else
  struct sockaddr peer;
#endif
652
653

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

Niels Möller's avatar
Niels Möller committed
656
657
658
  conn = accept(fd->fd,
		(struct sockaddr *) &peer, &addr_len);
  if (conn < 0)
659
    {
660
      werror("io.c: accept failed, %z", STRERROR(errno));
Niels Möller's avatar
Niels Möller committed
661
      return;
662
    }
663
  trace("io.c: accept on fd %i\n", conn);
664
  COMMAND_RETURN(self->c,
665
		 make_listen_value(make_lsh_fd(conn, "accepted socket", self->e),
666
667
				   sockaddr2info(addr_len,
						 (struct sockaddr *) &peer)));
Niels Möller's avatar
Niels Möller committed
668
}
669

670
struct io_callback *
671
make_listen_callback(struct command_continuation *c,
672
673
674
675
676
677
678
679
680
		     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
681

Niels Möller's avatar
Niels Möller committed
682
683
/* Connect callback */

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

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;
729
730
}

731

Niels Möller's avatar
Niels Möller committed
732
/* This function is called if a connection this file somehow depends
733
734
735
736
737
738
739
740
 * 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
741
742
  /* We use close_fd_nicely, so that any data in the write buffer is
   * flushed before the fd is closed. */
743
  if (r->alive)
744
    close_fd_nicely(fd);
745
746
}

747
748
749
750
751
752
753
754
755
756
/* 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);

757
      if (e->fd)
758
	close_fd(e->fd);
759
760
761
762
763
    }
  EXCEPTION_RAISE(self->parent, x);
  return;
}

764

765
/* These functions are used by werror and friends */
Niels Möller's avatar
Niels Möller committed
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
823
824
825
826
827
828
829
830
831
832
833
834
835

/* 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;
}

836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
/* 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
867
868
869

/* Network utility functions */

870
/* Converts a string port number or service name to a port number.
871
872
 * Returns the port number in _host_ byte order, or 0 if lookup
 * fails. */
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893

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);
894
895
	  if (!serv)
	    return 0;
896
897
898
899
900
901
	  return ntohs(serv->s_port);
	}
    }
}


902
903
904
905
906
/* 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)
907
908
{
  int portno = get_portno(port, "tcp");
909
910
911
912
913
914
  if (!portno)
    portno = def;

  if (!portno)
    return NULL;

915
916
917
918
919
  else
    {
      NEW(address_info, info);
      
      info->port = portno;
920
      info->ip = host ? ssh_format("%lz", host) : NULL;
921
922
923
924
      
      return info;
    }
}
925

926
927
struct address_info *
make_address_info(struct lsh_string *host, UINT32 port)
928
929
930
931
932
933
934
935
{
  NEW(address_info, info);

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

936
937
938
struct address_info *
sockaddr2info(size_t addr_len UNUSED,
	      struct sockaddr *addr)
939
{
940
  NEW(address_info, info);
941
942
943
944
945
946
947
  
  switch(addr->sa_family)
    {
    case AF_INET:
      {
	struct sockaddr_in *in = (struct sockaddr_in *) addr;
	UINT32 ip = ntohl(in->sin_addr.s_addr);
948
	info->port = ntohs(in->sin_port);
949
950
951
952
953
	info->ip = ssh_format("%di.%di.%di.%di",
			      (ip >> 24) & 0xff,
			      (ip >> 16) & 0xff,
			      (ip >> 8) & 0xff,
			      ip & 0xff);
954
955
	return info;
      }
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
#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;
      }
973
#endif
974
975
976
977
    case AF_UNIX:
      /* Silently return NULL. This happens when a gateway client
       * connects. */
      return NULL;
978
    default:
979
      werror("io.c: sockaddr2info: Unsupported address family.\n");
980
      return NULL;
981
982
    }
}
983

984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
#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? */
1003
1004
1005
struct sockaddr *
address_info2sockaddr(socklen_t *length,
		      struct address_info *a,
1006
1007
		      /* Preferred address families. Zero-terminated array. */
		      const int *preference,
1008
		      int lookup)
1009
{
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
  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;
1021

Niels Möller's avatar
Niels Möller committed
1022
1023
  /* Some systems have getaddrinfo, but still doesn't implement all of
   * RFC 2553 */
1024
1025
#if defined(HAVE_GETADDRINFO) && \
    defined(HAVE_GAI_STRERROR) && defined(HAVE_AI_NUMERICHOST)
1026
1027
1028
  {
    struct addrinfo hints;
    struct addrinfo *list;
1029
    struct addrinfo *chosen;
1030
    struct sockaddr *res;
1031
1032
1033
1034
1035
1036
1037
    const int default_preference
#if WITH_IPV6
      [3] = { AF_INET6, AF_INET }
#else
      [2] = { AF_INET, 0 }
#endif      
      ;
1038
1039
1040
    int err;
    /* FIXME: It seems ugly to have to convert the port number to a
     * string. */
1041
    struct lsh_string *service = ssh_format("%di", a->port);
1042
1043
1044
1045
1046
1047
1048
1049
1050

    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;
    
1051
    err = getaddrinfo(host, lsh_get_cstring(service), &hints, &list);
1052
1053
1054
1055
    lsh_string_free(service);

    if (err)
      {
1056
	debug("address_info2sockaddr: getaddrinfo failed (err = %i): %z\n",
1057
1058
1059
1060
	      err, gai_strerror(err));
	return NULL;
      }

1061
1062
1063
1064
1065
1066
1067
1068
1069
    chosen = choose_address(list,
			    preference ? preference : default_preference);
    if (!chosen)
      {
	freeaddrinfo(list);
	return NULL;
      }
    
    *length = chosen->ai_addrlen;
1070
1071
    
    res = lsh_space_alloc(*length);
1072
    memcpy(res, chosen->ai_addr, *length);
1073
1074
1075
1076
    freeaddrinfo(list);

    return res;
  }
1077
1078
1079
#else
/* !(defined(HAVE_GETADDRINFO) &&
     defined(HAVE_GAI_STRERROR) && defined(HAVE_AI_NUMERICHOST) */ 
1080
1081

#if WITH_IPV6
1082
#error IPv6 enabled, but getaddrinfo and friends were not found. 
1083
#endif
1084

1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
  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);
1097
1098
1099

      /* Use IPv4 only */
      addr->sin_family = AF_INET;
1100
1101
    
      if (!host)
1102
1103
	/* Any interface */
	addr->sin_addr.s_addr = INADDR_ANY;
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134

      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);
	    }
	}
1135
      return (struct sockaddr *) addr;
1136
1137
1138
1139
    }
#endif /* !HAVE_GETADDRINFO */  
}

1140

Niels Möller's avatar
Niels Möller committed
1141
1142
void io_set_nonblocking(int fd)
{
1143
1144
1145
1146
1147
1148
1149
  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
1150
1151
}

1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
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));
}

1163
1164
void io_set_close_on_exec(int fd)
{
1165
1166
1167
1168
1169
1170
1171
1172
1173
  /* 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)
1174
    fatal("Can't set close-on-exec flag for fd %i: %z\n",
1175
	  fd, STRERROR(errno));
1176
1177
}

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

1179
1180
1181
1182
1183
1184
1185
1186
1187
/* 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);
}

1188
struct lsh_fd *
1189
make_lsh_fd(int fd, const char *label,
1190
1191
	    struct exception_handler *e)
{
1192
  NEW(lsh_fd, self);
1193
1194
1195

  io_init_fd(fd);

1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
  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->prepare = NULL;

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

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

  gc_global(&self->super);
  return self;
1215
1216
}

Niels Möller's avatar
Niels Möller committed
1217
/* Some code is taken from Thomas Bellman's tcputils. */
1218
struct lsh_fd *
1219
io_connect(struct sockaddr *remote,
1220
	   socklen_t remote_length,
1221
	   struct command_continuation *c,