summaryrefslogtreecommitdiff
path: root/lib/win32/emu.cpp
blob: ee1f461a5994781ba20d82c02d37394fc1d93038 (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
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
// Box Backup Win32 native port by Nick Knight

#include "emu.h"

#ifdef WIN32

#include <assert.h>
#include <fcntl.h>
#include <process.h>
#include <windows.h>

#ifdef HAVE_UNISTD_H
	#include <unistd.h>
#endif

#include <string>
#include <list>
#include <sstream>

// message resource definitions for syslog()
#include "messages.h"

DWORD winerrno;
struct passwd gTempPasswd;

bool EnableBackupRights()
{
	HANDLE hToken;
	TOKEN_PRIVILEGES token_priv;

	//open current process to adjust privileges
	if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, 
		&hToken))
	{
		::syslog(LOG_ERR, "Failed to open process token: %s",
			GetErrorMessage(GetLastError()).c_str());
		return false;
	}

	//let's build the token privilege struct - 
	//first, look up the LUID for the backup privilege

	if (!LookupPrivilegeValue(
		NULL, //this system
		SE_BACKUP_NAME, //the name of the privilege
		&( token_priv.Privileges[0].Luid ))) //result
	{
		::syslog(LOG_ERR, "Failed to lookup backup privilege: %s",
			GetErrorMessage(GetLastError()).c_str());
		CloseHandle(hToken);
		return false;
	}

	token_priv.PrivilegeCount = 1;
	token_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

	// now set the privilege
	// because we're going exit right after dumping the streams, there isn't 
	// any need to save current state

	if (!AdjustTokenPrivileges(
		hToken, //our process token
		false,  //we're not disabling everything
		&token_priv, //address of structure
		sizeof(token_priv), //size of structure
		NULL, NULL)) //don't save current state
	{
		//this function is a little tricky - if we were adjusting
		//more than one privilege, it could return success but not
		//adjust them all - in the general case, you need to trap this
		::syslog(LOG_ERR, "Failed to enable backup privilege: %s",
			GetErrorMessage(GetLastError()).c_str());
		CloseHandle(hToken);
		return false;

	}

	CloseHandle(hToken);
	return true;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    GetDefaultConfigFilePath(std::string name)
//		Purpose: Calculates the default configuration file name,
//			 by using the directory location of the currently
//			 executing program, and appending the provided name.
//			 In case of fire, returns an empty string.
//		Created: 26th May 2007
//
// --------------------------------------------------------------------------
std::string GetDefaultConfigFilePath(const std::string& rName)
{
	WCHAR exePathWide[MAX_PATH];
	GetModuleFileNameW(NULL, exePathWide, MAX_PATH-1);

	char* exePathUtf8 = ConvertFromWideString(exePathWide, CP_UTF8);
	if (exePathUtf8 == NULL)
	{
		return "";
	}

	std::string configfile = exePathUtf8;
	delete [] exePathUtf8;
	
	// make the default config file name,
	// based on the program path
	configfile = configfile.substr(0,
		configfile.rfind('\\'));
	configfile += "\\";
	configfile += rName;

	return configfile;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    ConvertToWideString
//		Purpose: Converts a string from specified codepage to 
//			 a wide string (WCHAR*). Returns a buffer which 
//			 MUST be freed by the caller with delete[].
//			 In case of fire, logs the error and returns NULL.
//		Created: 4th February 2006
//
// --------------------------------------------------------------------------
WCHAR* ConvertToWideString(const char* pString, unsigned int codepage,
	bool logErrors)
{
	int len = MultiByteToWideChar
	(
		codepage, // source code page
		0,        // character-type options
		pString,  // string to map
		-1,       // number of bytes in string - auto detect
		NULL,     // wide-character buffer
		0         // size of buffer - work out 
		          //   how much space we need
	);

	if (len == 0)
	{
		winerrno = GetLastError();
		if (logErrors)
		{
			::syslog(LOG_WARNING, 
				"Failed to convert string to wide string: "
				"%s", GetErrorMessage(winerrno).c_str());
		}
		errno = EINVAL;
		return NULL;
	}

	WCHAR* buffer = new WCHAR[len];

	if (buffer == NULL)
	{
		if (logErrors)
		{
			::syslog(LOG_WARNING, 
				"Failed to convert string to wide string: "
				"out of memory");
		}
		winerrno = ERROR_OUTOFMEMORY;
		errno = ENOMEM;
		return NULL;
	}

	len = MultiByteToWideChar
	(
		codepage, // source code page
		0,        // character-type options
		pString,  // string to map
		-1,       // number of bytes in string - auto detect
		buffer,   // wide-character buffer
		len       // size of buffer
	);

	if (len == 0)
	{
		winerrno = GetLastError();
		if (logErrors)
		{
			::syslog(LOG_WARNING, 
				"Failed to convert string to wide string: "
				"%s", GetErrorMessage(winerrno).c_str());
		}
		errno = EACCES;
		delete [] buffer;
		return NULL;
	}

	return buffer;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    ConvertUtf8ToWideString
//		Purpose: Converts a string from UTF-8 to a wide string.
//			 Returns a buffer which MUST be freed by the caller 
//			 with delete[].
//			 In case of fire, logs the error and returns NULL.
//		Created: 4th February 2006
//
// --------------------------------------------------------------------------
WCHAR* ConvertUtf8ToWideString(const char* pString)
{
	return ConvertToWideString(pString, CP_UTF8, true);
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    ConvertFromWideString
//		Purpose: Converts a wide string to a narrow string in the
//			 specified code page. Returns a buffer which MUST 
//			 be freed by the caller with delete[].
//			 In case of fire, logs the error and returns NULL.
//		Created: 4th February 2006
//
// --------------------------------------------------------------------------
char* ConvertFromWideString(const WCHAR* pString, unsigned int codepage)
{
	int len = WideCharToMultiByte
	(
		codepage, // destination code page
		0,        // character-type options
		pString,  // string to map
		-1,       // number of bytes in string - auto detect
		NULL,     // output buffer
		0,        // size of buffer - work out 
		          //   how much space we need
		NULL,     // replace unknown chars with system default
		NULL      // don't tell us when that happened
	);

	if (len == 0)
	{
		::syslog(LOG_WARNING, 
			"Failed to convert wide string to narrow: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		errno = EINVAL;
		return NULL;
	}

	char* buffer = new char[len];

	if (buffer == NULL)
	{
		::syslog(LOG_WARNING, 
			"Failed to convert wide string to narrow: "
			"out of memory");
		errno = ENOMEM;
		return NULL;
	}

	len = WideCharToMultiByte
	(
		codepage, // source code page
		0,        // character-type options
		pString,  // string to map
		-1,       // number of bytes in string - auto detect
		buffer,   // output buffer
		len,      // size of buffer
		NULL,     // replace unknown chars with system default
		NULL      // don't tell us when that happened
	);

	if (len == 0)
	{
		::syslog(LOG_WARNING, 
			"Failed to convert wide string to narrow: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		errno = EACCES;
		delete [] buffer;
		return NULL;
	}

	return buffer;
}

bool ConvertFromWideString(const std::wstring& rInput, 
	std::string* pOutput, unsigned int codepage)
{
	int len = WideCharToMultiByte
	(
		codepage, // destination code page
		0,        // character-type options
		rInput.c_str(),  // string to map
		rInput.size(),       // number of bytes in string - auto detect
		NULL,     // output buffer
		0,        // size of buffer - work out 
		          //   how much space we need
		NULL,     // replace unknown chars with system default
		NULL      // don't tell us when that happened
	);

	if (len == 0)
	{
		::syslog(LOG_WARNING, 
			"Failed to convert wide string to narrow: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		errno = EINVAL;
		return false;
	}

	char* buffer = new char[len];

	if (buffer == NULL)
	{
		::syslog(LOG_WARNING, 
			"Failed to convert wide string to narrow: "
			"out of memory");
		errno = ENOMEM;
		return false;
	}

	len = WideCharToMultiByte
	(
		codepage, // source code page
		0,        // character-type options
		rInput.c_str(),  // string to map
		rInput.size(),       // number of bytes in string - auto detect
		buffer,   // output buffer
		len,      // size of buffer
		NULL,     // replace unknown chars with system default
		NULL      // don't tell us when that happened
	);

	if (len == 0)
	{
		::syslog(LOG_WARNING, 
			"Failed to convert wide string to narrow: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		errno = EACCES;
		delete [] buffer;
		return false;
	}

	*pOutput = std::string(buffer, len);
	delete [] buffer;
	return true;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    ConvertEncoding(const std::string&, int, 
//			 std::string&, int)
//		Purpose: Converts a string from one code page to another.
//			 On success, replaces contents of rDest and returns 
//			 true. In case of fire, logs the error and returns 
//			 false.
//		Created: 15th October 2006
//
// --------------------------------------------------------------------------
bool ConvertEncoding(const std::string& rSource, int sourceCodePage,
	std::string& rDest, int destCodePage)
{
	WCHAR* pWide = ConvertToWideString(rSource.c_str(), sourceCodePage,
		true);
	if (pWide == NULL)
	{
		::syslog(LOG_ERR, "Failed to convert string '%s' from "
			"current code page %d to wide string: %s",
			rSource.c_str(), sourceCodePage,
			GetErrorMessage(GetLastError()).c_str());
		return false;
	}

	char* pConsole = ConvertFromWideString(pWide, destCodePage);
	delete [] pWide;

	if (!pConsole)
	{
		// Error should have been logged by ConvertFromWideString
		return false;
	}

	rDest = pConsole;
	delete [] pConsole;

	return true;
}

bool ConvertToUtf8(const std::string& rSource, std::string& rDest,
	int sourceCodePage)
{
	return ConvertEncoding(rSource, sourceCodePage, rDest, CP_UTF8);
}

bool ConvertFromUtf8(const std::string& rSource, std::string& rDest,
	int destCodePage)
{
	return ConvertEncoding(rSource, CP_UTF8, rDest, destCodePage);
}

bool ConvertConsoleToUtf8(const std::string& rSource, std::string& rDest)
{
	return ConvertToUtf8(rSource, rDest, GetConsoleCP());
}

bool ConvertUtf8ToConsole(const std::string& rSource, std::string& rDest)
{
	return ConvertFromUtf8(rSource, rDest, GetConsoleOutputCP());
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    ConvertPathToAbsoluteUnicode
//		Purpose: Converts relative paths to absolute (with unicode marker)
//		Created: 4th February 2006
//
// --------------------------------------------------------------------------
std::string ConvertPathToAbsoluteUnicode(const char *pFileName)
{
	std::string filename;
	for (int i = 0; pFileName[i] != 0; i++)
	{
		if (pFileName[i] == '/')
		{
			filename += '\\';
		}
		else
		{
			filename += pFileName[i];
		}
	}

	std::string tmpStr("\\\\?\\");
	
	// Is the path relative or absolute?
	// Absolute paths on Windows are always a drive letter
	// followed by ':'
		
	char wd[PATH_MAX];
	if (::getcwd(wd, PATH_MAX) == 0)
	{
		::syslog(LOG_WARNING, 
			"Failed to open '%s': path too long", 
			pFileName);
		errno = ENAMETOOLONG;
		winerrno = ERROR_INVALID_NAME;
		tmpStr = "";
		return tmpStr;
	}

	if (filename.length() > 4 && filename[0] == '\\' &&
		filename[1] == '\\' && filename[2] == '?' &&
		filename[3] == '\\')
	{
		// File is already in absolute utf-8 format, e.g.
		// \\?\GLOBALROOT\...
		tmpStr = "";
	}
	else if (filename.length() > 2 && filename[0] == '\\' &&
		filename[1] == '\\')
	{
		tmpStr += "UNC\\";
		filename.replace(0, 2, "");
		// \\?\UNC\<server>\<share>
		// see http://msdn2.microsoft.com/en-us/library/aa365247.aspx
	}
	else if (filename.length() >= 1 && filename[0] == '\\')
	{
		// starts with \, i.e. root directory of current drive.
		tmpStr = wd;
		tmpStr.resize(2); // drive letter and colon
	}
	else if (filename.length() >= 2 && filename[1] != ':')
	{
		// Must be a relative path. We need to get the 
		// current directory to make it absolute.
		tmpStr += wd;
		if (tmpStr[tmpStr.length()-1] != '\\')
		{
			tmpStr += '\\';
		}
	}
	
	tmpStr += filename;

	// We are using direct filename access, which does not support ..,
	// so we need to implement it ourselves.

	for (std::string::size_type i = 1; i < tmpStr.size() - 3; i++)
	{
		if (tmpStr.substr(i, 3) == "\\..")
		{
			std::string::size_type lastSlash =
				tmpStr.rfind('\\', i - 1);

			if (lastSlash == std::string::npos)
			{
				// no previous directory, ignore it, 
				// CreateFile will fail with error 123
			}
			else
			{
				tmpStr.replace(lastSlash, i + 3 - lastSlash,
					"");
			}

			i = lastSlash - 1;
		}
	}

	return tmpStr;
}

std::string GetErrorMessage(DWORD errorCode)
{
	char* pMsgBuf = NULL;
	
	DWORD chars = FormatMessage
	(
		FORMAT_MESSAGE_ALLOCATE_BUFFER | 
		FORMAT_MESSAGE_FROM_SYSTEM,
		NULL,
		errorCode,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(char *)(&pMsgBuf),
		0, NULL
	);

	if (chars == 0 || pMsgBuf == NULL)
	{
		return std::string("failed to get error message");
	}

	// remove embedded newline
	pMsgBuf[chars - 1] = 0;
	pMsgBuf[chars - 2] = 0;

	std::ostringstream line;
	line << pMsgBuf << " (" << errorCode << ")";
	LocalFree(pMsgBuf);

	return line.str();
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    openfile
//		Purpose: replacement for any open calls - handles unicode 
//			filenames - supplied in utf8
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
HANDLE openfile(const char *pFileName, int flags, int mode)
{
	winerrno = ERROR_INVALID_FUNCTION;

	std::string AbsPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pFileName);
	
	if (AbsPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return INVALID_HANDLE_VALUE;
	}
	
	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
	// We are responsible for freeing pBuffer
	
	if (pBuffer == NULL)
	{
		// error already logged by ConvertUtf8ToWideString()
		return INVALID_HANDLE_VALUE;
	}

	// flags could be O_WRONLY | O_CREAT | O_RDONLY
	DWORD createDisposition = OPEN_EXISTING;
	DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE 
		| FILE_SHARE_DELETE;
	DWORD accessRights = FILE_READ_ATTRIBUTES | FILE_LIST_DIRECTORY 
		| FILE_READ_EA;

	if (flags & O_WRONLY)
	{
		accessRights = FILE_WRITE_DATA;
	}
	else if (flags & O_RDWR)
	{
		accessRights |= FILE_WRITE_ATTRIBUTES 
			| FILE_WRITE_DATA | FILE_WRITE_EA;
	}

	if (flags & O_CREAT)
	{
		createDisposition = OPEN_ALWAYS;
	}

	if (flags & O_TRUNC)
	{
		createDisposition = CREATE_ALWAYS;
	}

	if ((flags & O_CREAT) && (flags & O_EXCL))
	{
		createDisposition = CREATE_NEW;
	}

	if (flags & O_LOCK)
	{
		shareMode = 0;
	}

	DWORD winFlags = FILE_FLAG_BACKUP_SEMANTICS;
	if (flags & O_TEMPORARY)
	{
		winFlags  |= FILE_FLAG_DELETE_ON_CLOSE;
	}

	HANDLE hdir = CreateFileW(pBuffer, 
		accessRights, 
		shareMode, 
		NULL, 
		createDisposition, 
		winFlags,
		NULL);
	
	delete [] pBuffer;

	if (hdir == INVALID_HANDLE_VALUE)
	{
		winerrno = GetLastError();
		switch(winerrno)
		{
			case ERROR_SHARING_VIOLATION:
			errno = EBUSY;
			break;

			default:
			errno = EINVAL;
		}

		::syslog(LOG_WARNING, "Failed to open file '%s': "
			"%s", pFileName, 
			GetErrorMessage(GetLastError()).c_str());

		return INVALID_HANDLE_VALUE;
	}

	if (flags & O_APPEND)
	{
		if (SetFilePointer(hdir, 0, NULL, FILE_END) ==
			INVALID_SET_FILE_POINTER)
		{
			winerrno = GetLastError();
			errno = EINVAL;
			CloseHandle(hdir);
			return INVALID_HANDLE_VALUE;
		}
	}

	winerrno = NO_ERROR;
	return hdir;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    emu_fstat
//		Purpose: replacement for fstat. Supply a windows handle.
//			 Returns a struct emu_stat to have room for 64-bit
//			 file identifier in st_ino (mingw allows only 16!)
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
int emu_fstat(HANDLE hdir, struct emu_stat * st)
{
	if (hdir == INVALID_HANDLE_VALUE)
	{
		::syslog(LOG_ERR, "Error: invalid file handle in emu_fstat()");
		errno = EBADF;
		return -1;
	}

	BY_HANDLE_FILE_INFORMATION fi;
	if (!GetFileInformationByHandle(hdir, &fi))
	{
		::syslog(LOG_WARNING, "Failed to read file information: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		errno = EACCES;
		return -1;
	}

	if (INVALID_FILE_ATTRIBUTES == fi.dwFileAttributes)
	{
		::syslog(LOG_WARNING, "Failed to get file attributes: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		errno = EACCES;
		return -1;
	}

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

	// This is how we get our INODE (equivalent) information
	ULARGE_INTEGER conv;
	conv.HighPart = fi.nFileIndexHigh;
	conv.LowPart  = fi.nFileIndexLow;
	st->st_ino = conv.QuadPart;

	// get the time information
	st->st_ctime = ConvertFileTimeToTime_t(&fi.ftCreationTime);
	st->st_atime = ConvertFileTimeToTime_t(&fi.ftLastAccessTime);
	st->st_mtime = ConvertFileTimeToTime_t(&fi.ftLastWriteTime);

	if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
	{
		st->st_size = 0;
	}
	else
	{
		conv.HighPart = fi.nFileSizeHigh;
		conv.LowPart  = fi.nFileSizeLow;
		st->st_size = conv.QuadPart;
	}

	// at the mo
	st->st_uid = 0;
	st->st_gid = 0;
	st->st_nlink = 1;

	// the mode of the file
	// mode zero will make it impossible to restore on Unix
	// (no access to anybody, including the owner).
	// we'll fake a sensible mode:
	// all objects get user read (0400)
	// if it's a directory it gets user execute (0100)
	// if it's not read-only it gets user write (0200)
	st->st_mode = S_IREAD;

	if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
	{
		st->st_mode |= S_IFDIR | S_IEXEC;
	}
	else
	{
		st->st_mode |= S_IFREG;
	}

	if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
	{
		st->st_mode |= S_IWRITE;
	}

	// st_dev is normally zero, regardless of the drive letter,
	// since backup locations can't normally span drives. However,
	// a reparse point does allow all kinds of weird stuff to happen.
	// We set st_dev to 1 for a reparse point, so that Box will detect
	// a change of device number (from 0) and refuse to recurse down
	// the reparse point (which could lead to havoc).

	if (fi.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
	{
		st->st_dev = 1;
	}
	else
	{
		st->st_dev = 0;
	}

	return 0;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    OpenFileByNameUtf8
//		Purpose: Converts filename to Unicode and returns 
//			a handle to it. In case of error, sets errno,
//			logs the error and returns NULL.
//		Created: 10th December 2004
//
// --------------------------------------------------------------------------
HANDLE OpenFileByNameUtf8(const char* pFileName, DWORD flags)
{
	std::string AbsPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pFileName);
	
	if (AbsPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return NULL;
	}
	
	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
	// We are responsible for freeing pBuffer
	
	if (pBuffer == NULL)
	{
		// error already logged by ConvertUtf8ToWideString()
		return NULL;
	}

	HANDLE handle = CreateFileW(pBuffer, 
		flags,
		FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, 
		NULL, 
		OPEN_EXISTING, 
		FILE_FLAG_BACKUP_SEMANTICS,
		NULL);

	if (handle == INVALID_HANDLE_VALUE)
	{
		// if our open fails we should always be able to 
		// open in this mode - to get the inode information
		// at least one process must have the file open - 
		// in this case someone else does.
		handle = CreateFileW(pBuffer, 
			READ_CONTROL,
			FILE_SHARE_READ, 
			NULL, 
			OPEN_EXISTING, 
			FILE_FLAG_BACKUP_SEMANTICS,
			NULL);
	}

	delete [] pBuffer;

	if (handle == INVALID_HANDLE_VALUE)
	{
		DWORD err = GetLastError();

		if (err == ERROR_FILE_NOT_FOUND ||
			err == ERROR_PATH_NOT_FOUND)
		{
			errno = ENOENT;
		}
		else
		{
			::syslog(LOG_WARNING, "Failed to open '%s': "
				"%s", pFileName, 
				GetErrorMessage(err).c_str());
			errno = EACCES;
		}

		return NULL;
	}

	return handle;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    emu_stat 
//		Purpose: replacement for the lstat and stat functions. 
//			 Works with unicode filenames supplied in utf8.
//			 Returns a struct emu_stat to have room for 64-bit
//			 file identifier in st_ino (mingw allows only 16!)
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
int emu_stat(const char * pName, struct emu_stat * st)
{
	HANDLE handle = OpenFileByNameUtf8(pName, 
		FILE_READ_ATTRIBUTES | FILE_READ_EA);

	if (handle == NULL)
	{
		// errno already set and error logged by OpenFileByNameUtf8()
		return -1;
	}

	int retVal = emu_fstat(handle, st);
	if (retVal != 0)
	{
		// error logged, but without filename
		::syslog(LOG_WARNING, "Failed to get file information "
			"for '%s'", pName);
	}

	// close the handle
	CloseHandle(handle);

	return retVal;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    statfs
//		Purpose: returns the mount point of where a file is located - 
//			in this case the volume serial number
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
int statfs(const char * pName, struct statfs * s)
{
	HANDLE handle = OpenFileByNameUtf8(pName,
		FILE_READ_ATTRIBUTES | FILE_READ_EA);

	if (handle == NULL)
	{
		// errno already set and error logged by OpenFileByNameUtf8()
		return -1;
	}

	BY_HANDLE_FILE_INFORMATION fi;
	if (!GetFileInformationByHandle(handle, &fi))
	{
		::syslog(LOG_WARNING, "Failed to get file information "
			"for '%s': %s", pName,
			GetErrorMessage(GetLastError()).c_str());
		CloseHandle(handle);
		errno = EACCES;
		return -1;
	}

	// convert volume serial number to a string
	_ui64toa(fi.dwVolumeSerialNumber, s->f_mntonname + 1, 16);

	// pseudo unix mount point
	s->f_mntonname[0] = '\\';

	CloseHandle(handle);   // close the handle

	return 0;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    emu_utimes
//		Purpose: replacement for the POSIX utimes() function,
//			works with unicode filenames supplied in utf8 format,
//			sets creation time instead of last access time.
//		Created: 25th July 2006
//
// --------------------------------------------------------------------------
int emu_utimes(const char * pName, const struct timeval times[])
{
	FILETIME creationTime;
	if (!ConvertTime_tToFileTime(times[0].tv_sec, &creationTime))
	{
		errno = EINVAL;
		return -1;
	}

	FILETIME modificationTime;
	if (!ConvertTime_tToFileTime(times[1].tv_sec, &modificationTime))
	{
		errno = EINVAL;
		return -1;
	}

	HANDLE handle = OpenFileByNameUtf8(pName, FILE_WRITE_ATTRIBUTES);

	if (handle == NULL)
	{
		// errno already set and error logged by OpenFileByNameUtf8()
		return -1;
	}

	if (!SetFileTime(handle, &creationTime, NULL, &modificationTime))
	{
		::syslog(LOG_ERR, "Failed to set times on '%s': %s", pName,
			GetErrorMessage(GetLastError()).c_str());
		CloseHandle(handle);
		return 1;
	}

	CloseHandle(handle);
	return 0;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    emu_chmod
//		Purpose: replacement for the POSIX chmod function,
//			works with unicode filenames supplied in utf8 format
//		Created: 26th July 2006
//
// --------------------------------------------------------------------------
int emu_chmod(const char * pName, mode_t mode)
{
	std::string AbsPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pName);
	
	if (AbsPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return -1;
	}
	
	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
	// We are responsible for freeing pBuffer
	
	if (pBuffer == NULL)
	{
		// error already logged by ConvertUtf8ToWideString()
		free(pBuffer);
		return -1;
	}

	DWORD attribs = GetFileAttributesW(pBuffer);
	if (attribs == INVALID_FILE_ATTRIBUTES)
	{
		::syslog(LOG_ERR, "Failed to get file attributes of '%s': %s",
			pName, GetErrorMessage(GetLastError()).c_str());
		errno = EACCES;
		free(pBuffer);
		return -1;
	}

	if (mode & S_IWRITE)
	{
		attribs &= ~FILE_ATTRIBUTE_READONLY;
	}
	else
	{
		attribs |= FILE_ATTRIBUTE_READONLY;
	}

	if (!SetFileAttributesW(pBuffer, attribs))
	{
		::syslog(LOG_ERR, "Failed to set file attributes of '%s': %s",
			pName, GetErrorMessage(GetLastError()).c_str());
		errno = EACCES;
		free(pBuffer);
		return -1;
	}

	delete [] pBuffer;
	return 0;
}


// --------------------------------------------------------------------------
//
// Function
//		Name:    opendir
//		Purpose: replacement for unix function, uses win32 findfirst routines
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
DIR *opendir(const char *name)
{
	if (!name || !name[0])
	{
		errno = EINVAL;
		return NULL;
	}
	
	std::string dirName(name);

	//append a '\' win32 findfirst is sensitive to this
	if (dirName[dirName.size()-1] != '\\' || dirName[dirName.size()-1] != '/')
	{
		dirName += '\\';
	}

	// what is the search string? - everything
	dirName += '*';

	DIR *pDir = new DIR;
	if (pDir == NULL)
	{
		errno = ENOMEM;
		return NULL;
	}

	pDir->name = ConvertUtf8ToWideString(dirName.c_str());
	// We are responsible for freeing dir->name with delete[]
	
	if (pDir->name == NULL)
	{
		delete pDir;
		return NULL;
	}

	pDir->fd = FindFirstFileW(pDir->name, &pDir->info);

	if (pDir->fd == INVALID_HANDLE_VALUE)
	{
		delete [] pDir->name;
		delete pDir;
		return NULL;
	}
	
	pDir->result.d_name = 0;
	return pDir;
}

// this kinda makes it not thread friendly!
// but I don't think it needs to be.
char tempbuff[MAX_PATH];

// --------------------------------------------------------------------------
//
// Function
//		Name:    readdir
//		Purpose: as function above
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
struct dirent *readdir(DIR *dp)
{
	try
	{
		struct dirent *den = NULL;

		if (dp && dp->fd != INVALID_HANDLE_VALUE)
		{
			// first time around, when dp->result.d_name == NULL, use
			// the values returned by FindFirstFile. After that, call
			// FindNextFileW to return new ones.
			if (!dp->result.d_name ||
				FindNextFileW(dp->fd, &dp->info) != 0)
			{
				den = &dp->result;
				std::wstring input(dp->info.cFileName);
				memset(tempbuff, 0, sizeof(tempbuff));
				WideCharToMultiByte(CP_UTF8, 0, dp->info.cFileName, 
					-1, &tempbuff[0], sizeof (tempbuff), 
					NULL, NULL);
				//den->d_name = (char *)dp->info.name;
				den->d_name = &tempbuff[0];
				den->d_type = dp->info.dwFileAttributes;
			}
			else // FindNextFileW failed
			{
				// Why did it fail? No more files?
				winerrno = GetLastError();
				den = NULL;

				if (winerrno == ERROR_NO_MORE_FILES)
				{
					errno = 0; // no more files
				}
				else
				{
					errno = ENOSYS;
				}
			}
		}
		else
		{
			errno = EBADF;
		}

		return den;
	}
	catch (...)
	{
		printf("Caught readdir");
	}
	return NULL;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    closedir
//		Purpose: as function above
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
int closedir(DIR *dp)
{
	try
	{
		BOOL finres = false;

		if (dp)
		{
			if(dp->fd != INVALID_HANDLE_VALUE)
			{
				finres = FindClose(dp->fd);
			}

			delete [] dp->name;
			delete dp;
		}

		if (finres == FALSE) // errors go to EBADF 
		{
			winerrno = GetLastError();
			errno = EBADF;
		}

		return (finres == TRUE) ? 0 : -1;
	}
	catch (...)
	{
		printf("Caught closedir");
	}
	return -1;
}

// --------------------------------------------------------------------------
//
// Function
//		Name:    poll
//		Purpose: a weak implimentation (just enough for box) 
//			of the unix poll for winsock2
//		Created: 25th October 2004
//
// --------------------------------------------------------------------------
int poll (struct pollfd *ufds, unsigned long nfds, int timeout)
{
	try
	{
		fd_set readfd;
		fd_set writefd;

		FD_ZERO(&readfd);
		FD_ZERO(&writefd);

		// struct pollfd *ufdsTmp = ufds;

		timeval timOut;
		timeval *tmpptr; 

		if (timeout == INFTIM)
			tmpptr = NULL;
		else
			tmpptr = &timOut;

		timOut.tv_sec  = timeout / 1000;
		timOut.tv_usec = timeout * 1000;

		for (unsigned long i = 0; i < nfds; i++)
		{
			struct pollfd* ufd = &(ufds[i]);

			if (ufd->events & POLLIN)
			{
				FD_SET(ufd->fd, &readfd);
			}

			if (ufd->events & POLLOUT)
			{
				FD_SET(ufd->fd, &writefd);
			}

			if (ufd->events & ~(POLLIN | POLLOUT))
			{
				printf("Unsupported poll bits %d",
					ufd->events);
				return -1;
			}
		}	

		int nready = select(0, &readfd, &writefd, 0, tmpptr);

		if (nready == SOCKET_ERROR)
		{
			// int errval = WSAGetLastError();

			struct pollfd* pufd = ufds;
			for (unsigned long i = 0; i < nfds; i++)
			{
				pufd->revents = POLLERR;
				pufd++;
			}
			return (-1);
		}
		else if (nready > 0)
		{
			for (unsigned long i = 0; i < nfds; i++)
			{
				struct pollfd *ufd = &(ufds[i]);

				if (FD_ISSET(ufd->fd, &readfd))
				{
					ufd->revents |= POLLIN;
				}

				if (FD_ISSET(ufd->fd, &writefd))
				{
					ufd->revents |= POLLOUT;
				}
			}
		}

		return nready;
	}
	catch (...)
	{
		printf("Caught poll");
	}

	return -1;
}

// copied from MSDN: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/eventlog/base/adding_a_source_to_the_registry.asp

BOOL AddEventSource
(
	LPTSTR pszSrcName, // event source name
	DWORD  dwNum       // number of categories
)
{
	// Work out the executable file name, to register ourselves
	// as the event source

	WCHAR cmd[MAX_PATH];
	DWORD len = GetModuleFileNameW(NULL, cmd, MAX_PATH);

	if (len == 0)
	{
		::syslog(LOG_ERR, "Failed to get the program file name: %s",
			GetErrorMessage(GetLastError()).c_str());
		return FALSE;
	}

	// Create the event source as a subkey of the log. 

	std::string regkey("SYSTEM\\CurrentControlSet\\Services\\EventLog\\"
		"Application\\");
	regkey += pszSrcName; 
 
	HKEY hk;
	DWORD dwDisp;

	if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, regkey.c_str(), 
			 0, NULL, REG_OPTION_NON_VOLATILE,
			 KEY_WRITE, NULL, &hk, &dwDisp)) 
	{
		::syslog(LOG_ERR, "Failed to create the registry key: %s",
			GetErrorMessage(GetLastError()).c_str());
		return FALSE;
	}

	// Set the name of the message file. 
 
	if (RegSetValueExW(hk,                 // subkey handle 
			   L"EventMessageFile", // value name 
			   0,                  // must be zero 
			   REG_EXPAND_SZ,      // value type 
			   (LPBYTE)cmd,        // pointer to value data 
			   len*sizeof(WCHAR))) // data size
	{
		::syslog(LOG_ERR, "Failed to set the event message file: %s",
			GetErrorMessage(GetLastError()).c_str());
		RegCloseKey(hk); 
		return FALSE;
	}
 
	// Set the supported event types. 
 
	DWORD dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | 
		  EVENTLOG_INFORMATION_TYPE; 
 
	if (RegSetValueEx(hk,               // subkey handle 
			  "TypesSupported", // value name 
			  0,                // must be zero 
			  REG_DWORD,        // value type 
			  (LPBYTE) &dwData, // pointer to value data 
			  sizeof(DWORD)))   // length of value data 
	{
		::syslog(LOG_ERR, "Failed to set the supported types: %s",
			GetErrorMessage(GetLastError()).c_str());
		RegCloseKey(hk); 
		return FALSE;
	}
 
	// Set the category message file and number of categories.

	if (RegSetValueExW(hk,                    // subkey handle 
			   L"CategoryMessageFile", // value name 
			   0,                     // must be zero 
			   REG_EXPAND_SZ,         // value type 
			   (LPBYTE)cmd,           // pointer to value data 
			   len*sizeof(WCHAR)))    // data size
	{
		::syslog(LOG_ERR, "Failed to set the category message file: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		RegCloseKey(hk); 
		return FALSE;
	}
 
	if (RegSetValueEx(hk,              // subkey handle 
			  "CategoryCount", // value name 
			  0,               // must be zero 
			  REG_DWORD,       // value type 
			  (LPBYTE) &dwNum, // pointer to value data 
			  sizeof(DWORD)))  // length of value data 
	{
		::syslog(LOG_ERR, "Failed to set the category count: %s",
			GetErrorMessage(GetLastError()).c_str());
		RegCloseKey(hk); 
		return FALSE;
	}

	RegCloseKey(hk); 
	return TRUE;
}

static HANDLE gSyslogH = 0;
static bool sHaveWarnedEventLogFull = false;

void openlog(const char * daemonName, int, int)
{
	std::string nameStr = "Box Backup (";
	nameStr += daemonName;
	nameStr += ")";

	// register a default event source, so that we can
	// log errors with the process of adding or registering our own.
	gSyslogH = RegisterEventSource(
		NULL,        // uses local computer 
		nameStr.c_str()); // source name
	if (gSyslogH == NULL) 
	{
	}

	char* name = strdup(nameStr.c_str());
	BOOL success = AddEventSource(name, 0);
	free(name);

	if (!success)
	{
		::syslog(LOG_ERR, "Failed to add our own event source");
		return;
	}

	HANDLE newSyslogH = RegisterEventSource(NULL, nameStr.c_str());
	if (newSyslogH == NULL)
	{
		::syslog(LOG_ERR, "Failed to register our own event source: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		return;
	}

	DeregisterEventSource(gSyslogH);
	gSyslogH = newSyslogH;
}

void closelog(void)
{
	DeregisterEventSource(gSyslogH); 
}

void syslog(int loglevel, const char *frmt, ...)
{
	WORD errinfo;
	char buffer[4096];
	std::string sixfour(frmt);

	switch (loglevel)
	{
	case LOG_INFO:
		errinfo = EVENTLOG_INFORMATION_TYPE;
		break;
	case LOG_ERR:
		errinfo = EVENTLOG_ERROR_TYPE;
		break;
	case LOG_WARNING:
		errinfo = EVENTLOG_WARNING_TYPE;
		break;
	default:
		errinfo = EVENTLOG_WARNING_TYPE;
		break;
	}

	// taken from MSDN
	int sixfourpos;
	while ( (sixfourpos = (int)sixfour.find("%ll")) != -1 )
	{
		// maintain portability - change the 64 bit formater...
		std::string temp = sixfour.substr(0,sixfourpos);
		temp += "%I64";
		temp += sixfour.substr(sixfourpos+3, sixfour.length());
		sixfour = temp;
	}

	// printf("parsed string is:%s\r\n", sixfour.c_str());

	va_list args;
	va_start(args, frmt);

	int len = vsnprintf(buffer, sizeof(buffer)-1, sixfour.c_str(), args);
	assert(len >= 0);
	if (len < 0) 
	{
		printf("%s\r\n", buffer);
		fflush(stdout);
		return;
	}
	
	assert((size_t)len < sizeof(buffer));
	buffer[sizeof(buffer)-1] = 0;

	va_end(args);

	if (gSyslogH == 0)
	{
		printf("%s\r\n", buffer);
		fflush(stdout);
		return;
	}

	WCHAR* pWide = ConvertToWideString(buffer, CP_UTF8, false);
	// must delete[] pWide

	DWORD result;

	if (pWide == NULL)
	{
		std::string buffer2 = buffer;
		buffer2 += " (failed to convert string encoding)";
		LPCSTR strings[] = { buffer2.c_str(), NULL };

		result = ReportEventA(gSyslogH, // event log handle 
			errinfo,               // event type 
			0,                     // category zero 
			MSG_ERR,	       // event identifier - 
					       // we will call them all the same
			NULL,                  // no user security identifier 
			1,                     // one substitution string 
			0,                     // no data 
			strings,               // pointer to string array 
			NULL);                 // pointer to data 
	}
	else
	{
		LPCWSTR strings[] = { pWide, NULL };
		result = ReportEventW(gSyslogH, // event log handle 
			errinfo,               // event type 
			0,                     // category zero 
			MSG_ERR,	       // event identifier - 
					       // we will call them all the same
			NULL,                  // no user security identifier 
			1,                     // one substitution string 
			0,                     // no data 
			strings,               // pointer to string array 
			NULL);                 // pointer to data 
		delete [] pWide;
	}
		
	if (result == 0)
	{
		DWORD err = GetLastError();
		if (err == ERROR_LOG_FILE_FULL)
		{
			if (!sHaveWarnedEventLogFull)
			{
				printf("Unable to send message to Event Log "
					"(Event Log is full):\r\n");
				fflush(stdout);
				sHaveWarnedEventLogFull = TRUE;
			}
		}
		else
		{
			printf("Unable to send message to Event Log: %s:\r\n",
				GetErrorMessage(err).c_str());
			fflush(stdout);
		}
	}
	else
	{
		sHaveWarnedEventLogFull = false;
	}
}

int emu_chdir(const char* pDirName)
{
	/*
	std::string AbsPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pDirName);

	if (AbsPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return -1;
	}

	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
	*/

	WCHAR* pBuffer = ConvertUtf8ToWideString(pDirName);
	if (!pBuffer) return -1;

	int result = SetCurrentDirectoryW(pBuffer);
	delete [] pBuffer;

	if (result != 0) return 0;

	errno = EACCES;
	fprintf(stderr, "Failed to change directory to '%s': %s\n",
		pDirName, GetErrorMessage(GetLastError()).c_str());
	return -1;
}

char* emu_getcwd(char* pBuffer, int BufSize)
{
	DWORD len = GetCurrentDirectoryW(0, NULL);
	if (len == 0)
	{
		errno = EINVAL;
		return NULL;
	}

	if ((int)len > BufSize)
	{
		errno = ENAMETOOLONG;
		return NULL;
	}

	WCHAR* pWide = new WCHAR [len];
	if (!pWide)
	{
		errno = ENOMEM;
		return NULL;
	}

	DWORD result = GetCurrentDirectoryW(len, pWide);
	if (result <= 0 || result >= len)
	{
		errno = EACCES;
		delete [] pWide;
		return NULL;
	}

	char* pUtf8 = ConvertFromWideString(pWide, CP_UTF8);
	delete [] pWide;

	if (!pUtf8)
	{
		return NULL;
	}

	strncpy(pBuffer, pUtf8, BufSize - 1);
	pBuffer[BufSize - 1] = 0;
	delete [] pUtf8;

	return pBuffer;
}

int emu_mkdir(const char* pPathName)
{
	std::string AbsPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pPathName);

	if (AbsPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return -1;
	}

	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
	if (!pBuffer)
	{
		return -1;
	}

	BOOL result = CreateDirectoryW(pBuffer, NULL);
	delete [] pBuffer;

	if (!result)
	{
		errno = EACCES;
		return -1;
	}

	return 0;
}

int emu_link(const char* pOldPath, const char* pNewPath)
{
	std::string AbsOldPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pOldPath);

	if (AbsOldPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return -1;
	}

	std::string AbsNewPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pNewPath);

	if (AbsNewPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return -1;
	}

	WCHAR* pOldBuffer = ConvertUtf8ToWideString(AbsOldPathWithUnicode.c_str());
	if (!pOldBuffer)
	{
		return -1;
	}

	WCHAR* pNewBuffer = ConvertUtf8ToWideString(AbsNewPathWithUnicode.c_str());
	if (!pNewBuffer)
	{
		delete [] pOldBuffer;
		return -1;
	}

	BOOL result = CreateHardLinkW(pNewBuffer, pOldBuffer, NULL);
	DWORD err = GetLastError();
	delete [] pOldBuffer;
	delete [] pNewBuffer;

	if (!result)
	{
		if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
		{
			errno = ENOENT;
		}
		else if (err == ERROR_SHARING_VIOLATION)
		{
			errno = EBUSY;
		}
		else if (err == ERROR_ACCESS_DENIED)
		{
			errno = EACCES;
		}
		else
		{
			::syslog(LOG_WARNING, "Failed to hardlink file "
				"'%s' to '%s': %s", pOldPath, pNewPath,
				GetErrorMessage(err).c_str());
			errno = ENOSYS;
		}

		return -1;
	}

	return 0;

}

int emu_unlink(const char* pFileName)
{
	std::string AbsPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pFileName);

	if (AbsPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return -1;
	}

	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
	if (!pBuffer)
	{
		return -1;
	}

	BOOL result = DeleteFileW(pBuffer);
	DWORD err = GetLastError();
	delete [] pBuffer;

	if (!result)
	{
		if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
		{
			errno = ENOENT;
		}
		else if (err == ERROR_SHARING_VIOLATION)
		{
			errno = EBUSY;
		}
		else if (err == ERROR_ACCESS_DENIED)
		{
			errno = EACCES;
		}
		else
		{
			::syslog(LOG_WARNING, "Failed to delete file "
				"'%s': %s", pFileName, 
				GetErrorMessage(err).c_str());
			errno = ENOSYS;
		}

		return -1;
	}

	return 0;
}

int emu_rename(const char* pOldFileName, const char* pNewFileName)
{
	std::string OldPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pOldFileName);

	if (OldPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		return -1;
	}

	WCHAR* pOldBuffer = ConvertUtf8ToWideString(OldPathWithUnicode.c_str());
	if (!pOldBuffer)
	{
		return -1;
	}

	std::string NewPathWithUnicode = 
		ConvertPathToAbsoluteUnicode(pNewFileName);

	if (NewPathWithUnicode.size() == 0)
	{
		// error already logged by ConvertPathToAbsoluteUnicode()
		delete [] pOldBuffer;
		return -1;
	}

	WCHAR* pNewBuffer = ConvertUtf8ToWideString(NewPathWithUnicode.c_str());
	if (!pNewBuffer)
	{
		delete [] pOldBuffer;
		return -1;
	}

	BOOL result = MoveFileW(pOldBuffer, pNewBuffer);
	DWORD err = GetLastError();
	delete [] pOldBuffer;
	delete [] pNewBuffer;

	if (!result)
	{
		if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
		{
			errno = ENOENT;
		}
		else if (err == ERROR_SHARING_VIOLATION)
		{
			errno = EBUSY;
		}
		else if (err == ERROR_ACCESS_DENIED)
		{
			errno = EACCES;
		}
		else
		{
			::syslog(LOG_WARNING, "Failed to rename file "
				"'%s' to '%s': %s", pOldFileName, pNewFileName,
				GetErrorMessage(err).c_str());
			errno = ENOSYS;
		}
		return -1;
	}

	return 0;
}

int console_read(char* pBuffer, size_t BufferSize)
{
	HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);

	if (hConsole == INVALID_HANDLE_VALUE)
	{
		::fprintf(stderr, "Failed to get a handle on standard input: "
			"%s", GetErrorMessage(GetLastError()).c_str());
		return -1;
	}

	size_t WideSize = BufferSize / 5;
	WCHAR* pWideBuffer = new WCHAR [WideSize + 1];

	if (!pWideBuffer)
	{
		::perror("Failed to allocate wide character buffer");
		return -1;
	}

	DWORD numCharsRead = 0;

	if (!ReadConsoleW(
			hConsole,
			pWideBuffer,
			WideSize, // will not be null terminated by ReadConsole
			&numCharsRead,
			NULL // reserved
		)) 
	{
		::fprintf(stderr, "Failed to read from console: %s\n",
			GetErrorMessage(GetLastError()).c_str());
		return -1;
	}

	pWideBuffer[numCharsRead] = 0;

	char* pUtf8 = ConvertFromWideString(pWideBuffer, GetConsoleCP());
	delete [] pWideBuffer;

	strncpy(pBuffer, pUtf8, BufferSize);
	delete [] pUtf8;

	return strlen(pBuffer);
}

int readv (int filedes, const struct iovec *vector, size_t count)
{
	int bytes = 0;
	
	for (size_t i = 0; i < count; i++)
	{
		int result = read(filedes, vector[i].iov_base, 
			vector[i].iov_len);
		if (result < 0)
		{
			return result;
		}
		bytes += result;
	}

	return bytes;
}

int writev(int filedes, const struct iovec *vector, size_t count)
{
	int bytes = 0;
	
	for (size_t i = 0; i < count; i++)
	{
		int result = write(filedes, vector[i].iov_base, 
			vector[i].iov_len);
		if (result < 0)
		{
			return result;
		}
		bytes += result;
	}

	return bytes;
}

// Need this for conversions. Works in UTC.
time_t ConvertFileTimeToTime_t(FILETIME *fileTime)
{
	SYSTEMTIME stUTC;
	struct tm timeinfo;

	// Convert the last-write time to local time.
	FileTimeToSystemTime(fileTime, &stUTC);

	memset(&timeinfo, 0, sizeof(timeinfo));	
	timeinfo.tm_sec = stUTC.wSecond;
	timeinfo.tm_min = stUTC.wMinute;
	timeinfo.tm_hour = stUTC.wHour;
	timeinfo.tm_mday = stUTC.wDay;
	timeinfo.tm_wday = stUTC.wDayOfWeek;
	timeinfo.tm_mon = stUTC.wMonth - 1;
	// timeinfo.tm_yday = ...;
	timeinfo.tm_year = stUTC.wYear - 1900;

	time_t retVal = _mkgmtime(&timeinfo);
	return retVal;
}

bool ConvertTime_tToFileTime(const time_t from, FILETIME *pTo)
{
	struct tm *time_breakdown = gmtime(&from);
	if (time_breakdown == NULL)
	{
		::syslog(LOG_ERR, "Error: failed to convert time format: "
			"%d is not a valid time\n", from);
		return false;
	}

	SYSTEMTIME stUTC;
	stUTC.wSecond       = time_breakdown->tm_sec;
	stUTC.wMinute       = time_breakdown->tm_min;
	stUTC.wHour         = time_breakdown->tm_hour;
	stUTC.wDay          = time_breakdown->tm_mday;
	stUTC.wDayOfWeek    = time_breakdown->tm_wday;
	stUTC.wMonth        = time_breakdown->tm_mon  + 1;
	stUTC.wYear         = time_breakdown->tm_year + 1900;
	stUTC.wMilliseconds = 0;

	// Convert the last-write time to local time.
	if (!SystemTimeToFileTime(&stUTC, pTo))
	{
		syslog(LOG_ERR, "Failed to convert between time formats: %s",
			GetErrorMessage(GetLastError()).c_str());
		return false;
	}

	return true;
}

#endif // WIN32