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