io.c 17.2 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 21
 *
 * $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
22 23
 */

24 25 26 27 28
#include "io.h"
#include "werror.h"
#include "write_buffer.h"
#include "xalloc.h"

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

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

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

Niels Möller's avatar
Niels Möller committed
46 47 48 49
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
Niels Möller's avatar
Niels Möller committed
50
#include <arpa/inet.h>
51
#include <signal.h>
Niels Möller's avatar
Niels Möller committed
52

53 54 55 56 57 58
#define CLASS_DEFINE
#include "io.h.x"
#undef CLASS_DEFINE

#include "io.c.x"

Niels Möller's avatar
Niels Möller committed
59 60 61 62 63
/* If there's nothing to do for this amount of time (ms), do
 * spontaneous gc. */

#define IDLE_TIME 100

Niels Möller's avatar
Niels Möller committed
64 65 66 67 68
int io_iter(struct io_backend *b)
{
  unsigned long nfds; /* FIXME: Should be nfds_t if that type is defined */
  struct pollfd *fds;

Niels Möller's avatar
Niels Möller committed
69 70
  /* FIXME: Callouts not implemented */
  /* int timeout; */
Niels Möller's avatar
Niels Möller committed
71 72 73 74 75 76 77 78 79
  int res;

  nfds = 0;
  
  {
    /* Prepare fd:s. This fase calls the prepare-methods, also closes
     * and unlinks any fd:s that should be closed, and also counts how
     * many fd:s there are. */
    
Niels Möller's avatar
Niels Möller committed
80
    struct lsh_fd **fd_p;
Niels Möller's avatar
Niels Möller committed
81 82
    struct lsh_fd *fd;
    
Niels Möller's avatar
Niels Möller committed
83
    for(fd_p = &b->files; (fd = *fd_p); )
Niels Möller's avatar
Niels Möller committed
84
      {
85
	if (fd->super.alive && fd->prepare)
Niels Möller's avatar
Niels Möller committed
86 87
	  PREPARE_FD(fd);
	
88
	if (!fd->super.alive)
Niels Möller's avatar
Niels Möller committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
	  {
	    if (fd->fd < 0)
	      /* Unlink the file object, but don't close any underlying file. */
	      ;
	    else
	      {
		/* Used by write fd:s to make sure that writing to its
		 * buffer fails. */
		if (fd->really_close)
		  REALLY_CLOSE_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);
		
		debug("Closing fd %d.\n", fd->fd);
		
		close(fd->fd);
	      }
	    /* Unlink this fd */
Niels Möller's avatar
Niels Möller committed
110
	    *fd_p = fd->next;
Niels Möller's avatar
Niels Möller committed
111 112 113
	    continue;
	  }
	nfds++;
Niels Möller's avatar
Niels Möller committed
114
	fd_p = &fd->next;
Niels Möller's avatar
Niels Möller committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
      }
	
  }

  if (!nfds)
    /* Nothing more to do.
     *
     * NOTE: There might be some callouts left, but we won't wait for them. */
    return 0;
  
  fds = alloca(sizeof(struct pollfd) * nfds);

  /* Fill out fds-array */
  {
    struct lsh_fd *fd;
130
    unsigned long i;
Niels Möller's avatar
Niels Möller committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    int all_events = 0;
    
    for (fd = b->files, i = 0; fd; fd = fd->next, i++)
      {
	assert(i < nfds);

	fds[i].fd = fd->fd;
	fds[i].events = 0;

	if (fd->want_read)
	  fds[i].events |= POLLIN;

	if (fd->want_write)
	  fds[i].events |= POLLOUT;

	all_events |= fds[i].events;
      }
    assert(i == nfds);

    if (!all_events)
      {
	/* Nothing happens */
	/* NOTE: There might be some callouts left, but we don't wait */
	return 0;
      }
  }

Niels Möller's avatar
Niels Möller committed
158
  res = poll(fds, nfds, IDLE_TIME);
Niels Möller's avatar
Niels Möller committed
159

Niels Möller's avatar
Niels Möller committed
160 161 162 163 164
  if (!res)
    {
      gc_maybe(&b->super, 0);
      res = poll(fds, nfds, -1);
    }
165 166
  else
    gc_maybe(&b->super, 1);
Niels Möller's avatar
Niels Möller committed
167
  
Niels Möller's avatar
Niels Möller committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  if (!res)
    {
      /* Callouts are not implemented */
      fatal("Unexpected timeout\n");
    }
  if (res < 0)
    switch(errno)
      {
      case EAGAIN:
      case EINTR:
	return 1;
      default:
	fatal("io_iter: poll failed: %s", strerror(errno));
      }
  
  {
    /* Do io. Note that the callback functions may add new fds to the
185
     * head of the list, or clear the alive flag on any fd. */
Niels Möller's avatar
Niels Möller committed
186 187

    struct lsh_fd *fd;
188
    unsigned long i;
Niels Möller's avatar
Niels Möller committed
189 190 191 192 193
    
    for(fd = b->files, i=0; fd; fd = fd->next, i++)
      {
	assert(i<nfds);
	
194
	if (!fd->super.alive)
Niels Möller's avatar
Niels Möller committed
195 196 197 198 199
	  continue;

	if (fds[i].revents & POLLOUT)
	  WRITE_FD(fd);

200
	if (!fd->super.alive)
Niels Möller's avatar
Niels Möller committed
201 202 203 204 205 206 207 208 209 210
	  continue;

	if (fds[i].revents & POLLIN)
	  READ_FD(fd);
      }
    assert(i == nfds);
  }

  return 1;
}
Niels Möller's avatar
Niels Möller committed
211

212 213 214 215 216 217 218 219
/* CLASS:
   (class
     (name fd_read)
     (super abstract_read)
       (vars
         (fd simple int)))
*/

Niels Möller's avatar
Niels Möller committed
220
static int do_read(struct abstract_read **r, UINT32 length, UINT8 *buffer)
Niels Möller's avatar
Niels Möller committed
221
{
222
  CAST(fd_read, closure, *r);
223

224 225 226 227
  while(1)
    {
      int res = read(closure->fd, buffer, length);
      if (!res)
Niels Möller's avatar
Niels Möller committed
228 229 230 231
	{
	  debug("Read EOF on fd %d.\n", closure->fd);
	  return A_EOF;
	}
232 233
      if (res > 0)
	return res;
234

235 236 237
      switch(errno)
	{
	case EINTR:
238 239
	  continue;  /* FIXME: Is it really worth looping here,
		      * instead of in the select loop? */
240 241
	case EWOULDBLOCK:  /* aka EAGAIN */
	  return 0;
Niels Möller's avatar
Niels Möller committed
242
	case EPIPE:
243
	  wwrite("io.c: read() returned EPIPE! Treating it as EOF.\n");
Niels Möller's avatar
Niels Möller committed
244
	  return A_EOF;
245
	default:
Niels Möller's avatar
Niels Möller committed
246 247 248 249
	  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);
250 251 252 253
	  return A_FAIL;
	}
    }
}
Niels Möller's avatar
Niels Möller committed
254

Niels Möller's avatar
Niels Möller committed
255
static void read_callback(struct lsh_fd *fd)
256
{
257
  CAST(io_fd, self, fd);
Niels Möller's avatar
Niels Möller committed
258
  int res;
259

Niels Möller's avatar
Niels Möller committed
260 261
  struct fd_read r =
  { { STACK_HEADER, do_read }, fd->fd };
262

Niels Möller's avatar
Niels Möller committed
263 264 265
  /* The handler function may install a new handler */
  res = READ_HANDLER(self->handler,
		     &r.super);
266

Niels Möller's avatar
Niels Möller committed
267 268
  /* NOTE: These flags are not mutually exclusive. All combination
   * must be handled correctly. */
269
  
Niels Möller's avatar
Niels Möller committed
270 271
  /* 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. */
272

Niels Möller's avatar
Niels Möller committed
273 274
  /* This condition must be taken care of earlier. */
  assert(!(res & LSH_CHANNEL_FINISHED));
275

Niels Möller's avatar
Niels Möller committed
276 277
  /* Not implemented */
  assert(!(res & LSH_KILL_OTHERS));
278

Niels Möller's avatar
Niels Möller committed
279
  if (res & LSH_HOLD)
280
    {
Niels Möller's avatar
Niels Möller committed
281 282 283
      /* This flag should not be combined with anything else */
      assert(res == LSH_HOLD);
      fd->want_read = 0;
284
    }
Niels Möller's avatar
Niels Möller committed
285
  if (res & LSH_DIE)
Niels Möller's avatar
Niels Möller committed
286
    {
Niels Möller's avatar
Niels Möller committed
287 288
      if (self->buffer)
	write_buffer_close(self->buffer);
289 290 291

      close_fd(fd,
	       LSH_FAILUREP(res) ? CLOSE_PROTOCOL_FAILURE : 0);
292
    }
Niels Möller's avatar
Niels Möller committed
293
  else if (res & LSH_CLOSE)
294
    {
Niels Möller's avatar
Niels Möller committed
295 296 297 298 299 300 301 302 303
      if (self->buffer)
	{
	  write_buffer_close(self->buffer);
	  /* Don't attempt to read any further. */
	  /* FIXME: Is it safe to free the handler here? */
	  self->super.want_read = 0;
	  self->handler = NULL;
	}
      else
304
	kill_fd(fd);
Niels Möller's avatar
Niels Möller committed
305 306 307
		  
      fd->close_reason
	= LSH_FAILUREP(res) ? CLOSE_PROTOCOL_FAILURE : CLOSE_EOF;
308
    }
Niels Möller's avatar
Niels Möller committed
309
}
310

Niels Möller's avatar
Niels Möller committed
311 312
static void write_callback(struct lsh_fd *fd)
{
313
  CAST(io_fd, self, fd);
Niels Möller's avatar
Niels Möller committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  UINT32 size;
  int res;
  
  size = MIN(self->buffer->end - self->buffer->start,
	     self->buffer->block_size);
  assert(size);
  
  res = write(fd->fd,
	      self->buffer->buffer + self->buffer->start,
	      size);
  if (!res)
    fatal("Closed?");
  if (res < 0)
    switch(errno)
      {
      case EINTR:
      case EAGAIN:
	break;
      case EPIPE:
333 334
	debug("io.c: Broken pipe.\n");
	close_fd(fd, CLOSE_BROKEN_PIPE);
Niels Möller's avatar
Niels Möller committed
335 336 337 338
	break;
      default:
	werror("io.c: write failed, %s\n", strerror(errno));

339
	close_fd(fd, CLOSE_WRITE_FAILED);
Niels Möller's avatar
Niels Möller committed
340 341 342 343 344 345
	
	break;
      }
  else
    self->buffer->start += res;
}  
346

Niels Möller's avatar
Niels Möller committed
347 348
static void listen_callback(struct lsh_fd *fd)
{
349
  CAST(listen_fd, self, fd);
Niels Möller's avatar
Niels Möller committed
350 351 352 353
  struct sockaddr_in peer;
  size_t addr_len = sizeof(peer);
  int res;
  int conn;
354

Niels Möller's avatar
Niels Möller committed
355
  /* FIXME: Do something with the peer address? */
356

Niels Möller's avatar
Niels Möller committed
357 358 359
  conn = accept(fd->fd,
		(struct sockaddr *) &peer, &addr_len);
  if (conn < 0)
360
    {
Niels Möller's avatar
Niels Möller committed
361 362
      werror("io.c: accept() failed, %s", strerror(errno));
      return;
363
    }
Niels Möller's avatar
Niels Möller committed
364 365
  res = FD_CALLBACK(self->callback, conn);
  if (LSH_ACTIONP(res))
366
    {
367
      wwrite("Strange: Accepted a connection, "
Niels Möller's avatar
Niels Möller committed
368
	     "but failed before writing anything.\n");
369 370 371
      close_fd(fd, (LSH_FAILUREP(res)
		    ? CLOSE_PROTOCOL_FAILURE
		    : CLOSE_EOF));
372
    }
Niels Möller's avatar
Niels Möller committed
373
}
374

Niels Möller's avatar
Niels Möller committed
375 376
static void connect_callback(struct lsh_fd *fd)
{
377
  CAST(connect_fd, self, fd);
Niels Möller's avatar
Niels Möller committed
378 379 380
  int res;
  
  res = FD_CALLBACK(self->callback, fd->fd);
381

Niels Möller's avatar
Niels Möller committed
382
  if (LSH_ACTIONP(res))
383
    {
384
      wwrite("Strange: Connected, "
Niels Möller's avatar
Niels Möller committed
385
	     "but failed before writing anything.\n");
386 387
    }
  else
Niels Möller's avatar
Niels Möller committed
388 389 390
    {
      /* To avoid actually closing the fd */
      fd->fd = -1;
391
    }
392
  kill_fd(fd);
393 394
}

395
/* FIXME: Prehaps this function should return a suitable exit code? */
396 397
void io_run(struct io_backend *b)
{
Niels Möller's avatar
Niels Möller committed
398
  struct sigaction pipe;
399
  memset(&pipe, 0, sizeof(pipe));
Niels Möller's avatar
Niels Möller committed
400 401 402 403 404 405 406

  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");
407
  
408 409
  while(io_iter(b))
    ;
410 411
}

412 413
void init_backend(struct io_backend *b)
{
Niels Möller's avatar
Niels Möller committed
414 415 416 417
  b->files = NULL;
#if 0
  b->callouts = 0;
#endif
418 419
}

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
/* This function is called if a connection this file somehow dependent
 * 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);

  /* FIXME: It could make sense to you a separate close reason for
   * killed files. For now, using the zero reason will supress calling
   * of any close callbacks. */
  if (r->alive)
    close_fd(fd, 0);
}

Niels Möller's avatar
Niels Möller committed
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
/* Initializes a file structure, and adds it to the backend's list. */
static void init_file(struct io_backend *b, struct lsh_fd *f, int fd)
{
  /* assert(fd); */
  f->fd = fd;
  f->close_reason = -1; /* Invalid reason */
  f->close_callback = NULL;

  f->prepare = NULL;

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

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

452 453
  f->super.alive = 1;
  f->super.kill = do_kill_fd;
Niels Möller's avatar
Niels Möller committed
454 455 456 457 458
  f->really_close = NULL;

  f->next = b->files;
  b->files = f;
}
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483

/* Blocking read from a file descriptor (i.e. don't use the backend).
 * The fd should *not* be in non-blocking mode. */

int blocking_read(int fd, struct read_handler *handler)
{
  struct fd_read r =
  { { STACK_HEADER, do_read }, fd };

  while (1)
    {
      int res = READ_HANDLER(handler,
			     &r.super);

      assert(!(res & (LSH_HOLD | LSH_KILL_OTHERS)));

      if (res & (LSH_CLOSE | LSH_DIE))
	{
	  close(fd);
	  return res;
	}
      if (res & LSH_FAIL)
	werror("blocking_read: Ignoring error %d\n", res);
    }
}
484 485 486
/*
 * Fill in ADDR from HOST, SERVICE and PROTOCOL.
 * Supplying a null pointer for HOST means use INADDR_ANY.
487
 * Otherwise HOST is an numbers-and-dots ip-number or a dns name.
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
 *
 * 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 */
512
#if HAVE_INET_ATON
Niels Möller's avatar
Niels Möller committed
513
      if (!inet_aton(host, &addr->sin_addr))
514
#else /* !HAVE_INET_ATON */
515 516 517 518 519
	/* TODO: It is wrong to work with ((unsigned long int) -1)
	 * directly, as this breaks Linux/Alpha systems. But
	 * INADDR_NONE isn't portable. The clean solution is to use
	 * inet_aton rather than inet_addr; see the GNU libc
	 * documentation. */
520 521 522
# ifndef INADDR_NONE
# define INADDR_NONE ((unsigned long int) -1)
# endif /* !INADDR_NONE */
523
      addr->sin_addr.s_addr = inet_addr(host);
524
      if (addr->sin_addr.s_addr == INADDR_NONE)
525
#endif  /* !HAVE_INET_ATON */
526 527 528 529 530 531
	{
	  struct hostent * hp;
	  
	  hp = gethostbyname(host);
	  if (hp == NULL)
	    return 0;
532
	  memcpy(&addr->sin_addr, hp->h_addr, (size_t) (hp->h_length));
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
	  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;

557
	  serv = getservbyname(service, protocol);
558 559 560
	  if (serv == NULL)
	    return 0;
	  addr->sin_port = serv->s_port;
Niels Möller's avatar
Niels Möller committed
561 562
	}
    }
563 564

  return 1;
Niels Möller's avatar
Niels Möller committed
565 566
}

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
/* For fd:s in blocking mode. */
int write_raw(int fd, UINT32 length, UINT8 *data)
{
  while(length)
    {
      int written = write(fd, data, length);

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

int write_raw_with_poll(int fd, UINT32 length, 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 0;
	  }
      
      written = write(fd, data, length);

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

Niels Möller's avatar
Niels Möller committed
631 632 633 634 635 636
void io_set_nonblocking(int fd)
{
  if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
    fatal("io_set_nonblocking: fcntl() failed, %s", strerror(errno));
}

637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
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);
}

653 654 655 656 657
/* 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
658
{
659
  int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
Niels Möller's avatar
Niels Möller committed
660
  
661 662
  if (s<0)
    return NULL;
Niels Möller's avatar
Niels Möller committed
663

664 665
  debug("io.c: connecting using fd %d\n", s);
  
666
  io_init_fd(s);
Niels Möller's avatar
Niels Möller committed
667

668 669 670 671 672 673 674
  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
675

676 677 678 679 680 681 682 683 684
  if ( (connect(s, (struct sockaddr *)remote, sizeof *remote) < 0)
       && (errno != EINPROGRESS) )       
    {
      int saved_errno = errno;
      close(s);
      errno = saved_errno;
      return NULL;
    }

685 686 687 688
  {
    NEW(connect_fd, fd);

    init_file(b, &fd->super, s);
Niels Möller's avatar
Niels Möller committed
689

690 691 692 693 694 695
    fd->super.want_write = 1;
    fd->super.write = connect_callback;
    fd->callback = f;
    
    return fd;
  }
Niels Möller's avatar
Niels Möller committed
696 697
}

698 699 700 701 702
struct listen_fd *io_listen(struct io_backend *b,
			    struct sockaddr_in *local,
			    struct fd_callback *callback)
{
  int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
Niels Möller's avatar
Niels Möller committed
703
  
704 705 706
  if (s<0)
    return NULL;

707 708
  debug("io.c: listening on fd %d\n", s);
  
709
  io_init_fd(s);
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

  {
    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;
    }

728 729
  {
    NEW(listen_fd, fd);
730

731 732 733 734 735 736 737 738
    init_file(b, &fd->super, s);
    
    fd->super.want_read = 1;
    fd->super.read = listen_callback;
    fd->callback = callback;
    
    return fd;
  }
739 740
}

Niels Möller's avatar
Niels Möller committed
741 742
static void really_close(struct lsh_fd *fd)
{
743
  CAST(io_fd, self, fd);
Niels Möller's avatar
Niels Möller committed
744 745 746 747 748 749 750 751

  assert(self->buffer);

  write_buffer_close(self->buffer);
}

static void prepare_write(struct lsh_fd *fd)
{
752
  CAST(io_fd, self, fd);
Niels Möller's avatar
Niels Möller committed
753 754 755 756 757

  assert(self->buffer);

  if (! (fd->want_write = write_buffer_pre_write(self->buffer))
      && self->buffer->closed)
758
    close_fd(fd, CLOSE_EOF);
Niels Möller's avatar
Niels Möller committed
759 760
}
  
Niels Möller's avatar
Niels Möller committed
761 762
struct abstract_write *io_read_write(struct io_backend *b,
				     int fd,
Niels Möller's avatar
Niels Möller committed
763
				     struct read_handler *handler,
Niels Möller's avatar
Niels Möller committed
764
				     UINT32 block_size,
765
				     struct close_callback *close_callback)
766
{
767
  NEW(io_fd, f);
768
  struct write_buffer *buffer = write_buffer_alloc(block_size);
Niels Möller's avatar
Niels Möller committed
769

770 771
  debug("io.c: Preparing fd %d for reading and writing\n", fd);
  
772 773
  io_init_fd(fd);
  
Niels Möller's avatar
Niels Möller committed
774
  init_file(b, &f->super, fd);
775
  
776
  /* Reading */
Niels Möller's avatar
Niels Möller committed
777 778 779
  f->super.read = read_callback;
  f->super.want_read = !!handler;
  f->handler = handler;
780 781

  /* Writing */
Niels Möller's avatar
Niels Möller committed
782 783
  f->super.prepare = prepare_write;
  f->super.write = write_callback;
Niels Möller's avatar
Niels Möller committed
784
  f->buffer = buffer;
785

Niels Möller's avatar
Niels Möller committed
786 787 788
  /* Closing */
  f->super.really_close = really_close;
  f->super.close_callback = close_callback;
789

790
  return &buffer->super;
791
}
792 793 794

struct io_fd *io_read(struct io_backend *b,
		      int fd,
Niels Möller's avatar
Niels Möller committed
795
		      struct read_handler *handler,
796 797
		      struct close_callback *close_callback)
{
798
  NEW(io_fd, f);
799

800 801
  debug("io.c: Preparing fd %d for reading\n", fd);
  
802 803
  io_init_fd(fd);

Niels Möller's avatar
Niels Möller committed
804
  init_file(b, &f->super, fd);
805

Niels Möller's avatar
Niels Möller committed
806 807 808 809
  /* Reading */
  f->super.want_read = !!handler;
  f->super.read = read_callback;
  f->handler = handler;
810

Niels Möller's avatar
Niels Möller committed
811
  f->super.close_callback = close_callback;
812 813 814 815

  return f;
}

816 817 818 819
struct io_fd *io_write(struct io_backend *b,
		       int fd,
		       UINT32 block_size,
		       struct close_callback *close_callback)
820
{
821
  NEW(io_fd, f);
822 823
  struct write_buffer *buffer = write_buffer_alloc(block_size);

824 825
  debug("io.c: Preparing fd %d for writing\n", fd);
  
826 827
  io_init_fd(fd);
  
Niels Möller's avatar
Niels Möller committed
828
  init_file(b, &f->super, fd);
829 830

  /* Writing */
Niels Möller's avatar
Niels Möller committed
831 832
  f->super.prepare = prepare_write;
  f->super.write = write_callback;
833
  f->buffer = buffer;
Niels Möller's avatar
Niels Möller committed
834 835
  
  f->super.close_callback = close_callback;
836

837
  return f;
838
}
Niels Möller's avatar
Niels Möller committed
839

840 841 842 843
void kill_fd(struct lsh_fd *fd)
{
  fd->super.alive = 0;
}
Niels Möller's avatar
Niels Möller committed
844

845
void close_fd(struct lsh_fd *fd, int reason)
Niels Möller's avatar
Niels Möller committed
846
{
847
  debug("Marking fd %d for closing.\n", fd->fd);
848
  fd->close_reason = reason;
849
  kill_fd(fd);
Niels Möller's avatar
Niels Möller committed
850
}