summaryrefslogtreecommitdiffstats
path: root/dbus/dbus-sysdeps-util-win.c
blob: 8608ad0e4964b4aa973bbd80cce2dee8912e7890 (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
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* dbus-sysdeps-util.c Would be in dbus-sysdeps.c, but not used in libdbus
 * 
 * Copyright (C) 2002, 2003, 2004, 2005  Red Hat, Inc.
 * Copyright (C) 2003 CodeFactory AB
 *
 * Licensed under the Academic Free License version 2.1
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#undef open

#define STRSAFE_NO_DEPRECATE

#include "dbus-sysdeps.h"
#include "dbus-internals.h"
#include "dbus-protocol.h"
#include "dbus-string.h"
#include "dbus-sysdeps.h"
#include "dbus-sysdeps-win.h"
#include "dbus-memory.h"

#include <io.h>
#include <sys/stat.h>
#include <aclapi.h>

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>

#if defined __MINGW32__ || (defined _MSC_VER && _MSC_VER <= 1310)
/* save string functions version
   using DBusString needs to much time because of uncommon api 
*/ 
#define errno_t int

errno_t strcat_s(char *dest, size_t size, char *src) 
{
  _dbus_assert(strlen(dest) + strlen(src) +1 <= size);
  strcat(dest,src);
  return 0;
}

errno_t strcpy_s(char *dest, size_t size, char *src)
{
  _dbus_assert(strlen(src) +1 <= size);
  strcpy(dest,src);  
  return 0;
}
#endif

/**
 * Does the chdir, fork, setsid, etc. to become a daemon process.
 *
 * @param pidfile #NULL, or pidfile to create
 * @param print_pid_fd file descriptor to print daemon's pid to, or -1 for none
 * @param error return location for errors
 * @returns #FALSE on failure
 */
dbus_bool_t
_dbus_become_daemon (const DBusString *pidfile,
                     DBusPipe         *print_pid_pipe,
                     DBusError        *error)
{
  return TRUE;
}

/**
 * Creates a file containing the process ID.
 *
 * @param filename the filename to write to
 * @param pid our process ID
 * @param error return location for errors
 * @returns #FALSE on failure
 */
dbus_bool_t
_dbus_write_pid_file (const DBusString *filename,
                      unsigned long     pid,
                      DBusError        *error)
{
  const char *cfilename;
  DBusFile file;
  FILE *f;

  cfilename = _dbus_string_get_const_data (filename);

  if (!_dbus_file_open(&file, cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644))
    {
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to open \"%s\": %s", cfilename,
                      _dbus_strerror (errno));
      return FALSE;
    }

  if ((f = fdopen (file.FDATA, "w")) == NULL)
    {
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to fdopen fd %d: %s", file.FDATA, _dbus_strerror (errno));
      _dbus_file_close (&file, NULL);
      return FALSE;
    }

  if (fprintf (f, "%lu\n", pid) < 0)
    {
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to write to \"%s\": %s", cfilename,
                      _dbus_strerror (errno));

      fclose (f);
      return FALSE;
    }

  if (fclose (f) == EOF)
    {
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to close \"%s\": %s", cfilename,
                      _dbus_strerror (errno));
      return FALSE;
    }

  return TRUE;
}

/**
 * Verify that after the fork we can successfully change to this user.
 *
 * @param user the username given in the daemon configuration
 * @returns #TRUE if username is valid
 */
dbus_bool_t
_dbus_verify_daemon_user (const char *user)
{
  return TRUE;
}

/**
 * Changes the user and group the bus is running as.
 *
 * @param user the user to become
 * @param error return location for errors
 * @returns #FALSE on failure
 */
dbus_bool_t
_dbus_change_to_daemon_user  (const char    *user,
                              DBusError     *error)
{
  return TRUE;
}

/**
 * Changes the user and group the bus is running as.
 *
 * @param uid the new user ID
 * @param gid the new group ID
 * @param error return location for errors
 * @returns #FALSE on failure
 */
dbus_bool_t
_dbus_change_identity  (dbus_uid_t     uid,
                        dbus_gid_t     gid,
                        DBusError     *error)
{
  return TRUE;
}

/** Checks if user is at the console
*
* @param username user to check
* @param error return location for errors
* @returns #TRUE is the user is at the consolei and there are no errors
*/
dbus_bool_t
_dbus_user_at_console(const char *username,
                      DBusError  *error)
{
#ifdef DBUS_WINCE
	return TRUE;
#else
  dbus_bool_t retval = FALSE;
  wchar_t *wusername;
  DWORD sid_length;
  PSID user_sid, console_user_sid;
  HWINSTA winsta;

  wusername = _dbus_win_utf8_to_utf16 (username, error);
  if (!wusername)
    return FALSE;

  // TODO remove
  if (!_dbus_win_account_to_sid (wusername, &user_sid, error))
    goto out0;

  /* Now we have the SID for username. Get the SID of the
   * user at the "console" (window station WinSta0)
   */
  if (!(winsta = OpenWindowStation ("WinSta0", FALSE, READ_CONTROL)))
    {
      _dbus_win_set_error_from_win_error (error, GetLastError ());
      goto out2;
    }

  sid_length = 0;
  GetUserObjectInformation (winsta, UOI_USER_SID,
                            NULL, 0, &sid_length);
  if (sid_length == 0)
    {
      /* Nobody is logged on */
      goto out2;
    }

  if (sid_length < 0 || sid_length > 1000)
    {
      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID length");
      goto out3;
    }

  console_user_sid = dbus_malloc (sid_length);
  if (!console_user_sid)
    {
      _DBUS_SET_OOM (error);
      goto out3;
    }

  if (!GetUserObjectInformation (winsta, UOI_USER_SID,
                                 console_user_sid, sid_length, &sid_length))
    {
      _dbus_win_set_error_from_win_error (error, GetLastError ());
      goto out4;
    }

  if (!IsValidSid (console_user_sid))
    {
      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
      goto out4;
    }

  retval = EqualSid (user_sid, console_user_sid);

out4:
  dbus_free (console_user_sid);
out3:
  CloseWindowStation (winsta);
out2:
  dbus_free (user_sid);
out0:
  dbus_free (wusername);

  return retval;
#endif //DBUS_WINCE
}

/**
 * Removes a directory; Directory must be empty
 * 
 * @param filename directory filename
 * @param error initialized error object
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_delete_directory (const DBusString *filename,
                        DBusError        *error)
{
  const char *filename_c;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  filename_c = _dbus_string_get_const_data (filename);

  if (rmdir (filename_c) != 0)
    {
      dbus_set_error (error, DBUS_ERROR_FAILED,
                      "Failed to remove directory %s: %s\n",
                      filename_c, _dbus_strerror (errno));
      return FALSE;
    }

  return TRUE;
}

/** Installs a signal handler
 *
 * @param sig the signal to handle
 * @param handler the handler
 */
void
_dbus_set_signal_handler (int               sig,
                          DBusSignalHandler handler)
{
  _dbus_verbose ("_dbus_set_signal_handler() has to be implemented\n");
}

/** Checks if a file exists
*
* @param file full path to the file
* @returns #TRUE if file exists
*/
dbus_bool_t 
_dbus_file_exists (const char *file)
{
  HANDLE h = CreateFile(
          file, /* LPCTSTR lpFileName*/
          0, /* DWORD dwDesiredAccess */
          0, /* DWORD dwShareMode*/
          NULL, /* LPSECURITY_ATTRIBUTES lpSecurityAttributes */
          OPEN_EXISTING, /* DWORD dwCreationDisposition */
          FILE_ATTRIBUTE_NORMAL, /* DWORD dwFlagsAndAttributes */
          NULL /* HANDLE hTemplateFile */
        );

    /* file not found, use local copy of session.conf  */
    if (h != INVALID_HANDLE_VALUE && GetLastError() != ERROR_PATH_NOT_FOUND)
      {
        CloseHandle(h);
        return TRUE;
      }
    else
        return FALSE;  
}

/**
 * stat() wrapper.
 *
 * @param filename the filename to stat
 * @param statbuf the stat info to fill in
 * @param error return location for error
 * @returns #FALSE if error was set
 */
dbus_bool_t
_dbus_stat(const DBusString *filename,
           DBusStat         *statbuf,
           DBusError        *error)
{
#ifdef DBUS_WINCE
	return TRUE;
	//TODO
#else
  const char *filename_c;
#if !defined(DBUS_WIN) && !defined(DBUS_WINCE)

  struct stat sb;
#else

  WIN32_FILE_ATTRIBUTE_DATA wfad;
  char *lastdot;
  DWORD rc;
  PSID owner_sid, group_sid;
  PSECURITY_DESCRIPTOR sd;
#endif

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  filename_c = _dbus_string_get_const_data (filename);

  if (!GetFileAttributesEx (filename_c, GetFileExInfoStandard, &wfad))
    {
      _dbus_win_set_error_from_win_error (error, GetLastError ());
      return FALSE;
    }

  if (wfad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    statbuf->mode = _S_IFDIR;
  else
    statbuf->mode = _S_IFREG;

  statbuf->mode |= _S_IREAD;
  if (wfad.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
    statbuf->mode |= _S_IWRITE;

  lastdot = strrchr (filename_c, '.');
  if (lastdot && stricmp (lastdot, ".exe") == 0)
    statbuf->mode |= _S_IEXEC;

  statbuf->mode |= (statbuf->mode & 0700) >> 3;
  statbuf->mode |= (statbuf->mode & 0700) >> 6;

  statbuf->nlink = 1;

  sd = NULL;
  rc = GetNamedSecurityInfo ((char *) filename_c, SE_FILE_OBJECT,
                             OWNER_SECURITY_INFORMATION |
                             GROUP_SECURITY_INFORMATION,
                             &owner_sid, &group_sid,
                             NULL, NULL,
                             &sd);
  if (rc != ERROR_SUCCESS)
    {
      _dbus_win_set_error_from_win_error (error, rc);
      if (sd != NULL)
        LocalFree (sd);
      return FALSE;
    }

#ifdef ENABLE_UID_TO_SID
  /* FIXME */
  statbuf->uid = _dbus_win_sid_to_uid_t (owner_sid);
  statbuf->gid = _dbus_win_sid_to_uid_t (group_sid);
#endif

  LocalFree (sd);

  statbuf->size = ((dbus_int64_t) wfad.nFileSizeHigh << 32) + wfad.nFileSizeLow;

  statbuf->atime =
    (((dbus_int64_t) wfad.ftLastAccessTime.dwHighDateTime << 32) +
     wfad.ftLastAccessTime.dwLowDateTime) / 10000000 - DBUS_INT64_CONSTANT (116444736000000000);

  statbuf->mtime =
    (((dbus_int64_t) wfad.ftLastWriteTime.dwHighDateTime << 32) +
     wfad.ftLastWriteTime.dwLowDateTime) / 10000000 - DBUS_INT64_CONSTANT (116444736000000000);

  statbuf->ctime =
    (((dbus_int64_t) wfad.ftCreationTime.dwHighDateTime << 32) +
     wfad.ftCreationTime.dwLowDateTime) / 10000000 - DBUS_INT64_CONSTANT (116444736000000000);

  return TRUE;
#endif //DBUS_WINCE
}


#ifdef HAVE_DIRENT_H

// mingw ships with dirent.h
#include <dirent.h>
#define _dbus_opendir opendir
#define _dbus_readdir readdir
#define _dbus_closedir closedir

#else

#ifdef HAVE_IO_H
#include <io.h> // win32 file functions
#endif

#include <sys/types.h>
#include <stdlib.h>

/* This file is part of the KDE project
Copyright (C) 2000 Werner Almesberger

libc/sys/linux/sys/dirent.h - Directory entry as returned by readdir

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public License
along with this program; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#define HAVE_NO_D_NAMLEN	/* no struct dirent->d_namlen */
#define HAVE_DD_LOCK  		/* have locking mechanism */

#define MAXNAMLEN 255		/* sizeof(struct dirent.d_name)-1 */

#define __dirfd(dir) (dir)->dd_fd

/* struct dirent - same as Unix */
struct dirent
  {
    long d_ino;                    /* inode (always 1 in WIN32) */
    off_t d_off;                /* offset to this dirent */
    unsigned short d_reclen;    /* length of d_name */
    char d_name[_MAX_FNAME+1];    /* filename (null terminated) */
  };

/* typedef DIR - not the same as Unix */
typedef struct
  {
    long handle;                /* _findfirst/_findnext handle */
    short offset;                /* offset into directory */
    short finished;             /* 1 if there are not more files */
    struct _finddata_t fileinfo;  /* from _findfirst/_findnext */
    char *dir;                  /* the dir we are reading */
    struct dirent dent;         /* the dirent to return */
  }
DIR;

/**********************************************************************
* Implement dirent-style opendir/readdir/closedir on Window 95/NT
*
* Functions defined are opendir(), readdir() and closedir() with the
* same prototypes as the normal dirent.h implementation.
*
* Does not implement telldir(), seekdir(), rewinddir() or scandir().
* The dirent struct is compatible with Unix, except that d_ino is
* always 1 and d_off is made up as we go along.
*
* The DIR typedef is not compatible with Unix.
**********************************************************************/

DIR * _dbus_opendir(const char *dir)
{
  DIR *dp;
  char *filespec;
  long handle;
  int index;

  filespec = malloc(strlen(dir) + 2 + 1);
  strcpy(filespec, dir);
  index = strlen(filespec) - 1;
  if (index >= 0 && (filespec[index] == '/' || filespec[index] == '\\'))
    filespec[index] = '\0';
  strcat(filespec, "\\*");

  dp = (DIR *)malloc(sizeof(DIR));
  dp->offset = 0;
  dp->finished = 0;
  dp->dir = strdup(dir);

  if ((handle = _findfirst(filespec, &(dp->fileinfo))) < 0)
    {
      if (errno == ENOENT)
        dp->finished = 1;
      else
        return NULL;
    }

  dp->handle = handle;
  free(filespec);

  return dp;
}

struct dirent * _dbus_readdir(DIR *dp)
  {
    if (!dp || dp->finished)
      return NULL;

    if (dp->offset != 0)
      {
        if (_findnext(dp->handle, &(dp->fileinfo)) < 0)
          {
            dp->finished = 1;
            errno = 0;
            return NULL;
          }
      }
    dp->offset++;

    strncpy(dp->dent.d_name, dp->fileinfo.name, _MAX_FNAME);
    dp->dent.d_ino = 1;
    dp->dent.d_reclen = strlen(dp->dent.d_name);
    dp->dent.d_off = dp->offset;

    return &(dp->dent);
  }


int _dbus_closedir(DIR *dp)
{
  if (!dp)
    return 0;
  _findclose(dp->handle);
  if (dp->dir)
    free(dp->dir);
  if (dp)
    free(dp);

  return 0;
}

#endif //#ifdef HAVE_DIRENT_H

/**
 * Internals of directory iterator
 */
struct DBusDirIter
  {
    DIR *d; /**< The DIR* from opendir() */

  };

/**
 * Open a directory to iterate over.
 *
 * @param filename the directory name
 * @param error exception return object or #NULL
 * @returns new iterator, or #NULL on error
 */
DBusDirIter*
_dbus_directory_open (const DBusString *filename,
                      DBusError        *error)
{
  DIR *d;
  DBusDirIter *iter;
  const char *filename_c;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  filename_c = _dbus_string_get_const_data (filename);

  d = _dbus_opendir (filename_c);
  if (d == NULL)
    {
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to read directory \"%s\": %s",
                      filename_c,
                      _dbus_strerror (errno));
      return NULL;
    }
  iter = dbus_new0 (DBusDirIter, 1);
  if (iter == NULL)
    {
      _dbus_closedir (d);
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
                      "Could not allocate memory for directory iterator");
      return NULL;
    }

  iter->d = d;

  return iter;
}

/**
 * Get next file in the directory. Will not return "." or ".."  on
 * UNIX. If an error occurs, the contents of "filename" are
 * undefined. The error is never set if the function succeeds.
 *
 * @todo for thread safety, I think we have to use
 * readdir_r(). (GLib has the same issue, should file a bug.)
 *
 * @param iter the iterator
 * @param filename string to be set to the next file in the dir
 * @param error return location for error
 * @returns #TRUE if filename was filled in with a new filename
 */
dbus_bool_t
_dbus_directory_get_next_file (DBusDirIter      *iter,
                               DBusString       *filename,
                               DBusError        *error)
{
  struct dirent *ent;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

again:
  errno = 0;
  ent = _dbus_readdir (iter->d);
  if (ent == NULL)
    {
      if (errno != 0)
        dbus_set_error (error,
                        _dbus_error_from_errno (errno),
                        "%s", _dbus_strerror (errno));
      return FALSE;
    }
  else if (ent->d_name[0] == '.' &&
           (ent->d_name[1] == '\0' ||
            (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
    goto again;
  else
    {
      _dbus_string_set_length (filename, 0);
      if (!_dbus_string_append (filename, ent->d_name))
        {
          dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
                          "No memory to read directory entry");
          return FALSE;
        }
      else
        return TRUE;
    }
}

/**
 * Closes a directory iteration.
 */
void
_dbus_directory_close (DBusDirIter *iter)
{
  _dbus_closedir (iter->d);
  dbus_free (iter);
}

/**
 * Checks whether the filename is an absolute path
 *
 * @param filename the filename
 * @returns #TRUE if an absolute path
 */
dbus_bool_t
_dbus_path_is_absolute (const DBusString *filename)
{
  if (_dbus_string_get_length (filename) > 0)
    return _dbus_string_get_byte (filename, 1) == ':'
           || _dbus_string_get_byte (filename, 0) == '\\'
           || _dbus_string_get_byte (filename, 0) == '/';
  else
    return FALSE;
}

/** @} */ /* End of DBusInternalsUtils functions */

/**
 * @addtogroup DBusString
 *
 * @{
 */
/**
 * Get the directory name from a complete filename
 * @param filename the filename
 * @param dirname string to append directory name to
 * @returns #FALSE if no memory
 */
dbus_bool_t
_dbus_string_get_dirname(const DBusString *filename,
                         DBusString       *dirname)
{
  int sep;

  _dbus_assert (filename != dirname);
  _dbus_assert (filename != NULL);
  _dbus_assert (dirname != NULL);

  /* Ignore any separators on the end */
  sep = _dbus_string_get_length (filename);
  if (sep == 0)
    return _dbus_string_append (dirname, "."); /* empty string passed in */

  while (sep > 0 &&
         (_dbus_string_get_byte (filename, sep - 1) == '/' ||
          _dbus_string_get_byte (filename, sep - 1) == '\\'))
    --sep;

  _dbus_assert (sep >= 0);

  if (sep == 0 ||
      (sep == 2 &&
       _dbus_string_get_byte (filename, 1) == ':' &&
       isalpha (_dbus_string_get_byte (filename, 0))))
    return _dbus_string_copy_len (filename, 0, sep + 1,
                                  dirname, _dbus_string_get_length (dirname));

  {
    int sep1, sep2;
    _dbus_string_find_byte_backward (filename, sep, '/', &sep1);
    _dbus_string_find_byte_backward (filename, sep, '\\', &sep2);

    sep = MAX (sep1, sep2);
  }
  if (sep < 0)
    return _dbus_string_append (dirname, ".");

  while (sep > 0 &&
         (_dbus_string_get_byte (filename, sep - 1) == '/' ||
          _dbus_string_get_byte (filename, sep - 1) == '\\'))
    --sep;

  _dbus_assert (sep >= 0);

  if ((sep == 0 ||
       (sep == 2 &&
        _dbus_string_get_byte (filename, 1) == ':' &&
        isalpha (_dbus_string_get_byte (filename, 0))))
      &&
      (_dbus_string_get_byte (filename, sep) == '/' ||
       _dbus_string_get_byte (filename, sep) == '\\'))
    return _dbus_string_copy_len (filename, 0, sep + 1,
                                  dirname, _dbus_string_get_length (dirname));
  else
    return _dbus_string_copy_len (filename, 0, sep - 0,
                                  dirname, _dbus_string_get_length (dirname));
}


/**
 * Checks to see if the UNIX user ID matches the UID of
 * the process. Should always return #FALSE on Windows.
 *
 * @param uid the UNIX user ID
 * @returns #TRUE if this uid owns the process.
 */
dbus_bool_t
_dbus_unix_user_is_process_owner (dbus_uid_t uid)
{
  return FALSE;
}

/*=====================================================================
  unix emulation functions - should be removed sometime in the future
 =====================================================================*/

/**
 * Checks to see if the UNIX user ID is at the console.
 * Should always fail on Windows (set the error to
 * #DBUS_ERROR_NOT_SUPPORTED).
 *
 * @param uid UID of person to check 
 * @param error return location for errors
 * @returns #TRUE if the UID is the same as the console user and there are no errors
 */
dbus_bool_t
_dbus_unix_user_is_at_console (dbus_uid_t         uid,
                               DBusError         *error)
{
  return FALSE;
}


/**
 * Parse a UNIX group from the bus config file. On Windows, this should
 * simply always fail (just return #FALSE).
 *
 * @param groupname the groupname text
 * @param gid_p place to return the gid
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_parse_unix_group_from_config (const DBusString  *groupname,
                                    dbus_gid_t        *gid_p)
{
  return FALSE;
}

/**
 * Parse a UNIX user from the bus config file. On Windows, this should
 * simply always fail (just return #FALSE).
 *
 * @param username the username text
 * @param uid_p place to return the uid
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_parse_unix_user_from_config (const DBusString  *username,
                                   dbus_uid_t        *uid_p)
{
  return FALSE;
}


/**
 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
 * just calls _dbus_groups_from_uid(). On Windows, should always
 * fail since we don't know any UNIX groups.
 *
 * @param uid the UID
 * @param group_ids return location for array of group IDs
 * @param n_group_ids return location for length of returned array
 * @returns #TRUE if the UID existed and we got some credentials
 */
dbus_bool_t
_dbus_unix_groups_from_uid (dbus_uid_t            uid,
                            dbus_gid_t          **group_ids,
                            int                  *n_group_ids)
{
  return FALSE;
}



/** @} */ /* DBusString stuff */

/************************************************************************
 
 error handling
 
 ************************************************************************/


/**
 * Assigns an error name and message corresponding to a Win32 error
 * code to a DBusError. Does nothing if error is #NULL.
 *
 * @param error the error.
 * @param code the Win32 error code
 */
void
_dbus_win_set_error_from_win_error (DBusError *error,
                                    int        code)
{
  char *msg;

  /* As we want the English message, use the A API */
  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_IGNORE_INSERTS |
                  FORMAT_MESSAGE_FROM_SYSTEM,
                  NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
                  (LPTSTR) &msg, 0, NULL);
  if (msg)
    {
      char *msg_copy;

      msg_copy = dbus_malloc (strlen (msg));
      strcpy (msg_copy, msg);
      LocalFree (msg);

      dbus_set_error (error, "win32.error", "%s", msg_copy);
    }
  else
    dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
}

void
_dbus_win_warn_win_error (const char *message,
                          int         code)
{
  DBusError error = DBUS_ERROR_INIT;

  _dbus_win_set_error_from_win_error (&error, code);
  _dbus_warn ("%s: %s\n", message, error.message);
  dbus_error_free (&error);
}

/**
 * A wrapper around strerror() because some platforms
 * may be lame and not have strerror().
 *
 * @param error_number errno.
 * @returns error description.
 */
const char*
_dbus_strerror (int error_number)
{
#ifdef DBUS_WINCE
  // TODO
  return "unknown";
#else
  const char *msg;

  switch (error_number)
    {
    case WSAEINTR:
      return "Interrupted function call";
    case WSAEACCES:
      return "Permission denied";
    case WSAEFAULT:
      return "Bad address";
    case WSAEINVAL:
      return "Invalid argument";
    case WSAEMFILE:
      return "Too many open files";
    case WSAEWOULDBLOCK:
      return "Resource temporarily unavailable";
    case WSAEINPROGRESS:
      return "Operation now in progress";
    case WSAEALREADY:
      return "Operation already in progress";
    case WSAENOTSOCK:
      return "Socket operation on nonsocket";
    case WSAEDESTADDRREQ:
      return "Destination address required";
    case WSAEMSGSIZE:
      return "Message too long";
    case WSAEPROTOTYPE:
      return "Protocol wrong type for socket";
    case WSAENOPROTOOPT:
      return "Bad protocol option";
    case WSAEPROTONOSUPPORT:
      return "Protocol not supported";
    case WSAESOCKTNOSUPPORT:
      return "Socket type not supported";
    case WSAEOPNOTSUPP:
      return "Operation not supported";
    case WSAEPFNOSUPPORT:
      return "Protocol family not supported";
    case WSAEAFNOSUPPORT:
      return "Address family not supported by protocol family";
    case WSAEADDRINUSE:
      return "Address already in use";
    case WSAEADDRNOTAVAIL:
      return "Cannot assign requested address";
    case WSAENETDOWN:
      return "Network is down";
    case WSAENETUNREACH:
      return "Network is unreachable";
    case WSAENETRESET:
      return "Network dropped connection on reset";
    case WSAECONNABORTED:
      return "Software caused connection abort";
    case WSAECONNRESET:
      return "Connection reset by peer";
    case WSAENOBUFS:
      return "No buffer space available";
    case WSAEISCONN:
      return "Socket is already connected";
    case WSAENOTCONN:
      return "Socket is not connected";
    case WSAESHUTDOWN:
      return "Cannot send after socket shutdown";
    case WSAETIMEDOUT:
      return "Connection timed out";
    case WSAECONNREFUSED:
      return "Connection refused";
    case WSAEHOSTDOWN:
      return "Host is down";
    case WSAEHOSTUNREACH:
      return "No route to host";
    case WSAEPROCLIM:
      return "Too many processes";
    case WSAEDISCON:
      return "Graceful shutdown in progress";
    case WSATYPE_NOT_FOUND:
      return "Class type not found";
    case WSAHOST_NOT_FOUND:
      return "Host not found";
    case WSATRY_AGAIN:
      return "Nonauthoritative host not found";
    case WSANO_RECOVERY:
      return "This is a nonrecoverable error";
    case WSANO_DATA:
      return "Valid name, no data record of requested type";
    case WSA_INVALID_HANDLE:
      return "Specified event object handle is invalid";
    case WSA_INVALID_PARAMETER:
      return "One or more parameters are invalid";
    case WSA_IO_INCOMPLETE:
      return "Overlapped I/O event object not in signaled state";
    case WSA_IO_PENDING:
      return "Overlapped operations will complete later";
    case WSA_NOT_ENOUGH_MEMORY:
      return "Insufficient memory available";
    case WSA_OPERATION_ABORTED:
      return "Overlapped operation aborted";
#ifdef WSAINVALIDPROCTABLE

    case WSAINVALIDPROCTABLE:
      return "Invalid procedure table from service provider";
#endif
#ifdef WSAINVALIDPROVIDER

    case WSAINVALIDPROVIDER:
      return "Invalid service provider version number";
#endif
#ifdef WSAPROVIDERFAILEDINIT

    case WSAPROVIDERFAILEDINIT:
      return "Unable to initialize a service provider";
#endif

    case WSASYSCALLFAILURE:
      return "System call failure";
    }
  msg = strerror (error_number);
  if (msg == NULL)
    msg = "unknown";

  return msg;
#endif //DBUS_WINCE
}



/* lan manager error codes */
const char*
_dbus_lm_strerror(int error_number)
{
#ifdef DBUS_WINCE
  // TODO
  return "unknown";
#else
  const char *msg;
  switch (error_number)
    {
    case NERR_NetNotStarted:
      return "The workstation driver is not installed.";
    case NERR_UnknownServer:
      return "The server could not be located.";
    case NERR_ShareMem:
      return "An internal error occurred. The network cannot access a shared memory segment.";
    case NERR_NoNetworkResource:
      return "A network resource shortage occurred.";
    case NERR_RemoteOnly:
      return "This operation is not supported on workstations.";
    case NERR_DevNotRedirected:
      return "The device is not connected.";
    case NERR_ServerNotStarted:
      return "The Server service is not started.";
    case NERR_ItemNotFound:
      return "The queue is empty.";
    case NERR_UnknownDevDir:
      return "The device or directory does not exist.";
    case NERR_RedirectedPath:
      return "The operation is invalid on a redirected resource.";
    case NERR_DuplicateShare:
      return "The name has already been shared.";
    case NERR_NoRoom:
      return "The server is currently out of the requested resource.";
    case NERR_TooManyItems:
      return "Requested addition of items exceeds the maximum allowed.";
    case NERR_InvalidMaxUsers:
      return "The Peer service supports only two simultaneous users.";
    case NERR_BufTooSmall:
      return "The API return buffer is too small.";
    case NERR_RemoteErr:
      return "A remote API error occurred.";
    case NERR_LanmanIniError:
      return "An error occurred when opening or reading the configuration file.";
    case NERR_NetworkError:
      return "A general network error occurred.";
    case NERR_WkstaInconsistentState:
      return "The Workstation service is in an inconsistent state. Restart the computer before restarting the Workstation service.";
    case NERR_WkstaNotStarted:
      return "The Workstation service has not been started.";
    case NERR_BrowserNotStarted:
      return "The requested information is not available.";
    case NERR_InternalError:
      return "An internal error occurred.";
    case NERR_BadTransactConfig:
      return "The server is not configured for transactions.";
    case NERR_InvalidAPI:
      return "The requested API is not supported on the remote server.";
    case NERR_BadEventName:
      return "The event name is invalid.";
    case NERR_DupNameReboot:
      return "The computer name already exists on the network. Change it and restart the computer.";
    case NERR_CfgCompNotFound:
      return "The specified component could not be found in the configuration information.";
    case NERR_CfgParamNotFound:
      return "The specified parameter could not be found in the configuration information.";
    case NERR_LineTooLong:
      return "A line in the configuration file is too long.";
    case NERR_QNotFound:
      return "The printer does not exist.";
    case NERR_JobNotFound:
      return "The print job does not exist.";
    case NERR_DestNotFound:
      return "The printer destination cannot be found.";
    case NERR_DestExists:
      return "The printer destination already exists.";
    case NERR_QExists:
      return "The printer queue already exists.";
    case NERR_QNoRoom:
      return "No more printers can be added.";
    case NERR_JobNoRoom:
      return "No more print jobs can be added.";
    case NERR_DestNoRoom:
      return "No more printer destinations can be added.";
    case NERR_DestIdle:
      return "This printer destination is idle and cannot accept control operations.";
    case NERR_DestInvalidOp:
      return "This printer destination request contains an invalid control function.";
    case NERR_ProcNoRespond:
      return "The print processor is not responding.";
    case NERR_SpoolerNotLoaded:
      return "The spooler is not running.";
    case NERR_DestInvalidState:
      return "This operation cannot be performed on the print destination in its current state.";
    case NERR_QInvalidState:
      return "This operation cannot be performed on the printer queue in its current state.";
    case NERR_JobInvalidState:
      return "This operation cannot be performed on the print job in its current state.";
    case NERR_SpoolNoMemory:
      return "A spooler memory allocation failure occurred.";
    case NERR_DriverNotFound:
      return "The device driver does not exist.";
    case NERR_DataTypeInvalid:
      return "The data type is not supported by the print processor.";
    case NERR_ProcNotFound:
      return "The print processor is not installed.";
    case NERR_ServiceTableLocked:
      return "The service database is locked.";
    case NERR_ServiceTableFull:
      return "The service table is full.";
    case NERR_ServiceInstalled:
      return "The requested service has already been started.";
    case NERR_ServiceEntryLocked:
      return "The service does not respond to control actions.";
    case NERR_ServiceNotInstalled:
      return "The service has not been started.";
    case NERR_BadServiceName:
      return "The service name is invalid.";
    case NERR_ServiceCtlTimeout:
      return "The service is not responding to the control function.";
    case NERR_ServiceCtlBusy:
      return "The service control is busy.";
    case NERR_BadServiceProgName:
      return "The configuration file contains an invalid service program name.";
    case NERR_ServiceNotCtrl:
      return "The service could not be controlled in its present state.";
    case NERR_ServiceKillProc:
      return "The service ended abnormally.";
    case NERR_ServiceCtlNotValid:
      return "The requested pause or stop is not valid for this service.";
    case NERR_NotInDispatchTbl:
      return "The service control dispatcher could not find the service name in the dispatch table.";
    case NERR_BadControlRecv:
      return "The service control dispatcher pipe read failed.";
    case NERR_ServiceNotStarting:
      return "A thread for the new service could not be created.";
    case NERR_AlreadyLoggedOn:
      return "This workstation is already logged on to the local-area network.";
    case NERR_NotLoggedOn:
      return "The workstation is not logged on to the local-area network.";
    case NERR_BadUsername:
      return "The user name or group name parameter is invalid.";
    case NERR_BadPassword:
      return "The password parameter is invalid.";
    case NERR_UnableToAddName_W:
      return "@W The logon processor did not add the message alias.";
    case NERR_UnableToAddName_F:
      return "The logon processor did not add the message alias.";
    case NERR_UnableToDelName_W:
      return "@W The logoff processor did not delete the message alias.";
    case NERR_UnableToDelName_F:
      return "The logoff processor did not delete the message alias.";
    case NERR_LogonsPaused:
      return "Network logons are paused.";
    case NERR_LogonServerConflict:
      return "A centralized logon-server conflict occurred.";
    case NERR_LogonNoUserPath:
      return "The server is configured without a valid user path.";
    case NERR_LogonScriptError:
      return "An error occurred while loading or running the logon script.";
    case NERR_StandaloneLogon:
      return "The logon server was not specified. Your computer will be logged on as STANDALONE.";
    case NERR_LogonServerNotFound:
      return "The logon server could not be found.";
    case NERR_LogonDomainExists:
      return "There is already a logon domain for this computer.";
    case NERR_NonValidatedLogon:
      return "The logon server could not validate the logon.";
    case NERR_ACFNotFound:
      return "The security database could not be found.";
    case NERR_GroupNotFound:
      return "The group name could not be found.";
    case NERR_UserNotFound:
      return "The user name could not be found.";
    case NERR_ResourceNotFound:
      return "The resource name could not be found.";
    case NERR_GroupExists:
      return "The group already exists.";
    case NERR_UserExists:
      return "The user account already exists.";
    case NERR_ResourceExists:
      return "The resource permission list already exists.";
    case NERR_NotPrimary:
      return "This operation is only allowed on the primary domain controller of the domain.";
    case NERR_ACFNotLoaded:
      return "The security database has not been started.";
    case NERR_ACFNoRoom:
      return "There are too many names in the user accounts database.";
    case NERR_ACFFileIOFail:
      return "A disk I/O failure occurred.";
    case NERR_ACFTooManyLists:
      return "The limit of 64 entries per resource was exceeded.";
    case NERR_UserLogon:
      return "Deleting a user with a session is not allowed.";
    case NERR_ACFNoParent:
      return "The parent directory could not be located.";
    case NERR_CanNotGrowSegment:
      return "Unable to add to the security database session cache segment.";
    case NERR_SpeGroupOp:
      return "This operation is not allowed on this special group.";
    case NERR_NotInCache:
      return "This user is not cached in user accounts database session cache.";
    case NERR_UserInGroup:
      return "The user already belongs to this group.";
    case NERR_UserNotInGroup:
      return "The user does not belong to this group.";
    case NERR_AccountUndefined:
      return "This user account is undefined.";
    case NERR_AccountExpired:
      return "This user account has expired.";
    case NERR_InvalidWorkstation:
      return "The user is not allowed to log on from this workstation.";
    case NERR_InvalidLogonHours:
      return "The user is not allowed to log on at this time.";
    case NERR_PasswordExpired:
      return "The password of this user has expired.";
    case NERR_PasswordCantChange:
      return "The password of this user cannot change.";
    case NERR_PasswordHistConflict:
      return "This password cannot be used now.";
    case NERR_PasswordTooShort:
      return "The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.";
    case NERR_PasswordTooRecent:
      return "The password of this user is too recent to change.";
    case NERR_InvalidDatabase:
      return "The security database is corrupted.";
    case NERR_DatabaseUpToDate:
      return "No updates are necessary to this replicant network/local security database.";
    case NERR_SyncRequired:
      return "This replicant database is outdated; synchronization is required.";
    case NERR_UseNotFound:
      return "The network connection could not be found.";
    case NERR_BadAsgType:
      return "This asg_type is invalid.";
    case NERR_DeviceIsShared:
      return "This device is currently being shared.";
    case NERR_NoComputerName:
      return "The computer name could not be added as a message alias. The name may already exist on the network.";
    case NERR_MsgAlreadyStarted:
      return "The Messenger service is already started.";
    case NERR_MsgInitFailed:
      return "The Messenger service failed to start.";
    case NERR_NameNotFound:
      return "The message alias could not be found on the network.";
    case NERR_AlreadyForwarded:
      return "This message alias has already been forwarded.";
    case NERR_AddForwarded:
      return "This message alias has been added but is still forwarded.";
    case NERR_AlreadyExists:
      return "This message alias already exists locally.";
    case NERR_TooManyNames:
      return "The maximum number of added message aliases has been exceeded.";
    case NERR_DelComputerName:
      return "The computer name could not be deleted.";
    case NERR_LocalForward:
      return "Messages cannot be forwarded back to the same workstation.";
    case NERR_GrpMsgProcessor:
      return "An error occurred in the domain message processor.";
    case NERR_PausedRemote:
      return "The message was sent, but the recipient has paused the Messenger service.";
    case NERR_BadReceive:
      return "The message was sent but not received.";
    case NERR_NameInUse:
      return "The message alias is currently in use. Try again later.";
    case NERR_MsgNotStarted:
      return "The Messenger service has not been started.";
    case NERR_NotLocalName:
      return "The name is not on the local computer.";
    case NERR_NoForwardName:
      return "The forwarded message alias could not be found on the network.";
    case NERR_RemoteFull:
      return "The message alias table on the remote station is full.";
    case NERR_NameNotForwarded:
      return "Messages for this alias are not currently being forwarded.";
    case NERR_TruncatedBroadcast:
      return "The broadcast message was truncated.";
    case NERR_InvalidDevice:
      return "This is an invalid device name.";
    case NERR_WriteFault:
      return "A write fault occurred.";
    case NERR_DuplicateName:
      return "A duplicate message alias exists on the network.";
    case NERR_DeleteLater:
      return "@W This message alias will be deleted later.";
    case NERR_IncompleteDel:
      return "The message alias was not successfully deleted from all networks.";
    case NERR_MultipleNets:
      return "This operation is not supported on computers with multiple networks.";
    case NERR_NetNameNotFound:
      return "This shared resource does not exist.";
    case NERR_DeviceNotShared:
      return "This device is not shared.";
    case NERR_ClientNameNotFound:
      return "A session does not exist with that computer name.";
    case NERR_FileIdNotFound:
      return "There is not an open file with that identification number.";
    case NERR_ExecFailure:
      return "A failure occurred when executing a remote administration command.";
    case NERR_TmpFile:
      return "A failure occurred when opening a remote temporary file.";
    case NERR_TooMuchData:
      return "The data returned from a remote administration command has been truncated to 64K.";
    case NERR_DeviceShareConflict:
      return "This device cannot be shared as both a spooled and a non-spooled resource.";
    case NERR_BrowserTableIncomplete:
      return "The information in the list of servers may be incorrect.";
    case NERR_NotLocalDomain:
      return "The computer is not active in this domain.";
#ifdef NERR_IsDfsShare

    case NERR_IsDfsShare:
      return "The share must be removed from the Distributed File System before it can be deleted.";
#endif

    case NERR_DevInvalidOpCode:
      return "The operation is invalid for this device.";
    case NERR_DevNotFound:
      return "This device cannot be shared.";
    case NERR_DevNotOpen:
      return "This device was not open.";
    case NERR_BadQueueDevString:
      return "This device name list is invalid.";
    case NERR_BadQueuePriority:
      return "The queue priority is invalid.";
    case NERR_NoCommDevs:
      return "There are no shared communication devices.";
    case NERR_QueueNotFound:
      return "The queue you specified does not exist.";
    case NERR_BadDevString:
      return "This list of devices is invalid.";
    case NERR_BadDev:
      return "The requested device is invalid.";
    case NERR_InUseBySpooler:
      return "This device is already in use by the spooler.";
    case NERR_CommDevInUse:
      return "This device is already in use as a communication device.";
    case NERR_InvalidComputer:
      return "This computer name is invalid.";
    case NERR_MaxLenExceeded:
      return "The string and prefix specified are too long.";
    case NERR_BadComponent:
      return "This path component is invalid.";
    case NERR_CantType:
      return "Could not determine the type of input.";
    case NERR_TooManyEntries:
      return "The buffer for types is not big enough.";
    case NERR_ProfileFileTooBig:
      return "Profile files cannot exceed 64K.";
    case NERR_ProfileOffset:
      return "The start offset is out of range.";
    case NERR_ProfileCleanup:
      return "The system cannot delete current connections to network resources.";
    case NERR_ProfileUnknownCmd:
      return "The system was unable to parse the command line in this file.";
    case NERR_ProfileLoadErr:
      return "An error occurred while loading the profile file.";
    case NERR_ProfileSaveErr:
      return "@W Errors occurred while saving the profile file. The profile was partially saved.";
    case NERR_LogOverflow:
      return "Log file %1 is full.";
    case NERR_LogFileChanged:
      return "This log file has changed between reads.";
    case NERR_LogFileCorrupt:
      return "Log file %1 is corrupt.";
    case NERR_SourceIsDir:
      return "The source path cannot be a directory.";
    case NERR_BadSource:
      return "The source path is illegal.";
    case NERR_BadDest:
      return "The destination path is illegal.";
    case NERR_DifferentServers:
      return "The source and destination paths are on different servers.";
    case NERR_RunSrvPaused:
      return "The Run server you requested is paused.";
    case NERR_ErrCommRunSrv:
      return "An error occurred when communicating with a Run server.";
    case NERR_ErrorExecingGhost:
      return "An error occurred when starting a background process.";
    case NERR_ShareNotFound:
      return "The shared resource you are connected to could not be found.";
    case NERR_InvalidLana:
      return "The LAN adapter number is invalid.";
    case NERR_OpenFiles:
      return "There are open files on the connection.";
    case NERR_ActiveConns:
      return "Active connections still exist.";
    case NERR_BadPasswordCore:
      return "This share name or password is invalid.";
    case NERR_DevInUse:
      return "The device is being accessed by an active process.";
    case NERR_LocalDrive:
      return "The drive letter is in use locally.";
    case NERR_AlertExists:
      return "The specified client is already registered for the specified event.";
    case NERR_TooManyAlerts:
      return "The alert table is full.";
    case NERR_NoSuchAlert:
      return "An invalid or nonexistent alert name was raised.";
    case NERR_BadRecipient:
      return "The alert recipient is invalid.";
    case NERR_AcctLimitExceeded:
      return "A user's session with this server has been deleted.";
    case NERR_InvalidLogSeek:
      return "The log file does not contain the requested record number.";
    case NERR_BadUasConfig:
      return "The user accounts database is not configured correctly.";
    case NERR_InvalidUASOp:
      return "This operation is not permitted when the Netlogon service is running.";
    case NERR_LastAdmin:
      return "This operation is not allowed on the last administrative account.";
    case NERR_DCNotFound:
      return "Could not find domain controller for this domain.";
    case NERR_LogonTrackingError:
      return "Could not set logon information for this user.";
    case NERR_NetlogonNotStarted:
      return "The Netlogon service has not been started.";
    case NERR_CanNotGrowUASFile:
      return "Unable to add to the user accounts database.";
    case NERR_TimeDiffAtDC:
      return "This server's clock is not synchronized with the primary domain controller's clock.";
    case NERR_PasswordMismatch:
      return "A password mismatch has been detected.";
    case NERR_NoSuchServer:
      return "The server identification does not specify a valid server.";
    case NERR_NoSuchSession:
      return "The session identification does not specify a valid session.";
    case NERR_NoSuchConnection:
      return "The connection identification does not specify a valid connection.";
    case NERR_TooManyServers:
      return "There is no space for another entry in the table of available servers.";
    case NERR_TooManySessions:
      return "The server has reached the maximum number of sessions it supports.";
    case NERR_TooManyConnections:
      return "The server has reached the maximum number of connections it supports.";
    case NERR_TooManyFiles:
      return "The server cannot open more files because it has reached its maximum number.";
    case NERR_NoAlternateServers:
      return "There are no alternate servers registered on this server.";
    case NERR_TryDownLevel:
      return "Try down-level (remote admin protocol) version of API instead.";
    case NERR_UPSDriverNotStarted:
      return "The UPS driver could not be accessed by the UPS service.";
    case NERR_UPSInvalidConfig:
      return "The UPS service is not configured correctly.";
    case NERR_UPSInvalidCommPort:
      return "The UPS service could not access the specified Comm Port.";
    case NERR_UPSSignalAsserted:
      return "The UPS indicated a line fail or low battery situation. Service not started.";
    case NERR_UPSShutdownFailed:
      return "The UPS service failed to perform a system shut down.";
    case NERR_BadDosRetCode:
      return "The program below returned an MS-DOS error code:";
    case NERR_ProgNeedsExtraMem:
      return "The program below needs more memory:";
    case NERR_BadDosFunction:
      return "The program below called an unsupported MS-DOS function:";
    case NERR_RemoteBootFailed:
      return "The workstation failed to boot.";
    case NERR_BadFileCheckSum:
      return "The file below is corrupt.";
    case NERR_NoRplBootSystem:
      return "No loader is specified in the boot-block definition file.";
    case NERR_RplLoadrNetBiosErr:
      return "NetBIOS returned an error:      The NCB and SMB are dumped above.";
    case NERR_RplLoadrDiskErr:
      return "A disk I/O error occurred.";
    case NERR_ImageParamErr:
      return "Image parameter substitution failed.";
    case NERR_TooManyImageParams:
      return "Too many image parameters cross disk sector boundaries.";
    case NERR_NonDosFloppyUsed:
      return "The image was not generated from an MS-DOS diskette formatted with /S.";
    case NERR_RplBootRestart:
      return "Remote boot will be restarted later.";
    case NERR_RplSrvrCallFailed:
      return "The call to the Remoteboot server failed.";
    case NERR_CantConnectRplSrvr:
      return "Cannot connect to the Remoteboot server.";
    case NERR_CantOpenImageFile:
      return "Cannot open image file on the Remoteboot server.";
    case NERR_CallingRplSrvr:
      return "Connecting to the Remoteboot server...";
    case NERR_StartingRplBoot:
      return "Connecting to the Remoteboot server...";
    case NERR_RplBootServiceTerm:
      return "Remote boot service was stopped; check the error log for the cause of the problem.";
    case NERR_RplBootStartFailed:
      return "Remote boot startup failed; check the error log for the cause of the problem.";
    case NERR_RPL_CONNECTED:
      return "A second connection to a Remoteboot resource is not allowed.";
    case NERR_BrowserConfiguredToNotRun:
      return "The browser service was configured with MaintainServerList=No.";
    case NERR_RplNoAdaptersStarted:
      return "Service failed to start since none of the network adapters started with this service.";
    case NERR_RplBadRegistry:
      return "Service failed to start due to bad startup information in the registry.";
    case NERR_RplBadDatabase:
      return "Service failed to start because its database is absent or corrupt.";
    case NERR_RplRplfilesShare:
      return "Service failed to start because RPLFILES share is absent.";
    case NERR_RplNotRplServer:
      return "Service failed to start because RPLUSER group is absent.";
    case NERR_RplCannotEnum:
      return "Cannot enumerate service records.";
    case NERR_RplWkstaInfoCorrupted:
      return "Workstation record information has been corrupted.";
    case NERR_RplWkstaNotFound:
      return "Workstation record was not found.";
    case NERR_RplWkstaNameUnavailable:
      return "Workstation name is in use by some other workstation.";
    case NERR_RplProfileInfoCorrupted:
      return "Profile record information has been corrupted.";
    case NERR_RplProfileNotFound:
      return "Profile record was not found.";
    case NERR_RplProfileNameUnavailable:
      return "Profile name is in use by some other profile.";
    case NERR_RplProfileNotEmpty:
      return "There are workstations using this profile.";
    case NERR_RplConfigInfoCorrupted:
      return "Configuration record information has been corrupted.";
    case NERR_RplConfigNotFound:
      return "Configuration record was not found.";
    case NERR_RplAdapterInfoCorrupted:
      return "Adapter ID record information has been corrupted.";
    case NERR_RplInternal:
      return "An internal service error has occurred.";
    case NERR_RplVendorInfoCorrupted:
      return "Vendor ID record information has been corrupted.";
    case NERR_RplBootInfoCorrupted:
      return "Boot block record information has been corrupted.";
    case NERR_RplWkstaNeedsUserAcct:
      return "The user account for this workstation record is missing.";
    case NERR_RplNeedsRPLUSERAcct:
      return "The RPLUSER local group could not be found.";
    case NERR_RplBootNotFound:
      return "Boot block record was not found.";
    case NERR_RplIncompatibleProfile:
      return "Chosen profile is incompatible with this workstation.";
    case NERR_RplAdapterNameUnavailable:
      return "Chosen network adapter ID is in use by some other workstation.";
    case NERR_RplConfigNotEmpty:
      return "There are profiles using this configuration.";
    case NERR_RplBootInUse:
      return "There are workstations, profiles, or configurations using this boot block.";
    case NERR_RplBackupDatabase:
      return "Service failed to backup Remoteboot database.";
    case NERR_RplAdapterNotFound:
      return "Adapter record was not found.";
    case NERR_RplVendorNotFound:
      return "Vendor record was not found.";
    case NERR_RplVendorNameUnavailable:
      return "Vendor name is in use by some other vendor record.";
    case NERR_RplBootNameUnavailable:
      return "(boot name, vendor ID) is in use by some other boot block record.";
    case NERR_RplConfigNameUnavailable:
      return "Configuration name is in use by some other configuration.";
    case NERR_DfsInternalCorruption:
      return "The internal database maintained by the Dfs service is corrupt.";
    case NERR_DfsVolumeDataCorrupt:
      return "One of the records in the internal Dfs database is corrupt.";
    case NERR_DfsNoSuchVolume:
      return "There is no DFS name whose entry path matches the input Entry Path.";
    case NERR_DfsVolumeAlreadyExists:
      return "A root or link with the given name already exists.";
    case NERR_DfsAlreadyShared:
      return "The server share specified is already shared in the Dfs.";
    case NERR_DfsNoSuchShare:
      return "The indicated server share does not support the indicated DFS namespace.";
    case NERR_DfsNotALeafVolume:
      return "The operation is not valid on this portion of the namespace.";
    case NERR_DfsLeafVolume:
      return "The operation is not valid on this portion of the namespace.";
    case NERR_DfsVolumeHasMultipleServers:
      return "The operation is ambiguous because the link has multiple servers.";
    case NERR_DfsCantCreateJunctionPoint:
      return "Unable to create a link.";
    case NERR_DfsServerNotDfsAware:
      return "The server is not Dfs Aware.";
    case NERR_DfsBadRenamePath:
      return "The specified rename target path is invalid.";
    case NERR_DfsVolumeIsOffline:
      return "The specified DFS link is offline.";
    case NERR_DfsNoSuchServer:
      return "The specified server is not a server for this link.";
    case NERR_DfsCyclicalName:
      return "A cycle in the Dfs name was detected.";
    case NERR_DfsNotSupportedInServerDfs:
      return "The operation is not supported on a server-based Dfs.";
    case NERR_DfsDuplicateService:
      return "This link is already supported by the specified server-share.";
    case NERR_DfsCantRemoveLastServerShare:
      return "Can't remove the last server-share supporting this root or link.";
    case NERR_DfsVolumeIsInterDfs:
      return "The operation is not supported for an Inter-DFS link.";
    case NERR_DfsInconsistent:
      return "The internal state of the Dfs Service has become inconsistent.";
    case NERR_DfsServerUpgraded:
      return "The Dfs Service has been installed on the specified server.";
    case NERR_DfsDataIsIdentical:
      return "The Dfs data being reconciled is identical.";
    case NERR_DfsCantRemoveDfsRoot:
      return "The DFS root cannot be deleted. Uninstall DFS if required.";
    case NERR_DfsChildOrParentInDfs:
      return "A child or parent directory of the share is already in a Dfs.";
    case NERR_DfsInternalError:
      return "Dfs internal error.";
      /* the following are not defined in mingw */
#if 0

    case NERR_SetupAlreadyJoined:
      return "This machine is already joined to a domain.";
    case NERR_SetupNotJoined:
      return "This machine is not currently joined to a domain.";
    case NERR_SetupDomainController:
      return "This machine is a domain controller and cannot be unjoined from a domain.";
    case NERR_DefaultJoinRequired:
      return "The destination domain controller does not support creating machine accounts in OUs.";
    case NERR_InvalidWorkgroupName:
      return "The specified workgroup name is invalid.";
    case NERR_NameUsesIncompatibleCodePage:
      return "The specified computer name is incompatible with the default language used on the domain controller.";
    case NERR_ComputerAccountNotFound:
      return "The specified computer account could not be found.";
    case NERR_PersonalSku:
      return "This version of Windows cannot be joined to a domain.";
    case NERR_PasswordMustChange:
      return "The password must change at the next logon.";
    case NERR_AccountLockedOut:
      return "The account is locked out.";
    case NERR_PasswordTooLong:
      return "The password is too long.";
    case NERR_PasswordNotComplexEnough:
      return "The password does not meet the complexity policy.";
    case NERR_PasswordFilterError:
      return "The password does not meet the requirements of the password filter DLLs.";
#endif

    }
  msg = strerror (error_number);
  if (msg == NULL)
    msg = "unknown";

  return msg;
#endif //DBUS_WINCE
}