File: irc.c

package info (click to toggle)
epic5 3.0.3-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 5,328 kB
  • sloc: ansic: 75,810; makefile: 648; ruby: 227; python: 215; sh: 78; perl: 13
file content (1171 lines) | stat: -rw-r--r-- 30,852 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
/*
 * 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, 2016 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.
 */
#define __need_term_h__
#include "irc.h"


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

/*
 * 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[] = "20250227";

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

/*
 * 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[] = "Obturation";

#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 "lastlog.h"
#include "log.h"
#include "server.h"
#include "hook.h"
#include "keys.h"
#include "ircaux.h"
#include "commands.h"
#include "window.h"
#include "exec.h"
#include "notify.h"
#include "mail.h"
#include "timer.h"
#include "newio.h"
#include "parse.h"
#include "levels.h"
#include "extlang.h"
#include "files.h"
#include "ctcp.h"
#include <pwd.h>
#ifdef NEWLOCALE_REQUIRES__GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <locale.h>


/*
 * Global variables
 */

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

/* 
 * 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 = -1;

/* 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;

/*
 * 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;

/* 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 sig_atomic_t	cntl_c_hit = 0;

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

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

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

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

/* Output which should not trigger %F in hidden windows */
int		do_window_notifies = 1;

jmp_buf		panic_jumpseat;
int		system_reset = 0;

intmax_t	sequence_point = 0;

/*
 * If set, outbound connections will be bind()ed to the address
 * specified.  if unset, the default address for your host will
 * be used.  VHosts 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 *		LocalIPv4HostName = NULL;
char *		LocalIPv6HostName = NULL;

int		inbound_line_mangler = 0,
		outbound_line_mangler = 0;

static char	*epicrc_file = NULL,		/* full path .epicrc file */
		*ircrc_file = NULL;		/* full path .ircrc file */
char		*startup_file = NULL,		/* Set when epicrc loaded */
		*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 */
		*send_umode = NULL,		/* sent umode */
		*last_notify_nick = (char *) 0;	/* last detected nickname */
const char	empty_string[] = "",		/* just an empty string */
		space[] = " ",			/* just a lonely space */
		on[] = "ON",
/*		my_off[] = "OFF", */
		zero[] = "0",
		one[] = "1",
		star[] = "*",
		dot[] = ".",
		comma[] = ",";
char	*cut_buffer = (char *) 0;	/* global cut_buffer */

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\
      -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\
      -S\tEach argument will be tokenised by whitechar                \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 *	quit_message = NULL;
	int	old_window_display;
	int	value;

	/*
	 * 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, sizeof(buffer), format, arglist);
		va_end(arglist);
		quit_message = buffer;
	}
	else
	{
		strlcpy(buffer, "Default", sizeof(buffer));
		quit_message = NULL;
	}

	/* Do some clean up */
	do_hook(EXIT_LIST, "%s", buffer);
#ifdef HAVE_PERL
	perlstartstop(0);  /* In case there's perl code in the exit hook. */
#endif
#ifdef HAVE_RUBY
	ruby_startstop(0);
#endif

	close_all_servers(quit_message);
	value = 0;
	logger(&value);
	get_child_exit(-1);  /* In case some children died in the exit hook. */
	clean_up_processes();
	close_all_dbms();

	/* 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 */
	old_window_display = swap_window_display(0);
/*	dumpcmd(NULL, NULL, NULL); */
	remove_channel(NULL, 0);
	set_lastlog_size(&value);
	delete_all_windows();
	destroy_server_list();

	remove_bindings();
	flush_on_hooks();
	flush_all_symbols();
	swap_window_display(old_window_display);

	printf("\r");
	fflush(stdout);

	if (really_quit)
		exit(0);

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

volatile sig_atomic_t	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 sig_atomic_t	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\
EPIC 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 EPIC 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();

		while ((x_debug & DEBUG_CRASH) && !sleep(1)) {};
	}

        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, const 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 */
BUILT_IN_KEYBINDING(irc_quit)
{
	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(), SIGUSR2);
}

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 SIGNAL_HANDLER(sig_user2)
{
	system_exception++;
}

static	void	show_version (void)
{
	printf("ircII %s (Commit id: %lu) (Date of release: %s) (git: %s)\n\r", 
			irc_version, commit_id, internal_version, git_commit);
	printf("Compile metadata: %s\n", compile_info);
	printf("Compiler: %s\n", compiler_version);
	printf("Configure options: %s\n", configure_args);
	printf("Compilation FLAGS: %s\n", compile_cflags);
	printf("Compilation LIBS: %s\n", compile_libs);
	printf("Compilation link: %s\n", final_link);
	printf("OpenSSL version: %#8.8lx\n", OpenSSL_version_num());
	printf("OpenSSL version: %s\n", OpenSSL_version(OPENSSL_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 append_servers = 0;
	struct passwd *entry;
	char *ptr = (char *) 0;
	const char *cptr = NULL;
	const char *tmp_hostname = NULL;
	char *the_path = NULL;

	int altargc = 0;
	char **altargv;

	extern char *optarg;
	extern int optind;

	*nickname = 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;
			set_var_value(DEFAULT_REALNAME_VAR, entry->pw_gecos, 0);
		}

		if (entry->pw_name && *(entry->pw_name))
			set_var_value(DEFAULT_USERNAME_VAR, entry->pw_name, 0);

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


	if ((cptr = getenv("IRCNICK")))
		strlcpy(nickname, cptr, 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 (empty(get_string_var(DEFAULT_USERNAME_VAR)))
		if ((cptr = getenv("LOGNAME")) && *cptr)
			set_var_value(DEFAULT_USERNAME_VAR, cptr, 0);

#ifndef ALLOW_USER_SPECIFIED_LOGIN
	if (empty(get_string_var(DEFAULT_USERNAME_VAR)))
#endif
		if ((cptr = getenv("IRCUSER")) && *cptr) 
			set_var_value(DEFAULT_USERNAME_VAR, cptr, 0);
#ifdef ALLOW_USER_SPECIFIED_LOGIN
		else if (empty(get_string_var(DEFAULT_USERNAME_VAR)))
			;
#endif
		else if ((cptr = getenv("USER")) && *cptr) 
			set_var_value(DEFAULT_USERNAME_VAR, cptr, 0);
		else if ((cptr = getenv("HOME")) && *cptr)
		{
			const char *cptr2 = strrchr(cptr, '/');
			if (cptr2)
				set_var_value(DEFAULT_USERNAME_VAR, cptr2, 0);
			else
				set_var_value(DEFAULT_USERNAME_VAR, cptr, 0);
		}
		else
		{
			fprintf(stderr, "I dont know what your user name is.\n");
			fprintf(stderr, "Set your LOGNAME environment variable\n");
			fprintf(stderr, "and restart EPIC.\n");
			exit(1);
		}

	if ((cptr = getenv("IRCNAME")))
		set_var_value(DEFAULT_REALNAME_VAR, cptr, 0);
	else if ((cptr = getenv("NAME")))
		set_var_value(DEFAULT_REALNAME_VAR, cptr, 0);
	else if ((cptr = getenv("REALNAME")))
		set_var_value(DEFAULT_REALNAME_VAR, cptr, 0);
	else
	{
		cptr = get_string_var(DEFAULT_REALNAME_VAR);
		if (!cptr || !*cptr)
			set_var_value(DEFAULT_REALNAME_VAR, "*Unknown*", 0);
	}

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



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

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

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

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

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

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

	set_var_value(LOAD_PATH_VAR, the_path, 0);
	new_free(&the_path);

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

	/* The -S-option  / shebang tokeniser */
	if (argc > 1 && ((argv[1][0] == '-' && argv[1][1] == 'S')
			|| strchr(argv[1], ' ') != NULL 
			|| strchr(argv[1], '\t') != NULL))
	{
		int 	argn;

		altargv = new_malloc(sizeof(char *));
		altargv[0] = malloc_strdup(argv[0]);
		altargc = 1;
		
		for (argn = 1; argn < argc; argn++)
		{
		    const char *s;
		    char *	dest;
		    size_t	destlen;
		    char *	d;

		    s = argv[argn];
		    destlen = strlen(s) + 1;
		    d = dest = alloca(destlen + 1);

		    while (*s && ((ssize_t)(d - dest) < (ssize_t)destlen))
		    {
			if (*s == '\0' || *s == ' ' || *s == '\t')
			{
			    if (d - dest > 0)
			    {
				*d = 0;
				RESIZE(altargv, char *, altargc + 1);
				altargv[altargc++] = malloc_strdup(dest);
				d = dest;
			    }
		        }
			else
				*d++ = *s++;
		    }
		}

		RESIZE(altargv, char *, altargc + 1);
		altargv[altargc] = NULL;
		argc = altargc;
		argv = altargv;
	}

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

			case 'p': /* Default port to use */
				irc_port = my_atol(optarg);
				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': /* append server, not replace */
				append_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 'S': /* dummy option - to not choke on -S */
				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
				set_var_value(DEFAULT_USERNAME_VAR, optarg, 0);
#endif
				break;

			case 'B':
				/* Historical option */
				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, get_string_var(DEFAULT_USERNAME_VAR), 
				sizeof nickname);

	for (; *argv; argc--, argv++)
		if (**argv)
			add_servers(*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 (!check_nickname(nickname, 1))
	{
		fprintf(stderr, "Invalid nickname: [%s]\n", nickname);
		fprintf(stderr, "Please restart EPIC with a valid nickname\n");
		exit(1);
	}

	/*
	 * Find and build the server lists...
	 */
	if ((cptr = getenv("IRCSERVER")))
	{
		/* add_servers() will modify ptr - don't pass in an env var */
		ptr = malloc_strdup(cptr);
		add_servers(ptr, NULL);
		new_free(&ptr);
	}

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

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

	/*
	 * Make sure we have a hostname.
	 */
	if (!LocalIPv4HostName && !LocalIPv6HostName)
	{
		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);
		}
	}

	if (altargc > 0)
	{
		int argn;
		for (argn = 0; argn < altargc; argn++)
			new_free(&(altargv[altargc]));
		new_free(&altargv);
	}
	
	return;
}

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

	signals_caught[0] = 0;
	for (sig_no = 1; sig_no < NSIG; sig_no++)
	{
		while (signals_caught[sig_no])
		{
			do_hook(SIGNAL_LIST, "%d %ld", sig_no,
				(long)signals_caught[sig_no]);
			do_hook(SIGNAL_LIST, "%s %ld", get_signal_name(sig_no),
				(long)signals_caught[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;
	Timeval		timer;

	sequence_point++;

	if (system_reset)
	{
		int	i;

		system_reset = 0;
		for (i = 0; i < 51; i++)
			caller[i] = NULL;
		check_message_from_queue(1);
		level = 0;
	}

	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;
	    }
	}

	/* Try to avoid letting recursion of io() to get out of control */
	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(1, "Ahoy there matey!  Abandon ship!");
	}
	else if (level && (last_warn - level == 5))
	    last_warn -= 5;

	caller[level] = what;

	/* Calculate the time to the next timer timeout */
	timer = TimerTimeout();

	/* GO AHEAD AND WAIT FOR SOME DATA TO COME IN */
	make_window_current_by_refnum(0);
	switch (do_wait(&timer))
	{
		/* Timeout -- Need to do timers */
		case 0:
		{
			get_time(&now);
			ExecuteTimers();
			break;
		}

		/* Interrupted system call -- check for SIGINT */
		case -1:
		{
			get_time(&now);
			if (cntl_c_hit)		/* SIGINT is useful */
			{
				translate_user_input('\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);
			do_filedesc();
			break;
		} 
	}

	/* 
	 * Various things that need to be done synchronously...
	 */

	/* deal with caught signals - pegasus */
	if (signals_caught[0] != 0)
		do_signals();

	/* Account for dead child processes */
	get_child_exit(-1);

	/* Run /DEFERed commands */
	if (level == 1 && need_defered_commands)
		do_defered_commands();

	/* Make sure all the servers are connected that ought to be */
	window_check_servers();

	/* Make sure all the channels are joined that ought to be */
	window_check_channels();

	/* Redraw the screen after a SIGCONT */
	if (need_redraw)
		redraw_all_screens();

	if (x_debug & DEBUG_SEQUENCE_POINTS)
		update_all_status();

	/* Make sure all the windows and status bars are made current */
	update_all_windows();

	/* Move the cursor back to the input line */
	cursor_to_input();

	/* Release this io() accounting level */
	caller[level] = NULL;
	level--;

	if (level == 0)
		check_message_from_queue(0);

	return;
}

/*************************************************************************/
void    load_ircrc (void)
{
	if (startup_file || quick_startup)
		return;

	/* 
	 * epicrc_file and ircrc_file can't be NULL here, but try 
	 * telling clang's static analyzer that... bleh
	 */
	if (epicrc_file && access(epicrc_file, R_OK) == 0)
		startup_file = malloc_strdup(epicrc_file);
	else if (ircrc_file && access(ircrc_file, R_OK) == 0)
		startup_file = malloc_strdup(ircrc_file);
	else
		startup_file = malloc_strdup("global");

	load("LOAD", startup_file, empty_string);
}

/*************************************************************************/
int 	main (int argc, char *argv[])
{
	setlocale(LC_ALL, "");
	setlocale(LC_NUMERIC, "C");

	create_utf8_locale();
	setvbuf(stdout, NULL, _IOLBF, 1024);
        get_time(&start_time);

	init_levels();
	init_transforms();
	init_recodings();
	init_variables_stage1();
	parse_args(argc, argv);
	init_binds();
	init_keys();
	init_commands();
	init_functions();
	init_expandos();
	init_newio();
	init_ctcp();

	fprintf(stderr, "EPIC Version 5 -- %s\n", ridiculous_version_name);
	fprintf(stderr, "EPIC Software Labs (2006)\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, "OpenSSL version: %#8.8lx\n", OpenSSL_version_num());

	/* If we're a bot, do the bot thing. */
	if (!use_input)
	{
		pid_t	child_pid;

		child_pid = fork();
		if (child_pid == -1)
		{
			fprintf(stderr, "Could not fork a child process: %s\n",
					strerror(errno));
			_exit(1);
		}
		else if (child_pid > 0)
		{
			fprintf(stderr, "Process [%d] running in background\n",
					child_pid);
			_exit(0);
		}
	}
	else
	{
		fprintf(stderr, "Process [%d]", getpid());
		if (isatty(0))
			fprintf(stderr, " connected to tty [%s]", ttyname(0));
		else
			dumb_mode = 1;
		fprintf(stderr, "\n");
	}

	init_signals();
	init_signal_names();

	/* 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);
	my_signal(SIGUSR2, sig_user2);

	message_from(NULL, LEVEL_OTHER);

	/* 
	 * We use dumb mode for -d, -b, when stdout is redirected to a file,
	 * or as a failover if init_screen() fails. 
	 */
	if ((dumb_mode == 0) && (init_screen() == 0))
	{
		my_signal(SIGCONT, term_cont);
		my_signal(SIGWINCH, sig_refresh_screen);

		init_variables_stage2();
		permit_status_update(1);
		build_status(NULL);
		update_input(-1, UPDATE_ALL);
	}
	else
	{
		if (background)
		{
			my_signal(SIGHUP, SIG_IGN);
			if (!freopen("/dev/null", "w", stdout)) 
				(void) 0;
		}
		dumb_mode = 1;		/* Just in case */
		create_new_screen();
		new_window(main_screen);
		init_variables_stage2();
		build_status(NULL);
	}

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

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

	load_ircrc();

	init_input();

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

	/* The user may have used -S and /server in their startup script */
	window_check_servers();

	get_time(&idle_time);
	reset_system_timers();

	/*
	 * Have you ever seen a setjmp() before?
	 * The first time it returns 0 (thus is false and falls through)
	 * The second time it returns != 0 (thus is true, and calls itself twice)
	 * Consequently, this loop assures that panic_jumpseat is initialized.
	 * You can return here later with longjmp(panic_jumpseat);
	 */
	while (setjmp(panic_jumpseat))
		system_reset = 1;

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