summaryrefslogtreecommitdiffstats
path: root/src/url.c
blob: dcbd0068923a1b89db931d222f1856379aae7377 (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
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
/*
 * Copyright (c) 2012, Vsevolod Stakhov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY AUTHOR ''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 AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "url.h"
#include "util.h"
#include "fstring.h"
#include "main.h"
#include "message.h"
#include "trie.h"

#define POST_CHAR 1
#define POST_CHAR_S "\001"

/* Tcp port range */
#define LOWEST_PORT 0
#define HIGHEST_PORT    65535

#define uri_port_is_valid(port) \
    (LOWEST_PORT <= (port) && (port) <= HIGHEST_PORT)

struct _proto {
	guchar                         *name;
	gint                            port;
	uintptr_t                      *unused;
	guint                           need_slashes:1;
	guint                           need_slash_after_host:1;
	guint                           free_syntax:1;
	guint                           need_ssl:1;
};

typedef struct url_match_s {
	const gchar *m_begin;
	gsize m_len;
	const gchar *pattern;
	const gchar *prefix;
	gboolean add_prefix;
} url_match_t;

#define URL_FLAG_NOHTML 0x1
struct url_matcher {
	const gchar *pattern;
	const gchar *prefix;
	gboolean (*start)(const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);
	gboolean (*end)(const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);
	gint flags;
};

static gboolean url_file_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);
static gboolean url_file_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);

static gboolean url_web_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);
static gboolean url_web_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);

static gboolean url_tld_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);
static gboolean url_tld_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);

static gboolean url_email_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);
static gboolean url_email_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match);

struct url_matcher matchers[] = {
		/* Common prefixes */
		{ "file://",		"",			url_file_start, 		url_file_end,	0					},
		{ "ftp://",			"",			url_web_start,	 		url_web_end,	0					},
		{ "sftp://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "http://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "https://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "news://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "nntp://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "telnet://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "webcal://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "mailto://",		"",			url_email_start,	 	url_email_end,	0					},
		{ "callto://",		"",			url_web_start,	 		url_web_end,	0					},
		{ "h323:",			"",			url_web_start,	 		url_web_end,	0					},
		{ "sip:",			"",			url_web_start,	 		url_web_end,	0					},
		{ "www.",			"http://",	url_web_start,			url_web_end,	0					},
		{ "ftp.",			"ftp://", 	url_web_start,	 		url_web_end,	URL_FLAG_NOHTML		},
		/* TLD domains parts */
		{ ".ac",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ad",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ae",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".aero",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".af",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ag",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ai",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".al",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".am",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".an",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ao",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".aq",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ar",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".arpa",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".as",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".asia",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".at",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".au",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".aw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ax",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".az",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ba",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bb",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bd",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".be",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bf",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bh",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bi",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".biz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bj",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bo",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".br",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bs",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bt",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bv",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".by",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".bz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ca",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cat",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cc",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cd",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cf",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ch",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ci",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ck",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cl",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".co",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".com",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".coop",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cv",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cx",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cy",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".cz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".de",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".dj",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".dk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".dm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".do",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".dz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ec",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".edu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ee",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".eg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".er",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".es",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".et",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".eu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".fi",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".fj",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".fk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".fm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".fo",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".fr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ga",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gb",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gd",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ge",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gf",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gh",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gi",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gl",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gov",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gp",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gq",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gs",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gt",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".gy",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".hk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".hm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".hn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".hr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ht",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".hu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".id",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ie",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".il",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".im",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".in",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".info",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".int",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".io",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".iq",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ir",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".is",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".it",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".je",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".jm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".jo",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".jobs",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".jp",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ke",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".kg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".kh",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ki",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".km",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".kn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".kp",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".kr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".kw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ky",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".kz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".la",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".lb",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".lc",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".li",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".lk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".lr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ls",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".lt",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".lu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".lv",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ly",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ma",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mc",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".md",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".me",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mh",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mil",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ml",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mo",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mobi",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mp",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mq",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ms",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mt",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".museum",		"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mv",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mx",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".my",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".mz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".na",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".name",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".nc",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ne",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".net",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".nf",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ng",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ni",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".nl",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".no",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".np",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".nr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".nu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".nz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".om",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".org",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pa",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pe",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pf",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ph",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pl",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pro",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ps",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pt",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".pw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".py",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".qa",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".re",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ro",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".rs",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ru",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".rw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sa",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sb",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sc",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sd",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".se",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sh",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".si",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sj",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sl",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".so",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".st",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".su",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sv",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sx",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sy",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".sz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tc",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".td",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tel",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tf",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".th",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tj",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tl",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".to",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tp",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tr",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".travel",		"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tt",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tv",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".tz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ua",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ug",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".uk",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".us",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".uy",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".uz",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".va",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".vc",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ve",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".vg",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".vi",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".vn",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".vu",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".wf",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ws",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".xxx",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".ye",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".yt",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".za",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".zm",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		{ ".zw",			"http://",	url_tld_start,			url_tld_end,	URL_FLAG_NOHTML		},
		/* Likely emails */
		{ "@",				"mailto://",url_email_start,	 	url_email_end,	0					}
};

struct url_match_scanner {
	struct url_matcher *matchers;
	gsize matchers_count;
	rspamd_trie_t *patterns;
};

struct url_match_scanner *url_scanner = NULL;

static const struct _proto      protocol_backends[] = {
	{"file", 0, NULL, 1, 0, 0, 0},
	{"ftp", 21, NULL, 1, 0, 0, 0},
	{"http", 80, NULL, 1, 0, 0, 0},
	{"https", 443, NULL, 1, 0, 0, 1},
	{"mailto", 25, NULL, 1, 0, 0, 0},
	/* Keep these last! */
	{NULL, 0, NULL, 0, 0, 1, 0}
};

/* Convert an ASCII hex digit to the corresponding number between 0
   and 15.  H should be a hexadecimal digit that satisfies isxdigit;
   otherwise, the result is undefined.  */
#define XDIGIT_TO_NUM(h) ((h) < 'A' ? (h) - '0' : g_ascii_toupper (h) - 'A' + 10)
#define X2DIGITS_TO_NUM(h1, h2) ((XDIGIT_TO_NUM (h1) << 4) + XDIGIT_TO_NUM (h2))
/* The reverse of the above: convert a number in the [0, 16) range to
   the ASCII representation of the corresponding hexadecimal digit.
   `+ 0' is there so you can't accidentally use it as an lvalue.  */
#define XNUM_TO_DIGIT(x) ("0123456789ABCDEF"[x] + 0)
#define XNUM_TO_digit(x) ("0123456789abcdef"[x] + 0)

static guchar url_scanner_table[256] = {
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  9,  9,  1,  1,  9,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	 24,128,160,128,128,128,128,128,160,160,128,128,160,192,160,160,
	 68, 68, 68, 68, 68, 68, 68, 68, 68, 68,160,160, 32,128, 32,128,
	160, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
	 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,160,160,160,128,192,
	128, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
	 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66,128,128,128,128,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
	  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1
};

enum {
	IS_CTRL		= (1 << 0),
	IS_ALPHA        = (1 << 1),
	IS_DIGIT        = (1 << 2),
	IS_LWSP		= (1 << 3),
	IS_SPACE	= (1 << 4),
	IS_SPECIAL	= (1 << 5),
	IS_DOMAIN       = (1 << 6),
	IS_URLSAFE      = (1 << 7)
};

#define is_ctrl(x) ((url_scanner_table[(guchar)(x)] & IS_CTRL) != 0)
#define is_lwsp(x) ((url_scanner_table[(guchar)(x)] & IS_LWSP) != 0)
#define is_atom(x) ((url_scanner_table[(guchar)(x)] & (IS_SPECIAL|IS_SPACE|IS_CTRL)) == 0)
#define is_alpha(x) ((url_scanner_table[(guchar)(x)] & IS_ALPHA) != 0)
#define is_digit(x) ((url_scanner_table[(guchar)(x)] & IS_DIGIT) != 0)
#define is_domain(x) ((url_scanner_table[(guchar)(x)] & IS_DOMAIN) != 0)
#define is_urlsafe(x) ((url_scanner_table[(guchar)(x)] & (IS_ALPHA|IS_DIGIT|IS_URLSAFE)) != 0)


const gchar              *
url_strerror (enum uri_errno err)
{
	switch (err) {
	case URI_ERRNO_OK:
		return "Parsing went well";
	case URI_ERRNO_EMPTY:
		return "The URI string was empty";
	case URI_ERRNO_INVALID_PROTOCOL:
		return "No protocol was found";
	case URI_ERRNO_NO_SLASHES:
		return "Slashes after protocol missing";
	case URI_ERRNO_TOO_MANY_SLASHES:
		return "Too many slashes after protocol";
	case URI_ERRNO_TRAILING_DOTS:
		return "'.' after host";
	case URI_ERRNO_NO_HOST:
		return "Host part is missing";
	case URI_ERRNO_NO_PORT_COLON:
		return "':' after host without port";
	case URI_ERRNO_NO_HOST_SLASH:
		return "Slash after host missing";
	case URI_ERRNO_IPV6_SECURITY:
		return "IPv6 security bug detected";
	case URI_ERRNO_INVALID_PORT:
		return "Port number is bad";
	case URI_ERRNO_INVALID_PORT_RANGE:
		return "Port number is not within 0-65535";
	}
	return NULL;
}

static inline gint
end_of_dir (gchar c)
{
	return c == POST_CHAR || c == '#' || c == ';' || c == '?';
}

static inline gint
is_uri_dir_sep (struct uri *uri, gchar pos)
{
	return (pos == '/');
}

static gint
check_uri_file (gchar *name)
{
	static const gchar      chars[] = POST_CHAR_S "#?";

	return strcspn (name, chars);
}

static gint
url_init (void)
{
	guint                            i;
	if (url_scanner == NULL) {
		url_scanner = g_malloc (sizeof (struct url_match_scanner));
		url_scanner->matchers = matchers;
		url_scanner->matchers_count = G_N_ELEMENTS (matchers);
		url_scanner->patterns = rspamd_trie_create (TRUE);
		for (i = 0; i < url_scanner->matchers_count; i ++) {
			rspamd_trie_insert (url_scanner->patterns, matchers[i].pattern, i);
		}
	}

	return 0;
}

enum protocol
get_protocol (gchar *name, gint namelen)
{
	/* These are really enum protocol values but can take on negative
	 * values and since 0 <= -1 for enum values it's better to use clean
	 * integer type. */
	gint                            start, end;
	enum protocol                   protocol;
	guchar                          *pname;
	gint                            pnamelen, minlen, compare;

	/* Almost dichotomic search is used here */
	/* Starting at the HTTP entry which is the most common that will make
	 * file and NNTP the next entries checked and amongst the third checks
	 * are proxy and FTP. */
	start = 0;
	end = PROTOCOL_UNKNOWN - 1;
	protocol = PROTOCOL_HTTP;

	while (start <= end) {
		pname = protocol_backends[protocol].name;
		pnamelen = strlen (pname);
		minlen = MIN (pnamelen, namelen);
		compare = g_ascii_strncasecmp (pname, name, minlen);

		if (compare == 0) {
			if (pnamelen == namelen)
				return protocol;

			/* If the current protocol name is longer than the
			 * protocol name being searched for move @end else move
			 * @start. */
			compare = pnamelen > namelen ? 1 : -1;
		}

		if (compare > 0)
			end = protocol - 1;
		else
			start = protocol + 1;

		protocol = (start + end) / 2;
	}

	return PROTOCOL_UNKNOWN;
}


gint
get_protocol_port (enum protocol protocol)
{
	return protocol_backends[protocol].port;
}

gint
get_protocol_need_slashes (enum protocol protocol)
{
	return protocol_backends[protocol].need_slashes;
}

gint
get_protocol_need_slash_after_host (enum protocol protocol)
{
	return protocol_backends[protocol].need_slash_after_host;
}

gint
get_protocol_free_syntax (enum protocol protocol)
{
	return protocol_backends[protocol].free_syntax;
}

static gint
get_protocol_length (const gchar *url)
{
	gchar                          *end = (gchar *)url;

	/* Seek the end of the protocol name if any. */
	/* RFC1738:
	 * scheme  = 1*[ lowalpha | digit | "+" | "-" | "." ]
	 * (but per its recommendations we accept "upalpha" too) */
	while (g_ascii_isalnum (*end) || *end == '+' || *end == '-' || *end == '.')
		end++;

	/* Also return 0 if there's no protocol name (@end == @url). */
	return (*end == ':') ? end - url : 0;
}


/*
 * Calcualte new length of unescaped hostlen
 */
static guint
url_calculate_escaped_hostlen (gchar *host, guint hostlen)
{
	guint                           i, result = hostlen;
	gchar                           *p = host, c;

	for (i = 0; i < hostlen; i++, p++) {
		if (*p == '%' && g_ascii_isxdigit (*(p + 1)) && g_ascii_isxdigit (*(p + 2)) && i < hostlen - 2) {
			c = X2DIGITS_TO_NUM (*(p + 1), *(p + 2));
			if (c != '\0') {
				result -= 2;
			}
		}
	}

	return result;
}

/* URL-unescape the string S.

   This is done by transforming the sequences "%HH" to the character
   represented by the hexadecimal digits HH.  If % is not followed by
   two hexadecimal digits, it is inserted literally.

   The transformation is done in place.  If you need the original
   string intact, make a copy before calling this function.  */

static void
url_unescape (gchar *s)
{
	gchar                           *t = s;	/* t - tortoise */
	gchar                           *h = s;	/* h - hare     */

	for (; *h; h++, t++) {
		if (*h != '%') {
		  copychar:
			*t = *h;
		}
		else {
			gchar                           c;
			/* Do nothing if '%' is not followed by two hex digits. */
			if (!h[1] || !h[2] || !(g_ascii_isxdigit (h[1]) && g_ascii_isxdigit (h[2])))
				goto copychar;
			c = X2DIGITS_TO_NUM (h[1], h[2]);
			/* Don't unescape %00 because there is no way to insert it
			 * into a C string without effectively truncating it. */
			if (c == '\0')
				goto copychar;
			*t = c;
			h += 2;
		}
	}
	*t = '\0';
}

static void
url_strip (gchar *s)
{
	gchar                           *t = s;	/* t - tortoise */
	gchar                           *h = s;	/* h - hare     */

	while (*h) {
		if (g_ascii_isgraph (*h)) {
			*t = *h;
			t++;
		}
		h++;
	}
	*t = '\0';
}

static gchar                    *
url_escape_1 (const gchar *s, gint allow_passthrough, memory_pool_t * pool)
{
	const gchar                     *p1;
	gchar                           *p2, *newstr;
	gint                            newlen;
	gint                            addition = 0;

	for (p1 = s; *p1; p1++)
		if (!is_urlsafe (*p1)) {
			addition += 2;		/* Two more characters (hex digits) */
		}

	if (!addition) {
		if (allow_passthrough) {
			return (gchar *)s;
		}
		else {
			return memory_pool_strdup (pool, s);
		}
	}

	newlen = (p1 - s) + addition;
	newstr = (gchar *)memory_pool_alloc (pool, newlen + 1);

	p1 = s;
	p2 = newstr;
	while (*p1) {
		/* Quote the characters that match the test mask. */
		if (!is_urlsafe (*p1)) {
			guchar                          c = *p1++;
			*p2++ = '%';
			*p2++ = XNUM_TO_DIGIT (c >> 4);
			*p2++ = XNUM_TO_DIGIT (c & 0xf);
		}
		else
			*p2++ = *p1++;
	}
	*p2 = '\0';

	return newstr;
}

/* URL-escape the unsafe characters (see urlchr_table) in a given
   string, returning a freshly allocated string.  */

gchar                           *
url_escape (const gchar *s, memory_pool_t * pool)
{
	return url_escape_1 (s, 0, pool);
}

/* URL-escape the unsafe characters (see urlchr_table) in a given
   string.  If no characters are unsafe, S is returned.  */

static gchar                    *
url_escape_allow_passthrough (const gchar *s, memory_pool_t * pool)
{
	return url_escape_1 (s, 1, pool);
}

/* Decide whether the gchar at position P needs to be encoded.  (It is
   not enough to pass a single gchar *P because the function may need
   to inspect the surrounding context.)

   Return 1 if the gchar should be escaped as %XX, 0 otherwise.  */

static inline gint
char_needs_escaping (const gchar *p)
{
	if (*p == '%') {
		if (g_ascii_isxdigit (*(p + 1)) && g_ascii_isxdigit (*(p + 2)))
			return 0;
		else
			/* Garbled %.. sequence: encode `%'. */
			return 1;
	}
	else if (! is_urlsafe (*p))
		return 1;
	else
		return 0;
}

/* Translate a %-escaped (but possibly non-conformant) input string S
   into a %-escaped (and conformant) output string.  If no characters
   are encoded or decoded, return the same string S; otherwise, return
   a freshly allocated string with the new contents.

   After a URL has been run through this function, the protocols that
   use `%' as the quote character can use the resulting string as-is,
   while those that don't can use url_unescape to get to the intended
   data.  This function is stable: once the input is transformed,
   further transformations of the result yield the same output.
*/

static gchar                    *
reencode_escapes (gchar *s, memory_pool_t * pool)
{
	const gchar                     *p1;
	gchar                           *newstr, *p2;
	gint                            oldlen, newlen;

	gint                            encode_count = 0;

	/* First pass: inspect the string to see if there's anything to do,
	   and to calculate the new length.  */
	for (p1 = s; *p1; p1++)
		if (char_needs_escaping (p1))
			++encode_count;

	if (!encode_count) {
		/* The string is good as it is. */
		return s;
	}

	oldlen = p1 - s;
	/* Each encoding adds two characters (hex digits).  */
	newlen = oldlen + 2 * encode_count;
	newstr = memory_pool_alloc (pool, newlen + 1);

	/* Second pass: copy the string to the destination address, encoding
	   chars when needed.  */
	p1 = s;
	p2 = newstr;

	while (*p1)
		if (char_needs_escaping (p1)) {
			guchar                          c = *p1++;
			*p2++ = '%';
			*p2++ = XNUM_TO_DIGIT (c >> 4);
			*p2++ = XNUM_TO_DIGIT (c & 0xf);
		}
		else {
			*p2++ = *p1++;
		}

	*p2 = '\0';
	return newstr;
}

/* Unescape CHR in an otherwise escaped STR.  Used to selectively
   escaping of certain characters, such as "/" and ":".  Returns a
   count of unescaped chars.  */

static void
unescape_single_char (gchar *str, gchar chr)
{
	const gchar                      c1 = XNUM_TO_DIGIT (chr >> 4);
	const gchar                      c2 = XNUM_TO_DIGIT (chr & 0xf);
	gchar                           *h = str;	/* hare */
	gchar                           *t = str;	/* tortoise */

	for (; *h; h++, t++) {
		if (h[0] == '%' && h[1] == c1 && h[2] == c2) {
			*t = chr;
			h += 2;
		}
		else {
			*t = *h;
		}
	}
	*t = '\0';
}

/* Escape unsafe and reserved characters, except for the slash
	 characters.  */

static gchar                    *
url_escape_dir (const gchar *dir, memory_pool_t * pool)
{
	gchar                           *newdir = url_escape_1 (dir, 1, pool);
	if (newdir == dir)
		return (gchar *)dir;

	unescape_single_char (newdir, '/');
	return newdir;
}

/* Resolve "." and ".." elements of PATH by destructively modifying
   PATH and return non-zero if PATH has been modified, zero otherwise.

   The algorithm is in spirit similar to the one described in rfc1808,
   although implemented differently, in one pass.  To recap, path
   elements containing only "." are removed, and ".." is taken to mean
   "back up one element".  Single leading and trailing slashes are
   preserved.

   For example, "a/b/c/./../d/.." will yield "a/b/".  More exhaustive
   test examples are provided below.  If you change anything in this
   function, run test_path_simplify to make sure you haven't broken a
   test case.  */

static gint
path_simplify (gchar *path)
{
	gchar                           *h = path;	/* hare */
	gchar                           *t = path;	/* tortoise */
	gchar                           *beg = path;	/* boundary for backing the tortoise */
	gchar                           *end = path + strlen (path);

	while (h < end) {
		/* Hare should be at the beginning of a path element. */
		if (h[0] == '.' && (h[1] == '/' || h[1] == '\0')) {
			/* Ignore "./". */
			h += 2;
		}
		else if (h[0] == '.' && h[1] == '.' && (h[2] == '/' || h[2] == '\0')) {
			/* Handle "../" by retreating the tortoise by one path
			   element -- but not past beggining.  */
			if (t > beg) {
				/* Move backwards until T hits the beginning of the
				   previous path element or the beginning of path. */
				for (--t; t > beg && t[-1] != '/'; t--);
			}
			else {
				/* If we're at the beginning, copy the "../" literally
				   move the beginning so a later ".." doesn't remove
				   it.  */
				beg = t + 3;
				goto regular;
			}
			h += 3;
		}
		else {
		  regular:
			/* A regular path element.  If H hasn't advanced past T,
			   simply skip to the next path element.  Otherwise, copy
			   the path element until the next slash.  */
			if (t == h) {
				/* Skip the path element, including the slash.  */
				while (h < end && *h != '/')
					t++, h++;
				if (h < end)
					t++, h++;
			}
			else {
				/* Copy the path element, including the final slash.  */
				while (h < end && *h != '/')
					*t++ = *h++;
				if (h < end)
					*t++ = *h++;
			}
		}
	}

	if (t != h)
		*t = '\0';

	return t != h;
}

enum uri_errno
parse_uri (struct uri *uri, gchar *uristring, memory_pool_t * pool)
{
	guchar                          *prefix_end, *host_end, *p;
	guchar                          *lbracket, *rbracket;
	gint                            datalen, n, addrlen;
	guchar                          *frag_or_post, *user_end, *port_end;

	memset (uri, 0, sizeof (*uri));

	/* Nothing to do for an empty url. */
	if (!*uristring)
		return URI_ERRNO_EMPTY;

	uri->string = reencode_escapes (uristring, pool);
	msg_debug ("reencoding escapes in original url: '%s'", struri (uri));
	uri->protocollen = get_protocol_length (struri (uri));

	/* Assume http as default protocol */
	if (!uri->protocollen || (uri->protocol = get_protocol (struri (uri), uri->protocollen)) == PROTOCOL_UNKNOWN) {
		/* Make exception for numeric urls */
		p = uri->string;
		while (*p && (g_ascii_isalnum (*p) || *p == ':')) {
			p ++;
		}
		if (*p == '\0') {
			return URI_ERRNO_INVALID_PROTOCOL;
		}
		p = g_strconcat ("http://", uri->string, NULL);
		uri->string = memory_pool_strdup (pool, p);
		g_free (p);
		uri->protocol = PROTOCOL_HTTP;
		prefix_end = struri (uri) + 7;
	}
	else {
		/* Figure out whether the protocol is known */
		msg_debug ("getting protocol from url: %d", uri->protocol);

		prefix_end = struri (uri) + uri->protocollen;	/* ':' */

		/* Check if there's a digit after the protocol name. */
		if (g_ascii_isdigit (*prefix_end)) {
			p = struri (uri);
			uri->ip_family = p[uri->protocollen] - '0';
			prefix_end++;
		}
		if (*prefix_end != ':') {
			msg_debug ("invalid protocol in uri");
			return URI_ERRNO_INVALID_PROTOCOL;
		}
		prefix_end++;

		/* Skip slashes */

		if (prefix_end[0] == '/' && prefix_end[1] == '/') {
			if (prefix_end[2] == '/') {
				msg_debug ("too many '/' in uri");
				return URI_ERRNO_TOO_MANY_SLASHES;
			}

			prefix_end += 2;

		}
		else {
			msg_debug ("no '/' in uri");
			return URI_ERRNO_NO_SLASHES;
		}
	}

	if (get_protocol_free_syntax (uri->protocol)) {
		uri->data = prefix_end;
		uri->datalen = strlen (prefix_end);
		return URI_ERRNO_OK;

	}
	else if (uri->protocol == PROTOCOL_FILE) {
		datalen = check_uri_file (prefix_end);
		frag_or_post = prefix_end + datalen;

		/* Extract the fragment part. */
		if (datalen >= 0) {
			if (*frag_or_post == '#') {
				uri->fragment = frag_or_post + 1;
				uri->fragmentlen = strcspn (uri->fragment, POST_CHAR_S);
				frag_or_post = uri->fragment + uri->fragmentlen;
			}
			if (*frag_or_post == POST_CHAR) {
				uri->post = frag_or_post + 1;
			}
		}
		else {
			datalen = strlen (prefix_end);
		}

		uri->data = prefix_end;
		uri->datalen = datalen;

		return URI_ERRNO_OK;
	}

	/* Isolate host */

	/* Get brackets enclosing IPv6 address */
	lbracket = strchr (prefix_end, '[');
	if (lbracket) {
		rbracket = strchr (lbracket, ']');
		/* [address] is handled only inside of hostname part (surprisingly). */
		if (rbracket && rbracket < prefix_end + strcspn (prefix_end, "/"))
			uri->ipv6 = 1;
		else
			lbracket = rbracket = NULL;
	}
	else {
		rbracket = NULL;
	}

	/* Possibly skip auth part */
	host_end = prefix_end + strcspn (prefix_end, "@");

	if (prefix_end + strcspn (prefix_end, "/?") > host_end && *host_end) {	/* we have auth info here */

		/* Allow '@' in the password component */
		while (strcspn (host_end + 1, "@") < strcspn (host_end + 1, "/?"))
			host_end = host_end + 1 + strcspn (host_end + 1, "@");

		user_end = strchr (prefix_end, ':');

		if (!user_end || user_end > host_end) {
			uri->user = prefix_end;
			uri->userlen = host_end - prefix_end;
		}
		else {
			uri->user = prefix_end;
			uri->userlen = user_end - prefix_end;
			uri->password = user_end + 1;
			uri->passwordlen = host_end - user_end - 1;
		}
		prefix_end = host_end + 1;
	}

	if (uri->ipv6 && rbracket != NULL) {
		host_end = rbracket + strcspn (rbracket, ":/?");
	}
	else {
		host_end = prefix_end + strcspn (prefix_end, ":/?");
	}

	if (uri->ipv6) {
		addrlen = rbracket - lbracket - 1;


		uri->host = lbracket + 1;
		uri->hostlen = addrlen;
	}
	else {
		uri->host = prefix_end;
		uri->hostlen = host_end - prefix_end;

		/* Trim trailing '.'s */
		if (uri->hostlen && uri->host[uri->hostlen - 1] == '.')
			return URI_ERRNO_TRAILING_DOTS;
	}

	if (*host_end == ':') {		/* we have port here */
		port_end = host_end + 1 + strcspn (host_end + 1, "/");

		host_end++;

		uri->port = host_end;
		uri->portlen = port_end - host_end;

		if (uri->portlen == 0)
			return URI_ERRNO_NO_PORT_COLON;

		/* We only use 8 bits for portlen so better check */
		if ((gint)uri->portlen != port_end - host_end)
			return URI_ERRNO_INVALID_PORT;

		/* test if port is number */
		for (; host_end < port_end; host_end++)
			if (!g_ascii_isdigit (*host_end))
				return URI_ERRNO_INVALID_PORT;

		/* Check valid port value, and let show an error message
		 * about invalid url syntax. */
		if (uri->port && uri->portlen) {

			errno = 0;
			n = strtol (uri->port, NULL, 10);
			if (errno || !uri_port_is_valid (n))
				return URI_ERRNO_INVALID_PORT;
		}
	}

	if (*host_end == '/') {
		host_end++;

	}
	else if (get_protocol_need_slash_after_host (uri->protocol) && *host_end != '?') {
		/* The need for slash after the host component depends on the
		 * need for a host component. -- The dangerous mind of Jonah */
		if (!uri->hostlen)
			return URI_ERRNO_NO_HOST;

		return URI_ERRNO_NO_HOST_SLASH;
	}

	/* Look for #fragment or POST_CHAR */
	prefix_end = host_end + strcspn (host_end, "#" POST_CHAR_S);
	uri->data = host_end;
	uri->datalen = prefix_end - host_end;

	if (*prefix_end == '#') {
		uri->fragment = prefix_end + 1;
		uri->fragmentlen = strcspn (uri->fragment, POST_CHAR_S);
		prefix_end = uri->fragment + uri->fragmentlen;
	}

	if (*prefix_end == POST_CHAR) {
		uri->post = prefix_end + 1;
	}

	convert_to_lowercase (uri->string, uri->protocollen);
	convert_to_lowercase (uri->host, uri->hostlen);
	/* Decode %HH sequences in host name.  This is important not so much
	   to support %HH sequences in host names (which other browser
	   don't), but to support binary characters (which will have been
	   converted to %HH by reencode_escapes).  */
	if (strchr (uri->host, '%')) {
		uri->hostlen = url_calculate_escaped_hostlen (uri->host, uri->hostlen);
	}

	url_strip (struri (uri));
	url_unescape (uri->host);

	path_simplify (uri->data);

	return URI_ERRNO_OK;
}

static const gchar url_braces[] = {
	 '(', ')' ,
	 '{', '}' ,
	 '[', ']' ,
	 '<', '>' ,
	 '|', '|' ,
	 '\'', '\''
};

static gboolean
is_open_brace (gchar c)
{
	if (c == '(' ||
		c == '{' ||
		c == '[' ||
		c == '<' ||
		c == '|' ||
		c == '\'') {
		return TRUE;
	}

	return FALSE;
}

static gboolean
url_file_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	match->m_begin = pos;
	return TRUE;
}
static gboolean
url_file_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	const gchar                    *p;
	gchar                           stop;
	guint                           i;

	p = pos + strlen (match->pattern);
	stop = *p;
	if (*p == '/') {
		p ++;
	}

	for (i = 0; i < G_N_ELEMENTS (url_braces) / 2; i += 2) {
		if (*p == url_braces[i]) {
			stop = url_braces[i + 1];
			break;
		}
	}

	while (p < end && *p != stop && is_urlsafe (*p)) {
		p ++;
	}

	if (p == begin) {
		return FALSE;
	}
	match->m_len = p - match->m_begin;

	return TRUE;

}

static gboolean
url_tld_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	const gchar						*p = pos;

	/* Try to find the start of the url by finding any non-urlsafe character or whitespace/punctuation */
	while (p >= begin) {
		if ((!is_domain (*p) && *p != '.') || g_ascii_isspace (*p)) {
			p ++;
			if (*p == '.') {
				/* Urls cannot start with . */
				return FALSE;
			}
			match->m_begin = p;
			return TRUE;
		}
		p --;
	}

	return FALSE;
}

static gboolean
url_tld_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	const gchar						*p;

	/* A url must be finished by tld, so it must be followed by punctuation or by space character */
	p = pos + strlen (match->pattern);
	if (p == end || g_ascii_isspace (*(p + 1)) || g_ascii_ispunct (*(p + 1))) {
		match->m_len = p - match->m_begin;
		return TRUE;
	}
	else if (*(p + 1) == '/' || *(p + 1) == ':') {
		/* Parse arguments, ports by normal way by url default function */
		p = match->m_begin;
		/* Check common prefix */
		if (g_ascii_strncasecmp (p, "http://", sizeof ("http://") - 1) == 0) {
			return url_web_end (begin, end, match->m_begin + sizeof ("http://") - 1, match);
		}
		else {
			return url_web_end (begin, end, match->m_begin, match);
		}

	}
	return FALSE;
}

static gboolean
url_web_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	/* Check what we have found */
	if (pos > begin && *pos == 'w' && *(pos + 1) == 'w' && *(pos + 2) == 'w') {
		if (!is_open_brace (*(pos - 1)) && !g_ascii_isspace (*(pos - 1))) {
			return FALSE;
		}
	}
	if (*pos == '.') {
		/* Urls cannot start with . */
		return FALSE;
	}
	match->m_begin = pos;

	return TRUE;
}

static gboolean
url_web_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	const gchar                    *p, *c;
	gchar                           open_brace = '\0', close_brace = '\0';
	gint                            brace_stack = 0;
	gboolean                        passwd = FALSE;
	guint                           port, i;

	p = pos + strlen (match->pattern);
	for (i = 0; i < G_N_ELEMENTS (url_braces) / 2; i += 2) {
		if (*p == url_braces[i]) {
			close_brace = url_braces[i + 1];
			open_brace = *p;
			break;
		}
	}

	/* find the end of the domain */
	if (is_atom (*p)) {
		/* might be a domain or user@domain */
		c = p;
		while (p < end) {
			if (!is_atom (*p)) {
				break;
			}

			p++;

			while (p < end && is_atom (*p)) {
				p++;
			}

			if ((p + 1) < end && *p == '.' && (is_atom (*(p + 1)) || *(p + 1) == '/')) {
				p++;
			}
		}

		if (*p != '@') {
			p = c;
		}
		else {
			p++;
		}

		goto domain;
	}
	else if (is_domain (*p) || (*p & 0x80)) {
domain:
		while (p < end) {
			if (!is_domain (*p) && !(*p & 0x80)) {
				break;
			}

			p++;

			while (p < end && (is_domain (*p) || (*p & 0x80))) {
				p++;
			}

			if ((p + 1) < end && *p == '.' && (is_domain (*(p + 1)) || *(p + 1) == '/' || (*(p + 1) & 0x80))) {
				p++;
			}
		}
	}
	else {
		return FALSE;
	}

	if (p < end) {
		switch (*p) {
		case ':': /* we either have a port or a password */
			p++;

			if (is_digit (*p) || passwd) {
				port = (*p++ - '0');

				while (p < end && is_digit (*p) && port < 65536) {
					port = (port * 10) + (*p++ - '0');
				}

				if (!passwd && (port >= 65536 || *p == '@')) {
					if (p < end) {
						/* this must be a password? */
						goto passwd;
					}

					p--;
				}
			}
			else {
				passwd:
				passwd = TRUE;
				c = p;

				while (p < end && is_atom (*p)) {
					p++;
				}

				if ((p + 2) < end) {
					if (*p == '@') {
						p++;
						if (is_domain (*p)) {
							goto domain;
						}
					}

					return FALSE;
				}
			}

			if (p >= end || *p != '/') {
				break;
			}

			/* we have a '/' so there could be a path - fall through */
		case '/': /* we've detected a path component to our url */
			p++;
		case '?':
			while (p < end && is_urlsafe (*p)) {
				if (*p == open_brace) {
					brace_stack++;
				}
				else if (*p == close_brace) {
					brace_stack--;
					if (brace_stack == -1) {
						break;
					}
				}
				p++;
			}

			break;
		default:
			break;
		}
	}

	/* urls are extremely unlikely to end with any
	 * punctuation, so strip any trailing
	 * punctuation off. Also strip off any closing
	 * double-quotes. */
	while (p > pos && strchr (",.:;?!-|}])\"", p[-1])) {
		p--;
	}

	match->m_len = (p - pos);

	return TRUE;
}


static gboolean
url_email_start (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	const gchar                    *p;
	/* Check what we have found */
	if (pos > begin && *pos == '@') {
		/* Try to extract it with username */
		p = pos - 1;
		while (p > begin && (is_domain (*p) || *p == '.' || *p == '_')) {
			p --;
		}
		if (!is_domain (*p)) {
			match->m_begin = p + 1;
			return TRUE;
		}
		else if (p == begin) {
			match->m_begin = p;
			return TRUE;
		}
	}
	else {
		p = pos + strlen (match->pattern);
		if (is_domain (*p)) {
			match->m_begin = p;
			return TRUE;
		}
	}
	return FALSE;
}

static gboolean
url_email_end (const gchar *begin, const gchar *end, const gchar *pos, url_match_t *match)
{
	const gchar                    *p;

	p = pos + strlen (match->pattern);

	while (p < end && (is_domain (*p) || *p == '_' || (*p == '.' && p + 1 < end && is_domain (*(p + 1))))) {
		p ++;
	}
	match->m_len = p - match->m_begin;
	match->add_prefix = TRUE;
	return TRUE;
}

void
url_parse_text (memory_pool_t * pool, struct worker_task *task, struct mime_text_part *part, gboolean is_html)
{
	gint                            rc;
	gchar                          *url_str = NULL, *url_start, *url_end;
	struct uri                     *new;
	struct process_exception       *ex;
	gchar                          *p, *end, *begin;


	if (!part->orig->data || part->orig->len == 0) {
		msg_warn ("got empty text part");
		return;
	}

	if (url_init () == 0) {
		if (is_html) {
			begin = part->orig->data;
			end = begin + part->orig->len;
			p = begin;
		}
		else {
			begin = part->content->data;
			end = begin + part->content->len;
			p = begin;
		}
		while (p < end) {
			if (url_try_text (pool, p, end - p, &url_start, &url_end, &url_str, is_html)) {
				if (url_str != NULL) {
					new = memory_pool_alloc0 (pool, sizeof (struct uri));
					ex = memory_pool_alloc0 (pool, sizeof (struct process_exception));
					if (new != NULL) {
						g_strstrip (url_str);
						rc = parse_uri (new, url_str, pool);
						if ((rc == URI_ERRNO_OK || rc == URI_ERRNO_NO_SLASHES || rc == URI_ERRNO_NO_HOST_SLASH) &&
								new->hostlen > 0) {
							ex->pos = url_start - begin;
							ex->len = url_end - url_start;
							if (new->protocol == PROTOCOL_MAILTO) {
								if (new->userlen > 0) {
									if (!g_tree_lookup (task->emails, new)) {
										g_tree_insert (task->emails, new, new);
									}
								}
							}
							else {
								if (!g_tree_lookup (task->urls, new)) {
									g_tree_insert (task->urls, new, new);
								}
							}
							part->urls_offset = g_list_prepend (part->urls_offset, ex);
						}
						else if (rc != URI_ERRNO_OK) {
							msg_info ("extract of url '%s' failed: %s", url_str, url_strerror (rc));
						}
					}
				}
			}
			else {
				break;
			}
			p = url_end + 1;
		}
	}
	/* Handle offsets of this part */
	if (part->urls_offset != NULL) {
		part->urls_offset = g_list_reverse (part->urls_offset);
		memory_pool_add_destructor (task->task_pool, (pool_destruct_func)g_list_free, part->urls_offset);
	}
}

gboolean
url_try_text (memory_pool_t *pool, const gchar *begin, gsize len, gchar **start, gchar **fin, gchar **url_str, gboolean is_html)
{
	const gchar                    *end, *pos;
	gint                            idx, l;
	struct url_matcher             *matcher;
	url_match_t                     m;

	end = begin + len;
	if (url_init () == 0) {
		if ((pos = rspamd_trie_lookup (url_scanner->patterns, begin, len, &idx)) == NULL) {
			return FALSE;
		}
		else {
			matcher = &matchers[idx];
			if ((matcher->flags & URL_FLAG_NOHTML) && is_html) {
				/* Do not try to match non-html like urls in html texts */
				return FALSE;
			}
			m.pattern = matcher->pattern;
			m.prefix = matcher->prefix;
			m.add_prefix = FALSE;
			if (matcher->start (begin, end, pos, &m) && matcher->end (begin, end, pos, &m)) {
				if (m.add_prefix) {
					l = m.m_len + 1 + strlen (m.prefix);
					*url_str = memory_pool_alloc (pool, l);
					rspamd_snprintf (*url_str, l, "%s%*s", m.prefix, m.m_len, m.m_begin);
				}
				else {
					*url_str = memory_pool_alloc (pool, m.m_len + 1);
					memcpy (*url_str, m.m_begin, m.m_len);
					(*url_str)[m.m_len] = '\0';
				}
				if (start != NULL) {
					*start = (gchar *)m.m_begin;
				}
				if (fin != NULL) {
					*fin = (gchar *)m.m_begin + m.m_len;
				}
			}
			else {
				*url_str = NULL;
				if (start != NULL) {
					*start = (gchar *)pos;
				}
				if (fin != NULL) {
					*fin = (gchar *)pos + strlen (m.prefix);
				}
			}

			return TRUE;
		}
	}

	return FALSE;
}

/*
 * vi: ts=4
 */