about summary refs log tree commit diff stats
path: root/src/UCAux.c
blob: 44495a61860c5cb0aafc8a9a11ec17b272a70915 (plain) (blame)
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
/*
 * $LynxId: UCAux.c,v 1.58 2021/07/01 23:34:24 tom Exp $
 */
#include <HTUtils.h>

#include <HTCJK.h>
#include <UCMap.h>
#include <UCDefs.h>
#include <HTStream.h>
#include <UCAux.h>
#include <LYCharSets.h>
#include <LYCurses.h>
#include <LYStrings.h>

BOOL UCCanUniTranslateFrom(int from)
{
    if (from < 0)
	return NO;
#ifndef USE_JAPANESEUTF8_SUPPORT
    if (LYCharSet_UC[from].enc == UCT_ENC_CJK)
	return NO;
#endif
    if (!strcmp(LYCharSet_UC[from].MIMEname, "x-transparent"))
	return NO;

    /* others YES */
    return YES;
}

BOOL UCCanTranslateUniTo(int to)
{
    if (to < 0)
	return NO;

    return YES;			/* well at least some characters... */
}

BOOL UCCanTranslateFromTo(int from,
			  int to)
{
    if (from == to)
	return YES;
    if (from < 0 || to < 0)
	return NO;
    if (from == LATIN1)
	return UCCanTranslateUniTo(to);
    if (to == LATIN1 || LYCharSet_UC[to].enc == UCT_ENC_UTF8)
	return UCCanUniTranslateFrom(from);
    {
	const char *fromname = LYCharSet_UC[from].MIMEname;
	const char *toname = LYCharSet_UC[to].MIMEname;

	if (!strcmp(fromname, "x-transparent") ||
	    !strcmp(toname, "x-transparent")) {
	    return YES;		/* ??? */
	} else if (!strcmp(fromname, "us-ascii")) {
	    return YES;
	}
	if (LYCharSet_UC[from].enc == UCT_ENC_CJK) {
	    /*
	     * CJK mode may be off (i.e., !IS_CJK_TTY) because the current
	     * document is not CJK, but the check may be for capability in
	     * relation to another document, for which CJK mode might be turned
	     * on when retrieved.  Thus, when the from charset is CJK, check if
	     * the to charset is CJK, and return NO or YES in relation to that. 
	     * - FM
	     */
	    if (LYCharSet_UC[to].enc != UCT_ENC_CJK)
		return NO;
	    if ((!strcmp(toname, "euc-jp") ||
		 !strcmp(toname, "shift_jis")) &&
		(!strcmp(fromname, "euc-jp") ||
		 !strcmp(fromname, "shift_jis")))
		return YES;
	    /*
	     * The euc-cn and euc-kr charsets were handled by the (from == to)
	     * above, so we need not check those.  - FM
	     */
	    return NO;
	}
    }
    return YES;			/* others YES */
}

/*
 *  Returns YES if no translation necessary (because
 *  charsets are equal, are equivalent, etc.).
 */
BOOL UCNeedNotTranslate(int from,
			int to)
{
    const char *fromname;
    const char *toname;

    if (from == to)
	return YES;
    if (from < 0)
	return NO;		/* ??? */
    if (LYCharSet_UC[from].enc == UCT_ENC_7BIT) {
	return YES;		/* Only 7bit chars. */
    }
    fromname = LYCharSet_UC[from].MIMEname;
    if (!strcmp(fromname, "x-transparent") ||
	!strcmp(fromname, "us-ascii")) {
	return YES;
    }
    if (to < 0)
	return NO;		/* ??? */
    if (to == LATIN1) {
	if (LYCharSet_UC[from].codepoints & (UCT_CP_SUBSETOF_LAT1))
	    return YES;
    }
    toname = LYCharSet_UC[to].MIMEname;
    if (!strcmp(toname, "x-transparent")) {
	return YES;
    }
    if (LYCharSet_UC[to].enc == UCT_ENC_UTF8) {
	return NO;
    }
    if (from == LATIN1) {
	if (LYCharSet_UC[from].codepoints & (UCT_CP_SUPERSETOF_LAT1))
	    return YES;
    }
    if (LYCharSet_UC[from].enc == UCT_ENC_CJK) {
	if (!IS_CJK_TTY)	/* Use that global flag, for now. */
	    return NO;
	if (HTCJK == JAPANESE &&
	    (!strcmp(fromname, "euc-jp") ||
	     !strcmp(fromname, "shift_jis")))
	    return YES;		/* translate internally by lynx, no unicode */
	return NO;		/* If not handled by (from == to) above. */
    }
    return NO;
}

/*
 *  The idea here is that any stage of the stream pipe which is interested
 *  in some charset dependent processing will call this function.
 *  Given input and output charsets, this function will set various flags
 *  in a UCTransParams structure that _suggest_ to the caller what to do.
 *
 *  Should be called once when a stage starts processing text (and the
 *  input and output charsets are known), or whenever one of input or
 *  output charsets has changed (e.g., by SGML.c stage after HTML.c stage
 *  has processed a META tag).
 *  The global flags (LYRawMode, HTPassEightBitRaw etc.) are currently
 *  not taken into account here (except for HTCJK, somewhat), it's still
 *  up to the caller to do something about them. - KW
 */
void UCSetTransParams(UCTransParams * pT, int cs_in,
		      const LYUCcharset *p_in,
		      int cs_out,
		      const LYUCcharset *p_out)
{
    CTRACE((tfp, "UCSetTransParams: from %s(%d) to %s(%d)\n",
	    p_in->MIMEname, UCGetLYhndl_byMIME(p_in->MIMEname),
	    p_out->MIMEname, UCGetLYhndl_byMIME(p_out->MIMEname)));

    /*
     * Initialize this element to FALSE, and set it TRUE below if we're dealing
     * with VISCII.  - FM
     */
    pT->trans_C0_to_uni = FALSE;

    /*
     * The "transparent" display character set is a "super raw mode".  - FM
     */
    pT->transp = (BOOL) (!strcmp(p_in->MIMEname, "x-transparent") ||
			 !strcmp(p_out->MIMEname, "x-transparent"));

    /*
     * UCS-2 is handled as a special case in SGML_write().
     */
    pT->ucs_mode = 0;

    if (pT->transp) {
	/*
	 * Set up the structure for "transparent".  - FM
	 */
	pT->do_cjk = FALSE;
	pT->decode_utf8 = FALSE;
	pT->output_utf8 = FALSE;	/* We may, but won't know about it. - KW */
	pT->do_8bitraw = TRUE;
	pT->use_raw_char_in = TRUE;
	pT->strip_raw_char_in = FALSE;
	pT->pass_160_173_raw = TRUE;
	pT->repl_translated_C0 = (BOOL) (p_out->enc == UCT_ENC_8BIT_C0);
	pT->trans_C0_to_uni = (BOOL) (p_in->enc == UCT_ENC_8BIT_C0 ||
				      p_out->enc == UCT_ENC_8BIT_C0);
    } else {
	/*
	 * Initialize local flags.  - FM
	 */
	BOOL intm_ucs = FALSE;
	BOOL use_ucs = FALSE;

	/*
	 * Set this element if we want to treat the input as CJK.  - FM
	 */
	pT->do_cjk = (BOOL) ((p_in->enc == UCT_ENC_CJK) &&
			     (
				 IS_CJK_TTY
#ifdef EXP_CHINESEUTF8_SUPPORT
				 || !strcmp(p_in->MIMEname, "euc-cn")
				 || !strcmp(p_in->MIMEname, "big5")
				 || !strcmp(p_in->MIMEname, "euc-kr")
#endif
			     )
	    );
	/*
	 * Set these elements based on whether we are dealing with UTF-8.  - FM
	 */
	pT->decode_utf8 = (BOOL) (p_in->enc == UCT_ENC_UTF8);
	pT->output_utf8 = (BOOL) (p_out->enc == UCT_ENC_UTF8);
	if (pT->do_cjk) {
	    /*
	     * Set up the structure for a CJK input with
	     * a CJK output (IS_CJK_TTY).  - FM
	     */
	    pT->trans_to_uni = FALSE;
#ifdef EXP_CHINESEUTF8_SUPPORT
	    if (!strcmp(p_in->MIMEname, "euc-cn") ||
		!strcmp(p_in->MIMEname, "big5") ||
		!strcmp(p_in->MIMEname, "euc-kr")) {
		pT->trans_to_uni = (BOOL) UCCanUniTranslateFrom(cs_in);
	    }
#endif
	    pT->do_8bitraw = FALSE;
	    pT->pass_160_173_raw = TRUE;
	    pT->use_raw_char_in = FALSE;	/* Not used for CJK. - KW */
	    pT->repl_translated_C0 = FALSE;
	    pT->trans_from_uni = FALSE;		/* Not used for CJK. - KW */
	} else {
	    /*
	     * Set up for all other charset combinations.  The intm_ucs flag is
	     * set TRUE if the input charset is iso-8859-1 or UTF-8, or largely
	     * equivalent to them, i.e., if we have UCS without having to do a
	     * table translation.
	     */
	    intm_ucs = (BOOL) (cs_in == LATIN1 || pT->decode_utf8 ||
			       (p_in->codepoints &
				(UCT_CP_SUBSETOF_LAT1 | UCT_CP_SUBSETOF_UCS2)));
	    /*
	     * pT->trans_to_uni is set TRUE if we do not have that as input
	     * already, and we can translate to Unicode.  Note that UTF-8
	     * always is converted to Unicode in functions that use the
	     * transformation structure, so it is treated as already Unicode
	     * here.
	     */
	    pT->trans_to_uni = (BOOL) (!intm_ucs &&
				       UCCanUniTranslateFrom(cs_in));
	    /*
	     * We set this if we are translating to Unicode and what normally
	     * are low value control characters in fact are encoding octets for
	     * the input charset (presently, this applies to VISCII).  - FM
	     */
	    pT->trans_C0_to_uni = (BOOL) (pT->trans_to_uni &&
					  p_in->enc == UCT_ENC_8BIT_C0);
	    /*
	     * We set this, presently, for VISCII.  - FM
	     */
	    pT->repl_translated_C0 = (BOOL) (p_out->enc == UCT_ENC_8BIT_C0);
	    /*
	     * Currently unused for any charset combination.
	     * Should always be FALSE
	     */
	    pT->strip_raw_char_in = FALSE;
	    /*
	     * use_ucs should be set TRUE if we have or will create Unicode
	     * values for input octets or UTF multibytes.  - FM
	     */
	    use_ucs = (BOOL) (intm_ucs || pT->trans_to_uni);
	    /*
	     * This is set TRUE if use_ucs was set FALSE.  It is complementary
	     * to the HTPassEightBitRaw flag, which is set TRUE or FALSE
	     * elsewhere based on the raw mode setting in relation to the
	     * current Display Character Set.  - FM
	     */
	    pT->do_8bitraw = (BOOL) (!use_ucs);
	    /*
	     * This is set TRUE when 160 and 173 should not be treated as nbsp
	     * and shy, respectively.  - FM
	     */
	    pT->pass_160_173_raw = (BOOL) (!use_ucs &&
					   !(p_in->like8859 & UCT_R_8859SPECL));
	    /*
	     * This is set when the input and output charsets match, and they
	     * are not ones which should go through a Unicode translation
	     * process anyway.  - FM
	     */
	    pT->use_raw_char_in = (BOOL) (!pT->output_utf8 &&
					  cs_in == cs_out &&
					  !pT->trans_C0_to_uni);
	    /*
	     * This should be set TRUE when we expect to have done translation
	     * to Unicode or had the equivalent as input, can translate it to
	     * our output charset, and normally want to do so.  The latter
	     * depends on the pT->do_8bitraw and pT->use_raw_char_in values set
	     * above, but also on HTPassEightBitRaw in any functions which use
	     * the transformation structure..  - FM
	     */
	    pT->trans_from_uni = (BOOL) (use_ucs && !pT->do_8bitraw &&
					 !pT->use_raw_char_in &&
					 UCCanTranslateUniTo(cs_out));
	}
    }
    CTRACE((tfp, "UCSetTransParams (done):\n"));
    CTRACE((tfp, "  transp:             %d\n", pT->transp));
    CTRACE((tfp, "  do_cjk:             %d\n", pT->do_cjk));
    CTRACE((tfp, "  decode_utf8:        %d\n", pT->decode_utf8));
    CTRACE((tfp, "  output_utf8:        %d\n", pT->output_utf8));
    CTRACE((tfp, "  do_8bitraw:         %d\n", pT->do_8bitraw));
    CTRACE((tfp, "  use_raw_char_in:    %d\n", pT->use_raw_char_in));
    CTRACE((tfp, "  strip_raw_char_in:  %d\n", pT->strip_raw_char_in));
    CTRACE((tfp, "  pass_160_173_raw:   %d\n", pT->pass_160_173_raw));
    CTRACE((tfp, "  trans_to_uni:       %d\n", pT->trans_to_uni));
    CTRACE((tfp, "  trans_C0_to_uni:    %d\n", pT->trans_C0_to_uni));
    CTRACE((tfp, "  repl_translated_C0: %d\n", pT->repl_translated_C0));
    CTRACE((tfp, "  trans_from_uni:     %d\n", pT->trans_from_uni));
}

/*
 *  This function initializes the transformation
 *  structure by setting all its elements to
 *  FALSE. - KW
 */
void UCTransParams_clear(UCTransParams * pT)
{
    pT->transp = FALSE;
    pT->do_cjk = FALSE;
    pT->decode_utf8 = FALSE;
    pT->output_utf8 = FALSE;
    pT->do_8bitraw = FALSE;
    pT->use_raw_char_in = FALSE;
    pT->strip_raw_char_in = FALSE;
    pT->pass_160_173_raw = FALSE;
    pT->trans_to_uni = FALSE;
    pT->trans_C0_to_uni = FALSE;
    pT->repl_translated_C0 = FALSE;
    pT->trans_from_uni = FALSE;
}

/*
 * If terminal is in UTF-8 mode, it probably cannot understand box drawing
 * chars as the 8-bit (n)curses handles them.  (This may also be true for other
 * display character sets, but isn't currently checked.) In that case set the
 * chars for horizontal and vertical drawing chars to displayable ASCII chars
 * if '0' was requested.  They'll stay as they are otherwise.  -KW, TD
 *
 * If we're able to obtain a character set based on the locale settings,
 * assume that the user has setup $TERM and the fonts already so line-drawing
 * works.
 */
void UCSetBoxChars(int cset,
		   int *pvert_out,
		   int *phori_out,
		   int vert_in,
		   int hori_in)
{
    BOOL fix_lines = FALSE;

    if (cset >= 0) {
#ifndef WIDEC_CURSES
	if (LYCharSet_UC[cset].enc == UCT_ENC_UTF8) {
	    fix_lines = TRUE;
	}
#endif
	/*
	 * If we've identified a charset that works, require it.
	 * This is important if we have loaded a font, which would
	 * confuse curses.
	 */
	/* US-ASCII vs Latin-1 is safe (usually) */
	if ((cset == US_ASCII
	     || cset == LATIN1)
	    && (linedrawing_char_set == US_ASCII
		|| linedrawing_char_set == LATIN1)) {
#if (defined(FANCY_CURSES) && defined(A_ALTCHARSET)) || defined(USE_SLANG)
	    vert_in = 0;
	    hori_in = 0;
#else
	    ;
#endif
	}
#ifdef EXP_CHARTRANS_AUTOSWITCH
#if defined(NCURSES_VERSION) || defined(HAVE_TIGETSTR)
	else {
	    static BOOL first = TRUE;
	    static int last_cset = -99;
	    static BOOL last_result = TRUE;
	    /* *INDENT-OFF* */
	    static struct {
		int mapping;
		UCode_t internal;
		int external;
	    } table[] = {
		{ 'j', 0x2518, 0 }, /* BOX DRAWINGS LIGHT UP AND LEFT */
		{ 'k', 0x2510, 0 }, /* BOX DRAWINGS LIGHT DOWN AND LEFT */
		{ 'l', 0x250c, 0 }, /* BOX DRAWINGS LIGHT DOWN AND RIGHT */
		{ 'm', 0x2514, 0 }, /* BOX DRAWINGS LIGHT UP AND RIGHT */
		{ 'n', 0x253c, 0 }, /* BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */
		{ 'q', 0x2500, 0 }, /* BOX DRAWINGS LIGHT HORIZONTAL */
		{ 't', 0x251c, 0 }, /* BOX DRAWINGS LIGHT VERTICAL AND RIGHT */
		{ 'u', 0x2524, 0 }, /* BOX DRAWINGS LIGHT VERTICAL AND LEFT */
		{ 'v', 0x2534, 0 }, /* BOX DRAWINGS LIGHT UP AND HORIZONTAL */
		{ 'w', 0x252c, 0 }, /* BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */
		{ 'x', 0x2502, 0 }, /* BOX DRAWINGS LIGHT VERTICAL */
	    };
	    /* *INDENT-ON* */

	    unsigned n;

	    if (first) {
		static char acsc_name[] = "acsc";
		char *map = tigetstr(acsc_name);

		if (map != 0) {
		    CTRACE((tfp, "build terminal line-drawing map\n"));
		    while (map[0] != 0 && map[1] != 0) {
			for (n = 0; n < TABLESIZE(table); ++n) {
			    if (table[n].mapping == map[0]) {
				table[n].external = UCH(map[1]);
				CTRACE((tfp,
					"  map[%c] %#" PRI_UCode_t " -> %#x\n",
					table[n].mapping,
					CAST_UCode_t (table[n].internal),
					(unsigned)table[n].external));
				break;
			    }
			}
			map += 2;
		    }
		}
		first = FALSE;
	    }

	    if (cset == last_cset) {
		fix_lines = last_result;
	    } else if (cset == UTF8_handle) {
		last_result = FALSE;
		last_cset = cset;
	    } else {
		CTRACE((tfp, "check terminal line-drawing map\n"));
		for (n = 0; n < TABLESIZE(table); ++n) {
		    int test = UCTransUniChar(table[n].internal, cset);

		    if (test != table[n].external) {
			CTRACE((tfp,
				"line-drawing map %c mismatch (have %#x, want %#x)\n",
				table[n].mapping,
				(unsigned) test,
				(unsigned) table[n].external));
			fix_lines = TRUE;
			break;
		    }
		}
		last_result = fix_lines;
		last_cset = cset;
	    }
	}
#else
	else if (cset != linedrawing_char_set && linedrawing_char_set >= 0) {
	    fix_lines = TRUE;
	}
#endif
#endif
    }
    if (fix_lines) {
	if (!vert_in)
	    vert_in = '|';
	if (!hori_in)
	    hori_in = '-';
    }
    *pvert_out = vert_in;
    *phori_out = hori_in;
}

/*
 *  Given an output target HTStream* (can also be a HTStructured* via
 *  typecast), the target stream's put_character method, and a Unicode
 *  character,  CPutUtf8_charstring() will either output the UTF8
 *  encoding of the Unicode and return YES, or do nothing and return
 *  NO (if conversion would be unnecessary or the Unicode character is
 *  considered invalid).
 *
 *  [Could be used more generally, but is currently only used for &#nnnnn
 *  stuff - generation of UTF8 from 8-bit encoded charsets not yet done
 *  by SGML.c etc.]
 */
#define PUTC(ch) ((*myPutc)(target, (char)(ch)))
#define PUTC2(ch) ((*myPutc)(target,(char)(0x80|(0x3f &(ch)))))

BOOL UCPutUtf8_charstring(HTStream *target, putc_func_t *myPutc, UCode_t code)
{
    if (code < 128)
	return NO;		/* indicate to caller we didn't handle it */
    else if (code < 0x800L) {
	PUTC(0xc0 | (code >> 6));
	PUTC2(code);
    } else if (code < 0x10000L) {
	PUTC(0xe0 | (code >> 12));
	PUTC2(code >> 6);
	PUTC2(code);
    } else if (code < 0x200000L) {
	PUTC(0xf0 | (code >> 18));
	PUTC2(code >> 12);
	PUTC2(code >> 6);
	PUTC2(code);
    } else if (code < 0x4000000L) {
	PUTC(0xf8 | (code >> 24));
	PUTC2(code >> 18);
	PUTC2(code >> 12);
	PUTC2(code >> 6);
	PUTC2(code);
    } else if (code <= 0x7fffffffL) {
	PUTC(0xfc | (code >> 30));
	PUTC2(code >> 24);
	PUTC2(code >> 18);
	PUTC2(code >> 12);
	PUTC2(code >> 6);
	PUTC2(code);
    } else
	return NO;
    return YES;
}

/*
 *  This function converts a Unicode (UCode_t) value
 *  to a multibyte UTF-8 character, which is loaded
 *  into the buffer received as an argument.  The
 *  buffer should be large enough to hold at least
 *  seven characters (but should be declared as 8
 *  to minimize byte alignment problems with some
 *  compilers). - FM
 */
BOOL UCConvertUniToUtf8(UCode_t code, char *buffer)
{
    char *ch = buffer;

    if (!ch)
	return NO;

    if (code <= 0 || code > 0x7fffffffL) {
	*ch = '\0';
	return NO;
    }

    if (code < 0x800L) {
	*ch++ = (char) (0xc0 | (code >> 6));
	*ch++ = (char) (0x80 | (0x3f & (code)));
	*ch = '\0';
    } else if (code < 0x10000L) {
	*ch++ = (char) (0xe0 | (code >> 12));
	*ch++ = (char) (0x80 | (0x3f & (code >> 6)));
	*ch++ = (char) (0x80 | (0x3f & (code)));
	*ch = '\0';
    } else if (code < 0x200000L) {
	*ch++ = (char) (0xf0 | (code >> 18));
	*ch++ = (char) (0x80 | (0x3f & (code >> 12)));
	*ch++ = (char) (0x80 | (0x3f & (code >> 6)));
	*ch++ = (char) (0x80 | (0x3f & (code)));
	*ch = '\0';
    } else if (code < 0x4000000L) {
	*ch++ = (char) (0xf8 | (code >> 24));
	*ch++ = (char) (0x80 | (0x3f & (code >> 18)));
	*ch++ = (char) (0x80 | (0x3f & (code >> 12)));
	*ch++ = (char) (0x80 | (0x3f & (code >> 6)));
	*ch++ = (char) (0x80 | (0x3f & (code)));
	*ch = '\0';
    } else {
	*ch++ = (char) (0xfc | (code >> 30));
	*ch++ = (char) (0x80 | (0x3f & (code >> 24)));
	*ch++ = (char) (0x80 | (0x3f & (code >> 18)));
	*ch++ = (char) (0x80 | (0x3f & (code >> 12)));
	*ch++ = (char) (0x80 | (0x3f & (code >> 6)));
	*ch++ = (char) (0x80 | (0x3f & (code)));
	*ch = '\0';
    }
    return YES;
}

/*
 * Get UCS character code for one character from UTF-8 encoded string.
 *
 * On entry:
 *	*ppuni should point to beginning of UTF-8 encoding character
 * On exit:
 *	*ppuni is advanced to point to the last byte of UTF-8 sequence,
 *		if there was a valid one; otherwise unchanged.
 * returns the UCS value
 * returns negative value on error (invalid UTF-8 sequence)
 */
UCode_t UCGetUniFromUtf8String(const char **ppuni)
{
    UCode_t uc_out = 0;
    const char *p = *ppuni;
    int utf_count, i;

    if (!(**ppuni & 0x80))
	return (UCode_t) **ppuni;	/* ASCII range character */
    else if (!(**ppuni & 0x40))
	return (-1);		/* not a valid UTF-8 start */
    if ((*p & 0xe0) == 0xc0) {
	utf_count = 1;
    } else if ((*p & 0xf0) == 0xe0) {
	utf_count = 2;
    } else if ((*p & 0xf8) == 0xf0) {
	utf_count = 3;
    } else if ((*p & 0xfc) == 0xf8) {
	utf_count = 4;
    } else if ((*p & 0xfe) == 0xfc) {
	utf_count = 5;
    } else {			/* garbage */
	return (-1);
    }
    for (p = *ppuni, i = 0; i < utf_count; i++) {
	if ((*(++p) & 0xc0) != 0x80)
	    return (-1);
    }
    p = *ppuni;
    switch (utf_count) {
    case 1:
	uc_out = (((*p & 0x1f) << 6) |
		  (*(p + 1) & 0x3f));
	break;
    case 2:
	uc_out = (((((*p & 0x0f) << 6) |
		    (*(p + 1) & 0x3f)) << 6) |
		  (*(p + 2) & 0x3f));
	break;
    case 3:
	uc_out = (((((((*p & 0x07) << 6) |
		      (*(p + 1) & 0x3f)) << 6) |
		    (*(p + 2) & 0x3f)) << 6) |
		  (*(p + 3) & 0x3f));
	break;
    case 4:
	uc_out = (((((((((*p & 0x03) << 6) |
			(*(p + 1) & 0x3f)) << 6) |
		      (*(p + 2) & 0x3f)) << 6) |
		    (*(p + 3) & 0x3f)) << 6) |
		  (*(p + 4) & 0x3f));
	break;
    case 5:
	uc_out = (((((((((((*p & 0x01) << 6) |
			  (*(p + 1) & 0x3f)) << 6) |
			(*(p + 2) & 0x3f)) << 6) |
		      (*(p + 3) & 0x3f)) << 6) |
		    (*(p + 4) & 0x3f)) << 6) |
		  (*(p + 5) & 0x3f));
	break;
    }
    *ppuni = p + utf_count;
    return uc_out;
}

/*
 * Combine UTF-8 into Unicode.  Incomplete characters are either ignored, or
 * returned as the UCS replacement character.
 */
dUTF8 HTDecodeUTF8(UTFDecodeState * me, int *c_in_out, UCode_t *result)
{
    dUTF8 rc = dUTF8_ok;
    int c = *c_in_out;
    unsigned uc = UCH(c);

    if (TOASCII(uc) > 127) {
	/*
	 * continue a multibyte character...
	 */
	if (me->utf_count > 0 && (TOASCII(c) & 0xc0) == 0x80) {
	    if (me->utf_count <= 0) {
		me->utf_char = UCS_REPL;
	    } else if (me->utf_count == 1) {
		int limit = (int) (me->utf_buf_p - me->utf_buf) + 1;
		int maybe = 0;

		/*
		 * Check for overlong sequences (from comment in xterm):
		 *   1100000x 10xxxxxx
		 *   11100000 100xxxxx 10xxxxxx
		 *   11110000 1000xxxx 10xxxxxx 10xxxxxx
		 *   11111000 10000xxx 10xxxxxx 10xxxxxx 10xxxxxx
		 *   11111100 100000xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
		 */
		switch (limit) {
		case 2:
		    maybe = (UCH(me->utf_buf[0]) & 0xfe) == 0xc0;
		    break;
		case 3:
		    maybe = ((UCH(me->utf_buf[0]) == 0xe0) &&
			     (UCH(me->utf_buf[1]) & 0xf0) == 0x80);
		    break;
		case 4:
		    maybe = ((UCH(me->utf_buf[0]) == 0xf0) &&
			     (UCH(me->utf_buf[1]) & 0xf8) == 0x80);
		    break;
		case 5:
		    maybe = ((UCH(me->utf_buf[0]) == 0xf8) &&
			     (UCH(me->utf_buf[1]) & 0xfd) == 0x80);
		    break;
		}
		if (maybe) {
		    while (limit-- > 2) {
			if ((UCH(me->utf_buf[limit]) & 0xc0) != 0x80) {
			    maybe = 0;
			    break;
			}
		    }
		    if (maybe) {
			me->utf_char = UCS_REPL;
		    }
		}
	    }
	    if (me->utf_char == UCS_REPL) {
		rc = dUTF8_err;
	    } else if (me->utf_char || ((uc & 0x7f) >> (7 - me->utf_count))) {
		me->utf_char = (me->utf_char << 6) | (TOASCII(c) & 0x3f);
		if ((me->utf_char >= 0xd800 &&
		     me->utf_char <= 0xdfff) ||
		    (me->utf_char == 0xfffe) ||
		    (me->utf_char == UCS_HIDE)) {
		    me->utf_char = UCS_REPL;
		    rc = dUTF8_err;
		}
	    } else {
		me->utf_char = UCS_REPL;
		rc = dUTF8_err;
	    }
	    me->utf_count--;
	    *(me->utf_buf_p) = (char) c;
	    (me->utf_buf_p)++;

	    if (me->utf_count == 0) {
		*(me->utf_buf_p) = '\0';
		*result = me->utf_char;
		if (*result < 256) {
		    *c_in_out = UCH(*result & 0xff);
		}
		switch (*result) {
		case 0x200e:	/* left-to-right mark */
		case 0x200f:	/* right-to-left mark */
		    /* lynx does not use these */
		    *result = '\0';
		    break;
		}
	    } else {
		rc = dUTF8_more;
	    }
	} else {
	    /*
	     * begin a multibyte character
	     */
	    rc = dUTF8_more;
	    me->utf_buf_p = me->utf_buf;
	    *(me->utf_buf_p) = (char) c;
	    (me->utf_buf_p)++;
	    if ((uc & 0xe0) == 0xc0) {
		me->utf_count = 1;
		me->utf_char = (uc & 0x1f);
	    } else if ((uc & 0xf0) == 0xe0) {
		me->utf_count = 2;
		me->utf_char = (uc & 0x0f);
	    } else if ((uc & 0xf8) == 0xf0) {
		me->utf_count = 3;
		me->utf_char = (uc & 0x07);
	    } else if ((uc & 0xfc) == 0xf8) {
		me->utf_count = 4;
		me->utf_char = (uc & 0x03);
	    } else if ((uc & 0xfe) == 0xfc) {
		me->utf_count = 5;
		me->utf_char = (uc & 0x01);
	    } else {
		me->utf_count = 0;
		me->utf_buf_p = me->utf_buf;
		*(me->utf_buf_p) = '\0';
		rc = dUTF8_err;
	    }
	}
    } else {
	me->utf_count = 0;
	me->utf_buf_p = me->utf_buf;
	*(me->utf_buf_p) = '\0';
    }

#if 0
    if (rc != dUTF8_ok) {
	CTRACE((tfp, "UTF8 %#x ->%#x %s\n",
		uc, UCH(*c_in_out),
		(rc == dUTF8_err) ? "err" : "more"));
    } else {
	if (*result > 127) {
	    CTRACE((tfp, "UTF8 %#x == %#x\n", uc, (int) *result));
	} else if (c != UCS_REPL && !isspace(c)) {
	    CTRACE((tfp, "CHAR %#x == %c (%#x)\n", uc, uc, (int) *result));
	}
    }
#endif
    return rc;
}
picheta@googlemail.com> 2012-01-22 16:21:05 +0000 committer dom96 <dominikpicheta@googlemail.com> 2012-01-22 16:21:05 +0000 Added asyncio module; irc, scgi and the ftpclient modules work with it. Added (de)allocCStringArray. Many async sockets fixes.' href='/ahoang/Nim/commit/lib/pure/sockets.nim?h=devel&id=b298b07567e683de0b82b20f67fd661773edde30'>b298b0756 ^
a58a2f382 ^
3294cb10a ^
a58a2f382 ^
3294cb10a ^
a58a2f382 ^
ce412b4b6 ^



a58a2f382 ^
485c37194 ^
a58a2f382 ^
ec9b1f78e ^

e14bad3c6 ^

da609fc44 ^

ce412b4b6 ^


e14bad3c6 ^





7364d7254 ^
3294cb10a ^
e14bad3c6 ^


7364d7254 ^
3294cb10a ^
e14bad3c6 ^
3294cb10a ^
e14bad3c6 ^
ce412b4b6 ^



e14bad3c6 ^
e14bad3c6 ^

ec9b1f78e ^

9aeecaa4c ^



5310a3044 ^
9aeecaa4c ^



3294cb10a ^
9aeecaa4c ^




3294cb10a ^
9aeecaa4c ^
3294cb10a ^
9aeecaa4c ^





3cbac1354 ^
76c4b0516 ^
6b4101f82 ^


3cbac1354 ^

3294cb10a ^
0f37d0e1f ^

a58a2f382 ^
0f37d0e1f ^
6b4101f82 ^
0f37d0e1f ^
a58a2f382 ^
0f37d0e1f ^














6b4101f82 ^
5a9637f2f ^
ec9b1f78e ^
3cbac1354 ^
e14bad3c6 ^


3cbac1354 ^

3294cb10a ^



e14bad3c6 ^

5a9637f2f ^
e14bad3c6 ^
ec9b1f78e ^
da609fc44 ^
6b4101f82 ^




da609fc44 ^

485c37194 ^
0f37d0e1f ^



6b4101f82 ^
0f37d0e1f ^
3294cb10a ^


a6ee0eb29 ^
3294cb10a ^













6b4101f82 ^









0f37d0e1f ^

6b4101f82 ^
0f37d0e1f ^


6b4101f82 ^
e9604b443 ^

ec9b1f78e ^

e9604b443 ^








de04b50f6 ^
e9604b443 ^

8dd1a5a18 ^
e9604b443 ^
d00cb877f ^
e9604b443 ^
d00cb877f ^
e9604b443 ^
6ab873cc6 ^
e9604b443 ^

ec9b1f78e ^

76c4b0516 ^

e9604b443 ^

de04b50f6 ^
e9604b443 ^











3cbac1354 ^
a58a2f382 ^
3cbac1354 ^

485c37194 ^
a58a2f382 ^



3cbac1354 ^









ec9b1f78e ^

fb2ae12c4 ^
3294cb10a ^



1602e8e2f ^
496621214 ^
6b4101f82 ^
476f6fc8e ^
67d9933eb ^
3294cb10a ^
a58a2f382 ^
ec9b1f78e ^
fb2ae12c4 ^
3294cb10a ^





a58a2f382 ^
d6632ad97 ^








3294cb10a ^

d6632ad97 ^
63112696b ^
3294cb10a ^





63112696b ^
3294cb10a ^






d6632ad97 ^
6b4101f82 ^



d6632ad97 ^
6b4101f82 ^


d6632ad97 ^
6b4101f82 ^
d6632ad97 ^
6b4101f82 ^
ec9b1f78e ^
9aeecaa4c ^



e9604b443 ^
ec9b1f78e ^

e9604b443 ^















8dd1a5a18 ^
e9604b443 ^







ec9b1f78e ^

e9604b443 ^


fb2ae12c4 ^
f83881dd4 ^
adf13aaea ^








1dfc57c5f ^
adf13aaea ^

f83881dd4 ^
adf13aaea ^

3294cb10a ^
adf13aaea ^



3294cb10a ^
adf13aaea ^

e14bad3c6 ^
ec9b1f78e ^
e14bad3c6 ^



e9604b443 ^

e14bad3c6 ^




4218cde54 ^
e14bad3c6 ^
5310a3044 ^
e9604b443 ^
5310a3044 ^
d127ad507 ^


adf13aaea ^
fb2ae12c4 ^

a58a2f382 ^
a58a2f382 ^
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


                                     
                                         




                                                   
                                                                    

                                      


                                                                            
 

                    


                             
                     
                           
 


                  




                      

                                                          









                                                 



                                                          
 


                                                               
    



                                                                       
                                        






                                            

                                                       

                            



                            




                                                                               







                                                                               
                                                           




















                                                                               
 


                                                             

                              





                                                   
 

                                                 
 
                                        
                      
 


























































                                                                             









                                      
                                                                 
                                                                           
                                                                        
                        
                                                                                       
       











                                                                                           
                                
                
                                                    





                                                                                              
                                                                   




                                                                                        
                      
                                                            
                  
                  

                                                             
                     
                                                  


                                                            
                                             

                                                            

                                                                      





                                                                               



                                                                           




                                                                                                  




                                                                       



                                            


















                                                       

                                                                        
      

                                                                           

                       


                                                         
                                 





                                                  









































                                                                                       
                                                                        


                                                     
                                                        
 




























                                                                  
                                            
        
                                                     





                                         

                                                                 


                                                             
 
                   





                                              
                                                    
                                                             
                                                 
               
       




                                          
                                        
                                                                                 
               











                                                                
                                                 
               

                                            
                                                 
                        



                                         

                                           
                                     
                                                            

                                          
                                              
 

                                                                       
                       
                               
                                            
                                                                      
                                  
  




                                 





                                   


                                                 





                                   
                     










                                              

                                                                              










                                                                                

                                                                            

                                                                             
                                                                          
                          


                                                        

                                            






                                                                                           

                                                             
                                                                                    





                                                                   
 


                                                          

                                                           

                                                               
                                                                            
                                                                   













































                                                                                             
                                                                        

                                                                          
     

                                                                           



                                       

                                                                             

                                                  
                                                                       





                                     
                                                                        
                                                                       


                                     
 


                              
                                          
       




                                           
 
                                                                        










                                                 
                                                                                

                                   
                                                              
       
                                                            





                                                 
                                                               




                                                             
                                                                     


                                                        
                                                                       

















                                                    
                                                                  



















                                                    

                                                                 

                                    
                                 
                                                       



                                               

                                                                    

                                    
                                                                     
                                                


                                                              
                                                          



                                                                              

                                                                                




                                        
                                   
  



                          
                                                                       


                    
 


                           

















                                                                                          











                                                
                                                                                
               
 
                                                                  
                                                                 
                                                       

                                                                                  
                                                                                     



                                                                          




                                        
                                   



                          
                                                                    








                                                     

                        

                                                  

                        




                           

                    


                                  
                                                                        









                                                                              





                                                                                       


                                                         





                                                               




                                              
                                                                                






                                                      
 


                                                       

                                                              








                                                                

                         




                                                           
                                      





                   





                                                   





                                                                                   

                          



                
                                                             
                                                       
                                                                         

                                                                             

                                                                          

                                                                              


                                          
 
                                                                






                                 



                                                                           





                                                  
                                                      
                                                       


                                          
                                                                





                                



                                                                      



                                
                                              







                                                                            
                                                                











                                                                 
                                                             
                                            


                                          
                                                                




                               



                                                                 

                               






                                                                                      
                                                                                    
       
                                                                                  



                      


                        
                                         
                                           
              

                      


                
                                                                                
                                
                      



                          



                                         
    





                                                                        



                      









                                                                      
           
                                                        
         
                                                      
 

                                                               




















                                                                            

                                            




                                    
 

                                                                      
                                                                         
                                                                           



                                                                                  






                                                               
 

                                                                           




                                                          



                                                
                  

                     

               
 
                                                                             



                                                                        

                                                     



                        
 
                                                                      










                                                              





                                                                         

                                                  

                                                                 
                                                                                 
                                                                            

                       
                                                                     

                                                                          






                                                                               
                        

               
                                    

                            
                 
                             
                             
                                        
                               



                    
                 
                       
 

                                                                               

                                                                          

                                                            


                                 





                                                     
                                            
                                    


                            
                                              
                             
                             
                                        
                               



                    
                 

                       

                                                                 



                                                                       
                                                                           



                                                          
                                    




                                                                       
                             
                             
                                        





                                                                 
                                                                            
                                                     


                                                                         

                                                                           
                      

                                                
             
                                                                      
                                 
                                          
                                    














                                                           
 
                                 
                                                                  
                                 


                                                                           

                                                                           



                                                               

                    
       
 
                                                               
                                 




                                                                                 

                                                                           
                      



                            
             
                                                                 


                          
                                                                 













                                                                                         









                                                   

                                     
                                    


                                            
               

                                                              

                                                                           








                                                                              
                     

                                            
                                                                      
                                                                          
 
                  
                       
                                              
                                            

                                                                   

                                                              

                                                                             

                                                                    
                                                                    











                                                 
                                                             
                                                      

                                                                           
                      



                                                  









                                                          

                                                             
                            



                                                                  
                                           
                                                    
       
                           
                            
                                                             
 
                                                                
                            





                                                       
 








                                                                                

                    
                     
                                                              





                                                                                         
                    






                                                                 
                  



                                 
                


                                                 
                
                     
  
 
                                                                         



                                                                              
                                                                          

                                                                     















                                                                                  
                                                                       







                                           

                                                            


                                                                
                      
       








                                                                         
                                              

                                                                            
                                                                

                     
                                        



                                                                        
                                          

                 
                                                                           
                                                         



                                                                             

                                                                




                                     
                                                                
 
                                                        
                                                   
 


                                                     
                      

                                                
 
 
#
#
#            Nimrod's Runtime Library
#        (c) Copyright 2013 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

## This module implements a simple portable type-safe sockets layer.
##
## Most procedures raise EOS on error.
##
## For OpenSSL support compile with ``-d:ssl``. When using SSL be aware that
## most functions will then raise ``ESSL`` on SSL errors.

{.deadCodeElim: on.}

when hostos == "solaris":
  {.passl: "-lsocket -lnsl".}

import os, parseutils
from times import epochTime

when defined(ssl):
  import openssl

when defined(Windows):
  import winlean
else:
  import posix

# Note: The enumerations are mapped to Window's constants.

when defined(ssl):
  type
    ESSL* = object of ESynch

    TSSLCVerifyMode* = enum
      CVerifyNone, CVerifyPeer
    
    TSSLProtVersion* = enum
      protSSLv2, protSSLv3, protTLSv1, protSSLv23
    
    PSSLContext* = distinct PSSLCTX

    TSSLAcceptResult* = enum
      AcceptNoClient = 0, AcceptNoHandshake, AcceptSuccess

const
  BufferSize*: int = 4000 ## size of a buffered socket's buffer

type
  TSocketImpl = object ## socket type
    fd: cint
    case isBuffered: bool # determines whether this socket is buffered.
    of true:
      buffer: array[0..BufferSize, char]
      currPos: int # current index in buffer
      bufLen: int # current length of buffer
    of false: nil
    when defined(ssl):
      case isSsl: bool
      of true:
        sslHandle: PSSL
        sslContext: PSSLContext
        sslNoHandshake: bool # True if needs handshake.
        sslHasPeekChar: bool
        sslPeekChar: char
      of false: nil
  
  TSocket* = ref TSocketImpl
  
  TPort* = distinct int16  ## port type
  
  TDomain* = enum   ## domain, which specifies the protocol family of the
                    ## created socket. Other domains than those that are listed
                    ## here are unsupported.
    AF_UNIX,        ## for local socket (using a file). Unsupported on Windows.
    AF_INET = 2,    ## for network protocol IPv4 or
    AF_INET6 = 23   ## for network protocol IPv6.

  TType* = enum        ## second argument to `socket` proc
    SOCK_STREAM = 1,   ## reliable stream-oriented service or Stream Sockets
    SOCK_DGRAM = 2,    ## datagram service or Datagram Sockets
    SOCK_RAW = 3,      ## raw protocols atop the network layer.
    SOCK_SEQPACKET = 5 ## reliable sequenced packet service

  TProtocol* = enum     ## third argument to `socket` proc
    IPPROTO_TCP = 6,    ## Transmission control protocol. 
    IPPROTO_UDP = 17,   ## User datagram protocol.
    IPPROTO_IP,         ## Internet protocol. Unsupported on Windows.
    IPPROTO_IPV6,       ## Internet Protocol Version 6. Unsupported on Windows.
    IPPROTO_RAW,        ## Raw IP Packets Protocol. Unsupported on Windows.
    IPPROTO_ICMP        ## Control message protocol. Unsupported on Windows.

  TServent* {.pure, final.} = object ## information about a service
    name*: string
    aliases*: seq[string]
    port*: TPort
    proto*: string

  Thostent* {.pure, final.} = object ## information about a given host
    name*: string
    aliases*: seq[string]
    addrtype*: TDomain
    length*: int
    addrList*: seq[string]

  TRecvLineResult* = enum ## result for recvLineAsync
    RecvFullLine, RecvPartialLine, RecvDisconnected, RecvFail

  ETimeout* = object of ESynch

proc newTSocket(fd: int32, isBuff: bool): TSocket =
  new(result)
  result.fd = fd
  result.isBuffered = isBuff
  if isBuff:
    result.currPos = 0

let
  InvalidSocket*: TSocket = nil ## invalid socket

proc `==`*(a, b: TPort): bool {.borrow.}
  ## ``==`` for ports.

proc `$`*(p: TPort): string = 
  ## returns the port number as a string
  result = $ze(int16(p))

proc ntohl*(x: int32): int32 = 
  ## Converts 32-bit integers from network to host byte order.
  ## On machines where the host byte order is the same as network byte order,
  ## this is a no-op; otherwise, it performs a 4-byte swap operation.
  when cpuEndian == bigEndian: result = x
  else: result = (x shr 24'i32) or
                 (x shr 8'i32 and 0xff00'i32) or
                 (x shl 8'i32 and 0xff0000'i32) or
                 (x shl 24'i32)

proc ntohs*(x: int16): int16 =
  ## Converts 16-bit integers from network to host byte order. On machines
  ## where the host byte order is the same as network byte order, this is
  ## a no-op; otherwise, it performs a 2-byte swap operation.
  when cpuEndian == bigEndian: result = x
  else: result = (x shr 8'i16) or (x shl 8'i16)

proc htonl*(x: int32): int32 =
  ## Converts 32-bit integers from host to network byte order. On machines
  ## where the host byte order is the same as network byte order, this is
  ## a no-op; otherwise, it performs a 4-byte swap operation.
  result = sockets.ntohl(x)

proc htons*(x: int16): int16 =
  ## Converts 16-bit positive integers from host to network byte order.
  ## On machines where the host byte order is the same as network byte
  ## order, this is a no-op; otherwise, it performs a 2-byte swap operation.
  result = sockets.ntohs(x)
  
when defined(Posix):
  proc ToInt(domain: TDomain): cint =
    case domain
    of AF_UNIX:        result = posix.AF_UNIX
    of AF_INET:        result = posix.AF_INET
    of AF_INET6:       result = posix.AF_INET6
    else: nil

  proc ToInt(typ: TType): cint =
    case typ
    of SOCK_STREAM:    result = posix.SOCK_STREAM
    of SOCK_DGRAM:     result = posix.SOCK_DGRAM
    of SOCK_SEQPACKET: result = posix.SOCK_SEQPACKET
    of SOCK_RAW:       result = posix.SOCK_RAW
    else: nil

  proc ToInt(p: TProtocol): cint =
    case p
    of IPPROTO_TCP:    result = posix.IPPROTO_TCP
    of IPPROTO_UDP:    result = posix.IPPROTO_UDP
    of IPPROTO_IP:     result = posix.IPPROTO_IP
    of IPPROTO_IPV6:   result = posix.IPPROTO_IPV6
    of IPPROTO_RAW:    result = posix.IPPROTO_RAW
    of IPPROTO_ICMP:   result = posix.IPPROTO_ICMP
    else: nil

else:
  proc toInt(domain: TDomain): cint = 
    result = toU16(ord(domain))

  proc ToInt(typ: TType): cint =
    result = cint(ord(typ))
  
  proc ToInt(p: TProtocol): cint =
    result = cint(ord(p))

proc socket*(domain: TDomain = AF_INET, typ: TType = SOCK_STREAM,
             protocol: TProtocol = IPPROTO_TCP, buffered = true): TSocket =
  ## creates a new socket; returns `InvalidSocket` if an error occurs.  
  when defined(Windows):
    result = newTSocket(winlean.socket(ord(domain), ord(typ), ord(protocol)), buffered)
  else:
    result = newTSocket(posix.socket(ToInt(domain), ToInt(typ), ToInt(protocol)), buffered)

when defined(ssl):
  CRYPTO_malloc_init()
  SslLibraryInit()
  SslLoadErrorStrings()
  ErrLoadBioStrings()
  OpenSSL_add_all_algorithms()

  proc SSLError(s = "") =
    if s != "":
      raise newException(ESSL, s)
    let err = ErrPeekLastError()
    if err == 0:
      raise newException(ESSL, "No error reported.")
    if err == -1:
      OSError()
    var errStr = ErrErrorString(err, nil)
    raise newException(ESSL, $errStr)

  # http://simplestcodings.blogspot.co.uk/2010/08/secure-server-client-using-openssl-in-c.html
  proc loadCertificates(ctx: PSSL_CTX, certFile, keyFile: string) =
    if certFile != "" and not existsFile(certFile):
      raise newException(system.EIO, "Certificate file could not be found: " & certFile)
    if keyFile != "" and not existsFile(keyFile):
      raise newException(system.EIO, "Key file could not be found: " & keyFile)
    
    if certFile != "":
      var ret = SSLCTXUseCertificateChainFile(ctx, certFile)
      if ret != 1:
        SSLError()
    
    # TODO: Password? www.rtfm.com/openssl-examples/part1.pdf
    if keyFile != "":
      if SSL_CTX_use_PrivateKey_file(ctx, keyFile,
                                     SSL_FILETYPE_PEM) != 1:
        SSLError()
        
      if SSL_CTX_check_private_key(ctx) != 1:
        SSLError("Verification of private key file failed.")

  proc newContext*(protVersion = ProtSSLv23, verifyMode = CVerifyPeer,
                   certFile = "", keyFile = ""): PSSLContext =
    ## Creates an SSL context.
    ## 
    ## Protocol version specifies the protocol to use. SSLv2, SSLv3, TLSv1 are 
    ## are available with the addition of ``ProtSSLv23`` which allows for 
    ## compatibility with all of them.
    ##
    ## There are currently only two options for verify mode;
    ## one is ``CVerifyNone`` and with it certificates will not be verified
    ## the other is ``CVerifyPeer`` and certificates will be verified for
    ## it, ``CVerifyPeer`` is the safest choice.
    ##
    ## The last two parameters specify the certificate file path and the key file
    ## path, a server socket will most likely not work without these.
    ## Certificates can be generated using the following command:
    ## ``openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem``.
    var newCTX: PSSL_CTX
    case protVersion
    of protSSLv23:
      newCTX = SSL_CTX_new(SSLv23_method()) # SSlv2,3 and TLS1 support.
    of protSSLv2:
      when not defined(linux):
        newCTX = SSL_CTX_new(SSLv2_method())
      else:
        SSLError()
    of protSSLv3:
      newCTX = SSL_CTX_new(SSLv3_method())
    of protTLSv1:
      newCTX = SSL_CTX_new(TLSv1_method())
    
    if newCTX.SSLCTXSetCipherList("ALL") != 1:
      SSLError()
    case verifyMode
    of CVerifyPeer:
      newCTX.SSLCTXSetVerify(SSLVerifyPeer, nil)
    of CVerifyNone:
      newCTX.SSLCTXSetVerify(SSLVerifyNone, nil)
    if newCTX == nil:
      SSLError()
    
    newCTX.loadCertificates(certFile, keyFile)
    return PSSLContext(newCTX)

  proc wrapSocket*(ctx: PSSLContext, socket: TSocket) =
    ## Wraps a socket in an SSL context. This function effectively turns
    ## ``socket`` into an SSL socket.
    ##
    ## **Disclaimer**: This code is not well tested, may be very unsafe and
    ## prone to security vulnerabilities.
    
    socket.isSSL = true
    socket.sslContext = ctx
    socket.sslHandle = SSLNew(PSSLCTX(socket.sslContext))
    socket.sslNoHandshake = false
    socket.sslHasPeekChar = false
    if socket.sslHandle == nil:
      SSLError()
    
    if SSLSetFd(socket.sslHandle, socket.fd) != 1:
      SSLError()

proc SocketError*(socket: TSocket, err: int = -1, async = false) =
  ## Raises proper errors based on return values of ``recv`` functions.
  ##
  ## If ``async`` is ``True`` no error will be thrown in the case when the
  ## error was caused by no data being available to be read.
  ##
  ## If ``err`` is not lower than 0 no exception will be raised.
  when defined(ssl):
    if socket.isSSL:
      if err <= 0:
        var ret = SSLGetError(socket.sslHandle, err.cint)
        case ret
        of SSL_ERROR_ZERO_RETURN:
          SSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
        of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
          if async:
            return
          else: SSLError("Not enough data on socket.")
        of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ:
          if async:
            return
          else: SSLError("Not enough data on socket.")
        of SSL_ERROR_WANT_X509_LOOKUP:
          SSLError("Function for x509 lookup has been called.")
        of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
          SSLError()
        else: SSLError("Unknown Error")
  
  if err == -1 and not (when defined(ssl): socket.isSSL else: false):
    if async:
      when defined(windows):
        # TODO: Test on Windows
        var err = WSAGetLastError()
        if err == WSAEWOULDBLOCK:
          return
        else: OSError()
      else:
        if errno == EAGAIN or errno == EWOULDBLOCK:
          return
        else: OSError()
    else: OSError()

proc listen*(socket: TSocket, backlog = SOMAXCONN) {.tags: [FReadIO].} =
  ## Marks ``socket`` as accepting connections. 
  ## ``Backlog`` specifies the maximum length of the 
  ## queue of pending connections.
  if listen(socket.fd, cint(backlog)) < 0'i32: OSError()

proc invalidIp4(s: string) {.noreturn, noinline.} =
  raise newException(EInvalidValue, "invalid ip4 address: " & s)

proc parseIp4*(s: string): int32 = 
  ## parses an IP version 4 in dotted decimal form like "a.b.c.d".
  ## Raises EInvalidValue in case of an error.
  var a, b, c, d: int
  var i = 0
  var j = parseInt(s, a, i)
  if j <= 0: invalidIp4(s)
  inc(i, j)
  if s[i] == '.': inc(i)
  else: invalidIp4(s)
  j = parseInt(s, b, i)
  if j <= 0: invalidIp4(s)
  inc(i, j)
  if s[i] == '.': inc(i)
  else: invalidIp4(s)
  j = parseInt(s, c, i)
  if j <= 0: invalidIp4(s)
  inc(i, j)
  if s[i] == '.': inc(i)
  else: invalidIp4(s)
  j = parseInt(s, d, i)
  if j <= 0: invalidIp4(s)
  inc(i, j)
  if s[i] != '\0': invalidIp4(s)
  result = int32(a shl 24 or b shl 16 or c shl 8 or d)

template gaiNim(a, p, h, list: expr): stmt =
  block:
    var gaiResult = getAddrInfo(a, $p, addr(h), list)
    if gaiResult != 0'i32:
      when defined(windows):
        OSError()
      else:
        OSError($gai_strerror(gaiResult))

proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
  tags: [FReadIO].} =
  ## binds an address/port number to a socket.
  ## Use address string in dotted decimal form like "a.b.c.d"
  ## or leave "" for any address.

  if address == "":
    var name: Tsockaddr_in
    when defined(Windows):
      name.sin_family = int16(ord(AF_INET))
    else:
      name.sin_family = posix.AF_INET
    name.sin_port = sockets.htons(int16(port))
    name.sin_addr.s_addr = sockets.htonl(INADDR_ANY)
    if bindSocket(socket.fd, cast[ptr TSockAddr](addr(name)),
                  sizeof(name).TSockLen) < 0'i32:
      OSError()
  else:
    var hints: TAddrInfo
    var aiList: ptr TAddrInfo = nil
    hints.ai_family = toInt(AF_INET)
    hints.ai_socktype = toInt(SOCK_STREAM)
    hints.ai_protocol = toInt(IPPROTO_TCP)
    gaiNim(address, port, hints, aiList)
    if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrLen.TSockLen) < 0'i32:
      OSError()

when false:
  proc bindAddr*(socket: TSocket, port = TPort(0)) =
    ## binds a port number to a socket.
    var name: Tsockaddr_in
    when defined(Windows):
      name.sin_family = int16(ord(AF_INET))
    else:
      name.sin_family = posix.AF_INET
    name.sin_port = sockets.htons(int16(port))
    name.sin_addr.s_addr = sockets.htonl(INADDR_ANY)
    if bindSocket(cint(socket), cast[ptr TSockAddr](addr(name)),
                  sizeof(name).TSockLen) < 0'i32:
      OSError()
  
proc getSockName*(socket: TSocket): TPort = 
  ## returns the socket's associated port number.
  var name: Tsockaddr_in
  when defined(Windows):
    name.sin_family = int16(ord(AF_INET))
  else:
    name.sin_family = posix.AF_INET
  #name.sin_port = htons(cint16(port))
  #name.sin_addr.s_addr = htonl(INADDR_ANY)
  var namelen = sizeof(name).TSockLen
  if getsockname(socket.fd, cast[ptr TSockAddr](addr(name)),
                 addr(namelen)) == -1'i32:
    OSError()
  result = TPort(sockets.ntohs(name.sin_port))

template acceptAddrPlain(noClientRet, successRet: expr, 
                         sslImplementation: stmt): stmt {.immediate.} =
  assert(client != nil)
  var sockAddress: Tsockaddr_in
  var addrLen = sizeof(sockAddress).TSockLen
  var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
                    addr(addrLen))
  
  if sock < 0:
    # TODO: Test on Windows.
    when defined(windows):
      var err = WSAGetLastError()
      if err == WSAEINPROGRESS:
        client = InvalidSocket
        address = ""
        when noClientRet.int == -1:
          return
        else:
          return noClientRet
      else: OSError()
    else:
      if errno == EAGAIN or errno == EWOULDBLOCK:
        client = InvalidSocket
        address = ""
        when noClientRet.int == -1:
          return
        else:
          return noClientRet
      else: OSError()
  else:
    client.fd = sock
    client.isBuffered = server.isBuffered
    sslImplementation
    # Client socket is set above.
    address = $inet_ntoa(sockAddress.sin_addr)
    when successRet.int == -1:
      return
    else:
      return successRet

proc acceptAddr*(server: TSocket, client: var TSocket, address: var string) {.
  tags: [FReadIO].} =
  ## Blocks until a connection is being made from a client. When a connection
  ## is made sets ``client`` to the client socket and ``address`` to the address
  ## of the connecting client.
  ## If ``server`` is non-blocking then this function returns immediately, and
  ## if there are no connections queued the returned socket will be
  ## ``InvalidSocket``.
  ## This function will raise EOS if an error occurs.
  ##
  ## The resulting client will inherit any properties of the server socket. For
  ## example: whether the socket is buffered or not.
  ##
  ## **Note**: ``client`` must be initialised (with ``new``), this function 
  ## makes no effort to initialise the ``client`` variable.
  ##
  ## **Warning:** When using SSL with non-blocking sockets, it is best to use
  ## the acceptAddrSSL procedure as this procedure will most likely block.
  acceptAddrPlain(-1, -1):
    when defined(ssl):
      if server.isSSL:
        # We must wrap the client sock in a ssl context.
        
        server.sslContext.wrapSocket(client)
        let ret = SSLAccept(client.sslHandle)
        while ret <= 0:
          let err = SSLGetError(client.sslHandle, ret)
          if err != SSL_ERROR_WANT_ACCEPT:
            case err
            of SSL_ERROR_ZERO_RETURN:
              SSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
            of SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE,
               SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
              SSLError("acceptAddrSSL should be used for non-blocking SSL sockets.")
            of SSL_ERROR_WANT_X509_LOOKUP:
              SSLError("Function for x509 lookup has been called.")
            of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
              SSLError()
            else:
              SSLError("Unknown error")

proc setBlocking*(s: TSocket, blocking: bool) {.tags: [].}
  ## sets blocking mode on socket

when defined(ssl):
  proc acceptAddrSSL*(server: TSocket, client: var TSocket,
                      address: var string): TSSLAcceptResult {.
                      tags: [FReadIO].} =
    ## This procedure should only be used for non-blocking **SSL** sockets. 
    ## It will immediately return with one of the following values:
    ## 
    ## ``AcceptSuccess`` will be returned when a client has been successfully
    ## accepted and the handshake has been successfully performed between
    ## ``server`` and the newly connected client.
    ##
    ## ``AcceptNoHandshake`` will be returned when a client has been accepted
    ## but no handshake could be performed. This can happen when the client
    ## connects but does not yet initiate a handshake. In this case
    ## ``acceptAddrSSL`` should be called again with the same parameters.
    ##
    ## ``AcceptNoClient`` will be returned when no client is currently attempting
    ## to connect.
    template doHandshake(): stmt =
      when defined(ssl):
        if server.isSSL:
          client.setBlocking(false)
          # We must wrap the client sock in a ssl context.
          
          if not client.isSSL or client.sslHandle == nil:
            server.sslContext.wrapSocket(client)
          let ret = SSLAccept(client.sslHandle)
          while ret <= 0:
            let err = SSLGetError(client.sslHandle, ret)
            if err != SSL_ERROR_WANT_ACCEPT:
              case err
              of SSL_ERROR_ZERO_RETURN:
                SSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
              of SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE,
                 SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
                client.sslNoHandshake = true
                return AcceptNoHandshake
              of SSL_ERROR_WANT_X509_LOOKUP:
                SSLError("Function for x509 lookup has been called.")
              of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
                SSLError()
              else:
                SSLError("Unknown error")
          client.sslNoHandshake = false

    if client.isSSL and client.sslNoHandshake:
      doHandshake()
      return AcceptSuccess
    else:
      acceptAddrPlain(AcceptNoClient, AcceptSuccess):
        doHandshake()

proc accept*(server: TSocket, client: var TSocket) {.tags: [FReadIO].} =
  ## Equivalent to ``acceptAddr`` but doesn't return the address, only the
  ## socket.
  ## 
  ## **Note**: ``client`` must be initialised (with ``new``), this function
  ## makes no effort to initialise the ``client`` variable.
  
  var addrDummy = ""
  acceptAddr(server, client, addrDummy)

proc acceptAddr*(server: TSocket): tuple[client: TSocket, address: string] {.
  deprecated, tags: [FReadIO].} =
  ## Slightly different version of ``acceptAddr``.
  ##
  ## **Deprecated since version 0.9.0:** Please use the function above.
  var client: TSocket
  new(client)
  var address = ""
  acceptAddr(server, client, address)
  return (client, address)

proc accept*(server: TSocket): TSocket {.deprecated, tags: [FReadIO].} =
  ## **Deprecated since version 0.9.0:** Please use the function above.
  new(result)
  var address = ""
  acceptAddr(server, result, address)

proc close*(socket: TSocket) =
  ## closes a socket.
  when defined(windows):
    discard winlean.closeSocket(socket.fd)
  else:
    discard posix.close(socket.fd)

  when defined(ssl):
    if socket.isSSL:
      discard SSLShutdown(socket.sslHandle)

proc getServByName*(name, proto: string): TServent {.tags: [FReadIO].} =
  ## well-known getservbyname proc.
  when defined(Windows):
    var s = winlean.getservbyname(name, proto)
  else:
    var s = posix.getservbyname(name, proto)
  if s == nil: OSError()
  result.name = $s.s_name
  result.aliases = cstringArrayToSeq(s.s_aliases)
  result.port = TPort(s.s_port)
  result.proto = $s.s_proto
  
proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} = 
  ## well-known getservbyport proc.
  when defined(Windows):
    var s = winlean.getservbyport(ze(int16(port)).cint, proto)
  else:
    var s = posix.getservbyport(ze(int16(port)).cint, proto)
  if s == nil: OSError()
  result.name = $s.s_name
  result.aliases = cstringArrayToSeq(s.s_aliases)
  result.port = TPort(s.s_port)
  result.proto = $s.s_proto

proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} =
  ## This function will lookup the hostname of an IP Address.
  var myaddr: TInAddr
  myaddr.s_addr = inet_addr(ip)
  
  when defined(windows):
    var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint,
                                  cint(sockets.AF_INET))
    if s == nil: OSError()
  else:
    var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).TSockLen, 
                                cint(posix.AF_INET))
    if s == nil:
      raise newException(EOS, $hStrError(h_errno))
  
  result.name = $s.h_name
  result.aliases = cstringArrayToSeq(s.h_aliases)
  when defined(windows): 
    result.addrType = TDomain(s.h_addrtype)
  else:
    if s.h_addrtype == posix.AF_INET:
      result.addrType = AF_INET
    elif s.h_addrtype == posix.AF_INET6:
      result.addrType = AF_INET6
    else:
      OSError("unknown h_addrtype")
  result.addrList = cstringArrayToSeq(s.h_addr_list)
  result.length = int(s.h_length)

proc getHostByName*(name: string): THostEnt {.tags: [FReadIO].} = 
  ## well-known gethostbyname proc.
  when defined(Windows):
    var s = winlean.gethostbyname(name)
  else:
    var s = posix.gethostbyname(name)
  if s == nil: OSError()
  result.name = $s.h_name
  result.aliases = cstringArrayToSeq(s.h_aliases)
  when defined(windows): 
    result.addrType = TDomain(s.h_addrtype)
  else:
    if s.h_addrtype == posix.AF_INET:
      result.addrType = AF_INET
    elif s.h_addrtype == posix.AF_INET6:
      result.addrType = AF_INET6
    else:
      OSError("unknown h_addrtype")
  result.addrList = cstringArrayToSeq(s.h_addr_list)
  result.length = int(s.h_length)

proc getSockOptInt*(socket: TSocket, level, optname: int): int {.
  tags: [FReadIO].} = 
  ## getsockopt for integer options.
  var res: cint
  var size = sizeof(res).TSockLen
  if getsockopt(socket.fd, cint(level), cint(optname), 
                addr(res), addr(size)) < 0'i32:
    OSError()
  result = int(res)

proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {.
  tags: [FWriteIO].} =
  ## setsockopt for integer options.
  var value = cint(optval)
  if setsockopt(socket.fd, cint(level), cint(optname), addr(value),  
                sizeof(value).TSockLen) < 0'i32:
    OSError()

proc connect*(socket: TSocket, name: string, port = TPort(0), 
              af: TDomain = AF_INET) {.tags: [FReadIO].} =
  ## Connects socket to ``name``:``port``. ``Name`` can be an IP address or a
  ## host name. If ``name`` is a host name, this function will try each IP
  ## of that host name. ``htons`` is already performed on ``port`` so you must
  ## not do it.
  ##
  ## If ``socket`` is an SSL socket a handshake will be automatically performed.
  var hints: TAddrInfo
  var aiList: ptr TAddrInfo = nil
  hints.ai_family = toInt(af)
  hints.ai_socktype = toInt(SOCK_STREAM)
  hints.ai_protocol = toInt(IPPROTO_TCP)
  gaiNim(name, port, hints, aiList)
  
  # try all possibilities:
  var success = false
  var it = aiList
  while it != nil:
    if connect(socket.fd, it.ai_addr, it.ai_addrlen.TSockLen) == 0'i32:
      success = true
      break
    it = it.ai_next

  freeaddrinfo(aiList)
  if not success: OSError()
  
  when defined(ssl):
    if socket.isSSL:
      let ret = SSLConnect(socket.sslHandle)
      if ret <= 0:
        let err = SSLGetError(socket.sslHandle, ret)
        case err
        of SSL_ERROR_ZERO_RETURN:
          SSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
        of SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, 
           SSL_ERROR_WANT_ACCEPT:
          SSLError("The operation did not complete. Perhaps you should use connectAsync?")
        of SSL_ERROR_WANT_X509_LOOKUP:
          SSLError("Function for x509 lookup has been called.")
        of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
          SSLError()
        else:
          SSLError("Unknown error")
        
  when false:
    var s: TSockAddrIn
    s.sin_addr.s_addr = inet_addr(name)
    s.sin_port = sockets.htons(int16(port))
    when defined(windows):
      s.sin_family = toU16(ord(af))
    else:
      case af 
      of AF_UNIX: s.sin_family = posix.AF_UNIX
      of AF_INET: s.sin_family = posix.AF_INET
      of AF_INET6: s.sin_family = posix.AF_INET6
      else: nil
    if connect(socket.fd, cast[ptr TSockAddr](addr(s)), sizeof(s).cint) < 0'i32:
      OSError()

proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
                     af: TDomain = AF_INET) {.tags: [FReadIO].} =
  ## A variant of ``connect`` for non-blocking sockets.
  ##
  ## This procedure will immediatelly return, it will not block until a connection
  ## is made. It is up to the caller to make sure the connection has been established
  ## by checking (using ``select``) whether the socket is writeable.
  ##
  ## **Note**: For SSL sockets, the ``handshake`` procedure must be called
  ## whenever the socket successfully connects to a server.
  var hints: TAddrInfo
  var aiList: ptr TAddrInfo = nil
  hints.ai_family = toInt(af)
  hints.ai_socktype = toInt(SOCK_STREAM)
  hints.ai_protocol = toInt(IPPROTO_TCP)
  gaiNim(name, port, hints, aiList)
  # try all possibilities:
  var success = false
  var it = aiList
  while it != nil:
    var ret = connect(socket.fd, it.ai_addr, it.ai_addrlen.TSockLen)
    if ret == 0'i32:
      success = true
      break
    else:
      # TODO: Test on Windows.
      when defined(windows):
        var err = WSAGetLastError()
        # Windows EINTR doesn't behave same as POSIX.
        if err == WSAEWOULDBLOCK:
          success = true
          break
      else:
        if errno == EINTR or errno == EINPROGRESS:
          success = true
          break
        
    it = it.ai_next

  freeaddrinfo(aiList)
  if not success: OSError()
  when defined(ssl):
    if socket.isSSL:
      socket.sslNoHandshake = true

when defined(ssl):
  proc handshake*(socket: TSocket): bool {.tags: [FReadIO, FWriteIO].} =
    ## This proc needs to be called on a socket after it connects. This is
    ## only applicable when using ``connectAsync``.
    ## This proc performs the SSL handshake.
    ##
    ## Returns ``False`` whenever the socket is not yet ready for a handshake,
    ## ``True`` whenever handshake completed successfully.
    ##
    ## A ESSL error is raised on any other errors.
    result = true
    if socket.isSSL:
      var ret = SSLConnect(socket.sslHandle)
      if ret <= 0:
        var errret = SSLGetError(socket.sslHandle, ret)
        case errret
        of SSL_ERROR_ZERO_RETURN:
          SSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
        of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT,
          SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE:
          return false
        of SSL_ERROR_WANT_X509_LOOKUP:
          SSLError("Function for x509 lookup has been called.")
        of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
          SSLError()
        else:
          SSLError("Unknown Error")
      socket.sslNoHandshake = false
    else:
      SSLError("Socket is not an SSL socket.")

  proc gotHandshake*(socket: TSocket): bool =
    ## Determines whether a handshake has occurred between a client (``socket``)
    ## and the server that ``socket`` is connected to.
    ##
    ## Throws ESSL if ``socket`` is not an SSL socket.
    if socket.isSSL:
      return not socket.sslNoHandshake
    else:
      SSLError("Socket is not an SSL socket.")

proc timeValFromMilliseconds(timeout = 500): TTimeVal =
  if timeout != -1:
    var seconds = timeout div 1000
    result.tv_sec = seconds.int32
    result.tv_usec = ((timeout - seconds * 1000) * 1000).int32
#proc recvfrom*(s: TWinSocket, buf: cstring, len, flags: cint, 
#               fromm: ptr TSockAddr, fromlen: ptr cint): cint 

#proc sendto*(s: TWinSocket, buf: cstring, len, flags: cint,
#             to: ptr TSockAddr, tolen: cint): cint

proc createFdSet(fd: var TFdSet, s: seq[TSocket], m: var int) = 
  FD_ZERO(fd)
  for i in items(s): 
    m = max(m, int(i.fd))
    FD_SET(i.fd, fd)
   
proc pruneSocketSet(s: var seq[TSocket], fd: var TFdSet) = 
  var i = 0
  var L = s.len
  while i < L:
    if FD_ISSET(s[i].fd, fd) != 0'i32:
      s[i] = s[L-1]
      dec(L)
    else:
      inc(i)
  setLen(s, L)

proc hasDataBuffered*(s: TSocket): bool =
  ## Determines whether a socket has data buffered.
  result = false
  if s.isBuffered:
    result = s.bufLen > 0 and s.currPos != s.bufLen

proc checkBuffer(readfds: var seq[TSocket]): int =
  ## Checks the buffer of each socket in ``readfds`` to see whether there is data.
  ## Removes the sockets from ``readfds`` and returns the count of removed sockets.
  var res: seq[TSocket] = @[]
  result = 0
  for s in readfds:
    if hasDataBuffered(s):
      inc(result)
    else:
      res.add(s)
  readfds = res

proc select*(readfds, writefds, exceptfds: var seq[TSocket], 
             timeout = 500): int {.tags: [FReadIO].} = 
  ## Traditional select function. This function will return the number of
  ## sockets that are ready to be read from, written to, or which have errors
  ## if there are none; 0 is returned. 
  ## ``Timeout`` is in miliseconds and -1 can be specified for no timeout.
  ## 
  ## A socket is removed from the specific ``seq`` when it has data waiting to
  ## be read/written to or has errors (``exceptfds``).
  let buffersFilled = checkBuffer(readfds)
  if buffersFilled > 0:
    return buffersFilled

  var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
  
  var rd, wr, ex: TFdSet
  var m = 0
  createFdSet((rd), readfds, m)
  createFdSet((wr), writefds, m)
  createFdSet((ex), exceptfds, m)
  
  if timeout != -1:
    result = int(select(cint(m+1), addr(rd), addr(wr), addr(ex), addr(tv)))
  else:
    result = int(select(cint(m+1), addr(rd), addr(wr), addr(ex), nil))
  
  pruneSocketSet(readfds, (rd))
  pruneSocketSet(writefds, (wr))
  pruneSocketSet(exceptfds, (ex))

proc select*(readfds, writefds: var seq[TSocket], 
             timeout = 500): int {.tags: [FReadIO].} =
  ## variant of select with only a read and write list.
  let buffersFilled = checkBuffer(readfds)
  if buffersFilled > 0:
    return buffersFilled
  var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
  
  var rd, wr: TFdSet
  var m = 0
  createFdSet((rd), readfds, m)
  createFdSet((wr), writefds, m)
  
  if timeout != -1:
    result = int(select(cint(m+1), addr(rd), addr(wr), nil, addr(tv)))
  else:
    result = int(select(cint(m+1), addr(rd), addr(wr), nil, nil))
  
  pruneSocketSet(readfds, (rd))
  pruneSocketSet(writefds, (wr))

proc selectWrite*(writefds: var seq[TSocket], 
                  timeout = 500): int {.tags: [FReadIO].} =
  ## When a socket in ``writefds`` is ready to be written to then a non-zero
  ## value will be returned specifying the count of the sockets which can be
  ## written to. The sockets which can be written to will also be removed
  ## from ``writefds``.
  ##
  ## ``timeout`` is specified in miliseconds and ``-1`` can be specified for
  ## an unlimited time.
  var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
  
  var wr: TFdSet
  var m = 0
  createFdSet((wr), writefds, m)
  
  if timeout != -1:
    result = int(select(cint(m+1), nil, addr(wr), nil, addr(tv)))
  else:
    result = int(select(cint(m+1), nil, addr(wr), nil, nil))
  
  pruneSocketSet(writefds, (wr))

proc select*(readfds: var seq[TSocket], timeout = 500): int =
  ## variant of select with a read list only
  let buffersFilled = checkBuffer(readfds)
  if buffersFilled > 0:
    return buffersFilled
  var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
  
  var rd: TFdSet
  var m = 0
  createFdSet((rd), readfds, m)
  
  if timeout != -1:
    result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv)))
  else:
    result = int(select(cint(m+1), addr(rd), nil, nil, nil))
  
  pruneSocketSet(readfds, (rd))

proc readIntoBuf(socket: TSocket, flags: int32): int =
  result = 0
  when defined(ssl):
    if socket.isSSL:
      result = SSLRead(socket.sslHandle, addr(socket.buffer), int(socket.buffer.high))
    else:
      result = recv(socket.fd, addr(socket.buffer), cint(socket.buffer.high), flags)
  else:
    result = recv(socket.fd, addr(socket.buffer), cint(socket.buffer.high), flags)
  if result <= 0:
    socket.buflen = 0
    socket.currPos = 0
    return result
  socket.bufLen = result
  socket.currPos = 0

template retRead(flags, readBytes: int) =
  let res = socket.readIntoBuf(flags.int32)
  if res <= 0:
    if readBytes > 0:
      return readBytes
    else:
      return res

proc recv*(socket: TSocket, data: pointer, size: int): int {.tags: [FReadIO].} =
  ## receives data from a socket
  if size == 0: return
  if socket.isBuffered:
    if socket.bufLen == 0:
      retRead(0'i32, 0)
    
    var read = 0
    while read < size:
      if socket.currPos >= socket.bufLen:
        retRead(0'i32, read)
    
      let chunk = min(socket.bufLen-socket.currPos, size-read)
      var d = cast[cstring](data)
      copyMem(addr(d[read]), addr(socket.buffer[socket.currPos]), chunk)
      read.inc(chunk)
      socket.currPos.inc(chunk)

    result = read
  else:
    when defined(ssl):
      if socket.isSSL:
        if socket.sslHasPeekChar:
          copyMem(data, addr(socket.sslPeekChar), 1)
          socket.sslHasPeekChar = false
          if size-1 > 0:
            var d = cast[cstring](data)
            result = SSLRead(socket.sslHandle, addr(d[1]), size-1) + 1
          else:
            result = 1
        else:
          result = SSLRead(socket.sslHandle, data, size)
      else:
        result = recv(socket.fd, data, size.cint, 0'i32)
    else:
      result = recv(socket.fd, data, size.cint, 0'i32)

proc recv*(socket: TSocket, data: var string, size: int): int =
  ## higher-level version of the above
  ##
  ## When 0 is returned the socket's connection has been closed.
  ##
  ## This function will throw an EOS exception when an error occurs. A value
  ## lower than 0 is never returned.
  ##
  ## **Note**: ``data`` must be initialised.
  data.setLen(size)
  result = recv(socket, cstring(data), size)
  if result < 0:
    data.setLen(0)
    socket.SocketError(result)
  data.setLen(result)

proc recvAsync*(socket: TSocket, data: var string, size: int): int =
  ## Async version of the above.
  ##
  ## When socket is non-blocking and no data is available on the socket,
  ## ``-1`` will be returned and ``data`` will be ``""``.
  ##
  ## **Note**: ``data`` must be initialised.
  data.setLen(size)
  result = recv(socket, cstring(data), size)
  if result < 0:
    data.setLen(0)
    socket.SocketError(async = true)
    result = -1
  data.setLen(result)

proc waitFor(socket: TSocket, waited: var float, timeout: int): int {.
  tags: [FTime].} =
  ## returns the number of characters available to be read. In unbuffered
  ## sockets this is always 1, otherwise this may as big as ``BufferSize``.
  result = 1
  if socket.isBuffered and socket.bufLen != 0 and socket.bufLen != socket.currPos:
    result = socket.bufLen - socket.currPos
  else:
    if timeout - int(waited * 1000.0) < 1:
      raise newException(ETimeout, "Call to recv() timed out.")
    var s = @[socket]
    var startTime = epochTime()
    if select(s, timeout - int(waited * 1000.0)) != 1:
      raise newException(ETimeout, "Call to recv() timed out.")
    waited += (epochTime() - startTime)

proc recv*(socket: TSocket, data: pointer, size: int, timeout: int): int {.
  tags: [FReadIO, FTime].} =
  ## overload with a ``timeout`` parameter in miliseconds.
  var waited = 0.0 # number of seconds already waited  
  
  var read = 0
  while read < size:
    let avail = waitFor(socket, waited, timeout)
    var d = cast[cstring](data)
    result = recv(socket, addr(d[read]), avail)
    if result == 0: break
    if result < 0:
      return result
    inc(read, result)
  
  result = read

proc recv*(socket: TSocket, data: var string, size: int, timeout: int): int =
  ## higher-level version of the above.
  ##
  ## Similar to the non-timeout version this will throw an EOS exception
  ## when an error occurs.
  data.setLen(size)
  result = recv(socket, cstring(data), size, timeout)
  if result < 0:
    data.setLen(0)
    socket.SocketError()
  data.setLen(result)

proc peekChar(socket: TSocket, c: var char): int {.tags: [FReadIO].} =
  if socket.isBuffered:
    result = 1
    if socket.bufLen == 0 or socket.currPos > socket.bufLen-1:
      var res = socket.readIntoBuf(0'i32)
      if res <= 0:
        result = res
    
    c = socket.buffer[socket.currPos]
  else:
    when defined(ssl):
      if socket.isSSL:
        if not socket.sslHasPeekChar:
          result = SSLRead(socket.sslHandle, addr(socket.sslPeekChar), 1)
          socket.sslHasPeekChar = true
        
        c = socket.sslPeekChar
        return
    result = recv(socket.fd, addr(c), 1, MSG_PEEK)

proc recvLine*(socket: TSocket, line: var TaintedString): bool {.
  tags: [FReadIO].} =
  ## retrieves a line from ``socket``. If a full line is received ``\r\L`` is not
  ## added to ``line``, however if solely ``\r\L`` is received then ``line``
  ## will be set to it.
  ## 
  ## ``True`` is returned if data is available. ``False`` suggests an
  ## error, EOS exceptions are not raised and ``False`` is simply returned
  ## instead.
  ## 
  ## If the socket is disconnected, ``line`` will be set to ``""`` and ``True``
  ## will be returned.
  template addNLIfEmpty(): stmt =
    if line.len == 0:
      line.add("\c\L")

  setLen(line.string, 0)
  while true:
    var c: char
    var n = recv(socket, addr(c), 1)
    if n < 0: return
    elif n == 0: return true
    if c == '\r':
      n = peekChar(socket, c)
      if n > 0 and c == '\L':
        discard recv(socket, addr(c), 1)
      elif n <= 0: return false
      addNlIfEmpty()
      return true
    elif c == '\L': 
      addNlIfEmpty()
      return true
    add(line.string, c)

proc recvLine*(socket: TSocket, line: var TaintedString, timeout: int): bool {.
  tags: [FReadIO, FTime].} =
  ## variant with a ``timeout`` parameter, the timeout parameter specifies
  ## how many miliseconds to wait for data.
  ##
  ## ``ETimeout`` will be raised if ``timeout`` is exceeded.
  template addNLIfEmpty(): stmt =
    if line.len == 0:
      line.add("\c\L")
  
  var waited = 0.0 # number of seconds already waited
  
  setLen(line.string, 0)
  while true:
    var c: char
    discard waitFor(socket, waited, timeout)
    var n = recv(socket, addr(c), 1)
    if n < 0: return
    elif n == 0: return true
    if c == '\r':
      discard waitFor(socket, waited, timeout)
      n = peekChar(socket, c)
      if n > 0 and c == '\L':
        discard recv(socket, addr(c), 1)
      elif n <= 0: return false
      addNlIfEmpty()
      return true
    elif c == '\L': 
      addNlIfEmpty()
      return true
    add(line.string, c)

proc recvLineAsync*(socket: TSocket, 
  line: var TaintedString): TRecvLineResult {.tags: [FReadIO].} =
  ## similar to ``recvLine`` but for non-blocking sockets.
  ## The values of the returned enum should be pretty self explanatory:
  ## If a full line has been retrieved; ``RecvFullLine`` is returned.
  ## If some data has been retrieved; ``RecvPartialLine`` is returned.
  ## If the socket has been disconnected; ``RecvDisconnected`` is returned.
  ## If call to ``recv`` failed; ``RecvFail`` is returned.
  setLen(line.string, 0)
  while true:
    var c: char
    var n = recv(socket, addr(c), 1)
    if n < 0: 
      return (if line.len == 0: RecvFail else: RecvPartialLine)
    elif n == 0: 
      return (if line.len == 0: RecvDisconnected else: RecvPartialLine)
    if c == '\r':
      n = peekChar(socket, c)
      if n > 0 and c == '\L':
        discard recv(socket, addr(c), 1)
      elif n <= 0: 
        return (if line.len == 0: RecvFail else: RecvPartialLine)
      return RecvFullLine
    elif c == '\L': return RecvFullLine
    add(line.string, c)

proc recv*(socket: TSocket): TaintedString {.tags: [FReadIO], deprecated.} =
  ## receives all the available data from the socket.
  ## Socket errors will result in an ``EOS`` error.
  ## If socket is not a connectionless socket and socket is not connected
  ## ``""`` will be returned.
  ##
  ## **Deprecated since version 0.9.2**: This function is not safe for use.
  const bufSize = 4000
  result = newStringOfCap(bufSize).TaintedString
  var pos = 0
  while true:
    var bytesRead = recv(socket, addr(string(result)[pos]), bufSize-1)
    if bytesRead == -1: OSError()
    setLen(result.string, pos + bytesRead)
    if bytesRead != bufSize-1: break
    # increase capacity:
    setLen(result.string, result.string.len + bufSize)
    inc(pos, bytesRead)
  when false:
    var buf = newString(bufSize)
    result = TaintedString""
    while true:
      var bytesRead = recv(socket, cstring(buf), bufSize-1)
      # Error
      if bytesRead == -1: OSError()
      
      buf[bytesRead] = '\0' # might not be necessary
      setLen(buf, bytesRead)
      add(result.string, buf)
      if bytesRead != bufSize-1: break

{.push warning[deprecated]: off.}
proc recvTimeout*(socket: TSocket, timeout: int): TaintedString {.
  tags: [FReadIO], deprecated.} =
  ## overloaded variant to support a ``timeout`` parameter, the ``timeout``
  ## parameter specifies the amount of miliseconds to wait for data on the
  ## socket.
  ##
  ## **Deprecated since version 0.9.2**: This function is not safe for use.
  if socket.bufLen == 0:
    var s = @[socket]
    if s.select(timeout) != 1:
      raise newException(ETimeout, "Call to recv() timed out.")
  
  return socket.recv
{.pop.}

proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
  tags: [FReadIO], deprecated.} =
  ## receives all the data from a non-blocking socket. If socket is non-blocking 
  ## and there are no messages available, `False` will be returned.
  ## Other socket errors will result in an ``EOS`` error.
  ## If socket is not a connectionless socket and socket is not connected
  ## ``s`` will be set to ``""``.
  ##
  ## **Deprecated since version 0.9.2**: This function is not safe for use.
  const bufSize = 1000
  # ensure bufSize capacity:
  setLen(s.string, bufSize)
  setLen(s.string, 0)
  var pos = 0
  while true:
    var bytesRead = recv(socket, addr(string(s)[pos]), bufSize-1)
    when defined(ssl):
      if socket.isSSL:
        if bytesRead <= 0:
          var ret = SSLGetError(socket.sslHandle, bytesRead.cint)
          case ret
          of SSL_ERROR_ZERO_RETURN:
            SSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
          of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
            SSLError("Unexpected error occured.") # This should just not happen.
          of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ:
            return false
          of SSL_ERROR_WANT_X509_LOOKUP:
            SSLError("Function for x509 lookup has been called.")
          of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
            SSLError()
          else: SSLError("Unknown Error")
          
    if bytesRead == -1 and not (when defined(ssl): socket.isSSL else: false):
      when defined(windows):
        # TODO: Test on Windows
        var err = WSAGetLastError()
        if err == WSAEWOULDBLOCK:
          return False
        else: OSError()
      else:
        if errno == EAGAIN or errno == EWOULDBLOCK:
          return False
        else: OSError()

    setLen(s.string, pos + bytesRead)
    if bytesRead != bufSize-1: break
    # increase capacity:
    setLen(s.string, s.string.len + bufSize)
    inc(pos, bytesRead)
  result = True

proc recvFrom*(socket: TSocket, data: var string, length: int,
               address: var string, port: var TPort, flags = 0'i32): int {.
               tags: [FReadIO].} =
  ## Receives data from ``socket``. This function should normally be used with
  ## connection-less sockets (UDP sockets).
  ##
  ## **Warning:** This function does not yet have a buffered implementation,
  ## so when ``socket`` is buffered the non-buffered implementation will be
  ## used. Therefore if ``socket`` contains something in its buffer this
  ## function will make no effort to return it.
  
  # TODO: Buffered sockets
  data.setLen(length)
  var sockAddress: Tsockaddr_in
  var addrLen = sizeof(sockAddress).TSockLen
  result = recvFrom(socket.fd, cstring(data), length.cint, flags.cint,
                    cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen))

  if result != -1:
    data.setLen(result)
    address = $inet_ntoa(sockAddress.sin_addr)
    port = ntohs(sockAddress.sin_port).TPort

proc recvFromAsync*(socket: TSocket, data: var String, length: int,
                    address: var string, port: var TPort, 
                    flags = 0'i32): bool {.tags: [FReadIO].} =
  ## Similar to ``recvFrom`` but raises an EOS error when an error occurs and
  ## is also meant for non-blocking sockets.
  ## Returns False if no messages could be received from ``socket``.
  result = true
  var callRes = recvFrom(socket, data, length, address, port, flags)
  if callRes < 0:
    when defined(windows):
      # TODO: Test on Windows
      var err = WSAGetLastError()
      if err == WSAEWOULDBLOCK:
        return False
      else: OSError()
    else:
      if errno == EAGAIN or errno == EWOULDBLOCK:
        return False
      else: OSError()

proc skip*(socket: TSocket) {.tags: [FReadIO], deprecated.} =
  ## skips all the data that is pending for the socket
  ##
  ## **Deprecated since version 0.9.2**: This function is not safe for use.
  const bufSize = 1000
  var buf = alloc(bufSize)
  while recv(socket, buf, bufSize) == bufSize: nil
  dealloc(buf)

proc skip*(socket: TSocket, size: int) =
  ## Skips ``size`` amount of bytes.
  ##
  ## Returns the number of skipped bytes.
  var dummy = alloc(size)
  var bytesSkipped = 0
  while bytesSkipped != size:
    bytesSkipped += recv(socket, dummy, size-bytesSkipped)
  dealloc(dummy)

proc send*(socket: TSocket, data: pointer, size: int): int {.
  tags: [FWriteIO].} =
  ## sends data to a socket.
  when defined(ssl):
    if socket.isSSL:
      return SSLWrite(socket.sslHandle, cast[cstring](data), size)
  
  when defined(windows) or defined(macosx):
    result = send(socket.fd, data, size.cint, 0'i32)
  else:
    when defined(solaris): 
      const MSG_NOSIGNAL = 0
    result = send(socket.fd, data, size, int32(MSG_NOSIGNAL))

proc send*(socket: TSocket, data: string) {.tags: [FWriteIO].} =
  ## sends data to a socket.
  if send(socket, cstring(data), data.len) != data.len:
    when defined(ssl):
      if socket.isSSL:
        SSLError()
    
    OSError()

proc sendAsync*(socket: TSocket, data: string): int {.tags: [FWriteIO].} =
  ## sends data to a non-blocking socket.
  ## Returns ``0`` if no data could be sent, if data has been sent
  ## returns the amount of bytes of ``data`` that was successfully sent. This
  ## number may not always be the length of ``data`` but typically is.
  ##
  ## An EOS (or ESSL if socket is an SSL socket) exception is raised if an error
  ## occurs.
  result = send(socket, cstring(data), data.len)
  when defined(ssl):
    if socket.isSSL:
      if result <= 0:
          let ret = SSLGetError(socket.sslHandle, result.cint)
          case ret
          of SSL_ERROR_ZERO_RETURN:
            SSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
          of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
            SSLError("Unexpected error occured.") # This should just not happen.
          of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ:
            return 0
          of SSL_ERROR_WANT_X509_LOOKUP:
            SSLError("Function for x509 lookup has been called.")
          of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
            SSLError()
          else: SSLError("Unknown Error")
      else:
        return
  if result == -1:
    when defined(windows):
      var err = WSAGetLastError()
      # TODO: Test on windows.
      if err == WSAEINPROGRESS:
        return 0
      else: OSError()
    else:
      if errno == EAGAIN or errno == EWOULDBLOCK:
        return 0
      else: OSError()
  

proc trySend*(socket: TSocket, data: string): bool {.tags: [FWriteIO].} =
  ## safe alternative to ``send``. Does not raise an EOS when an error occurs,
  ## and instead returns ``false`` on failure.
  result = send(socket, cstring(data), data.len) == data.len

proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
             size: int, af: TDomain = AF_INET, flags = 0'i32): int {.
             tags: [FWriteIO].} =
  ## low-level sendTo proc. This proc sends ``data`` to the specified ``address``,
  ## which may be an IP address or a hostname, if a hostname is specified 
  ## this function will try each IP of that hostname.
  ##
  ## **Note:** This proc is not available for SSL sockets.
  var hints: TAddrInfo
  var aiList: ptr TAddrInfo = nil
  hints.ai_family = toInt(af)
  hints.ai_socktype = toInt(SOCK_STREAM)
  hints.ai_protocol = toInt(IPPROTO_TCP)
  gaiNim(address, port, hints, aiList)
  
  # try all possibilities:
  var success = false
  var it = aiList
  while it != nil:
    result = sendTo(socket.fd, data, size.cint, flags.cint, it.ai_addr,
                    it.ai_addrlen.TSockLen)
    if result != -1'i32:
      success = true
      break
    it = it.ai_next

  freeaddrinfo(aiList)

proc sendTo*(socket: TSocket, address: string, port: TPort, 
             data: string): int {.tags: [FWriteIO].} =
  ## Friendlier version of the low-level ``sendTo``.
  result = socket.sendTo(address, port, cstring(data), data.len)

when defined(Windows):
  const
    IOCPARM_MASK = 127
    IOC_IN = int(-2147483648)
    FIONBIO = int(IOC_IN or ((sizeof(int) and IOCPARM_MASK) shl 16) or 
                             (102 shl 8) or 126)

  proc ioctlsocket(s: TWinSocket, cmd: clong, 
                   argptr: ptr clong): cint {.
                   stdcall, importc:"ioctlsocket", dynlib: "ws2_32.dll".}

proc setBlocking(s: TSocket, blocking: bool) =
  when defined(Windows):
    var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking
    if ioctlsocket(TWinSocket(s.fd), FIONBIO, addr(mode)) == -1:
      OSError()
  else: # BSD sockets
    var x: int = fcntl(s.fd, F_GETFL, 0)
    if x == -1:
      OSError()
    else:
      var mode = if blocking: x and not O_NONBLOCK else: x or O_NONBLOCK
      if fcntl(s.fd, F_SETFL, mode) == -1:
        OSError()

proc connect*(socket: TSocket, timeout: int, name: string, port = TPort(0),
             af: TDomain = AF_INET) {.tags: [FReadIO].} =
  ## Overload for ``connect`` to support timeouts. The ``timeout`` parameter 
  ## specifies the time in miliseconds of how long to wait for a connection
  ## to be made.
  ##
  ## **Warning:** If ``socket`` is non-blocking then
  ## this function will set blocking mode on ``socket`` to true.
  socket.setBlocking(true)
  
  socket.connectAsync(name, port, af)
  var s: seq[TSocket] = @[socket]
  if selectWrite(s, timeout) != 1:
    raise newException(ETimeout, "Call to connect() timed out.")

proc isSSL*(socket: TSocket): bool = return socket.isSSL
  ## Determines whether ``socket`` is a SSL socket.

proc getFD*(socket: TSocket): cint = return socket.fd
  ## Returns the socket's file descriptor

when defined(Windows):
  var wsa: TWSADATA
  if WSAStartup(0x0101'i16, wsa) != 0: OSError()