summary refs log blame commit diff stats
path: root/plugins/dns/dns.c
blob: 2bf58195b297058fb13330cb6e5c4b97490818c2 (plain) (tree)








































































































































































































































































































































                                                                                                                     
/* XChat Win32 DNS Plugin
 * Copyright (C) 2003-2004 Peter Zelezny.
 * Copyright (C) 2012 Berke Viktor.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */
/*
 * Requires MS Visual Studio and IPV6 headers to compile (run nmake).
 * Compiling with gcc (mingw) will fail due to missing gai_strerror.
 */

#define DNS_VERSION "2.4"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

#define USE_IPV6

#ifdef WIN32
#ifdef USE_IPV6
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <winsock2.h>
#endif
#else
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#endif

#include "xchat-plugin.h"
#include "thread.h"

#define HELP "Usage: DNS <nickname|hostname|numerical address>\n"
#define HEAD "\0034[DNS]\017\t"

#define PIPE_READ 0
#define PIPE_WRITE 1
#define MAX_HOSTNAME 128

static xchat_plugin *ph;
static thread *active_thread = NULL;


static int
waitline (void *source, char *buf, int bufsize)
{
	int i = 0;
	int len;

	while(1)
	{
		len = 1;
		/* we can't read() here, due to glib's giowin32 */
		if(ph->xchat_read_fd(ph, source, buf + i, &len) != 0)
			return -1;
		if(buf[i] == '\n' || bufsize == i + 1)
		{
			buf[i] = 0;
			return i;
		}
		i++;
	}
}

static void *
thread_function (void *ud)
{
#ifdef USE_IPV6
	struct addrinfo *ent;
	struct addrinfo *cur;
	struct addrinfo hints;
#else
	struct hostent *ent;
#endif
	thread *th = ud;
	int fd = th->pipe_fd[PIPE_WRITE];
	int ret;
	char ipstring[MAX_HOSTNAME];
	char reverse[MAX_HOSTNAME];
//	int i;

	active_thread = th;

#ifdef USE_IPV6
	memset (&hints, 0, sizeof (hints));
	hints.ai_family = PF_UNSPEC; /* support ipv6 and ipv4 */
	hints.ai_flags = AI_CANONNAME;
//	hints.ai_socktype = SOCK_STREAM;

	ret = getaddrinfo (th->userdata, NULL, &hints, &ent);
	if (ret != 0)
	{
		sprintf (ipstring, "1%d\n", ret);	/* failed */
		write (fd, ipstring, strlen (ipstring));
//		Sleep (3000);
		active_thread = NULL;
		return 0;
	}

//	i = 0;
	cur = ent;
	while (cur)
	{
		/* find the numeric IP number */
		ipstring[0] = 0;
		getnameinfo (cur->ai_addr, cur->ai_addrlen,
						 ipstring, sizeof (ipstring), NULL, 0, NI_NUMERICHOST);

		if (cur->ai_canonname)
		{
			/* force reverse lookup if canonname & ipstring are the same */
			if (/*i == 0 &&*/ strcmp (cur->ai_canonname, ipstring) == 0)
				goto lamecode;
		}

		if (cur->ai_canonname)
		{
			write (fd, "0", 1);
			write (fd, ipstring, strlen (ipstring));
			write (fd, "\n", 1);
			write (fd, cur->ai_canonname, strlen (cur->ai_canonname));
		} else
		{
lamecode:
	//		ret = 1;
	//		if (i == 0)
			{
				/* reverse lookup */
				reverse[0] = 0;
				ret = getnameinfo (cur->ai_addr, cur->ai_addrlen,
							 reverse, sizeof (reverse), NULL, 0, NI_NAMEREQD);
			}

			write (fd, "0", 1);
			write (fd, ipstring, strlen (ipstring));

			write (fd, "\n", 1);
			if (ret == 0)
				write (fd, reverse, strlen (reverse));
		}
		write (fd, "\n", 1);

//		i++;
		cur = cur->ai_next;
	}

	/* tell the parent we're done */
	write (fd, "2\n", 2);
	freeaddrinfo (ent);

#else
	ent = gethostbyname (th->userdata);
	if (ent)
	{
		write (fd, "0", 1);
		write (fd, ent->h_name, strlen (ent->h_name));
		write (fd, "\n", 1);
		write (fd, ent->h_name, strlen (ent->h_name));
		write (fd, "\n", 1);
		write (fd, "2\n", 2);
	} else
	{
		write (fd, "10\n", 1);
	}
#endif

//	Sleep (3000);
	active_thread = NULL;	/* race condition, better than nothing */

	return 0;
}

static int
dns_close_pipe (int fd)
{
	close (fd);
	return 0;
}

/* read messages comming from the child (through the pipe) */

static int
dns_read_cb (int fd, int flags, thread *th, void *source)
{
	char buf[512];
	char buf2[512];

	while (waitline (source, buf, sizeof (buf)))
	{
		switch (buf[0])
		{
		case '0':		/* got data to show */
			waitline (source, buf2, sizeof (buf2));
			if (buf2[0] == 0)
				xchat_printf(ph, HEAD"\002Numerical\002: %s\n", buf + 1);
			else
				xchat_printf(ph, HEAD"\002Canonical\002: %s \002Numerical\002: %s\n", buf2, buf + 1);
			return 1;

		case '1':		/* failed */
			xchat_printf(ph, HEAD"Lookup failed. %s\n", gai_strerrorA (atoi (buf + 1)));

		case '2':		/* done */
		//	close (th->pipe_fd[PIPE_WRITE]);
		//	close (th->pipe_fd[PIPE_READ]);
			xchat_hook_timer(ph, 3000, dns_close_pipe, (void *)th->pipe_fd[PIPE_WRITE]);
			xchat_hook_timer(ph, 4000, dns_close_pipe, (void *)th->pipe_fd[PIPE_READ]);
			free (th->userdata); 	/* hostname strdup'ed */
			free (th);
			return 0;
		}
	}

	return 1;
}

/* find hostname from nickname (search the userlist, current chan only) */

static char *
find_nick_host (char *nick)
{
	xchat_list *list;
	char *at;
	const char *host;

	list = xchat_list_get (ph, "users");
	if (!list)
		return NULL;

	while (xchat_list_next (ph, list))
	{
		if (stricmp (nick, xchat_list_str (ph, list, "nick")) == 0)
		{
			host = xchat_list_str (ph, list, "host");
			if (host)
			{
				at = strrchr (host, '@');
				if (at)
					return at + 1;
			}
			break;
		}
	}

	return NULL;
}

static int
dns_cmd_cb (char *word[], char *word_eol[], void *ud)
{
	thread *th;
	char *nickhost;

	if (!word[2][0])
	{
		xchat_print (ph, HELP);
		return XCHAT_EAT_ALL;
	}

	th = thread_new ();
	if (th)
	{
		nickhost = find_nick_host (word[2]);
		if (nickhost)
		{
			xchat_printf (ph, HEAD"Looking up %s (%s)...\n", nickhost, word[2]);
			th->userdata = strdup (nickhost);
		} else
		{
			xchat_printf (ph, HEAD"Looking up %s...\n", word[2]);
			th->userdata = strdup (word[2]);
		}

		if (thread_start (th, thread_function, th))
		{
			xchat_hook_fd(ph, th->pipe_fd[PIPE_READ],
							XCHAT_FD_READ | XCHAT_FD_EXCEPTION | XCHAT_FD_NOTSOCKET,
							(void *)dns_read_cb, th);

		}
	}

	return XCHAT_EAT_ALL;
}

int
xchat_plugin_deinit (xchat_plugin *plugin_handle)
{
	while (active_thread)	/* children will set this var to NULL soon... */
	{
		Sleep (1000);
	}
	xchat_printf (ph, "DNS plugin unloaded\n");
	return 1;
}

int
xchat_plugin_init
				(xchat_plugin *plugin_handle, char **plugin_name,
				char **plugin_desc, char **plugin_version, char *arg)
{
	/* we need to save this for use with any xchat_* functions */
	ph = plugin_handle;

	*plugin_name = "DNS";
	*plugin_desc = "Threaded IPv4/6 DNS Command";
	*plugin_version = DNS_VERSION;

	xchat_hook_command(ph, "DNS", XCHAT_PRI_LOW, dns_cmd_cb, HELP, 0);
	xchat_printf (ph, "DNS plugin loaded\n");

	return 1;       /* return 1 for success */
}
ass='alt'>
4a6ceffb ^
d03d6e60 ^



4a6ceffb ^

d03d6e60 ^











d0b5d53f ^
d03d6e60 ^
22064278 ^
d03d6e60 ^
22064278 ^
d03d6e60 ^


4a6ceffb ^


d03d6e60 ^











565a4927 ^
d03d6e60 ^










628100c1 ^
d03d6e60 ^



4a6ceffb ^
d03d6e60 ^

83032b1a ^
d03d6e60 ^

4a6ceffb ^
d03d6e60 ^

4a6ceffb ^
83032b1a ^
d03d6e60 ^
77cad8e7 ^
d03d6e60 ^

4a6ceffb ^
d03d6e60 ^


5d9264af ^
d03d6e60 ^




65da34f1 ^
5d9264af ^


d03d6e60 ^


4a6ceffb ^





d03d6e60 ^
bf27d430 ^

d03d6e60 ^
bf27d430 ^

4a6ceffb ^




d03d6e60 ^
4a6ceffb ^
d03d6e60 ^
4a6ceffb ^
d03d6e60 ^




4a6ceffb ^

d03d6e60 ^
4a6ceffb ^
d03d6e60 ^
4a6ceffb ^
d03d6e60 ^
4a6ceffb ^





d03d6e60 ^
4a6ceffb ^




4a6ceffb ^















606cb09f ^
4a6ceffb ^
















4a6ceffb ^




























f5631b2e ^

4a6ceffb ^
785455cc ^
4a6ceffb ^
f5631b2e ^

4a6ceffb ^
785455cc ^
4a6ceffb ^





















9f7444ba ^
4a6ceffb ^











4a6ceffb ^


































































































bbf2ad17 ^
4a6ceffb ^


9969282c ^
4a6ceffb ^














10d3c151 ^



4a6ceffb ^









d03d6e60 ^
4a6ceffb ^



d03d6e60 ^


cf78762b ^
d03d6e60 ^







4a6ceffb ^




























































4a6ceffb ^
bb5d589c ^




3a7fb4d8 ^




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














                                                                       
                                                                            

   

                   





                     
            
               



                       
                     
      
                      
                  
                        

                               
                               





                               





                                                          
                                                         

 

                                                                   
 
 



                                     
 
                                                                                                
                                                                       





                                         









                                               
                            




                                                    
                                  





                                   
                                      
                                    
                                                                             

                                                             
                                            










                                                                  
                          
                        




                                                
                                                                                              


          
                                 


                          




                                                               



                                 

                                                                            
                                                                                         


                                                                                         

                                                              




                                                            
                                                       
 
                                 

                               
                                              






                                           
                                                      












                                                 
                                             



























                                                                              
                                                                                             















                                                                                                          
                                                             





                                              


                                                                      




































                                                                         
                                                         


















                                                                         
                                                 




                                              
                    

                         
         




                                                    

                                          
                         
 

                                   
    

                                                              
 


                                                        
                                                       
 
                                 
         





                                              
                 


                                                      
                 






































                                                                              
                                                         











                                                     
                                                 







                                              
         






                                                    
                         






                              




                                                             
                                                                          

 





                                                                                  


                         
                              




                                                         

                            
 





                                                              
                                              
      
 





                                                      
 



                                                                   

 











                                                                                                                  
                                                                                                                        
                                                                                                          
                                                                                                                              
                                                                                                         
                                                                                                                             


       


                                











                                                                                   
 










                                                        
                                                            



                              
         

                                           
                                                    

                                         
                 

                                                      
                 
                             
     
                                               

                         
         


                            
                                             




                                                         
                              


                                                    


                                    





                  
                                                                              

                                          
                                                                              

                                     




              
                                   
 
                                                 
 




                                                                 

      
                                                                   
 
                                   
 
               





                    
                                    




                                   















                                      
                       
















                                                                      




























                                                                            

                                                                                      
 
                 
 

                                                   
 
                 





















                                               
                                                                             











                                                            


































































































                                                                               
                                                                                           


    
                                    














                                  



                                                                       









                                                              
                                



                                                          


                                                                      
                                                                                







                                                   




























































                                                                                                
                                                            




                                                              




                          
/* X-Chat
 * Copyright (C) 1998 Peter Zelezny.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#ifdef WIN32
#include <io.h>
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#else
#include <unistd.h>
#include <sys/time.h>
#endif
#include <sys/types.h>
#include <ctype.h>
#include <glib-object.h>
#include "../common/hexchat.h"
#include "../common/hexchatc.h"
#include "../common/cfgfiles.h"
#include "../common/outbound.h"
#include "../common/util.h"
#include "../common/fe.h"
#include "fe-text.h"


static int done = FALSE;		  /* finished ? */


static void
send_command (char *cmd)
{
	handle_multiline (current_tab, cmd, TRUE, FALSE);
}

static gboolean
handle_line (GIOChannel *channel, GIOCondition cond, gpointer data)
{

	gchar *str_return;
	gsize length, terminator_pos;
	GError *error = NULL;
	GIOStatus result;

	result = g_io_channel_read_line(channel, &str_return, &length, &terminator_pos, &error);
	if (result == G_IO_STATUS_ERROR || result == G_IO_STATUS_EOF) {
		return FALSE;
	}
	else {
		send_command(str_return);
		g_free(str_return);
		return TRUE;
	}
}

static int done_intro = 0;

void
fe_new_window (struct session *sess, int focus)
{
	char buf[512];

	current_sess = sess;

	if (!sess->server->front_session)
		sess->server->front_session = sess;
	if (!sess->server->server_session)
		sess->server->server_session = sess;
	if (!current_tab || focus)
		current_tab = sess;

	if (done_intro)
		return;
	done_intro = 1;

	g_snprintf (buf, sizeof (buf),
				"\n"
				" \017HexChat-Text \00310"PACKAGE_VERSION"\n"
				" \017Running on \00310%s\n",
				get_sys_str (1));
	fe_print_text (sess, buf, 0, FALSE);

	fe_print_text (sess, "\n\nCompiled in Features\0032:\017 "
#ifdef USE_PLUGIN
	"Plugin "
#endif
#ifdef ENABLE_NLS
	"NLS "
#endif
#ifdef USE_OPENSSL
	"OpenSSL "
#endif
	"\n\n", 0, FALSE);
	fflush (stdout);
}

static int
get_stamp_str (time_t tim, char *dest, int size)
{
	return strftime_validated (dest, size, prefs.hex_stamp_text_format, localtime (&tim));
}

static int
timecat (char *buf, time_t stamp)
{
	char stampbuf[64];

	/* set the stamp to the current time if not provided */
	if (!stamp)
		stamp = time (0);

	get_stamp_str (stamp, stampbuf, sizeof (stampbuf));
	strcat (buf, stampbuf);
	return strlen (stampbuf);
}

/* Windows doesn't handle ANSI codes in cmd.exe, need to not display them */
#ifndef WIN32
/*                               0  1  2  3  4  5  6  7   8   9  10  11  12  13  14 15 */
static const short colconv[] = { 0, 7, 4, 2, 1, 3, 5, 11, 13, 12, 6, 16, 14, 15, 10, 7 };

void
fe_print_text (struct session *sess, char *text, time_t stamp,
			   gboolean no_activity)
{
	int dotime = FALSE;
	char num[8];
	int reverse = 0, under = 0, bold = 0,
		comma, k, i = 0, j = 0, len = strlen (text);
	unsigned char *newtext = g_malloc (len + 1024);

	if (prefs.hex_stamp_text)
	{
		newtext[0] = 0;
		j += timecat (newtext, stamp);
	}
	while (i < len)
	{
		if (dotime && text[i] != 0)
		{
			dotime = FALSE;
			newtext[j] = 0;
			j += timecat (newtext, stamp);
		}
		switch (text[i])
		{
		case 3:
			i++;
			if (!isdigit (text[i]))
			{
				newtext[j] = 27;
				j++;
				newtext[j] = '[';
				j++;
				newtext[j] = 'm';
				j++;
				goto endloop;
			}
			k = 0;
			comma = FALSE;
			while (i < len)
			{
				if (text[i] >= '0' && text[i] <= '9' && k < 2)
				{
					num[k] = text[i];
					k++;
				} else
				{
					int col, mirc;
					num[k] = 0;
					newtext[j] = 27;
					j++;
					newtext[j] = '[';
					j++;
					if (k == 0)
					{
						newtext[j] = 'm';
						j++;
					} else
					{
						if (comma)
							col = 40;
						else
							col = 30;
						mirc = atoi (num);
						mirc = colconv[mirc % G_N_ELEMENTS(colconv)];
						if (mirc > 9)
						{
							mirc += 50;
							sprintf ((char *) &newtext[j], "%dm", mirc + col);
						} else
						{
							sprintf ((char *) &newtext[j], "%dm", mirc + col);
						}
						j = strlen (newtext);
					}
					switch (text[i])
					{
					case ',':
						comma = TRUE;
						break;
					default:
						goto endloop;
					}
					k = 0;
				}
				i++;
			}
			break;
		/* don't actually want hidden text */
		case '\010':				  /* hidden */
			break;
		case '\026':				  /* REVERSE */
			if (reverse)
			{
				reverse = FALSE;
				strcpy (&newtext[j], "\033[27m");
			} else
			{
				reverse = TRUE;
				strcpy (&newtext[j], "\033[7m");
			}
			j = strlen (newtext);
			break;
		case '\037':				  /* underline */
			if (under)
			{
				under = FALSE;
				strcpy (&newtext[j], "\033[24m");
			} else
			{
				under = TRUE;
				strcpy (&newtext[j], "\033[4m");
			}
			j = strlen (newtext);
			break;
		case '\002':				  /* bold */
			if (bold)
			{
				bold = FALSE;
				strcpy (&newtext[j], "\033[22m");
			} else
			{
				bold = TRUE;
				strcpy (&newtext[j], "\033[1m");
			}
			j = strlen (newtext);
			break;
		case '\007':
			if (!prefs.hex_input_filter_beep)
			{
				newtext[j] = text[i];
				j++;
			}
			break;
		case '\017':				  /* reset all */
			strcpy (&newtext[j], "\033[m");
			j += 3;
			reverse = FALSE;
			bold = FALSE;
			under = FALSE;
			break;
		case '\t':
			newtext[j] = ' ';
			j++;
			break;
		case '\n':
			newtext[j] = '\r';
			j++;
			if (prefs.hex_stamp_text)
				dotime = TRUE;
		default:
			newtext[j] = text[i];
			j++;
		}
		i++;
		endloop:
			;
	}

	/* make sure last character is a new line */
	if (text[i-1] != '\n')
		newtext[j++] = '\n';

	newtext[j] = 0;
	write (STDOUT_FILENO, newtext, j);
	g_free (newtext);
}
#else
/* The win32 version for cmd.exe */
void
fe_print_text (struct session *sess, char *text, time_t stamp,
			   gboolean no_activity)
{
	int dotime = FALSE;
	int comma, k, i = 0, j = 0, len = strlen (text);

	unsigned char *newtext = g_malloc (len + 1024);

	if (prefs.hex_stamp_text)
	{
		newtext[0] = 0;
		j += timecat (newtext, stamp);
	}
	while (i < len)
	{
		if (dotime && text[i] != 0)
		{
			dotime = FALSE;
			newtext[j] = 0;
			j += timecat (newtext, stamp);
		}
		switch (text[i])
		{
		case 3:
			i++;
			if (!isdigit (text[i]))
			{
				goto endloop;
			}
			k = 0;
			comma = FALSE;
			while (i < len)
			{
				if (text[i] >= '0' && text[i] <= '9' && k < 2)
				{
					k++;
				} else
				{
					switch (text[i])
					{
					case ',':
						comma = TRUE;
						break;
					default:
						goto endloop;
					}
					k = 0;

				}
				i++;
			}
			break;
		/* don't actually want hidden text */
		case '\010':				  /* hidden */
		case '\026':				  /* REVERSE */
		case '\037':				  /* underline */
		case '\002':				  /* bold */
		case '\017':				  /* reset all */
			break;
		case '\007':
			if (!prefs.hex_input_filter_beep)
			{
				newtext[j] = text[i];
				j++;
			}
			break;
		case '\t':
			newtext[j] = ' ';
			j++;
			break;
		case '\n':
			newtext[j] = '\r';
			j++;
			if (prefs.hex_stamp_text)
				dotime = TRUE;
		default:
			newtext[j] = text[i];
			j++;
		}
		i++;
		endloop:
			;
	}

	/* make sure last character is a new line */
	if (text[i-1] != '\n')
		newtext[j++] = '\n';

	newtext[j] = 0;
	write (STDOUT_FILENO, newtext, j);
	g_free (newtext);
}
#endif

void
fe_timeout_remove (int tag)
{
	g_source_remove (tag);
}

int
fe_timeout_add (int interval, void *callback, void *userdata)
{
	return g_timeout_add (interval, (GSourceFunc) callback, userdata);
}

int
fe_timeout_add_seconds (int interval, void *callback, void *userdata)
{
	return g_timeout_add_seconds (interval, (GSourceFunc) callback, userdata);
}

void
fe_input_remove (int tag)
{
	g_source_remove (tag);
}

int
fe_input_add (int sok, int flags, void *func, void *data)
{
	int tag, type = 0;
	GIOChannel *channel;

#ifdef G_OS_WIN32
	if (flags & FIA_FD)
		channel = g_io_channel_win32_new_fd (sok);
	else
		channel = g_io_channel_win32_new_socket (sok);
#else
	channel = g_io_channel_unix_new (sok);
#endif

	if (flags & FIA_READ)
		type |= G_IO_IN | G_IO_HUP | G_IO_ERR;
	if (flags & FIA_WRITE)
		type |= G_IO_OUT | G_IO_ERR;
	if (flags & FIA_EX)
		type |= G_IO_PRI;

	tag = g_io_add_watch (channel, type, (GIOFunc) func, data);
	g_io_channel_unref (channel);

	return tag;
}

/* === command-line parameter parsing : requires glib 2.6 === */

static char *arg_cfgdir = NULL;
static gint arg_show_autoload = 0;
static gint arg_show_config = 0;
static gint arg_show_version = 0;

static const GOptionEntry gopt_entries[] = 
{
 {"no-auto",	'a', 0, G_OPTION_ARG_NONE,	&arg_dont_autoconnect, N_("Don't auto connect to servers"), NULL},
 {"cfgdir",	'd', 0, G_OPTION_ARG_STRING,	&arg_cfgdir, N_("Use a different config directory"), "PATH"},
 {"no-plugins",	'n', 0, G_OPTION_ARG_NONE,	&arg_skip_plugins, N_("Don't auto load any plugins"), NULL},
 {"plugindir",	'p', 0, G_OPTION_ARG_NONE,	&arg_show_autoload, N_("Show plugin/script auto-load directory"), NULL},
 {"configdir",	'u', 0, G_OPTION_ARG_NONE,	&arg_show_config, N_("Show user config directory"), NULL},
 {"url",	 0,  G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING,	&arg_url, N_("Open an irc://server:port/channel URL"), "URL"},
 {"version",	'v', 0, G_OPTION_ARG_NONE,	&arg_show_version, N_("Show version information"), NULL},
 {G_OPTION_REMAINING, '\0', 0, G_OPTION_ARG_STRING_ARRAY, &arg_urls, N_("Open an irc://server:port/channel?key URL"), "URL"},
 {NULL}
};

int
fe_args (int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

#ifdef ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	context = g_option_context_new (NULL);
	g_option_context_add_main_entries (context, gopt_entries, GETTEXT_PACKAGE);
	g_option_context_parse (context, &argc, &argv, &error);

	if (error)
	{
		if (error->message)
			printf ("%s\n", error->message);
		return 1;
	}

	g_option_context_free (context);

	if (arg_show_version)
	{
		printf (PACKAGE_NAME" "PACKAGE_VERSION"\n");
		return 0;
	}

	if (arg_show_autoload)
	{
#ifdef WIN32
		/* see the chdir() below */
		char *sl, *exe = g_strdup (argv[0]);
		sl = strrchr (exe, '\\');
		if (sl)
		{
			*sl = 0;
			printf ("%s\\plugins\n", exe);
		}
		g_free (exe);
#else
		printf ("%s\n", HEXCHATLIBDIR);
#endif
		return 0;
	}

	if (arg_show_config)
	{
		printf ("%s\n", get_xdir ());
		return 0;
	}

	if (arg_cfgdir)	/* we want filesystem encoding */
	{
		g_free (xdir);
		xdir = strdup (arg_cfgdir);
		if (xdir[strlen (xdir) - 1] == '/')
			xdir[strlen (xdir) - 1] = 0;
		g_free (arg_cfgdir);
	}

	return -1;
}

void
fe_init (void)
{
	/* the following should be default generated, not enfoced in binary */
	prefs.hex_gui_tab_server = 0;
	prefs.hex_gui_autoopen_dialog = 0;
	/* except for these, there is no lag meter, there is no server list */
	prefs.hex_gui_lagometer = 0;
	prefs.hex_gui_slist_skip = 1;
}

void
fe_main (void)
{
	GIOChannel *keyboard_input;

	main_loop = g_main_loop_new(NULL, FALSE);

	/* Keyboard Entry Setup */
#ifdef G_OS_WIN32
	keyboard_input = g_io_channel_win32_new_fd(STDIN_FILENO);
#else
	keyboard_input = g_io_channel_unix_new(STDIN_FILENO);
#endif

	g_io_add_watch(keyboard_input, G_IO_IN, handle_line, NULL);

	g_main_loop_run(main_loop);

	return;
}

void
fe_exit (void)
{
	done = TRUE;
	g_main_loop_quit(main_loop);
}

void
fe_new_server (struct server *serv)
{
}

void
fe_message (char *msg, int flags)
{
	puts (msg);
}

void
fe_close_window (struct session *sess)
{
	session_free (sess);
	done = TRUE;
}

void
fe_beep (session *sess)
{
	putchar (7);
}

void
fe_add_rawlog (struct server *serv, char *text, int len, int outbound)
{
}
void
fe_set_topic (struct session *sess, char *topic, char *stripped_topic)
{
}
void
fe_cleanup (void)
{
}
void
fe_set_tab_color (struct session *sess, int col)
{
}
void
fe_update_mode_buttons (struct session *sess, char mode, char sign)
{
}
void
fe_update_channel_key (struct session *sess)
{
}
void
fe_update_channel_limit (struct session *sess)
{
}
int
fe_is_chanwindow (struct server *serv)
{
	return 0;
}

void
fe_add_chan_list (struct server *serv, char *chan, char *users, char *topic)
{
}
void
fe_chan_list_end (struct server *serv)
{
}
gboolean
fe_add_ban_list (struct session *sess, char *mask, char *who, char *when, int rplcode)
{
	return 0;
}
gboolean
fe_ban_list_end (struct session *sess, int rplcode)
{
	return 0;
}
void
fe_notify_update (char *name)
{
}
void
fe_notify_ask (char *name, char *networks)
{
}
void
fe_text_clear (struct session *sess, int lines)
{
}
void
fe_progressbar_start (struct session *sess)
{
}
void
fe_progressbar_end (struct server *serv)
{
}
void
fe_userlist_insert (struct session *sess, struct User *newuser, gboolean sel)
{
}
int
fe_userlist_remove (struct session *sess, struct User *user)
{
	return 0;
}
void
fe_userlist_rehash (struct session *sess, struct User *user)
{
}
void
fe_userlist_numbers (struct session *sess)
{
}
void
fe_userlist_clear (struct session *sess)
{
}
void
fe_userlist_set_selected (struct session *sess)
{
}
void
fe_dcc_add (struct DCC *dcc)
{
}
void
fe_dcc_update (struct DCC *dcc)
{
}
void
fe_dcc_remove (struct DCC *dcc)
{
}
void
fe_clear_channel (struct session *sess)
{
}
void
fe_session_callback (struct session *sess)
{
}
void
fe_server_callback (struct server *serv)
{
}
void
fe_url_add (const char *text)
{
}
void
fe_pluginlist_update (void)
{
}
void
fe_buttons_update (struct session *sess)
{
}
void
fe_dlgbuttons_update (struct session *sess)
{
}
void
fe_dcc_send_filereq (struct session *sess, char *nick, int maxcps, int passive)
{
}
void
fe_set_channel (struct session *sess)
{
}
void
fe_set_title (struct session *sess)
{
}
void
fe_set_nonchannel (struct session *sess, int state)
{
}
void
fe_set_nick (struct server *serv, char *newnick)
{
}
void
fe_change_nick (struct server *serv, char *nick, char *newnick)
{
}
void
fe_ignore_update (int level)
{
}
int
fe_dcc_open_recv_win (int passive)
{
	return FALSE;
}
int
fe_dcc_open_send_win (int passive)
{
	return FALSE;
}
int
fe_dcc_open_chat_win (int passive)
{
	return FALSE;
}
void
fe_userlist_hide (session * sess)
{
}
void
fe_lastlog (session *sess, session *lastlog_sess, char *sstr, gtk_xtext_search_flags flags)
{
}
void
fe_set_lag (server * serv, long lag)
{
}
void
fe_set_throttle (server * serv)
{
}
void
fe_set_away (server *serv)
{
}
void
fe_serverlist_open (session *sess)
{
}
void
fe_get_bool (char *title, char *prompt, void *callback, void *userdata)
{
}
void
fe_get_str (char *prompt, char *def, void *callback, void *ud)
{
}
void
fe_get_int (char *prompt, int def, void *callback, void *ud)
{
}
void
fe_idle_add (void *func, void *data)
{
	g_idle_add (func, data);
}
void
fe_ctrl_gui (session *sess, fe_gui_action action, int arg)
{
	/* only one action type handled for now, but could add more */
	switch (action)
	{
	/* gui focus is really the only case hexchat-text needs to wory about */
	case FE_GUI_FOCUS:
		current_sess = sess;
		current_tab = sess;
		sess->server->front_session = sess;
		break;
	default:
		break;
	}
}
int
fe_gui_info (session *sess, int info_type)
{
	return -1;
}
void *
fe_gui_info_ptr (session *sess, int info_type)
{
	return NULL;
}
void fe_confirm (const char *message, void (*yesproc)(void *), void (*noproc)(void *), void *ud)
{
}
char *fe_get_inputbox_contents (struct session *sess)
{
	return NULL;
}
void fe_set_inputbox_contents (struct session *sess, char *text)
{
}
int fe_get_inputbox_cursor (struct session *sess)
{
	return 0;
}
void fe_set_inputbox_cursor (struct session *sess, int delta, int pos)
{
}
void fe_open_url (const char *url)
{
}
void fe_menu_del (menu_entry *me)
{
}
char *fe_menu_add (menu_entry *me)
{
	return NULL;
}
void fe_menu_update (menu_entry *me)
{
}
void fe_uselect (struct session *sess, char *word[], int do_clear, int scroll_to)
{
}
void
fe_server_event (server *serv, int type, int arg)
{
}
void
fe_flash_window (struct session *sess)
{
}
void fe_get_file (const char *title, char *initial,
				 void (*callback) (void *userdata, char *file), void *userdata,
				 int flags)
{
}
void fe_tray_set_flash (const char *filename1, const char *filename2, int timeout){}
void fe_tray_set_file (const char *filename){}
void fe_tray_set_icon (feicon icon){}
void fe_tray_set_tooltip (const char *text){}
void fe_userlist_update (session *sess, struct User *user){}
void
fe_open_chan_list (server *serv, char *filter, int do_refresh)
{
	serv->p_list_channels (serv, filter, 1);
}
const char *
fe_get_default_font (void)
{
	return NULL;
}