File: net.c

package info (click to toggle)
xshipwars 1.32-5
  • links: PTS
  • area: main
  • in suites: potato
  • size: 17,176 kB
  • ctags: 6,357
  • sloc: ansic: 157,152; makefile: 226; sh: 75
file content (1497 lines) | stat: -rw-r--r-- 39,022 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
/*
	                 General Network Functions

	Functions:

	int NetConGuests()

	int NetManageNewConnections(int socket)
	void NetCloseConnection(int condescriptor)

        int NetSendDataToConnection(
                int condescriptor,
                char *data,
                int priority
	)
	void NetDoSend(int condescriptor, char *sndbuf)
	int NetManageSend()

	int NetHandleExtCmd(int condescriptor, char *arg)
	int NetManageRecvConnection(int condescriptor)
	int NetManageRecv()

	---
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "../include/netio.h"

#include "swserv.h"
#include "siteban.h"



/*
 *	Returns the current number of guest connections.
 */
int NetConGuests()
{
        int gcon = 0;
	connection_struct **con_ptr, **end_ptr;


        for(con_ptr = connection,
            end_ptr = connection + total_connections;
            con_ptr < end_ptr;
            con_ptr++
	)
        {
            if(*con_ptr == NULL)
		continue;

            if((*con_ptr)->socket < 0)
                continue;

            if((*con_ptr)->is_guest)
                gcon++;
        }


        return(gcon);
}



/*
 *	Checks listening socket for incoming connections
 *	and processes them.  Returns non-zero on error.
 */
int NetManageNewConnections(int socket)
{
	int i, n;
	int condescriptor;
	connection_struct *con_ptr;

	int sin_size;
	int new_socket;
	struct sockaddr_in foreign_addr;

	siteban_ip_union ip;

	char sndbuf[CS_DATA_MAX_LEN];
	char text[512];



	/*   Check if listening socket has any queued incoming
         *   connection(s).
	 */
	if(!NetIsSocketReadable(socket, NULL))
	    return(0);


	/* `Answer' new connection. */
        sin_size = sizeof(struct sockaddr_in);
        new_socket = accept(
	    socket,
	    (struct sockaddr *)&foreign_addr,
            &sin_size
	);
	if(new_socket == -1)
	    return(-1);

	/* Set socket nonblocking. */
	fcntl(new_socket, F_SETFL, O_NONBLOCK);


	/* Get IP (in nbo). */
	ip.whole = foreign_addr.sin_addr.s_addr;

	/* Is this IP banned? */
	if(SiteBanIsBanned(&ip, 0))
	{
            sprintf(sndbuf,
                "%i Your address %i.%i.%i.%i has been banned.\n",
                CS_CODE_LIVEMESSAGE,
                ip.part_u8[0],
                ip.part_u8[1],
                ip.part_u8[2],
                ip.part_u8[3]
            );
            send(new_socket, sndbuf, strlen(sndbuf), 0);
            sprintf(sndbuf,
                "%i\n",
                CS_CODE_LOGOUT  
            );
            send(new_socket, sndbuf, strlen(sndbuf), 0);
 
            close(new_socket);

	    /* Pretend like we didn't do anything. */
	    return(0);
	}



        /* Do we have room for new connection? */
        for(i = 0, n = 0; i < total_connections; i++)
        {       
            if(connection[i] == NULL)
                continue;

            if(connection[i]->socket < 0)
                continue;

            n++;
        }
        if(n >= sysparm.max_connections)
	{
            sprintf(sndbuf,
                "%i Maximum of %i connections reached.\n",
		CS_CODE_LIVEMESSAGE,
                sysparm.max_connections
            );
            send(new_socket, sndbuf, strlen(sndbuf), 0);
            sprintf(sndbuf,
                "%i\n",
                CS_CODE_LOGOUT
            );
            send(new_socket, sndbuf, strlen(sndbuf), 0);

            close(new_socket);

            return(-3);
	}


	/* Get a new connection descriptor for new connection. */
	condescriptor = ConCreateNew();
	if(ConIsAllocated(condescriptor))
	{
            con_ptr = connection[condescriptor];
	}
	else
	{
	    sprintf(
		text,
		"Error: Unable to allocate new connection structure."
	    );
	    if(sysparm.log_net)
	        LogAppendLineFormatted(fname.primary_log, text);

	    close(new_socket);
	    new_socket = -1;

	    return(-3);
	}


	/* Reset some statistics for the new connection. */
        con_ptr->contime = time(NULL);

        con_ptr->obj_ud_interval = DEF_NET_UPDATE_INT;
	con_ptr->obj_ud_next = cur_millitime;


        /* Add data for members of connection structure. */
        con_ptr->socket = new_socket;
	strncpy(
	    con_ptr->conhost,
	    inet_ntoa(foreign_addr.sin_addr),
	    HOST_NAME_MAX
	);
	con_ptr->conhost[HOST_NAME_MAX - 1] = '\0';


        /*   We don't give connection a new object untill they send
         *   us a valid name and password.
         */
        con_ptr->object_num = -1;


        /* Log newly allocated descriptor for connection. */
        if(!sysparm.console_quiet)
            fprintf(
                stdout,
                "Connection %i: Got connection from `%s'.\n",
                condescriptor,
                con_ptr->conhost
            );

	sprintf(text,
            "Connection %i: Got connection from `%s'.",
            condescriptor,
	    con_ptr->conhost
        );
        if(sysparm.log_net)
            LogAppendLineFormatted(fname.primary_log, text);


	/* Request new connection for login name and password. */
	NetSendLogin(condescriptor);


	return(0);
}


/*
 *	Procedure to close a connection.
 *
 *	If the connection's socket is connected, then a
 *	CS_CODE_LOGOUT is sent before closing its socket.
 *
 *      If the connection is a guest connection, it's guest object
 *      will be recycled.
 *
 *      The connection will be recycled.
 */
void NetCloseConnection(int condescriptor)
{
	int i;
        long object_num, object_count;
	xsw_object_struct **obj_ptr;
	connection_struct *con_ptr;
        char text[1024];
        char sndbuf[CS_DATA_MAX_LEN + 256];



        /* Make sure condescriptor is allocated. */
        if(ConIsAllocated(condescriptor))
	    con_ptr = connection[condescriptor];
	else
	    return;


        /* Check if the connection's socket is connected. */
        if(con_ptr->socket > -1)
        {
	    /* Send a logout to the connection.
	     * If there was an error sending to the connection,
	     * then this function NetCloseConnection() is called
	     * again but the socket will already be closed and set
	     * to -1.
	     */
	    NetSendLogout(condescriptor);

	    /* If NetSendLogout() deallocated this connection, then
	     * give up.
	     */
	    if(ConIsAllocated(condescriptor))
                con_ptr = connection[condescriptor];
            else
                return;


	    /* NetSendLogout() may have already closed this socket. */
	    if(con_ptr->socket > -1)
	    {
		/* Nope, it did not close it so we need to close it. */
                close(con_ptr->socket);
                con_ptr->socket = -1;
	    }

            /* Notify console of disconnect as needed. */
	    if(!sysparm.console_quiet)
	    {
	        if(DBIsObjectGarbage(con_ptr->object_num))
	            fprintf(
		        stdout,
		        "Connection %i: *Unknown* disconnected.\n",
		        condescriptor
                    );
	        else
                    fprintf(   
                        stdout,
                        "Connection %i: %s disconnected.\n",
		        condescriptor,
                        DBGetFormalNameStr(con_ptr->object_num)
                    );
	    }

	    /* Log disconnect. */
            if(DBIsObjectGarbage(con_ptr->object_num))
                sprintf(text,
	            "Connection %i: Disconnected.",
                    condescriptor
	        );
	    else
                sprintf(text,
                    "Connection %i: %s disconnected.",
		    condescriptor,
                    DBGetFormalNameStr(con_ptr->object_num)
		);
	    if(sysparm.log_net)
		LogAppendLineFormatted(fname.primary_log, text);
	}


        /* Begin recycling connection. */

        /*   Recycle object associated with connection if
         *   connection is a guest connection.
         *
         *   WARNING: DBRecycleObject() should be called after the
         *   connection is closed and reset or else DBRecycleObject()
         *   will call *this* function to close if the object is a player
         *   (and the object IS usually a player).
         */
	object_num = con_ptr->object_num;
        if(DBIsObjectGarbage(object_num))
	{
            /* Object is invalid, so just recycle connection. */ 
            ConRecycle(condescriptor);
	}
	else
	{
	    /* Connection's object is valid.*/

	    /* Notify all connections of disconnect (as needed). */
	    if(sysparm.con_notify)
	    {
	        strncpy(
		    sndbuf,
		    "%name has disconnected.",
		    CS_DATA_MAX_LEN
		);
	        sndbuf[CS_DATA_MAX_LEN - 1] = '\0';
                substr(sndbuf, "%name", xsw_object[object_num]->name);

	        for(i = 0; i < total_connections; i++)
	        {
		    if(connection[i] == NULL)
		        continue;
		    if(connection[i]->socket < 0)
                        continue;
		    if(connection[i]->object_num < 0)
		        continue;
		    if(i == condescriptor)
		        continue;

		    NetSendLiveMessage(i, sndbuf);
	        }

		/* Mark object as not connected. */
		xsw_object[object_num]->server_options &= ~(XSW_OBJF_CONNECTED);

		/*   Mark object hidden as needed and if within bounds of
		 *   a HOME object.
		 */
		if(sysparm.hide_players)
		{
		    /* Go through XSW objects list. */
		    for(object_count = 0, obj_ptr = xsw_object;
                        object_count < total_objects;
		        object_count++, obj_ptr++
		    )
		    {
			/* Skip if not a HOME object. */
			if((*obj_ptr)->type != XSW_OBJ_TYPE_HOME)
			    continue;

			/* Is our object in contact with this object? */
		        if(Mu3DInContactPtr(*obj_ptr, xsw_object[object_num]))
		        {
			    /* Mark it hidden from connections. */
                            xsw_object[object_num]->server_options |=
				(XSW_OBJF_HIDEFROMCON);

			    break;
			}
		    }
		}
	    }	/* if(sysparm.con_notify) */
/* Quick debug check. */
/*
printf("Our con_ptr (stage 2) = 0x%.8x\n", (unsigned int)con_ptr);
for(i = 0; i < total_connections; i++)
{
	if(connection[i] == NULL)
	    continue;
	if(connection[i]->socket < 0)
	{  }

	printf("Connection %i: ptr 0x%.8x\n", i, (unsigned int)con_ptr);
}
 */
	    /* Check if connection is a guest connection. */
	    if(con_ptr->is_guest)
            {
                /*   Is a guest connection, so recycle connection
		 *   and object.
		 */
                ConRecycle(condescriptor);

		NetSendRecycleObject(-1, object_num);
                DBRecycleObject(object_num);
            }
            else
            {
                /*   Not a guest connection, so just recycle
		 *   connection.
		 */
                ConRecycle(condescriptor);
	    }
        }

        return;
}


/*
 *      Sends sndbuf to condescriptor or to all connections if
 *      condescriptor is -1.
 * 
 *      The priority will be 1 if the condescriptor is not -1
 *      and the priority will be 2 if the condescriptor is -1.
 */
void NetDoSend(int condescriptor, char *sndbuf)
{
        int i;
	connection_struct **ptr, *con_ptr;


        if(condescriptor == -1)
        {
	    /* Send to all connections. */
            for(i = 0, ptr = connection;
                i < total_connections;
                i++, ptr++
	    )
            {
		con_ptr = *ptr;
		if(con_ptr == NULL)
		    continue;
		if(con_ptr->socket < 0)
		    continue;

                NetSendDataToConnection(
                    i,
                    sndbuf,
                    2               /* Send priority bulk. */
                );
            }
        }  
        else
        {
	    /* Send to specific connection. */
            NetSendDataToConnection(
                condescriptor,
                sndbuf,   
                1               /* Send priority queue as needed. */
            );
        }


        return;
}

/*
 *      Sends data to the connection, queing it as needed.
 *      
 *      Before the data is sent however, if any queued data in the
 *      connection is buffered, the queued data will be sent first.
 * 
 *      Priority can be 1 or 2.
 * 
 *      1 means the data will be queued as needed, 2 means the
 *      data will be sent on the `first try' and discarded if it fails.
 */
int NetSendDataToConnection(
        int condescriptor,
        char *data, 
        int priority
)
{
        int i, s, n, l, buf_len, error_level;
	int bytes_sent = 0;

        long object_num;
        connection_struct *con_ptr;

	conbuf_struct *qbuf;
	int total_qbufs, cur_qbufs;     

	char text[256];


        if(data == NULL)
	    return(-1);
	if(*data == '\0')
	    return(0);

        if(ConIsConnected(condescriptor))
	    con_ptr = connection[condescriptor];
	else
	    return(-1);



        /* Get connection's socket. */
        s = con_ptr->socket;

        /* Get length of data to be sent. */
        buf_len = strlen(data);
        if(buf_len >= CS_DATA_MAX_LEN)
            return(-1);


        /* Make sure there is a newline character. */
/*
        if(strchr(data, '\n') == NULL)
        {
            sprintf(text,
  "NetSendDataToConnection(): data missing newline character, not sent."
            );
            if(sysparm.log_errors)
                LogAppendLineFormatted(fname.primary_log, text);

            sprintf(
		text,
                "NetSendDataToConnection(): `%s'",
                data
            );
            if(sysparm.log_errors)
                LogAppendLineFormatted(fname.primary_log, text);
        
        
            return(-1);
        }
*/ 

        /* ********************************************************** */
        /* Send out queued buffers in connection first. */

	cur_qbufs = con_ptr->conbuf_items;

	/* Any queued buffers to send? */
	if(cur_qbufs > 0)
	{
	    total_qbufs = MAX_CON_BUF_ITEMS;
	    qbuf = con_ptr->conbuf;

	    if(cur_qbufs > total_qbufs) 
                cur_qbufs = total_qbufs;

	    /* Send each queued line. */
	    for(i = 0; i < cur_qbufs; i++)
	    {
                /* Check if socket is writeable. */
                if(NetIsSocketWritable(s, &error_level))
                {
                    /* Socket is writeable. */

                    bytes_sent += send(
                        s,
                        qbuf[i].buffer,
                        strlen(qbuf[i].buffer),
                        0
                    );
	        }
	        else
	        {
	            /* Could not send, see what error was. */

		    con_ptr->errors_sent++;

		    switch(error_level)
		    {
		      case 3:
                        /*   Must force close before calling
		         *   NetCloseConnection().
		         */
                        close(con_ptr->socket);
                        con_ptr->socket = -1;

                        NetCloseConnection(condescriptor);

			return(-1);
		        break;

		      default:
		        break;
		    }
                    break;
	        }
            }
	    if(i < cur_qbufs)
	    {
		/* Not able to send out all queued buffers. */

		/* Shift remaining queued buffers. */
		if(i > 0)
		{
		    for(n = 0, l = i;
                        l < total_qbufs;
                        n++, l++
		    )
		    {
		        if(l >= cur_qbufs)
			    break;

		        memcpy(
			    qbuf[n].buffer,		/* Target. */
			    qbuf[l].buffer,		/* Source. */
			    CS_DATA_MAX_LEN
		        );
		    }

		    /* Set new amount of queued buffers. */
		    con_ptr->conbuf_items = n;
		}
	    }
	    else
	    {
		/* All queued buffers sent! */

		/* Reset number of queued buffers on connection. */
		con_ptr->conbuf_items = 0;
	    }
	}


        /* ******************************************************* */
        /* Send out data. */

        /*
         *   Check Priority:
         *
         *      0 = Highest, force send for up to 5 seconds.
         *      1 = Moderate, try to send. If cannot then put into
         *          connection's buffer.
         *      2 = Lowest, try to send, If cannot then forget it.
         */
        switch(priority)
        {
          case 0:
            fprintf(stderr,
       "NetSendDataToConnection(): Priority 0 not supported.\n"
            );
            break;

	  /* High send priority. */
	  case 1:

	    if(NetIsSocketWritable(s, &error_level))
                bytes_sent += send(s, data, buf_len, 0);

            if(error_level)
            {
                /* Socket is not writeable or there was an error. */

                switch(error_level)
                {
		  /* Sever error. */
                  case 3:
                    /*   Must force close before calling
                     *   NetCloseConnection().
                     */
                    close(con_ptr->socket);
                    con_ptr->socket = -1;

                    NetCloseConnection(condescriptor);
                    break;

                  /* Other error. */
                  default:
                    /* Can't send, general error, so queue it. */
                    cur_qbufs = con_ptr->conbuf_items;   
                    if(cur_qbufs < MAX_CON_BUF_ITEMS)
                    {
                        strcpy(
                            con_ptr->conbuf[cur_qbufs].buffer,
                            data
                        );
                        cur_qbufs++;

                        con_ptr->conbuf_items = cur_qbufs;
                    }
                    break;
                }

                con_ptr->errors_sent++;
            }
	    break;

	  /* Low send priority. */
          default:

            if(NetIsSocketWritable(s, &error_level))  
                bytes_sent += send(s, data, buf_len, 0);

            if(error_level)
            {
                /* Socket is not writeable or there was an error. */

                switch(error_level)
                {
                  /* Sever error. */
                  case 3:
                    /*   Must force close before calling
                     *   NetCloseConnection().
                     */
                    close(con_ptr->socket);
                    con_ptr->socket = -1; 
                    NetCloseConnection(condescriptor);
		    return(-1);

                    break;

		  default:
                    break;
		}

                con_ptr->errors_sent++;
            }
            break;
        }

        /* Update number of bytes sent on that connection. */
        con_ptr->bytes_sent += bytes_sent;


        return(0);
}

/*
 *      Procedure to send out schedualed network data to all
 *      connections.
 */
int NetManageSend()
{
	int con_num;
        long object_num, object_count;
        int trac_obj_num;
        int wep_num;

	xsw_object_struct *con_obj_ptr;

	connection_struct **con_ptr;
	xsw_object_struct **obj_ptr;


	/* Send object poses. */
	/* Go through connections list. */
        for(con_num = 0, con_ptr = connection;
            con_num < total_connections;
            con_num++, con_ptr++
	)
        {
            /* Is connection valid and logged in? */
            if(*con_ptr == NULL)
		continue;

            object_num = (*con_ptr)->object_num;
	    if(DBIsObjectGarbage(object_num))
		continue;
	    else
		con_obj_ptr = xsw_object[object_num];


            /* Connection due to recieve XSW object updates? */
            if((*con_ptr)->obj_ud_next <= cur_millitime)
            {
                /* Go through XSW objects list. */
                for(object_count = 0, obj_ptr = xsw_object;
                    object_count < total_objects;
                    object_count++, obj_ptr++
                )
                {
                    /* Check if objects are valid and in range. */
                    if(!Mu3DInRangePtr(con_obj_ptr, *obj_ptr,
                        con_obj_ptr->scanner_range
                    ))
                        continue;

                    /*   If object is not owned by the connection,
		     *   then check the visibility of the object.
		     */
                    if((*obj_ptr)->owner != object_num)
                    {
                        if(DBGetObjectVisibilityPtr(*obj_ptr)
                           <= 0.00
                        )
                            continue;
                    }

		    /* Check if marked hidden from connection. */
		    if((*obj_ptr)->server_options & XSW_OBJF_HIDEFROMCON)
			continue;
       
                    /* Send object position (pose). */
                    NetSendObjectPose(con_num, object_count);
                }

                /* Schedual next. */ 
                (*con_ptr)->obj_ud_next = cur_millitime +
                    (*con_ptr)->obj_ud_interval;
            }
        }


        /* Time to send standard XSW object values? */
        if(next.object_values <= cur_millitime)
        {
	    /* Send object values. */
	    /* Go through connections. */
            for(con_num = 0,
                con_ptr = connection;
                con_num < total_connections;
                con_num++, con_ptr++
            )
            {
                /* Is connection valid and logged in? */
                if(*con_ptr == NULL)
                    continue;
                object_num = (*con_ptr)->object_num;
                if(DBIsObjectGarbage(object_num))  
                    continue;
                else
                    con_obj_ptr = xsw_object[object_num];


                /* Go through XSW objects list. */
                for(object_count = 0, obj_ptr = xsw_object;
                    object_count < total_objects;
                    object_count++, obj_ptr++
                )
                {
                    /* Check if objects are valid and in range. */
                    if(!Mu3DInRangePtr(con_obj_ptr, *obj_ptr,
                        con_obj_ptr->scanner_range
                    ))
			continue;

		    /* Not owned objects, check for visibility. */
		    if((*obj_ptr)->owner != object_num)
		    {
			if(DBGetObjectVisibilityPtr(*obj_ptr)
			   <= 0.00
			)
			    continue;
		    }

                    /* Check if marked hidden from connection. */
                    if((*obj_ptr)->server_options & XSW_OBJF_HIDEFROMCON)
                        continue;


                    /* Send standard values. */
                    NetSendObjectValues(con_num, object_count);

                    /* Send sector. */
                    NetSendObjectSect(con_num, object_count);

                    /* Send object maximum values. */
                    NetSendObjectMaximums(con_num, object_count);
                }
            }

            /* Schedual next object values send. */
            next.object_values = cur_millitime +
                sysparm.int_object_values;
        }


        /* Time to send weapon values? */
        if(next.weapon_values <= cur_millitime)
        {
	    /* Send weapon values. */

            /* Go through connections. */
            for(con_num = 0, con_ptr = connection;
                con_num < total_connections; 
                con_num++, con_ptr++
            )
            {
                /* Is connection valid and logged in? */
                if(*con_ptr == NULL)
                    continue;
                object_num = (*con_ptr)->object_num;
                if(DBIsObjectGarbage(object_num))
                    continue;
                else
                    con_obj_ptr = xsw_object[object_num];


                /* Go through XSW objects list. */
                for(object_count = 0, obj_ptr = xsw_object;
                    object_count < total_objects;
                    object_count++, obj_ptr++
                )
                {
                    /* Check if objects are valid and in range. */
                    if(!Mu3DInRangePtr(con_obj_ptr, *obj_ptr,
                        con_obj_ptr->scanner_range
                    ))
                        continue;

                    /* Not owned objects, check for visibility. */
                    if((*obj_ptr)->owner != object_num)
                    {
                        if(DBGetObjectVisibilityPtr(*obj_ptr)
                           <= 0.00 
                        )  
                            continue;
                    }

                    /* Check if marked hidden from connection. */
                    if((*obj_ptr)->server_options & XSW_OBJF_HIDEFROMCON)
                        continue;


                    /* Send all weapons values. */
                    for(wep_num = 0;
                        wep_num < (*obj_ptr)->total_weapons;
                        wep_num++
                    )
                    {
                        NetSendWeaponValues(
                            con_num,
                            object_count,
                            wep_num
                        );
                    }

                    /* Send tractor beam lock. */
                    for(trac_obj_num = 0;
                        trac_obj_num < (*obj_ptr)->total_tractored_objects;
                        trac_obj_num++
                    )
                    {
                        NetSendTractorBeamLock(
                            con_num,
                            object_count,
                            (*obj_ptr)->tractored_object[trac_obj_num]
                        );
                    }
                }
            }

            /* Schedual next weapons update. */
            next.weapon_values = cur_millitime +
                sysparm.int_weapon_values;
        }


        return(0);
}



/*
 *      Handles an XSW extended command.
 *
 *      (This function called by NetHandleConnection() as needed.)
 */
int NetHandleExtCmd(int condescriptor, char *arg)
{
	char *strptr;
        char ext_arg[CS_DATA_MAX_LEN];
        int ext_cmd;


	/* condescriptor and arg assumed valid. */


        /* Get command and argument. */          
        ext_cmd = StringGetNetCommand(arg);
        if(ext_cmd < 0)
            return(-1);

	strptr = StringGetNetArgument(arg);
	if(strptr == NULL)
	    return(-1);
        strncpy(ext_arg, strptr, CS_DATA_MAX_LEN);
        ext_arg[CS_DATA_MAX_LEN - 1] = '\0';
            

        /* ****************************************************** */
        /* Handle extended command. */

        switch(ext_cmd)
        {
	  /* System and enviroment. */
          case SWEXTCMD_SETOCSN:
            NetHandleSetOCSN(condescriptor, ext_arg);
            break;

	  case SWEXTCMD_SETUNITS:
	    NetHandleSetUnits(condescriptor, ext_arg);
            break;


          /* Standards. */
          case SWEXTCMD_STDOBJVALS:
            NetHandleObjectValues(condescriptor, ext_arg);
            break;

          case SWEXTCMD_STDOBJMAXS:
            /* Server does not accept set object maximums. */
            break;
        
          case SWEXTCMD_STDWEPVALS:
            /* Server does not accept set weapon values. */
            break;
            

          /* Set. */  
          case SWEXTCMD_SETOBJNAME:
            /* Server does not accept set names. */
            break;
   
          case SWEXTCMD_SETOBJSECT:
            NetHandleObjectSect(condescriptor, ext_arg);
            break;

         case SWEXTCMD_SETFOBJSECT:
	    /* Handle this as SWEXTCMD_SETOBJSECT. */
            NetHandleObjectSect(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETTHROTTLE:
            NetHandleObjectThrottle(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETWEAPON:
            NetHandleSelectWeapon(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETINTERCEPT:
            NetHandleSetIntercept(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETWEPLOCK:
            NetHandleSetWeaponsLock(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETSHIELDS:
            NetHandleSetShields(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETDMGCTL:
            NetHandleSetDmgCtl(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETCLOAK:
            NetHandleSetCloak(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETSHIELDVIS:
            /* Server does not handle this command. */
            break;

          case SWEXTCMD_SETLIGHTING:
            NetHandleLighting(condescriptor, ext_arg);
            break;

	  case SWEXTCMD_SETCHANNEL:
	    NetHandleSetChannel(condescriptor, ext_arg);
	    break;

	  case SWEXTCMD_SETSCORE:
	    NetHandleScore(condescriptor, ext_arg);
            break;

          case SWEXTCMD_SETENGINE:
            NetHandleSetEngine(condescriptor, ext_arg);
            break;


          /* Requests. */
          case SWEXTCMD_REQNAME:
            NetHandleObjectName(condescriptor, ext_arg);
            break;

          case SWEXTCMD_REQSECT:
            NetHandleReqObjectSect(condescriptor, ext_arg);
            break;


          /* Notifies. */
          case SWEXTCMD_NOTIFYHIT:
            break;


          /* Actions. */
          case SWEXTCMD_FIREWEAPON:
            NetHandleFireWeapon(condescriptor, ext_arg);
            break;

          case SWEXTCMD_TRACTORBEAMLOCK:
            NetHandleTractorBeamLock(condescriptor, ext_arg);
            break;

	  case SWEXTCMD_HAIL:
	    NetHandleHail(condescriptor, ext_arg);
	    break;

	  case SWEXTCMD_COMMESSAGE:
	    NetHandleComMesg(condescriptor, ext_arg);
	    break;


	  /* Economy. */
	  case SWEXTCMD_ECO_REQVALUES:
            NetHandleReqValues(condescriptor, ext_arg);
	    break;

	  case SWEXTCMD_ECO_SETVALUES:
	    break;

	  case SWEXTCMD_ECO_SETPRODUCTVALUES:
	    break;

	  case SWEXTCMD_ECO_BUY:
	    NetHandleEcoBuy(condescriptor, ext_arg);
	    break;

	  case SWEXTCMD_ECO_SELL:
	    NetHandleEcoSell(condescriptor, ext_arg);
	    break;



          default:
            break;
        }   


        return(0);
}


/*
 *      Checks and processes incoming network data on
 *      connection condescriptor.
 *
 *	Warning condescriptor is assumed to be valid.
 */
int NetManageRecvConnection(int condescriptor)
{
        static char recvbuf[CS_DATA_MAX_BACKLOG];
        static int recvbuf_cnt;
	static char *recvbuf_ptr;

        static char workbuf[CS_DATA_MAX_LEN];
        static int workbuf_cnt;
        static char *workbuf_ptr;

        static char arg[CS_DATA_MAX_LEN];
        static int command;

        static int bytes_read;

        static char stringa[CS_DATA_MAX_LEN];
        static int socket;


        /* Get socket (condescriptor is assumed valid). */
        socket = connection[condescriptor]->socket;
 

        /* Is socket valid and contains data to be read? */
        if(!NetIsSocketReadable(socket, NULL))
            return(0);

        /* Recieve incoming data. */
        bytes_read = recv(socket, recvbuf, CS_DATA_MAX_BACKLOG, 0);
        if(bytes_read == 0)
	{
	    /*   When polling of socket says there are bytes to be
	     *   read and recv() returns 0, it implies that the
	     *   socket has died.
	     */

            sprintf(stringa,
		"Connection %i: Socket has died.",
		condescriptor
            );
            if(sysparm.log_errors)
                LogAppendLineFormatted(fname.primary_log, stringa);


	    /*   Explicitly set connection's socket to -1 and close
	     *   the connection.
	     */
	    connection[condescriptor]->socket = -1;
	    NetCloseConnection(condescriptor);


            return(-1);
	}

        /* Recieve error? */
        if(bytes_read < 0)
        {
            /* Handle error. */ 
            switch(errno)
            {
	      /* Invalid descriptor. */
              case EBADF:
		if(socket > -1)
		{
                    /* Log lost connection. */
                    sprintf(stringa,
 "NetManageRecvConnection(): Connection %i: Socket invalid and no longer used.",
                        condescriptor
                    );
                    if(sysparm.log_errors)
                        LogAppendLineFormatted(fname.primary_log, stringa);

                    /* Close connection. */
                    NetCloseConnection(condescriptor);

		    return(-1);
		}
		break;

              default:
                sprintf(stringa,
 "NetManageRecvConnection(): recv(): Unknown error `%i' on descriptor `%i'.",
                    errno, socket
                );
                if(sysparm.log_errors)
                    LogAppendLineFormatted(fname.primary_log, stringa);

                return(-1);
		break;
	    }
        }


        /* ************************************************************* */

        /* bytes_read cannot be greater than CS_DATA_MAX_BACKLOG. */
        if(bytes_read > CS_DATA_MAX_BACKLOG)
            bytes_read = CS_DATA_MAX_BACKLOG;

        /* Increment bytes_received for this condescriptor. */
        connection[condescriptor]->bytes_recieved += bytes_read;


        /* Set null character at the end of recvbuf just to be safe. */
        recvbuf[CS_DATA_MAX_BACKLOG - 1] = '\0';
            
              
        /* *************************************************************** */
        /* Begin parsing recieve buffer. */

        /* Reset recieve buffer count and pointer. */
        recvbuf_cnt = 0;
        recvbuf_ptr = recvbuf;

        while(recvbuf_cnt < bytes_read)
        {
            /* Reset work buffer count and pointer. */
            workbuf_cnt = 0;
            workbuf_ptr = workbuf;
            
            /* Fetch data for workbuf. */
            while(1)
            {
                if(workbuf_cnt >= CS_DATA_MAX_LEN)
                {
                    /* Increment recvbuf count and ptr to next delimiter. */
                    while(recvbuf_cnt < bytes_read)
                    {
                        if((*recvbuf_ptr == '\n') ||
                           (*recvbuf_ptr == '\r') ||
                           (*recvbuf_ptr == '\0')
                        )
                        {
                            recvbuf_cnt++;
			    recvbuf_ptr++;
                            break;
                        }
                        recvbuf_cnt++;
                        recvbuf_ptr++;
                    }
                    /*   Null terminating character for workbuf will
                     *   be added farther below.
                     */
                    break;
                }

                /* End of recieve buffer data reached? */
                else if(recvbuf_cnt >= bytes_read)
                {
                    *workbuf_ptr = '\0';
                    break;
                }

                /* Deliminator in recieve buffer encountered? */
                else if((*recvbuf_ptr == '\n') ||
                        (*recvbuf_ptr == '\r') ||
                        (*recvbuf_ptr == '\0')
                )
                {   
                    *workbuf_ptr = '\0';

                    recvbuf_cnt++;
                    recvbuf_ptr++;

                    break;
                }

                /* Copy data from recieve buffer to work buffer normally. */
                else
                {
                    *workbuf_ptr = *recvbuf_ptr;
                
                    recvbuf_cnt++;
                    recvbuf_ptr++;
                        
                    workbuf_cnt++;
                    workbuf_ptr++;
                }
            }

            /* Skip if workbuf is empty. */
            if(*workbuf == '\0')
                continue;

            /* Set null terminating character for workbuf. */
            workbuf[CS_DATA_MAX_LEN - 1] = '\0';


            /* Get command command. */
	    command = StringGetNetCommand(workbuf);
            if(command < 0)
                continue;

            /* Get argument arg. */
            strncpy(arg, StringGetNetArgument(workbuf), CS_DATA_MAX_LEN);
            arg[CS_DATA_MAX_LEN - 1] = '\0';
                 
         
            /* See which net command handling function to call. */
            switch(command)
            {
              case CS_CODE_LOGIN:
                NetHandleLogin(condescriptor, arg);
                break;

              case CS_CODE_LOGOUT:
                NetHandleLogout(condescriptor);
                break;

              case CS_CODE_WHOAMI:
                NetHandleWhoAmI(condescriptor, arg);
                break;

              case CS_CODE_REFRESH:
                NetHandleRefresh(condescriptor, arg);
                break;

              case CS_CODE_INTERVAL:
                NetHandleSetInterval(condescriptor, arg);
                break;

              case CS_CODE_IMAGESET:
                NetHandleSetImageSet(condescriptor, arg);
                break;

              case CS_CODE_SOUNDSET:
                NetHandleSetSoundSet(condescriptor, arg);
                break;

              case CS_CODE_PLAYSOUND:
                /* server dosen't play sounds. */
                break;


              case CS_CODE_LIVEMESSAGE:
                NetHandleLiveMessage(condescriptor, arg);
                break;

              case CS_CODE_SYSMESSAGE:
                /* Server does not handle this. */
                break;

              case CS_CODE_LITERALCMD:
                CmdHandleInput(condescriptor, arg);
                break;


              case CS_CODE_CREATEOBJ:
                /* Server doesn't accept this command. */
                break;

              case CS_CODE_RECYCLEOBJ:
                /* Server dosen't accept this command. */
                break;

              case CS_CODE_POSEOBJ:
                NetHandleObjectPose(condescriptor, arg);
                break;

              case CS_CODE_FORCEPOSEOBJ:
                /* Server does not accept this. */
                break;

              case CS_CODE_EXT:
                NetHandleExtCmd(condescriptor, arg);
                break;

              /* Unknown command. */
              default:
/*
fprintf(stderr, "Recieved unsupported command %i.\n", command);
fprintf(stderr, "Raw text: `%s'\n", workbuf);
 */
                connection[condescriptor]->errors_recieved++;
                break;
            }


	    /*   The call to the net handling function may have reallocated
             *   the connection pointers (espessially a call to
	     *   CmdHandleInput()) so we need to test if condescriptor is
	     *   still valid.
	     */
	    if(condescriptor >= total_connections)
		break;
        }


        return(0);
}


/*
 *      Procedure to check all connections for incoming network
 *      data and process the data.
 */
int NetManageRecv()
{
        static int con_num;
	static connection_struct **con_ptr;


        for(con_num = 0, con_ptr = connection;
            con_num < total_connections;
            con_num++, con_ptr++
	)
	{
	    if(*con_ptr == NULL)
		continue;
            if((*con_ptr)->socket < 0)
		continue;

	    /*   Note: The functions that NetManageRecvConnection() calls
	     *   may cause the connections to be deallocated.
	     *   If they are, global total_connections would have been reset
	     *   to 0 and this loop would exit.
	     */
            NetManageRecvConnection(con_num);
	}


        return(0);
}