File: irc.c

package info (click to toggle)
epic4 1%3A3.0-2
  • links: PTS
  • area: main
  • in suites: sid
  • size: 3,740 kB
  • sloc: ansic: 56,285; makefile: 667; sh: 160; perl: 30
file content (1221 lines) | stat: -rw-r--r-- 31,812 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
/* $EPIC: irc.c,v 1.778 2014/03/31 13:57:22 jnelson Exp $ */
/*
 * ircII: a new irc client.  I like it.  I hope you will too!
 *
 * Copyright (c) 1990 Michael Sandroff.
 * Copyright (c) 1991, 1992 Troy Rollo.
 * Copyright (c) 1992-1996 Matthew Green.
 * Copyright  1994 Jake Khuon.
 * Copyright  1993, 2003 EPIC Software Labs.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notices, the above paragraph (the one permitting redistribution),
 *    this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The names of the author(s) may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
#include "irc.h"


/*
 * irc_version is what $J returns, its the common-name for the version.
 */
const char irc_version[] = "EPIC4-3.0";
const char useful_info[] = "epic4 3 0 0";

/*
 * internal_version is what $V returns, its the integer-id for the
 * version, and corresponds to the date of release, YYYYMMDD.
 */ 
const char internal_version[] = "20240904";

/*
 * In theory, this number is incremented for every commit.
 */
const unsigned long	commit_id = 795;

/*
 * As a way to poke fun at the current rage of naming releases after
 * english words, which often have little or no correlation with outside
 * reality, I have decided to start doing that with EPIC.  These names
 * are intentionally and maliciously silly.  Complaints will be ignored.
 */
const char ridiculous_version_name[] = "Conducement";

#define __need_putchar_x__
#include "status.h"
#include "clock.h"
#include "dcc.h"
#include "names.h"
#include "vars.h"
#include "input.h"
#include "alias.h"
#include "output.h"
#include "termx.h"
#include "exec.h"
#include "screen.h"
#include "log.h"
#include "server.h"
#include "hook.h"
#include "keys.h"
#include "ircaux.h"
#include "commands.h"
#include "window.h"
#include "history.h"
#include "exec.h"
#include "notify.h"
#include "mail.h"
#include "timer.h"
#include "newio.h"
#include "parse.h"
#include "notice.h"
#include <pwd.h>


/*
 * Global variables
 */

/* The ``DEFAULT'' port used for irc server connections. */
int		irc_port = IRC_PORT;

/* Set if ircII should usurp flow control, unset if not.  Probably bogus. */
int		use_flow_control = 1;

/* Set if ircII should turn on IEXTEN, unset to suppress */
int		use_iexten = -1;

/* 
 * When a numeric is being processed, this holds the negative value
 * of the numeric.  Its negative so if we pass it to do_hook, it can
 * tell its a numeric and not a named ON event.
 */
int		current_numeric;

/* Set if the client is not using a termios interface */
int		dumb_mode = 0;

/* Set if the client is supposed to fork(). (a bot.)  Probably bogus. */
int		background = 0;

/* Set if the client is checking fd 0 for input. (usu. op of "background") */
int		use_input = 1;

/* The number of WAIT tokens sent out so far */
int		waiting_out = 0;

/* The number of WAIT tokens returned so far */
int		waiting_in = 0;

/*
 * Set when an OPER command is sent out, reset when umode +o or 464 reply
 * comes back.  This is *seriously* bogus.
 */
int		oper_command = 0;

/* Set if your IRCRC file is NOT to be loaded on startup. */
int		quick_startup = 0;

/* Set if user does not want to auto-connect to a server upon startup */
int		dont_connect = 0;

/* Set to the current time, each time you press a key. */
Timeval		idle_time = { 0, 0 };

/* Set to the time the client booted up */
Timeval		start_time;

/* The number of child processes still unreaped. */
int		child_dead = 0;

/* Set if the current output is from a trusted source */
int		trusted_output = 1;

/* Set to 0 when you want to suppress all beeps (such as window repaints) */
int		global_beep_ok = 1;

/* The unknown userhost value.  Bogus, but DONT CHANGE THIS!  */
const char	*unknown_userhost = "<UNKNOWN>@<UNKNOWN>";

/* Whether or not the client is dying. */
int		dead = 0;

/* The number of pending SIGINTs (^C) still unprocessed. */
volatile int	cntl_c_hit = 0;

/* This is 1 if we are in the foreground process group */
int		foreground = 1;

/* This is 0 until your ~/.ircrc is loaded */
int		ircrc_loaded = 0;

/* This is 0 unless you specify the -B command line flag */
int		load_ircrc_right_away = 0;

/* This is 1 if you want all logging to be inhibited. Dont leave this on! */
int		inhibit_logging = 0;

/* This is 1 if we're currently loading the "global" script, 0 afterwards */
int		loading_global = 0;

/* This is reset every time io() is called.  Use this to save calls to time */
Timeval		now = {0, 0};

/* When you "highlight ignore", this is what is used to embellish */
char *		highlight_char;

/* Output which is displayed without modification by the user */
int		privileged_output = 0;

/*
 * If set, outbound connections will be bind()ed to the address
 * specified.  if unset, the default address for your host will
 * be used.  LocalHostName can be set by the /HOSTNAME command 
 * or via the IRCHOST environment variable.  These variables should
 * be considered read-only.  Dont ever change them.
 *
 * Its important (from a user's point of view) that these never be
 * set to addresses that do not belong to the current hostname.
 * If that happens, outbound connections will fail, and its not my fault.
 */
char *		LocalHostName = NULL;
ISA *		LocalIPv4Addr = NULL;
#ifdef INET6
ISA6 *		LocalIPv6Addr = NULL;
#endif

int		inbound_line_mangler = 0,
		outbound_line_mangler = 0;

char		*startup_file = NULL,		/* full path .epicrc file */
		*epicrc_file = NULL,		/* full path .epicrc file */
		*ircrc_file = NULL,		/* full path .ircrc file */
		*my_path = (char *) 0,		/* path to users home dir */
		*irc_lib = (char *) 0,		/* path to the ircII library */
		*default_channel = NULL,	/* Channel to join on connect */
		nickname[NICKNAME_LEN + 1],	/* users nickname */
		hostname[NAME_LEN + 1],		/* name of current host */
		realname[REALNAME_LEN + 1],	/* real name of user */
		username[NAME_LEN + 1],		/* usernameof user */
		userhost[NAME_LEN + 1],		/* userhost of user */
		*send_umode = NULL,		/* sent umode */
		*last_notify_nick = (char *) 0,	/* last detected nickname */
		empty_string[] = "",		/* just an empty string */
		space[] = " ",			/* just a lonely space */
		on[] = "ON",
		off[] = "OFF",
		zero[] = "0",
		one[] = "1",
		star[] = "*",
		dot[] = ".",
		comma[] = ",",
		*cut_buffer = (char *) 0;	/* global cut_buffer */

fd_set		readables, held_readables;
fd_set		writables, held_writables;
int		global_max_fd = -1;


static		char	switch_help[] =
"Usage: epic [switches] [nickname] [server list]                      \n\
  The [nickname] can be up to 30 characters long                      \n\
  The [server list] are one or more server descriptions               \n\
  The [switches] are zero or more of the following:                   \n\
      -a\tThe [server list] adds to default server list               \n"
#ifndef NO_BOTS
"      -b\tThe program should run in the background ``bot mode''       \n"
#endif
"      -B\tLoads your .ircrc file before you connect to a server.      \n\
      -d\tThe program should run in ``dumb mode'' (no fancy screen)   \n\
      -f\tThe program won't mess with your flow control                \n\
      -F\tThe program will mess with your flow control                \n\
      -o\tThe program wll turn on IEXTEN terminal setting (^V/^O)     \n\
      -O\tThe program will turn off IEXTEN (so you can bind ^V/^O)    \n\
      -h\tPrint this help message                                     \n\
      -q\tThe program will not load your .ircrc file                  \n\
      -s\tThe program will not connect to a server upon startup       \n\
      -v\tPrint the version of this irc client and exit               \n\
      -x\tRun the client in full X_DEBUG mode                         \n\
      -c <chan>\tJoin <chan> after first connection to a server       \n\
      -H <host>\tUse a virtual host instead of default hostname	      \n\
      -l <file>\tLoads <file> instead of your .ircrc file             \n\
      -L <file>\tLoads <file> instead of your .ircrc file             \n\
      -n <nick>\tThe program will use <nick> as your default nickname \n\
      -p <port>\tThe program will use <port> as the default portnum   \n\
      -z <user>\tThe program will use <user> as your default username \n";



static SIGNAL_HANDLER(sig_irc_exit)
{
	irc_exit (1, NULL);
}

/* irc_exit: cleans up and leaves */
void	irc_exit (int really_quit, const char *format, ...)
{
	char 	buffer[BIG_BUFFER_SIZE];
	char *	sub_format;
	int	old_window_display = window_display;
	int	value;
#ifdef PERL
	extern void perlstartstop(int);
#endif
#ifdef TCL
	extern void tclstartstop(int);
#endif

	/*
	 * If we get called recursively, something is hosed.
	 * Each recursion we get more insistant.
	 */
	if (dead == 1)
		exit(1);			/* Take that! */
	if (dead == 2)
		_exit(1);			/* Try harder */
	if (dead >= 3)
		kill(getpid(), SIGKILL);	/* DIE DIE DIE! */

	/* Faults in the following code are just silently punted */
	dead++;	

	if (really_quit == 0)	/* Don't clean up if we're crashing */
		goto die_now;

	close_all_dcc(); /* Need to do this before we close the server */

	if (format)
	{
		va_list arglist;
		va_start(arglist, format);
		vsnprintf(buffer, BIG_BUFFER_SIZE - 1, format, arglist);
		va_end(arglist);
	}
	else
	{
		if (!(format = get_string_var(QUIT_MESSAGE_VAR)))
			format = "%s";

		sub_format = convert_sub_format(format, 's');
		snprintf(buffer, BIG_BUFFER_SIZE - 1, sub_format, irc_version);
		new_free(&sub_format);
	}


	/* Do some clean up */
	do_hook(EXIT_LIST, "%s", buffer);
#ifdef TCL
	tclstartstop(0);
#endif
#ifdef PERL
	perlstartstop(0);  /* In case there's perl code in the exit hook. */
#endif
	close_all_servers(buffer);
	value = 0;
	logger(&value);
	get_child_exit(-1);  /* In case some children died in the exit hook. */
	clean_up_processes();

	/* Arrange to have the cursor on the input line after exit */
	if (!dumb_mode)
	{
		cursor_to_input();
		term_cr();
		term_clear_to_eol();
		term_reset();
	}
	
	/* Try to free as much memory as possible */
	window_display = 0;
	dumpcmd(NULL, NULL, NULL);
	set_lastlog_size(&value);
	set_history_size(&value);
	remove_channel(NULL, 0);
	destroy_call_stack();
	remove_bindings();
	delete_all_windows();
	destroy_server_list();
	window_display = old_window_display;
	fprintf(stdout, "\r");
	fflush(stdout);

	if (really_quit)
		exit(0);

die_now:
	my_signal(SIGABRT, SIG_DFL);
	kill(getpid(), SIGABRT);
	kill(getpid(), SIGQUIT);
	exit(1);
}

volatile int	dead_children_processes;

/* 
 * This is needed so that the fork()s we do to read compressed files dont
 * sit out there as zombies and chew up our fd's while we read more.
 */
static SIGNAL_HANDLER(child_reap)
{
	dead_children_processes = 1;
}

volatile int	segv_recurse = 0;

/* sigsegv: something to handle segfaults in a nice way */
static SIGNAL_HANDLER(coredump)
{
	if (segv_recurse++)
		exit(1);

	if (!dead)
	{
		term_reset();
		fprintf(stderr, "\
									\n\
									\n\
									\n\
* * * * * * * * * * * * * * * * * * * * * * * *				\n\
IRC-II has trapped a critical protection error.				\n\
This is probably due to a bug in the program.				\n\
									\n\
If you have access to the 'BUG_FORM' in the ircII source distribution,	\n\
we would appreciate your filling it out if you feel doing so would	\n\
be helpful in finding the cause of your problem.			\n\
									\n\
If you do not know what the 'BUG_FORM' is or you do not have access	\n\
to it, please dont worry about filling it out.  You might try talking	\n\
to the person who is in charge of IRC at your site and see if you can	\n\
get them to help you.							\n\
									\n\
This version of IRC II is  --->[%s (%lu)]				\n\
The date of release is     --->[%s]					\n\
									\n\
* * * * * * * * * * * * * * * * * * * * * * * *				\n\
The program will now terminate.						\n", irc_version, commit_id, internal_version);

		fflush(stdout);
		panic_dump_call_stack();
	}

        if (x_debug & DEBUG_CRASH)
                irc_exit(0, "Hmmm. %s (%lu) has another bug.  Go figure...",
			irc_version, commit_id);
        else
                irc_exit(1, "Hmmm. %s (%lu) has another bug.  Go figure...",
			irc_version, commit_id);
}

/*
 * quit_response: Used by irc_io when called from irc_quit to see if we got
 * the right response to our question.  If the response was affirmative, the
 * user gets booted from irc.  Otherwise, life goes on. 
 */
static void quit_response (char *dummy, char *ptr)
{
	int	len;

	if ((len = strlen(ptr)) != 0)
		if (!my_strnicmp(ptr, "yes", len))
			irc_exit(1, NULL);
}

/* irc_quit: prompts the user if they wish to exit, then does the right thing */
void irc_quit (char unused, char *not_used)
{
	static	int in_it = 0;

	if (in_it)
		return;
	in_it = 1;
	add_wait_prompt("Do you really want to quit? ", 
			quit_response, empty_string, WAIT_PROMPT_LINE, 1);
	in_it = 0;
}

/*
 * cntl_c: emergency exit.... if somehow everything else freezes up, hitting
 * ^C five times should kill the program.   Note that this only works when
 * the program *is* frozen -- if it doesnt die when you do this, then the
 * program is functioning correctly (ie, something else is wrong)
 */
static SIGNAL_HANDLER(cntl_c)
{
	/* after 5 hits, we stop whatever were doing */
	if (cntl_c_hit++ >= 4)
		irc_exit(1, "User pressed ^C five times.");
	else if (cntl_c_hit > 1)
		kill(getpid(), SIGALRM);
}

static SIGNAL_HANDLER(nothing)
{
	/* nothing to do! */
}

static SIGNAL_HANDLER(sig_user1)
{
	say("Got SIGUSR1, closing DCC connections and EXECed processes");
	close_all_dcc();
	clean_up_processes();
}

static	void	show_version (void)
{
	printf("ircII %s (Commit id: %lu) (Date of release: %s)\n\r", irc_version, commit_id, internal_version);
	exit (0);
}

/*
 * parse_args: parse command line arguments for irc, and sets all initial
 * flags, etc. 
 *
 * major rewrite 12/22/94 -jfn
 * major rewrite 02/18/97 -jfn
 *
 * Sanity check:
 *   Supported flags: -a, -b, -B, -d, -f, -F, -h, -q, -s -v, -x
 *   Flags that take args: -c, -l, -L, -n, -p, -z
 *
 * We use getopt() so that your local argument passing convension
 * will prevail.  The first argument that occurs after all of the normal 
 * arguments have been parsed will be taken as a default nickname.
 * All the rest of the args will be taken as servers to be added to your
 * default server list.
 */
static	void	parse_args (int argc, char **argv)
{
	int ch;
	int add_servers = 0;
	struct passwd *entry;
	char *ptr = (char *) 0;
	char *tmp_hostname = NULL;
	char *the_path = NULL;
	char *translation_path = NULL;

	extern char *optarg;
	extern int optind;

	*nickname = 0;
	*realname = 0;
	*username = 0;

	/* 
	 * Its probably better to parse the environment variables
	 * first -- that way they can be used as defaults, but can 
	 * still be overriden on the command line.
	 */
	if ((entry = getpwuid(getuid())))
	{
		if (entry->pw_gecos && *(entry->pw_gecos))
		{
			if ((ptr = strchr(entry->pw_gecos, ',')))
				*ptr = 0;
			strlcpy(realname, entry->pw_gecos, sizeof realname);
		}

		if (entry->pw_name && *(entry->pw_name))
			strlcpy(username, entry->pw_name, sizeof username);

		if (entry->pw_dir && *(entry->pw_dir))
			malloc_strcpy(&my_path, entry->pw_dir);
	}


	if ((ptr = getenv("IRCNICK")))
		strlcpy(nickname, ptr, sizeof nickname);

	/*
	 * We now allow users to use IRCUSER or USER if we couldnt get the
	 * username from the password entries.  For those systems that use
	 * NIS and getpwuid() fails (boo, hiss), we make a last ditch effort
	 * to see what LOGNAME is (defined by POSIX.2 to be the canonical 
	 * username under which the person logged in as), and if that fails,
	 * we're really tanked, so we just let the user specify their own
	 * username.  I think everyone would have to agree this is the most
	 * reasonable way to handle this.
	 */
	if (!*username)
		if ((ptr = getenv("LOGNAME")) && *ptr)
			strlcpy(username, ptr, sizeof username);

#ifndef ALLOW_USER_SPECIFIED_LOGIN
	if (!*username)
#endif
		if ((ptr = getenv("IRCUSER")) && *ptr) 
			strlcpy(username, ptr, sizeof username);
#ifdef ALLOW_USER_SPECIFIED_LOGIN
		else if (*username)
			;
#endif
		else if ((ptr = getenv("USER")) && *ptr) 
			strlcpy(username, ptr, sizeof username);
		else if ((ptr = getenv("HOME")) && *ptr)
		{
			char *ptr2 = strrchr(ptr, '/');
			if (ptr2)
				strlcpy(username, ptr2, sizeof username);
			else
				strlcpy(username, ptr, sizeof username);
		}
		else
		{
			fprintf(stderr, "I dont know what your user name is.\n");
			fprintf(stderr, "Set your LOGNAME environment variable\n");
			fprintf(stderr, "and restart IRC II.\n");
			exit(1);
		}

	if ((ptr = getenv("IRCNAME")))
		strlcpy(realname, ptr, sizeof realname);
	else if ((ptr = getenv("NAME")))
		strlcpy(realname, ptr, sizeof realname);
	else if (!*realname)
		strlcpy(realname, "*Unknown*", sizeof realname);

	if ((ptr = getenv("HOME")))
		malloc_strcpy(&my_path, ptr);
	else if (!my_path)
		malloc_strcpy(&my_path, "/");



	if ((ptr = getenv("IRCPORT")))
		irc_port = my_atol(ptr);

	if ((ptr = getenv("EPICRC")))
		epicrc_file = malloc_strdup(ptr);
	else
		epicrc_file = malloc_strdup2(my_path, EPICRC_NAME);

	if ((ptr = getenv("IRCRC")))
		ircrc_file = malloc_strdup(ptr);
	else
		ircrc_file = malloc_strdup2(my_path, IRCRC_NAME);

	if ((ptr = getenv("IRCLIB")))
		irc_lib = malloc_strdup2(ptr, "/");
	else
		irc_lib = malloc_strdup(IRCLIB);

	if ((ptr = getenv("IRCUMODE")))
		send_umode = malloc_strdup(ptr);

	if ((ptr = getenv("IRCPATH")))
		the_path = malloc_strdup(ptr);
	else
		the_path = malloc_sprintf(NULL, DEFAULT_IRCPATH, irc_lib);

	set_string_var(LOAD_PATH_VAR, the_path);
	new_free(&the_path);

	if ((ptr = getenv("IRCHOST")) && *ptr)
		tmp_hostname = ptr;

	if ((ptr = getenv("IRCTRANSLATIONPATH")))
		translation_path = malloc_strdup(ptr);
	else
		translation_path = malloc_strdup2(IRCLIB, "/translation/");

	set_string_var(TRANSLATION_PATH_VAR, translation_path);
	new_free(&translation_path);

	/*
	 * Parse the command line arguments.
	 */
	while ((ch = getopt(argc, argv, "aBbc:dfFhH:l:L:n:oOp:qsvxz:")) != EOF)
	{
		switch (ch)
		{
			case 'v':	/* Output ircII version */
				show_version();
				/* NOTREACHED */

			case 'p': /* Default port to use */
				irc_port = my_atol(optarg);
				break;

			case 'f': /* Use flow control */
				use_flow_control = 1;
				break;

			case 'F': /* dont use flow control */
				use_flow_control = 0;
				break;

			case 'o': /* Use IEXTEN */
				use_iexten = 1;
				break;

			case 'O': /* dont use IEXTEN */
				use_iexten = 0;
				break;

			case 'd': /* use dumb mode */
				dumb_mode = 1;
				break;

			case 'l': /* Load some file instead of ~/.ircrc */
			case 'L': /* Same as above. Doesnt work like before */
				malloc_strcpy(&epicrc_file, optarg);
				break;

			case 'a': /* add server, not replace */
				add_servers = 1;
				break;

			case 'q': /* quick startup -- no .ircrc */
				quick_startup = 1;
				break;

			case 's': /* dont connect - let user choose server */
				dont_connect = 1;
				break;

			case 'b':
/* siiiiiiiigh */
#ifdef NO_BOTS
				fprintf(stderr, "This client was compiled to not support the -b flag. Tough for you.\n");
				exit(1);
#endif
				dumb_mode = 1;
				use_input = 0;
				background = 1;
				break;

			case 'n':
				strlcpy(nickname, optarg, sizeof nickname);
				break;

			case 'x': /* x_debug flag */
				x_debug = (unsigned long)0x0fffffff;
				break;

			case 'z':
#ifdef ALLOW_USER_SPECIFIED_LOGIN
				strlcpy(username, optarg, sizeof username);
#endif
				break;

			case 'B':
				load_ircrc_right_away = 1;
				break;

			case 'c':
				malloc_strcpy(&default_channel, optarg);
				break;

			case 'H':
				tmp_hostname = optarg;
				break;

			default:
			case 'h':
			case '?':
				fputs(switch_help, stderr);
				exit(1);
		} /* End of switch */
	}
	argc -= optind;
	argv += optind;

	if (argc && **argv && !strchr(*argv, '.'))
		strlcpy(nickname, *argv++, sizeof nickname), argc--;

	/*
 	 * "nickname" needs to be valid before we call build_server_list,
	 * so do a final check on whatever nickname we're going to use.
	 */
	if (!*nickname)
		strlcpy(nickname, username, sizeof nickname);

	for (; *argv; argc--, argv++)
		if (**argv)
			build_server_list(*argv, NULL);

	if (!use_input && quick_startup)
	{
		fprintf(stderr, "Cannot use -b and -q at the same time\n");
		exit(1);
	}
	if (!use_input && dont_connect)
	{
		fprintf(stderr, "Cannot use -b and -s at the same time\n");
		exit(1);
	}

	if (strcmp(nickname, "0") && !check_nickname(nickname, 1))
	{
		fprintf(stderr, "Invalid nickname: [%s]\n", nickname);
		fprintf(stderr, "Please restart IRC II with a valid nickname\n");
		exit(1);
	}

	/*
	 * Find and build the server lists...
	 */
	if ((ptr = getenv("IRCSERVER")))
		build_server_list(ptr, NULL);

	if (!server_list_size() || add_servers)
	{
		read_server_file();
		if (!server_list_size())
		{
			ptr = malloc_strdup(DEFAULT_SERVER);
			build_server_list(ptr, NULL);
			new_free(&ptr);
		}
	}

	/*
	 * Figure out our virtual hostname, if any.
	 */
	LocalHostName = NULL;
	if (tmp_hostname)
	{
		char *s = switch_hostname(tmp_hostname);
		fprintf(stderr, "%s\n", s);
		new_free(&s);
	}

	/*
	 * Make sure we have a hostname.
	 */
	if (!LocalHostName)
	{
		if (gethostname(hostname, NAME_LEN) || strlen(hostname) == 0)
		{
			fprintf(stderr, "I don't know what your hostname is and I can't do much without it.\n");
			exit(1);
		}
	}

	
	return;
}

/* fire scripted signal events -pegasus */
void do_signals(void)
{
	int sig_no;

	signals_caught[0] = 0;
	for (sig_no = 0; sig_no < NSIG; sig_no++)
		while (signals_caught[sig_no])
			do_hook(SIGNAL_LIST, "%d %d", sig_no, signals_caught[sig_no]--);
}

/* 
 * io() is a ONE TIME THROUGH loop!  It simply does ONE check on the
 * file descriptors, and if there is nothing waiting, it will time
 * out and drop out.  It does everything as far as checking for exec,
 * dcc, ttys, notify, the whole ball o wax, but it does NOT iterate!
 * 
 * You should usually NOT call io() unless you are specifically waiting
 * for something from a file descriptor.  Experience has shown that this
 * function can be called from pretty much anywhere and it doesnt have
 * any serious re-entrancy problems.  It certainly is more reliably 
 * predictable than the old irc_io, and it even uses less CPU.
 *
 * Heavily optimized for EPIC3-final to do as little work as possible
 *			-jfn 3/96
 */
void	io (const char *what)
{
static	const	char	*caller[51] = { NULL }; /* XXXX */
static	int		level = 0,
			old_level = 0,
			last_warn = 0;
static 	const Timeval	right_away = { 0, 0 };

	Timeval		timer;
	fd_set		rd, wd;


	level++;
	get_time(&now);

	/* Don't let this accumulate behind the user's back. */
	cntl_c_hit = 0;

	if (x_debug & DEBUG_WAITS)
	{
		if (level != old_level)
		{
			yell("Moving from io level [%d] to level [%d] from [%s]", old_level, level, what);
			old_level = level;
		}
	}

	if (level && (level - last_warn == 5))
	{
		last_warn = level;
		yell("io's recursion level is [%d],  [%s]<-[%s]<-[%s]<-[%s]<-[%s]", level, what, caller[level-1], caller[level-2], caller[level-3], caller[level-4]);
		if (level % 50 == 0)
			panic("Ahoy there matey!  Abandon ship!");
	}
	else if (level && (last_warn - level == 5))
		last_warn -= 5;


	caller[level] = what;

#if 1
	/* 
	 * XXXXXXX! It pains me greatly to call this here.
	 * This is an experimental test to see if i can get
	 * away with not having to call update_all_windows()
	 * in about a zillion other places by doing it here.
	 */
	update_all_windows();
#endif

	/* SET UP FD SETS */
	rd = readables;
	wd = writables;

	/* If there is a timer that expires sooner, wait for that */
	/* There is now a timer at all times, so this is our baseline */
	timer = TimerTimeout();

	/* If for any reason the timeout is negative, do a poll */
	if (time_diff(right_away, timer) < 0)
		timer = right_away;

	/* GO AHEAD AND WAIT FOR SOME DATA TO COME IN */
	switch (new_select(&rd, &wd, &timer))
	{
		/* Timeout -- nothing interesting. */
		case 0:
		{
			get_time(&now);
#ifdef HAVE_SSL
			/* Yes, this is slow, but we have to check for this */
			do_server(&rd, &wd);
#endif
			break;
		}

		/* Interrupted system call -- check for SIGINT */
		case -1:
		{
			get_time(&now);
			if (cntl_c_hit)		/* SIGINT is useful */
			{
				edit_char('\003');
				cntl_c_hit = 0;
			}
			else if (errno != EINTR) /* Deal with EINTR */
				yell("Select failed with [%s]", strerror(errno));
			break;
		}

		/* Check it out -- something is on one of our descriptors. */
		default:
		{
			get_time(&now);
			make_window_current(NULL);
			dcc_check(&rd, &wd);
			do_server(&rd, &wd);
			do_processes(&rd, &wd);
			do_screens(&rd, &wd);
			break;
		} 
	}

	if (signals_caught[0] != 0)
		do_signals();
	ExecuteTimers();
	get_child_exit(-1);
	if (level == 1 && need_defered_commands)
		do_defered_commands();

	cursor_to_input();

	/* (set in term.c) -- we need to redraw the screen */
	if (need_redraw)
		refresh_a_screen(main_screen);

	window_check_channels();
	update_all_windows();
	alloca(0);
	caller[level] = NULL;
	level--;

#ifdef DELAYED_FREES
	if (level == 0 && need_delayed_free)
		do_delayed_frees();
#endif
	return;
}

static void check_password (void)
{
#if defined(PASSWORD) && (defined(HARD_SECURE) || defined(SOFT_SECURE))
#define INPUT_PASSWD_LEN 15
	char 	input_passwd[INPUT_PASSWD_LEN];
#ifdef HAVE_GETPASS
	strlcpy(input_passwd, getpass("Passwd: "), sizeof input_passwd);
#else
	fprintf(stderr, "Passwd: ");
	fgets(input_passwd, INPUT_PASSWD_LEN - 1, stdin);
	chop(input_passwd);
#endif
	if (strcmp(input_passwd, PASSWORD))
		execl(SPOOF_PROGRAM, SPOOF_PROGRAM, NULL);
	else
		memset(input_passwd, 0, INPUT_PASSWD_LEN);
#endif
	return;
}

static void check_valid_user (void)
{
#ifdef INVALID_UID_FILE
{
	long myuid = getuid();
	long curr_uid;
	char curr_uid_s[10];
	char *curr_uid_s_ptr;
	FILE *uid_file;

	uid_file = fopen(INVALID_UID_FILE, "r");
	if (uid_file == NULL)
		return;

	while (fgets(curr_uid_s, 9, uid_file))
	{
		chop(curr_uid_s, 1);
		curr_uid_s_ptr = curr_uid_s;
		while (!isdigit(*curr_uid_s_ptr) && *curr_uid_s_ptr != 0)
			curr_uid_s_ptr++;

		if (*curr_uid_s_ptr == 0)
			continue;
		else
			curr_uid = my_atol(curr_uid_s);

		if (myuid == curr_uid)
			exit(1);
	}
	fclose(uid_file);
}
#endif
#ifdef HARD_SECURE
{
	int myuid = getuid();
	long curr_uid;
	char *curr_uid_s;
	char *uid_s_copy = NULL;
	char *uid_s_ptr;

	malloc_strcpy(&uid_s_copy, VALID_UIDS);
	uid_s_ptr = uid_s_copy;
	while (uid_s_ptr && *uid_s_ptr)
	{
		curr_uid_s = next_arg(uid_s_ptr, &uid_s_ptr);
		if (curr_uid_s && *curr_uid_s)
			curr_uid = my_atol(curr_uid_s);
		else
			continue;
		if (myuid == curr_uid)
			return;
	}
	new_free(&uid_s_copy);
	execl(SPOOF_PROGRAM, SPOOF_PROGRAM, NULL);
}
#else
# if defined(SOFT_SECURE) && defined(VALID_UID_FILE)
{
	long myuid = getuid();
	long curr_uid;
	char curr_uid_s[10];
	char *uid_s_ptr;
	char *curr_uid_s_ptr;
	FILE *uid_file;

	uid_file = fopen(VALID_UID_FILE, "r");
	if (uid_file == NULL)
		return;

	while (fgets(curr_uid_s, 9, uid_file))
	{
		chop(curr_uid_s, 1);
		curr_uid_s_ptr = curr_uid_s;
		while (*curr_uid_s_ptr && !isdigit(*curr_uid_s_ptr))
			curr_uid_s_ptr++;

		if (*curr_uid_s_ptr == 0)
			continue;
		else	
			curr_uid = my_atol(curr_uid_s_ptr);

		if (myuid == curr_uid)
		{
			fclose(uid_file);
			return;
		}
	}
	fclose(uid_file);
	execl(SPOOF_PROGRAM, SPOOF_PROGRAM, NULL);
}
# endif
#endif
	return;
}


/* 
 * contributed by:
 *
 * Chris A. Mattingly (Chris_Mattingly@ncsu.edu)
 *
 */
static void check_invalid_host (void)
{
#if defined(HOST_SECURE) && defined(INVALID_HOST_FILE)
	char *curr_host_s_ptr;
	char curr_host_s[256];
	FILE *host_file;
	char myhostname[256];
	size_t size;
	int err;

	gethostname(myhostname, 256);
	host_file = fopen(INVALID_HOST_FILE, "r");
	if (host_file == NULL)
		return;

	while (fgets(curr_host_s, 255, host_file))
	{
		chop(curr_host_s, 1);
		if (!my_stricmp(myhostname,curr_host_s))
			execl(SPOOF_PROGRAM, SPOOF_PROGRAM, NULL);
	}
	fclose(host_file);
#endif
	return;
}

/*************************************************************************/
int 	main (int argc, char *argv[])
{
#ifdef SOCKS
	SOCKSinit(argv[0]);
#endif
        get_time(&start_time);
	check_password();
	check_valid_user();
	check_invalid_host();
	parse_args(argc, argv);
	init_binds();
	init_keys();

	fprintf(stderr, "EPIC Version 4 -- %s\n", ridiculous_version_name);
	fprintf(stderr, "EPIC Software Labs (2004)\n");
	fprintf(stderr, "Version (%s), Commit Id (%lu) -- Date (%s)\n", irc_version, commit_id, internal_version);
	fprintf(stderr, "%s\n", compile_info);
	fprintf(stderr, "Process [%d]", getpid());
	if (isatty(0))
		fprintf(stderr, " connected to tty [%s]", ttyname(0));
	else
		dumb_mode = 1;
	fprintf(stderr, "\n");

	FD_ZERO(&readables);
	FD_ZERO(&writables);
	FD_ZERO(&held_readables);
	FD_ZERO(&held_writables);

	/* If we're a bot, do the bot thing. */
	if (!use_input && fork())
		_exit(0);

	/* make sure we don't start with spurious signals events firing */
	memset((void *)&signals_caught, 0, NSIG * sizeof(int));
	/* hook all signals! */
	init_signals();
	/* we *might* want to check for SIG_ERR from the above function.
	 * i leave it to hop to decide what to do on SIG_ERR. -pegasus 
	 */

	/* these should be taken by both dumb and smart displays */
	my_signal(SIGSEGV, coredump);
	my_signal(SIGBUS, coredump);
	my_signal(SIGQUIT, SIG_IGN);
	my_signal(SIGHUP, sig_irc_exit);
	my_signal(SIGTERM, sig_irc_exit);
	my_signal(SIGPIPE, SIG_IGN);
	my_signal(SIGCHLD, child_reap);
	my_signal(SIGINT, cntl_c);
	my_signal(SIGALRM, nothing);
	my_signal(SIGUSR1, sig_user1);

	if ((dumb_mode == 0) && (init_screen() == 0))
	{
		my_signal(SIGCONT, term_cont);
		my_signal(SIGWINCH, sig_refresh_screen);
		init_variables();
		build_status(NULL);
		update_input(UPDATE_ALL);
	}
	else
	{
		if (background)
		{
			my_signal(SIGHUP, SIG_IGN);
			freopen("/dev/null", "w", stdout);
		}
		dumb_mode = 1;		/* Just in case */
		create_new_screen();
		new_window(main_screen);
		init_variables();
		build_status(NULL);
	}

	/* Get the terminal-specific keybindings now */
	init_termkeys();

	/* The all-collecting stack frame */
	make_local_stack("TOP");

	/* XXXX Move this somewhere else eventually XXXX */
	if (load_ircrc_right_away)
		load_ircrc();

	set_input(empty_string);
	set_input_prompt(get_string_var(INPUT_PROMPT_VAR));

	if (dont_connect)
		display_server_list();		/* Let user choose server */
	else
		reconnect(NOSERV, 0);		/* Connect to default server */

	get_time(&idle_time);
	reset_system_timers();

	for (;;system_exception = 0)
		io("main");
	/* NOTREACHED */
}