summaryrefslogtreecommitdiffstats
path: root/kviewshell/plugins/djvu/libdjvu/GURL.cpp
blob: 812f1d22a5dd8a7b167600f81af1055a8f039020 (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
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002  Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001  AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, Version 2. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//C- GNU General Public License for more details.
//C- 
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library
//C- distributed by Lizardtech Software.  On July 19th 2002, Lizardtech 
//C- Software authorized us to replace the original DjVu(r) Reference 
//C- Library notice by the following text (see doc/lizard2002.djvu):
//C-
//C-  ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, Version 2. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE."  Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free, 
//C- | non-exclusive license to make, use, sell, or otherwise dispose of 
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the 
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU 
//C- | General Public License.   This grant only confers the right to 
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to 
//C- | the extent such infringement is reasonably necessary to enable 
//C- | recipient to make, have made, practice, sell, or otherwise dispose 
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to 
//C- | any greater extent that may be necessary to utilize further 
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
// 
// $Id: GURL.cpp,v 1.19 2005/04/27 16:34:13 leonb Exp $
// $Name: release_3_5_15 $

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma implementation
#endif

// From: Leon Bottou, 1/31/2002
// This has been heavily changed by Lizardtech.
// They decided to use URLs for everyting, including
// the most basic file access.  The URL class now is a unholy 
// mixture of code for syntactically parsing the urls (which it was)
// and file status code (only for local file: urls).

#include "GException.h"
#include "GOS.h"
#include "GURL.h"
#include "debug.h"

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>

#ifdef WIN32
# include <atlbase.h>
# include <windows.h>
# include <direct.h>
#endif /* WIN32 */

// -- MAXPATHLEN
#ifndef MAXPATHLEN
# ifdef _MAX_PATH
#  define MAXPATHLEN _MAX_PATH
# else
#  define MAXPATHLEN 1024
# endif
#else
# if ( MAXPATHLEN < 1024 )
#  undef MAXPATHLEN
#  define MAXPATHLEN 1024
# endif
#endif

#if defined(UNIX) || defined(OS2)
# include <unistd.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <errno.h>
# include <fcntl.h>
# include <pwd.h>
# include <stdio.h>
# ifdef AUTOCONF
#  ifdef TIME_WITH_SYS_TIME
#   include <sys/time.h>
#   include <time.h>
#  else
#   ifdef HAVE_SYS_TIME_H
#    include <sys/time.h>
#   else
#    include <time.h>
#   endif
#  endif
#  ifdef HAVE_DIRENT_H
#   include <dirent.h>
#   define NAMLEN(dirent) strlen((dirent)->d_name)
#  else
#   define dirent direct
#   define NAMLEN(dirent) (dirent)->d_namlen
#   ifdef HAVE_SYS_NDIR_H
#    include <sys/ndir.h>
#   endif
#   ifdef HAVE_SYS_DIR_H
#    include <sys/dir.h>
#   endif
#   ifdef HAVE_NDIR_H
#    include <ndir.h>
#   endif
#  endif
# else /* !AUTOCONF */ 
#  include <sys/time.h>
#  if defined(XENIX)
#   define USE_DIRECT
#   include <sys/ndir.h>
#  elif defined(OLDBSD)
#   define USE_DIRECT
#   include <sys/dir.h>
#  endif
#  ifdef USE_DIRECT
#   define dirent direct
#   define NAMLEN(dirent) (dirent)->d_namlen
#  else
#   include <dirent.h>
#   define NAMLEN(dirent) strlen((dirent)->d_name)
#  endif 
# endif /* !AUTOCONF */
#endif /* UNIX */

#ifdef macintosh
#include <unix.h>
#include <errno.h>
#include <unistd.h>
#endif


#ifdef HAVE_NAMESPACES
namespace DJVU {
# ifdef NOT_DEFINED // Just to fool emacs c++ mode
}
#endif
#endif


static const char djvuopts[]="DJVUOPTS";
static const char localhost[]="file://localhost/";
static const char backslash='\\';  
static const char colon=':';
static const char dot='.';
static const char filespecslashes[] = "file://";
static const char filespec[] = "file:";
static const char slash='/';
static const char percent='%';
static const char localhostspec1[] = "//localhost/";
static const char localhostspec2[] = "///";
static const char nillchar=0;
#if defined(UNIX)
  static const char tilde='~';
  static const char root[] = "/";
#elif defined(WIN32) || defined(OS2)
  static const char root[] = "\\";
#elif defined(macintosh)
  static char const * const root = &nillchar; 
#else
#error "Define something here for your operating system"
#endif


static const int
pathname_start(const GUTF8String &url, const int protolength);

// hexval --
// -- Returns the hexvalue of a character.
//    Returns -1 if illegal;

static int 
hexval(char c)
{
  return ((c>='0' && c<='9')
    ?(c-'0')
    :((c>='A' && c<='F')
      ?(c-'A'+10)
      :((c>='a' && c<='f')
        ?(c-'a'+10):(-1))));
}


static bool
is_argument(const char * start)
      // Returns TRUE if 'start' points to the beginning of an argument
      // (either hash or CGI)
{
   // return (*start=='#' || *start=='?' || *start=='&' || *start==';');
   return (*start=='#' || *start=='?' );
}

static bool
is_argument_sep(const char * start)
      // Returns TRUE if 'start' points to the beginning of an argument
      // (either hash or CGI)
{
   return (*start=='&')||(*start == ';');
}

void
GURL::convert_slashes(void)
{
   GUTF8String xurl(get_string());
#if defined(WIN32)
   const int protocol_length=protocol(xurl).length();
   for(char *ptr=(xurl.getbuf()+protocol_length);*ptr;ptr++)
     if(*ptr == backslash)
       *ptr=slash;
   url=xurl;
#endif
}

static void
collapse(char * ptr, const int chars)
      // Will remove the first 'chars' chars from the string and
      // move the rest toward the beginning. Will take into account
      // string length
{
   const int length=strlen(ptr);
   const char *srcptr=ptr+((chars>length)?length:chars);
   while((*(ptr++) = *(srcptr++)))
     EMPTY_LOOP;
}

GUTF8String
GURL::beautify_path(GUTF8String xurl)
{

  const int protocol_length=GURL::protocol(xurl).length();
   
  // Eats parts like ./ or ../ or ///
  char * buffer;
  GPBuffer<char> gbuffer(buffer,xurl.length()+1);
  strcpy(buffer, (const char *)xurl);
   
  // Find start point
  char * start=buffer+pathname_start(xurl,protocol_length);

  // Find end of the url (don't touch arguments)
  char * ptr;
  GUTF8String args;
  for(ptr=start;*ptr;ptr++)
  {
    if (is_argument(ptr))
    {
      args=ptr;
      *ptr=0;
      break;
    }
  }

  // Eat multiple slashes
  for(;(ptr=strstr(start, "////"));collapse(ptr, 3))
    EMPTY_LOOP;
  for(;(ptr=strstr(start, "//"));collapse(ptr, 1))
    EMPTY_LOOP;
  // Convert /./ stuff into plain /
  for(;(ptr=strstr(start, "/./"));collapse(ptr, 2))
    EMPTY_LOOP;
#if defined(WIN32) || defined(OS2)
  if(!xurl.cmp(filespec,sizeof(filespec)-1))
  {
	int offset=1;
	if(start&&(start[0] == '/')&& 
           !xurl.cmp("file:////",sizeof("file:////")-1))
	{
	  collapse(start, 1);
	  offset=0;
	}
    for(ptr=start+offset;(ptr=strchr(ptr, '/'));)
	{
	  if(isalpha((++ptr)[0]))
	  {
	    if((ptr[1] == ':')&&(ptr[2]=='/'))
		{
		  char *buffer2;
                  GPBuffer<char> gbuffer2(buffer2,strlen(ptr)+1);
		  strcpy(buffer2,ptr);
		  gbuffer.resize(strlen(ptr)+sizeof(localhost));
		  strcpy(buffer,localhost);
		  strcat(buffer,buffer2);
		  ptr=(start=buffer+sizeof(localhost))+1;
		}
	  }
	}
  }
#endif
  // Process /../
  while((ptr=strstr(start, "/../")))
  {
    for(char * ptr1=ptr-1;(ptr1>=start);ptr1--)
    {
      if (*ptr1==slash)
      {
        collapse(ptr1, ptr-ptr1+3);
        break;
      }
    }
  }

  // Remove trailing /.
  ptr=start+strlen(start)-2;
  if((ptr>=start)&& (ptr == GUTF8String("/.")))
  {
    ptr[1]=0;
  }
  // Eat trailing /..
  ptr=start+strlen(start)-3;
  if((ptr >= start) && (ptr == GUTF8String("/..")))
  {
    for(char * ptr1=ptr-1;(ptr1>=start);ptr1--)
    {
      if (*ptr1==slash)
      {
        ptr1[1]=0;
        break;
      }
    }
  }

  // Done. Copy the buffer back into the URL and add arguments.
  xurl=buffer;
  return (xurl+args);
}


void
GURL::beautify_path(void)
{
  url=beautify_path(get_string());
}

void
GURL::init(const bool nothrow)
{
   GCriticalSectionLock lock(&class_lock);
   validurl=true;
   
   if (url.length())
   {
      GUTF8String proto=protocol();
      if (proto.length()<2)
      {
        validurl=false;
        if(!nothrow)
          G_THROW( ERR_MSG("GURL.no_protocol") "\t"+url);
        return;
      }

         // Below we have to make this complex test to detect URLs really
         // referring to *local* files. Surprisingly, file://hostname/dir/file
         // is also valid, but shouldn't be treated thru local FS.
      if (proto=="file" && url[5]==slash &&
          (url[6]!=slash || !url.cmp(localhost, sizeof(localhost))))
      {
            // Separate the arguments
         GUTF8String arg;
         {
           const char * const url_ptr=url;
           const char * ptr;
           for(ptr=url_ptr;*ptr&&!is_argument(ptr);ptr++)
           		EMPTY_LOOP;
           arg=ptr;
           url=url.substr(0,(size_t)ptr-(size_t)url_ptr);
         }

            // Do double conversion
         GUTF8String tmp=UTF8Filename();
         if (!tmp.length())
         {
           validurl=false;
           if(!nothrow)
             G_THROW( ERR_MSG("GURL.fail_to_file") );
           return;
         }
         url=GURL::Filename::UTF8(tmp).get_string();
         if (!url.length())
         {
           validurl=false;
           if(!nothrow)
             G_THROW( ERR_MSG("GURL.fail_to_URL") );
           return;
         }
            // Return the argument back
         url+=arg;
      }
      convert_slashes();
      beautify_path();
      parse_cgi_args();
   }
}

GURL::GURL(void) 
  : validurl(false) 
{
}

GURL::GURL(const char * url_in) 
  : url(url_in ? url_in : ""), validurl(false)
{
}

GURL::GURL(const GUTF8String & url_in)
  : url(url_in), validurl(false)
{
}

GURL::GURL(const GNativeString & url_in)
  : url(url_in.getNative2UTF8()), validurl(false)
{
#if defined(WIN32) || defined(OS2)
  if(is_valid() && is_local_file_url())
  {
    GURL::Filename::UTF8 xurl(UTF8Filename());
    url=xurl.get_string(true);
    validurl=false;
  }
#endif
}

GURL::GURL(const GURL & url_in)
  : validurl(false)
{
  if(url_in.is_valid())
  {
    url=url_in.get_string();
    init();
  }else
  {
    url=url_in.url;
  }
}

GURL &
GURL::operator=(const GURL & url_in)
{
   GCriticalSectionLock lock(&class_lock);
   if(url_in.is_valid())
   {
     url=url_in.get_string();
     init(true);
   }else
   {
     url=url_in.url;
     validurl=false;
   }
   return *this;
}

GUTF8String
GURL::protocol(const GUTF8String& url)
{
   const char * const url_ptr=url;
   const char * ptr=url_ptr;
   for(char c=*ptr;
     c && (isalnum(c) || c == '+' || c == '-' || c == '.');
     c=*(++ptr)) EMPTY_LOOP;
   return(*ptr==colon)?GUTF8String(url_ptr, ptr-url_ptr):GUTF8String();
}

GUTF8String
GURL::hash_argument(void) const
      // Returns the HASH argument (anything after '#' and before '?')
{
   const GUTF8String xurl(get_string());

   bool found=false;
   GUTF8String arg;

         // Break if CGI argument is found
   for(const char * start=xurl;*start&&(*start!='?');start++)
   {
      if (found)
      {
         arg+=*start;
      }else
      {
         found=(*start=='#');
      }
   }
   return decode_reserved(arg);
}

void
GURL::set_hash_argument(const GUTF8String &arg)
{
   const GUTF8String xurl(get_string());

   GUTF8String new_url;
   bool found=false;
   const char * ptr;
   for(ptr=xurl;*ptr;ptr++)
   {
      if (is_argument(ptr))
      {
         if (*ptr!='#')
         {
           break;
         }
         found=true;
      } else if (!found)
      {
         new_url+=*ptr;
      }
   }

   url=new_url+"#"+GURL::encode_reserved(arg)+ptr;
}

void
GURL::parse_cgi_args(void)
      // Will read CGI arguments from the URL into
      // cgi_name_arr and cgi_value_arr
{
   if(!validurl)
     init();
   GCriticalSectionLock lock1(&class_lock);
   cgi_name_arr.empty();
   cgi_value_arr.empty();

      // Search for the beginning of CGI arguments
   const char * start=url;
   while(*start)
   {
     if(*(start++)=='?')
     {
       break;
     }
   }

      // Now loop until we see all of them
   while(*start)
   {
      GUTF8String arg;        // Storage for another argument
      while(*start)        // Seek for the end of it
      {
         if (is_argument_sep(start))
         {
            start++;
            break;
         } else
         {
           arg+=*start++;
         }
      }
      if (arg.length())
      {
            // Got argument in 'arg'. Split it into 'name' and 'value'
         const char * ptr;
         const char * const arg_ptr=arg;
	 for(ptr=arg_ptr;*ptr&&(*ptr != '=');ptr++)
	   EMPTY_LOOP;

         GUTF8String name, value;
         if (*ptr)
         {
            name=GUTF8String(arg_ptr, (int)((ptr++)-arg_ptr));
            value=GUTF8String(ptr, arg.length()-name.length()-1);
         } else
         {
           name=arg;
         }
            
         int args=cgi_name_arr.size();
         cgi_name_arr.resize(args);
         cgi_value_arr.resize(args);
         cgi_name_arr[args]=decode_reserved(name);
         cgi_value_arr[args]=decode_reserved(value);
      }
   }
}

void
GURL::store_cgi_args(void)
      // Will store CGI arguments from the cgi_name_arr and cgi_value_arr
      // back into the URL
{
   if(!validurl)
     init();
   GCriticalSectionLock lock1(&class_lock);

   const char * const url_ptr=url;
   const char * ptr;
   for(ptr=url_ptr;*ptr&&(*ptr!='?');ptr++)
   		EMPTY_LOOP;
   
   GUTF8String new_url(url_ptr, ptr-url_ptr);
   
   for(int i=0;i<cgi_name_arr.size();i++)
   {
      GUTF8String name=GURL::encode_reserved(cgi_name_arr[i]);
      GUTF8String value=GURL::encode_reserved(cgi_value_arr[i]);
      new_url+=(i?"&":"?")+name;
      if (value.length())
         new_url+="="+value;
   }

   url=new_url;
}

int
GURL::cgi_arguments(void) const
{
   if(!validurl)
      const_cast<GURL *>(this)->init();
   return cgi_name_arr.size();
}

int
GURL::djvu_cgi_arguments(void) const
{
   if(!validurl)
     const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);

   int args=0;
   for(int i=0;i<cgi_name_arr.size();i++)
   {
      if (cgi_name_arr[i].upcase()==djvuopts)
      {
         args=cgi_name_arr.size()-(i+1);
         break;
      }
   } 
   return args;
}

GUTF8String
GURL::cgi_name(int num) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);
   return (num<cgi_name_arr.size())?cgi_name_arr[num]:GUTF8String();
}

GUTF8String
GURL::djvu_cgi_name(int num) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);

   GUTF8String arg;
   for(int i=0;i<cgi_name_arr.size();i++)
      if (cgi_name_arr[i].upcase()==djvuopts)
      {
         for(i++;i<cgi_name_arr.size();i++)
            if (! num--)
            {
               arg=cgi_name_arr[i];
               break;
            }
         break;
      }
   return arg;
}

GUTF8String
GURL::cgi_value(int num) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);
   return (num<cgi_value_arr.size())?cgi_value_arr[num]:GUTF8String();
}

GUTF8String
GURL::djvu_cgi_value(int num) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);

   GUTF8String arg;
   for(int i=0;i<cgi_name_arr.size();i++)
   {
      if (cgi_name_arr[i].upcase()==djvuopts)
      {
         for(i++;i<cgi_name_arr.size();i++)
         {
            if (! num--)
            {
               arg=cgi_value_arr[i];
               break;
            }
         }
         break;
      }
   }
   return arg;
}

DArray<GUTF8String>
GURL::cgi_names(void) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);
   return cgi_name_arr;
}

DArray<GUTF8String>
GURL::cgi_values(void) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);
   return cgi_value_arr;
}

DArray<GUTF8String>
GURL::djvu_cgi_names(void) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);

   int i;
   DArray<GUTF8String> arr;
   for(i=0;(i<cgi_name_arr.size())&&
     (cgi_name_arr[i].upcase()!=djvuopts)
     ;i++)
     	EMPTY_LOOP;

   int size=cgi_name_arr.size()-(i+1);
   if (size>0)
   {
      arr.resize(size-1);
      for(i=0;i<arr.size();i++)
         arr[i]=cgi_name_arr[cgi_name_arr.size()-arr.size()+i];
   }

   return arr;
}

DArray<GUTF8String>
GURL::djvu_cgi_values(void) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);

   int i;
   DArray<GUTF8String> arr;
   for(i=0;i<cgi_name_arr.size()&&(cgi_name_arr[i].upcase()!=djvuopts);i++)
   		EMPTY_LOOP;

   int size=cgi_name_arr.size()-(i+1);
   if (size>0)
   {
      arr.resize(size-1);
      for(i=0;i<arr.size();i++)
         arr[i]=cgi_value_arr[cgi_value_arr.size()-arr.size()+i];
   }

   return arr;
}

void
GURL::clear_all_arguments(void)
{
   clear_hash_argument();
   clear_cgi_arguments();
}

void
GURL::clear_hash_argument(void)
      // Clear anything after first '#' and before the following '?'
{
   if(!validurl) init();
   GCriticalSectionLock lock(&class_lock);
   bool found=false;
   GUTF8String new_url;
   for(const char * start=url;*start;start++)
   {
         // Break on first CGI arg.
      if (*start=='?')
      {
         new_url+=start;
         break;
      }

      if (!found)
      { 
        if (*start=='#')
          found=true;
        else
          new_url+=*start;
      }
   }
   url=new_url;
}

void
GURL::clear_cgi_arguments(void)
{
   if(!validurl)
     init();
   GCriticalSectionLock lock1(&class_lock);

      // Clear the arrays
   cgi_name_arr.empty();
   cgi_value_arr.empty();

      // And clear everything past the '?' sign in the URL
   for(const char * ptr=url;*ptr;ptr++)
      if (*ptr=='?')
      {
         url.setat(ptr-url, 0);
         break;
      }
}

void
GURL::clear_djvu_cgi_arguments(void)
{
   if(!validurl) init();
      // First - modify the arrays
   GCriticalSectionLock lock(&class_lock);
   for(int i=0;i<cgi_name_arr.size();i++)
   {
      if (cgi_name_arr[i].upcase()==djvuopts)
      {
         cgi_name_arr.resize(i-1);
         cgi_value_arr.resize(i-1);
         break;
      }
   }

      // And store them back into the URL
   store_cgi_args();
}

void
GURL::add_djvu_cgi_argument(const GUTF8String &name, const char * value)
{
   if(!validurl)
     init();
   GCriticalSectionLock lock1(&class_lock);

      // Check if we already have the "DJVUOPTS" argument
   bool have_djvuopts=false;
   for(int i=0;i<cgi_name_arr.size();i++)
   {
      if (cgi_name_arr[i].upcase()==djvuopts)
      {
         have_djvuopts=true;
         break;
      }
   }

      // If there is no DJVUOPTS, insert it
   if (!have_djvuopts)
   {
      int pos=cgi_name_arr.size();
      cgi_name_arr.resize(pos);
      cgi_value_arr.resize(pos);
      cgi_name_arr[pos]=djvuopts;
   }

      // Add new argument to the array
   int pos=cgi_name_arr.size();
   cgi_name_arr.resize(pos);
   cgi_value_arr.resize(pos);
   cgi_name_arr[pos]=name;
   cgi_value_arr[pos]=value;

      // And update the URL
   store_cgi_args();
}

bool
GURL::is_local_file_url(void) const
{
   if(!validurl) const_cast<GURL *>(this)->init();
   GCriticalSectionLock lock((GCriticalSection *) &class_lock);
   return (protocol()=="file" && url[5]==slash);
}

static const int
pathname_start(const GUTF8String &url, const int protolength)
{
  const int length=url.length();
  int retval=0;
  if(protolength+1<length)
  {
    retval=url.search(slash,((url[protolength+1] == '/')
      ?((url[protolength+2] == '/')?(protolength+3):(protolength+2))
      :(protolength+1)));
  }
  return (retval>0)?retval:length;
}

GUTF8String
GURL::pathname(void) const
{
  return (is_local_file_url())
    ?GURL::encode_reserved(UTF8Filename()) 
    :url.substr(pathname_start(url,protocol().length()),(unsigned int)(-1));
}

GURL
GURL::base(void) const
{
   const GUTF8String xurl(get_string());
   const int protocol_length=protocol(xurl).length();
   const int xurl_length=xurl.length();
   const char * const url_ptr=xurl;
   const char * ptr, * xslash;
   ptr=xslash=url_ptr+protocol_length+1;
   if(xslash[0] == '/')
   {
     xslash++;
     if(xslash[0] == '/')
       xslash++;
     for(ptr=xslash;ptr[0] && !is_argument(ptr);ptr++)
     {
       if ((ptr[0]==slash)&&ptr[1]&&!is_argument(ptr+1))
        xslash=ptr;
     }
     if(xslash[0] != '/')
     {
       xslash=url_ptr+xurl_length;
     }
   }
   return GURL::UTF8(
// ifdef WIN32
// (*(xslash-1) == colon)?
//   (GUTF8String(xurl,(int)(xslash-url_ptr))+"/" ):
// endif
     (GUTF8String(xurl,(int)(xslash-url_ptr))+"/"));
}

bool
GURL::operator==(const GURL & gurl2) const
{
  bool retval=false;
  const GUTF8String g1(get_string());
  const int g1_length=g1.length();
  const GUTF8String g2(gurl2.get_string());
  const int g2_length=g2.length();
  if(g1_length == g2_length) // exactly equal
  {
	retval=(g1==g2);
  }else if(g1_length+1 == g2_length) // g1 is g2 with a slash at the end
  {
    retval=(g2[g1_length] == '/')&&!g1.cmp(g2,g1_length);
  }else if(g2_length+1 == g1_length)  // g2 is g1 with a slash at the end
  {
    retval=(g1[g2_length] == '/')&&!g1.cmp(g2,g2_length);
  }
  return retval;
}

GUTF8String
GURL::name(void) const
{
   if(!validurl)
     const_cast<GURL *>(this)->init();
   GUTF8String retval;
   if(!is_empty())
   {
     const GUTF8String xurl(url);
     const int protocol_length=protocol(xurl).length();
     const char * ptr, * xslash=(const char *)xurl+protocol_length-1;
     for(ptr=(const char *)xurl+protocol_length;
       *ptr && !is_argument(ptr);ptr++)
	 {
       if (*ptr==slash)
          xslash=ptr;
	 }
     retval=GUTF8String(xslash+1, ptr-xslash-1);
   }
   return retval;
}

GUTF8String
GURL::fname(void) const
{
   if(!validurl)
     const_cast<GURL *>(this)->init();
   return decode_reserved(name());
}

GUTF8String
GURL::extension(void) const
{
   if(!validurl)
     const_cast<GURL *>(this)->init();
   GUTF8String xfilename=name();
   GUTF8String retval;

   for(int i=xfilename.length()-1;i>=0;i--)
   {
      if (xfilename[i]=='.')
      {
         retval=(const char*)xfilename+i+1;
         break;
      }
   } 
   return retval;
}

GUTF8String
GURL::decode_reserved(const GUTF8String &gurl)
{
  const char *url=gurl;
  char *res;
  GPBuffer<char> gres(res,gurl.length()+1);
  char *r=res;
  for(const char * ptr=url;*ptr;++ptr,++r)
  {
    if (*ptr!=percent)
    {
      r[0]=*ptr;
    }else
    {
      int c1,c2;
      if ( ((c1=hexval(ptr[1]))>=0)
        && ((c2=hexval(ptr[2]))>=0) )
      {
        r[0]=(c1<<4)|c2;
        ptr+=2;
      } else
      {
        r[0]=*ptr;
      }
    }
  }
  r[0]=0;
  GUTF8String retval(res);
  if(!retval.is_valid())
  {
    retval=GNativeString(res);
  }
  return retval;
}

GUTF8String
GURL::encode_reserved(const GUTF8String &gs)
{
  const char *s=(const char *)gs;
  // Potentially unsafe characters (cf. RFC1738 and RFC1808)
  static const char hex[] = "0123456789ABCDEF";
  
  unsigned char *retval;
  GPBuffer<unsigned char> gd(retval,strlen(s)*3+1);
  unsigned char *d=retval;
  for (; *s; s++,d++)
  {
    // Convert directory separator to slashes
#if defined(WIN32) || defined(OS2)
    if (*s == backslash || *s== slash)
#else
#ifdef macintosh
    if (*s == colon )
#else
#ifdef UNIX
    if (*s == slash )
#else
#error "Define something here for your operating system"
#endif  
#endif
#endif
    {
      *d = slash; 
      continue;
    }
    unsigned char const ss=(unsigned char const)(*s);
    // WARNING: Whenever you modify this conversion code,
    // make sure, that the following functions are in sync:
    //   encode_reserved()
    //   decode_reserved()
    //   url_to_filename()
    //   filename_to_url()
    // unreserved characters
    if ( (ss>='a' && ss<='z') ||
         (ss>='A' && ss<='Z') ||
         (ss>='0' && ss<='9') ||
         (strchr("$-_.+!*'(),:~=", ss)) ) 
    {
      *d = ss;
      continue;
    }
    // escape sequence
    d[0] = percent;
    d[1] = hex[ (ss >> 4) & 0xf ];
    d[2] = hex[ (ss) & 0xf ];
    d+=2;
  }
  *d = 0;
  return retval;
}

// -------------------------------------------
// Functions for converting filenames and urls
// -------------------------------------------

static GUTF8String
url_from_UTF8filename(const GUTF8String &gfilename)
{
  if(GURL::UTF8(gfilename).is_valid())
  {
    DEBUG_MSG("Debug: URL as Filename: " << gfilename << "\n");
  } 
  const char *filename=gfilename;
  if(filename && (unsigned char)filename[0] == (unsigned char)0xEF
     && (unsigned char)filename[1] == (unsigned char)0xBB 
     && (unsigned char)filename[2] == (unsigned char)0xBF)
  {
    filename+=3;
  }

  // Special case for blank pages
  if(!filename || !filename[0])
  {
    return GUTF8String();
  } 

  // Normalize file name to url slash-and-escape syntax
  GUTF8String oname=GURL::expand_name(filename);
  GUTF8String nname=GURL::encode_reserved(oname);

  // Preprend "file://" to file name. If file is on the local
  // machine, include "localhost".
  GUTF8String url=filespecslashes;
  const char *cnname=nname;
  if (cnname[0] == slash)
  {
    if (cnname[1] == slash)
    {
      url += cnname+2;
    }else
    {
      url = localhost + nname;
    }
  }else
  {
    url += (localhostspec1+2) + nname;
  }
  return url;
}

GUTF8String 
GURL::get_string(const bool nothrow) const
{
  if(!validurl)
    const_cast<GURL *>(this)->init(nothrow);
  return url;
}

// -- Returns a url for accessing a given file.
//    If useragent is not provided, standard url will be created,
//    but will not be understood by some versions if IE.
GUTF8String 
GURL::get_string(const GUTF8String &useragent) const
{
  if(!validurl)
    const_cast<GURL *>(this)->init();
  GUTF8String retval(url);
  if(is_local_file_url()&&useragent.length())
  {
    if(useragent.search("MSIE") >= 0 || useragent.search("Microsoft")>=0)
    {
      retval=filespecslashes + expand_name(UTF8Filename());
    }
  }
  return retval;
}

GURL::UTF8::UTF8(const GUTF8String &xurl)
: GURL(xurl) {}

GURL::UTF8::UTF8(const GUTF8String &xurl,const GURL &codebase)
: GURL(xurl,codebase) {}

GURL::GURL(const GUTF8String &xurl,const GURL &codebase)
  : validurl(false)
{
  if(GURL::UTF8(xurl).is_valid())
  {
    url=xurl;
  }else
  {
    const char *c=xurl;
    if(c[0] == slash)
    {
      GURL base(codebase);
      for(GURL newbase=base.base();newbase!=base;newbase=base.base())
      {
        base=newbase;
      }
      url=base.get_string(true)+GURL::encode_reserved(xurl);
    }else
    {
      url=beautify_path(codebase.get_string(true)+GUTF8String(slash)+GURL::encode_reserved(xurl));
    }
  }
}

GURL::Native::Native(const GNativeString &xurl)
: GURL(xurl) {}

GURL::Native::Native(const GNativeString &xurl,const GURL &codebase)
: GURL(xurl,codebase) {}

GURL::GURL(const GNativeString &xurl,const GURL &codebase)
  : validurl(false)
{
  GURL retval(xurl.getNative2UTF8(),codebase);
  if(retval.is_valid())
  {
#if defined(WIN32)
    // Hack for IE to change \\ to /
    if(retval.is_local_file_url())
    {
      GURL::Filename::UTF8 retval2(retval.UTF8Filename());
      url=retval2.get_string(true);
      validurl=false;
    }else
#endif // WIN32
    {
      url=retval.get_string(true);
      validurl=false;
    }
  }
}

GURL::Filename::Filename(const GNativeString &gfilename)
{
  url=url_from_UTF8filename(gfilename.getNative2UTF8());
}

GURL::Filename::Native::Native(const GNativeString &gfilename)
: GURL::Filename(gfilename) {}

GURL::Filename::Filename(const GUTF8String &gfilename)
{
  url=url_from_UTF8filename(gfilename);
}

GURL::Filename::UTF8::UTF8(const GUTF8String &gfilename)
: GURL::Filename(gfilename) {}

// filename --
// -- Applies heuristic rules to convert a url into a valid file name.  
//    Returns a simple basename in case of failure.
GUTF8String 
GURL::UTF8Filename(void) const
{
  GUTF8String retval;
  if(! is_empty())
  {
    const char *url_ptr=url;
  
    // WARNING: Whenever you modify this conversion code,
    // make sure, that the following functions are in sync:
    //   encode_reserved()
    //   decode_reserved()
    //   url_to_filename()
    //   filename_to_url()

    GUTF8String urlcopy=decode_reserved(url);
    url_ptr = urlcopy;

    // All file urls are expected to start with filespec which is "file:"
    if (GStringRep::cmp(filespec, url_ptr, sizeof(filespec)-1))  //if not
      return GOS::basename(url_ptr);
    url_ptr += sizeof(filespec)-1;
  
#if defined(macintosh)
    //remove all leading slashes
    for(;*url_ptr==slash;url_ptr++)
      EMPTY_LOOP;
    // Remove possible localhost spec
    if ( !GStringRep::cmp(localhost, url_ptr, sizeof(localhost)-1) )
      url_ptr += sizeof(localhost)-1;
    //remove all leading slashes
    while(*url_ptr==slash)
      url_ptr++;
#else
    // Remove possible localhost spec
    if ( !GStringRep::cmp(localhostspec1, url_ptr, sizeof(localhostspec1)-1) )
      // RFC 1738 local host form
      url_ptr += sizeof(localhostspec1)-1;
    else if ( !GStringRep::cmp(localhostspec2, url_ptr, sizeof(localhostspec2)-1 ) )
      // RFC 1738 local host form
      url_ptr += sizeof(localhostspec2)-1;
    else if ( (strlen(url_ptr) > 4)   // "file://<letter>:/<path>"
        && (url_ptr[0] == slash)      // "file://<letter>|/<path>"
        && (url_ptr[1] == slash)
        && isalpha(url_ptr[2])
        && ( url_ptr[3] == colon || url_ptr[3] == '|' )
        && (url_ptr[4] == slash) )
      url_ptr += 2;
    else if ( (strlen(url_ptr)) > 2 // "file:/<path>"
        && (url_ptr[0] == slash)
        && (url_ptr[1] != slash) )
      url_ptr++;
#endif

    // Check if we are finished
#if defined(macintosh)
    {
      char *l_url;
      GPBuffer<char> gl_url(l_url,strlen(url_ptr)+1);
      const char *s;
      char *r;
      for ( s=url_ptr,r=l_url; *s; s++,r++)
      {
        *r=(*s == slash)?colon:*s;
      }
      *r=0;
      retval = expand_name(l_url,root);
    }
#else  
    retval = expand_name(url_ptr,root);
#endif
    
#if defined(WIN32) || defined(OS2)
    if (url_ptr[0] && url_ptr[1]=='|' && url_ptr[2]== slash)
    {
      if ((url_ptr[0]>='a' && url_ptr[0]<='z') 
          || (url_ptr[0]>='A' && url_ptr[0]<='Z'))
      {
	GUTF8String drive;
	drive.format("%c%c%c", url_ptr[0],colon,backslash);
	retval = expand_name(url_ptr+3, drive);
      }
    }
#endif
  }
  // Return what we have
  return retval;
}

GNativeString 
GURL::NativeFilename(void) const
{
  return UTF8Filename().getUTF82Native();
}

#if defined(UNIX) || defined(macintosh) || defined(OS2)
static int
urlstat(const GURL &url,struct stat &buf)
{
  return ::stat(url.NativeFilename(),&buf);
}
#endif

// is_file(url) --
// -- returns true if filename denotes a regular file.
bool
GURL::is_file(void) const
{
  bool retval=false;
  if(is_local_file_url())
  {
#if defined(UNIX) || defined(macintosh) || defined(OS2)
    struct stat buf;
    if (!urlstat(*this,buf))
    {
      retval=!(buf.st_mode & S_IFDIR);
    }
#elif defined(WIN32)
    GUTF8String filename(UTF8Filename());
    if(filename.length() >= MAX_PATH)
      {
        if(!filename.cmp("\\\\",2))
          filename="\\\\?\\UNC"+filename.substr(1,-1);
        else
          filename="\\\\?\\"+filename;
      }
    wchar_t *wfilename;
    const size_t wfilename_size=filename.length()+1;
    GPBuffer<wchar_t> gwfilename(wfilename,wfilename_size);
    filename.ncopy(wfilename,wfilename_size);
    DWORD dwAttrib;
    dwAttrib = GetFileAttributesW(wfilename);
    if((dwAttrib|1) == 0xFFFFFFFF)
      {
        USES_CONVERSION ;
        dwAttrib = GetFileAttributes(A2CT(NativeFilename())) ;//MBCS cvt
      }
    retval=!( dwAttrib & FILE_ATTRIBUTE_DIRECTORY );
#else
# error "Define something here for your operating system"
#endif
  }
  return retval;
}

bool
GURL::is_local_path(void) const
{
  bool retval=false;
  if(is_local_file_url())
  {
#if defined(UNIX) || defined(macintosh) || defined(OS2)
    struct stat buf;
    retval=!urlstat(*this,buf);
#else
    GUTF8String filename(UTF8Filename());
    if(filename.length() >= MAX_PATH)
      {
        if(!filename.cmp("\\\\",2))
          filename="\\\\?\\UNC"+filename.substr(1,-1);
        else
          filename="\\\\?\\"+filename;
      }
    wchar_t *wfilename;
    const size_t wfilename_size=filename.length()+1;
    GPBuffer<wchar_t> gwfilename(wfilename,wfilename_size);
    filename.ncopy(wfilename,wfilename_size);
    DWORD dwAttrib;
    dwAttrib = GetFileAttributesW(wfilename);
    if((dwAttrib|1) == 0xFFFFFFFF)
      {
        USES_CONVERSION ;
        dwAttrib = GetFileAttributes(A2CT(NativeFilename())) ;//MBCS cvt
      }
    retval=( (dwAttrib|1) != 0xFFFFFFFF);
#endif
  }
  return retval;
}

// is_dir(url) --
// -- returns true if url denotes a directory.
bool 
GURL::is_dir(void) const
{
  bool retval=false;
  if(is_local_file_url())
  {
    // UNIX implementation
#if defined(UNIX) || defined(macintosh) || defined(OS2)
    struct stat buf;
    if (!urlstat(*this,buf))
    {
      retval=(buf.st_mode & S_IFDIR);
    }
#elif defined(WIN32)   // (either Windows or WCE)
    GUTF8String filename(UTF8Filename());
    if(filename.length() >= MAX_PATH)
      {
        if(!filename.cmp("\\\\",2))
          filename="\\\\?\\UNC"+filename.substr(1,-1);
        else
          filename="\\\\?\\"+filename;
      }
    wchar_t *wfilename;
    const size_t wfilename_size=filename.length()+1;
    GPBuffer<wchar_t> gwfilename(wfilename,wfilename_size);
    filename.ncopy(wfilename,wfilename_size);
    DWORD dwAttrib;
    dwAttrib = GetFileAttributesW(wfilename);
    if((dwAttrib|1) == 0xFFFFFFFF)
      {
        USES_CONVERSION ;
        dwAttrib = GetFileAttributes(A2CT(NativeFilename())) ;//MBCS cvt
      }
    retval=((dwAttrib != 0xFFFFFFFF)&&( dwAttrib & FILE_ATTRIBUTE_DIRECTORY ));
#else
# error "Define something here for your operating system"
#endif
  }
  return retval;
}

// Follows symbolic links.
GURL 
GURL::follow_symlinks(void) const
{
  GURL ret = *this;
#if defined(S_IFLNK)
#if defined(UNIX) || defined(macintosh)
  int lnklen;
  char lnkbuf[MAXPATHLEN+1];
  struct stat buf;
  while ( (urlstat(ret, buf) >= 0) &&
          (buf.st_mode & S_IFLNK) &&
          ((lnklen = readlink(ret.NativeFilename(),lnkbuf,sizeof(lnkbuf))) > 0) )
    {
      lnkbuf[lnklen] = 0;
      GNativeString lnk(lnkbuf);
      ret = GURL(lnk, ret.base());
    }
#endif
#endif
  return ret;
}

int
GURL::mkdir() const
{
  if(! is_local_file_url())
    return -1;
  int retval=0;
  const GURL baseURL=base();
  if (baseURL.get_string() != url && !baseURL.is_dir())
    retval = baseURL.mkdir();
  if(!retval)
    {
#if defined(UNIX)
      if (is_dir())
        retval = 0;
      else 
        retval = ::mkdir(NativeFilename(), 0755);
#elif defined(WIN32)
      USES_CONVERSION;
      if (is_dir())
        retval = 0;
      else 
        retval = CreateDirectory(A2CT(NativeFilename()), NULL);
#else
# error "Define something here for your operating system"
#endif
    }
  return retval;
}

// deletefile
// -- deletes a file or directory
  
int
GURL::deletefile(void) const
{
  int retval = -1;
  if(is_local_file_url())
    {
#if defined(UNIX)
      if (is_dir())
        retval = ::rmdir(NativeFilename());
      else
        retval = ::unlink(NativeFilename());
#elif defined(WIN32)
      USES_CONVERSION;
      if (is_dir())
        retval = ::RemoveDirectory(A2CT(NativeFilename()));
      else
        retval = ::DeleteFile(A2CT(NativeFilename()));
#else
# error "Define something here for your operating system"
#endif
  }
  return retval;
}

GList<GURL>
GURL::listdir(void) const
{
  GList<GURL> retval;
  if(is_dir())
  {
#if defined(UNIX) || defined(OS2)
    DIR * dir=opendir(NativeFilename());//MBCS cvt
    for(dirent *de=readdir(dir);de;de=readdir(dir))
    {
      const int len = NAMLEN(de);
      if (de->d_name[0]== dot  && len==1)
        continue;
      if (de->d_name[0]== dot  && de->d_name[1]== dot  && len==2)
        continue;
      retval.append(GURL::Native(de->d_name,*this));
    }
    closedir(dir);
#elif defined (WIN32)
    GURL::UTF8 wildcard("*.*",*this);
    WIN32_FIND_DATA finddata;
    HANDLE handle = FindFirstFile(wildcard.NativeFilename(), &finddata);//MBCS cvt
    const GUTF8String gpathname=pathname();
    const GUTF8String gbase=base().pathname();
    if( handle != INVALID_HANDLE_VALUE)
    {
      do
      {
        GURL::UTF8 Entry(finddata.cFileName,*this);
        const GUTF8String gentry=Entry.pathname();
        if((gentry != gpathname) && (gentry != gbase))
          retval.append(Entry);
      } while( FindNextFile(handle, &finddata) );

      FindClose(handle);
    }
#else
# error "Define something here for your operating system"
#endif
  }
  return retval;
}

int
GURL::cleardir(const int timeout) const
{
  int retval=(-1);
  if(is_dir())
  {
    GList<GURL> dirlist=listdir();
    retval=0;
    for(GPosition pos=dirlist;pos&&!retval;++pos)
    {
      const GURL &Entry=dirlist[pos];
      if(Entry.is_dir())
      {
        if((retval=Entry.cleardir(timeout)) < 0)
        {
          break;
        }
      }
      if(((retval=Entry.deletefile())<0) && (timeout>0))
      {
        GOS::sleep(timeout);
        retval=Entry.deletefile();
      }
    }
  }
  return retval;
}

int
GURL::renameto(const GURL &newurl) const
{
  if (is_local_file_url() && newurl.is_local_file_url())
    return rename(NativeFilename(),newurl.NativeFilename());
  return -1;
}

// expand_name(filename[, fromdirname])
// -- returns the full path name of filename interpreted
//    relative to fromdirname.  Use current working dir when
//    fromdirname is null.
GUTF8String 
GURL::expand_name(const GUTF8String &xfname, const char *from)
{
  const char *fname=xfname;
  GUTF8String retval;
  const size_t maxlen=xfname.length()*9+MAXPATHLEN+10;
  char * const string_buffer = retval.getbuf(maxlen);
  // UNIX implementation
#if defined(UNIX)
  // Perform tilde expansion
  GUTF8String senv;
  if (fname && fname[0]==tilde)
  {
    int n;
    for(n=1;fname[n] && fname[n]!= slash;n++) 
      EMPTY_LOOP;
    struct passwd *pw=0;
    if (n!=1)
    {
      GUTF8String user(fname+1, n-1);
      pw=getpwnam(user);
    }else if ((senv=GOS::getenv("HOME")).length())
    {
      from=(const char *)senv;
      fname = fname + n;
    }else if ((senv=GOS::getenv("LOGNAME")).length())
    {
      pw = getpwnam((const char *)senv.getUTF82Native());
    }else
    {
      pw=getpwuid(getuid());
    }
    if (pw)
    {
      senv=GNativeString(pw->pw_dir).getNative2UTF8();
      from = (const char *)senv;
      fname = fname + n;
    }
    for(;fname[0] == slash; fname++)
      EMPTY_LOOP;
  }
  // Process absolute vs. relative path
  if (fname && fname[0]== slash)
  {
    string_buffer[0]=slash;
    string_buffer[1]=0;
  }else if (from)
  {
    strcpy(string_buffer, expand_name(from));
  }else
  {
    strcpy(string_buffer, GOS::cwd());
  }
  char *s = string_buffer + strlen(string_buffer);
  if(fname)
  {
    for(;fname[0]== slash;fname++)
      EMPTY_LOOP;
    // Process path components
    while(fname[0])
    {
      if (fname[0] == dot )
      {
        if (!fname[1] || fname[1]== slash)
        {
          fname++;
          continue;
        }else if (fname[1]== dot && (fname[2]== slash || !fname[2]))
        {
          fname +=2;
          for(;s>string_buffer+1 && *(s-1)== slash; s--)
            EMPTY_LOOP;
          for(;s>string_buffer+1 && *(s-1)!= slash; s--)
            EMPTY_LOOP;
          continue;
        }
      }
      if ((s==string_buffer)||(*(s-1)!= slash))
      {
        *s = slash;
        s++;
      }
      while (*fname &&(*fname!= slash))
      {
        *s = *fname++;
        if ((size_t)((++s)-string_buffer) > maxlen)
        {
          G_THROW( ERR_MSG("GURL.big_name") );
        }
      }
      *s = 0;
      for(;fname[0]== slash;fname++)
        EMPTY_LOOP;
    }
  }
  if (!fname || !fname[0])
  {
    for(;s>string_buffer+1 && *(s-1) == slash; s--)
      EMPTY_LOOP;
    *s = 0;
  }
#elif defined (WIN32) // WIN32 implementation
  // Handle base
  strcpy(string_buffer, (char const *)(from ? expand_name(from) : GOS::cwd()));
  //  GNativeString native;
  if (fname)
  {
    char *s = string_buffer;
    char  drv[4];
    // Handle absolute part of fname
    //      Put absolute part of the file name in string_buffer, and
    //      the relative part pointed to by fname.
    if (fname[0]== slash || fname[0]== backslash)
    {
      if (fname[1]== slash || fname[1]== backslash)
      {       // Case "//abcd"
        s[0]=s[1]= backslash; s[2]=0;
      }
      else
      {       // Case "/abcd" or "/"
              //    File is at the root of the current drive. Delete the
              //    slash at the beginning of the filename and leave
              //    an explicit identification of the root of the drive in
              //    string_buffer.
        fname++;
        s[3] = '\0';
      }
    }
    else if (fname[0] && fname[1]==colon)
    {
      if (fname[2]!= slash && fname[2]!= backslash)
      {       // Case "x:abcd"
        if ( toupper((unsigned char)s[0]) != toupper((unsigned char)fname[0])
          || s[1]!=colon)
        {
          drv[0]=fname[0];
          drv[1]=colon;
          drv[2]= dot ;
          drv[3]=0;
          GetFullPathName(drv, maxlen, string_buffer, &s);
          strcpy(string_buffer,(const char *)GUTF8String(string_buffer).getNative2UTF8());
          s = string_buffer;
        }
        fname += 2;
      }
      else if (fname[3]!= slash && fname[3]!= backslash)
      {       // Case "x:/abcd"
        s[0]=toupper((unsigned char)fname[0]);
        s[1]=colon;
        s[2]=backslash;
        s[3]=0;
        fname += 3;
      }
      else
      {       // Case "x://abcd"
        s[0]=s[1]=backslash;
        s[2]=0;
        fname += 4;
      }
    }
    // Process path components
    for(;*fname== slash || *fname==backslash;fname++)
      EMPTY_LOOP;
    while(*fname)
    {
      if (fname[0]== dot )
      {
        if (fname[1]== slash || fname[1]==backslash || !fname[1])
        {
          fname++;
          continue;
        }else if ((fname[1] == dot)
          && (fname[2]== slash || fname[2]==backslash || !fname[2]))
        {
          fname += 2;
          char *back=_tcsrchr(string_buffer,backslash);
          char *forward=_tcsrchr(string_buffer,slash);
          if(back>forward)
          {
            *back=0;
          }else if(forward)
          {
            *forward=0;
          }
          s = string_buffer;
          continue;
        }
        char* s2=s;//MBCS DBCS
        for(;*s;s++) 
          EMPTY_LOOP;
        char* back = _tcsrchr(s2,backslash);//MBCS DBCS
        if ((s>string_buffer)&&(*(s-1)!= slash)&&
            (back == NULL || (back!=NULL && s-1 != back) ))//MBCS DBCS
        {
          *s = backslash;
          s++;
        }
        while (*fname && *fname!= slash && *fname!=backslash)
        {
          *s = *fname++;
          if ((size_t)((++s)-string_buffer) > maxlen)
            G_THROW( ERR_MSG("GURL.big_name") );
        }
        *s = 0;
      }
      char* s2=s;//MBCS DBCS
      for(;*s;s++) 
        EMPTY_LOOP;
      char* back = _tcsrchr(s2,backslash);//MBCS DBCS
      if ((s>string_buffer)&&(*(s-1)!= slash)
          &&(back == NULL || (back!=NULL && s-1 != back) ))//MBCS DBCS
      {
        *s = backslash;
        s++;
      }
      while (*fname && (*fname!= slash) && (*fname!=backslash))
      {
        *s = *fname++;
        if ((size_t)((++s)-string_buffer) > maxlen)
          G_THROW( ERR_MSG("GURL.big_name") );
      }
      *s = 0;
      for(;(*fname== slash)||(*fname==backslash);fname++)
        EMPTY_LOOP;
    }
  }
#elif defined(macintosh) // MACINTOSH implementation
  strcpy(string_buffer, (const char *)(from?from:GOS::cwd()));
  
  if (!GStringRep::cmp(fname, string_buffer,strlen(string_buffer)) || is_file(fname))
  {
    strcpy(string_buffer, "");//please don't expand, the logic of filename is chaos.
  }
  
  // Process path components
  char *s = string_buffer + strlen(string_buffer);
  if(fname)
  {
    for(;fname[0]==colon;fname++)
      EMPTY_LOOP;
    while(fname[0])
    {
      if (fname[0]== dot )
      {
        if (fname[1]==colon || !fname[1])
        {
          fname++;
          continue;
        }
        if ((fname[1]== dot )
          &&(fname[2]==colon || fname[2]==0))
        {
          fname +=2;
          for(;(s>string_buffer+1)&&(*(s-1)==colon);s--)
            EMPTY_LOOP;
          for(;(s>string_buffer+1)&&(*(s-1)!=colon);s--)
            EMPTY_LOOP;
          continue;
        }
      }
      if ((s==string_buffer)||(*(s-1)!=colon))
      {
        *s = colon;
        s++;
      }
      while (*fname!=0 && *fname!=colon)
      {
        *s = *fname++;
        if ((++s)-string_buffer > maxlen)
          G_THROW( ERR_MSG("GURL.big_name") );
      }
      *s = 0;
      for(;fname[0]==colon;fname++)
        EMPTY_LOOP;
    }
  }
  for(;(s>string_buffer+1) && (*(s-1)==colon);s--)
    EMPTY_LOOP;
  *s = 0;
  return ((string_buffer[0]==colon)?(string_buffer+1):string_buffer);
#else
# error "Define something here for your operating system"
#endif  
  return retval;
}

unsigned int
hash(const GURL & gurl)
{
  unsigned int retval;
  const GUTF8String s(gurl.get_string());
  const int len=s.length();
  if(len && (s[len-1] == '/')) // Don't include the trailing slash as part of the hash.
  {
	retval=hash(s.substr(0,len-1));
  }else
  {
    retval=hash(s);
  }
  return retval;
}


#ifdef HAVE_NAMESPACES
}
# ifndef NOT_USING_DJVU_NAMESPACE
using namespace DJVU;
# endif
#endif