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