Merge branch 'fd-passing'
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-util-win.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-sysdeps-util.c Would be in dbus-sysdeps.c, but not used in libdbus
3  * 
4  * Copyright (C) 2002, 2003, 2004, 2005  Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 2.1
8  * 
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22  *
23  */
24
25 #undef open
26
27 #define STRSAFE_NO_DEPRECATE
28
29 #include "dbus-sysdeps.h"
30 #include "dbus-internals.h"
31 #include "dbus-protocol.h"
32 #include "dbus-string.h"
33 #include "dbus-sysdeps.h"
34 #include "dbus-sysdeps-win.h"
35 #include "dbus-memory.h"
36
37 #include <io.h>
38 #include <sys/stat.h>
39 #include <aclapi.h>
40
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <fcntl.h>
44 #include <errno.h>
45
46 #if defined __MINGW32__ || (defined _MSC_VER && _MSC_VER <= 1310)
47 /* save string functions version
48    using DBusString needs to much time because of uncommon api 
49 */ 
50 #define errno_t int
51
52 errno_t strcat_s(char *dest, size_t size, char *src) 
53 {
54   _dbus_assert(strlen(dest) + strlen(src) +1 <= size);
55   strcat(dest,src);
56   return 0;
57 }
58
59 errno_t strcpy_s(char *dest, size_t size, char *src)
60 {
61   _dbus_assert(strlen(src) +1 <= size);
62   strcpy(dest,src);  
63   return 0;
64 }
65 #endif
66
67 /**
68  * Does the chdir, fork, setsid, etc. to become a daemon process.
69  *
70  * @param pidfile #NULL, or pidfile to create
71  * @param print_pid_fd file descriptor to print daemon's pid to, or -1 for none
72  * @param error return location for errors
73  * @param keep_umask #TRUE to keep the original umask
74  * @returns #FALSE on failure
75  */
76 dbus_bool_t
77 _dbus_become_daemon (const DBusString *pidfile,
78                      DBusPipe         *print_pid_pipe,
79                      DBusError        *error,
80                      dbus_bool_t       keep_umask)
81 {
82   return TRUE;
83 }
84
85 /**
86  * Creates a file containing the process ID.
87  *
88  * @param filename the filename to write to
89  * @param pid our process ID
90  * @param error return location for errors
91  * @returns #FALSE on failure
92  */
93 dbus_bool_t
94 _dbus_write_pid_file (const DBusString *filename,
95                       unsigned long     pid,
96                       DBusError        *error)
97 {
98   const char *cfilename;
99   DBusFile file;
100   FILE *f;
101
102   cfilename = _dbus_string_get_const_data (filename);
103
104   if (!_dbus_file_open(&file, cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644))
105     {
106       dbus_set_error (error, _dbus_error_from_errno (errno),
107                       "Failed to open \"%s\": %s", cfilename,
108                       _dbus_strerror (errno));
109       return FALSE;
110     }
111
112   if ((f = fdopen (file.FDATA, "w")) == NULL)
113     {
114       dbus_set_error (error, _dbus_error_from_errno (errno),
115                       "Failed to fdopen fd %d: %s", file.FDATA, _dbus_strerror (errno));
116       _dbus_file_close (&file, NULL);
117       return FALSE;
118     }
119
120   if (fprintf (f, "%lu\n", pid) < 0)
121     {
122       dbus_set_error (error, _dbus_error_from_errno (errno),
123                       "Failed to write to \"%s\": %s", cfilename,
124                       _dbus_strerror (errno));
125
126       fclose (f);
127       return FALSE;
128     }
129
130   if (fclose (f) == EOF)
131     {
132       dbus_set_error (error, _dbus_error_from_errno (errno),
133                       "Failed to close \"%s\": %s", cfilename,
134                       _dbus_strerror (errno));
135       return FALSE;
136     }
137
138   return TRUE;
139 }
140
141 /**
142  * Verify that after the fork we can successfully change to this user.
143  *
144  * @param user the username given in the daemon configuration
145  * @returns #TRUE if username is valid
146  */
147 dbus_bool_t
148 _dbus_verify_daemon_user (const char *user)
149 {
150   return TRUE;
151 }
152
153 /**
154  * Changes the user and group the bus is running as.
155  *
156  * @param user the user to become
157  * @param error return location for errors
158  * @returns #FALSE on failure
159  */
160 dbus_bool_t
161 _dbus_change_to_daemon_user  (const char    *user,
162                               DBusError     *error)
163 {
164   return TRUE;
165 }
166
167 /**
168  * Changes the user and group the bus is running as.
169  *
170  * @param uid the new user ID
171  * @param gid the new group ID
172  * @param error return location for errors
173  * @returns #FALSE on failure
174  */
175 dbus_bool_t
176 _dbus_change_identity  (dbus_uid_t     uid,
177                         dbus_gid_t     gid,
178                         DBusError     *error)
179 {
180   return TRUE;
181 }
182
183 /** Checks if user is at the console
184 *
185 * @param username user to check
186 * @param error return location for errors
187 * @returns #TRUE is the user is at the consolei and there are no errors
188 */
189 dbus_bool_t
190 _dbus_user_at_console(const char *username,
191                       DBusError  *error)
192 {
193 #ifdef DBUS_WINCE
194         return TRUE;
195 #else
196   dbus_bool_t retval = FALSE;
197   wchar_t *wusername;
198   DWORD sid_length;
199   PSID user_sid, console_user_sid;
200   HWINSTA winsta;
201
202   wusername = _dbus_win_utf8_to_utf16 (username, error);
203   if (!wusername)
204     return FALSE;
205
206   // TODO remove
207   if (!_dbus_win_account_to_sid (wusername, &user_sid, error))
208     goto out0;
209
210   /* Now we have the SID for username. Get the SID of the
211    * user at the "console" (window station WinSta0)
212    */
213   if (!(winsta = OpenWindowStation ("WinSta0", FALSE, READ_CONTROL)))
214     {
215       _dbus_win_set_error_from_win_error (error, GetLastError ());
216       goto out2;
217     }
218
219   sid_length = 0;
220   GetUserObjectInformation (winsta, UOI_USER_SID,
221                             NULL, 0, &sid_length);
222   if (sid_length == 0)
223     {
224       /* Nobody is logged on */
225       goto out2;
226     }
227
228   if (sid_length < 0 || sid_length > 1000)
229     {
230       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID length");
231       goto out3;
232     }
233
234   console_user_sid = dbus_malloc (sid_length);
235   if (!console_user_sid)
236     {
237       _DBUS_SET_OOM (error);
238       goto out3;
239     }
240
241   if (!GetUserObjectInformation (winsta, UOI_USER_SID,
242                                  console_user_sid, sid_length, &sid_length))
243     {
244       _dbus_win_set_error_from_win_error (error, GetLastError ());
245       goto out4;
246     }
247
248   if (!IsValidSid (console_user_sid))
249     {
250       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
251       goto out4;
252     }
253
254   retval = EqualSid (user_sid, console_user_sid);
255
256 out4:
257   dbus_free (console_user_sid);
258 out3:
259   CloseWindowStation (winsta);
260 out2:
261   dbus_free (user_sid);
262 out0:
263   dbus_free (wusername);
264
265   return retval;
266 #endif //DBUS_WINCE
267 }
268
269 /**
270  * Removes a directory; Directory must be empty
271  * 
272  * @param filename directory filename
273  * @param error initialized error object
274  * @returns #TRUE on success
275  */
276 dbus_bool_t
277 _dbus_delete_directory (const DBusString *filename,
278                         DBusError        *error)
279 {
280   const char *filename_c;
281
282   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
283
284   filename_c = _dbus_string_get_const_data (filename);
285
286   if (rmdir (filename_c) != 0)
287     {
288       dbus_set_error (error, DBUS_ERROR_FAILED,
289                       "Failed to remove directory %s: %s\n",
290                       filename_c, _dbus_strerror (errno));
291       return FALSE;
292     }
293
294   return TRUE;
295 }
296
297 /** Installs a signal handler
298  *
299  * @param sig the signal to handle
300  * @param handler the handler
301  */
302 void
303 _dbus_set_signal_handler (int               sig,
304                           DBusSignalHandler handler)
305 {
306   _dbus_verbose ("_dbus_set_signal_handler() has to be implemented\n");
307 }
308
309 /** Checks if a file exists
310 *
311 * @param file full path to the file
312 * @returns #TRUE if file exists
313 */
314 dbus_bool_t 
315 _dbus_file_exists (const char *file)
316 {
317   HANDLE h = CreateFile(
318           file, /* LPCTSTR lpFileName*/
319           0, /* DWORD dwDesiredAccess */
320           0, /* DWORD dwShareMode*/
321           NULL, /* LPSECURITY_ATTRIBUTES lpSecurityAttributes */
322           OPEN_EXISTING, /* DWORD dwCreationDisposition */
323           FILE_ATTRIBUTE_NORMAL, /* DWORD dwFlagsAndAttributes */
324           NULL /* HANDLE hTemplateFile */
325         );
326
327     /* file not found, use local copy of session.conf  */
328     if (h != INVALID_HANDLE_VALUE && GetLastError() != ERROR_PATH_NOT_FOUND)
329       {
330         CloseHandle(h);
331         return TRUE;
332       }
333     else
334         return FALSE;  
335 }
336
337 /**
338  * stat() wrapper.
339  *
340  * @param filename the filename to stat
341  * @param statbuf the stat info to fill in
342  * @param error return location for error
343  * @returns #FALSE if error was set
344  */
345 dbus_bool_t
346 _dbus_stat(const DBusString *filename,
347            DBusStat         *statbuf,
348            DBusError        *error)
349 {
350 #ifdef DBUS_WINCE
351         return TRUE;
352         //TODO
353 #else
354   const char *filename_c;
355 #if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
356
357   struct stat sb;
358 #else
359
360   WIN32_FILE_ATTRIBUTE_DATA wfad;
361   char *lastdot;
362   DWORD rc;
363   PSID owner_sid, group_sid;
364   PSECURITY_DESCRIPTOR sd;
365 #endif
366
367   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
368
369   filename_c = _dbus_string_get_const_data (filename);
370
371   if (!GetFileAttributesEx (filename_c, GetFileExInfoStandard, &wfad))
372     {
373       _dbus_win_set_error_from_win_error (error, GetLastError ());
374       return FALSE;
375     }
376
377   if (wfad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
378     statbuf->mode = _S_IFDIR;
379   else
380     statbuf->mode = _S_IFREG;
381
382   statbuf->mode |= _S_IREAD;
383   if (wfad.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
384     statbuf->mode |= _S_IWRITE;
385
386   lastdot = strrchr (filename_c, '.');
387   if (lastdot && stricmp (lastdot, ".exe") == 0)
388     statbuf->mode |= _S_IEXEC;
389
390   statbuf->mode |= (statbuf->mode & 0700) >> 3;
391   statbuf->mode |= (statbuf->mode & 0700) >> 6;
392
393   statbuf->nlink = 1;
394
395   sd = NULL;
396   rc = GetNamedSecurityInfo ((char *) filename_c, SE_FILE_OBJECT,
397                              OWNER_SECURITY_INFORMATION |
398                              GROUP_SECURITY_INFORMATION,
399                              &owner_sid, &group_sid,
400                              NULL, NULL,
401                              &sd);
402   if (rc != ERROR_SUCCESS)
403     {
404       _dbus_win_set_error_from_win_error (error, rc);
405       if (sd != NULL)
406         LocalFree (sd);
407       return FALSE;
408     }
409
410 #ifdef ENABLE_UID_TO_SID
411   /* FIXME */
412   statbuf->uid = _dbus_win_sid_to_uid_t (owner_sid);
413   statbuf->gid = _dbus_win_sid_to_uid_t (group_sid);
414 #endif
415
416   LocalFree (sd);
417
418   statbuf->size = ((dbus_int64_t) wfad.nFileSizeHigh << 32) + wfad.nFileSizeLow;
419
420   statbuf->atime =
421     (((dbus_int64_t) wfad.ftLastAccessTime.dwHighDateTime << 32) +
422      wfad.ftLastAccessTime.dwLowDateTime) / 10000000 - DBUS_INT64_CONSTANT (116444736000000000);
423
424   statbuf->mtime =
425     (((dbus_int64_t) wfad.ftLastWriteTime.dwHighDateTime << 32) +
426      wfad.ftLastWriteTime.dwLowDateTime) / 10000000 - DBUS_INT64_CONSTANT (116444736000000000);
427
428   statbuf->ctime =
429     (((dbus_int64_t) wfad.ftCreationTime.dwHighDateTime << 32) +
430      wfad.ftCreationTime.dwLowDateTime) / 10000000 - DBUS_INT64_CONSTANT (116444736000000000);
431
432   return TRUE;
433 #endif //DBUS_WINCE
434 }
435
436
437 #ifdef HAVE_DIRENT_H
438
439 // mingw ships with dirent.h
440 #include <dirent.h>
441 #define _dbus_opendir opendir
442 #define _dbus_readdir readdir
443 #define _dbus_closedir closedir
444
445 #else
446
447 #ifdef HAVE_IO_H
448 #include <io.h> // win32 file functions
449 #endif
450
451 #include <sys/types.h>
452 #include <stdlib.h>
453
454 /* This file is part of the KDE project
455 Copyright (C) 2000 Werner Almesberger
456
457 libc/sys/linux/sys/dirent.h - Directory entry as returned by readdir
458
459 This program is free software; you can redistribute it and/or
460 modify it under the terms of the GNU Library General Public
461 License as published by the Free Software Foundation; either
462 version 2 of the License, or (at your option) any later version.
463
464 This program is distributed in the hope that it will be useful,
465 but WITHOUT ANY WARRANTY; without even the implied warranty of
466 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
467 Library General Public License for more details.
468
469 You should have received a copy of the GNU Library General Public License
470 along with this program; see the file COPYING.  If not, write to
471 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
472 Boston, MA 02110-1301, USA.
473 */
474 #define HAVE_NO_D_NAMLEN        /* no struct dirent->d_namlen */
475 #define HAVE_DD_LOCK            /* have locking mechanism */
476
477 #define MAXNAMLEN 255           /* sizeof(struct dirent.d_name)-1 */
478
479 #define __dirfd(dir) (dir)->dd_fd
480
481 /* struct dirent - same as Unix */
482 struct dirent
483   {
484     long d_ino;                    /* inode (always 1 in WIN32) */
485     off_t d_off;                /* offset to this dirent */
486     unsigned short d_reclen;    /* length of d_name */
487     char d_name[_MAX_FNAME+1];    /* filename (null terminated) */
488   };
489
490 /* typedef DIR - not the same as Unix */
491 typedef struct
492   {
493     long handle;                /* _findfirst/_findnext handle */
494     short offset;                /* offset into directory */
495     short finished;             /* 1 if there are not more files */
496     struct _finddata_t fileinfo;  /* from _findfirst/_findnext */
497     char *dir;                  /* the dir we are reading */
498     struct dirent dent;         /* the dirent to return */
499   }
500 DIR;
501
502 /**********************************************************************
503 * Implement dirent-style opendir/readdir/closedir on Window 95/NT
504 *
505 * Functions defined are opendir(), readdir() and closedir() with the
506 * same prototypes as the normal dirent.h implementation.
507 *
508 * Does not implement telldir(), seekdir(), rewinddir() or scandir().
509 * The dirent struct is compatible with Unix, except that d_ino is
510 * always 1 and d_off is made up as we go along.
511 *
512 * The DIR typedef is not compatible with Unix.
513 **********************************************************************/
514
515 DIR * _dbus_opendir(const char *dir)
516 {
517   DIR *dp;
518   char *filespec;
519   long handle;
520   int index;
521
522   filespec = malloc(strlen(dir) + 2 + 1);
523   strcpy(filespec, dir);
524   index = strlen(filespec) - 1;
525   if (index >= 0 && (filespec[index] == '/' || filespec[index] == '\\'))
526     filespec[index] = '\0';
527   strcat(filespec, "\\*");
528
529   dp = (DIR *)malloc(sizeof(DIR));
530   dp->offset = 0;
531   dp->finished = 0;
532   dp->dir = strdup(dir);
533
534   if ((handle = _findfirst(filespec, &(dp->fileinfo))) < 0)
535     {
536       if (errno == ENOENT)
537         dp->finished = 1;
538       else
539         return NULL;
540     }
541
542   dp->handle = handle;
543   free(filespec);
544
545   return dp;
546 }
547
548 struct dirent * _dbus_readdir(DIR *dp)
549   {
550     if (!dp || dp->finished)
551       return NULL;
552
553     if (dp->offset != 0)
554       {
555         if (_findnext(dp->handle, &(dp->fileinfo)) < 0)
556           {
557             dp->finished = 1;
558             errno = 0;
559             return NULL;
560           }
561       }
562     dp->offset++;
563
564     strncpy(dp->dent.d_name, dp->fileinfo.name, _MAX_FNAME);
565     dp->dent.d_ino = 1;
566     dp->dent.d_reclen = strlen(dp->dent.d_name);
567     dp->dent.d_off = dp->offset;
568
569     return &(dp->dent);
570   }
571
572
573 int _dbus_closedir(DIR *dp)
574 {
575   if (!dp)
576     return 0;
577   _findclose(dp->handle);
578   if (dp->dir)
579     free(dp->dir);
580   if (dp)
581     free(dp);
582
583   return 0;
584 }
585
586 #endif //#ifdef HAVE_DIRENT_H
587
588 /**
589  * Internals of directory iterator
590  */
591 struct DBusDirIter
592   {
593     DIR *d; /**< The DIR* from opendir() */
594
595   };
596
597 /**
598  * Open a directory to iterate over.
599  *
600  * @param filename the directory name
601  * @param error exception return object or #NULL
602  * @returns new iterator, or #NULL on error
603  */
604 DBusDirIter*
605 _dbus_directory_open (const DBusString *filename,
606                       DBusError        *error)
607 {
608   DIR *d;
609   DBusDirIter *iter;
610   const char *filename_c;
611
612   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
613
614   filename_c = _dbus_string_get_const_data (filename);
615
616   d = _dbus_opendir (filename_c);
617   if (d == NULL)
618     {
619       dbus_set_error (error, _dbus_error_from_errno (errno),
620                       "Failed to read directory \"%s\": %s",
621                       filename_c,
622                       _dbus_strerror (errno));
623       return NULL;
624     }
625   iter = dbus_new0 (DBusDirIter, 1);
626   if (iter == NULL)
627     {
628       _dbus_closedir (d);
629       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
630                       "Could not allocate memory for directory iterator");
631       return NULL;
632     }
633
634   iter->d = d;
635
636   return iter;
637 }
638
639 /**
640  * Get next file in the directory. Will not return "." or ".."  on
641  * UNIX. If an error occurs, the contents of "filename" are
642  * undefined. The error is never set if the function succeeds.
643  *
644  * @todo for thread safety, I think we have to use
645  * readdir_r(). (GLib has the same issue, should file a bug.)
646  *
647  * @param iter the iterator
648  * @param filename string to be set to the next file in the dir
649  * @param error return location for error
650  * @returns #TRUE if filename was filled in with a new filename
651  */
652 dbus_bool_t
653 _dbus_directory_get_next_file (DBusDirIter      *iter,
654                                DBusString       *filename,
655                                DBusError        *error)
656 {
657   struct dirent *ent;
658
659   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
660
661 again:
662   errno = 0;
663   ent = _dbus_readdir (iter->d);
664   if (ent == NULL)
665     {
666       if (errno != 0)
667         dbus_set_error (error,
668                         _dbus_error_from_errno (errno),
669                         "%s", _dbus_strerror (errno));
670       return FALSE;
671     }
672   else if (ent->d_name[0] == '.' &&
673            (ent->d_name[1] == '\0' ||
674             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
675     goto again;
676   else
677     {
678       _dbus_string_set_length (filename, 0);
679       if (!_dbus_string_append (filename, ent->d_name))
680         {
681           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
682                           "No memory to read directory entry");
683           return FALSE;
684         }
685       else
686         return TRUE;
687     }
688 }
689
690 /**
691  * Closes a directory iteration.
692  */
693 void
694 _dbus_directory_close (DBusDirIter *iter)
695 {
696   _dbus_closedir (iter->d);
697   dbus_free (iter);
698 }
699
700 /**
701  * Checks whether the filename is an absolute path
702  *
703  * @param filename the filename
704  * @returns #TRUE if an absolute path
705  */
706 dbus_bool_t
707 _dbus_path_is_absolute (const DBusString *filename)
708 {
709   if (_dbus_string_get_length (filename) > 0)
710     return _dbus_string_get_byte (filename, 1) == ':'
711            || _dbus_string_get_byte (filename, 0) == '\\'
712            || _dbus_string_get_byte (filename, 0) == '/';
713   else
714     return FALSE;
715 }
716
717 /** @} */ /* End of DBusInternalsUtils functions */
718
719 /**
720  * @addtogroup DBusString
721  *
722  * @{
723  */
724 /**
725  * Get the directory name from a complete filename
726  * @param filename the filename
727  * @param dirname string to append directory name to
728  * @returns #FALSE if no memory
729  */
730 dbus_bool_t
731 _dbus_string_get_dirname(const DBusString *filename,
732                          DBusString       *dirname)
733 {
734   int sep;
735
736   _dbus_assert (filename != dirname);
737   _dbus_assert (filename != NULL);
738   _dbus_assert (dirname != NULL);
739
740   /* Ignore any separators on the end */
741   sep = _dbus_string_get_length (filename);
742   if (sep == 0)
743     return _dbus_string_append (dirname, "."); /* empty string passed in */
744
745   while (sep > 0 &&
746          (_dbus_string_get_byte (filename, sep - 1) == '/' ||
747           _dbus_string_get_byte (filename, sep - 1) == '\\'))
748     --sep;
749
750   _dbus_assert (sep >= 0);
751
752   if (sep == 0 ||
753       (sep == 2 &&
754        _dbus_string_get_byte (filename, 1) == ':' &&
755        isalpha (_dbus_string_get_byte (filename, 0))))
756     return _dbus_string_copy_len (filename, 0, sep + 1,
757                                   dirname, _dbus_string_get_length (dirname));
758
759   {
760     int sep1, sep2;
761     _dbus_string_find_byte_backward (filename, sep, '/', &sep1);
762     _dbus_string_find_byte_backward (filename, sep, '\\', &sep2);
763
764     sep = MAX (sep1, sep2);
765   }
766   if (sep < 0)
767     return _dbus_string_append (dirname, ".");
768
769   while (sep > 0 &&
770          (_dbus_string_get_byte (filename, sep - 1) == '/' ||
771           _dbus_string_get_byte (filename, sep - 1) == '\\'))
772     --sep;
773
774   _dbus_assert (sep >= 0);
775
776   if ((sep == 0 ||
777        (sep == 2 &&
778         _dbus_string_get_byte (filename, 1) == ':' &&
779         isalpha (_dbus_string_get_byte (filename, 0))))
780       &&
781       (_dbus_string_get_byte (filename, sep) == '/' ||
782        _dbus_string_get_byte (filename, sep) == '\\'))
783     return _dbus_string_copy_len (filename, 0, sep + 1,
784                                   dirname, _dbus_string_get_length (dirname));
785   else
786     return _dbus_string_copy_len (filename, 0, sep - 0,
787                                   dirname, _dbus_string_get_length (dirname));
788 }
789
790
791 /**
792  * Checks to see if the UNIX user ID matches the UID of
793  * the process. Should always return #FALSE on Windows.
794  *
795  * @param uid the UNIX user ID
796  * @returns #TRUE if this uid owns the process.
797  */
798 dbus_bool_t
799 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
800 {
801   return FALSE;
802 }
803
804 /*=====================================================================
805   unix emulation functions - should be removed sometime in the future
806  =====================================================================*/
807
808 /**
809  * Checks to see if the UNIX user ID is at the console.
810  * Should always fail on Windows (set the error to
811  * #DBUS_ERROR_NOT_SUPPORTED).
812  *
813  * @param uid UID of person to check 
814  * @param error return location for errors
815  * @returns #TRUE if the UID is the same as the console user and there are no errors
816  */
817 dbus_bool_t
818 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
819                                DBusError         *error)
820 {
821   return FALSE;
822 }
823
824
825 /**
826  * Parse a UNIX group from the bus config file. On Windows, this should
827  * simply always fail (just return #FALSE).
828  *
829  * @param groupname the groupname text
830  * @param gid_p place to return the gid
831  * @returns #TRUE on success
832  */
833 dbus_bool_t
834 _dbus_parse_unix_group_from_config (const DBusString  *groupname,
835                                     dbus_gid_t        *gid_p)
836 {
837   return FALSE;
838 }
839
840 /**
841  * Parse a UNIX user from the bus config file. On Windows, this should
842  * simply always fail (just return #FALSE).
843  *
844  * @param username the username text
845  * @param uid_p place to return the uid
846  * @returns #TRUE on success
847  */
848 dbus_bool_t
849 _dbus_parse_unix_user_from_config (const DBusString  *username,
850                                    dbus_uid_t        *uid_p)
851 {
852   return FALSE;
853 }
854
855
856 /**
857  * Gets all groups corresponding to the given UNIX user ID. On UNIX,
858  * just calls _dbus_groups_from_uid(). On Windows, should always
859  * fail since we don't know any UNIX groups.
860  *
861  * @param uid the UID
862  * @param group_ids return location for array of group IDs
863  * @param n_group_ids return location for length of returned array
864  * @returns #TRUE if the UID existed and we got some credentials
865  */
866 dbus_bool_t
867 _dbus_unix_groups_from_uid (dbus_uid_t            uid,
868                             dbus_gid_t          **group_ids,
869                             int                  *n_group_ids)
870 {
871   return FALSE;
872 }
873
874
875
876 /** @} */ /* DBusString stuff */
877
878 /************************************************************************
879  
880  error handling
881  
882  ************************************************************************/
883
884
885 /**
886  * Assigns an error name and message corresponding to a Win32 error
887  * code to a DBusError. Does nothing if error is #NULL.
888  *
889  * @param error the error.
890  * @param code the Win32 error code
891  */
892 void
893 _dbus_win_set_error_from_win_error (DBusError *error,
894                                     int        code)
895 {
896   char *msg;
897
898   /* As we want the English message, use the A API */
899   FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
900                   FORMAT_MESSAGE_IGNORE_INSERTS |
901                   FORMAT_MESSAGE_FROM_SYSTEM,
902                   NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
903                   (LPTSTR) &msg, 0, NULL);
904   if (msg)
905     {
906       char *msg_copy;
907
908       msg_copy = dbus_malloc (strlen (msg));
909       strcpy (msg_copy, msg);
910       LocalFree (msg);
911
912       dbus_set_error (error, "win32.error", "%s", msg_copy);
913     }
914   else
915     dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
916 }
917
918 void
919 _dbus_win_warn_win_error (const char *message,
920                           int         code)
921 {
922   DBusError error = DBUS_ERROR_INIT;
923
924   _dbus_win_set_error_from_win_error (&error, code);
925   _dbus_warn ("%s: %s\n", message, error.message);
926   dbus_error_free (&error);
927 }
928
929 /**
930  * A wrapper around strerror() because some platforms
931  * may be lame and not have strerror().
932  *
933  * @param error_number errno.
934  * @returns error description.
935  */
936 const char*
937 _dbus_strerror (int error_number)
938 {
939 #ifdef DBUS_WINCE
940   // TODO
941   return "unknown";
942 #else
943   const char *msg;
944
945   switch (error_number)
946     {
947     case WSAEINTR:
948       return "Interrupted function call";
949     case WSAEACCES:
950       return "Permission denied";
951     case WSAEFAULT:
952       return "Bad address";
953     case WSAEINVAL:
954       return "Invalid argument";
955     case WSAEMFILE:
956       return "Too many open files";
957     case WSAEWOULDBLOCK:
958       return "Resource temporarily unavailable";
959     case WSAEINPROGRESS:
960       return "Operation now in progress";
961     case WSAEALREADY:
962       return "Operation already in progress";
963     case WSAENOTSOCK:
964       return "Socket operation on nonsocket";
965     case WSAEDESTADDRREQ:
966       return "Destination address required";
967     case WSAEMSGSIZE:
968       return "Message too long";
969     case WSAEPROTOTYPE:
970       return "Protocol wrong type for socket";
971     case WSAENOPROTOOPT:
972       return "Bad protocol option";
973     case WSAEPROTONOSUPPORT:
974       return "Protocol not supported";
975     case WSAESOCKTNOSUPPORT:
976       return "Socket type not supported";
977     case WSAEOPNOTSUPP:
978       return "Operation not supported";
979     case WSAEPFNOSUPPORT:
980       return "Protocol family not supported";
981     case WSAEAFNOSUPPORT:
982       return "Address family not supported by protocol family";
983     case WSAEADDRINUSE:
984       return "Address already in use";
985     case WSAEADDRNOTAVAIL:
986       return "Cannot assign requested address";
987     case WSAENETDOWN:
988       return "Network is down";
989     case WSAENETUNREACH:
990       return "Network is unreachable";
991     case WSAENETRESET:
992       return "Network dropped connection on reset";
993     case WSAECONNABORTED:
994       return "Software caused connection abort";
995     case WSAECONNRESET:
996       return "Connection reset by peer";
997     case WSAENOBUFS:
998       return "No buffer space available";
999     case WSAEISCONN:
1000       return "Socket is already connected";
1001     case WSAENOTCONN:
1002       return "Socket is not connected";
1003     case WSAESHUTDOWN:
1004       return "Cannot send after socket shutdown";
1005     case WSAETIMEDOUT:
1006       return "Connection timed out";
1007     case WSAECONNREFUSED:
1008       return "Connection refused";
1009     case WSAEHOSTDOWN:
1010       return "Host is down";
1011     case WSAEHOSTUNREACH:
1012       return "No route to host";
1013     case WSAEPROCLIM:
1014       return "Too many processes";
1015     case WSAEDISCON:
1016       return "Graceful shutdown in progress";
1017     case WSATYPE_NOT_FOUND:
1018       return "Class type not found";
1019     case WSAHOST_NOT_FOUND:
1020       return "Host not found";
1021     case WSATRY_AGAIN:
1022       return "Nonauthoritative host not found";
1023     case WSANO_RECOVERY:
1024       return "This is a nonrecoverable error";
1025     case WSANO_DATA:
1026       return "Valid name, no data record of requested type";
1027     case WSA_INVALID_HANDLE:
1028       return "Specified event object handle is invalid";
1029     case WSA_INVALID_PARAMETER:
1030       return "One or more parameters are invalid";
1031     case WSA_IO_INCOMPLETE:
1032       return "Overlapped I/O event object not in signaled state";
1033     case WSA_IO_PENDING:
1034       return "Overlapped operations will complete later";
1035     case WSA_NOT_ENOUGH_MEMORY:
1036       return "Insufficient memory available";
1037     case WSA_OPERATION_ABORTED:
1038       return "Overlapped operation aborted";
1039 #ifdef WSAINVALIDPROCTABLE
1040
1041     case WSAINVALIDPROCTABLE:
1042       return "Invalid procedure table from service provider";
1043 #endif
1044 #ifdef WSAINVALIDPROVIDER
1045
1046     case WSAINVALIDPROVIDER:
1047       return "Invalid service provider version number";
1048 #endif
1049 #ifdef WSAPROVIDERFAILEDINIT
1050
1051     case WSAPROVIDERFAILEDINIT:
1052       return "Unable to initialize a service provider";
1053 #endif
1054
1055     case WSASYSCALLFAILURE:
1056       return "System call failure";
1057     }
1058   msg = strerror (error_number);
1059   if (msg == NULL)
1060     msg = "unknown";
1061
1062   return msg;
1063 #endif //DBUS_WINCE
1064 }
1065
1066
1067
1068 /* lan manager error codes */
1069 const char*
1070 _dbus_lm_strerror(int error_number)
1071 {
1072 #ifdef DBUS_WINCE
1073   // TODO
1074   return "unknown";
1075 #else
1076   const char *msg;
1077   switch (error_number)
1078     {
1079     case NERR_NetNotStarted:
1080       return "The workstation driver is not installed.";
1081     case NERR_UnknownServer:
1082       return "The server could not be located.";
1083     case NERR_ShareMem:
1084       return "An internal error occurred. The network cannot access a shared memory segment.";
1085     case NERR_NoNetworkResource:
1086       return "A network resource shortage occurred.";
1087     case NERR_RemoteOnly:
1088       return "This operation is not supported on workstations.";
1089     case NERR_DevNotRedirected:
1090       return "The device is not connected.";
1091     case NERR_ServerNotStarted:
1092       return "The Server service is not started.";
1093     case NERR_ItemNotFound:
1094       return "The queue is empty.";
1095     case NERR_UnknownDevDir:
1096       return "The device or directory does not exist.";
1097     case NERR_RedirectedPath:
1098       return "The operation is invalid on a redirected resource.";
1099     case NERR_DuplicateShare:
1100       return "The name has already been shared.";
1101     case NERR_NoRoom:
1102       return "The server is currently out of the requested resource.";
1103     case NERR_TooManyItems:
1104       return "Requested addition of items exceeds the maximum allowed.";
1105     case NERR_InvalidMaxUsers:
1106       return "The Peer service supports only two simultaneous users.";
1107     case NERR_BufTooSmall:
1108       return "The API return buffer is too small.";
1109     case NERR_RemoteErr:
1110       return "A remote API error occurred.";
1111     case NERR_LanmanIniError:
1112       return "An error occurred when opening or reading the configuration file.";
1113     case NERR_NetworkError:
1114       return "A general network error occurred.";
1115     case NERR_WkstaInconsistentState:
1116       return "The Workstation service is in an inconsistent state. Restart the computer before restarting the Workstation service.";
1117     case NERR_WkstaNotStarted:
1118       return "The Workstation service has not been started.";
1119     case NERR_BrowserNotStarted:
1120       return "The requested information is not available.";
1121     case NERR_InternalError:
1122       return "An internal error occurred.";
1123     case NERR_BadTransactConfig:
1124       return "The server is not configured for transactions.";
1125     case NERR_InvalidAPI:
1126       return "The requested API is not supported on the remote server.";
1127     case NERR_BadEventName:
1128       return "The event name is invalid.";
1129     case NERR_DupNameReboot:
1130       return "The computer name already exists on the network. Change it and restart the computer.";
1131     case NERR_CfgCompNotFound:
1132       return "The specified component could not be found in the configuration information.";
1133     case NERR_CfgParamNotFound:
1134       return "The specified parameter could not be found in the configuration information.";
1135     case NERR_LineTooLong:
1136       return "A line in the configuration file is too long.";
1137     case NERR_QNotFound:
1138       return "The printer does not exist.";
1139     case NERR_JobNotFound:
1140       return "The print job does not exist.";
1141     case NERR_DestNotFound:
1142       return "The printer destination cannot be found.";
1143     case NERR_DestExists:
1144       return "The printer destination already exists.";
1145     case NERR_QExists:
1146       return "The printer queue already exists.";
1147     case NERR_QNoRoom:
1148       return "No more printers can be added.";
1149     case NERR_JobNoRoom:
1150       return "No more print jobs can be added.";
1151     case NERR_DestNoRoom:
1152       return "No more printer destinations can be added.";
1153     case NERR_DestIdle:
1154       return "This printer destination is idle and cannot accept control operations.";
1155     case NERR_DestInvalidOp:
1156       return "This printer destination request contains an invalid control function.";
1157     case NERR_ProcNoRespond:
1158       return "The print processor is not responding.";
1159     case NERR_SpoolerNotLoaded:
1160       return "The spooler is not running.";
1161     case NERR_DestInvalidState:
1162       return "This operation cannot be performed on the print destination in its current state.";
1163     case NERR_QInvalidState:
1164       return "This operation cannot be performed on the printer queue in its current state.";
1165     case NERR_JobInvalidState:
1166       return "This operation cannot be performed on the print job in its current state.";
1167     case NERR_SpoolNoMemory:
1168       return "A spooler memory allocation failure occurred.";
1169     case NERR_DriverNotFound:
1170       return "The device driver does not exist.";
1171     case NERR_DataTypeInvalid:
1172       return "The data type is not supported by the print processor.";
1173     case NERR_ProcNotFound:
1174       return "The print processor is not installed.";
1175     case NERR_ServiceTableLocked:
1176       return "The service database is locked.";
1177     case NERR_ServiceTableFull:
1178       return "The service table is full.";
1179     case NERR_ServiceInstalled:
1180       return "The requested service has already been started.";
1181     case NERR_ServiceEntryLocked:
1182       return "The service does not respond to control actions.";
1183     case NERR_ServiceNotInstalled:
1184       return "The service has not been started.";
1185     case NERR_BadServiceName:
1186       return "The service name is invalid.";
1187     case NERR_ServiceCtlTimeout:
1188       return "The service is not responding to the control function.";
1189     case NERR_ServiceCtlBusy:
1190       return "The service control is busy.";
1191     case NERR_BadServiceProgName:
1192       return "The configuration file contains an invalid service program name.";
1193     case NERR_ServiceNotCtrl:
1194       return "The service could not be controlled in its present state.";
1195     case NERR_ServiceKillProc:
1196       return "The service ended abnormally.";
1197     case NERR_ServiceCtlNotValid:
1198       return "The requested pause or stop is not valid for this service.";
1199     case NERR_NotInDispatchTbl:
1200       return "The service control dispatcher could not find the service name in the dispatch table.";
1201     case NERR_BadControlRecv:
1202       return "The service control dispatcher pipe read failed.";
1203     case NERR_ServiceNotStarting:
1204       return "A thread for the new service could not be created.";
1205     case NERR_AlreadyLoggedOn:
1206       return "This workstation is already logged on to the local-area network.";
1207     case NERR_NotLoggedOn:
1208       return "The workstation is not logged on to the local-area network.";
1209     case NERR_BadUsername:
1210       return "The user name or group name parameter is invalid.";
1211     case NERR_BadPassword:
1212       return "The password parameter is invalid.";
1213     case NERR_UnableToAddName_W:
1214       return "@W The logon processor did not add the message alias.";
1215     case NERR_UnableToAddName_F:
1216       return "The logon processor did not add the message alias.";
1217     case NERR_UnableToDelName_W:
1218       return "@W The logoff processor did not delete the message alias.";
1219     case NERR_UnableToDelName_F:
1220       return "The logoff processor did not delete the message alias.";
1221     case NERR_LogonsPaused:
1222       return "Network logons are paused.";
1223     case NERR_LogonServerConflict:
1224       return "A centralized logon-server conflict occurred.";
1225     case NERR_LogonNoUserPath:
1226       return "The server is configured without a valid user path.";
1227     case NERR_LogonScriptError:
1228       return "An error occurred while loading or running the logon script.";
1229     case NERR_StandaloneLogon:
1230       return "The logon server was not specified. Your computer will be logged on as STANDALONE.";
1231     case NERR_LogonServerNotFound:
1232       return "The logon server could not be found.";
1233     case NERR_LogonDomainExists:
1234       return "There is already a logon domain for this computer.";
1235     case NERR_NonValidatedLogon:
1236       return "The logon server could not validate the logon.";
1237     case NERR_ACFNotFound:
1238       return "The security database could not be found.";
1239     case NERR_GroupNotFound:
1240       return "The group name could not be found.";
1241     case NERR_UserNotFound:
1242       return "The user name could not be found.";
1243     case NERR_ResourceNotFound:
1244       return "The resource name could not be found.";
1245     case NERR_GroupExists:
1246       return "The group already exists.";
1247     case NERR_UserExists:
1248       return "The user account already exists.";
1249     case NERR_ResourceExists:
1250       return "The resource permission list already exists.";
1251     case NERR_NotPrimary:
1252       return "This operation is only allowed on the primary domain controller of the domain.";
1253     case NERR_ACFNotLoaded:
1254       return "The security database has not been started.";
1255     case NERR_ACFNoRoom:
1256       return "There are too many names in the user accounts database.";
1257     case NERR_ACFFileIOFail:
1258       return "A disk I/O failure occurred.";
1259     case NERR_ACFTooManyLists:
1260       return "The limit of 64 entries per resource was exceeded.";
1261     case NERR_UserLogon:
1262       return "Deleting a user with a session is not allowed.";
1263     case NERR_ACFNoParent:
1264       return "The parent directory could not be located.";
1265     case NERR_CanNotGrowSegment:
1266       return "Unable to add to the security database session cache segment.";
1267     case NERR_SpeGroupOp:
1268       return "This operation is not allowed on this special group.";
1269     case NERR_NotInCache:
1270       return "This user is not cached in user accounts database session cache.";
1271     case NERR_UserInGroup:
1272       return "The user already belongs to this group.";
1273     case NERR_UserNotInGroup:
1274       return "The user does not belong to this group.";
1275     case NERR_AccountUndefined:
1276       return "This user account is undefined.";
1277     case NERR_AccountExpired:
1278       return "This user account has expired.";
1279     case NERR_InvalidWorkstation:
1280       return "The user is not allowed to log on from this workstation.";
1281     case NERR_InvalidLogonHours:
1282       return "The user is not allowed to log on at this time.";
1283     case NERR_PasswordExpired:
1284       return "The password of this user has expired.";
1285     case NERR_PasswordCantChange:
1286       return "The password of this user cannot change.";
1287     case NERR_PasswordHistConflict:
1288       return "This password cannot be used now.";
1289     case NERR_PasswordTooShort:
1290       return "The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.";
1291     case NERR_PasswordTooRecent:
1292       return "The password of this user is too recent to change.";
1293     case NERR_InvalidDatabase:
1294       return "The security database is corrupted.";
1295     case NERR_DatabaseUpToDate:
1296       return "No updates are necessary to this replicant network/local security database.";
1297     case NERR_SyncRequired:
1298       return "This replicant database is outdated; synchronization is required.";
1299     case NERR_UseNotFound:
1300       return "The network connection could not be found.";
1301     case NERR_BadAsgType:
1302       return "This asg_type is invalid.";
1303     case NERR_DeviceIsShared:
1304       return "This device is currently being shared.";
1305     case NERR_NoComputerName:
1306       return "The computer name could not be added as a message alias. The name may already exist on the network.";
1307     case NERR_MsgAlreadyStarted:
1308       return "The Messenger service is already started.";
1309     case NERR_MsgInitFailed:
1310       return "The Messenger service failed to start.";
1311     case NERR_NameNotFound:
1312       return "The message alias could not be found on the network.";
1313     case NERR_AlreadyForwarded:
1314       return "This message alias has already been forwarded.";
1315     case NERR_AddForwarded:
1316       return "This message alias has been added but is still forwarded.";
1317     case NERR_AlreadyExists:
1318       return "This message alias already exists locally.";
1319     case NERR_TooManyNames:
1320       return "The maximum number of added message aliases has been exceeded.";
1321     case NERR_DelComputerName:
1322       return "The computer name could not be deleted.";
1323     case NERR_LocalForward:
1324       return "Messages cannot be forwarded back to the same workstation.";
1325     case NERR_GrpMsgProcessor:
1326       return "An error occurred in the domain message processor.";
1327     case NERR_PausedRemote:
1328       return "The message was sent, but the recipient has paused the Messenger service.";
1329     case NERR_BadReceive:
1330       return "The message was sent but not received.";
1331     case NERR_NameInUse:
1332       return "The message alias is currently in use. Try again later.";
1333     case NERR_MsgNotStarted:
1334       return "The Messenger service has not been started.";
1335     case NERR_NotLocalName:
1336       return "The name is not on the local computer.";
1337     case NERR_NoForwardName:
1338       return "The forwarded message alias could not be found on the network.";
1339     case NERR_RemoteFull:
1340       return "The message alias table on the remote station is full.";
1341     case NERR_NameNotForwarded:
1342       return "Messages for this alias are not currently being forwarded.";
1343     case NERR_TruncatedBroadcast:
1344       return "The broadcast message was truncated.";
1345     case NERR_InvalidDevice:
1346       return "This is an invalid device name.";
1347     case NERR_WriteFault:
1348       return "A write fault occurred.";
1349     case NERR_DuplicateName:
1350       return "A duplicate message alias exists on the network.";
1351     case NERR_DeleteLater:
1352       return "@W This message alias will be deleted later.";
1353     case NERR_IncompleteDel:
1354       return "The message alias was not successfully deleted from all networks.";
1355     case NERR_MultipleNets:
1356       return "This operation is not supported on computers with multiple networks.";
1357     case NERR_NetNameNotFound:
1358       return "This shared resource does not exist.";
1359     case NERR_DeviceNotShared:
1360       return "This device is not shared.";
1361     case NERR_ClientNameNotFound:
1362       return "A session does not exist with that computer name.";
1363     case NERR_FileIdNotFound:
1364       return "There is not an open file with that identification number.";
1365     case NERR_ExecFailure:
1366       return "A failure occurred when executing a remote administration command.";
1367     case NERR_TmpFile:
1368       return "A failure occurred when opening a remote temporary file.";
1369     case NERR_TooMuchData:
1370       return "The data returned from a remote administration command has been truncated to 64K.";
1371     case NERR_DeviceShareConflict:
1372       return "This device cannot be shared as both a spooled and a non-spooled resource.";
1373     case NERR_BrowserTableIncomplete:
1374       return "The information in the list of servers may be incorrect.";
1375     case NERR_NotLocalDomain:
1376       return "The computer is not active in this domain.";
1377 #ifdef NERR_IsDfsShare
1378
1379     case NERR_IsDfsShare:
1380       return "The share must be removed from the Distributed File System before it can be deleted.";
1381 #endif
1382
1383     case NERR_DevInvalidOpCode:
1384       return "The operation is invalid for this device.";
1385     case NERR_DevNotFound:
1386       return "This device cannot be shared.";
1387     case NERR_DevNotOpen:
1388       return "This device was not open.";
1389     case NERR_BadQueueDevString:
1390       return "This device name list is invalid.";
1391     case NERR_BadQueuePriority:
1392       return "The queue priority is invalid.";
1393     case NERR_NoCommDevs:
1394       return "There are no shared communication devices.";
1395     case NERR_QueueNotFound:
1396       return "The queue you specified does not exist.";
1397     case NERR_BadDevString:
1398       return "This list of devices is invalid.";
1399     case NERR_BadDev:
1400       return "The requested device is invalid.";
1401     case NERR_InUseBySpooler:
1402       return "This device is already in use by the spooler.";
1403     case NERR_CommDevInUse:
1404       return "This device is already in use as a communication device.";
1405     case NERR_InvalidComputer:
1406       return "This computer name is invalid.";
1407     case NERR_MaxLenExceeded:
1408       return "The string and prefix specified are too long.";
1409     case NERR_BadComponent:
1410       return "This path component is invalid.";
1411     case NERR_CantType:
1412       return "Could not determine the type of input.";
1413     case NERR_TooManyEntries:
1414       return "The buffer for types is not big enough.";
1415     case NERR_ProfileFileTooBig:
1416       return "Profile files cannot exceed 64K.";
1417     case NERR_ProfileOffset:
1418       return "The start offset is out of range.";
1419     case NERR_ProfileCleanup:
1420       return "The system cannot delete current connections to network resources.";
1421     case NERR_ProfileUnknownCmd:
1422       return "The system was unable to parse the command line in this file.";
1423     case NERR_ProfileLoadErr:
1424       return "An error occurred while loading the profile file.";
1425     case NERR_ProfileSaveErr:
1426       return "@W Errors occurred while saving the profile file. The profile was partially saved.";
1427     case NERR_LogOverflow:
1428       return "Log file %1 is full.";
1429     case NERR_LogFileChanged:
1430       return "This log file has changed between reads.";
1431     case NERR_LogFileCorrupt:
1432       return "Log file %1 is corrupt.";
1433     case NERR_SourceIsDir:
1434       return "The source path cannot be a directory.";
1435     case NERR_BadSource:
1436       return "The source path is illegal.";
1437     case NERR_BadDest:
1438       return "The destination path is illegal.";
1439     case NERR_DifferentServers:
1440       return "The source and destination paths are on different servers.";
1441     case NERR_RunSrvPaused:
1442       return "The Run server you requested is paused.";
1443     case NERR_ErrCommRunSrv:
1444       return "An error occurred when communicating with a Run server.";
1445     case NERR_ErrorExecingGhost:
1446       return "An error occurred when starting a background process.";
1447     case NERR_ShareNotFound:
1448       return "The shared resource you are connected to could not be found.";
1449     case NERR_InvalidLana:
1450       return "The LAN adapter number is invalid.";
1451     case NERR_OpenFiles:
1452       return "There are open files on the connection.";
1453     case NERR_ActiveConns:
1454       return "Active connections still exist.";
1455     case NERR_BadPasswordCore:
1456       return "This share name or password is invalid.";
1457     case NERR_DevInUse:
1458       return "The device is being accessed by an active process.";
1459     case NERR_LocalDrive:
1460       return "The drive letter is in use locally.";
1461     case NERR_AlertExists:
1462       return "The specified client is already registered for the specified event.";
1463     case NERR_TooManyAlerts:
1464       return "The alert table is full.";
1465     case NERR_NoSuchAlert:
1466       return "An invalid or nonexistent alert name was raised.";
1467     case NERR_BadRecipient:
1468       return "The alert recipient is invalid.";
1469     case NERR_AcctLimitExceeded:
1470       return "A user's session with this server has been deleted.";
1471     case NERR_InvalidLogSeek:
1472       return "The log file does not contain the requested record number.";
1473     case NERR_BadUasConfig:
1474       return "The user accounts database is not configured correctly.";
1475     case NERR_InvalidUASOp:
1476       return "This operation is not permitted when the Netlogon service is running.";
1477     case NERR_LastAdmin:
1478       return "This operation is not allowed on the last administrative account.";
1479     case NERR_DCNotFound:
1480       return "Could not find domain controller for this domain.";
1481     case NERR_LogonTrackingError:
1482       return "Could not set logon information for this user.";
1483     case NERR_NetlogonNotStarted:
1484       return "The Netlogon service has not been started.";
1485     case NERR_CanNotGrowUASFile:
1486       return "Unable to add to the user accounts database.";
1487     case NERR_TimeDiffAtDC:
1488       return "This server's clock is not synchronized with the primary domain controller's clock.";
1489     case NERR_PasswordMismatch:
1490       return "A password mismatch has been detected.";
1491     case NERR_NoSuchServer:
1492       return "The server identification does not specify a valid server.";
1493     case NERR_NoSuchSession:
1494       return "The session identification does not specify a valid session.";
1495     case NERR_NoSuchConnection:
1496       return "The connection identification does not specify a valid connection.";
1497     case NERR_TooManyServers:
1498       return "There is no space for another entry in the table of available servers.";
1499     case NERR_TooManySessions:
1500       return "The server has reached the maximum number of sessions it supports.";
1501     case NERR_TooManyConnections:
1502       return "The server has reached the maximum number of connections it supports.";
1503     case NERR_TooManyFiles:
1504       return "The server cannot open more files because it has reached its maximum number.";
1505     case NERR_NoAlternateServers:
1506       return "There are no alternate servers registered on this server.";
1507     case NERR_TryDownLevel:
1508       return "Try down-level (remote admin protocol) version of API instead.";
1509     case NERR_UPSDriverNotStarted:
1510       return "The UPS driver could not be accessed by the UPS service.";
1511     case NERR_UPSInvalidConfig:
1512       return "The UPS service is not configured correctly.";
1513     case NERR_UPSInvalidCommPort:
1514       return "The UPS service could not access the specified Comm Port.";
1515     case NERR_UPSSignalAsserted:
1516       return "The UPS indicated a line fail or low battery situation. Service not started.";
1517     case NERR_UPSShutdownFailed:
1518       return "The UPS service failed to perform a system shut down.";
1519     case NERR_BadDosRetCode:
1520       return "The program below returned an MS-DOS error code:";
1521     case NERR_ProgNeedsExtraMem:
1522       return "The program below needs more memory:";
1523     case NERR_BadDosFunction:
1524       return "The program below called an unsupported MS-DOS function:";
1525     case NERR_RemoteBootFailed:
1526       return "The workstation failed to boot.";
1527     case NERR_BadFileCheckSum:
1528       return "The file below is corrupt.";
1529     case NERR_NoRplBootSystem:
1530       return "No loader is specified in the boot-block definition file.";
1531     case NERR_RplLoadrNetBiosErr:
1532       return "NetBIOS returned an error:      The NCB and SMB are dumped above.";
1533     case NERR_RplLoadrDiskErr:
1534       return "A disk I/O error occurred.";
1535     case NERR_ImageParamErr:
1536       return "Image parameter substitution failed.";
1537     case NERR_TooManyImageParams:
1538       return "Too many image parameters cross disk sector boundaries.";
1539     case NERR_NonDosFloppyUsed:
1540       return "The image was not generated from an MS-DOS diskette formatted with /S.";
1541     case NERR_RplBootRestart:
1542       return "Remote boot will be restarted later.";
1543     case NERR_RplSrvrCallFailed:
1544       return "The call to the Remoteboot server failed.";
1545     case NERR_CantConnectRplSrvr:
1546       return "Cannot connect to the Remoteboot server.";
1547     case NERR_CantOpenImageFile:
1548       return "Cannot open image file on the Remoteboot server.";
1549     case NERR_CallingRplSrvr:
1550       return "Connecting to the Remoteboot server...";
1551     case NERR_StartingRplBoot:
1552       return "Connecting to the Remoteboot server...";
1553     case NERR_RplBootServiceTerm:
1554       return "Remote boot service was stopped; check the error log for the cause of the problem.";
1555     case NERR_RplBootStartFailed:
1556       return "Remote boot startup failed; check the error log for the cause of the problem.";
1557     case NERR_RPL_CONNECTED:
1558       return "A second connection to a Remoteboot resource is not allowed.";
1559     case NERR_BrowserConfiguredToNotRun:
1560       return "The browser service was configured with MaintainServerList=No.";
1561     case NERR_RplNoAdaptersStarted:
1562       return "Service failed to start since none of the network adapters started with this service.";
1563     case NERR_RplBadRegistry:
1564       return "Service failed to start due to bad startup information in the registry.";
1565     case NERR_RplBadDatabase:
1566       return "Service failed to start because its database is absent or corrupt.";
1567     case NERR_RplRplfilesShare:
1568       return "Service failed to start because RPLFILES share is absent.";
1569     case NERR_RplNotRplServer:
1570       return "Service failed to start because RPLUSER group is absent.";
1571     case NERR_RplCannotEnum:
1572       return "Cannot enumerate service records.";
1573     case NERR_RplWkstaInfoCorrupted:
1574       return "Workstation record information has been corrupted.";
1575     case NERR_RplWkstaNotFound:
1576       return "Workstation record was not found.";
1577     case NERR_RplWkstaNameUnavailable:
1578       return "Workstation name is in use by some other workstation.";
1579     case NERR_RplProfileInfoCorrupted:
1580       return "Profile record information has been corrupted.";
1581     case NERR_RplProfileNotFound:
1582       return "Profile record was not found.";
1583     case NERR_RplProfileNameUnavailable:
1584       return "Profile name is in use by some other profile.";
1585     case NERR_RplProfileNotEmpty:
1586       return "There are workstations using this profile.";
1587     case NERR_RplConfigInfoCorrupted:
1588       return "Configuration record information has been corrupted.";
1589     case NERR_RplConfigNotFound:
1590       return "Configuration record was not found.";
1591     case NERR_RplAdapterInfoCorrupted:
1592       return "Adapter ID record information has been corrupted.";
1593     case NERR_RplInternal:
1594       return "An internal service error has occurred.";
1595     case NERR_RplVendorInfoCorrupted:
1596       return "Vendor ID record information has been corrupted.";
1597     case NERR_RplBootInfoCorrupted:
1598       return "Boot block record information has been corrupted.";
1599     case NERR_RplWkstaNeedsUserAcct:
1600       return "The user account for this workstation record is missing.";
1601     case NERR_RplNeedsRPLUSERAcct:
1602       return "The RPLUSER local group could not be found.";
1603     case NERR_RplBootNotFound:
1604       return "Boot block record was not found.";
1605     case NERR_RplIncompatibleProfile:
1606       return "Chosen profile is incompatible with this workstation.";
1607     case NERR_RplAdapterNameUnavailable:
1608       return "Chosen network adapter ID is in use by some other workstation.";
1609     case NERR_RplConfigNotEmpty:
1610       return "There are profiles using this configuration.";
1611     case NERR_RplBootInUse:
1612       return "There are workstations, profiles, or configurations using this boot block.";
1613     case NERR_RplBackupDatabase:
1614       return "Service failed to backup Remoteboot database.";
1615     case NERR_RplAdapterNotFound:
1616       return "Adapter record was not found.";
1617     case NERR_RplVendorNotFound:
1618       return "Vendor record was not found.";
1619     case NERR_RplVendorNameUnavailable:
1620       return "Vendor name is in use by some other vendor record.";
1621     case NERR_RplBootNameUnavailable:
1622       return "(boot name, vendor ID) is in use by some other boot block record.";
1623     case NERR_RplConfigNameUnavailable:
1624       return "Configuration name is in use by some other configuration.";
1625     case NERR_DfsInternalCorruption:
1626       return "The internal database maintained by the Dfs service is corrupt.";
1627     case NERR_DfsVolumeDataCorrupt:
1628       return "One of the records in the internal Dfs database is corrupt.";
1629     case NERR_DfsNoSuchVolume:
1630       return "There is no DFS name whose entry path matches the input Entry Path.";
1631     case NERR_DfsVolumeAlreadyExists:
1632       return "A root or link with the given name already exists.";
1633     case NERR_DfsAlreadyShared:
1634       return "The server share specified is already shared in the Dfs.";
1635     case NERR_DfsNoSuchShare:
1636       return "The indicated server share does not support the indicated DFS namespace.";
1637     case NERR_DfsNotALeafVolume:
1638       return "The operation is not valid on this portion of the namespace.";
1639     case NERR_DfsLeafVolume:
1640       return "The operation is not valid on this portion of the namespace.";
1641     case NERR_DfsVolumeHasMultipleServers:
1642       return "The operation is ambiguous because the link has multiple servers.";
1643     case NERR_DfsCantCreateJunctionPoint:
1644       return "Unable to create a link.";
1645     case NERR_DfsServerNotDfsAware:
1646       return "The server is not Dfs Aware.";
1647     case NERR_DfsBadRenamePath:
1648       return "The specified rename target path is invalid.";
1649     case NERR_DfsVolumeIsOffline:
1650       return "The specified DFS link is offline.";
1651     case NERR_DfsNoSuchServer:
1652       return "The specified server is not a server for this link.";
1653     case NERR_DfsCyclicalName:
1654       return "A cycle in the Dfs name was detected.";
1655     case NERR_DfsNotSupportedInServerDfs:
1656       return "The operation is not supported on a server-based Dfs.";
1657     case NERR_DfsDuplicateService:
1658       return "This link is already supported by the specified server-share.";
1659     case NERR_DfsCantRemoveLastServerShare:
1660       return "Can't remove the last server-share supporting this root or link.";
1661     case NERR_DfsVolumeIsInterDfs:
1662       return "The operation is not supported for an Inter-DFS link.";
1663     case NERR_DfsInconsistent:
1664       return "The internal state of the Dfs Service has become inconsistent.";
1665     case NERR_DfsServerUpgraded:
1666       return "The Dfs Service has been installed on the specified server.";
1667     case NERR_DfsDataIsIdentical:
1668       return "The Dfs data being reconciled is identical.";
1669     case NERR_DfsCantRemoveDfsRoot:
1670       return "The DFS root cannot be deleted. Uninstall DFS if required.";
1671     case NERR_DfsChildOrParentInDfs:
1672       return "A child or parent directory of the share is already in a Dfs.";
1673     case NERR_DfsInternalError:
1674       return "Dfs internal error.";
1675       /* the following are not defined in mingw */
1676 #if 0
1677
1678     case NERR_SetupAlreadyJoined:
1679       return "This machine is already joined to a domain.";
1680     case NERR_SetupNotJoined:
1681       return "This machine is not currently joined to a domain.";
1682     case NERR_SetupDomainController:
1683       return "This machine is a domain controller and cannot be unjoined from a domain.";
1684     case NERR_DefaultJoinRequired:
1685       return "The destination domain controller does not support creating machine accounts in OUs.";
1686     case NERR_InvalidWorkgroupName:
1687       return "The specified workgroup name is invalid.";
1688     case NERR_NameUsesIncompatibleCodePage:
1689       return "The specified computer name is incompatible with the default language used on the domain controller.";
1690     case NERR_ComputerAccountNotFound:
1691       return "The specified computer account could not be found.";
1692     case NERR_PersonalSku:
1693       return "This version of Windows cannot be joined to a domain.";
1694     case NERR_PasswordMustChange:
1695       return "The password must change at the next logon.";
1696     case NERR_AccountLockedOut:
1697       return "The account is locked out.";
1698     case NERR_PasswordTooLong:
1699       return "The password is too long.";
1700     case NERR_PasswordNotComplexEnough:
1701       return "The password does not meet the complexity policy.";
1702     case NERR_PasswordFilterError:
1703       return "The password does not meet the requirements of the password filter DLLs.";
1704 #endif
1705
1706     }
1707   msg = strerror (error_number);
1708   if (msg == NULL)
1709     msg = "unknown";
1710
1711   return msg;
1712 #endif //DBUS_WINCE
1713 }