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

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

Niels Möller's avatar
Niels Möller committed
26 27 28
#include <assert.h>
#include <string.h>

Niels Möller's avatar
Niels Möller committed
29 30 31 32 33 34
#include <unistd.h>
#include <poll.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
Niels Möller's avatar
Niels Möller committed
35
#include <arpa/inet.h>
Niels Möller's avatar
Niels Möller committed
36

Niels Möller's avatar
Niels Möller committed
37 38 39 40 41
#include "io.h"
#include "werror.h"
#include "write_buffer.h"
#include "xalloc.h"

Niels Möller's avatar
Niels Möller committed
42 43 44 45 46
/* A little more than an hour */
#define MAX_TIMEOUT 4000

struct fd_read
{
47
  struct abstract_read super;
Niels Möller's avatar
Niels Möller committed
48 49 50
  int fd;
};

Niels Möller's avatar
Niels Möller committed
51
static int do_read(struct abstract_read **r, UINT32 length, UINT8 *buffer)
Niels Möller's avatar
Niels Möller committed
52
{
53 54 55
  struct fd_read *closure
    = (struct fd_read *) *r;

56 57
  MDEBUG(closure);
  
58 59 60 61 62 63 64
  while(1)
    {
      int res = read(closure->fd, buffer, length);
      if (!res)
	return A_EOF;
      if (res > 0)
	return res;
65

66 67 68 69 70 71 72
      switch(errno)
	{
	case EINTR:
	  continue;
	case EWOULDBLOCK:  /* aka EAGAIN */
	  return 0;
	default:
Niels Möller's avatar
Niels Möller committed
73 74 75 76
	  werror("io.c: do_read: read() failed (errno %d), %s\n",
		 errno, strerror(errno));
	  debug("  fd = %d, buffer = %p, length = %ud\n",
		closure->fd, buffer, length);
77 78 79 80
	  return A_FAIL;
	}
    }
}
Niels Möller's avatar
Niels Möller committed
81

82 83 84
#define FOR_FDS(type, fd, list, extra)				\
{								\
  type **(_fd);							\
Niels Möller's avatar
Niels Möller committed
85
  type *(fd);							\
Niels Möller's avatar
Niels Möller committed
86
  for(_fd = &(list); ((fd) = *_fd); (extra)) {
87 88


Niels Möller's avatar
Niels Möller committed
89 90 91
#define END_FOR_FDS _fd = &(*_fd)->next; } }

/* UNLINK_FD must be followed by a continue, to avoid updating _fd */
92
#define UNLINK_FD (*_fd = (*_fd)->next)
93

94 95 96 97 98 99 100 101
static void close_fd(struct io_fd *fd)
{
  /* FIXME: The value returned from the close callback could be used
   * to choose an exit code. */
  if (fd->close_callback && fd->close_reason)
    (void) CLOSE_CALLBACK(fd->close_callback, fd->close_reason);
  
  close(fd->fd);
102 103 104 105 106

  /* Make sure writing to the buffer fails. */
  if (fd->buffer)
    write_buffer_close(fd->buffer);
  
107 108 109 110
  /* There can be other objects around that may still
   * attempt to write to the buffer. So let gc handle it
   * instead of freeing it explicitly */
#if 0
111
  lsh_object_free(fd->buffer);
112 113
#endif
  /* Handlers are not shared, so it should be ok to free them. */
114 115
  lsh_object_free(fd->handler);
  lsh_object_free(fd);
116 117
}

118
static int io_iter(struct io_backend *b)
Niels Möller's avatar
Niels Möller committed
119
{
120 121 122 123 124 125 126 127 128
  struct pollfd *fds;
  int i;
  unsigned long nfds; /* FIXME: Should be nfds_t if that type is defined */
  int timeout;
  int res;

  nfds = b->nio + b->nlisten + b->nconnect;

  if (b->callouts)
Niels Möller's avatar
Niels Möller committed
129
    {
130 131 132
      time_t now = time(NULL);
      if (now >= b->callouts->when)
	timeout = 0;
Niels Möller's avatar
Niels Möller committed
133
      else
134 135 136 137 138 139 140 141 142 143 144 145 146 147
	{
	  if (b->callouts->when > now + MAX_TIMEOUT)
	    timeout = MAX_TIMEOUT * 1000;
	  else
	    timeout = (b->callouts->when - now) * 1000;
	}
    }
  else
    {
      if (!nfds)
	/* All done */
	return 0;
      timeout = -1;
    }
148

149
  fds = alloca(sizeof(struct pollfd) * nfds);
Niels Möller's avatar
Niels Möller committed
150

151 152
  /* Handle fds in order: write, read, accept, connect. */
  i = 0;
153

154 155 156 157
  FOR_FDS(struct io_fd, fd, b->io, i++)
    {
      fds[i].fd = fd->fd;
      fds[i].events = 0;
Niels Möller's avatar
Niels Möller committed
158
      if (fd->handler && !fd->on_hold)
159 160 161
	fds[i].events |= POLLIN;

      /* pre_write returns 0 if the buffer is empty */
162 163 164 165 166 167 168 169 170 171 172
      if (fd->buffer)
	{
	  if (write_buffer_pre_write(fd->buffer))
	    fds[i].events |= POLLOUT;
	  else
	    /* Buffer is empty. Should we close? */
	    if (fd->buffer->closed)
	      {
		fd->close_now = 1;
	      }
	}
173 174
    }
  END_FOR_FDS;
175

176 177 178 179 180 181
  FOR_FDS(struct listen_fd, fd, b->listen, i++)
    {
      fds[i].fd = fd->fd;
      fds[i].events = POLLIN;
    }
  END_FOR_FDS;
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  FOR_FDS(struct connect_fd, fd, b->connect, i++)
    {
      fds[i].fd = fd->fd;
      fds[i].events = POLLOUT;
    }
  END_FOR_FDS;

  res = poll(fds, nfds, timeout);

  if (!res)
    {
      /* Timeout. Run the callout */
      struct callout *f = b->callouts;

      if (!CALLBACK(f->callout))
	fatal("What now?");
      b->callouts = f->next;
200
      lsh_object_free(f);
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    }
  if (res<0)
    {
      switch(errno)
	{
	case EAGAIN:
	case EINTR:
	  return 1;
	default:
	  fatal("io_run:poll failed: %s", strerror(errno));
	}
    }
  else
    { /* Process files */
      i = 0;

      /* Handle writing first */
      FOR_FDS(struct io_fd, fd, b->io, i++)
	{
	  if (fds[i].revents & POLLOUT)
	    {
	      UINT32 size = MIN(fd->buffer->end - fd->buffer->start,
				fd->buffer->block_size);
	      int res = write(fd->fd,
			      fd->buffer->buffer + fd->buffer->start,
			      size);
	      if (!res)
		fatal("Closed?");
	      if (res < 0)
		switch(errno)
		  {
		  case EINTR:
		  case EAGAIN:
		    break;
		  default:
		    werror("io.c: write failed, %s\n", strerror(errno));

238 239
		    fd->close_reason = CLOSE_WRITE_FAILED;
		    fd->close_now = 1;
240 241 242 243 244 245 246

		    break;
		  }
	      else
		fd->buffer->start += res;
	    }
	}
247 248
      END_FOR_FDS;

249 250 251 252
      /* Handle reading */
      i = 0; /* Start over */
      FOR_FDS(struct io_fd, fd, b->io, i++)
	{
253
	  if (!fd->close_now
254 255
	      && (fds[i].revents & POLLIN))
	    {
256 257
	      int res;
	      
258
	      struct fd_read r =
Niels Möller's avatar
Niels Möller committed
259
	      { { STACK_HEADER, do_read }, fd->fd };
Niels Möller's avatar
Niels Möller committed
260

261
	      /* The handler function may install a new handler */
262 263
	      res = READ_HANDLER(fd->handler,
				 &r.super);
264 265 266
	      /* NOTE: These flags are not mutually exclusive. All
	       * combination must be handled correctly. */

267 268 269 270
	      /* NOTE: (i) If LSH_DIE is set, LSH_CLOSE is ignored.
	       * (ii) If the fd is read_only, LSH_CLOSE is the same as LSH_DIE.
	       */
#if 0
271 272 273 274 275 276 277 278 279 280
	      if ( (res & (LSH_CLOSE | LSH_DIE)) == (LSH_CLOSE | LSH_DIE) )
		{
		  debug("return code %x, both LSH_CLOSE and LSH_DIE set.\n",
			res);
		  /* LSH_DIE takes precedence */
		  res &= ~LSH_CLOSE;

		  /* FIXME: Perhaps we should always set LSH_FAIL in
		   * this case? */
		}
281 282 283 284 285 286 287
#endif
	      if (res & LSH_HOLD)
		{
		  /* This flag should not be combined with anything else */
		  assert(res == LSH_HOLD);
		  fd->on_hold = 1;
		}
288 289 290 291 292 293 294
	      if (res & LSH_DIE)
		{
		  if (fd->buffer)
		    write_buffer_close(fd->buffer);
		  
		  fd->close_reason = LSH_FAILUREP(res)
		    ? CLOSE_PROTOCOL_FAILURE : 0;
295
		  fd->close_now = 1;
296
		}
297 298 299 300 301 302 303 304 305 306
	      else if (res & LSH_CLOSE)
		{
		  if (fd->buffer)
		    write_buffer_close(fd->buffer);
		  else
		    fd->close_now = 1;
		  
		  fd->close_reason
		    = LSH_FAILUREP(res) ? CLOSE_PROTOCOL_FAILURE : CLOSE_EOF;
		}
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
	      if (res & LSH_KILL_OTHERS)
		{
		  /* Close all other files. We have probably fork()ed. */
		  {
		    struct io_fd *p;
		    struct io_fd *next;
		    
		    for (p = b->io; (p = next) ; )
		      {
			next = p->next;
			
			if (p->fd != fd->fd)
			  {
			    p->close_reason = 0;
			    
			    /* In this case, it should be safe to
			     * deallocate the buffer immediately */
324
			    lsh_object_free(p->buffer);
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
			    close_fd(p);
			  }
		      }
		    if (fd->close_now)
		      {
			/* Some error occured. So close this fd too! */
			close_fd(fd);
			b->io = NULL;
			b->nio = 0;
		      }
		    else
		      { /* Keep this single descriptor open */
			fd->next = NULL;
			b->io = fd;
			b->nio = 1;
		      }
		  }{
		    struct listen_fd *p;
		    struct listen_fd *next;
		    for (p = b->listen; (p = next); )
		      {
			next = p->next;
			close(p->fd);
348
			lsh_space_free(p);
349 350 351 352 353 354 355 356 357 358
		      }
		    b->listen = NULL;
		    b->nlisten = 0;
		  }{
		    struct connect_fd *p;
		    struct connect_fd *next;
		    for (p = b->connect; (p = next); )
		      {
			next = p->next;
			close(p->fd);
359
			lsh_space_free(p);
360 361 362 363 364 365
		      }
		    b->connect = NULL;
		    b->nconnect = 0;
		  }{
		    struct callout *p;
		    struct callout *next;
Niels Möller's avatar
Niels Möller committed
366
		    for (p = b->callouts; (p = next); )
367 368
		      {
			next = p->next;
369
			lsh_space_free(p);
370 371 372 373 374
		      }
		    b->callouts = NULL;
		  }
		  /* Skip the rest od this iteration */
		  return 1;
Niels Möller's avatar
Niels Möller committed
375
		}
376
	    }
377
	  if (fd->close_now)
378 379 380 381 382
	    {
	      /* FIXME: Cleanup properly...
	       *
	       * After a write error, read state must be freed,
	       * and vice versa. */
383

384
	      close_fd(fd);
385

386
	      UNLINK_FD;
387

388 389 390 391 392
	      b->nio--;
	      continue;
	    }
	}
      END_FOR_FDS;
393

394 395 396
      FOR_FDS(struct listen_fd, fd, b->listen, i++)
	{
	  if (fds[i].revents & POLLIN)
Niels Möller's avatar
Niels Möller committed
397
	    {
398 399 400
	      /* FIXME: Do something with the peer address? */
	      struct sockaddr_in peer;
	      size_t addr_len = sizeof(peer);
401 402
	      int res;
	      
403 404 405 406 407 408
	      int conn = accept(fd->fd,
				(struct sockaddr *) &peer, &addr_len);
	      if (conn < 0)
		{
		  werror("io.c: accept() failed, %s", strerror(errno));
		  continue;
Niels Möller's avatar
Niels Möller committed
409
		}
410
	      res = FD_CALLBACK(fd->callback, conn);
411
	      if (LSH_ACTIONP(res))
Niels Möller's avatar
Niels Möller committed
412
		{
413 414 415
		  werror("Strange: Accepted a connection, "
			 "but failed before writing anything.\n");
		  close(fd->fd);
416
		  UNLINK_FD;
417
		  lsh_object_free(fd);
Niels Möller's avatar
Niels Möller committed
418
		  continue;
Niels Möller's avatar
Niels Möller committed
419 420
		}
	    }
421
	}
422 423 424 425 426 427
      END_FOR_FDS;
	  
      FOR_FDS(struct connect_fd, fd, b->connect, i++)
	{
	  if (fds[i].revents & POLLOUT)
	    {
428 429
	      int res = FD_CALLBACK(fd->callback, fd->fd);

430
	      if (LSH_ACTIONP(res))
431 432
		werror("Strange: Connected, "
		       "but failed before writing anything.\n");
433 434
	      b->nconnect--;
	      UNLINK_FD;
435
	      lsh_object_free(fd);
436 437 438 439 440 441 442 443
	      continue;
	    }
	}
      END_FOR_FDS;
    }
  return 1;
}

444
/* FIXME: Prehaps this function should return a suitable exit code? */
445 446 447 448
void io_run(struct io_backend *b)
{
  while(io_iter(b))
    ;
449 450
}

451 452 453 454 455 456 457 458 459 460 461
void init_backend(struct io_backend *b)
{
  b->nio = 0;
  b->io = NULL;
  b->nlisten = 0;
  b->listen = NULL;
  b->nconnect = 0;
  b->connect = NULL;
  b->callouts = NULL;
}

462 463 464
/*
 * Fill in ADDR from HOST, SERVICE and PROTOCOL.
 * Supplying a null pointer for HOST means use INADDR_ANY.
465
 * Otherwise HOST is an numbers-and-dots ip-number or a dns name.
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 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
 *
 * PROTOCOL can be tcp or udp.
 *
 * Supplying a null pointer for SERVICE, means use port 0, i.e. no port.
 * 
 * Returns zero on errors, 1 if everything is ok.
 */
int
get_inaddr(struct sockaddr_in	* addr,
	   const char		* host,
	   const char		* service,
	   const char		* protocol)
{
  memset(addr, 0, sizeof *addr);
  addr->sin_family = AF_INET;

  /*
   *  Set host part of ADDR
   */
  if (host == NULL)
    addr->sin_addr.s_addr = INADDR_ANY;
  else
    {
      /* First check for numerical ip-number */
      addr->sin_addr.s_addr = inet_addr(host);
      if (addr->sin_addr.s_addr == (unsigned long)-1)
	{
	  struct hostent * hp;
	  
	  hp = gethostbyname(host);
	  if (hp == NULL)
	    return 0;
	  memcpy(&addr->sin_addr, hp->h_addr, hp->h_length);
	  addr->sin_family = hp->h_addrtype;
	}
    }

  /*
   *  Set port part of ADDR
   */
  if (service == NULL)
    addr->sin_port = htons(0);
  else
    {
      char		* end;
      long		  portno;

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

	  serv = getservbyname(service, "tcp");
	  if (serv == NULL)
	    return 0;
	  addr->sin_port = serv->s_port;
Niels Möller's avatar
Niels Möller committed
527 528
	}
    }
529 530

  return 1;
Niels Möller's avatar
Niels Möller committed
531 532 533 534 535 536 537 538
}

void io_set_nonblocking(int fd)
{
  if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
    fatal("io_set_nonblocking: fcntl() failed, %s", strerror(errno));
}

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
void io_set_close_on_exec(int fd)
{
  if (fcntl(fd, F_SETFD, 1) < 0)
    fatal("Can't set close-on-exec flag for fd %d: %s\n",
	  fd, strerror(errno));
}

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

555 556 557 558 559
/* Some code is taken from bellman's tcputils. */
struct connect_fd *io_connect(struct io_backend *b,
			      struct sockaddr_in *remote,
			      struct sockaddr_in *local,
			      struct fd_callback *f)
Niels Möller's avatar
Niels Möller committed
560
{
561 562
  struct connect_fd *fd;
  int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
Niels Möller's avatar
Niels Möller committed
563
  
564 565
  if (s<0)
    return NULL;
Niels Möller's avatar
Niels Möller committed
566

567
  io_init_fd(s);
Niels Möller's avatar
Niels Möller committed
568

569 570 571 572 573 574 575
  if (local  &&  bind(s, (struct sockaddr *)local, sizeof *local) < 0)
    {
      int saved_errno = errno;
      close(s);
      errno = saved_errno;
      return NULL;
    }
Niels Möller's avatar
Niels Möller committed
576

577 578 579 580 581 582 583 584 585
  if ( (connect(s, (struct sockaddr *)remote, sizeof *remote) < 0)
       && (errno != EINPROGRESS) )       
    {
      int saved_errno = errno;
      close(s);
      errno = saved_errno;
      return NULL;
    }
  
Niels Möller's avatar
Niels Möller committed
586
  NEW(fd);
587
  fd->fd = s;
Niels Möller's avatar
Niels Möller committed
588
  fd->callback = f;
589 590 591

  fd->next = b->connect;
  b->connect = fd;
Niels Möller's avatar
Niels Möller committed
592

593 594 595
  b->nconnect++;
  
  return fd;
Niels Möller's avatar
Niels Möller committed
596 597
}

598 599 600 601 602 603
struct listen_fd *io_listen(struct io_backend *b,
			    struct sockaddr_in *local,
			    struct fd_callback *callback)
{
  struct listen_fd *fd;
  int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
Niels Möller's avatar
Niels Möller committed
604
  
605 606 607
  if (s<0)
    return NULL;

608
  io_init_fd(s);
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626

  {
    int yes = 1;
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof yes);
  }

  if (bind(s, (struct sockaddr *)local, sizeof *local) < 0)
    {
      close(s);
      return NULL;
    }

  if (listen(s, 256) < 0) 
    {
      close(s);
      return NULL;
    }

Niels Möller's avatar
Niels Möller committed
627
  NEW(fd);
628 629 630 631 632 633 634

  fd->fd = s;
  fd->callback = callback;

  fd->next = b->listen;
  b->listen = fd;
  b->nlisten++;
Niels Möller's avatar
Niels Möller committed
635
  
636 637 638
  return fd;
}

Niels Möller's avatar
Niels Möller committed
639 640
struct abstract_write *io_read_write(struct io_backend *b,
				     int fd,
Niels Möller's avatar
Niels Möller committed
641
				     struct read_handler *read_callback,
Niels Möller's avatar
Niels Möller committed
642
				     UINT32 block_size,
643
				     struct close_callback *close_callback)
644
{
Niels Möller's avatar
Niels Möller committed
645
  struct io_fd *f;
646
  struct write_buffer *buffer = write_buffer_alloc(block_size);
Niels Möller's avatar
Niels Möller committed
647

648 649
  io_init_fd(fd);
  
Niels Möller's avatar
Niels Möller committed
650
  NEW(f);
Niels Möller's avatar
Niels Möller committed
651
  f->fd = fd;
652 653 654
  
  f->close_reason = -1; /* Invalid reason */
  f->close_now = 0;
655 656

  /* Reading */
Niels Möller's avatar
Niels Möller committed
657
  f->handler = read_callback;
658 659 660
  f->on_hold = 0;

  /* Writing */
Niels Möller's avatar
Niels Möller committed
661
  f->buffer = buffer;
662
  f->close_callback = close_callback;
663

Niels Möller's avatar
Niels Möller committed
664 665
  f->next = b->io;
  b->io = f;
Niels Möller's avatar
Niels Möller committed
666
  b->nio++;
667

668
  return &buffer->super;
669
}
670 671 672 673 674 675 676 677

struct io_fd *io_read(struct io_backend *b,
		      int fd,
		      struct read_handler *read_callback,
		      struct close_callback *close_callback)
{
  struct io_fd *f;

678 679
  io_init_fd(fd);

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
  NEW(f);
  f->fd = fd;
  
  f->close_reason = -1; /* Invalid reason */
  f->close_now = 0;

  /* Reading */
  f->handler = read_callback;
  f->on_hold = 0;

  /* Writing */
  f->buffer = NULL;

  f->close_callback = close_callback;

  f->next = b->io;
  b->io = f;
  b->nio++;

  return f;
}

702 703 704 705
struct io_fd *io_write(struct io_backend *b,
		       int fd,
		       UINT32 block_size,
		       struct close_callback *close_callback)
706 707 708 709
{
  struct io_fd *f;
  struct write_buffer *buffer = write_buffer_alloc(block_size);

710 711
  io_init_fd(fd);
  
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
  NEW(f);
  f->fd = fd;
  
  f->close_reason = -1; /* Invalid reason */
  f->close_now = 0;

  /* Reading */
  f->handler = NULL;

  /* Writing */
  f->buffer = buffer;
  f->close_callback = close_callback;

  f->next = b->io;
  b->io = f;
  b->nio++;

729
  return f;
730
}