File: socket.c

package info (click to toggle)
scheme48 1.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 14,980 kB
  • ctags: 14,127
  • sloc: lisp: 76,272; ansic: 71,514; sh: 3,026; makefile: 637
file content (941 lines) | stat: -rw-r--r-- 25,320 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
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
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
/* Copyright (c) 1993-2008 by Richard Kelsey and Jonathan Rees.
   See file COPYING. */

/*
 * An interface to Unix sockets.
 */

#define _XOPEN_SOURCE_EXTENDED 1		/* AIX wants this to be 1 */
#include "sysdep.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "c-mods.h"
#include "scheme48.h"
#include "unix.h"
#include "fd-io.h"		/* ps_close_fd() */
#include "event.h"		/* add_pending_fd() */

/* Henry Cejtin says that 5 is the largest safe number for this. */
#define	LISTEN_QUEUE_SIZE	5

extern void		s48_init_socket(void);
static s48_value	s48_socket(s48_value udp_p, s48_value input_p),
			s48_bind(s48_value socket_channel, s48_value number),
			s48_socket_number(s48_value socket_channel),
			s48_listen(s48_value socket_channel),
			s48_accept(s48_value socket_channel),
			s48_connect(s48_value socket_channel,
				    s48_value address,
				    s48_value port,
				    s48_value retry_p),
                        s48_dup_socket_channel(s48_value socket_fd),
			s48_close_socket_half(s48_value socket_channel,
					      s48_value input_p),
                        s48_get_host_by_name(s48_value machine),
                        s48_get_host_by_name_result(s48_value event_uid),
                        s48_get_host_by_address(s48_value address),
                        s48_get_host_by_address_result(s48_value event_uid),
			s48_get_host_name(void),
			s48_udp_send(s48_value channel,
				     s48_value udp_address,
				     s48_value buffer,
				     s48_value length),
			s48_udp_receive(s48_value channel, s48_value message),
			s48_lookup_udp_address(s48_value address, s48_value port);

/* Forward declaration. */
static s48_value dup_socket_channel(int socket_fd);

/*
 * Record type imported from Scheme.
 */

static s48_value	s48_udp_address_type_binding = S48_FALSE;

/*
 * An array of udp_addresess (and S48_FALSE's) acting as a hash table.
 * The initial size is small so that rehashing will be tested often.
 */

#define INITIAL_CONNECTIONS_SIZE	16

static s48_value	connections = S48_FALSE;
static long		connections_size = INITIAL_CONNECTIONS_SIZE; 
static long		connections_index_mask = INITIAL_CONNECTIONS_SIZE - 1;
static long		connection_count = 0;

/*
 * Install all exported functions in Scheme48.
 */

void
s48_init_socket(void)
{
  S48_EXPORT_FUNCTION(s48_socket);
  S48_EXPORT_FUNCTION(s48_bind);
  S48_EXPORT_FUNCTION(s48_socket_number);
  S48_EXPORT_FUNCTION(s48_listen);
  S48_EXPORT_FUNCTION(s48_accept);
  S48_EXPORT_FUNCTION(s48_connect);
  S48_EXPORT_FUNCTION(s48_dup_socket_channel);
  S48_EXPORT_FUNCTION(s48_close_socket_half);
  S48_EXPORT_FUNCTION(s48_get_host_by_name);
  S48_EXPORT_FUNCTION(s48_get_host_by_name_result);
  S48_EXPORT_FUNCTION(s48_get_host_by_address);
  S48_EXPORT_FUNCTION(s48_get_host_by_address_result);
  S48_EXPORT_FUNCTION(s48_get_host_name);
  
  S48_EXPORT_FUNCTION(s48_udp_send);
  S48_EXPORT_FUNCTION(s48_udp_receive);
  S48_EXPORT_FUNCTION(s48_lookup_udp_address);

  S48_GC_PROTECT_GLOBAL(s48_udp_address_type_binding);
  s48_udp_address_type_binding = s48_get_imported_binding("s48-udp-address-type");

  S48_GC_PROTECT_GLOBAL(connections);
  connections = s48_make_vector(INITIAL_CONNECTIONS_SIZE, S48_FALSE);
}

/*
 * Create an internet-domain stream (reliable, sequenced) socket.
 * We return an input channel on success and raise an exception on failure.
 * The socket has been made non-blocking.
 */

static s48_value
s48_socket(s48_value udp_p, s48_value input_p)
{
  int		fd,
    		mode,
    		status;
  s48_value	channel;
  int on = 1;

  RETRY_OR_RAISE_NEG(fd, socket(PF_INET,
				(udp_p == S48_FALSE) ?
				  SOCK_STREAM :
				  SOCK_DGRAM,
				0));
  RETRY_OR_RAISE_NEG(status, fcntl(fd, F_SETFL, O_NONBLOCK));

  /*
   * If we don't do this, we may get "Address already in use" if we
   * try to do anything on the same port too soon.
   * Alan Bawden says this is OK:
   * http://news.gmane.org/gmane.lisp.scheme.scheme48/cutoff=1672
   */
  RETRY_OR_RAISE_NEG(status,
		     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
				&on, sizeof(on)));

  mode = (input_p == S48_FALSE) ?
    S48_CHANNEL_STATUS_SPECIAL_OUTPUT :
    S48_CHANNEL_STATUS_SPECIAL_INPUT;

  channel = s48_add_channel(mode, s48_enter_string_latin_1("socket"), fd);

  if (!S48_CHANNEL_P(channel)) {
    ps_close_fd(fd);		/* retries if interrupted */
    s48_raise_scheme_exception(s48_extract_fixnum(channel), 0); };

  return channel;
}

/*
 * Given an internet-domain stream socket and a port number, bind
 * the socket to the port and prepare to receive connections.
 * If the port number is #f, then we bind the socket to any available
 * port.
 * 
 * Nothing useful is returned.
 */

static s48_value
s48_bind(s48_value channel, s48_value port_number)
{
  int			socket_fd,
			port,
    			status;
  struct sockaddr_in	address;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  if (port_number == S48_FALSE)
    port = 0;
  else
    port = s48_extract_fixnum(port_number);

  memset(&address, 0, sizeof(address));
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = htonl(INADDR_ANY);
  address.sin_port = htons(port);

  RETRY_OR_RAISE_NEG(status,
		     bind(socket_fd,
			  (struct sockaddr *)&address,
			  sizeof(address)));

  return S48_UNSPECIFIC;
}

/*
 * Return the port number associated with an internet stream socket.
 */

static s48_value
s48_socket_number(s48_value channel)
{
  int			socket_fd,
			status;
  socklen_t		len;
  struct sockaddr_in	address;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  address.sin_addr.s_addr = htonl(INADDR_ANY);

  len = sizeof(address);

  RETRY_NEG(status, getsockname(socket_fd, (struct sockaddr *)&address, &len));

  if ((status < 0) || (address.sin_family != AF_INET))
    s48_raise_os_error(errno);

  return s48_enter_fixnum(ntohs(address.sin_port));
}

static s48_value
s48_listen(s48_value channel)
{
  int			socket_fd;
  int			status;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  RETRY_OR_RAISE_NEG(status, listen(socket_fd, LISTEN_QUEUE_SIZE));

  return S48_UNSPECIFIC;
}


/*
 * Given an internet-domain stream socket which has been bound
 * accept a connection and return the resulting socket as a pair of channels
 * (after marking it non-blocking).
 *
 * If the accept fails because the client hasn't connected yet, then we
 * return #f.
 *
 * If it fails for any other reason, then an exception is raised.
 */

static s48_value
s48_accept(s48_value channel)
{
  int			socket_fd,
   			connect_fd,
			status;
  socklen_t		len;
  struct sockaddr_in	address;
  s48_value		input_channel,
			output_channel;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  len = sizeof(address);
  
  connect_fd = accept(socket_fd, (struct sockaddr *)&address, &len);
  
  /*
   * Check for a connection.  If we have one we create two channels, one
   * input and one, with a dup()'ed fd, output.  Lots of error checking
   * makes this messy.
   */

  if (connect_fd >= 0) {
    
    S48_DECLARE_GC_PROTECT(1);
  
    RETRY_OR_RAISE_NEG(status, fcntl(connect_fd, F_SETFL, O_NONBLOCK));

    input_channel = s48_add_channel(S48_CHANNEL_STATUS_INPUT,
				    s48_enter_string_latin_1("socket connection"),
				    connect_fd);

    if (!S48_CHANNEL_P(input_channel)) {
      ps_close_fd(connect_fd);		/* retries if interrupted */
      s48_raise_scheme_exception(s48_extract_fixnum(input_channel), 0); };
    
    return input_channel;
  }

  /*
   * Check for errors.  If we need to retry we mark the socket as pending
   * and return #F to tell the Scheme procedure to wait.
   */

  if ((errno != EWOULDBLOCK) && (errno != EINTR) && (errno != EAGAIN))
    s48_raise_os_error(errno);

  if (! s48_add_pending_fd(socket_fd, PSTRUE))
    s48_raise_out_of_memory_error();

  return S48_FALSE;
}

static s48_value
call_gethostbyaddr(s48_value sch_addr)
{
  char *addr = s48_extract_byte_vector(sch_addr);
  char		*hostname;
  struct hostent *hostdata;
  
  hostdata = gethostbyaddr(addr,
			   sizeof(struct in_addr),
			   AF_INET);
  if (hostdata == NULL)
    hostname = inet_ntoa(*((struct in_addr *) addr));
  else
    hostname = hostdata->h_name;
  
  return s48_enter_string_latin_1(hostname);
}

#ifdef HAVE_PTHREAD_H
#define S48_MAX_HOST_NAME_LENGTH 1024

struct gethostbyname_handshake
{
  long event_uid;
  char host_name[S48_MAX_HOST_NAME_LENGTH + 1]; /* is enough */
  int errno_val;
  int host_length;
  char* host_addr;
};

/*
 * Only one call can be active at any given time:
 * We expect mutual exclusion at the Scheme end
 */

static void
gethostbyname_thread(void *void_handshake)
{
  struct gethostbyname_handshake *handshake = void_handshake;
  static struct hostent *host; /* will be thread-local */

  host = gethostbyname(handshake->host_name);
  if (host == NULL)
    handshake->errno_val = h_errno;
  else
    {
      handshake->host_length = host->h_length;
      handshake->host_addr = malloc(handshake->host_length);
      if (handshake->host_addr == NULL)
	handshake->errno_val = ENOMEM;
      else
	handshake->errno_val = 0;
      
      memcpy(handshake->host_addr, host->h_addr, handshake->host_length);
    }
  s48_note_external_event((long) handshake->event_uid);
}

static s48_value
s48_get_host_by_name(s48_value machine)
{
  pthread_t t;
  struct gethostbyname_handshake* handshake;

  int machine_length = S48_BYTE_VECTOR_LENGTH(machine);
  if (machine_length > S48_MAX_HOST_NAME_LENGTH)
    s48_raise_argument_type_error(machine);

  handshake = malloc(sizeof(struct gethostbyname_handshake));
  if (handshake == NULL)
    s48_raise_out_of_memory_error();

  memcpy(handshake->host_name, s48_extract_byte_vector(machine), machine_length);
  handshake->host_name[machine_length] = '\0';
  
  handshake->event_uid = s48_external_event_uid();
  if (pthread_create(&t, NULL, gethostbyname_thread, (void*) handshake))
    {
      static struct hostent *host;
      s48_unregister_external_event_uid(handshake->event_uid);
      host = gethostbyname(handshake->host_name);
      free(handshake);
      if (host == NULL)
	s48_raise_os_error(h_errno);
      return s48_enter_byte_vector(host->h_addr, host->h_length);
    }
  else
    {
      s48_value sch_event_uid = S48_UNSPECIFIC;
      s48_value sch_handshake = S48_UNSPECIFIC;
      s48_value sch_result;
      S48_DECLARE_GC_PROTECT(2);

      pthread_detach(t);

      S48_GC_PROTECT_2(sch_event_uid, sch_handshake);
      sch_event_uid = s48_enter_integer(handshake->event_uid);
      sch_handshake = s48_enter_pointer(handshake);

      sch_result = s48_cons(sch_event_uid, sch_handshake);
      S48_GC_UNPROTECT();
      return sch_result;
    }
}

static s48_value
s48_get_host_by_name_result(s48_value sch_handshake)
{
  struct gethostbyname_handshake* handshake
    = s48_extract_pointer(sch_handshake);

  s48_unregister_external_event_uid(handshake->event_uid);

  if (handshake->errno_val)
    {
      int errno_val = handshake->errno_val;
      free(handshake);
      s48_raise_os_error(errno_val);
    }
  else
    {
      s48_value sch_result
	= s48_enter_byte_vector(handshake->host_addr, handshake->host_length);
      free(handshake->host_addr);
      free(handshake);
      return sch_result;
    }
}

/*
 * Get the name of the `sch_addr''s host.  If we can't get the real
 * host name we use the numbers-and-dots representation of the
 * address.
 */

struct gethostbyaddr_handshake
{
  long event_uid;
  struct in_addr address;
  char host_name[S48_MAX_HOST_NAME_LENGTH + 1];
};

static void
gethostbyaddr_thread(void *void_handshake)
{
  struct gethostbyaddr_handshake *handshake = void_handshake;
  struct in_addr addr;
  struct hostent *hostdata;
  
  hostdata = gethostbyaddr(&(handshake->address),
			   sizeof(struct in_addr),
			   AF_INET);
  if (hostdata == NULL)
    strcpy(handshake->host_name,
	   inet_ntoa(*((struct in_addr *) &(handshake->address))));
  else
    strcpy(handshake->host_name, hostdata->h_name);

  s48_note_external_event((long) handshake->event_uid);
}
 
static s48_value
s48_get_host_by_address(s48_value sch_addr)
{
  pthread_t t;
  struct gethostbyaddr_handshake* handshake;
  
  handshake = malloc(sizeof(struct gethostbyaddr_handshake));
  if (handshake == NULL)
    s48_raise_out_of_memory_error();

  memcpy(&(handshake->address),
	 (char *) s48_extract_byte_vector(sch_addr), sizeof(struct in_addr));

  handshake->event_uid = s48_external_event_uid();
  if (pthread_create(&t, NULL, gethostbyaddr_thread, (void*) handshake))
    {
      s48_unregister_external_event_uid(handshake->event_uid);
      free(handshake);
      return call_gethostbyaddr(sch_addr);
    }
  else
    {
      s48_value sch_event_uid = S48_UNSPECIFIC;
      s48_value sch_handshake = S48_UNSPECIFIC;
      s48_value sch_result;
      S48_DECLARE_GC_PROTECT(2);

      pthread_detach(t);

      S48_GC_PROTECT_2(sch_event_uid, sch_handshake);
      sch_event_uid = s48_enter_integer(handshake->event_uid);
      sch_handshake = s48_enter_pointer(handshake);

      sch_result = s48_cons(sch_event_uid, sch_handshake);
      S48_GC_UNPROTECT();
      return sch_result;
    }
}
	 
static s48_value 
s48_get_host_by_address_result(s48_value sch_handshake)
{
  struct gethostbyaddr_handshake* handshake
    = s48_extract_pointer(sch_handshake);
  s48_value sch_result;

  s48_unregister_external_event_uid(handshake->event_uid);
  sch_result = s48_enter_string_latin_1(handshake->host_name);
  free(handshake);
  return sch_result;
}
#else
static s48_value
s48_get_host_by_name(s48_value machine)
{
  struct hostent *host;
  char* machine_name = s48_extract_byte_vector(machine);
  RETRY_NULL(host, gethostbyname(machine_name));
  if (host == NULL)
    s48_raise_os_error(h_errno);
  return s48_enter_byte_vector(host->host_addr, host->host_length);
}

static s48_value
s48_get_host_by_name_result(void)
{
  /* won't be used here */
}

/*
 * Get the name of the `sch_addr''s host.  If we can't get the real
 * host name we use the numbers-and-dots representation of the
 * address.
 */
 
static s48_value
s48_get_host_by_address(s48_value sch_addr)
{
  return call_gethostbyaddr(sch_addr);
}

static s48_value
s48_get_host_by_address_result(void)
{
  /* won't be used here */
}
#endif


/*
 * Given an internet-domain stream socket, a machine name and a port number,
 * connect the socket to that machine/port.
 *
 * If this succeeds, it returns an output channel for the connection.
 * If it fails because the connect would block, add the socket to the
 * pending queue (for output) and return #f.
 * If it fails for any other reason, raise an exception.
 */

static s48_value
s48_connect(s48_value channel,
	    s48_value sch_address,
	    s48_value port,
	    s48_value retry_p)
{
  int			socket_fd,
    			port_number;
  struct sockaddr_in	address;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  S48_CHECK_FIXNUM(port);
  port_number = S48_UNSAFE_EXTRACT_FIXNUM(port);
  
  /*
   * Initialize `address'.
   */

  memset((void *)&address, 0, sizeof(address));
  address.sin_family = AF_INET;

  if (S48_BYTE_VECTOR_LENGTH(sch_address) > sizeof(address.sin_addr))
    s48_raise_range_error(s48_enter_fixnum(S48_BYTE_VECTOR_LENGTH(sch_address)),
			  S48_UNSAFE_ENTER_FIXNUM(0),
			  s48_enter_fixnum(sizeof(address.sin_addr)));
  memcpy((void *)&address.sin_addr,
	 (void *)s48_extract_byte_vector(sch_address),
	 S48_BYTE_VECTOR_LENGTH(sch_address));
  address.sin_port = htons(port_number);

  /*
   * Try the connection.  If it works we make an output channel and return it.
   * The original socket channel will be used as the input channel.
   *
   * FreeBSD's connect() behaves oddly.  If you get told to wait, wait for
   * select() to signal the all-clear, and then try to connect again, you
   * get an `already connected' (EISCONN) error.  To handle this we pass in
   * a retry_p flag.  If retry_p is  true the `already connected' error is
   * ignored.
   */

  if (connect(socket_fd, (struct sockaddr *)&address, sizeof(address)) >= 0
      || ((errno == EISCONN) && (retry_p == S48_TRUE))) {
    S48_STOB_SET(channel, S48_CHANNEL_STATUS_OFFSET, S48_CHANNEL_STATUS_INPUT);
    
    return dup_socket_channel(socket_fd); }
    
  /*
   * Check for errors.  If we need to retry we mark the socket as pending
   * and return #F to tell the Scheme procedure to wait.
   */

  /* already connected, will raise an error from Scheme */
  if (errno == EISCONN)
    return S48_TRUE;

  if (errno != EWOULDBLOCK && errno != EINTR && errno != EALREADY
      && errno != EINPROGRESS && errno != EAGAIN)
    s48_raise_os_error(errno);

  if (! (s48_add_pending_fd(socket_fd, PSFALSE)))
    s48_raise_out_of_memory_error();

  return S48_FALSE;
}

/*
 * dup() `socket_fd' and return an output channel holding the result.
 *
 * We have to versions, one for calling from C and one for calling from Scheme.
 */

static s48_value
s48_dup_socket_channel(s48_value channel)
{
  int			socket_fd;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));
  
  return dup_socket_channel(socket_fd);
}

static s48_value
dup_socket_channel(int socket_fd)
{
  int 			output_fd;
  s48_value		output_channel;

  RETRY_OR_RAISE_NEG(output_fd, dup(socket_fd));

  output_channel = s48_add_channel(S48_CHANNEL_STATUS_OUTPUT,
				   s48_enter_string_latin_1("socket connection"),
				   output_fd);
  
  if (!S48_CHANNEL_P(output_channel)) {
    ps_close_fd(output_fd);		/* retries if interrupted */
    s48_raise_scheme_exception(s48_extract_fixnum(output_channel), 0); };
  
  return output_channel;
}

/*
 * Close half of a socket; if `input_p' is true we close the input half,
 * otherwise the output half.  This horribleness is forced upon us by
 * Unix's use of bidirectional file descriptors.
 */

static s48_value
s48_close_socket_half(s48_value channel, s48_value input_p)
{
  int	socket_fd,
    	status;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  /* We ignore `endpoint is not connected' errors, as we just want to get
     the file descriptor closed. */
  RETRY_NEG(status, shutdown(socket_fd, S48_EXTRACT_BOOLEAN(input_p) ? 0 : 1));
  if ((0 > status) && (errno != ENOTCONN))
    s48_raise_os_error(errno);
  
  return S48_TRUE;
}  

/*
 * Get the name of the local machine.
 */

static s48_value
s48_get_host_name(void)
{
  char	mbuff[MAXHOSTNAMELEN];
  int	status;

  RETRY_OR_RAISE_NEG(status, gethostname(mbuff, sizeof(mbuff)));

  return s48_enter_string_latin_1(mbuff);
}

/*
 * UDP sockets.
 */

/*
 * A udp_address is a Scheme record with the following fields:
 *   address		; an in_addr inside a Scheme byte vector
 *   port		; the port as a fixnum
 *   name		; printable version of the name as a Scheme string
 *   + possibly others that we don't care about
 */

#define UDP_ADDRESS_PTR(udp)						\
(S48_UNSAFE_EXTRACT_VALUE_POINTER(S48_UNSAFE_RECORD_REF((udp), 0),	\
			          struct in_addr))

#define UDP_PORT(udp)							\
(S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_RECORD_REF((udp), 1)))

/*
 * Forward declaration of internal procedures.
 */

static void		connection_init();
static s48_value	address_connection(struct sockaddr_in *addr);
static s48_value	lookup_connection(struct in_addr address,
					  unsigned long port);
static s48_value	address_hash(struct in_addr address,
				     unsigned long port);
static s48_value	add_new_connection(int index,
					   struct in_addr address,
					   unsigned long port);
static void		expand_and_rehash();
static s48_value	get_hostname(struct in_addr addr);

/*
 * Receive a message.  Returns pair (<byte-count> . <sender>).
 */

static s48_value
s48_udp_receive(s48_value channel, s48_value buffer)
{
  int			socket_fd;
  struct sockaddr_in	from;
  socklen_t		from_len = sizeof(struct sockaddr_in);
  int			count;

  S48_CHECK_CHANNEL(channel);
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  S48_CHECK_VALUE(buffer);
  
  count = recvfrom(socket_fd,
		   S48_UNSAFE_EXTRACT_VALUE_POINTER(buffer, void *),
		   S48_UNSAFE_BYTE_VECTOR_LENGTH(buffer),
		   0,
		   (struct sockaddr*)&from,
		   &from_len);
  
  if (0 <= count)
    return s48_cons(S48_UNSAFE_ENTER_FIXNUM(count),
		    address_connection(&from));
		    
  /*
   * Check for errors.  If we need to retry we mark the socket as pending
   * and return #F to tell the Scheme procedure to wait.
   */
  
  if (errno != EWOULDBLOCK && errno != EINTR && errno != EALREADY
      && errno != EINPROGRESS && errno != EAGAIN)
    s48_raise_os_error(errno);

  if (! (s48_add_pending_fd(socket_fd, PSTRUE)))
    s48_raise_out_of_memory_error();

  return S48_FALSE;
}

static s48_value
s48_udp_send(s48_value channel,
		s48_value address,
		s48_value buffer,
		s48_value count)
{
  int socket_fd;
  int sent;
  struct sockaddr_in	to;
  
  S48_CHECK_CHANNEL(channel);
  s48_check_record_type(address, s48_udp_address_type_binding);
  S48_CHECK_VALUE(buffer);
  S48_CHECK_FIXNUM(count);
  
  socket_fd = S48_UNSAFE_EXTRACT_FIXNUM(S48_UNSAFE_CHANNEL_OS_INDEX(channel));

  memset(&to, 0, sizeof(to));
  to.sin_family = AF_INET;
  to.sin_addr = *(UDP_ADDRESS_PTR(address));
  to.sin_port = htons(UDP_PORT(address));

  sent = sendto(socket_fd,
		S48_UNSAFE_EXTRACT_VALUE_POINTER(buffer, void *),
		S48_UNSAFE_EXTRACT_FIXNUM(count),
		0,
		(struct sockaddr *)&to,
		sizeof(struct sockaddr_in));
  
  if (0 <= sent)
    return S48_UNSAFE_ENTER_FIXNUM(sent);

  /*
   * Check for errors.  If we need to retry we mark the socket as pending
   * and return #F to tell the Scheme procedure to wait.
   */
  
  if (errno != EWOULDBLOCK && errno != EINTR && errno != EALREADY
      && errno != EINPROGRESS && errno != EAGAIN)
    s48_raise_os_error(errno);

  if (! (s48_add_pending_fd(socket_fd, PSFALSE)))
    s48_raise_out_of_memory_error();

  return S48_FALSE;
}

/*
 * We keep a hash table of the sockets we have corresponded with.
 *
 * Get the connection struct for `addr', creating a new one if necessary.
 * We hash the address and port to get an initial index into the `connections'
 * array and then search linearly from there.
 */

static s48_value
address_connection(struct sockaddr_in *addr)
{
  return lookup_connection(addr->sin_addr, ntohs(addr->sin_port));
}

static s48_value
s48_lookup_udp_address(s48_value address, s48_value port)
{
  return lookup_connection(*((struct in_addr *) s48_extract_byte_vector(address)),
			   s48_extract_fixnum(port));
}

/*
 * `port' should be in host byte order.
 */

static s48_value
lookup_connection(struct in_addr address, unsigned long port)
{
  unsigned long hash = address_hash(address, port);
  int		i = hash & connections_index_mask;

  while (1) {
    s48_value	search = S48_UNSAFE_VECTOR_REF(connections, i);
    if (search == S48_FALSE)
      return add_new_connection(i, address, port);
    else if ((address.s_addr == UDP_ADDRESS_PTR(search)->s_addr)
	      && port == UDP_PORT(search))
      return search;
    else
      i = (i + 1) & connections_index_mask; }
}

static s48_value
address_hash(struct in_addr address, unsigned long port)
{
  unsigned long hash = port ^ address.s_addr;

  return (hash >> 16) * (hash & 0xFFFF);
}

/*
 * Add a new connection record for `addr', putting it at `index' in the
 * connections' hash table. 
 */

static s48_value
add_new_connection(int index, struct in_addr address, unsigned long port)
{
  s48_value	udp_address;
  s48_value	sch_address;
  s48_value	name;

  S48_DECLARE_GC_PROTECT(1);

  udp_address = s48_make_record(s48_udp_address_type_binding);

  S48_GC_PROTECT_1(udp_address);

  sch_address
    = s48_enter_byte_vector((char*) (&address), sizeof(struct in_addr)); /* may GC */
  
  S48_UNSAFE_RECORD_SET(udp_address, 0, sch_address);
  S48_UNSAFE_RECORD_SET(udp_address, 1, S48_UNSAFE_ENTER_FIXNUM(port));
  
  S48_UNSAFE_RECORD_SET(udp_address, 2, S48_FALSE);

  S48_UNSAFE_VECTOR_SET(connections, index, udp_address);
  connection_count += 1;
  if (connection_count * 3 > connections_size)
    expand_and_rehash();				/* may GC */

  S48_GC_UNPROTECT();
  
  return udp_address;
}

/*
 * Double the size of the hash table and rehash all connections into it.
 */
    
static void
expand_and_rehash()
{
  s48_value	new_connections;
  long		new_size = connections_size * 2;
  long		new_index_mask = new_size - 1;
  long		i;

  new_connections = s48_make_vector(new_size, S48_FALSE);

  for(i = 0; i < connections_size; i++) {
    s48_value next = S48_UNSAFE_VECTOR_REF(connections, i);
    if (next != S48_FALSE) {
      i = address_hash(*UDP_ADDRESS_PTR(next), UDP_PORT(next))
	  & new_index_mask;
      for (; S48_UNSAFE_VECTOR_REF(new_connections, i) != S48_FALSE;
	   i = (i + 1) & new_index_mask);
      S48_UNSAFE_VECTOR_SET(new_connections, i, next); }}

  connections = new_connections;
  connections_size = new_size;
  connections_index_mask = new_index_mask;
}