summaryrefslogtreecommitdiffstats
path: root/contrib/idn/idnkit-1.0-src/lib/converter.c
blob: faed44fb39525d9a2f4bad2f5a15b4ee363b9824 (plain)
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
#ifndef lint
static char *rcsid = "$Id: converter.c,v 1.1.1.1 2003/06/04 00:25:51 marka Exp $";
#endif

/*
 * Copyright (c) 2000,2002 Japan Network Information Center.
 * All rights reserved.
 *  
 * By using this file, you agree to the terms and conditions set forth bellow.
 * 
 * 			LICENSE TERMS AND CONDITIONS 
 * 
 * The following License Terms and Conditions apply, unless a different
 * license is obtained from Japan Network Information Center ("JPNIC"),
 * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
 * Chiyoda-ku, Tokyo 101-0047, Japan.
 * 
 * 1. Use, Modification and Redistribution (including distribution of any
 *    modified or derived work) in source and/or binary forms is permitted
 *    under this License Terms and Conditions.
 * 
 * 2. Redistribution of source code must retain the copyright notices as they
 *    appear in each source code file, this License Terms and Conditions.
 * 
 * 3. Redistribution in binary form must reproduce the Copyright Notice,
 *    this License Terms and Conditions, in the documentation and/or other
 *    materials provided with the distribution.  For the purposes of binary
 *    distribution the "Copyright Notice" refers to the following language:
 *    "Copyright (c) 2000-2002 Japan Network Information Center.  All rights reserved."
 * 
 * 4. The name of JPNIC may not be used to endorse or promote products
 *    derived from this Software without specific prior written approval of
 *    JPNIC.
 * 
 * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC
 *    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 *    PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL JPNIC BE LIABLE
 *    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 *    BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *    OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 *    ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 */

#include <config.h>

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#ifndef WITHOUT_ICONV
#include <iconv.h>
#endif

#include <idn/result.h>
#include <idn/assert.h>
#include <idn/logmacro.h>
#include <idn/converter.h>
#include <idn/aliaslist.h>
#include <idn/strhash.h>
#include <idn/debug.h>
#include <idn/ucs4.h>
#include <idn/punycode.h>
#include <idn/race.h>
#include <idn/util.h>

#ifndef IDN_UTF8_ENCODING_NAME
#define IDN_UTF8_ENCODING_NAME "UTF-8"		/* by IANA */
#endif
#ifndef IDN_RACE_ENCODING_NAME
#define IDN_RACE_ENCODING_NAME "RACE"
#endif
#ifndef IDN_AMCACEZ_ENCODING_NAME
#define IDN_AMCACEZ_ENCODING_NAME "AMC-ACE-Z"
#endif
#ifndef IDN_PUNYCODE_ENCODING_NAME
#define IDN_PUNYCODE_ENCODING_NAME "Punycode"
#endif

#define MAX_RECURSE	20

#ifdef WIN32

#define IDNKEY_IDNKIT		"Software\\JPNIC\\IDN"
#define IDNVAL_ALIASFILE	"AliasFile"

#else /* WIN32 */

#ifndef IDN_RESCONF_DIR
#define IDN_RESCONF_DIR		"/etc"
#endif
#define IDN_ALIAS_FILE		IDN_RESCONF_DIR "/idnalias.conf"

#endif /* WIN32 */

typedef struct {
	idn_converter_openproc_t openfromucs4;
	idn_converter_openproc_t opentoucs4;
	idn_converter_convfromucs4proc_t convfromucs4;
	idn_converter_convtoucs4proc_t convtoucs4;
	idn_converter_closeproc_t close;
	int encoding_type;
} converter_ops_t;

struct idn_converter {
	char *local_encoding_name;
	converter_ops_t *ops;
	int flags;
	int opened_convfromucs4;
	int opened_convtoucs4;
	int reference_count;
	void *private_data;
};

static idn__strhash_t encoding_name_hash;
static idn__aliaslist_t encoding_alias_list;

static idn_result_t	register_standard_encoding(void);
static idn_result_t	roundtrip_check(idn_converter_t ctx,
					const unsigned long *from,
					const char *to);

static idn_result_t
       converter_none_open(idn_converter_t ctx, void **privdata);
static idn_result_t
       converter_none_close(idn_converter_t ctx, void *privdata);
static idn_result_t
       converter_none_convfromucs4(idn_converter_t ctx,
				   void *privdata,
				   const unsigned long *from,
				   char *to, size_t tolen);
static idn_result_t
       converter_none_convtoucs4(idn_converter_t ctx,
				 void *privdata, const char *from,
				 unsigned long *to, size_t tolen);

#ifndef WITHOUT_ICONV
static idn_result_t
       converter_iconv_openfromucs4(idn_converter_t ctx, void **privdata);
static idn_result_t
       converter_iconv_opentoucs4(idn_converter_t ctx, void **privdata);
static idn_result_t
       converter_iconv_close(idn_converter_t ctx, void *privdata);
static idn_result_t
       converter_iconv_convfromucs4(idn_converter_t ctx,
				    void *privdata,
				    const unsigned long *from,
				    char *to, size_t tolen);
static idn_result_t
       converter_iconv_convtoucs4(idn_converter_t ctx,
				  void *privdata,
				  const char *from,
				  unsigned long *to, size_t tolen);

static idn_result_t
iconv_initialize_privdata(void **privdata);
static void
iconv_finalize_privdata(void *privdata);

static char *		get_system_aliasfile(void);
static int		file_exist(const char *filename);

#endif /* !WITHOUT_ICONV */

#ifdef DEBUG
static idn_result_t
       converter_uescape_convfromucs4(idn_converter_t ctx,
				      void *privdata,
				      const unsigned long *from,
				      char *to, size_t tolen);
static idn_result_t
       converter_uescape_convtoucs4(idn_converter_t ctx,
				    void *privdata,
				    const char *from,
				    unsigned long *to,
				    size_t tolen);
#endif /* DEBUG */

static converter_ops_t none_converter_ops = {
	converter_none_open,
	converter_none_open,
	converter_none_convfromucs4,
	converter_none_convtoucs4,
	converter_none_close,
	IDN_NONACE,
};

#ifndef WITHOUT_ICONV
static converter_ops_t iconv_converter_ops = {
	converter_iconv_openfromucs4,
	converter_iconv_opentoucs4,
	converter_iconv_convfromucs4,
	converter_iconv_convtoucs4,
	converter_iconv_close,
	IDN_NONACE,
};
#endif

/*
 * Initialize.
 */

idn_result_t
idn_converter_initialize(void) {
	idn_result_t r;
	idn__strhash_t hash;
	idn__aliaslist_t list;
#ifndef WITHOUT_ICONV
	const char *fname;
#endif

	TRACE(("idn_converter_initialize()\n"));

	if (encoding_name_hash == NULL) {
		if ((r = idn__strhash_create(&hash)) != idn_success)
			goto ret;
		encoding_name_hash = hash;
		r = register_standard_encoding();
	}
	if (encoding_alias_list == NULL) {
		if ((r = idn__aliaslist_create(&list)) != idn_success)
			goto ret;
		encoding_alias_list = list;
#ifndef WITHOUT_ICONV
		fname = get_system_aliasfile();
		if (fname != NULL && file_exist(fname))
			idn_converter_aliasfile(fname);
#endif
	}

	r = idn_success;
ret:
	TRACE(("idn_converter_initialize(): %s\n", idn_result_tostring(r)));
	return (r);
}

#ifndef WITHOUT_ICONV
static char *
get_system_aliasfile() {
#ifdef WIN32
	static char alias_path[500];	/* a good longer than MAX_PATH */

	if (idn__util_getregistrystring(idn__util_hkey_localmachine,
					IDNVAL_ALIASFILE,
					alias_path, sizeof(alias_path))) {
		return (alias_path);
	} else {
		return (NULL);
	}
#else
	return (IDN_ALIAS_FILE);
#endif
}

static int
file_exist(const char *filename) {
	FILE  *fp;

	if ((fp = fopen(filename, "r")) == NULL)
		return (0);
	fclose(fp);
	return (1);
}
#endif

idn_result_t
idn_converter_create(const char *name, idn_converter_t *ctxp, int flags) {
	const char *realname;
	idn_converter_t ctx;
	idn_result_t r;
	void *v;

	assert(name != NULL && ctxp != NULL);

	TRACE(("idn_converter_create(%s)\n", name));

	realname = idn_converter_getrealname(name);
#ifdef DEBUG
	if (strcmp(name, realname) != 0) {
		TRACE(("idn_converter_create: realname=%s\n", realname));
	}
#endif

	*ctxp = NULL;

	/* Allocate memory for a converter context and the name. */
	ctx = malloc(sizeof(struct idn_converter) + strlen(realname) + 1);
	if (ctx == NULL) {
		r = idn_nomemory;
		goto ret;
	}

	ctx->local_encoding_name = (char *)(ctx + 1);
	(void)strcpy(ctx->local_encoding_name, realname);
	ctx->flags = flags;
	ctx->reference_count = 1;
	ctx->opened_convfromucs4 = 0;
	ctx->opened_convtoucs4 = 0;
	ctx->private_data = NULL;

	assert(encoding_name_hash != NULL);

	if (strcmp(realname, IDN_UTF8_ENCODING_NAME) == 0) {
		/* No conversion needed */
		ctx->ops = &none_converter_ops;
	} else if ((r = idn__strhash_get(encoding_name_hash, realname, &v))
		   == idn_success) {
		/* Special converter found */
		ctx->ops = (converter_ops_t *)v;
	} else {
		/* General case */
#ifdef WITHOUT_ICONV
		free(ctx);
		*ctxp = NULL;
		r = idn_invalid_name;
		goto ret;
#else
		ctx->ops = &iconv_converter_ops;
#endif
	}

	if ((flags & IDN_CONVERTER_DELAYEDOPEN) == 0) {
		r = (ctx->ops->openfromucs4)(ctx, &(ctx->private_data));
		if (r != idn_success) {
			WARNING(("idn_converter_create(): open failed "
			     "(ucs4->local)\n"));
			free(ctx);
			*ctxp = NULL;
			goto ret;
		}
		ctx->opened_convfromucs4 = 1;

		r = (*ctx->ops->opentoucs4)(ctx, &(ctx->private_data));
		if (r != idn_success) {
			WARNING(("idn_converter_create(): open failed "
			     "(local->ucs4)\n"));
			free(ctx);
			*ctxp = NULL;
			goto ret;
		}
		ctx->opened_convtoucs4 = 1;
	}

	*ctxp = ctx;
	r = idn_success;
ret:
	TRACE(("idn_converter_create(): %s\n", idn_result_tostring(r)));
	return (r);
}

void
idn_converter_destroy(idn_converter_t ctx) {
	assert(ctx != NULL);

	TRACE(("idn_converter_destroy(ctx=%s)\n", ctx->local_encoding_name));

	ctx->reference_count--;
	if (ctx->reference_count <= 0) {
		TRACE(("idn_converter_destroy(): the object is destroyed\n"));
		(void)(*ctx->ops->close)(ctx, ctx->private_data);
		free(ctx);
	} else {
		TRACE(("idn_converter_destroy(): "
		       "update reference count (%d->%d)\n",
		       ctx->reference_count + 1, ctx->reference_count));
	}
}

void
idn_converter_incrref(idn_converter_t ctx) {
	assert(ctx != NULL);

	TRACE(("idn_converter_incrref(ctx=%s)\n", ctx->local_encoding_name));
	TRACE(("idn_converter_incrref: update reference count (%d->%d)\n",
	    ctx->reference_count, ctx->reference_count + 1));

	ctx->reference_count++;
}

char *
idn_converter_localencoding(idn_converter_t ctx) {
	assert(ctx != NULL);
	TRACE(("idn_converter_localencoding(ctx=%s)\n",
	       ctx->local_encoding_name));
	return (ctx->local_encoding_name);
}
	
int
idn_converter_encodingtype(idn_converter_t ctx) {
	int encoding_type;

	assert(ctx != NULL);
	TRACE(("idn_converter_encodingtype(ctx=%s)\n",
	       ctx->local_encoding_name));

	encoding_type = ctx->ops->encoding_type;
	TRACE(("idn_converter_encodingtype(): %d\n", encoding_type));
	return (encoding_type);
}

int
idn_converter_isasciicompatible(idn_converter_t ctx) {
	int iscompat;

	assert(ctx != NULL);
	TRACE(("idn_converter_isasciicompatible(ctx=%s)\n",
	       ctx->local_encoding_name));

	iscompat = (ctx->ops->encoding_type != IDN_NONACE);
	TRACE(("idn_converter_isasciicompatible(): %d\n", iscompat));
	return (iscompat);
}

idn_result_t
idn_converter_convfromucs4(idn_converter_t ctx, const unsigned long *from,
			   char *to, size_t tolen) {
	idn_result_t r;

	assert(ctx != NULL && from != NULL && to != NULL);

	TRACE(("idn_converter_convfromucs4(ctx=%s, from=\"%s\", tolen=%d)\n",
	       ctx->local_encoding_name, idn__debug_ucs4xstring(from, 50),
	       (int)tolen));

	if (!ctx->opened_convfromucs4) {
		r = (*ctx->ops->openfromucs4)(ctx, &(ctx->private_data));
		if (r != idn_success)
			goto ret;
		ctx->opened_convfromucs4 = 1;
	}

	r = (*ctx->ops->convfromucs4)(ctx, ctx->private_data, from, to, tolen);
	if (r != idn_success)
		goto ret;
	if ((ctx->flags & IDN_CONVERTER_RTCHECK) != 0) {
		r = roundtrip_check(ctx, from, to);
		if (r != idn_success)
			goto ret;
	}
	
	r = idn_success;
ret:
	if (r == idn_success) {
		TRACE(("idn_converter_convfromucs4(): success (to=\"%s\")\n",
		       idn__debug_xstring(to, 50)));
	} else {
		TRACE(("idn_converter_convfromucs4(): %s\n",
		       idn_result_tostring(r)));
	}
	return (r);
}

idn_result_t
idn_converter_convtoucs4(idn_converter_t ctx, const char *from,
			 unsigned long *to, size_t tolen) {
	idn_result_t r;

	assert(ctx != NULL && from != NULL && to != NULL);

	TRACE(("idn_converter_convtoucs4(ctx=%s, from=\"%s\", tolen=%d)\n",
	       ctx->local_encoding_name, idn__debug_xstring(from, 50),
	       (int)tolen));

	if (!ctx->opened_convtoucs4) {
		r = (*ctx->ops->opentoucs4)(ctx, &(ctx->private_data));
		if (r != idn_success)
			goto ret;
		ctx->opened_convtoucs4 = 1;
	}

	r = (*ctx->ops->convtoucs4)(ctx, ctx->private_data, from, to, tolen);
ret:
	if (r == idn_success) {
		TRACE(("idn_converter_convtoucs4(): success (to=\"%s\")\n",
		       idn__debug_ucs4xstring(to, 50)));
	} else {
		TRACE(("idn_converter_convtoucs4(): %s\n",
		       idn_result_tostring(r)));
	}
	return (r);
}

/*
 * Encoding registration.
 */

idn_result_t
idn_converter_register(const char *name,
		       idn_converter_openproc_t openfromucs4,
		       idn_converter_openproc_t opentoucs4,
		       idn_converter_convfromucs4proc_t convfromucs4,
		       idn_converter_convtoucs4proc_t convtoucs4,
		       idn_converter_closeproc_t close,
		       int encoding_type) {
	converter_ops_t *ops;
	idn_result_t r;

	assert(name != NULL && convfromucs4 != NULL && convtoucs4 != NULL);

	TRACE(("idn_converter_register(name=%s)\n", name));

	if ((ops = malloc(sizeof(*ops))) == NULL) {
		r = idn_nomemory;
		goto ret;
	}

	if (openfromucs4 == NULL)
		openfromucs4 = converter_none_open;
	if (opentoucs4 == NULL)
		opentoucs4 = converter_none_open;
	if (close == NULL)
		close = converter_none_close;

	ops->openfromucs4 = openfromucs4;
	ops->opentoucs4 = opentoucs4;
	ops->convfromucs4 = convfromucs4;
	ops->convtoucs4 = convtoucs4;
	ops->close = close;
	ops->encoding_type = encoding_type;

	r = idn__strhash_put(encoding_name_hash, name, ops);
	if (r != idn_success) {
		free(ops);
		goto ret;
	}

	r = idn_success;
ret:
	TRACE(("idn_converter_register(): %s\n", idn_result_tostring(r)));
	return (r);
}

static idn_result_t
register_standard_encoding(void) {
	idn_result_t r;

	r = idn_converter_register(IDN_PUNYCODE_ENCODING_NAME,
				   NULL,
				   NULL,
				   idn__punycode_encode,
				   idn__punycode_decode,
				   converter_none_close,
				   IDN_ACE_STRICTCASE);
	if (r != idn_success)
		return (r);

#ifdef IDN_EXTRA_ACE
	r = idn_converter_register(IDN_AMCACEZ_ENCODING_NAME,
				   NULL,
				   NULL,
				   idn__punycode_encode,
				   idn__punycode_decode,
				   converter_none_close,
				   IDN_ACE_STRICTCASE);
	if (r != idn_success)
		return (r);

	r = idn_converter_register(IDN_RACE_ENCODING_NAME,
				   NULL,
				   NULL,
				   idn__race_encode,
				   idn__race_decode,
				   converter_none_close,
				   IDN_ACE_LOOSECASE);
	if (r != idn_success)
		return (r);
#endif /* IDN_EXTRA_ACE */

#ifdef DEBUG
	/* This is convenient for debug.  Not useful for other purposes. */
	r = idn_converter_register("U-escape",
				   NULL,
				   NULL,
				   converter_uescape_convfromucs4,
				   converter_uescape_convtoucs4,
				   NULL,
				   IDN_NONACE);
	if (r != idn_success)
		return (r);
#endif /* DEBUG */

	return (r);
}

/*
 * Encoding alias support.
 */
idn_result_t
idn_converter_addalias(const char *alias_name, const char *real_name,
		       int first_item) {
	idn_result_t r;

	assert(alias_name != NULL && real_name != NULL);

	TRACE(("idn_converter_addalias(alias_name=%s,real_name=%s)\n",
	       alias_name, real_name));

	if (strlen(alias_name) == 0 || strlen(real_name) == 0) {
		return idn_invalid_syntax;
	}

	if (strcmp(alias_name, real_name) == 0) {
		r = idn_success;
		goto ret;
	}

	if (encoding_alias_list == NULL) {
		WARNING(("idn_converter_addalias(): the module is not "
			 "initialized\n"));
		r = idn_failure;
		goto ret;
	}

	r = idn__aliaslist_additem(encoding_alias_list, alias_name, real_name,
				   first_item);
ret:
	TRACE(("idn_converter_addalias(): %s\n", idn_result_tostring(r)));
	return (r);
}

idn_result_t
idn_converter_aliasfile(const char *path) {
	idn_result_t r;

	assert(path != NULL);

	TRACE(("idn_converter_aliasfile(path=%s)\n", path));

	if (encoding_alias_list == NULL) {
		WARNING(("idn_converter_aliasfile(): the module is not "
			 "initialized\n"));
		return (idn_failure);
	}

	r = idn__aliaslist_aliasfile(encoding_alias_list, path);

	TRACE(("idn_converter_aliasfile(): %s\n", idn_result_tostring(r)));
	return (r);
}

idn_result_t
idn_converter_resetalias(void) {
	idn__aliaslist_t list;
	idn_result_t r;

 	TRACE(("idn_converter_resetalias()\n"));
 
	if (encoding_alias_list == NULL) {
		WARNING(("idn_converter_resetalias(): the module is not "
			 "initialized\n"));
		return (idn_failure);
	}

	list = encoding_alias_list;
	encoding_alias_list = NULL;
	idn__aliaslist_destroy(list);
	list = NULL;
	r = idn__aliaslist_create(&list);
	encoding_alias_list = list;

	TRACE(("idn_converter_resetalias(): %s\n", idn_result_tostring(r)));
	return (r);
}

const char *
idn_converter_getrealname(const char *name) {
	char *realname;
	idn_result_t r;

 	TRACE(("idn_converter_getrealname()\n"));

	assert(name != NULL);

	if (encoding_alias_list == NULL) {
		WARNING(("idn_converter_getrealname(): the module is not "
			 "initialized\n"));
		return (name);
	}

	r = idn__aliaslist_find(encoding_alias_list, name, &realname);
	if (r != idn_success) {
		return (name);
	}
	return (realname);
}

/*
 * Round trip check.
 */

static idn_result_t
roundtrip_check(idn_converter_t ctx, const unsigned long *from, const char *to)
{
	/*
	 * One problem with iconv() convertion is that
	 * iconv() doesn't signal an error if the input
	 * string contains characters which are valid but
	 * do not have mapping to the output codeset.
	 * (the behavior of iconv() for that case is defined as
	 * `implementation dependent')
	 * One way to check this case is to perform round-trip
	 * conversion and see if it is same as the original string.
	 */
	idn_result_t r;
	unsigned long *back;
	unsigned long backbuf[256];
	size_t fromlen;
	size_t backlen;

	TRACE(("idn_converter_convert: round-trip checking (from=\"%s\")\n",
	       idn__debug_ucs4xstring(from, 50)));

	/* Allocate enough buffer. */
	fromlen = idn_ucs4_strlen(from) + 1;
	if (fromlen * sizeof(*back) <= sizeof(backbuf)) {
		backlen = sizeof(backbuf);
		back = backbuf;
	} else {
		backlen = fromlen;
		back = (unsigned long *)malloc(backlen * sizeof(*back));
		if (back == NULL)
			return (idn_nomemory);
	}

	/*
	 * Perform backward conversion.
	 */
	r = idn_converter_convtoucs4(ctx, to, back, backlen);
	switch (r) {
	case idn_success:
		if (memcmp(back, from, sizeof(*from) * fromlen) != 0)
			r = idn_nomapping;
		break;
	case idn_invalid_encoding:
	case idn_buffer_overflow:
		r = idn_nomapping;
		break;
	default:
		break;
	}

	if (back != backbuf)
		free(back);

	if (r != idn_success) {
		TRACE(("round-trip check failed: %s\n",
		       idn_result_tostring(r)));
	}

	return (r);
}

/*
 * Identity conversion (or, no conversion at all).
 */

static idn_result_t
converter_none_open(idn_converter_t ctx, void **privdata) {
	assert(ctx != NULL);

	return (idn_success);
}

static idn_result_t
converter_none_close(idn_converter_t ctx, void *privdata) {
	assert(ctx != NULL);

	return (idn_success);
}

static idn_result_t
converter_none_convfromucs4(idn_converter_t ctx, void *privdata,
		       const unsigned long *from, char *to, size_t tolen) {
	assert(ctx != NULL && from != NULL && to != NULL);

	return idn_ucs4_ucs4toutf8(from, to, tolen);
}

static idn_result_t
converter_none_convtoucs4(idn_converter_t ctx, void *privdata,
		     const char *from, unsigned long *to, size_t tolen) {
	assert(ctx != NULL && from != NULL && to != NULL);

	return idn_ucs4_utf8toucs4(from, to, tolen);
}

#ifndef WITHOUT_ICONV

/*
 * Conversion using iconv() interface.
 */

static idn_result_t
converter_iconv_openfromucs4(idn_converter_t ctx, void **privdata) {
	iconv_t *ictxp;
	idn_result_t r;

	assert(ctx != NULL);

	r = iconv_initialize_privdata(privdata);
	if (r != idn_success)
		return (r);

	ictxp = (iconv_t *)*privdata;
	*ictxp = iconv_open(ctx->local_encoding_name, IDN_UTF8_ENCODING_NAME);
	if (*ictxp == (iconv_t)(-1)) {
		free(*privdata);
		*privdata = NULL;
		switch (errno) {
		case ENOMEM:
			return (idn_nomemory);
		case EINVAL:
			return (idn_invalid_name);
		default:
			WARNING(("iconv_open failed with errno %d\n", errno));
			return (idn_failure);
		}
	}

	return (idn_success);
}

static idn_result_t
converter_iconv_opentoucs4(idn_converter_t ctx, void **privdata) {
	iconv_t *ictxp;
	idn_result_t r;

	assert(ctx != NULL);

	r = iconv_initialize_privdata(privdata);
	if (r != idn_success)
		return (r);

	ictxp = (iconv_t *)*privdata + 1;
	*ictxp = iconv_open(IDN_UTF8_ENCODING_NAME, ctx->local_encoding_name);
	if (*ictxp == (iconv_t)(-1)) {
		free(*privdata);
		*privdata = NULL;
		switch (errno) {
		case ENOMEM:
			return (idn_nomemory);
		case EINVAL:
			return (idn_invalid_name);
		default:
			WARNING(("iconv_open failed with errno %d\n", errno));
			return (idn_failure);
		}
	}

	return (idn_success);
}

static idn_result_t
iconv_initialize_privdata(void **privdata) {
	if (*privdata == NULL) {
		*privdata = malloc(sizeof(iconv_t) * 2);
		if (*privdata == NULL)
			return (idn_nomemory);
		*((iconv_t *)*privdata) = (iconv_t)(-1);
		*((iconv_t *)*privdata + 1) = (iconv_t)(-1);
	}

	return (idn_success);
}

static void
iconv_finalize_privdata(void *privdata) {
	iconv_t *ictxp;
	
	if (privdata != NULL) {
		ictxp = (iconv_t *)privdata;
		if (*ictxp != (iconv_t)(-1))
			iconv_close(*ictxp);

		ictxp++;
		if (*ictxp != (iconv_t)(-1))
			iconv_close(*ictxp);
		free(privdata);
	}
}

static idn_result_t
converter_iconv_close(idn_converter_t ctx, void *privdata) {
	assert(ctx != NULL);

	iconv_finalize_privdata(privdata);

	return (idn_success);
}

static idn_result_t
converter_iconv_convfromucs4(idn_converter_t ctx, void *privdata,
			     const unsigned long *from, char *to,
			     size_t tolen) {
	iconv_t ictx;
	char *utf8 = NULL;
	size_t utf8size = 256;  /* large enough */
	idn_result_t r;
	size_t sz;
	size_t inleft;
	size_t outleft;
	char *inbuf, *outbuf;

	assert(ctx != NULL && from != NULL && to != NULL);

	if (tolen <= 0) {
		r = idn_buffer_overflow;	/* need space for NUL */
		goto ret;
	}

	/*
	 * UCS4 -> UTF-8 conversion.
	 */
	utf8 = (char *)malloc(utf8size);
	if (utf8 == NULL) {
		r = idn_nomemory;
		goto ret;
	}

try_again:
	r = idn_ucs4_ucs4toutf8(from, utf8, utf8size);
	if (r == idn_buffer_overflow) {
		char *new_utf8;

		utf8size *= 2;
		new_utf8 = (char *)realloc(utf8, utf8size);
		if (new_utf8 == NULL) {
			r = idn_nomemory;
			goto ret;
		}
		utf8 = new_utf8;
		goto try_again;
	} else if (r != idn_success) {
		goto ret;
	}

	ictx = ((iconv_t *)privdata)[0];

	/*
	 * Reset internal state.
	 * 
	 * The following code should work according to the SUSv2 spec,
	 * but causes segmentation fault with Solaris 2.6.
	 * So.. a work-around.
	 * 
	 * (void)iconv(ictx, (const char **)NULL, (size_t *)NULL, 
	 * 	    (char **)NULL, (size_t *)NULL);
	 */
	inleft = 0;
	outbuf = NULL;
	outleft = 0;
	(void)iconv(ictx, (const char **)NULL, &inleft, &outbuf, &outleft);

	inleft = strlen(utf8);
	inbuf = utf8;
	outleft = tolen - 1;	/* reserve space for terminating NUL */
	sz = iconv(ictx, (const char **)&inbuf, &inleft, &to, &outleft);

	if (sz == (size_t)(-1) || inleft > 0) {
		switch (errno) {
		case EILSEQ:
		case EINVAL:
			/*
			 * We already checked the validity of the input
			 * string.  So we assume a mapping error.
			 */
			r = idn_nomapping;
			goto ret;
		case E2BIG:
			r = idn_buffer_overflow;
			goto ret;
		default:
			WARNING(("iconv failed with errno %d\n", errno));
			r = idn_failure;
			goto ret;
		}
	}

	/*
	 * For UTF-8 -> local conversion, append a sequence of
	 * state reset.
	 */
	inleft = 0;
	sz = iconv(ictx, (const char **)NULL, &inleft, &to, &outleft);
	if (sz == (size_t)(-1)) {
		switch (errno) {
		case EILSEQ:
		case EINVAL:
			r = idn_invalid_encoding;
			goto ret;
		case E2BIG:
			r = idn_buffer_overflow;
			goto ret;
		default:
			WARNING(("iconv failed with errno %d\n", errno));
			r = idn_failure;
			goto ret;
		}
	}
	*to = '\0';
	r = idn_success;

ret:
	free(utf8);
	return (r);

}

static idn_result_t
converter_iconv_convtoucs4(idn_converter_t ctx, void *privdata,
			   const char *from, unsigned long *to, size_t tolen) {
	iconv_t ictx;
	char *utf8 = NULL;
	size_t utf8size = 256;  /* large enough */
	idn_result_t r;
	size_t sz;
	size_t inleft;
	size_t outleft;
	const char *from_ptr;
	char *outbuf;

	assert(ctx != NULL && from != NULL && to != NULL);

	if (tolen <= 0) {
		r = idn_buffer_overflow;	/* need space for NUL */
		goto ret;
	}
	ictx = ((iconv_t *)privdata)[1];
	utf8 = (char *)malloc(utf8size);
	if (utf8 == NULL) {
		r = idn_nomemory;
		goto ret;
	}

try_again:
	/*
	 * Reset internal state.
	 */
	inleft = 0;
	outbuf = NULL;
	outleft = 0;
	(void)iconv(ictx, (const char **)NULL, &inleft, &outbuf, &outleft);

	from_ptr = from;
	inleft = strlen(from);
	outbuf = utf8;
	outleft = utf8size - 1;    /* reserve space for terminating NUL */
	sz = iconv(ictx, (const char **)&from_ptr, &inleft, &outbuf, &outleft);

	if (sz == (size_t)(-1) || inleft > 0) {
		char *new_utf8;

		switch (errno) {
		case EILSEQ:
		case EINVAL:
			/*
			 * We assume all the characters in the local
			 * codeset are included in UCS.  This means mapping
			 * error is not possible, so the input string must
			 * have some problem.
			 */
			r = idn_invalid_encoding;
			goto ret;
		case E2BIG:
			utf8size *= 2;
			new_utf8 = (char *)realloc(utf8, utf8size);
			if (new_utf8 == NULL) {
				r = idn_nomemory;
				goto ret;
			}
			utf8 = new_utf8;
			goto try_again;
		default:
			WARNING(("iconv failed with errno %d\n", errno));
			r = idn_failure;
			goto ret;
		}
	}
	*outbuf = '\0';

	/*
	 * UTF-8 -> UCS4 conversion.
	 */
	r = idn_ucs4_utf8toucs4(utf8, to, tolen);

ret:
	free(utf8);
	return (r);
}

#endif /* !WITHOUT_ICONV */

#ifdef DEBUG
/*
 * Conversion to/from unicode escape string.
 * Arbitrary UCS-4 character can be specified by a special sequence
 *	\u{XXXXXX}
 * where XXXXX denotes any hexadecimal string up to FFFFFFFF.
 * This is designed for debugging.
 */

static idn_result_t
converter_uescape_convfromucs4(idn_converter_t ctx, void *privdata,
			  const unsigned long *from, char *to,
			  size_t tolen) {
	idn_result_t r;
	unsigned long v;

	while (*from != '\0') {
		v = *from++;

		if (v <= 0x7f) {
			if (tolen < 1) {
				r = idn_buffer_overflow;
				goto failure;
			}
			*to++ = v;
			tolen--;
		} else if (v <= 0xffffffff) {
			char tmp[20];
			int len;

			(void)sprintf(tmp, "\\u{%lx}", v);
			len = strlen(tmp);
			if (tolen < len) {
				r = idn_buffer_overflow;
				goto failure;
			}
			(void)memcpy(to, tmp, len);
			to += len;
			tolen -= len;
		} else {
			r = idn_invalid_encoding;
			goto failure;
		}
	}

	if (tolen <= 0) {
		r = idn_buffer_overflow;
		goto failure;
	}
	*to = '\0';

	return (idn_success);

failure:
	if (r != idn_buffer_overflow) {
		WARNING(("idn_uescape_convfromucs4(): %s\n",
			 idn_result_tostring(r)));
	}
	return (r);
}

static idn_result_t
converter_uescape_convtoucs4(idn_converter_t ctx, void *privdata,
			const char *from, unsigned long *to, size_t tolen)
{
	idn_result_t r;
	size_t fromlen = strlen(from);

	while (*from != '\0') {
		if (tolen <= 0) {
			r = idn_buffer_overflow;
			goto failure;
		}
		if (strncmp(from, "\\u{", 3) == 0 ||
		    strncmp(from, "\\U{", 3) == 0) {
			size_t ullen;
			unsigned long v;
			char *end;

			v = strtoul(from + 3, &end, 16);
			ullen = end - (from + 3);
			if (*end == '}' && ullen > 1 && ullen < 8) {
				*to = v;
				from = end + 1;
				fromlen -= ullen;
			} else {
				*to = '\\';
				from++;
				fromlen--;
			}
		} else {
			int c = *(unsigned char *)from;
			size_t width;
			char buf[8];

			if (c < 0x80)
				width = 1;
			else if (c < 0xc0)
				width = 0;
			else if (c < 0xe0)
				width = 2;
			else if (c < 0xf0)
				width = 3;
			else if (c < 0xf8)
				width = 4;
			else if (c < 0xfc)
				width = 5;
			else if (c < 0xfe)
				width = 6;
			else
				width = 0;
			if (width == 0 || width > fromlen) {
				r = idn_invalid_encoding;
				goto failure;
			}

			memcpy(buf, from, width);
			buf[width] = '\0';
			r = idn_ucs4_utf8toucs4(buf, to, tolen);
			if (r != idn_success) {
				r = idn_invalid_encoding;
				goto failure;
			}
			from += width;
			fromlen -= width;
		}
		to++;
		tolen--;
	}

	if (tolen <= 0) {
		r = idn_buffer_overflow;
		goto failure;
	}
	*to = '\0';

	return (idn_success);

failure:
	if (r != idn_buffer_overflow) {
		WARNING(("idn_uescape_convtoucs4(): %s\n",
			 idn_result_tostring(r)));
	}
	return (r);
}

#endif