File: conquestd.c

package info (click to toggle)
conquest 8.1-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 7,984 kB
  • ctags: 3,086
  • sloc: ansic: 39,393; sh: 8,540; yacc: 446; makefile: 296; lex: 146
file content (1999 lines) | stat: -rw-r--r-- 48,383 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
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
#include "c_defs.h"

/************************************************************************
 *
 * conquestd - the Conquest server/client driver
 *
 * $Id: conquestd.c,v 1.25 2004/12/26 08:19:31 jon Exp $
 *
 * Copyright 2003 Jon Trulson under the ARTISTIC LICENSE. (See LICENSE).
 ***********************************************************************/


#define NOEXTERN

#include "conqdef.h"
#include "conqcom.h"
#include "conqlb.h"
#include "context.h"
#include "conf.h"
#include "global.h"
#include "color.h"
#include "record.h"
#include "ibuf.h"
#include "sem.h"

#include "conqnet.h"
#include "packet.h"
#include "udp.h"

#define SERVER_NOEXTERN
#include "server.h"
#undef SERVER_NOEXTERN
#include "serverpkt.h"

#include "servauth.h"
#include "servercmd.h"
#include "meta.h"

#define LISTEN_BACKLOG 5 /* # of requests we're willing to to queue */

static Unsgn16 listenPort = CN_DFLT_PORT;

static char cbuf[MID_BUFFER_SIZE]; /* general purpose buffer */
static char *progName;

static int localOnly = FALSE;   /* whether to only listen on loopback */
static char *metaServer = META_DFLT_SERVER; /* meta server hostname */
static int updateMeta = FALSE;  /* whether to notify meta server */
static char *myServerName = NULL; /* to meta */

cpHello_t chello;		/* client hello info we want to keep */
ServerInfo_t sInfo;

static int hello(void);		/* meet and greet the client */
int updateClient(int force);
void updateProc(void);
void startUpdate(void);
void stopUpdate(void);

void catchSignals(void);
void handleSignal(int sig);
void conqend(void);
int welcome( int *unum );
void menu(void);
int play(void);

void printUsage()
{
  printf("Usage: conquestd [ -d ] [ -l ] [ -p port ] [ -u user ]\n");
  printf("                 [ -m ] [ -M metaserver ] [ -N myname ]\n");
  printf("\n");
  printf("   -d            daemon mode\n");
  printf("   -l            listen for local connections only\n");
  printf("   -p port       specify port to listen on\n");
  printf("                 default is %d\n", CN_DFLT_PORT);
  printf("   -m            notify the metaserver (%s)\n", META_DFLT_SERVER);
  printf("   -M metaserver specify an alternate metaserver to contact\n");
  printf("   -N myname     explicitly specify server name 'myname' to metaserver\n");
  printf("   -u user       run as user 'user'.\n");
  return;
}


int getHostname(int sock, char *buf, int buflen)
{
  struct sockaddr_in addr;
  socklen_t len;
  struct hostent *host;

  len = sizeof(struct sockaddr_in);
  if (getpeername(sock, (struct sockaddr *) &addr, &len) < 0)
    {
      clog("getpeername failed: %s\n", strerror(errno));
      return FALSE;
    }
  else
    {
      if ((host = gethostbyaddr((char *) &addr.sin_addr.s_addr,
                                sizeof(unsigned long),
                                AF_INET)) == NULL)
	{
	  strncpy(buf, inet_ntoa((struct in_addr)addr.sin_addr), 
		  buflen);
	}
      else
        {
	  strncpy(buf, host->h_name, buflen);
        }
    }
  
  return TRUE;
}
    

/* we only return if we are a client driver, else we listen for requests,
   updating the meta server if requested */
void checkMaster(void)
{
  int s,t;			/* socket descriptor */
  int i,rv;			/* general purpose integer */
  struct sockaddr_in sa, isa;	/* internet socket addr. structure */
  struct hostent *hp;		/* result of host name lookup */
  struct timeval tv;
  fd_set readfds;

  signal(SIGCLD, SIG_IGN);	/* allow children to die */

  if (!checkPID(ConqInfo->conqservPID))
    {				/* see if one is really running */
      /* if we are here, we will be the listener */
      PVLOCK(&ConqInfo->lockword);
      ConqInfo->conqservPID = getpid();
      PVUNLOCK(&ConqInfo->lockword);
      sInfo.isMaster = TRUE;
      clog("NET: master server listening on port %d\n", listenPort);
    }

  /* get our own host information */
  memset(sInfo.localhost, 0, MAXHOSTNAME);

  gethostname ( sInfo.localhost, MAXHOSTNAME - 1 );

  if ((hp = gethostbyname(sInfo.localhost)) == NULL) 
    {
      perror("gethostbyname");
      exit (1);
    }
  
  sa.sin_port = htons(listenPort);

  if (localOnly)
    sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  else
    sa.sin_addr.s_addr = htonl(INADDR_ANY); /* Bind to all addresses.
                                               -Werewolf */
  sa.sin_family = hp->h_addrtype;
  
  /* allocate an open socket for incoming connections */
  if (( s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0) 
    {
      perror ( "socket" );
      exit(1);
    }
  
  /* bind the socket to the service port so we hear incoming
   * connections 
   */
  if ( bind( s, (struct sockaddr *)&sa, sizeof ( sa )) < 0 ) 
    {
      perror( "bind" );
      exit(1);
    }
  
  /* set the maximum connections we will fall behind */
  listen( s, LISTEN_BACKLOG );

  
  /* go into infinite loop waiting for new connections */
  while (TRUE) 
    {
      if (updateMeta)
        {
          /* get any changes to sysconf so that meta updates are
             up to date */
          GetSysConf(TRUE);
          metaUpdateServer(metaServer, myServerName, listenPort);
        }

      tv.tv_sec = 120;           /* update meta server every 120 secs */
      tv.tv_usec = 0;
      FD_ZERO(&readfds);
      FD_SET(s, &readfds);

      if ((rv = select(s+1, &readfds, NULL, NULL, &tv)) < 0)
        {
          clog("checkMaster: select failed: %s", strerror(errno));
          exit(1);
        }

      if (FD_ISSET(s, &readfds))
        {        

          i = sizeof (isa);
      
          /* hang in accept() while waiting for new connections */
          if ((t = accept(s, (struct sockaddr *)&isa, &i )) < 0) 
            {
              perror ( "accept" );
              exit (1);
            }
      
          if ( fork() == 0 ) 
            {			/* child - client driver */
              sInfo.sock = t;
              pktSetNodelay(sInfo.sock);
              memset(sInfo.remotehost, 0, MAXHOSTNAME);
              getHostname(sInfo.sock, sInfo.remotehost, MAXHOSTNAME - 1);
              
              clog("NET: forked client driver, pid = %d", getpid());
              return;
            }
          
          /* parent */
          close(t);	/* make socket go away */
        }

    }

  return;			/* NOTREACHED */
}


/*  conquestd - main program */
int main(int argc, char *argv[]) 
{
  int i;
  char *myuidname = NULL;              /* what user do I run under? */
  int dodaemon = FALSE;

  progName = argv[0];
  sInfo.state = SVR_STATE_PREINIT;
  sInfo.sock = -1;
  sInfo.usock = -1;
  sInfo.doUDP = FALSE;
  sInfo.tryUDP = TRUE;
  sInfo.clientDead = TRUE;
  sInfo.isMaster = FALSE;
  sInfo.isLoggedIn = FALSE;

  while ((i = getopt(argc, argv, "dlp:u:mM:N:")) != EOF)    /* get command args */
    switch (i)
      {
      case 'd':
        dodaemon = TRUE;
        break; 

      case 'p':
	listenPort = (Unsgn16)atoi(optarg);
	break;

      case 'l':                 /* local conn only */
        localOnly = TRUE;
        break;

      case 'u':
        myuidname = optarg;
        break;

      case 'm':
        updateMeta = TRUE;
        break;

      case 'M':
        metaServer = optarg;
        break;

      case 'N':
        myServerName = optarg;
        break;

      default:
	printUsage();
	exit(1);
      }


  /* clear out our stored packets */
  spktInit();

  if ((ConquestGID = getConquestGID()) == ERR)
    {
      fprintf(stderr, "%s: getConquestGID() failed\n", progName);
      exit(1);
    }
  

  /* at this point, we see if the -u option was used.  If it was, we
     setuid() to it */

  if (myuidname)
    {
      int myuid;

      if ((myuid = getUID(myuidname)) == ERR)
        {
          fprintf(stderr, "%s: getUID(%s) failed\n", progName, myuidname);
          exit(1);
        }

      if (setuid(myuid) == -1)
        {
          fprintf(stderr, "%s: setuid(%d) failed: %s\n", progName, myuid,
                  strerror(errno));
          exit(1);
        }        
      else
        clog("INFO: running as user '%s', uid %d.", myuidname, myuid); 
    }

  
#ifdef DEBUG_CONFIG
  clog("%s@%d: main() Reading Configuration files.", __FILE__, __LINE__);
#endif
  
  if (GetSysConf(FALSE) == ERR)
    {
#ifdef DEBUG_CONFIG
      clog("%s@%d: main(): GetSysConf() returned ERR.", __FILE__, __LINE__);
#endif
    }

  if (setgid(ConquestGID) == -1)
    {
      clog("conquest: setgid(%d): %s",
           ConquestGID,
           strerror(errno));
      fprintf(stderr, "conquest: setgid(): failed\n");
      exit(1);
    }
  
#ifdef DEBUG_FLOW
  clog("%s@%d: main() *STARTING*", __FILE__, __LINE__);
#endif
  
#ifdef DEBUG_FLOW
  clog("%s@%d: main() getting semephores - semInit()", __FILE__, __LINE__);
#endif
  
  if (semInit() == ERR)
    {
      fprintf(stderr, "semInit() failed to get semaphores. exiting.\n");
      exit(1);
    }
  
#ifdef DEBUG_FLOW
  clog("%s@%d: main() mapping common block.", __FILE__, __LINE__);
#endif
  
  map_common();

  if ( *CBlockRevision != COMMONSTAMP )
    {
      fprintf(stderr,"conquestd: Common block ident mismatch.\n" );
      fprintf(stderr,"           You must initialize the universe with conqoper.\n" );
      exit(1);
    }

  
#ifdef DEBUG_FLOW
  clog("%s@%d: main() starting conqinit().", __FILE__, __LINE__);
#endif
  
  Context.maxlin = 0;		/* not used here */
  Context.maxcol = 0;		/* not used here */
  
  Context.snum = 0;
  Context.histslot = ERR;
  Context.lasttang = Context.lasttdist = 0;
  Context.lasttarg[0] = EOS;
  Context.updsec = 10;		/* 10 per second default update rate */


  /* if daemon mode requested, fork off and detach */
  if (dodaemon)
    {
      int cpid;
      clog("INFO: becoming daemon");
      chdir("/");

      cpid = fork();
      switch (cpid) 
        {
        case 0:
          /* child */

#if defined(HAVE_DAEMON)
          daemon(0, 0);
#else
# if defined(HAVE_SETPGRP)
#  if defined(SETPGRP_VOID)
          setpgrp ();
#  else
          setpgrp (0, getpid());
#  endif
# endif

          close (0);
          close (1);
          close (2);

          /* Set up the standard file descriptors. */

          (void) open ("/", O_RDONLY);        /* root inode already in core */
          (void) dup2 (0, 1);
          (void) dup2 (0, 2);

#endif /* !HAVE_DAEMON */

          break;

        case -1:
          /* error */
          fprintf(stderr, "daemon fork failed: %s\n", strerror(errno));
          break;

        default:
          /* parent */
          exit(0);
        }
    }

  /* see if we are master server.  If we are, we won't return from this
     call.  If we are a forked client driver, we will. */
  checkMaster();

  /* if we are here, then we are a client driver, with an active socket */
  sInfo.state = SVR_STATE_INIT;

  /* re-read sys conf here for indivulual client drivers... */
  if (GetSysConf(FALSE) == ERR)
    {
#ifdef DEBUG_CONFIG
      clog("%s@%d: main(): GetSysConf() returned ERR.", __FILE__, __LINE__);
#endif
    }



  conqinit();			/* machine dependent initialization */
  
  rndini( 0, 0 );		/* initialize random numbers */
  
  clog("CONNECT: client %s\n", sInfo.remotehost);

  /* now we need to negotiate. */
  if (!hello())
    {
      clog("conquestd: hello() failed\n");
      exit(1);
    }

  clog("CONNECT: client %s SUCCESS.\n", sInfo.remotehost);

  Context.recmode = RECMODE_OFF; /* always */

  if ( welcome( &Context.unum ) )
    {
      sInfo.state = SVR_STATE_MAINMENU;

      menu();
    }
  
  drpexit();			/* make the driver go away */
  conqend();			/* machine dependent clean-up */
  
#ifdef DEBUG_FLOW
  clog("%s@%d: main() *EXITING*", __FILE__, __LINE__);
#endif
  
  exit(0);
  
}

/* responsible for updating the client */
void updateProc(void)
{
#if 0
  static Unsgn32 lastms = 0;
  Unsgn32 millis = clbGetMillis();

  if ((millis - lastms) > 100)
    clog("millisdiff = %u", (millis - lastms));
  lastms = millis;
#endif

  /* Don't do anything if we're not supposed to. */
  if (sInfo.state != SVR_STATE_PLAY)
    return;

  stopUpdate();

  drcheck();			/* check the driver */  

  /* update client view of the universe */
  updateClient(FALSE);

  recordUpdateFrame();

  /* check for and send any new messages */
  if ( getamsg( Context.snum, &Ships[Context.snum].lastmsg ) )
    sendMessage(&(Msgs[Ships[Context.snum].lastmsg]));

  /* Schedule for next time. */
  startUpdate();
  
  return;
  
}

void startUpdate(void)
{
  static struct sigaction Sig;

#ifdef HAVE_SETITIMER
  struct itimerval itimer;
#endif

  Sig.sa_handler = (void (*)(int))updateProc;
  
  Sig.sa_flags = 0;

  if (sigaction(SIGALRM, &Sig, NULL) == -1)
    {
      clog("startUpdater():sigaction(): %s\n", strerror(errno));
      exit(errno);
    }
  
#ifdef HAVE_SETITIMER
  if (Context.updsec >= 1 && Context.updsec <= 10)
    {
      if (Context.updsec == 1)
	{
	  itimer.it_value.tv_sec = 1;
	  itimer.it_value.tv_usec = 0;
	}
      else
	{
	  itimer.it_value.tv_sec = 0;
	  itimer.it_value.tv_usec = (1000000 / Context.updsec);
	}
    }
  else
    {
      itimer.it_value.tv_sec = 0;
      itimer.it_value.tv_usec = (1000000 / 2); /* 2/sec */
    }

  itimer.it_interval.tv_sec = itimer.it_value.tv_sec;
  itimer.it_interval.tv_usec = itimer.it_value.tv_usec;

  setitimer(ITIMER_REAL, &itimer, NULL);
#else
  alarm(1);			/* set alarm() */
#endif  

  return;
}

void stopUpdate(void)
{
#ifdef HAVE_SETITIMER
  struct itimerval itimer;
#endif
  
  signal(SIGALRM, SIG_IGN);
  
#ifdef HAVE_SETITIMER
  itimer.it_value.tv_sec = itimer.it_interval.tv_sec = 0;
  itimer.it_value.tv_usec = itimer.it_interval.tv_usec = 0;
  
  setitimer(ITIMER_REAL, &itimer, NULL);
#else
  alarm(0);
#endif

  return;
  
}



/*  capentry - captured system entry for a new ship */
/*  SYNOPSIS */
/*    int flag, capentry */
/*    int capentry, snum, system */
/*    system = capentry( snum, system ) */
int capentry( int snum, int *system )
{
  int i, j; 
  int owned[NUMPLAYERTEAMS]; 
  int pkttype;
  cpCommand_t *ccmd;
  Unsgn8 buf[PKT_MAXSIZE];
  Unsgn8 esystem = 0;
  int sockl[2] = {sInfo.sock, sInfo.usock};
  
  /* First figure out which systems we can enter from. */
  for ( i = 0; i < NUMPLAYERTEAMS; i = i + 1 )
    {
      owned[i] = FALSE;
      /* We must own all three planets in a system. */
      for ( j = 0; j < 3; j = j + 1 )
	{
	  if ( Planets[Teams[i].teamhplanets[j]].team != Ships[snum].team )
	    goto cnext2_1; /* next 2; */
	}
      owned[i] = TRUE;
    cnext2_1:
      ;
    }
  owned[Ships[snum].team] = TRUE;		/* always can enter in our system */
  
  /* Now count how many systems we can enter from. */
  j = 0;
  esystem = 0;
  for ( i = 0; i < NUMPLAYERTEAMS; i = i + 1 )
    if ( owned[i] )
      {
	esystem |= (1 << i);
	j++;
      }
  
  /* If we can only enter from one, we're done. */
  if ( j <= 1 )
    {
      *system = Ships[snum].team; /* tell the client */
      if (!sendClientStat(sInfo.sock, SPCLNTSTAT_FLAG_NONE, snum, 
			  Ships[snum].team,
			  Context.unum, 0))
	return FALSE;
      return TRUE;
    }
  
  /* ask the client - use a clientstat with non-zero esystem */

  if (!sendClientStat(sInfo.sock, SPCLNTSTAT_FLAG_NONE, snum, Ships[snum].team,
		     Context.unum, esystem))
    return FALSE;

  while ( clbStillAlive( Context.snum ) )
    {

      /* now we wait for another ENTER command packet with it's detail member
	 indicating the desired system. */

      if ((pkttype = waitForPacket(PKT_FROMCLIENT, sockl, CP_COMMAND,
				   buf, PKT_MAXSIZE, 1, NULL)) < 0)
        {
	  clog("conquestd:capentry: waitforpacket returned %d", pkttype); 
          return FALSE;
        }


      if ( pkttype == 0 )       /* timeout */
	continue; 

      ccmd = (cpCommand_t *)buf;
      ccmd->detail = ntohs(ccmd->detail);

      clog("conquestd: capentry: got CP_COMMAND, detail =0x%x", 
	   ccmd->detail);

      if (ccmd->cmd != CPCMD_ENTER)
	{			/* we'll just use the home team */
	  *system = Ships[snum].team;
	  return TRUE;
	}

      if (ccmd->detail == 0)	/* didn't want to select one */
	return FALSE;

      /* else we'll use the first set bit */
      esystem &= (Unsgn8)(ccmd->detail & 0x00ff);

      for ( i = 0; i < NUMPLAYERTEAMS; i++ )
	if (esystem & (1 << i))
	  {
	    *system = i;
	    return TRUE;
	  }

      /* shouldn't happen, but... */
      *system = Ships[snum].team;
      return TRUE;
    }

  return FALSE;	    /* can get here because of clbStillAlive() */
  
}


/*  dead - do dead-type stuff for the server. (DOES LOCKING) */
/*  SYNOPSIS */
/*    int snum */
/*    int leave */
/*    dead( snum, leave ) */
void dead( int snum, int leave )
{
  int i, j, kb, now, entertime; 
  Unsgn8 flags = SPCLNTSTAT_FLAG_NONE; /* for clientstat msg */
  char buf[PKT_MAXSIZE];	/* gen purpose */
  int sockl[2] = {sInfo.sock, sInfo.usock};
  
  /* If something is wrong, don't do anything. */
  if ( snum < 1 || snum > MAXSHIPS )
    return;
  
  /* If our ships pid is wrong, we are indeed lost. */
  if ( Ships[snum].pid != Context.pid )
    return;
  
  kb = Ships[snum].killedby;
  
  /* Delay while our torps are exploding. */
  grand( &entertime );
  i = 0;
  while ( dgrand( entertime, &now ) < TORPEDOWAIT_GRAND )
    {
      updateClient(FALSE);
      i = 0;
      for ( j = 0; j < MAXTORPS; j = j + 1 )
	if ( Ships[snum].torps[j].status == TS_DETONATE )
	  i = i + 1;
      if ( i <= 0 )
	break;
      c_sleep( (1.0 / (real)Context.updsec) );
    }
  
  /* There aren't supposed to be any torps left. */
  if ( i > 0 )
    {
      buf[0] = EOS;
      appship( snum, buf );
      clog("INFO: dead: %s, detonating torp count is %d.",
	   buf, i);
    }
  
  buf[0] = EOS;
  appship( snum, buf );
  clog("INFO: dead: %s was killed by %d.", buf, kb);
  
  updateClient(FALSE);
  for ( i=0; i<10 && Ships[snum].status == SS_DYING; i++ )
    {
      c_sleep( (1.0 / (real)Context.updsec) );
      updateClient(FALSE);
    }

  /* if you conquered the universe, let the client know, and wait for
     a cpMessage packet indicating the desired last words.  We'll wait up
     to 2 minutes before we decide on our own. */

  flags |= SPCLNTSTAT_FLAG_KILLED; /* you are quite dead */

  if (kb == KB_CONQUER)
    flags |= SPCLNTSTAT_FLAG_CONQUER;

  /* send the clientstat */
  if (!sendClientStat(sInfo.sock, flags, Context.snum, Users[Context.unum].team,
		      Context.unum, 0))
    {				/* an error, let the ai code choose some
				   last words and bail */
      if (kb == KB_CONQUER)
        {
          robreply(buf);
          strncpy(ConqInfo->lastwords, buf, MAXLASTWORDS - 1);
          ConqInfo->lastwords[MAXLASTWORDS - 1] = 0;
        }

      clog("conquestd: dead(): sendClientStat failed, fl = 0x%0x\n",
           flags);

      return;
    }

  clog("INFO: dead(): sent sendClientStat, fl = 0x%0x",
       flags);

  /* fix things up */
  Ships[snum].status = SS_RESERVED;
  Ships[snum].sdfuse = -TIMEOUT_PLAYER;
  /*  Ships[snum].killedby = 0;*/

  /* let the client know. */
  updateClient(FALSE);

  /* if conquered, wait for the cpMessage_t */
  if (kb == KB_CONQUER)
    {
      if (waitForPacket(PKT_FROMCLIENT, sockl, CP_MESSAGE, 
			buf, PKT_MAXSIZE,
			(60 * 5), NULL) <= 0)
	{			/* error or timeout.  gen lastwords */
	  robreply(buf);
	  strncpy(ConqInfo->lastwords, buf, MAXLASTWORDS);
	  ConqInfo->lastwords[MAXLASTWORDS - 1] = 0;
	  
	  return;
	}
      else
	{
	  cpMessage_t *cmsg = (cpMessage_t *)buf;

	  /* copy as much of the message as you can. */
	  strncpy(ConqInfo->lastwords, cmsg->msg, MAXLASTWORDS);
          ConqInfo->lastwords[MAXLASTWORDS - 1] = 0;
	}
    }
      
  /* Turn off sticky war so we can change war settings from menu(). */
  for ( i = 0; i < NUMPLAYERTEAMS; i++ )
    Ships[snum].rwar[i] = FALSE;
  
  return;
  
}

/* send all pertinent data, and any users attached to them. */
int updateClient(int force)
{
  int i,j;
  static int sentallusers = FALSE; /* we will send all user data once. */
  static time_t oldtime = 0;
  time_t newtime = getnow(NULL, 0);
  int seciter = FALSE;
  static time_t histtime = 0;   /* timers that try to save some time() */
  static time_t infotime = 0;
  static time_t teamtime = 0;
  int dohist = FALSE;
  int doinfo = FALSE;
  int doteam = FALSE;

  if (force)
    {                           /* we need to reload everything */
      oldtime = 0;
      histtime = 0;   
      infotime = 0;
      teamtime = 0;
      sentallusers = FALSE;
    }
     
  
  /* some things really should not be checked every update iter */
  if (oldtime != newtime)
    {
      seciter = TRUE;
      oldtime = newtime;
    }

  /* hist */
  if ((abs((unsigned int)newtime - (unsigned int)histtime) >
       HISTORY_UPDATE_INTERVAL))
    {
      dohist = TRUE;
      histtime = newtime;
    }

  /* info */
  if ((abs((unsigned int)newtime - (unsigned int)infotime) >
       CONQINFO_UPDATE_INTERVAL))
    {
      doinfo = TRUE;
      infotime = newtime;
    }

  /* team */
  if ((abs((unsigned int)newtime - (unsigned int)teamtime) >
       TEAM_UPDATE_INTERVAL))
    {
      doteam = TRUE;
      teamtime = newtime;
    }


  if (!sentallusers)
    {                           /* send all valid user data the first time */
      sentallusers = TRUE;
      for (i=0; i<MAXUSERS; i++)
        if (Users[i].live)
          if (!sendUser(sInfo.sock, i))
            return FALSE;
    }

  for (i=1; i<=MAXSHIPS; i++)
    {
      if (!sendShip(sInfo.sock, i))
	return FALSE;

      for (j=0; j<MAXTORPS; j++)
	if (!sendTorp(sInfo.sock, i, j))
	  return FALSE;

      /* we only send user data for active ships. */
      if (Ships[i].status != SS_OFF)
	{
          if (seciter)
            {
              if (!sendUser(sInfo.sock, Ships[i].unum))
                {
                  return FALSE;
                }
            }
        }
    }

  for (i=1; i<=NUMPLANETS; i++)
    sendPlanet(sInfo.sock, i, force);

  if (doteam)
    for (i=0; i<NUMALLTEAMS; i++)
      sendTeam(sInfo.sock, i, FALSE);

  if (doinfo)
    sendConqInfo(sInfo.sock, FALSE);

  if (dohist)
    {
      for (i=0; i<MAXHISTLOG; i++)
        {
          if (History[i].histunum >= 0)
            sendUser(sInfo.sock, History[i].histunum);
          
          sendHistory(sInfo.sock, i);
        }
    }

  sendDoomsday(sInfo.sock);

  return TRUE;
}


/* handle simple client commands */
void handleSimpleCmdPkt(cpCommand_t *ccmd)
{
  int cmd;

  if (!ccmd)
    return;

  cmd = ccmd->cmd;
  /*  Some commands are only available in certain states */

  switch (cmd)
    {
    case CPCMD_SWITCHTEAM:	
      if (sInfo.state == SVR_STATE_MAINMENU)
	{
	  int team = (int)((Unsgn16)ntohs(ccmd->detail));

	  if (team >= 0 && team < NUMPLAYERTEAMS)
	    {

	      if (Users[Context.unum].ooptions[OOPT_SWITCHTEAMS] && 
		  Users[Context.unum].ooptions[OOPT_MULTIPLE] <= 1)
		{
		  Ships[Context.snum].team = team; 
		  Ships[Context.snum].shiptype = 
		    Teams[Ships[Context.snum].team].shiptype;
		  Users[Context.unum].team = Ships[Context.snum].team;
		  Ships[Context.snum].war[Ships[Context.snum].team] = FALSE;
		  Users[Context.unum].war[Users[Context.unum].team] = FALSE;
		}

	    }
	}
	  
      break;
      
    case CPCMD_SETWAR:
      if (sInfo.state == SVR_STATE_MAINMENU || sInfo.state == SVR_STATE_PLAY)
	procSetWar(ccmd);

      break;

    case CPCMD_SETWARP:
      if (sInfo.state == SVR_STATE_PLAY)
	procSetWarp(ccmd);

      break;

    case CPCMD_SETSHIELDS:
      if (sInfo.state == SVR_STATE_PLAY)
	procSetShields(ccmd);

      break;

    case CPCMD_ALLOC:
      if (sInfo.state == SVR_STATE_PLAY)
	procAlloc(ccmd);

      break;

    case CPCMD_CLOAK:
      if (sInfo.state == SVR_STATE_PLAY)
	procCloak(ccmd);

      break;

    case CPCMD_DETSELF:
      if (sInfo.state == SVR_STATE_PLAY)
	procDetSelf(ccmd);

    case CPCMD_DETENEMY:
      if (sInfo.state == SVR_STATE_PLAY)
	procDetEnemy(ccmd);

      break;

    case CPCMD_DISTRESS:
      if (sInfo.state == SVR_STATE_PLAY)
	procDistress(ccmd);

      break;

    case CPCMD_REPAIR:
      if (sInfo.state == SVR_STATE_PLAY)
	procRepair(ccmd);

      break;

    case CPCMD_FIREPHASER:
      if (sInfo.state == SVR_STATE_PLAY)
	procFirePhaser(ccmd);

      break;

    case CPCMD_ORBIT:
      if (sInfo.state == SVR_STATE_PLAY)
        procOrbit(ccmd);

      break;

    case CPCMD_REFIT:
      if (sInfo.state == SVR_STATE_PLAY)
        procRefit(ccmd);

      break;

    case CPCMD_SETRATE:
      procSetRate(ccmd);

      break;

    case CPCMD_TOW:
      if (sInfo.state == SVR_STATE_PLAY)
	procTow(ccmd);

      break;

    case CPCMD_UNTOW:
      if (sInfo.state == SVR_STATE_PLAY)
	procUnTow(ccmd);

      break;

    case CPCMD_COUP:
      if (sInfo.state == SVR_STATE_PLAY)
	procCoup(ccmd);

      break;

    case CPCMD_BOMB:
      if (sInfo.state == SVR_STATE_PLAY)
	procBomb(ccmd);

      break;

    case CPCMD_BEAM:
      if (sInfo.state == SVR_STATE_PLAY)
	procBeam(ccmd);

      break;

    case CPCMD_DESTRUCT:
      if (sInfo.state == SVR_STATE_PLAY)
	procDestruct(ccmd);

      break;

    case CPCMD_AUTOPILOT:
      if (sInfo.state == SVR_STATE_PLAY)
	procAutoPilot(ccmd);

      break;

    case CPCMD_RELOAD:
      procReload(ccmd);
      clbBlockAlarm();
      updateClient(TRUE);
      clbUnblockAlarm();

      break;

    case CPCMD_DISCONNECT:
      clog("CPCMD_DISCONNECT");
      /* 'fake' signal.  cleans up and exits. */
      handleSignal(0);
      /* NOTREACHED */
      break;

    case CPCMD_PING:
      clbBlockAlarm();
      sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_INFO, PERR_PINGRESP, NULL);
      clbUnblockAlarm();
      break;

    default:
      clog("conquestd: handleSimpleCmdPkt(): unexpected command code %d",
	   cmd);
      break;
    }

  return;
}

/* DOES LOCKING */
void freeship(void)
{
  conqstats( Context.snum );
  PVLOCK(&ConqInfo->lockword);
  Ships[Context.snum].sdfuse = 0;
  Ships[Context.snum].status = SS_OFF;
  PVUNLOCK(&ConqInfo->lockword);
  return;
}

/*  menu - main user menu (DOES LOCKING) */
/*  SYNOPSIS */
/*    menu */
void menu(void)
{
  int i, sleepy, countdown;
  int lose, oclosed, switchteams, multiple, redraw;
  int playrv;
  int pkttype;
  Unsgn8 buf[PKT_MAXSIZE];
  cpCommand_t *ccmd;
  int sockl[2] = {sInfo.sock, sInfo.usock};

  catchSignals();	/* enable trapping of interesting signals */
  
  /* we'll set some things up,  */

  /* Initialize statistics. */
  initstats( &Ships[Context.snum].ctime, &Ships[Context.snum].etime );
  
  /* Log this entry into the Game. */
  Context.histslot = clbLogHist( Context.unum );
  
  /* Set up a few ship characteristics here rather than in clbInitShip(). */
  Ships[Context.snum].unum = Context.unum;
  Ships[Context.snum].team = Users[Context.unum].team;
  Ships[Context.snum].shiptype = Teams[Ships[Context.snum].team].shiptype;

  Ships[Context.snum].pid = Context.pid;
  Ships[Context.snum].killedby = 0;

  for ( i = 0; i < NUMPLAYERTEAMS; i = i + 1 )
    {
      Ships[Context.snum].rwar[i] = FALSE;
      Ships[Context.snum].war[i] = Users[Context.unum].war[i];
    }
  stcpn( Users[Context.unum].alias, Ships[Context.snum].alias, MAXUSERPNAME );
  
  /* Set up some things for the menu display. */
  switchteams = Users[Context.unum].ooptions[OOPT_SWITCHTEAMS];
  multiple = Users[Context.unum].ooptions[OOPT_MULTIPLE];
  oclosed = ConqInfo->closed;
  Context.leave = FALSE;
  redraw = TRUE;
  sleepy = 0;
  countdown = 0;
  playrv = FALSE;

  /* send a ship packet for our ship.  Since this is the first ship packet,
     an SP_SHIP should get sent. */
  if (!sendShip(sInfo.sock, Context.snum))
    {				/* something went wrong */
      /* Make our ship available for others to use. */
      if ( Ships[Context.snum].status == SS_RESERVED )
	{
	  freeship();
	  return;
	}
    }
  
  do                 
    {
      if (!updateClient(FALSE))	/* sends packets */
	{
	  freeship();
	  return;
	}

      /* Make sure things are proper. */
      if (playrv == ERR) 
	{
	  if ( Context.snum < 1 || Context.snum > MAXSHIPS )
	    lose = TRUE;
	  else if ( Ships[Context.snum].pid != Context.pid )
	    lose = TRUE;
	  else if ( Ships[Context.snum].status != SS_RESERVED )
	    {
	      clog( "menu(): Ship %d no longer reserved.", Context.snum );
	      lose = TRUE;
	    }
	  else
	    lose = FALSE;
	}
      else
	lose = FALSE;

      if ( lose )				/* again, Jorge? */
	{
	  sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_FATAL, PERR_LOSE, NULL);
	  return;
	}
      
      /* Try to kill the driver if we started one the last time */
      /*  we played and we've been in the menu long enough. */
      if ( countdown > 0 )
	{
	  countdown = countdown - 1;
	  if ( countdown <= 0 )
	    drkill();
	}
      
      /* Reset up the destruct fuse. */
      Ships[Context.snum].sdfuse = -TIMEOUT_PLAYER;
      
      if ((pkttype = waitForPacket(PKT_FROMCLIENT, sockl, PKT_ANYPKT,
			buf, PKT_MAXSIZE, 1, NULL)) < 0)
	{
	  freeship();
	  clog("conquestd:menu: waitforpacket returned %d", pkttype); 
          handleSignal(0);
          /* not reached */

	  return;
	}
      
      if ( pkttype == 0 )	/* timeout */
	{
	  /* We get here if a packet hasn't been recieved. */
	  sleepy++;
	  if ( sleepy > 300 )
	    break;
	  continue; /* next */
	}

      switch(pkttype)
	{
	case CP_SETNAME:
	  procSetName(buf);
	  break;
	  
	case CP_AUTHENTICATE:
	  procChangePassword(buf);
	  break;

	case CP_COMMAND:
	  ccmd = (cpCommand_t *)buf;
	  if (ccmd->cmd == CPCMD_ENTER)
	    {			/* time to play */
	      playrv = play();
	      sInfo.state = SVR_STATE_MAINMENU;
	      if ( Context.childpid != 0 )
		countdown = 15;
	      else
		countdown = 0;
	      break;
	    }
	  else if (ccmd->cmd == CPCMD_RESIGN)
	    {
	      for ( i = 1; i <= MAXSHIPS; i = i + 1 )
                if ( !((Ships[i].status == SS_LIVE ||
		     Ships[i].status == SS_ENTERING) && 
		     Ships[i].unum == Context.unum))
		  {
		    clbResign( Context.unum, FALSE );
		    Ships[Context.snum].status = SS_OFF;
		    exit(0);	/* exit here */
		  }
	    }
	  else
	    {
	      handleSimpleCmdPkt((cpCommand_t *)buf);
	    }

	  break;

	default:
	  clog("conquestd: MENU: got unexp packet type %d", pkttype);
	  break;
	}
      
      /* Got a character, zero timeout. */
      
      sleepy = 0;
    }
  while ( clbStillAlive( Context.snum ) &&  !Context.leave );
  
  /* Make our ship available for others to use. */
  if ( Ships[Context.snum].status == SS_RESERVED )
    freeship();
  
  return;
  
}


/*  newship - create a new ship for a user (DOES LOCKING) */

/*  here we will fnd a ship for the client.  If the client has a VACANT
    ship it will return that ship, else it will get a new one.  No more
    multiples (for clients) supported currently I'm afraid..., if the
    client would be able to enter from multiple systems, this will be
    indicated by a non-zero esystems member of the clnt stat pkt */

/*  SYNOPSIS */
/*    int status, newship, unum, snum */
/*    int flag, newship */
/*    flag = newship( unum, snum ) */
int newship( int unum, int *snum )
{
  int i, j, system; 
  int fresh;
  int vec[MAXSHIPS];
  int numavail = 0;
  int numvec = 0;

  PVLOCK(&ConqInfo->lockword);
  
  Ships[*snum].status = SS_ENTERING;		/* show intent to fly */

  fresh = TRUE;				/* assume we want a fresh ship*/
  
  /* Count number of his ships flying. */
  j = 0;
  numvec = 0;
  for ( i = 1; i <= MAXSHIPS; i = i + 1 )
    if ( Ships[i].status == SS_LIVE || Ships[i].status == SS_ENTERING )
      if ( Ships[i].unum == unum && *snum != i )
	{
	  j++;
	  vec[numvec++] = i;
	}

  PVUNLOCK(&ConqInfo->lockword);

  if ( ! Users[unum].ooptions[OOPT_MULTIPLE] )
    {
      /* Isn't a multiple; see if we need to reincarnate. */
      if ( j > 0 )
	{
	  /* Need to reincarnate. */

	  if (!SVACANT(vec[0]))
	    {		   /* if it's available, we'll take it */
			   /* ...if it's not already being flown... */
	      sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_ERROR, PERR_FLYING, NULL);
	      Ships[*snum].status = SS_RESERVED;
	      return ( FALSE );
	    }


	  /* Look for a live ship for us to take. */
	  PVLOCK(&ConqInfo->lockword);
	  for ( i = 1; i <= MAXSHIPS; i = i + 1)
	    if ( Ships[i].unum == unum && Ships[i].status == SS_LIVE )
	      {
		fresh = FALSE;
		Ships[*snum].status = SS_OFF;
		*snum = i;
		Ships[*snum].pid = Context.pid;
		Ships[*snum].status = SS_ENTERING;
		bitClear(Ships[*snum].flags, SHIP_F_VACANT);
		break;
	      }
	  PVUNLOCK(&ConqInfo->lockword);
	}
    }
  else
    {				/* a multiple, so see what's available */
      PVLOCK(&ConqInfo->lockword);
      
      /* Count number of his ships flying. */
      j = 0;
      numvec = 0;
      for ( i = 1; i <= MAXSHIPS; i = i + 1 )
	if ( Ships[i].status == SS_LIVE || Ships[i].status == SS_ENTERING )
	  if ( Ships[i].unum == unum && *snum != i )
	    {
	      j++;
	      vec[numvec++] = i;
	      /* JET maybe we should turn off vacant ships for
		 multiples? */
	    }
      
      PVUNLOCK(&ConqInfo->lockword);
      
      /* Is a multiple, max ships already in and no ships to
	 reincarnate too */
      if ( j >= Users[unum].multiple && numavail == 0)
	{
	  sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_ERROR, PERR_TOOMANYSHIPS, 
		  NULL);
	  Ships[*snum].status = SS_RESERVED;
	  
	  return ( FALSE );
	}
      
      /* we can squeeze a new one in. */
	  
	  if ( j < Users[unum].multiple)
	    fresh = TRUE;
    }
  
  /* Figure out which system to enter. */
  if ( fresh )
    {
				/* (re)init the ship's team! (bug 1/10/98) */
      Ships[*snum].team = Users[Context.unum].team;
      Ships[*snum].shiptype = Teams[Ships[*snum].team].shiptype; 
      system = Ships[*snum].team;

      if ( ! capentry( *snum, &system ) )
	{
	  Ships[*snum].status = SS_RESERVED;
	  return ( ERR );
	}
    }
  else
    {
				/* now we clear ship's elapsed/cpu seconds
                                   so that there won't be a huge addition to
                                   the Teams/Users/Ships timing stats when
                                   a VACANT ships re-enters Conquest (in
				   case the signal handler didn't get a
				   chance to run) */
      Ships[*snum].ctime = 0;
      Ships[*snum].etime = 0;
    }

  PVLOCK(&ConqInfo->lockword);
  
  /* If necessary, initalize the ship */
  if ( fresh )
    {
      clbInitShip( *snum, unum );
      
      /* Randomly position the ship near the home sun (or planet). */
      if ( Planets[Teams[system].homeplanet].primary == Teams[system].homesun )
	i = Teams[system].homesun;
      else
	i = Teams[system].homeplanet;
      clPutShip( *snum, Planets[i].x, Planets[i].y );
      Ships[*snum].dhead = rnduni( 0.0, 359.9 );
      Ships[*snum].head = Ships[*snum].dhead;
      Ships[*snum].dwarp = (real) rndint( 2, 5 ) ;/* #~~~ this is a kludge*/
      Ships[*snum].lock = -Teams[system].homeplanet;
    }
  else
    {				/* if we're reincarnating, skip any
				   messages that might have been sent
				   while we were gone */
      PVLOCK(&ConqInfo->lockmesg);
      Ships[*snum].lastmsg = ConqInfo->lastmsg;
      Ships[*snum].alastmsg = Ships[*snum].lastmsg;
      PVUNLOCK(&ConqInfo->lockmesg);
      /* init user's last entry time */
      Users[Ships[*snum].unum].lastentry = getnow(NULL, 0);
    }
      
  SFCLR(*snum, SHIP_F_ROBOT);
  Ships[*snum].action = 0;
  
  
  /* Straighten out the ships deltas. */
  clbFixDeltas( *snum );
  
  /* Finally, turn the ship on. */
  Ships[*snum].status = SS_LIVE;
  
  PVUNLOCK(&ConqInfo->lockword);
  Context.entship = TRUE;

  return ( TRUE );
  
}


/*  play - play the game (PLAY) */
/*  SYNOPSIS */
/*    play */
int play(void)
{
  int laststat, now;
  int didsomething;             /* update immediately if we did anything */
  int rv;
  char msgbuf[128];
  int pkttype;
  Unsgn8 buf[PKT_MAXSIZE];
  int sockl[2] = {sInfo.sock, sInfo.usock};

  /* Can't carry on without a vessel. */
  if ( (rv = newship( Context.unum, &Context.snum )) != TRUE)
    {
      clog("conquestd:play: newship() returned %d",
	   rv);
      return(rv);
    }
  
  drstart();			/* start a driver, if necessary */
  Ships[Context.snum].sdfuse = 0;	/* zero self destruct fuse */
  grand( &Context.msgrand );		/* initialize message timer */
  Context.leave = FALSE;		/* assume we won't want to bail */
  Context.redraw = TRUE;		/* want redraw first time */
  Context.msgok = TRUE;		/* ok to get messages */
  Context.display = FALSE;		/* ok to get messages */
  stopUpdate();			/* stop the display interrupt */
  gsecs( &laststat );		/* initialize stat timer */

  /* send a clientstat packet and a ship packet. */

  if (!sendClientStat(sInfo.sock, SPCLNTSTAT_FLAG_NONE, Context.snum,
		      Ships[Context.snum].team,
		      Context.unum, 0))
    return FALSE;

  if (!sendShip(sInfo.sock, Context.snum))
    return FALSE;

  sInfo.state = SVR_STATE_PLAY;

  startUpdate();			/* setup for next interval */
  
  /* Tell everybody, we're here */

  sprintf(msgbuf, "%c%d (%s) has entered the game.",
	  Teams[Ships[Context.snum].team].teamchar,
	  Context.snum,
	  Ships[Context.snum].alias);
  
  clbStoreMsg(MSG_COMP, MSG_ALL, msgbuf);
  

  /* client updates will be handled by updateProc */
  /* While we're alive, field commands and process them. */
  while ( clbStillAlive( Context.snum ) )
    {
      /* Make sure we still control our ship. */
      if ( Ships[Context.snum].pid != Context.pid )
	break;

      didsomething = 0;
      if ((pkttype = waitForPacket(PKT_FROMCLIENT, sockl, PKT_ANYPKT,
				   buf, PKT_MAXSIZE, 0, NULL)) < 0)
	{
	  if (errno != EINTR)
	    {
	      clog("conquestd:play:waitForPacket: %s", strerror(errno));
              handleSignal(0);
              /* NOTREACHED */
	      return FALSE;
	    }
	}

      switch (pkttype)
	{
	case CP_SETCOURSE:
	  procSetCourse(buf);
          didsomething++;
	  break;
	  
	case CP_FIRETORPS:
	  procFireTorps(buf);
          didsomething++;
	  break;

	case CP_AUTHENTICATE:
	  procChangePassword(buf);
          didsomething++;
	  break;

	case CP_SETNAME:
	  procSetName(buf);
          didsomething++;
	  break;

	case CP_MESSAGE:
	  procMessage(buf);
          didsomething++;
	  break;

	case CP_COMMAND:
	  handleSimpleCmdPkt((cpCommand_t *)buf);
          didsomething++;
	  break;

	default:
	  if (pkttype != 0 && pkttype != -1)
	    clog("conquestd: play: got unexpected packet type %d", pkttype);
	  break;
	}

      if (didsomething)         /* update immediately if we did something */
        {
          clbBlockAlarm();
          updateClient(FALSE);
          clbUnblockAlarm();
        }

      grand( &Context.msgrand );
      Context.msgok = TRUE;
      
      /* See if it's time to update the statistics. */
      if ( dsecs( laststat, &now ) >= 15 )
	{
	  conqstats( Context.snum );
	  laststat = now;
	}

      if (didsomething)         
        continue;               /* see if there is another pkt */

      c_sleep(0.05);
    }
  
  conqstats( Context.snum );
  upchuck();
  
  /* Asts are still enabled, simply cancel the next screen update. */


  stopUpdate();
  updateClient(FALSE);	/* one last, to be sure. */
  sendConqInfo(sInfo.sock, TRUE);
  c_sleep( 2.0 );
  clog("INFO: ship %d died, calling dead()", Context.snum);
  dead( Context.snum, Context.leave );
  
  return(TRUE);
  
}



/*  SYNOPSIS */
/*    int flag, welcome */
/*    int unum */
/*    flag = welcome( unum ) */
int welcome( int *unum )
{
  int i, team; 
  char name[MAXUSERNAME];
  char password[MAXUSERNAME];	/* encrypted pw, "" if local */
  Unsgn8 flags = SPCLNTSTAT_FLAG_NONE;

  if (!Authenticate(name, password))
    return FALSE;

  sInfo.isLoggedIn = TRUE;

  if ( ! clbGetUserNum( unum, name, 0 ) )
    {				
      flags |= SPCLNTSTAT_FLAG_NEW;
      /* Must be a new player. */
      if ( ConqInfo->closed )
	{
	  sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_FATAL, PERR_CLOSED,
                  NULL);
	  return ( FALSE );
	}
      team = rndint( 0, NUMPLAYERTEAMS - 1 );
      clog("CONQD: TEAM = %d", team);
      
      cbuf[0] = EOS;
      apptitle( team, cbuf );
      appchr( ' ', cbuf );
      i = strlen( cbuf );
      appstr( name, cbuf );
      cbuf[i] = (char)toupper( cbuf[i] );

      if ( ! clbRegister( name, cbuf, team, unum ) )
	{
	  sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_FATAL, PERR_REGISTER,
                  NULL);
	  return ( FALSE );
	}

      clog("conquestd: clbRegister COMPLETE!!!! unum = %d, team = %d\n", 
	   *unum, team);

				/* copy in the password */
      strcpy(Users[*unum].pw, password);
				/* set lastentry time for new players */
      Users[*unum].lastentry = getnow(NULL, 0);

    }


  /* Must be special to play when closed. */
  if ( ConqInfo->closed && ! Users[*unum].ooptions[OOPT_PLAYWHENCLOSED] )
    {
      sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_FATAL, PERR_CLOSED,
	      NULL);
      clog("conquestd: welcome: game closed\n");
      return ( FALSE );
    }

  /* Can't play without a ship. */
  if ( ! clbFindShip( &Context.snum ) )
    {
      sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_FATAL, PERR_NOSHIP,
	      NULL);
      clog("WELCOME: findship failed");
      return ( FALSE );
    }

  /* send a clntstat packet if everything's ok */

  if (!sendClientStat(sInfo.sock, flags, Context.snum, Users[*unum].team, 
		     *unum, 0))
    return FALSE;

  /* send a user packet for the user as well. */
  if (sendUser(sInfo.sock, *unum) <= 0)
    return FALSE;

  return ( TRUE );
  
}


static int hello(void)
{
  spHello_t shello;
  Unsgn8 buf[PKT_MAXSIZE];
  char cbuf[MESSAGE_SIZE * 2];
  int pkttype;
  extern char *ConquestVersion, *ConquestDate;
  int rv;
  struct timeval tv;
  fd_set readfds;
  struct sockaddr_in usa;	/* internet socket addr. structure - udp */
  cpAck_t *cpack;
  int sockl[2] = {sInfo.sock, sInfo.usock};

  /* open a UDP socket and bind to it */
  if ((sInfo.usock = udpOpen(listenPort, &usa)) < 0)
    {
      clog("NET: SERVER hello: udpOpen() failed: %s", strerror(errno));
      sInfo.usock = -1;
      sInfo.tryUDP = FALSE;
    }

  /* first loadup and send a server hello */
  shello.type = SP_HELLO;
  shello.protover = (Unsgn16)htons(PROTOCOL_VERSION);

  shello.cmnrev = (Unsgn32)htonl(COMMONSTAMP);
  strncpy(shello.servername, SysConf.ServerName, CONF_SERVER_NAME_SZ);
  strncpy(shello.serverver, ConquestVersion, CONF_SERVER_NAME_SZ);
  strcat(shello.serverver, " ");
  strncat(shello.serverver, ConquestDate, 
         (CONF_SERVER_NAME_SZ - strlen(ConquestVersion)) - 2);
  strncpy(shello.motd, SysConf.ServerMotd, CONF_SERVER_MOTD_SZ);
  shello.flags = 0;

  if (ConqInfo->closed)
    shello.flags |= SPHELLO_FLAGS_CLOSED;

  if (!writePacket(PKT_TOCLIENT, sInfo.sock, (Unsgn8 *)&shello))
    {
      clog("NET: SERVER: hello: write shello failed\n");
      return FALSE;
    }

  clog("NET: SERVER: hello: sent server hello to client");

  if (sInfo.tryUDP)
    {
      /* wait a few seconds to see if client sends a udp */
      tv.tv_sec = 5;
      tv.tv_usec = 0;
      FD_ZERO(&readfds);
      FD_SET(sInfo.usock, &readfds);
      if ((rv = select(sInfo.usock+1, &readfds, NULL, NULL, &tv)) <= 0)
        {
          if (rv == 0)
            clog("NET: SERVER: hello: udp select timed out. No UDP");
          else
            clog("NET: SERVER: hello: udp select failed: %s", strerror(errno));

          sInfo.tryUDP = FALSE;
        }
      else
        {
          if (FD_ISSET(sInfo.usock, &readfds))
            {                       /* get the packet, almost done negotiating udp */
              rv = udpRecv(sInfo.usock, buf, PKT_MAXSIZE, &sInfo.clntaddr);
              clog("NET: SERVER: hello: got %d UDP bytes from client port %d", rv, 
                   (int)ntohs(sInfo.clntaddr.sin_port));
              
              if (connect(sInfo.usock, (const struct sockaddr *)&sInfo.clntaddr, 
                          sizeof(sInfo.clntaddr)) < 0)
                {
                  clog("NET: SERVER: hello: udp connect() failed: %s", strerror(errno));
                  sInfo.tryUDP = FALSE;
                }
            }
        }
    }

  /* now we want a client hello in response */
  if ((pkttype = readPacket(PKT_FROMCLIENT, sockl, buf, PKT_MAXSIZE, 60)) < 0)
  {
    clog("NET: SERVER: hello: read client hello failed, pkttype = %d",
         pkttype);
    return FALSE;
  }

  if (pkttype == 0)
  {
    clog("NET: SERVER: hello: read client hello: timeout.\n");
    return FALSE;
  }

  if (pkttype != CP_HELLO)
  {
    clog("NET: SERVER: hello: read client hello: wrong packet type %d\n", pkttype);
    return FALSE;
  }

  chello = *(cpHello_t *)buf;

  /* fix up byte ordering */
  chello.protover = ntohs(chello.protover);
  chello.cmnrev = ntohl(chello.cmnrev);

  chello.clientname[CONF_SERVER_NAME_SZ - 1] = 0;
  chello.clientver[CONF_SERVER_NAME_SZ - 1] = 0;

  clog("CLIENTID:%s:%s:%d:0x%04hx:%d",
       chello.clientname, 
       chello.clientver,
       chello.updates, 
       chello.protover, 
       chello.cmnrev);

  /* do some checks - send a NAK and fail if things aren't cool */
  if (chello.protover != PROTOCOL_VERSION)
    {
      sprintf(cbuf, "SERVER: Protocol mismatch, server 0x%x, client 0x%x",
	      PROTOCOL_VERSION, chello.protover);
      sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_FATAL, PERR_BADPROTO, cbuf);
      clog("NET: %s", cbuf);
      return FALSE;
    }

  if (chello.cmnrev != COMMONSTAMP)
    {
      sprintf(cbuf, "SERVER: commonblock mismatch, expected %d, got %d",
	      COMMONSTAMP, chello.cmnrev);
      sendAck(sInfo.sock, PKT_TOCLIENT, PSEV_FATAL, PERR_BADCMN, cbuf);
      clog("NET: %s", cbuf);
      return FALSE;
    }

  if (chello.updates >= 1 && chello.updates <= 10)
    Context.updsec = chello.updates;

  /* send a server stat to the udp client socket.  If the client gets
     it, it will acknowlege it in it's ACK packet, which will tell us
     we can do udp. woohoo! */
  if (sInfo.tryUDP)
    sendServerStat(sInfo.usock);

  /* now send the server stats normally */
  if (!sendServerStat(sInfo.sock))
    {
      clog("NET: SERVER: hello: sendServerStat failed");
      return FALSE;
    }

  /* now we want an ack.  If we get it, we're done! */
  if ((pkttype = readPacket(PKT_FROMCLIENT, sockl, buf, PKT_MAXSIZE, 60)) < 0)
    {
      clog("NET: SERVER: hello: read client Ack failed");
      return FALSE;
    }

  if (pkttype != CP_ACK)
    {
      clog("NET: SERVER: hello: got packet type %d, expected CP_ACK", 
           pkttype);
      return FALSE;
    }

  if (sInfo.tryUDP)
    {
      /* see if the client could read our udp */
      cpack = (cpAck_t *)buf;
      if (cpack->code == PERR_DOUDP)
        {
          sInfo.doUDP = TRUE;
          clog("NET: SERVER: hello: Client acknowleged UDP from server. Doing UDP.");
        }
    }

  return TRUE;
}

void catchSignals(void)
{
  signal(SIGHUP, (void (*)(int))handleSignal);
  signal(SIGTSTP, SIG_IGN);
  signal(SIGTERM, (void (*)(int))handleSignal);
  signal(SIGINT, (void (*)(int))handleSignal);
  signal(SIGPIPE, (void (*)(int))handleSignal);
  signal(SIGQUIT, (void (*)(int))handleSignal);

  return;
}

void handleSignal(int sig)
{
  stopUpdate();

  if (sig)
    clog("conquestd: exiting on signal %d", sig);
  
  if (sInfo.state == SVR_STATE_PLAY)
    {
      if (SysConf.AllowVacant)
        {			/* this allows vacant ships */
          drpexit();
          conqstats(Context.snum);          /* update stats */
          /* now we clear ship's elapsed/cpu seconds so
             that there won't be a huge addition to the
             Teams/Users/Ships timing stats when a VACANT
             ships re-enters Conquest */
          Ships[Context.snum].ctime = 0;
          Ships[Context.snum].etime = 0;
          
          SFSET(Context.snum, SHIP_F_VACANT); /* help the driver */
        }
      else
        {
          /* so we can detect cowards */
          clbKillShip( Context.snum, KB_LIGHTNING );
          /* turn ship off */
          Ships[Context.snum].status = SS_OFF;
        }
    }
  else
    {                       /* not playing (main menu, etc) */
      /* if we aren't playing, then just turn it off */
      if (Context.snum >= 1 && Context.snum <= MAXSHIPS)
        Ships[Context.snum].status = SS_OFF;
    }

  conqend();
  exit(0);

}

/*  conqend - machine dependent clean-up */
/*  SYNOPSIS */
/*    conqend */
void conqend(void)
{

  char msgbuf[128];

  if (Context.entship == TRUE)
    {				/* let everyone know we're leaving */
      sprintf(msgbuf, "%s has left the game.",
	      Users[Context.unum].alias);
      clbStoreMsg(MSG_COMP, MSG_ALL, msgbuf);
    }
  
  recordCloseOutput();

  return;
  
}