File: irc.c

package info (click to toggle)
ircii-pana 1%3A1.1-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 14,048 kB
  • ctags: 14,567
  • sloc: ansic: 130,654; sql: 6,041; makefile: 4,313; cpp: 1,270; tcl: 1,230; sh: 638; java: 151
file content (1712 lines) | stat: -rw-r--r-- 38,641 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
/*
 * ircII: a new irc client.  I like it.  I hope you will too!
 *
 * Written By Michael Sandrof
 * Copyright(c) 1990 
 * See the COPYRIGHT file, or do a HELP IRCII COPYRIGHT 
 */

#define __irc_c

#include "irc.h"
#include "struct.h"

static char cvsrevision[] = "$Id: irc.c,v 1.1.1.2 2003/06/11 07:00:42 root Exp $";
CVS_REVISION(irc_c)

#include <sys/types.h>
#include <sys/stat.h>
#include <pwd.h>
#ifdef USING_CURSES
#include <curses.h>
#endif
#include <stdarg.h>

#include "status.h"
#include "dcc.h"
#include "names.h"
#include "vars.h"
#include "input.h"
#include "alias.h"
#include "output.h"
#include "ircterm.h"
#include "exec.h"
#include "flood.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 "numbers.h"
#include "mail.h"
#include "debug.h"
#include "newio.h"
#include "timer.h"
#include "whowas.h"
#include "misc.h"
#include "gui.h"
#include "cdns.h"
#include "tcl_bx.h"
#include "ssl.h"
#include <pwd.h>
#define MAIN_SOURCE
#include "modval.h"

#ifdef __EMX__
#include <signame.h>
#endif

#ifndef VERSION
	const char irc_version[] = "BitchX-1.1-final";
#else
	const char irc_version[] = VERSION;
#endif

/*
 * major version is 75
 * minor version is 14
 * 000 is non-alpha/non-patch
 * 001 is alpha 
 * 002 is patch
 */
const unsigned long bitchx_numver = 100001;

/*
 * INTERNAL_VERSION is the number that the special alias $V returns.
 * Make sure you are prepared for floods, pestilence, hordes of locusts( 
 * and all sorts of HELL to break loose if you change this number.
 * Its format is actually YYYYMMDD, for the _release_ date of the
 * client..
 */
const char internal_version[] = "20040326";

int	irc_port = IRC_PORT,			/* port of ircd */
	strip_ansi_in_echo,
	current_on_hook = -1,			/* used in the send_text()
						 * routine */
	use_flow_control = USE_FLOW_CONTROL,	/* true: ^Q/^S used for flow
						 * cntl */
	current_numeric,			/* this is negative of the
						 * current numeric! */
	dumb_mode = 0,				/* if true, IRCII is put in
						 * "dumb" mode */
	bflag = 1,
	
	use_input = 1,				/* if 0, stdin is never
						 * checked */
	waiting_out = 0,				/* used by /WAIT command */
	waiting_in = 0,				/* used by /WAIT command */
	who_mask = 0,				/* keeps track of which /who
						 * switchs are set */
	dead	   = 0, 
	inhibit_logging = 0,
#ifndef ONLY_STD_CHARS
	startup_ansi = 1,			/* display startup ansi */
#else
#ifdef ASCII_LOGO
	startup_ansi = 1,			/* display startup ansi */
#else
	startup_ansi = 0,			/* DO NOT display startup ansi */
#endif
#endif
	auto_connect = 1,			/* auto-connect to first server*/

	background = 0,
	do_check_pid = 0,
	do_ignore_ajoin = 0,
#ifdef HAVE_SSL
	do_use_ssl = 0,
#endif
	run_level = 0,

	foreground = 1,
	reconnect = 0,				/* reconnecting to old process */
	use_nat_address = 0,			/* use NAT address */
	term_initialized = 0;
	
char	zero[]	= "0",
	one[]	= "1",
	space[]	= " ",
	space_plus[] = " +",
	space_minus[] = " -",
	dot[]   = ".",
	star[]	= "*",
	comma[] = ",",
	empty_string[] = "",
	on[]	= "ON",
	off[]	= "OFF";
		 
const	char	*unknown_userhost = "<UNKNOWN>@<UNKNOWN>";

char	oper_command = 0;	/* true just after an oper() command is
				 * given.  Used to tell the difference
				 * between an incorrect password generated by
				 * an oper() command and one generated when
				 * connecting to a new server */
	struct	sockaddr_foobar	MyHostAddr;		/* The local machine address */
	struct	sockaddr_foobar LocalHostAddr;
char	*LocalHostName = NULL;

char	*channel = NULL;


int		inbound_line_mangler = 0,
		logfile_line_mangler = 0,
		operlog_line_mangler = 0,
		outbound_line_mangler = 0;



char	*invite_channel = NULL,		/* last channel of an INVITE */
	*ircrc_file = NULL,		/* full path .ircrc file */
	*bircrc_file = NULL,		/* full path .ircrc file */
	*my_path = NULL,		/* path to users home dir */
	*irc_path = NULL,		/* paths used by /load */
	*irc_lib = NULL,		/* path to the ircII library */
	*ircservers_file = NULL,	/* name  of server file */
	nickname[NICKNAME_LEN + 1],	/* users nickname */
	hostname[NAME_LEN + 1],		/* name of current host */
	userhost[(NAME_LEN + 1) * 2],
	realname[REALNAME_LEN + 1],	/* real name of user */
	username[NAME_LEN + 1],		/* usernameof user */
	attach_ttyname[500],		/* ttyname for this term */
	socket_path[500],		/* ttyname for this term */
	*forwardnick = NULL,		/* used for /forward */
	*send_umode = NULL,		/* sent umode */
	*args_str = NULL,		/* list of command line args */
	*last_notify_nick = NULL,	/* last detected nickname */
	*auto_str = NULL,		/* auto response str */
	*new_script = NULL,		/* rephacement for .bitchxrc and .ircrc */
	*cut_buffer = NULL;		/* global cut_buffer */

	int quick_startup = 0;		/* set if we ignore .ircrc */
	int cpu_saver = 0;

	int use_socks = 0;		/* do we use socks info to connect */
	char	*old_tty = NULL,	/* re-attach tty and password */
		*old_pass = NULL;
	
extern char *FromUserHost;

		
	int cx_line = 0;
	char cx_file[BIG_BUFFER_SIZE/4];		/* debug file info */
	char cx_function[BIG_BUFFER_SIZE/4];
extern	int	doing_privmsg, doing_notice;




time_t	idle_time = 0,
	now = 0,
	start_time;
fd_set	readables, writables;
struct in_addr nat_address;


static	void	quit_response (char *, char *);
static	void	versionreply (void);
static	char	*parse_args (char **, int, char **);
static	void	remove_pid(void);
	void	do_ansi_logo(int);
	
extern void set_process_bits(fd_set *rd);

static	volatile int	cntl_c_hit = 0;

	char	version[] = _VERSION_;
	
static		char	*switch_help[] = {
"Usage: BitchX [switches] [nickname] [server list] \n",
"  The [nickname] can be at most 15 characters long\n",
"  The [server list] is a whitespace separate list of server name\n",
"  The [switches] may be any or all of the following\n",
#ifndef WINNT
"   -H <hostname>\tuses the virtual hostname if possible\n",
#endif
"   -N do not auto-connect to the first server\n",
"   -A do not display the startup ansi\n",
"   -c <channel>\tjoins <channel> on startup. don\'t forget to escape the # using \\\n",
#if defined(WINNT) || defined(__EMX__)
"   -b\t\tload bx-rc or irc-rc after connecting to a server\n",
#else
"   -b\t\tload .bitchxrc  or .ircrc after connecting to a server\n",
#endif
"   -p <port>\tdefault server connection port (usually 6667)\n",
#ifndef WINNT
"   -f\t\tyour terminal uses flow controls (^S/^Q), so BitchX shouldn't\n",
"   -F\t\tyour terminal doesn't use flow control (default)\n",
#endif
	"   -d\t\truns BitchX in \"dumb\" terminal mode\n",
#if defined(WINNT) || defined(__EMX__)
"   -q\t\tdoes not load ~/irc-rc\n",
#else
"   -q\t\tdoes not load ~/.ircrc\n",
#endif
"   -r file\tload file as list of servers\n",
"   -n nickname\tnickname to use\n",
"   -a\t\tadds default servers and command line servers to server list\n",
"   -x\t\truns BitchX in \"debug\" mode\n",
"   -Z\t\tuse NAT address when doing dcc.\n",
"   -P\t\ttoggle check pid.nickname for running program.\n",
"   -v\t\ttells you about the client's version\n",
#ifdef HAVE_SSL
"   -s\t\tservers specified are SSL.\n",
"   -ssl2\t\tservers specified are SSL (v2 only).\n",
"   -ssl3\t\tservers specified are SSL (v3 only).\n",
#endif
"   -i\t\tignores the autojoin list entries.\n",
#if defined(WINNT) || defined(__EMX__)
"   -l <file>\tloads <file> in place of your irc-rc\n\
   -L <file>\tloads <file> in place of your irc-rc and expands $ expandos\n",
#else
"   -l <file>\tloads <file> in place of your .ircrc\n\
   -L <file>\tloads <file> in place of your .ircrc and expands $ expandos\n",
#endif
#if !defined(WINNT) && !defined(__EMX__)
"   -B\t\tforce BitchX to fork and return you to shell. pid check on.\n",
#endif
NULL };

char	*time_format = NULL;	/* XXX Bogus XXX */
#ifdef __EMX__
char	*strftime_24hour = "%H:%M";
#else
char	*strftime_24hour = "%R";
#endif
char	*strftime_12hour = "%I:%M%p";
char	time_str[61];

void detachcmd(char *, char *, char *, char *);



/* update_clock: figUres out the current time and returns it in a nice format */
char	*BX_update_clock(int flag)
{
	static	int		min = -1,
				hour = -1;
	static	time_t		last_minute = -1;
	time_t			idlet;
	static struct tm	time_val;
		time_t		hideous;
		int		new_minute = 0;
		int		new_hour = 0;

	hideous = now;

#if !defined(NO_CHEATING)
	if (hideous / 60 > last_minute)
	{
		last_minute = hideous / 60;
		time_val = *localtime(&hideous);
	}
#else
	time_val = *localtime(&hideous);
#endif


	if (flag == RESET_TIME || time_val.tm_min != min || time_val.tm_hour != hour)
	{
		int ofs = from_server;
		from_server = primary_server;
		
		if (time_format)	/* XXXX Bogus XXXX */
			strftime(time_str, 60, time_format, &time_val);
		else if (get_int_var(CLOCK_24HOUR_VAR))
			strftime(time_str, 60, strftime_24hour, &time_val);
		else
			strftime(time_str, 60, strftime_12hour, &time_val);

		lower(time_str);
		if ((time_val.tm_min != min) || (time_val.tm_hour != hour))
		{
			int is_away = 0;
			if (time_val.tm_hour != hour)
				new_hour = 1;
			new_minute = 1;
			hour = time_val.tm_hour;
			min = time_val.tm_min;
			do_hook(TIMER_LIST, "%02d:%02d", hour, min);
			if (min == 0 || new_hour)
				do_hook(TIMER_HOUR_LIST, "%02d:%02d", hour, min);
			idlet = (hideous - idle_time) / 60L;
			if (from_server != -1)
				is_away = get_server_away(from_server) ? 1 : 0;
			if (do_hook(IDLE_LIST, "%lu", (unsigned long)idlet))
			{
				if (is_away && new_hour && get_int_var(TIMESTAMP_AWAYLOG_HOURLY_VAR))
					logmsg(LOG_CRAP, NULL, 4, NULL);
				if (!is_away && get_int_var(AUTO_AWAY_TIME_VAR) && (idlet >= get_int_var(AUTO_AWAY_TIME_VAR)/60))
					auto_away(idlet);
			}
			check_channel_limits();
		}
		if (!((hideous - start_time) % 20))
			check_serverlag();
		from_server = ofs;
		if (flag != RESET_TIME || new_minute)
			return time_str;
		else
			return NULL;
	}
	if (flag == GET_TIME)
		return time_str;
	else
		return NULL;
}

void reset_clock(Window *win, char *unused, int unused1)
{
	update_clock(RESET_TIME);
	update_all_status(win, NULL, 0);
}



/* sig_refresh_screen: the signal-callable version of refresh_screen */
SIGNAL_HANDLER(sig_refresh_screen)
{
	refresh_screen(0, NULL);
}

/* irc_exit: cleans up and leaves */
SIGNAL_HANDLER(irc_exit_old)
{
	irc_exit(1,NULL, NULL);
}

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.
 */
SIGNAL_HANDLER(child_reap)
{
	dead_children_processes++;
#ifdef __EMX__
	my_signal(SIGCHLD, SIG_IGN, 0);
#endif
}

SIGNAL_HANDLER(nothing)
{
      /* nothing to do! */
}
                           
SIGNAL_HANDLER(sigpipe)
{
static int sigpipe_hit = 0;
	sigpipe_hit++;
	
}
          
#if 0
SIGNAL_HANDLER(sigusr2)
{
	mtrace();
}
SIGNAL_HANDLER(sigusr3)
{
	muntrace();
}
#endif

/* irc_exit: cleans up and leaves */
void BX_irc_exit (int really_quit, char *reason, char *format, ...)
{
	char buffer[BIG_BUFFER_SIZE];
		
	logger(current_window, NULL, 0);
	if (get_int_var(MSGLOG_VAR))
		log_toggle(0, NULL);
	if (format)
	{
		va_list arglist;
		va_start(arglist, format);
		vsprintf(buffer, format, arglist);
		va_end(arglist);
	}
	else
		sprintf(buffer, "%s -- just do it.",irc_version);

	if (really_quit)
	{
		put_it("%s", convert_output_format("$G Signon time  :    $0-", "%s", my_ctime(start_time)));
		put_it("%s", convert_output_format("$G Signoff time :    $0-", "%s", my_ctime(now)));
		put_it("%s", convert_output_format("$G Total uptime :   $0-", "%s", convert_time(now - start_time)));
	}
	do_hook(EXIT_LIST, "%s", reason ? reason : buffer);

	close_all_servers(reason ? reason : buffer);

	put_it("%s", buffer ? buffer : reason ? reason : empty_string);


	clean_up_processes();
	if (!dumb_mode && term_initialized)
	{
		cursor_to_input();	/* Needed so that ircII doesn't gobble
					 * the last line of the kill. */
		term_cr();
		term_clear_to_eol();
		term_reset();
	}

	destroy_call_stack();

#if defined(THREAD) && defined(WANT_NSLOOKUP)
	kill_dns();
#endif

	remove_pid();
	if (really_quit)
	{
		
#ifdef GUI
		gui_exit();
#else
#if defined(WANT_DETACH) && !defined(GUI)
		kill_attached_if_needed(0);
#endif
		fprintf(stdout, "\r");
		fflush(stdout);
		exit(0);
#endif
	}
}

#ifndef WANT_CORE
volatile int segv_recurse = 0;
/* sigsegv: something to handle segfaults in a nice way */
/* this needs to be changed to *NOT* use printf(). */
SIGNAL_HANDLER(coredump)
{
#if defined(WINNT)
extern char *sys_siglist[];
#endif
	if (segv_recurse)
		_exit(1);
	segv_recurse = 1;
	panic_dump_call_stack();
	
#ifdef TDEBUG
	putlog(LOG_ALL, "*", "Error logged. %s at (%d)  %s", cx_file, cx_line, cx_function?cx_function:empty_string);
#endif
	printf("\n\r\n\rIRCII has been terminated by a [%s]\n\r", sys_siglist[unused]);
	printf("Please inform panasync (edwards@bitchx.dimension6.com) of this\n\r");
	printf("with as much detail as possible about what you were doing when it happened.\n\r");
	printf("Please include the version of IRCII (%s) and type of system in the report.\n\r", irc_version);
	fflush(stdout);
	irc_exit(1, "Hmmmm... BitchX error!!!! unusual :)", NULL);
}
#endif

/*
 * 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][ %s:  Rest in peace", irc_version);
}

/* irc_quit: prompts the user if they wish to exit, then does the right thing */
void irc_quit(char key, char * ptr)
{
	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. 
 */
SIGNAL_HANDLER(cntl_c)
{

	if (cntl_c_hit++ >= 4)
		irc_exit(1, "User abort with 5 Ctrl-C's", NULL);
	else if (cntl_c_hit > 1)
		kill(getpid(), SIGALRM);
}

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


SIGNAL_HANDLER(sig_detach)
{
	detachcmd(NULL, NULL, NULL, NULL);
}

void set_detach_on_hup(Window *dummy, char *unused, int value)
{
	if(value)
		my_signal(SIGHUP, sig_detach, 0);
	else
		my_signal(SIGHUP, irc_exit_old, 0);
}

/* shows the version of irc */
static	void versionreply(void)
{
	printf("BitchX version %s (%s)\n\r", irc_version, internal_version);
	exit (0);
}

#ifndef RAND_MAX
#define RAND_MAX 2147483647
#endif

void display_bitchx(int j) 
{

int i = 0;
int old_strip_ansi = strip_ansi_in_echo;

	if (j == -1)
#ifdef ASCII_LOGO
	        i = (int) (5.0*rand()/RAND_MAX);
#else
	        i = (int) (17.0*rand()/RAND_MAX);
#endif   
	else
		i = j;

	if (!startup_ansi)
		return;

	strip_ansi_in_echo = 0; 

#ifndef ASCII_LOGO
#if !defined(WINNT) && !defined(__EMX__)
	charset_ibmpc();
#endif
#endif

	do_ansi_logo(i);

#ifndef ASCII_LOGO
#if !defined(WINNT) && !defined(__EMX__)
#if defined(LATIN1)
	charset_lat1();
#elif defined(CHARSET_CUSTOM)
	charset_cst();
#endif
#endif
#endif

	strip_ansi_in_echo = old_strip_ansi;
}



/*
 * parse_args: parse command line arguments for irc, and sets all initial
 * flags, etc. 
 *
 * major rewrite 12/22/94 -jfn
 *
 *
 * Im going to break backwards compatability here:  I think that im 
 * safer in doing this becuase there are a lot less shell script with
 * the command line flags then there are ircII scripts with old commands/
 * syntax that would be a nasty thing to break..
 *
 * Sanity check:
 *   Supported flags: -b, -l, -v, -c, -p, -f, -F, -L, -a, -S, -z
 *   New (changed) flags: -s, -I, -i, -n
 *
 * Rules:
 *   Each flag must be included by a hyphen:  -lb <filename> is not the
 * 		same as -l <filename> -b  any more...
 *   Each flag may or may not have a space between the flag and the argument.
 *   		-lfoo  is the same as -l foo
 *   Anything surrounded by quotation marks is honored as one word.
 *   The -c, -p, -L, -l, -s, -z flags all take arguments.  If no argumenTs
 *		are given between the flag and the next flag, an error
 * 		message is printed and the program is halted.
 *		Exception: the -s flag will be accepted without a argument.
 *		(ick: backwards compatability sucks. ;-)
 *   Arguments occuring after a flag that does not take an argument
 * 		will be parsed in the following way: the first instance
 *		will be an assumed nickname, and the second instance will
 *		will be an assumed server. (some semblance of back compat.)
 *   The -bl sequence will emit a depreciated feature warning.
 *   The -I flag forces you to become invisible <NOT YET SUPPORTED>
 *   The -i flag forces you to become visible <NOT YET SUPPORTED>
 *   The -X flag forces ircII to become an X application <NOT YET SUPPORTED>
 *   The -n flag means "nickname"
 *
 * Bugs:
 *   The -s flag is hard to use without an argument unless youre careful.
 */
#ifdef CLOAKED
extern char proctitlestr[140];
extern char **Argv;
extern char *LastArgv;
#endif


static	char	*parse_args (char *argv[], int argc, char **envp)
{
	int ac;
	int add_servers = 0;
#if !defined(WINNT)
	struct passwd *entry;
#endif
	char *channel = NULL;
	struct hostent * hp;
	char *ptr;
	
	*nickname = 0;

#ifdef CLOAKED
	Argv = argv;
	while (*envp)
		envp++;
	LastArgv = envp[-1] + strlen(envp[-1]);
#endif                    

	for ( ac = 1; ac < argc; ac++ )
	{
		if (argv[ac][0] == '-')
		{
		    switch (argv[ac][1]) {

			case 'A': /* turn off startup ansi */
				startup_ansi =  0;
				break;
			case 'v': /* Output ircII version */
			{
				versionreply();
				/* NOTREACHED */
			}

			case 'c': /* Default channel to join */
			{
				char *what = empty_string;

				if (argv[ac][2])
					what = &(argv[ac][2]);
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
				{
					fprintf(stderr, "Missing parameter after -c\n");
					exit(1);
				}
				malloc_strcpy(&channel, what);
				break;
			}

			case 'p': /* Default port to use */
			{
				char *what = empty_string;
				if (reconnect)
				{
					what = getpass("Enter password : ");
					if (what && *what)
						malloc_strcpy(&old_pass, what);
					break;
				}

				if (argv[ac][2])
					what = &argv[ac][2];
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
				{
					fprintf(stderr, "Missing parameter after -p\n");
					exit(1);
				}
				irc_port = my_atol(what);
				break;
			}
#ifndef WINNT
			case 'f': /* Use flow control */
			{
				use_flow_control = 1;
				if (argv[ac][2])
					fprintf(stderr, "Ignoring junk after -f\n");
				break;
			}

			case 'F': /* dont use flow control */
			{
				use_flow_control = 0;
				if (argv[ac][2])
					fprintf(stderr, "Ignoring junk after -F\n");
				break;
			}
#endif
			case 'd': /* use dumb mode */
			{
#if 0
				dumb_mode = 1;
				if (argv[ac][2])
					fprintf(stderr, "Ignoring junk after -d\n");
#else
				fprintf(stderr, "Dumb mode is no longer supported.\n");
				exit(1);
#endif
				break;
			}

			case 'l': /* Load some file instead of ~/.ircrc */
			{
				char *what = empty_string;

				if (argv[ac][2])
					what = &argv[ac][2];
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
				{
					fprintf(stderr, "Missing argument to -l\n");
					exit(1);
				}
				malloc_strcpy(&new_script, what);
				break;
			}

			case 'L': /* load and expand */
			{
				char *what = empty_string;

				if (argv[ac][2])
					what = &argv[ac][2];
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
				{
					fprintf(stderr, "Missing argument to -L\n");
					exit(1);
				}
				malloc_strcpy(&ircrc_file, what);
/*				malloc_strcat(&ircrc_file, " -");*/
				break;
			}

			case 'r': /* Load list of servers from this file */
			{
				char *what = empty_string;

				if (argv[ac][2])
					what = &argv[ac][2];
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
					fprintf(stderr, "Missing argumenT to -r\n");

				if (*what)
				{
					add_servers = 1;
					malloc_strcpy(&ircservers_file, what);
				}
				break;
			}
			case 'R':
				fprintf(stderr, "Use \"scr-bx\" to reconnect\r\n");
				exit(1);
				break;
			case 'a': /* add server, not replace */
			{
				add_servers = 1;
				if (argv[ac][2])
					fprintf(stderr, "Ignoring junk after -a\n");
				break;
			}

			case 'q': /* quick startup -- no .ircrc */
			{
				quick_startup = 1;
				if (argv[ac][2])
					fprintf(stderr, "Ignoring junk after -q\n");
				break;
			}

			case 'b':
			{
				bflag = 0;
				break;
			}

			case 'B':
			{
				if (argv[ac][2] && argv[ac][2] != 'l')
					fprintf(stderr, "Ignoring junk after -B\n");
				else if (argv[ac][2] == 'l')
				{
					fprintf(stderr, "Usage of -bl is decprecated: use -b -l instead.\n");
					exit(1);
				}
/*				dumb_mode = 1;*/
/*				use_input = 0;*/
				background = 1;
			}
			case 'P':
			{
				do_check_pid ^= 1;
				break;
			}
			case 'n':
			{
				char *what = empty_string;

				if (argv[ac][2])
					what = &(argv[ac][2]);
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
				{
					fprintf(stderr,"Missing argument for -n\n");
					exit(1);
				}
				strmcpy(nickname, what, NICKNAME_LEN);
				break;
			}
			case 'N':
			{
				auto_connect = 0;
				break;
			}
			case 'x': /* set server debug */
			{
				x_debug = (unsigned long)0xffffffff;
				if (argv[ac][2])
					fprintf(stderr, "Ignoring junk after -x\n");
				break;
			}
			case 'Z':
			{
				use_nat_address = 1;
				break;
			}

			case 'z':
			{
				char *what;
				if (argv[ac][2])
					what = &argv[ac][2];
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
					break;
				strmcpy(username, what, NAME_LEN);
				break;
			}
			case 'H':
			{
				char *what = empty_string;
				
				if (argv[ac][2])
					what = &(argv[ac][2]);
				else if (argv[ac+1] && argv[ac+1][0] != '-')
				{
					what = argv[ac+1];
					ac++;
				}
				else
				{
					fprintf(stderr, "You forgot to specify a hostname\n");
					
					exit(1);
				}
				malloc_strcpy(&LocalHostName, what);
				break;
			}
			case 'S':
				use_socks = 1;
				break;
			case 'i':
				do_ignore_ajoin = 1;
				break;
#ifdef HAVE_SSL
			case 's':
				if (strcmp (argv[ac], "-ssl2") == 0)
					do_use_ssl = 2;
				else if (strcmp (argv[ac], "-ssl3") == 0)
					do_use_ssl = 3;
				else
					do_use_ssl = 1;
				break;
#endif
			case '\0': 
				break;	/* ignore - alone */

			default:
				fprintf(stderr, "Unknown flag: %s\n",argv[ac]);
			case 'h':
				{
					int t = 0;

					while(switch_help[t])
					{
						fprintf(stderr, "%s", switch_help[t]);
						t++;
					}
					exit(1);
				}
		   } /* End of switch */
		}
		else
		{
			if (!strchr(argv[ac], '.') && !strchr(argv[ac], ',') && !*nickname)
				strmcpy(nickname, argv[ac], NICKNAME_LEN);
			else
				build_server_list(argv[ac]);
		}
	}

	if (!*nickname && (ptr = getenv("IRCNICK")))
		strmcpy(nickname, ptr, NICKNAME_LEN);

	if (!ircservers_file)
#if defined(WINNT) || defined(__EMX__)
		malloc_strcpy(&ircservers_file, "irc-serv");
#else
		malloc_strcpy(&ircservers_file, ".ircservers");
#endif
	/* v-- right there was a '!' that should not have been there. */
	if ((ptr = getenv("IRCLIB")))
	{
		malloc_strcpy(&irc_lib, ptr);
		malloc_strcat(&irc_lib, "/");
	}
	else
		malloc_strcpy(&irc_lib, IRCLIB);

	if (!ircrc_file && (ptr = getenv("IRCRC")))
		malloc_strcpy(&ircrc_file, ptr);

	if ((ptr = getenv("IRCUMODE")))
		malloc_strcpy(&send_umode, ptr);

	if ((ptr = getenv("IRCNAME")))
		strmcpy(realname, ptr, REALNAME_LEN);
	else if ((ptr = getenv("NAME")))
		strmcpy(realname, ptr, REALNAME_LEN);

	if ((ptr = getenv("IRCPATH")))
		malloc_strcpy(&irc_path, ptr);
	else
	{
#ifdef IRCPATH
		malloc_strcpy(&irc_path, IRCPATH);
#else
		malloc_strcpy(&irc_path, ".:~/.irc:");
		malloc_strcat(&irc_path, irc_lib);
		malloc_strcat(&irc_path, "script");
#endif
	}

	set_string_var(LOAD_PATH_VAR, irc_path);
	new_free(&irc_path);
	
#ifndef WINNT
	if ((entry = getpwuid(getuid())))
	{
		if (!*realname && entry->pw_gecos && *(entry->pw_gecos))
		{
#ifdef GECOS_DELIMITER
			if ((ptr = index(entry->pw_gecos, GECOS_DELIMITER)))
				*ptr = (char) 0;
#endif
			if ((ptr = strchr(entry->pw_gecos, '&')) == NULL)
				strmcpy(realname, entry->pw_gecos, REALNAME_LEN);
			else {
				int len = ptr - entry->pw_gecos;

				if (len < REALNAME_LEN && *(entry->pw_name)) {
					char *q = realname + len;

					strmcpy(realname, entry->pw_gecos, len);
					strmcat(realname, entry->pw_name, REALNAME_LEN);
					strmcat(realname, ptr + 1, REALNAME_LEN);
					if (islower((unsigned char)*q) && (q == realname || isspace((unsigned char)*(q - 1))))
						*q = toupper(*q);
				} else
					strmcpy(realname, entry->pw_gecos, REALNAME_LEN);
			}
		}
		if (entry->pw_name && *(entry->pw_name) && !*username)
			strmcpy(username, entry->pw_name, NAME_LEN);
		if (entry->pw_dir && *(entry->pw_dir))
			malloc_strcpy(&my_path, entry->pw_dir);
	}
#else
	{
		u_long size=NAME_LEN+1;
		if (!(ptr = getenv("IRCUSER")))
			strcpy(username, "unknown");
		else
			strncpy(username,ptr, size);
	}
#endif

	if ((ptr = getenv("HOME")))
		malloc_strcpy(&my_path, ptr);
	else if (!my_path || !*my_path)
#ifdef WINNT
		malloc_strcpy(&my_path, empty_string);
#else
		malloc_strcpy(&my_path, "/");
#endif
#if defined(WINNT) || defined(__EMX__)
	convert_unix(my_path);
#endif
	if (!*realname)
		strmcpy(realname, "* I'm too lame to read BitchX.doc *", REALNAME_LEN);

       /*
        * Yes... this is EXACTLY what you think it is.  And if you don't know..
        * then I'm not about to tell you!           -- Jake [WinterHawk] Khuon
        */
	if ((ptr = getenv("IRCUSER"))) strmcpy(username, ptr, NAME_LEN);
	else if ((ptr = getenv("USER"))) strmcpy(username, ptr, NAME_LEN);
	else if (!*username)
	{
#ifdef IDENT_FAKE
		char *p = NULL, *q = NULL;
		FILE *f;
		malloc_sprintf(&p, "~/%s", get_string_var(IDENT_HACK_VAR));
		q = expand_twiddle(p);
		if ((f = fopen(q, "r")))
		{
			fgets(username, NAME_LEN, f);
			if (*username && strchr(username, '\n'))
				username[strlen(username)-1] = 0;
		}
		fclose(f);
		new_free(&p); new_free(&q);
		if (!*username)
#endif
			strmcpy(username, "Unknown", NAME_LEN); 

	}

	if (!LocalHostName && ((ptr = getenv("IRC_HOST")) || (ptr = getenv("IRCHOST"))))
		LocalHostName = m_strdup(ptr);

	if ((gethostname(hostname, sizeof(hostname))))
		if (!LocalHostName)
			exit(1);

	if (LocalHostName)
	{
		printf("Your hostname appears to be [%s]\n", LocalHostName);
#ifndef IPV6
		memset((void *)&LocalHostAddr, 0, sizeof(LocalHostAddr));
		if ((hp = gethostbyname(LocalHostName)))
			memcpy((void *)&LocalHostAddr.sf_addr, hp->h_addr, sizeof(struct in_addr));
	} 
	else
	{
		if ((hp = gethostbyname(hostname)))
			memcpy((char *) &MyHostAddr.sf_addr, hp->h_addr, sizeof(struct in_addr));
#endif
	}

	if (!nickname || !*nickname)
		strmcpy(nickname, username, NICKNAME_LEN);

	if (!check_nickname(nickname))
	{
		fprintf(stderr, "Illegal nickname %s\n", nickname);
		fprintf(stderr, "Please restart IRC II with a valid nickname\n");
		exit(1);
	}
	if (ircrc_file == NULL)
	{
		ircrc_file = (char *) new_malloc(strlen(my_path) + strlen(IRCRC_NAME) + 1);
		strcpy(ircrc_file, my_path);
		strcat(ircrc_file, IRCRC_NAME);
	}
	if (bircrc_file == NULL)
#if defined(WINNT) || defined(__EMX__)
		malloc_sprintf(&bircrc_file, "%s/bx-rc", my_path);
#else
		malloc_sprintf(&bircrc_file, "%s/.bitchxrc", my_path);
#endif

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

	if ((ptr = getenv("IRCSERVER")))
		build_server_list(ptr);
	
	if (!server_list_size() || add_servers)
	{
		if (!read_server_file(ircservers_file) && !server_list_size())
		{
#ifdef DEFAULT_SERVER
			char *ptr = NULL;
			malloc_strcpy(&ptr, DEFAULT_SERVER);
			build_server_list(ptr);
			new_free(&ptr);

#endif
			from_server = -1;
		}
	}
	return (channel);
}



/* 
 * 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.  It doesnt look like bad things
 * will happen if you call this elsewhere, but its long time behavior has
 * not been observed.  It *does* however, appear to be much more reliable
 * then the old irc_io, and i even know how this works. >;-)
 */
extern void set_screens (fd_set *, fd_set *);

void BX_io (const char *what)
{
	static	int	first_time = 1,	
			level = 0;
		long	clock_timeout = 0, 
			timer_timeout = 0,
			server_timeout = 0,
			real_timeout = 0; 
static	struct	timeval my_now,
			my_timer,
			*time_ptr = &my_timer;

	int		hold_over,
			rc;
	fd_set		rd, 
			wd;
	static int 	old_level = 0;
static	const	char	*caller[51] = { NULL }; /* XXXX */
	static	int	last_warn = 0;

	level++;

	get_time(&my_now);
	now = my_now.tv_sec;
	
	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 nesting level is [%d],  [%s]<-[%s]<-[%s]<-[%s]<-[%s]<-[%s]", level, what, caller[level-1], caller[level-2], caller[level-3], caller[level-4], caller[level-5]);
		if ((level % 30) == 0)
			ircpanic("Ahoy there matey!  Abandon ship!");
		return;
	}
	else if (level  && (last_warn -level == 5))
		last_warn -= 5;

	caller[level] = what;

	/* CHECK FOR CPU SAVER MODE */
	if (!cpu_saver && get_int_var(CPU_SAVER_AFTER_VAR))
		if (now - idle_time > get_int_var(CPU_SAVER_AFTER_VAR) * 60)
			cpu_saver_on(0, NULL);

	rd = readables;
	wd = writables;
	FD_ZERO(&wd);
	FD_ZERO(&rd);

#ifndef GUI
	set_screens(&rd, &wd);
#endif
	server_timeout = set_server_bits(&rd, &wd);
	set_process_bits(&rd);
	set_socket_read(&rd, &wd);
	set_nslookupfd(&rd);
#ifdef GUI
	gui_setfd(&rd);
#endif

	clock_timeout = (60 - (my_now.tv_sec % 60)) * 1000;
	if (cpu_saver && get_int_var(CPU_SAVER_EVERY_VAR))
		clock_timeout += (get_int_var(CPU_SAVER_EVERY_VAR) - 1) * 60000;

	timer_timeout = TimerTimeout();

	if ((hold_over = unhold_windows()))
		real_timeout = 0;
	else if (timer_timeout <= clock_timeout)
		real_timeout = timer_timeout;
	else
		real_timeout = clock_timeout;

	if(server_timeout && (server_timeout == -1 || server_timeout < real_timeout))
		real_timeout = server_timeout;

	time_ptr = &my_timer;

	if (real_timeout == -1)
		time_ptr = NULL;
	else
	{
		time_ptr->tv_sec = real_timeout / 1000;
		time_ptr->tv_usec = ((real_timeout % 1000) * 1000);
	}
	
	/* GO AHEAD AND WAIT FOR SOME DATA TO COME IN */
	switch ((rc = new_select(&rd, &wd, time_ptr)))
	{
		case 0:
			if(server_timeout)
				do_idle_server();
			break;
		case -1:
		{
			/* if we just got a sigint */
			first_time = 0;
			if (cntl_c_hit)
			{
				edit_char('\003');
/*				cntl_c_hit = 0; */
			}
			else if (errno != EINTR)
				yell("Select failed with [%s]", strerror(errno));
			break;

		}

		/* we got something on one of the descriptors */
		default:
		{
			cntl_c_hit = 0;
			now = time(NULL);
			make_window_current(NULL);
			do_server(&rd, &wd);
			do_processes(&rd);
			do_screens(&rd);
#ifdef WANT_CDCC
			dcc_sendfrom_queue();
#endif
			dcc_check_idle();
			print_nslookup(&rd);
			scan_sockets(&rd, &wd);
#ifdef GUI
			scan_gui(&rd);
#endif
			break;
		} 
	}

	now = time(NULL);
	ExecuteTimers();
#ifdef WANT_TCL
	check_utimers();
#endif	
	send_from_server_queue();
	get_child_exit(-1);

	if (!hold_over)
		cursor_to_input();


#ifdef WANT_LLOOK
	if (get_int_var(LLOOK_VAR) && from_server > -1 && !get_server_linklook(from_server)) 
	{
		if (now - get_server_linklook_time(from_server) > get_int_var(LLOOK_DELAY_VAR)) 
		{
			set_server_linklook(from_server, get_server_linklook(from_server)+1);
			my_send_to_server(from_server, "LINKS");
			set_server_linklook_time(from_server, now);
		}
	}
#endif
	if (update_clock(RESET_TIME))
	{
		do_notify();
#ifdef WANT_TCL
		check_timers();
#endif
		clean_whowas_chan_list();
		clean_whowas_list();
		clean_flood_list();
		clean_split_server_list(CHAN_SPLIT, 1800);
#ifdef WANT_LLOOK
		clean_split_server_list(LLOOK_SPLIT, 3600);
#endif
		if (get_int_var(CLOCK_VAR) || check_mail_status())
		{
			update_all_status(current_window, NULL, 0);
			cursor_to_input();
		}
		check_server_connect(from_server);
	}

	/* (set in term.c) -- we should redraw the screen here */
	if (need_redraw)
		refresh_screen(0, NULL);
	
	FromUserHost = empty_string;
	
	
	alloca(0);
	caller[level] = NULL;
	level--;
	return;
}

char pidfile[80];

void check_pid(void)
{
char *p = NULL;
FILE *t;
	if (!do_check_pid)
		return;
	p = expand_twiddle(DEFAULT_CTOOLZ_DIR);
	snprintf(pidfile, 79, "%s/pid.%s", p, nickname);
	if ((t = fopen(pidfile, "r")))
	{
		char buffer[80];
		int i;
		fgets(buffer, 10, t);
		i = atol(buffer);
		kill(i, SIGCHLD);
		if (errno != ESRCH)
		{
			fprintf(stderr, "Bitchx already running as %s\n", nickname);
			exit(1);
		}
	}
}

extern int save_ipc;

static void remove_pid(void)
{
#ifdef WANT_DETACH
char *p;
FILE *t;
	if (!do_check_pid)
		return;
	p = expand_twiddle(DEFAULT_CTOOLZ_DIR);
	snprintf(pidfile, 79, "%s/pid.%s", p, nickname);
	if ((t = fopen(pidfile, "r")))
	{
#if !defined(__EMX__) && !defined(WINNT) && !defined(GUI)
		SocketList *s;
		fclose(t);
		unlink(pidfile);
		if (save_ipc != -1 && (s = get_socket(save_ipc)))
		{
			char buf[500];
			sprintf(buf, s->server, s->port);
			unlink(buf);
		}
#endif
	}	
#endif
}

void setup_pid(void)
{
#ifdef WANT_DETACH
pid_t pid;
	if (!do_check_pid)
		return;
	if ((pid = getpid()))
	{
		FILE *t;
		unlink(pidfile);
		if ((t = fopen(pidfile, "w")))
		{
			fprintf(t, "%u\n", pid);
			fclose(t);
		}
	}
#endif
}


int main(int argc, char *argv[], char *envp[])
{
	srand((unsigned)time(NULL));
	time(&start_time);
	time(&idle_time);
	time(&now);

	/* We need to zero these early */
	FD_ZERO(&readables);
	FD_ZERO(&writables);

	/* First thing we need to do is initialize
	 * the global function table with the default
	 * function pointers.
	 */
	init_global_functions();

	/* Setup OS/2 */
#if defined(__EMX__)
	setvbuf(stdout, NULL, _IOLBF, 80);
#endif
	/* Setup the GUIs */
#ifdef GUI
	gui_startup(argc, argv);
#endif
        
#ifdef SOCKS
	SOCKSinit(argv[0]);
#endif

#ifdef TDEBUG
	*cx_file = 0;
	cx_line = 0;
	*cx_function = 0;
#endif

#if !defined(GUI) 

	printf("BitchX - Based on EPIC Software Labs epic ircII (1998).\r\n");
	printf("Version (%s) -- Date (%s).\r\n", irc_version, internal_version);
	printf("Process [%d]", getpid());
	if ((isatty(0) && !background) || (!isatty(0) && background))
	{
		char s[90];
		if (ttyname(0))
		{
			strncpy(s, ttyname(0), 85);
/*			printf(" connected to tty [%s]", s);*/
			strncpy(attach_ttyname, s, 400);
		}		
		else if (background)
			strcpy(attach_ttyname, "tty1");
	}
	else
		dumb_mode = 1;
	printf("\n");
#endif	

	
	channel = parse_args(argv, argc, envp);
	check_pid();
	init_socketpath();

#ifdef WANT_TCL
	tcl_interp = Tcl_CreateInterp();
#endif
	ns_init();
	
	if (!dumb_mode && term_init(NULL))
		_exit(1);

	if (background)
	{
#ifdef WANT_DETACH
#ifndef PUBLIC_ACCESS
		detachcmd(NULL, NULL, NULL, NULL);
#else
		exit(0);
#endif
#else
		fprintf(stderr, "Try compiling with WANT_DETACH\r\n");
		exit(0);
#endif
	}
#ifndef WANT_CORE
	my_signal(SIGSEGV, coredump, 0);
	my_signal(SIGBUS, coredump, 0);
#endif
	my_signal(SIGQUIT, SIG_IGN, 0);
#ifdef WANT_DETACH
	set_detach_on_hup(NULL, NULL, DEFAULT_DETACH_ON_HUP);
#else
	my_signal(SIGHUP, irc_exit_old, 0);
#endif
	my_signal(SIGTERM, irc_exit_old, 0);
	my_signal(SIGPIPE, SIG_IGN, 0);
	my_signal(SIGINT, cntl_c, 0);
	my_signal(SIGCHLD, child_reap, 0);
	my_signal(SIGALRM, nothing, 0);
	my_signal(SIGUSR1, sig_user1, 0);
#ifdef GTK
	my_signal(SIGTTOU, SIG_IGN, 0);
#endif
#if 0
	my_signal(SIGUSR1, sigusr2, 0);
	my_signal(SIGUSR2, sigusr3, 0);
#endif	
	init_output();

	if (!dumb_mode) 
	{
		init_screen();
		if (background)
		{
			use_input = 0;
			main_screen->fdin = main_screen->fdout = open("/dev/null", O_RDWR|O_NOCTTY);
			new_open(main_screen->fdin);
			main_screen->fpout = fdopen(1, "w");
			main_screen->fpin = fdopen(0, "r");
		}
#ifndef __EMX__
		my_signal(SIGCONT, term_cont, 0);
#if !defined(WINNT) && !defined(GTK)
		my_signal(SIGWINCH, sig_refresh_screen, 0);
#endif
#endif

	}
	else
	{
		if (background)
		{
			my_signal(SIGHUP, SIG_IGN, 0);
			background = 0;
#ifndef WANT_DETACH
			term_reset();
			fprintf(stderr, "try recompiling the client with WANT_DETACH defined\r\n");
			exit(0);
			use_input = 0;
#endif
		}
		create_new_screen();
		new_window(main_screen);
	}

	setup_pid();
	init_keys();
	init_keys2();
	init_variables();
	init_dcc_table();

#if defined(THREAD) && defined(WANT_NSLOOKUP)
	start_dns();
#endif
	
	if (!dumb_mode)
	{
		build_status(current_window, NULL, 0);
		update_input(UPDATE_ALL);
	}

	start_identd();

#ifdef WANT_TCL
	tcl_init();
#ifdef WANT_TK
	Tk_Init(tcl_interp);
#endif
	add_tcl_vars();
#endif
#ifdef HAVE_SSL
	{
		char *entropy = malloc(100);
		int i;

		for(i=0;i<100;i++)
			entropy[i] = (char) getrandom(0, 255);

		/* Many systems don't have /dev/random so we seed */
		RAND_seed(entropy, 100);
		SSLeay_add_ssl_algorithms();
		SSL_load_error_strings();
		free(entropy);
	}
#endif

#ifdef CLOAKED
	initsetproctitle(argc, argv, envp);
	sprintf(proctitlestr, CLOAKED);
	setproctitle("%s", proctitlestr);
#endif

	/* We move from run level 0 to run level 1
	 * signifying that we have completed the initial
	 * startup and are now ready to load scripts.
	 */
	run_level = 1;

	display_bitchx(-1);
	if (bflag)
		load_scripts();

#ifdef GUI
	gui_font_init();
#endif

	reinit_autoresponse(current_window, NULL, 0);
	if (auto_connect)
		get_connected(0, -1);
	else
		display_server_list();
	start_memdebug();	
		
	set_input(empty_string);
	set_input_prompt(current_window, get_string_var(INPUT_PROMPT_VAR), 0);

	/* We now move from run level 1 to run level 2
	 * signifying that we are in normal operation mode.
	 */
	run_level = 2;

	for (;;)
		io("main");
#ifdef GUI
	gui_exit();
#else
	ircpanic("get_line() returned");
#endif
	return (-((int)0xdead));
}