File: sysdep.c

package info (click to toggle)
mah-jong 1.8-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 2,384 kB
  • ctags: 2,186
  • sloc: ansic: 26,312; perl: 393; makefile: 272; sh: 122
file content (904 lines) | stat: -rw-r--r-- 23,845 bytes parent folder | download
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
/* $Header: /home/jcb/newmj/RCS/sysdep.c,v 11.32 2006/01/24 22:06:59 jcb Exp $
 * sysdep.c
 * By intention, this file contains all functions that might need
 * fiddling with to cope with different variants of Unix.
 * In particular, all the networking code is in here.
 * Some parts of the other code assume POSIXish functions for file
 * descriptors and the like; this file is responsible for providing them
 * if they're not native. All such cases that occurred to me as I was
 * writing them can be found by searching for sysdep.c in the other
 * files.
 */
/****************** COPYRIGHT STATEMENT **********************
 * This file is Copyright (c) 2000 by J. C. Bradfield.       *
 * Distribution and use is governed by the LICENCE file that *
 * accompanies this file.                                    *
 * The moral rights of the author are asserted.              *
 *                                                           *
 ***************** DISCLAIMER OF WARRANTY ********************
 * This code is not warranted fit for any purpose. See the   *
 * LICENCE file for further information.                     *
 *                                                           *
 *************************************************************/

static const char rcs_id[] = "$Header: /home/jcb/newmj/RCS/sysdep.c,v 11.32 2006/01/24 22:06:59 jcb Exp $";

#include "sysdep.h"
#include <string.h>
#include <fcntl.h>
#include <errno.h>

#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
/* needed for HP-UX 11 with _XOPEN_SOURCE_EXTENDED */
#include <arpa/inet.h>
#include <sys/un.h>
/* this is modern, I think. */
#include <netdb.h>
#include <pwd.h>
#endif /* not WIN32 */

#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <signal.h>

#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif

/* warn: = fprintf(stderr,...), with automatic new line */
/* log_msg is a generalized version with a syslog like warning
   level. */


int (*log_msg_hook)(LogLevel l,char *);

char *(*log_msg_add_note_hook)(LogLevel l);

static char *log_prefixes[] = { "" , "-I- ", "+W+ ", "*E* " };

/* internal function */
static int vlog_msg(LogLevel l, char *format,va_list args) {
  char buf[1024];
  char *note = NULL;
  int ret;
  int n;

  if ( l > LogError ) l = LogError;
  strcpy(buf,log_prefixes[l]);
  n = strlen(log_prefixes[l]);
  /* reserve 1 char for extra '\n' */
  ret = vsnprintf(buf+n,sizeof(buf)-n-1,format,args);
  buf[1023] = 0;
  n = strlen(buf);
  /* do quick check for terminators */
#ifdef WIN32
  if ( buf[n-2] == '\r' ) {
    /* OK */
    ;
  } else if ( buf[n-1] == '\n' ) {
    /* already have unix terminator */
    buf[n-1] = '\r' ; buf[n] = '\n' ; buf[n+1] = 0 ;
  } else {
    /* no terminator */
    strcat(buf,"\r\n");
  }
#else
  if ( buf[n-1] != '\n' ) strcat(buf,"\n");
#endif
  /* add program supplied note? */
  n = 0;
  if ( log_msg_add_note_hook ) {
    note = (*log_msg_add_note_hook)(l);
    if ( note ) n = strlen(note);
  }
  {
    char nbuf[1024+n+1];
    strcpy(nbuf,buf);
    if ( n > 0 ) { strcat(nbuf,note); }
    /* call the hook */
    if ( log_msg_hook == NULL || log_msg_hook(l,nbuf) == 0 ) {
      fprintf(stderr,"%s",nbuf);
    }
  }
  return ret;
}

int log_msg(LogLevel l,char *format,...) {
  va_list args;
  va_start(args,format);
  return vlog_msg(l,format,args);
}

int log_error(const char *function, const char *file, const int line, const char *format,...) {
  char nformat[1024];
  va_list args;
  sprintf(nformat,"Error occurred in %s(), at %s:%d\n",function,file,line);
  strmcat(nformat,format,1023-(strlen(nformat)+strlen(format)));
  va_start(args,format);
  return vlog_msg(LogError,nformat,args);
}

int warn(char *format,...) {
  va_list args;
  va_start(args,format);
  return vlog_msg(LogWarning,format,args);
}

int info(char *format,...) {
  va_list args;
  va_start(args,format);
  return vlog_msg(LogInfo,format,args);
}

/* ignore the SIGPIPE signal. Return 0 on success, -1 on error */
int ignore_sigpipe(void) {
#ifdef WIN32
  return 0;
#else
  /* this is just posix at present */
  struct sigaction act;

  act.sa_handler = SIG_IGN;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  return sigaction(SIGPIPE,&act,NULL);
#endif /* WIN32 */
}

/* functions to be applied by the socket routines */
static void *(*skt_open_transform)(SOCKET) = NULL;
static int (*skt_closer)(void *) = NULL;
static int (*skt_reader)(void *, void *, size_t) = NULL;
static int (*skt_writer)(void *, const void *,size_t) = NULL;
static int sockets_initialized = 0;

#ifdef WIN32
static void shutdown_sockets(void) {
  WSACleanup();
  /* I don't care what it returns */
}
#endif /* WIN32 */

/* initialize sockets */
int initialize_sockets(void *(*open_transform)(SOCKET),
		       int (*closer)(void *),
		       int (*reader)(void *, void *, size_t),
		       int (*writer)(void *, const void *,size_t)) {
  skt_open_transform = open_transform;
  skt_closer = closer;
  skt_reader = reader;
  skt_writer = writer;
#ifdef WIN32

  if ( ! sockets_initialized ) {
    WORD version;
    WSADATA data;
    int err;
    
    version = MAKEWORD( 2, 2 );
    
    err = WSAStartup( version, &data );
    if (err != 0) {
      return 0;
    }
    if ((LOBYTE( data.wVersion ) != 2) || (HIBYTE( data.wVersion ) != 2)) {
      WSACleanup();
      return 0;
    }
    if ( atexit(shutdown_sockets) != 0 ) {
      warn("couldn't register socket shutdown routine");
    }
  }
#endif /* WIN32 */

  sockets_initialized = 1;
  return 1;
}

/* this function takes a string and parses it as an address.
   It returns 0 for an Internet address, 1 for a Unix address.
   For Internet addresses, the host name and port are placed
   in the given variables (the string had better be long enough);
   for Unix, the file name is copied to the given variable.
*/
static int parse_address(const char *address,
			 char *ret_host,
			 unsigned short *ret_port,
			 char *ret_file, size_t n) {
  if ( strchr(address,':') ) {
    /* grrr */
    if ( address[0] == ':' ) {
      strcpy(ret_host,"localhost");
      sscanf(address,":%hu",ret_port);
    } else {
      sscanf(address,"%[^:]:%hu",ret_host,ret_port);
    }
    return 0;
  } else {
    if ( ret_file) strmcpy(ret_file,address,n);
    return 1;
  }
}

/* set_up_listening_socket:
   Set up a socket listening on the given address.
   Return its fd.
*/
SOCKET set_up_listening_socket(const char *address) {
  SOCKET sfd;
  struct protoent *prstruc = NULL;
  struct sockaddr_in inaddr;
#ifndef WIN32
  struct sockaddr_un unaddr;
#endif
  int unixsockets;
  unsigned short port;
  char name[256];
  int sockopt;

  if ( ! sockets_initialized ) initialize_sockets(NULL,NULL,NULL,NULL);

  unixsockets = 
#ifdef WIN32
    parse_address(address,name,&port,NULL,0);
#else
    parse_address(address,name,&port,unaddr.sun_path,sizeof(unaddr.sun_path));
#endif /* WIN32 */

#ifdef WIN32
  if ( unixsockets ) {
    warn("unix sockets not available on Windows");
    return INVALID_SOCKET;
  }
#endif /* WINDOWS */

  if ( !unixsockets ) {
    prstruc = getprotobyname("tcp");
    if ( prstruc == NULL ) {
      perror("getprotobyname failed");
      return INVALID_SOCKET;
    }
  }
  sfd = socket(unixsockets ? AF_UNIX : AF_INET,
	       SOCK_STREAM,
	       unixsockets ? 0 : prstruc->p_proto);
  if ( sfd == INVALID_SOCKET ) {
    perror("socket failed");
    return INVALID_SOCKET;
  }

  sockopt=1;
  setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,(void *)&sockopt,sizeof(int));

#ifndef WIN32
  if ( unixsockets ) {
    unaddr.sun_family = AF_UNIX;
    unlink(unaddr.sun_path); /* need to check success FIXME */
    if ( bind(sfd,(struct sockaddr *)&unaddr,sizeof(struct sockaddr_un)) < 0 ) {
      perror("bind failed");
      return INVALID_SOCKET;
    }
  } else {
#else
  if ( 1 ) {
#endif /* WIN32 */
    inaddr.sin_family = AF_INET;
    inaddr.sin_port = htons(port);
    inaddr.sin_addr.s_addr = INADDR_ANY;
    if ( bind(sfd,(struct sockaddr *)&inaddr,sizeof(struct sockaddr_in)) < 0 ) {
      perror("bind failed");
      return INVALID_SOCKET;
    }
  }

  if ( listen(sfd,5) < 0 ) {
    perror("listen failed");
    return INVALID_SOCKET;
  }
  
  if ( skt_open_transform ) {
    return (SOCKET) skt_open_transform(sfd);
  } else {
    return sfd;
  }
}
  
  

/* accept_new_connection:
   A connection has arrived on the socket fd.
   Accept the connection, and return the new fd,
   or INVALID_SOCKET on error.
*/

SOCKET accept_new_connection(SOCKET fd) {
  SOCKET newfd;
  struct sockaddr saddr;
  struct linger l = { 1, 1000 } ; /* linger on close for 10 seconds */
  socklen_t saddrlen = sizeof(saddr);

  if ( ! sockets_initialized ) initialize_sockets(NULL,NULL,NULL,NULL);

  newfd = accept(fd,&saddr,&saddrlen);
  if ( newfd == INVALID_SOCKET ) { perror("accept failed"); }
  /* we should make sure that data is sent when this socket is closed */
  if ( setsockopt(newfd,SOL_SOCKET,SO_LINGER,(void *)&l,sizeof(l)) < 0 ) {
    warn("setsockopt failed");
  }
  if ( skt_open_transform ) {
    return (SOCKET) skt_open_transform(newfd);
  } else {
    return newfd;
  }
}

/* connect_to_host:
   Establish a connection to the given address.
   Return the file descriptor or INVALID_SOCKET on error.
   If unixsockets, only the port number is used in making the name
   The returned socket is marked close-on-exec .
*/

static SOCKET _connect_to_host(int plain, const char *address) {
  SOCKET fd;
  struct sockaddr_in inaddr;
#ifndef WIN32
  struct sockaddr_un unaddr;
#endif
  char name[512];
  int unixsockets;
  unsigned short port;
  struct hostent *hent = NULL;
  struct protoent *prstruc = NULL;

  if ( ! sockets_initialized ) initialize_sockets(NULL,NULL,NULL,NULL);

#ifdef WIN32
  unixsockets = parse_address(address,name,&port,NULL,0);
  if ( unixsockets ) {
    warn("Unix sockets not supported on Windows");
    return INVALID_SOCKET;
  }
#else
  unixsockets = parse_address(address,name,&port,unaddr.sun_path,sizeof(unaddr.sun_path));
#endif /* WIN32 */

  if ( !unixsockets ) {
    hent = gethostbyname(name);
    
    if ( ! hent ) {
      perror("connect_to_host: gethostbyname failed");
      return INVALID_SOCKET;
    }
    
    prstruc = getprotobyname("tcp");
    if ( prstruc == NULL ) {
      perror("connect_to_host: getprotobyname failed");
      return INVALID_SOCKET;
    }
  }

  fd = socket(unixsockets ? AF_UNIX : AF_INET,
	      SOCK_STREAM,
	      unixsockets ? 0 : prstruc->p_proto);
  if ( fd == INVALID_SOCKET ) {
    perror("connect_to_host: socket failed");
    return INVALID_SOCKET;
  }

#ifndef WIN32
  if ( unixsockets ) {
    unaddr.sun_family = AF_UNIX;
    if ( connect(fd,(struct sockaddr *)&unaddr,sizeof(struct sockaddr_un)) < 0 ) {
      perror("connect_to_host: connect failed");
      return INVALID_SOCKET;
    }
  } else {
#else
  if ( 1 ) {
#endif /* WIN32 */
    inaddr.sin_family = AF_INET;
    inaddr.sin_port = htons(port);
    inaddr.sin_addr = *((struct in_addr *)hent->h_addr);
    if ( connect(fd,(struct sockaddr *)&inaddr,sizeof(struct sockaddr_in)) < 0 ) {
      perror("connect_to_host: connect failed");
      return INVALID_SOCKET;
    }
  }
  
#ifndef WIN32
  /* mark close on exec */
  fcntl(fd,F_SETFD,1);
#endif /* WIN32 */

  /* Set a five-minute keepalive in order to dissuade natting routers
     from dropping the connection */
  { int data = 1;
    int n;
    n = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&data, sizeof(int));
    if ( n < 0 ) {
      perror("connect_to_host: setsockopt keepalive failed");
    } else {
#ifdef TCP_KEEPIDLE
      /* this call exists on modern Linuxes, but not everywhere */
      data = 300;
      n = setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &data, sizeof(int));
      if ( n < 0 ) {
	/* of course, this is not supported for unix sockets. We could
	   have checked the address family, but it's probably simpler
	   just to ignore errors */
	if ( errno != ENOTSUP ) {
	  perror("connect_to_host: setsockopt keepidle failed");
	}
      }
#endif
    }
  }

  if ( !plain && skt_open_transform ) {
    return (SOCKET) skt_open_transform(fd);
  } else {
    return fd;
  }
}

SOCKET connect_to_host(const char *address) {
  return _connect_to_host(0,address);
}

SOCKET plain_connect_to_host(const char *address) {
  return _connect_to_host(1,address);
}


/* close a network connection */
static int _close_socket(int plain, SOCKET s) {
  if ( !plain && skt_closer ) {
    return skt_closer((void *)s);
  } else {
    return closesocket(s);
  }
}

int close_socket(SOCKET s) {
  return _close_socket(0,s);
}

int plain_close_socket(SOCKET s) {
  return _close_socket(1,s);
}

/* read a line, up to lf/crlf terminator, from the socket,
   and return it.
   Internal backslashes are removed, unless doubled.
   If the line ends with an unescaped backslash, replace by newline,
   and append the next line.
   If there is an error or end of file before seeing a terminator,
   NULL is returned. At present, error includes reading a partial line.
   The returned string is valid until the next call of get_line.
   This is the internal function implementing the next two;
   the second arg says whether the first is int or SOCKET.
*/
static char *_get_line(int fd,int is_socket) {
  int length,i,j;
  int offset=0;
  static char *buffer = NULL;
  static size_t buffer_size = 0;

  while ( 1 ) {
    while ( 1 ) {
      while (offset+1 >= (int)buffer_size) { /* +1 to keep some space for '\0' */
	buffer_size = (buffer_size == 0) ? 1024 : (2 * buffer_size);
	buffer = realloc(buffer, buffer_size);
	if (!buffer) {
	  perror("get_line");
	  exit(-1);
	}
      }
      length = (is_socket ?
	(skt_reader ? skt_reader((void *)fd,buffer+offset,1)
		  : 
#ifdef WIN32
		  recv(fd,buffer+offset,1,0)
#else
		  read(fd,buffer+offset,1)
#endif
	 ) : read(fd,buffer+offset,1));
      if ((length <= 0) || (buffer[offset] == '\n'))
	break;
      offset += length;
    }
    if ( offset == 0 ) return NULL;
    if ( length <= 0 ) {
      fprintf(stderr,"get_line read partial line");
      return NULL;
    }
    offset += length;
    buffer[offset] = '\0';
    /* now check for newline */
    if ( buffer[offset-1] == '\n' ) {
      if ( buffer[offset-2] == '\r' && buffer[offset-3] == '\\' ) {
        /* zap the CR */
	buffer[offset-2] = '\n';
	buffer[offset-1] = '\0';
	offset -= 1;
        /* and go onto next clause */
      }
      if ( buffer[offset-2] == '\\' ) {
	/* we have to decide whether this is an escaped backslash */
	int j = 1,k=offset-3;
	while ( k >= 0 && buffer[k--] == '\\' ) j++;
	if ( j & 1 ) {
	  /* odd number, not escaped */
	  buffer[offset-2] = '\n' ;
	  buffer[--offset] = '\0' ;
	  /* read another line */
	} else break; /* return this line */
      } else break; /* return this line */
    } /* no newline, keep going */
  }
  /* now remove internal backslashes */
  for ( i = j = 0; 1; i++, j++ ) {
    if ( buffer[j] == '\\' ) {
      j++;
    }
    buffer[i] = buffer[j];
    if ( !buffer[i] ) break;
  }
  return buffer;
}

char *get_line(SOCKET fd) {
  /* are we actually being asked to read from stdout? Then read
     from stdin */
  if ( fd == STDOUT_FILENO ) return _get_line(STDIN_FILENO,0);
  return _get_line((int)fd,1);
}

char *fd_get_line(int fd) {
  return _get_line(fd,0);
}

static int _put_line_aux(int fd, char* line, int length, int is_socket) {
  int n;
  if ( is_socket ) {
    n = skt_writer ? skt_writer((void *)fd,line,length)
      :
#ifdef WIN32
      send(fd,line,length,0)
#else
      write(fd,line,length)
#endif
      ;
  } else {
    n = write(fd,line,length);
  }
  if ( n < length ) {
    perror("put_line: write failed");
    return -1;
  }
  return n;
}

/* write a line (which is assumed to have any terminator included)
   to the given socket. Return -1 on error, length of line on success.
   Replace internal newlines by backslash CRLF and write as lines.
   Double all internal backslashes.
   Third arg says whether first arg is really an int, or a SOCKET.
   This is the internal function implemented the next two.
*/
static int _put_line(int fd,char *line,int is_socket) {
  int length,n;
  static char *buffer = NULL;
  static size_t buf_size = 0;
  int i,j;

  /* the backslash/newline escaping can at worst treble the size
     of the input */
  length = strlen(line) + 1; /* include null */
  while ( (int)buf_size <= 3*length ) {
    buf_size = buf_size ? 2*buf_size : 1024;
    buffer = realloc(buffer,buf_size);
  }

  /* FIXME: should retry if only write partial line */
  i = j = 0;
  while ( *line ) {
    if ( *line == '\\' ) { buffer[i++] = '\\' ; }
    if ( *line == '\n' && *(line+1) ) {
      buffer[i++] = '\\' ;
      buffer[i++] = '\r' ;
      buffer[i++] = *(line++) ;
      n = _put_line_aux(fd,buffer,i,is_socket);
      if ( n < 0 ) { return -1 ; }
      i = 0;
    } else {
      buffer[i++] = *(line++);
    }
  }
  return _put_line_aux(fd,buffer,i,is_socket);
}

int put_line(SOCKET fd,char *line) {
  /* are we asked to write to stdout? */
  if ( fd == STDOUT_FILENO ) return _put_line(STDOUT_FILENO,line,0);
  return _put_line((int)fd,line,1);
}

int fd_put_line(int fd,char *line) {
  return _put_line(fd,line,0);
}

int put_data(SOCKET fd, char *data, int len) {
  int n;
  
  if ( len == 0 ) {
#   ifdef WIN32
    n = shutdown(fd, SD_SEND);
#   else
    n = shutdown(fd, SHUT_WR);
#   endif
    if ( n < 0 ) {
      warn("put_data failed to shutdown: %s",strerror(errno));
    }
    return n;
  }
# ifdef WIN32
  n = send(fd,data,len,0);
# else
  n = write(fd,data,len);
# endif
  if ( n < 0 ) {
    warn("put_data failed: %s",strerror(errno));
  }
  return n;
}

int get_data(SOCKET fd, char *data, int len) {
  int n;
# ifdef WIN32
  n = recv(fd,data,len,0);
# else
  n = read(fd,data,len);
# endif
  if ( n < 0 ) {
    warn("put_data failed: %s",strerror(errno));
  }
  return n;
}


/* random integer from 0 to top inclusive */
static int seed = 0;

unsigned int rand_index(int top) {

  if ( seed == 0 ) {
    /* seed the generator */
    rand_seed(0);
  }

  return (unsigned int)((1.0+top)*rand()/(RAND_MAX+1.0));
}

/* and seed it */
void rand_seed(int s) {
  if ( s == 0 ) s = time(NULL);
  srand(seed = s);
}

/* utility function for following: return "NULL" for null string */
char *nullprotect(char *s) { return s ? s : "NULL"; }

/* feed a command to the system to be started in background.
   No fancy argument processing, just pass to shell or equiv.
   Return 1 on success, 0 on failure. */
int start_background_program(const char *cmd) {
  char buf[1024];
# ifdef WIN32
  int res;
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  
  strmcpy(buf,cmd,1023); buf[1023] = 0;
  memset((void *)&si,0,sizeof(STARTUPINFO));
  si.cb = sizeof(STARTUPINFO);
  res = CreateProcess(NULL,buf,NULL,NULL,
		0,DETACHED_PROCESS,NULL,NULL,&si,&pi);
  if ( res ) {
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
  } else {
    warn("Failed to start process %s",cmd);
  }
  return res;
# else
  strmcpy(buf,cmd,sizeof(buf)-strlen(buf)-1);
  strcat(buf," &");
# endif
  return ! system(buf);
}

/* unfortunately we need a slightly more sophisticated one where
   we can get at the output. This passes out a write handle for the
   new process's stdin, and a read handle for its stdout */
#ifndef WIN32
int start_background_program_with_io(const char *cmd,int *childin,
  int *childout)
{
  int tochild[2], fromchild[2];
  int cpid;
  
  if ( pipe(tochild) < 0 ) {
    perror("Unable to create pipe");
    return 0;
  }
  if ( pipe(fromchild) < 0 ) {
    perror("Unable to create pipe: %s");
    return 0;
  }
  cpid = fork();
  if ( cpid < 0 ) {
    perror("Unable to fork: %s");
  }
  if ( cpid ) {
    /* parent */
    close(tochild[0]);
    close(fromchild[1]);
    *childin = tochild[1];
    *childout = fromchild[0];
    return 1;
  } else {
    close(tochild[1]);
    close(fromchild[0]);
    dup2(tochild[0],0);
    close(tochild[0]);
    dup2(fromchild[1],1);
    close(fromchild[1]);
    execl("/bin/sh","sh","-c",cmd,NULL);
    /* what can we do if we get here? Not a lot... */
    perror("Exec of child failed");
    exit(1);
  }
  return 0;
}
#else
/* This windows version is loosely based on the example
   Creating a Child Process with Redirected Input and Output
   from the MSDN Library. See that example for all the comments
   explaining what's going on. 
   In fact it's (a) easier than that, since instead of saving, setting
   and inheriting handles, we can put the pipes into the startup
   info of the CreateProcess call. (Thanks to somebody on Usenet,
   no thanks to Microsoft!); (b) harder, because we need to pass
   back C-style file descriptors, not Windows handles. Hence the mystic
   call to _open_osfhandle. */
int start_background_program_with_io(const char *cmd,int *childin,
  int *childout)
{
  int res;
  char buf[1024];
  STARTUPINFO si;
  PROCESS_INFORMATION pi;
  SECURITY_ATTRIBUTES sa;
  HANDLE tochildr, tochildw, tochildw2, 
    fromchildr, fromchildr2, fromchildw;
  
  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa.bInheritHandle = TRUE;
  sa.lpSecurityDescriptor = NULL;
  if ( ! CreatePipe(&fromchildr,&fromchildw,&sa,0 ) ) {
    perror("couldn't create pipe");
    return 0;
  }
  DuplicateHandle(GetCurrentProcess(),
    fromchildr,GetCurrentProcess(),&fromchildr2,0,
    FALSE, DUPLICATE_SAME_ACCESS);
  CloseHandle(fromchildr);

  if ( ! CreatePipe(&tochildr,&tochildw,&sa,0 ) ) {
    perror("couldn't create pipe");
    return 0;
  }
  DuplicateHandle(GetCurrentProcess(),
    tochildw,GetCurrentProcess(),&tochildw2,0,
    FALSE, DUPLICATE_SAME_ACCESS);
  CloseHandle(tochildw);

  strmcpy(buf,cmd,1023); buf[1023] = 0;
  memset((void *)&si,0,sizeof(STARTUPINFO));
  si.cb = sizeof(STARTUPINFO);
  si.dwFlags = STARTF_USESTDHANDLES;
  si.hStdOutput = fromchildw;              
  si.hStdInput  = tochildr;           
  si.hStdError  = 0;
  res = CreateProcess(NULL,buf,NULL,NULL,
		TRUE,DETACHED_PROCESS,NULL,NULL,&si,&pi);
  if ( res ) {
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
  } else {
    warn("Failed to start process %s",cmd);
  }
  /* I think the mingw has the wrong type for _open_osfhandle ? */
  *childin = _open_osfhandle((int)tochildw2,_O_WRONLY);
  *childout = _open_osfhandle((int)fromchildr2,_O_RDONLY);
  /* do we, as in unix, close our versions of the handles we don't want? */
  if ( 1 ) {
    CloseHandle(tochildr);
    CloseHandle(fromchildw);
  }
  return res;
}
#endif

/* return a home directory */
char *get_homedir(void) {
  char *p;
# ifdef WIN32
  static char buf[512];
  buf[0] = 0;
  if ( (p = getenv("HOMEDRIVE")) ) strcpy(buf,p);
  if ( (p = getenv("HOMEPATH")) ) strcat(buf,p);
  if ( buf[0] ) return buf;
  return NULL;
# else
  struct passwd *pw;
  if ( (p = getenv("HOME")) ) return p;
  if ( (pw = getpwuid(getuid())) ) return pw->pw_dir;
  return NULL;
# endif
}

/* stuff for Windows */
#ifdef WIN32
int gettimeofday(struct timeval *tv, void *tz UNUSED) {
  long sec, usec;
  LONGLONG ll;
  FILETIME ft;

  GetSystemTimeAsFileTime(&ft);
  ll = ft.dwHighDateTime;
  ll <<= 32;
  ll |= ft.dwLowDateTime;
  /* this magic number comes from Microsoft's knowledge base ' */
  ll -= 116447360000000000;  /* 100 nanoseconds since 1970 */
  ll /= 10; /* microseconds since 1970 */
  sec = (long)(ll / 1000000);
  usec = (long)(ll - 1000000*((LONGLONG) sec));
  if ( tv ) {
    tv->tv_sec = sec;
    tv->tv_usec = usec;
  }
  return 0;
}

char *getlogin(void) { 
  static char buf[128];
  DWORD len = 128;

  buf[0] = 0;
  GetUserName(buf,&len);
  return buf;
}
 
int getpid(void) {
  return GetCurrentProcessId();
}

int unlink(const char *f) {
  return DeleteFile(f); 
}

unsigned int sleep(unsigned int t) { Sleep(1000*t); return 0; }

/* I don't think we really need submillisecond resolution ... */
unsigned int usleep(unsigned int t) { Sleep(t/1000); return 0; }


#endif /* WIN32 */