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