-
Notifications
You must be signed in to change notification settings - Fork 23
/
comm.c
executable file
·4157 lines (3579 loc) · 124 KB
/
comm.c
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
/**************************************************************************
* File: comm.c Part of LuminariMUD *
* Usage: Communication, socket handling, main(), central game loop. *
* *
* All rights reserved. See license for complete information. *
* *
* Copyright (C) 1993, 94 by the Trustees of the Johns Hopkins University *
* Circle/tbaMUD is based on DikuMUD, Copyright (C) 1990, 1991. *
**************************************************************************/
#define __COMM_C__
#include "conf.h"
#include "sysdep.h"
/* Begin conf.h dependent includes */
#if CIRCLE_GNU_LIBC_MEMORY_TRACK
#include <mcheck.h>
#endif
#ifdef CIRCLE_MACINTOSH /* Includes for the Macintosh */
#define SIGPIPE 13
#define SIGALRM 14
/* GUSI headers */
#include <sys/ioctl.h>
/* Codewarrior dependant */
#include <SIOUX.h>
#include <console.h>
#endif
#ifdef CIRCLE_WINDOWS /* Includes for Win32 */
#ifdef __BORLANDC__
#include <dir.h>
#else /* MSVC */
#include <direct.h>
#endif
#include <mmsystem.h>
#endif /* CIRCLE_WINDOWS */
#ifdef CIRCLE_AMIGA /* Includes for the Amiga */
#include <sys/ioctl.h>
#include <clib/socket_protos.h>
#endif /* CIRCLE_AMIGA */
#ifdef CIRCLE_ACORN /* Includes for the Acorn (RiscOS) */
#include <socklib.h>
#include <inetlib.h>
#include <sys/ioctl.h>
#endif
#ifdef HAVE_ARPA_TELNET_H
#include <arpa/telnet.h>
#else
#include "telnet.h"
#endif
/* end conf.h dependent includes */
/* Note, most includes for all platforms are in sysdep.h. The list of
* files that is included is controlled by conf.h for that platform. */
#include "structs.h"
#include "utils.h"
#include "comm.h"
#include "interpreter.h"
#include "handler.h"
#include "db.h"
#include "house.h"
#include "oasis.h"
#include "genolc.h"
#include "dg_scripts.h"
#include "dg_event.h"
#include "screen.h" /* to support the gemote act type command */
#include "constants.h" /* For mud versions */
#include "boards.h"
#include "act.h"
#include "ban.h"
#include "msgedit.h"
#include "fight.h"
#include "spells.h" /* for affect_update */
#include "modify.h"
#include "quest.h"
#include "ibt.h" /* for free_ibt_lists */
#include "mud_event.h"
#include "clan.h"
#include "class.h" /* needed for level_exp for prompt */
#include "mail.h" /* has_mail() */
#include "new_mail.h" /* new mail system on prompt */
#include "screen.h"
#include "mudlim.h"
#include "actions.h"
#include "actionqueues.h"
#include "assign_wpn_armor.h"
#include "wilderness.h"
#include "spell_prep.h"
#include "perfmon.h"
#include "transport.h"
#include "hunts.h"
#include "bardic_performance.h" /* for the bard performance pulse */
#ifndef INVALID_SOCKET
#define INVALID_SOCKET (-1)
#endif
extern time_t motdmod;
extern time_t newsmod;
/* locally defined globals, used externally */
struct descriptor_data *descriptor_list = NULL; /* master desc list */
int buf_largecount = 0; /* # of large buffers which exist */
int buf_overflows = 0; /* # of overflows of output */
int buf_switches = 0; /* # of switches from small to large buf */
int circle_shutdown = 0; /* clean shutdown */
int circle_reboot = 0; /* reboot the game after a shutdown */
int no_specials = 0; /* Suppress ass. of special routines */
int scheck = 0; /* for syntax checking mode */
FILE *logfile = NULL; /* Where to send the log messages. */
unsigned long pulse = 0; /* number of pulses since game start */
ush_int port;
socket_t mother_desc;
int next_tick = SECS_PER_MUD_HOUR; /* Tick countdown */
/* used with do_tell and handle_webster_file utility */
long last_webster_teller = -1L;
const unsigned PERF_pulse_per_second = PASSES_PER_SEC;
/* static local global variable declarations (current file scope only) */
static struct txt_block *bufpool = NULL; /* pool of large output buffers */
static int max_players = 0; /* max descriptors available */
static int tics_passed = 0; /* for extern checkpointing */
static struct timeval null_time; /* zero-valued time structure */
static byte reread_wizlist; /* signal: SIGUSR1 */
/* normally signal SIGUSR2, currently orphaned in favor of Webster dictionary
* lookup
static byte emergency_unban;
*/
static int dg_act_check; /* toggle for act_trigger */
static bool fCopyOver; /* Are we booting in copyover mode? */
static char *last_act_message = NULL;
static byte webster_file_ready = FALSE; /* signal: SIGUSR2 */
/* static local function prototypes (current file scope only) */
static RETSIGTYPE reread_wizlists(int sig);
/* Appears to be orphaned right now...
static RETSIGTYPE unrestrict_game(int sig);
*/
static RETSIGTYPE reap(int sig);
static RETSIGTYPE checkpointing(int sig);
static RETSIGTYPE hupsig(int sig);
static ssize_t perform_socket_read(socket_t desc, char *read_point, size_t space_left);
static ssize_t perform_socket_write(socket_t desc, const char *txt, size_t length);
static void circle_sleep(struct timeval *timeout);
static int get_from_q(struct txt_q *queue, char *dest, int *aliased);
static void init_game(ush_int port);
static void signal_setup(void);
static socket_t init_socket(ush_int port);
static int new_descriptor(socket_t s);
static int get_max_players(void);
static int process_output(struct descriptor_data *t);
static int process_input(struct descriptor_data *t);
static void timediff(struct timeval *diff, struct timeval *a, struct timeval *b);
static void timeadd(struct timeval *sum, struct timeval *a, struct timeval *b);
static void flush_queues(struct descriptor_data *d);
static void nonblock(socket_t s);
static int perform_subst(struct descriptor_data *t, char *orig, char *subst);
static void record_usage(void);
static char *make_prompt(struct descriptor_data *point);
static void check_idle_passwords(void);
static void init_descriptor(struct descriptor_data *newd, int desc);
static struct in_addr *get_bind_addr(void);
static int parse_ip(const char *addr, struct in_addr *inaddr);
static int set_sendbuf(socket_t s);
static void free_bufpool(void);
static void setup_log(const char *filename, int fd);
static int open_logfile(const char *filename, FILE *stderr_fp);
#if defined(POSIX)
static sigfunc *my_signal(int signo, sigfunc *func);
#endif
/* Webster Dictionary Lookup functions */
static RETSIGTYPE websterlink(int sig);
static void handle_webster_file();
static void msdp_update(void); /* KaVir plugin*/
void update_msdp_affects(struct char_data *ch);
void update_damage_and_effects_over_time(void);
void update_player_last_on(void);
void check_auto_shutdown(void);
void update_player_misc(void);
void check_auto_happy_hour(void);
void regen_psp(void);
void process_walkto_actions(void);
void self_buffing(void);
void moving_rooms_update(void);
void recharge_activated_items(void);
/* externally defined functions, used locally */
#ifdef __CXREF__
#undef FD_ZERO
#undef FD_SET
#undef FD_ISSET
#undef FD_CLR
#define FD_ZERO(x)
#define FD_SET(x, y) 0
#define FD_ISSET(x, y) 0
#define FD_CLR(x, y)
#endif
/* main game loop and related stuff */
#if defined(CIRCLE_WINDOWS) || defined(CIRCLE_MACINTOSH)
/* Windows and Mac do not have gettimeofday, so we'll simulate it. Borland C++
* warns: "Undefined structure 'timezone'" */
void gettimeofday(struct timeval *t, struct timezone *dummy)
{
#if defined(CIRCLE_WINDOWS)
DWORD millisec = GetTickCount();
#elif defined(CIRCLE_MACINTOSH)
unsigned long int millisec;
millisec = (int)((float)TickCount() * 1000.0 / 60.0);
#endif
t->tv_sec = (int)(millisec / 1000);
t->tv_usec = (millisec % 1000) * 1000;
}
#endif /* CIRCLE_WINDOWS || CIRCLE_MACINTOSH */
#if defined(LUMINARI_CUTEST)
int luminari_main(int argc, char **argv)
#else
int main(int argc, char **argv)
#endif
{
/* Copy to stack memory to ensure the build info is embedded in core dumps */
char embed_version_build[512];
snprintf(embed_version_build, sizeof(embed_version_build), "%s\r\n%s", luminari_version, luminari_build);
int pos = 1;
const char *dir = NULL;
#ifdef MEMORY_DEBUG
zmalloc_init();
#endif
#if CIRCLE_GNU_LIBC_MEMORY_TRACK
mtrace(); /* This must come before any use of malloc(). */
#endif
#ifdef CIRCLE_MACINTOSH
/* ccommand() calls the command line/io redirection dialog box from
* Codewarriors's SIOUX library. */
argc = ccommand(&argv);
/* Initialize the GUSI library calls. */
GUSIDefaultSetup();
#endif
/* Load the game configuration. We must load BEFORE we use any of the
* constants stored in constants.c. Otherwise, there will be no variables
* set to set the rest of the vars to, which will mean trouble --> Mythran */
CONFIG_CONFFILE = NULL;
while ((pos < argc) && (*(argv[pos]) == '-'))
{
if (*(argv[pos] + 1) == 'f')
{
if (*(argv[pos] + 2))
CONFIG_CONFFILE = argv[pos] + 2;
else if (++pos < argc)
CONFIG_CONFFILE = argv[pos];
else
{
puts("SYSERR: File name to read from expected after option -f.");
exit(1);
}
}
pos++;
}
pos = 1;
if (!CONFIG_CONFFILE)
CONFIG_CONFFILE = strdup(CONFIG_FILE);
load_config();
port = CONFIG_DFLT_PORT;
dir = CONFIG_DFLT_DIR;
while ((pos < argc) && (*(argv[pos]) == '-'))
{
switch (*(argv[pos] + 1))
{
case 'f':
if (!*(argv[pos] + 2))
++pos;
break;
case 'o':
if (*(argv[pos] + 2))
CONFIG_LOGNAME = argv[pos] + 2;
else if (++pos < argc)
CONFIG_LOGNAME = argv[pos];
else
{
puts("SYSERR: File name to log to expected after option -o.");
exit(1);
}
break;
case 'C': /* -C<socket number> - recover from copyover, this is the control socket */
fCopyOver = TRUE;
mother_desc = atoi(argv[pos] + 2);
break;
case 'd':
if (*(argv[pos] + 2))
dir = argv[pos] + 2;
else if (++pos < argc)
dir = argv[pos];
else
{
puts("SYSERR: Directory arg expected after option -d.");
exit(1);
}
break;
case 'm':
mini_mud = 1;
no_rent_check = 1;
puts("Running in minimized mode & with no rent check.");
break;
case 'c':
scheck = 1;
puts("Syntax check mode enabled.");
break;
case 'q':
no_rent_check = 1;
puts("Quick boot mode -- rent check supressed.");
break;
case 'r':
circle_restrict = 1;
puts("Restricting game -- no new players allowed.");
break;
case 's':
no_specials = 1;
puts("Suppressing assignment of special routines.");
break;
case 'h':
/* From: Anil Mahajan. Do NOT use -C, this is the copyover mode and
* without the proper copyover.dat file, the game will go nuts! */
printf("Usage: %s [-c] [-m] [-q] [-r] [-s] [-d pathname] [port #]\n"
" -c Enable syntax check mode.\n"
" -d <directory> Specify library directory (defaults to 'lib').\n"
" -h Print this command line argument help.\n"
" -m Start in mini-MUD mode.\n"
" -f<file> Use <file> for configuration.\n"
" -o <file> Write log to <file> instead of stderr.\n"
" -q Quick boot (doesn't scan rent for object limits)\n"
" -r Restrict MUD -- no new players allowed.\n"
" -s Suppress special procedure assignments.\n"
" Note: These arguments are 'CaSe SeNsItIvE!!!'\n",
argv[0]);
exit(0);
default:
printf("SYSERR: Unknown option -%c in argument string.\n", *(argv[pos] + 1));
break;
}
pos++;
}
if (pos < argc)
{
if (!isdigit(*argv[pos]))
{
printf("Usage: %s [-c] [-m] [-q] [-r] [-s] [-d pathname] [port #]\n", argv[0]);
exit(1);
}
else if ((port = atoi(argv[pos])) <= 1024)
{
printf("SYSERR: Illegal port number %d.\n", port);
exit(1);
}
}
/* All arguments have been parsed, try to open log file. */
setup_log(CONFIG_LOGNAME, STDERR_FILENO);
/* Moved here to distinguish command line options and to show up
* in the log if stderr is redirected to a file. */
log("Loading configuration.");
log("%s\r\n%s", luminari_version, luminari_build);
if (chdir(dir) < 0)
{
perror("SYSERR: Fatal error changing to data directory");
exit(1);
}
log("Using %s as data directory.", dir);
if (scheck)
boot_world();
else
{
log("Running game on port %d.", port);
init_game(port);
log("Dev port set in utils.h to: %d.", CONFIG_DFLT_DEV_PORT);
}
log("Clearing game world.");
destroy_db();
if (!scheck)
{
log("Clearing other memory.");
free_bufpool(); /* comm.c */
free_player_index(); /* players.c */
free_messages(); /* fight.c */
free_text_files(); /* db.c */
board_clear_all(); /* boards.c */
free(cmd_sort_info); /* act.informative.c */
free_command_list(); /* act.informative.c */
free_social_messages(); /* act.social.c */
free_help_table(); /* db.c */
free_invalid_list(); /* ban.c */
free_save_list(); /* genolc.c */
free_strings(&config_info, OASIS_CFG); /* oasis_delete.c */
free_ibt_lists(); /* ibt.c */
free_recent_players(); /* act.informative.c */
free_list(world_events); /* free up our global lists */
free_list(global_lists);
}
if (last_act_message)
free(last_act_message);
/* probably should free the entire config here.. */
free(CONFIG_CONFFILE);
log("Done.");
#ifdef MEMORY_DEBUG
zmalloc_check();
#endif
return (0);
}
/* Reload players after a copyover */
void copyover_recover()
{
struct descriptor_data *d;
FILE *fp;
char host[1024], guiopt[1024];
int desc, i, player_i;
bool fOld;
char name[MAX_INPUT_LENGTH] = {'\0'};
long pref;
log("Copyover recovery initiated");
fp = fopen(COPYOVER_FILE, "r");
/* there are some descriptors open which will hang forever then ? */
if (!fp)
{
perror("copyover_recover:fopen");
log("Copyover file not found. Exitting.\n\r");
exit(1);
}
/* In case something crashes - doesn't prevent reading */
unlink(COPYOVER_FILE);
/* read boot_time - first line in file */
i = fscanf(fp, "%ld\n", (long *)&boot_time);
if (i != 1)
log("SYSERR: Error reading boot time.");
for (;;)
{
fOld = TRUE;
i = fscanf(fp, "%d %ld %s %s %s\n", &desc, &pref, name, host, guiopt);
if (desc == -1)
break;
/* Write something, and check if it goes error-free */
if (write_to_descriptor(desc, "\n\rRestoring from copyover...\n\r") < 0)
{
close(desc); /* nope */
continue;
}
/* create a new descriptor */
CREATE(d, struct descriptor_data, 1);
memset((char *)d, 0, sizeof(struct descriptor_data));
init_descriptor(d, desc); /* set up various stuff */
strcpy(d->host, host);
d->next = descriptor_list;
descriptor_list = d;
d->connected = CON_CLOSE;
CopyoverSet(d, guiopt);
/* Now, find the pfile */
CREATE(d->character, struct char_data, 1);
clear_char(d->character);
CREATE(d->character->player_specials, struct player_special_data, 1);
new_mobile_data(d->character);
/* Allocate mobile event list */
// d->character->events = create_list();
d->character->desc = d;
if ((player_i = load_char(name, d->character)) >= 0)
{
GET_PFILEPOS(d->character) = player_i;
if (!PLR_FLAGGED(d->character, PLR_DELETED))
{
REMOVE_BIT_AR(PLR_FLAGS(d->character), PLR_WRITING);
REMOVE_BIT_AR(PLR_FLAGS(d->character), PLR_MAILING);
REMOVE_BIT_AR(PLR_FLAGS(d->character), PLR_CRYO);
}
else
fOld = FALSE;
}
else
fOld = FALSE;
/* Player file not found?! */
if (!fOld)
{
write_to_descriptor(desc, "\n\rSomehow, your character was lost in the copyover. Sorry.\n\r");
close_socket(d);
}
else
{
write_to_descriptor(desc, "\n\rCopyover recovery complete.\n\r");
GET_PREF(d->character) = pref;
enter_player_game(d);
/* Clear their load room if it's not persistant. */
if (!PLR_FLAGGED(d->character, PLR_LOADROOM))
GET_LOADROOM(d->character) = NOWHERE;
d->connected = CON_PLAYING;
look_at_room(d->character, 0);
/* Add to the list of 'recent' players (since last reboot) with copyover flag */
if (AddRecentPlayer(GET_NAME(d->character), d->host, FALSE, TRUE) == FALSE)
{
mudlog(BRF, MAX(LVL_IMMORT, GET_INVIS_LEV(d->character)), TRUE, "Failure to AddRecentPlayer (returned FALSE).");
}
}
}
fclose(fp);
}
/* Init sockets, run game, and cleanup sockets */
static void init_game(ush_int local_port)
{
/* We don't want to restart if we crash before we get up. */
touch(KILLSCRIPT_FILE);
circle_srandom(time(0));
log("Finding player limit.");
max_players = get_max_players();
/* If copyover mother_desc is already set up */
if (!fCopyOver)
{
log("Opening mother connection.");
mother_desc = init_socket(local_port);
}
event_init();
/* set up hash table for find_char() */
init_lookup_table();
boot_db();
#if defined(CIRCLE_UNIX) || defined(CIRCLE_MACINTOSH)
log("Signal trapping.");
signal_setup();
#endif
/* If we made it this far, we will be able to restart without problem. */
remove(KILLSCRIPT_FILE);
if (fCopyOver) /* reload players */
copyover_recover();
log("Entering game loop.");
game_loop(mother_desc);
Crash_save_all();
log("Closing all sockets.");
while (descriptor_list)
close_socket(descriptor_list);
CLOSE_SOCKET(mother_desc);
if (circle_reboot != 2)
save_all();
log("Saving current MUD time.");
save_mud_time(&time_info);
if (circle_reboot)
{
log("Rebooting.");
exit(52); /* what's so great about HHGTTG, anyhow? */
}
log("Normal termination of game.");
}
/* init_socket sets up the mother descriptor - creates the socket, sets
* its options up, binds it, and listens. */
static socket_t init_socket(ush_int local_port)
{
socket_t s;
struct sockaddr_in sa;
int opt;
#ifdef CIRCLE_WINDOWS
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
if (WSAStartup(wVersionRequested, &wsaData) != 0)
{
log("SYSERR: WinSock not available!");
exit(1);
}
/* 4 = stdin, stdout, stderr, mother_desc. Windows might keep sockets and
* files separate, in which case this isn't necessary, but we will err on
* the side of caution. */
if ((wsaData.iMaxSockets - 4) < max_players)
{
max_players = wsaData.iMaxSockets - 4;
}
log("Max players set to %d", max_players);
if ((s = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
log("SYSERR: Error opening network connection: Winsock error #%d",
WSAGetLastError());
exit(1);
}
}
#else
/* Should the first argument to socket() be AF_INET or PF_INET? I don't
* know, take your pick. PF_INET seems to be more widely adopted, and
* Comer (_Internetworking with TCP/IP_) even makes a point to say that
* people erroneously use AF_INET with socket() when they should be using
* PF_INET. However, the man pages of some systems indicate that AF_INET
* is correct; some such as ConvexOS even say that you can use either one.
* All implementations I've seen define AF_INET and PF_INET to be the same
* number anyway, so the point is (hopefully) moot. */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("SYSERR: Error creating socket");
exit(1);
}
#endif /* CIRCLE_WINDOWS */
#if defined(SO_REUSEADDR) && !defined(CIRCLE_MACINTOSH)
opt = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0)
{
perror("SYSERR: setsockopt REUSEADDR");
exit(1);
}
#endif
set_sendbuf(s);
/* The GUSI sockets library is derived from BSD, so it defines SO_LINGER, even
* though setsockopt() is unimplimented. (from Dean Takemori) */
#if defined(SO_LINGER) && !defined(CIRCLE_MACINTOSH)
{
struct linger ld;
ld.l_onoff = 0;
ld.l_linger = 0;
if (setsockopt(s, SOL_SOCKET, SO_LINGER, (char *)&ld, sizeof(ld)) < 0)
perror("SYSERR: setsockopt SO_LINGER"); /* Not fatal I suppose. */
}
#endif
/* Clear the structure */
memset((char *)&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(local_port);
sa.sin_addr = *(get_bind_addr());
if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0)
{
perror("SYSERR: bind");
CLOSE_SOCKET(s);
exit(1);
}
nonblock(s);
listen(s, 5);
return (s);
}
static int get_max_players(void)
{
#ifndef CIRCLE_UNIX
return (CONFIG_MAX_PLAYING);
#else
int max_descs = 0;
const char *method;
/* First, we'll try using getrlimit/setrlimit. This will probably work
* on most systems. HAS_RLIMIT is defined in sysdep.h. */
#ifdef HAS_RLIMIT
{
struct rlimit limit;
/* find the limit of file descs */
method = "rlimit";
if (getrlimit(RLIMIT_NOFILE, &limit) < 0)
{
perror("SYSERR: calling getrlimit");
exit(1);
}
/* set the current to the maximum */
limit.rlim_cur = limit.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &limit) < 0)
{
perror("SYSERR: calling setrlimit");
exit(1);
}
#ifdef RLIM_INFINITY
if (limit.rlim_max == RLIM_INFINITY)
max_descs = CONFIG_MAX_PLAYING + NUM_RESERVED_DESCS;
else
max_descs = MIN(CONFIG_MAX_PLAYING + NUM_RESERVED_DESCS, limit.rlim_max);
#else
max_descs = MIN(CONFIG_MAX_PLAYING + NUM_RESERVED_DESCS, limit.rlim_max);
#endif
}
#elif defined(OPEN_MAX) || defined(FOPEN_MAX)
#if !defined(OPEN_MAX)
#define OPEN_MAX FOPEN_MAX
#endif
method = "OPEN_MAX";
max_descs = OPEN_MAX; /* Uh oh.. rlimit didn't work, but we have
* OPEN_MAX */
#elif defined(_SC_OPEN_MAX)
/* Okay, you don't have getrlimit() and you don't have OPEN_MAX. Time to
* try the POSIX sysconf() function. (See Stevens' _Advanced Programming
* in the UNIX Environment_). */
method = "POSIX sysconf";
errno = 0;
if ((max_descs = sysconf(_SC_OPEN_MAX)) < 0)
{
if (errno == 0)
max_descs = CONFIG_MAX_PLAYING + NUM_RESERVED_DESCS;
else
{
perror("SYSERR: Error calling sysconf");
exit(1);
}
}
#else
/* if everything has failed, we'll just take a guess */
method = "random guess";
max_descs = CONFIG_MAX_PLAYING + NUM_RESERVED_DESCS;
#endif
/* now calculate max _players_ based on max descs */
max_descs = MIN(CONFIG_MAX_PLAYING, max_descs - NUM_RESERVED_DESCS);
if (max_descs <= 0)
{
log("SYSERR: Non-positive max player limit! (Set at %d using %s).",
max_descs, method);
exit(1);
}
log(" Setting player limit to %d using %s.", max_descs, method);
return (max_descs);
#endif /* CIRCLE_UNIX */
}
/* game_loop contains the main loop which drives the entire MUD. It
* cycles once every 0.10 seconds and is responsible for accepting new
* new connections, polling existing connections for input, dequeueing
* output and sending it out to players, and calling "heartbeat" functions
* such as mobile_activity(). */
void game_loop(socket_t local_mother_desc)
{
fd_set input_set, output_set, exc_set, null_set;
struct timeval last_time, opt_time, process_time, temp_time;
struct timeval before_sleep, now, timeout;
char comm[MAX_INPUT_LENGTH] = {'\0'};
struct descriptor_data *d = NULL, *next_d = NULL;
int missed_pulses = 0, maxdesc = 0, aliased = 0;
long int perf_high_water_mark = 0;
/* initialize various time values */
null_time.tv_sec = 0;
null_time.tv_usec = 0;
opt_time.tv_usec = OPT_USEC;
opt_time.tv_sec = 0;
FD_ZERO(&null_set);
gettimeofday(&last_time, (struct timezone *)0);
/* The Main Loop. The Big Cheese. The Top Dog. The Head Honcho. The.. */
while (!circle_shutdown)
{
/* Sleep if we don't have any connections */
if (descriptor_list == NULL)
{
log("No connections. Going to sleep.");
FD_ZERO(&input_set);
FD_SET(local_mother_desc, &input_set);
if (select(local_mother_desc + 1, &input_set, (fd_set *)0, (fd_set *)0, NULL) < 0)
{
if (errno == EINTR)
log("Waking up to process signal.");
else
perror("SYSERR: Select coma");
}
else
log("New connection. Waking up.");
gettimeofday(&last_time, (struct timezone *)0);
}
/* Set up the input, output, and exception sets for select(). */
FD_ZERO(&input_set);
FD_ZERO(&output_set);
FD_ZERO(&exc_set);
FD_SET(local_mother_desc, &input_set);
maxdesc = local_mother_desc;
for (d = descriptor_list; d; d = d->next)
{
#ifndef CIRCLE_WINDOWS
if (d->descriptor > maxdesc)
maxdesc = d->descriptor;
#endif
FD_SET(d->descriptor, &input_set);
FD_SET(d->descriptor, &output_set);
FD_SET(d->descriptor, &exc_set);
}
/* At this point, we have completed all input, output and heartbeat
* activity from the previous iteration, so we have to put ourselves
* to sleep until the next 0.1 second tick. The first step is to
* calculate how long we took processing the previous iteration. */
gettimeofday(&before_sleep, (struct timezone *)0); /* current time */
timediff(&process_time, &before_sleep, &last_time);
{
long int total_usec = 1000000 * process_time.tv_sec + process_time.tv_usec;
double usage_pcnt = 100 * ((double)total_usec / OPT_USEC);
PERF_log_pulse(usage_pcnt);
if (total_usec > perf_high_water_mark)
{
perf_high_water_mark = total_usec;
char buf[MAX_STRING_LENGTH] = {'\0'};
PERF_prof_repr_pulse(buf, sizeof(buf));
log("Pulse usage new high water mark [%.2f%%, %ld usec]. Trace info: \n%s",
usage_pcnt, total_usec, buf);
}
}
/* just in case, re-calculate after PERF logging */
gettimeofday(&before_sleep, (struct timezone *)0);
timediff(&process_time, &before_sleep, &last_time);
/* If we were asleep for more than one pass, count missed pulses and sleep
* until we're resynchronized with the next upcoming pulse. */
if (process_time.tv_sec == 0 && process_time.tv_usec < OPT_USEC)
{
missed_pulses = 0;
}
else
{
missed_pulses = process_time.tv_sec * PASSES_PER_SEC;
missed_pulses += process_time.tv_usec / OPT_USEC;
process_time.tv_sec = 0;
process_time.tv_usec = process_time.tv_usec % OPT_USEC;
}
/* Calculate the time we should wake up */
timediff(&temp_time, &opt_time, &process_time);
timeadd(&last_time, &before_sleep, &temp_time);
/* Now keep sleeping until that time has come */
gettimeofday(&now, (struct timezone *)0);
timediff(&timeout, &last_time, &now);
/* Go to sleep */
do
{
circle_sleep(&timeout);
gettimeofday(&now, (struct timezone *)0);
timediff(&timeout, &last_time, &now);
} while (timeout.tv_usec || timeout.tv_sec);
PERF_prof_reset();
PERF_PROF_ENTER(pr_main_loop_, "Main Loop");
/* Poll (without blocking) for new input, output, and exceptions */
if (select(maxdesc + 1, &input_set, &output_set, &exc_set, &null_time) < 0)
{
perror("SYSERR: Select poll");
return;
}
/* If there are new connections waiting, accept them. */
if (FD_ISSET(local_mother_desc, &input_set))
new_descriptor(local_mother_desc);
/* Kick out the freaky folks in the exception set and marked for close */
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
if (FD_ISSET(d->descriptor, &exc_set))
{
FD_CLR(d->descriptor, &input_set);
FD_CLR(d->descriptor, &output_set);
close_socket(d);
}
}
PERF_PROF_ENTER(pr_process_input_, "Process Input");
/* Process descriptors with input pending */
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
if (FD_ISSET(d->descriptor, &input_set))
{
if (d->pProtocol != NULL) /* KaVir's plugin */
d->pProtocol->WriteOOB = 0; /* KaVir's plugin */
if (process_input(d) < 0)
close_socket(d);
}
}
PERF_PROF_EXIT(pr_process_input_);
PERF_PROF_ENTER(pr_process_commands_, "Process Commands");
/* Process commands we just read from process_input */
for (d = descriptor_list; d; d = next_d)
{
next_d = d->next;
/* Not combined to retain --(d->wait) behavior. -gg 2/20/98 If no wait
* state, no subtraction. If there is a wait state then 1 is subtracted.
* Therefore we don't go less than 0 ever and don't require an 'if'
* bracket. -gg 2/27/99 */
if (d->character)
{
GET_WAIT_STATE(d->character) -= (GET_WAIT_STATE(d->character) > 0);
if (GET_WAIT_STATE(d->character))
continue;
}
if (get_from_q(&d->input, comm, &aliased))
{
if (d->character)
{
/* Reset the idle timer & pull char back from void if necessary */
d->character->char_specials.timer = 0;
if (STATE(d) == CON_PLAYING && GET_WAS_IN(d->character) != NOWHERE)
{
if (IN_ROOM(d->character) != NOWHERE)
char_from_room(d->character);
if (ZONE_FLAGGED(GET_ROOM_ZONE(GET_WAS_IN(d->character)), ZONE_WILDERNESS))
{
X_LOC(d->character) = world[GET_WAS_IN(d->character)].coords[0];
Y_LOC(d->character) = world[GET_WAS_IN(d->character)].coords[1];
}
char_to_room(d->character, GET_WAS_IN(d->character));
GET_WAS_IN(d->character) = NOWHERE;
act("$n has returned.", TRUE, d->character, 0, 0, TO_ROOM);
}
GET_WAIT_STATE(d->character) = 1;