summaryrefslogtreecommitdiffstats
path: root/dbus/dbus-sysdeps-util-win.c
blob: 3b308f8c47545bef8eca2dd2fbcfb474267f6134 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
/* -*- mode: C; c-file-style: "gnu" -*- */
/* dbus-sysdeps-util.c Would be in dbus-sysdeps.c, but not used in libdbus
 * 
 * Copyright (C) 2002, 2003, 2004, 2005  Red Hat, Inc.
 * Copyright (C) 2003 CodeFactory AB
 *
 * Licensed under the Academic Free License version 2.1
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#undef open

#define STRSAFE_NO_DEPRECATE

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

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

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

#ifdef __MINGW32__
/* save string functions version
   using DBusString needs to much time because of uncommon api 
*/ 
#define errno_t int

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

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

/**
 * return the absolute path of the dbus installation 
 *
 * @param s buffer for installation path
 * @param len length of buffer
 * @returns #FALSE on failure
 */
dbus_bool_t 
_dbus_get_install_root(char *s, int len)
{
  char *p = NULL;
  int ret = GetModuleFileName(NULL,s,len);
  if ( ret == 0 
    || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
      *s = '\0';
      return FALSE;
    }
  else if ((p = strstr(s,"\\bin\\")))
    {
      *(p+1)= '\0';
      return TRUE;
    }
  else
    {
      *s = '\0';
      return FALSE;
    }
}

/* 
  find session.conf either from installation or build root according to 
  the following path layout 
    install-root/
      bin/dbus-daemon[d].exe
      etc/session.conf 

    build-root/
      bin/dbus-daemon[d].exe
      bus/session.conf 
*/             
dbus_bool_t 
_dbus_get_config_file_name(DBusString *config_file, char *s)
{
  char path[MAX_PATH*2];
  int path_size = sizeof(path);

  if (!_dbus_get_install_root(path,path_size))
    return FALSE;

  strcat_s(path,path_size,"etc\\");
  strcat_s(path,path_size,s);
  if (_dbus_file_exists(path)) 
    {
      // find path from executable 
      if (!_dbus_string_append (config_file, path))
        return FALSE;
    }
  else 
    {
      if (!_dbus_get_install_root(path,path_size))
        return FALSE;
      strcat_s(path,path_size,"bus\\");
      strcat_s(path,path_size,s);
  
      if (_dbus_file_exists(path)) 
        {
          if (!_dbus_string_append (config_file, path))
            return FALSE;
        }
    }
  return TRUE;
}    
    
/**
 * Does the chdir, fork, setsid, etc. to become a daemon process.
 *
 * @param pidfile #NULL, or pidfile to create
 * @param print_pid_fd file descriptor to print daemon's pid to, or -1 for none
 * @param error return location for errors
 * @returns #FALSE on failure
 */
dbus_bool_t
_dbus_become_daemon (const DBusString *pidfile,
                     DBusPipe         *print_pid_pipe,
                     DBusError        *error)
{
  return TRUE;
}

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

  cfilename = _dbus_string_get_const_data (filename);

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

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

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

      fclose (f);
      return FALSE;
    }

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

  return TRUE;
}

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

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

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

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

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

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

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

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

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

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

  retval = EqualSid (user_sid, console_user_sid);

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

  return retval;
#endif //DBUS_WINCE
}

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

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  filename_c = _dbus_string_get_const_data (filename);

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

  return TRUE;
}

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

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

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

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

  struct stat sb;
#else

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

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  filename_c = _dbus_string_get_const_data (filename);

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

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

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

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

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

  statbuf->nlink = 1;

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

  statbuf->uid = _dbus_win_sid_to_uid_t (owner_sid);
  statbuf->gid = _dbus_win_sid_to_uid_t (group_sid);

  LocalFree (sd);

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

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

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

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

  return TRUE;
#endif //DBUS_WINCE
}


#ifdef HAVE_DIRENT_H

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

#else

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return dp;
}

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

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

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

    return &(dp->dent);
  }


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

  return 0;
}

#endif //#ifdef HAVE_DIRENT_H

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

  };

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

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  filename_c = _dbus_string_get_const_data (filename);

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

  iter->d = d;

  return iter;
}

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

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

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

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

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


static dbus_bool_t
fill_group_info(DBusGroupInfo    *info,
                dbus_gid_t        gid,
                const DBusString *groupname,
                DBusError        *error)
{
  const char *group_c_str;

  _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
  _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);

  if (groupname)
    group_c_str = _dbus_string_get_const_data (groupname);
  else
    group_c_str = NULL;

  if (group_c_str)
    {
      PSID group_sid;
      wchar_t *wgroupname = _dbus_win_utf8_to_utf16 (group_c_str, error);

      if (!wgroupname)
        return FALSE;

      if (!_dbus_win_account_to_sid (wgroupname, &group_sid, error))
        {
          dbus_free (wgroupname);
          return FALSE;
        }

      info->gid = _dbus_win_sid_to_uid_t (group_sid);
      info->groupname = _dbus_strdup (group_c_str);

      dbus_free (group_sid);
      dbus_free (wgroupname);

      return TRUE;
    }
  else
    {
      dbus_bool_t retval = FALSE;
      wchar_t *wname, *wdomain;
      char *name, *domain;

      info->gid = gid;

      if (!_dbus_win_sid_to_name_and_domain (gid, &wname, &wdomain, error))
        return FALSE;

      name = _dbus_win_utf16_to_utf8 (wname, error);
      if (!name)
        goto out0;

      domain = _dbus_win_utf16_to_utf8 (wdomain, error);
      if (!domain)
        goto out1;

      info->groupname = dbus_malloc (strlen (domain) + 1 + strlen (name) + 1);

      strcpy (info->groupname, domain);
      strcat (info->groupname, "\\");
      strcat (info->groupname, name);

      retval = TRUE;

      dbus_free (domain);
out1:
      dbus_free (name);
out0:
      dbus_free (wname);
      dbus_free (wdomain);

      return retval;
    }
}

/**
 * Initializes the given DBusGroupInfo struct
 * with information about the given group ID.
 *
 * @param info the group info struct
 * @param gid group ID
 * @param error the error return
 * @returns #FALSE if error is set
 */
dbus_bool_t
_dbus_group_info_fill_gid (DBusGroupInfo *info,
                           dbus_gid_t     gid,
                           DBusError     *error)
{
  return fill_group_info (info, gid, NULL, error);
}

/**
 * Initializes the given DBusGroupInfo struct
 * with information about the given group name.
 *
 * @param info the group info struct
 * @param groupname name of group
 * @param error the error return
 * @returns #FALSE if error is set
 */
dbus_bool_t
_dbus_group_info_fill (DBusGroupInfo    *info,
                       const DBusString *groupname,
                       DBusError        *error)
{
  return fill_group_info (info, DBUS_GID_UNSET,
                          groupname, error);
}

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

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

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

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

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

  _dbus_assert (sep >= 0);

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

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

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

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

  _dbus_assert (sep >= 0);

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

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