cmd.exe: Add errorlevel support for DIR command.
[wine] / programs / cmd / directory.c
1 /*
2  * CMD - Wine-compatible command line interface - Directory functions.
3  *
4  * Copyright (C) 1999 D A Pickles
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /*
22  * NOTES:
23  * On entry, global variables quals, param1, param2 contain
24  * the qualifiers (uppercased and concatenated) and parameters entered, with
25  * environment-variable and batch parameter substitution already done.
26  */
27
28 #define WIN32_LEAN_AND_MEAN
29
30 #include "wcmd.h"
31 #include "wine/debug.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
34
35 int WCMD_dir_sort (const void *a, const void *b);
36 void WCMD_list_directory (char *path, int level);
37 char * WCMD_filesize64 (ULONGLONG free);
38 char * WCMD_strrev (char *buff);
39 static void WCMD_getfileowner(char *filename, char *owner, int ownerlen);
40
41 extern int echo_mode;
42 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
43 extern DWORD errorlevel;
44
45 typedef enum _DISPLAYTIME
46 {
47     Creation = 0,
48     Access,
49     Written
50 } DISPLAYTIME;
51
52 typedef enum _DISPLAYORDER
53 {
54     Name = 0,
55     Extension,
56     Size,
57     Date
58 } DISPLAYORDER;
59
60 static int file_total, dir_total, recurse, wide, bare, max_width, lower;
61 static int shortname, usernames;
62 static ULONGLONG byte_total;
63 static DISPLAYTIME dirTime;
64 static DISPLAYORDER dirOrder;
65 static BOOL orderReverse, orderGroupDirs, orderGroupDirsReverse, orderByCol;
66 static BOOL seperator;
67 static ULONG showattrs, attrsbits;
68
69 /*****************************************************************************
70  * WCMD_directory
71  *
72  * List a file directory.
73  *
74  */
75
76 void WCMD_directory (void) {
77
78   char path[MAX_PATH], drive[8];
79   int status, paged_mode;
80   ULARGE_INTEGER avail, total, free;
81   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
82   char *p;
83   char string[MAXSTRING];
84
85   errorlevel = 0;
86
87   /* Prefill Quals with (uppercased) DIRCMD env var */
88   if (GetEnvironmentVariable ("DIRCMD", string, sizeof(string))) {
89     p = string;
90     while ( (*p = toupper(*p)) ) ++p;
91     strcat(string,quals);
92     strcpy(quals, string);
93   }
94
95   byte_total = 0;
96   file_total = dir_total = 0;
97
98   /* Initialize all flags to their defaults as if no DIRCMD or quals */
99   paged_mode = FALSE;
100   recurse    = FALSE;
101   wide       = FALSE;
102   bare       = FALSE;
103   lower      = FALSE;
104   shortname  = FALSE;
105   usernames  = FALSE;
106   orderByCol = FALSE;
107   seperator  = TRUE;
108   dirTime = Written;
109   dirOrder = Name;
110   orderReverse = FALSE;
111   orderGroupDirs = FALSE;
112   orderGroupDirsReverse = FALSE;
113   showattrs  = 0;
114   attrsbits  = 0;
115
116   /* Handle args - Loop through so right most is the effective one */
117   /* Note: /- appears to be a negate rather than an off, eg. dir
118            /-W is wide, or dir /w /-w /-w is also wide             */
119   p = quals;
120   while (*p && (*p=='/' || *p==' ')) {
121     BOOL negate = FALSE;
122     if (*p++==' ') continue;  /* Skip / and blanks introduced through DIRCMD */
123
124     if (*p=='-') {
125       negate = TRUE;
126       p++;
127     }
128
129     WINE_TRACE("Processing arg '%c' (in %s)\n", *p, quals);
130     switch (*p) {
131     case 'P': if (negate) paged_mode = !paged_mode;
132               else paged_mode = TRUE;
133               break;
134     case 'S': if (negate) recurse = !recurse;
135               else recurse = TRUE;
136               break;
137     case 'W': if (negate) wide = !wide;
138               else wide = TRUE;
139               break;
140     case 'B': if (negate) bare = !bare;
141               else bare = TRUE;
142               break;
143     case 'L': if (negate) lower = !lower;
144               else lower = TRUE;
145               break;
146     case 'X': if (negate) shortname = !shortname;
147               else shortname = TRUE;
148               break;
149     case 'Q': if (negate) usernames = !usernames;
150               else usernames = TRUE;
151               break;
152     case 'D': if (negate) orderByCol = !orderByCol;
153               else orderByCol = TRUE;
154               break;
155     case 'C': if (negate) seperator = !seperator;
156               else seperator = TRUE;
157               break;
158     case 'T': p = p + 1;
159               if (*p==':') p++;  /* Skip optional : */
160
161               if (*p == 'A') dirTime = Access;
162               else if (*p == 'C') dirTime = Creation;
163               else if (*p == 'W') dirTime = Written;
164
165               /* Support /T and /T: with no parms, default to written */
166               else if (*p == 0x00 || *p == '/') {
167                 dirTime = Written;
168                 p = p - 1; /* So when step on, move to '/' */
169               } else {
170                 SetLastError(ERROR_INVALID_PARAMETER);
171                 WCMD_print_error();
172                 errorlevel = 1;
173                 return;
174               }
175               break;
176     case 'O': p = p + 1;
177               if (*p==':') p++;  /* Skip optional : */
178               while (*p && *p != '/') {
179                 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, quals);
180                 switch (*p) {
181                 case 'N': dirOrder = Name;       break;
182                 case 'E': dirOrder = Extension;  break;
183                 case 'S': dirOrder = Size;       break;
184                 case 'D': dirOrder = Date;       break;
185                 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
186                           else orderReverse = TRUE;
187                           break;
188                 case 'G': orderGroupDirs = TRUE; break;
189                 default:
190                     SetLastError(ERROR_INVALID_PARAMETER);
191                     WCMD_print_error();
192                     errorlevel = 1;
193                     return;
194                 }
195                 p++;
196               }
197               p = p - 1; /* So when step on, move to '/' */
198               break;
199     case 'A': p = p + 1;
200               showattrs = 0;
201               attrsbits = 0;
202               if (*p==':') p++;  /* Skip optional : */
203               while (*p && *p != '/') {
204                 BOOL anegate = FALSE;
205                 ULONG mask;
206
207                 /* Note /A: - options are 'offs' not toggles */
208                 if (*p=='-') {
209                   anegate = TRUE;
210                   p++;
211                 }
212
213                 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, quals);
214                 switch (*p) {
215                 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
216                 case 'H': mask = FILE_ATTRIBUTE_HIDDEN;    break;
217                 case 'S': mask = FILE_ATTRIBUTE_SYSTEM;    break;
218                 case 'R': mask = FILE_ATTRIBUTE_READONLY;  break;
219                 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE;   break;
220                 default:
221                     SetLastError(ERROR_INVALID_PARAMETER);
222                     WCMD_print_error();
223                     errorlevel = 1;
224                     return;
225                 }
226
227                 /* Keep running list of bits we care about */
228                 attrsbits |= mask;
229
230                 /* Mask shows what MUST be in the bits we care about */
231                 if (anegate) showattrs = showattrs & ~mask;
232                 else showattrs |= mask;
233
234                 p++;
235               }
236               p = p - 1; /* So when step on, move to '/' */
237               WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
238               break;
239     default:
240               SetLastError(ERROR_INVALID_PARAMETER);
241               WCMD_print_error();
242               errorlevel = 1;
243               return;
244     }
245     p = p + 1;
246   }
247
248   /* Handle conflicting args and initialization */
249   if (bare || shortname) wide = FALSE;
250   if (bare) shortname = FALSE;
251   if (wide) usernames = FALSE;
252   if (orderByCol) wide = TRUE;
253
254   if (wide) {
255       if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
256           max_width = consoleInfo.dwSize.X;
257       else
258           max_width = 80;
259   }
260   if (paged_mode) {
261      WCMD_enter_paged_mode();
262   }
263
264   if (param1[0] == '\0') strcpy (param1, ".");
265   status = GetFullPathName (param1, sizeof(path), path, NULL);
266   if (!status) {
267     WCMD_print_error();
268     if (paged_mode) WCMD_leave_paged_mode();
269     errorlevel = 1;
270     return;
271   }
272   lstrcpyn (drive, path, 3);
273
274   if (!bare) {
275      status = WCMD_volume (0, drive);
276      if (!status) {
277          if (paged_mode) WCMD_leave_paged_mode();
278        errorlevel = 1;
279        return;
280      }
281   }
282
283   WCMD_list_directory (path, 0);
284   lstrcpyn (drive, path, 4);
285   GetDiskFreeSpaceEx (drive, &avail, &total, &free);
286
287   if (!bare) {
288      if (recurse) {
289        WCMD_output ("\n\n     Total files listed:\n%8d files%25s bytes\n",
290             file_total, WCMD_filesize64 (byte_total));
291        WCMD_output ("%8d directories %18s bytes free\n\n",
292             dir_total, WCMD_filesize64 (free.QuadPart));
293      } else {
294        WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free.QuadPart));
295      }
296   }
297   if (paged_mode) WCMD_leave_paged_mode();
298 }
299
300 /*****************************************************************************
301  * WCMD_list_directory
302  *
303  * List a single file directory. This function (and those below it) can be called
304  * recursively when the /S switch is used.
305  *
306  * FIXME: Entries sorted by name only. Should we support DIRCMD??
307  * FIXME: Assumes 24-line display for the /P qualifier.
308  * FIXME: Other command qualifiers not supported.
309  * FIXME: DIR /S FILENAME fails if at least one matching file is not found in the top level.
310  */
311
312 void WCMD_list_directory (char *search_path, int level) {
313
314   char string[1024], datestring[32], timestring[32];
315   char *p;
316   char real_path[MAX_PATH];
317   WIN32_FIND_DATA *fd;
318   FILETIME ft;
319   SYSTEMTIME st;
320   HANDLE hff;
321   int status, dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
322   int numCols, numRows;
323   int rows, cols;
324   ULARGE_INTEGER byte_count, file_size;
325
326   dir_count = 0;
327   file_count = 0;
328   entry_count = 0;
329   byte_count.QuadPart = 0;
330   widest = 0;
331   cur_width = 0;
332
333 /*
334  *  If the path supplied does not include a wildcard, and the endpoint of the
335  *  path references a directory, we need to list the *contents* of that
336  *  directory not the directory file itself.
337  */
338
339   if ((strchr(search_path, '*') == NULL) && (strchr(search_path, '%') == NULL)) {
340     status = GetFileAttributes (search_path);
341     if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
342       if (search_path[strlen(search_path)-1] == '\\') {
343         strcat (search_path, "*");
344       }
345       else {
346         strcat (search_path, "\\*");
347       }
348     }
349   }
350
351   /* Work out the actual current directory name */
352   p = strrchr (search_path, '\\');
353   memset(real_path, 0x00, sizeof(real_path));
354   lstrcpyn (real_path, search_path, (p-search_path+2));
355
356   /* Load all files into an in memory structure */
357   fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA));
358   hff = FindFirstFile (search_path, fd);
359   if (hff == INVALID_HANDLE_VALUE) {
360     SetLastError (ERROR_FILE_NOT_FOUND);
361     WCMD_print_error ();
362     HeapFree(GetProcessHeap(),0,fd);
363     errorlevel = 1;
364     return;
365   }
366   do {
367     /* Skip any which are filtered out by attribute */
368     if (((fd+entry_count)->dwFileAttributes & attrsbits) != showattrs) continue;
369
370     entry_count++;
371
372     /* Keep running track of longest filename for wide output */
373     if (wide || orderByCol) {
374        int tmpLen = strlen((fd+(entry_count-1))->cFileName) + 3;
375        if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
376        if (tmpLen > widest) widest = tmpLen;
377     }
378
379     fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
380     if (fd == NULL) {
381       FindClose (hff);
382       WCMD_output ("Memory Allocation Error");
383       errorlevel = 1;
384       return;
385     }
386   } while (FindNextFile(hff, (fd+entry_count)) != 0);
387   FindClose (hff);
388
389   /* Handle case where everything is filtered out */
390   if (entry_count == 0) {
391     SetLastError (ERROR_FILE_NOT_FOUND);
392     WCMD_print_error ();
393     HeapFree(GetProcessHeap(),0,fd);
394     errorlevel = 1;
395     return;
396   }
397
398   /* Sort the list of files */
399   qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
400
401   /* Output the results */
402   if (!bare) {
403      if (level != 0) WCMD_output ("\n\n");
404      WCMD_output ("Directory of %s\n\n", real_path);
405   }
406
407   /* Work out the number of columns */
408   WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
409   if (wide || orderByCol) {
410     numCols = max(1, (int)max_width / widest);
411     numRows = entry_count / numCols;
412     if (entry_count % numCols) numRows++;
413   } else {
414     numCols = 1;
415     numRows = entry_count;
416   }
417   WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
418
419   for (rows=0; rows<numRows; rows++) {
420    for (cols=0; cols<numCols; cols++) {
421     char username[24];
422
423     /* Work out the index of the entry being pointed to */
424     if (orderByCol) {
425       i = (cols * numRows) + rows;
426       if (i >= entry_count) continue;
427     } else {
428       i = (rows * numCols) + cols;
429       if (i >= entry_count) continue;
430     }
431
432     /* /L convers all names to lower case */
433     if (lower) {
434         char *p = (fd+i)->cFileName;
435         while ( (*p = tolower(*p)) ) ++p;
436     }
437
438     /* /Q gets file ownership information */
439     if (usernames) {
440         p = strrchr (search_path, '\\');
441         lstrcpyn (string, search_path, (p-search_path+2));
442         lstrcat (string, (fd+i)->cFileName);
443         WCMD_getfileowner(string, username, sizeof(username));
444     }
445
446     if (dirTime == Written) {
447       FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
448     } else if (dirTime == Access) {
449       FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
450     } else {
451       FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
452     }
453     FileTimeToSystemTime (&ft, &st);
454     GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
455                 sizeof(datestring));
456     GetTimeFormat (0, TIME_NOSECONDS, &st,
457                 NULL, timestring, sizeof(timestring));
458
459     if (wide) {
460
461       tmp_width = cur_width;
462       if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
463           WCMD_output ("[%s]", (fd+i)->cFileName);
464           dir_count++;
465           tmp_width = tmp_width + strlen((fd+i)->cFileName) + 2;
466       } else {
467           WCMD_output ("%s", (fd+i)->cFileName);
468           tmp_width = tmp_width + strlen((fd+i)->cFileName) ;
469           file_count++;
470           file_size.u.LowPart = (fd+i)->nFileSizeLow;
471           file_size.u.HighPart = (fd+i)->nFileSizeHigh;
472       byte_count.QuadPart += file_size.QuadPart;
473       }
474       cur_width = cur_width + widest;
475
476       if ((cur_width + widest) > max_width) {
477           cur_width = 0;
478       } else {
479           WCMD_output ("%*.s", (tmp_width - cur_width) ,"");
480       }
481
482     } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
483       dir_count++;
484
485       if (!bare) {
486          WCMD_output ("%10s  %8s  <DIR>         ", datestring, timestring);
487          if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
488          if (usernames) WCMD_output ("%-23s", username);
489          WCMD_output("%s",(fd+i)->cFileName);
490       } else {
491          if (!((strcmp((fd+i)->cFileName, ".") == 0) ||
492                (strcmp((fd+i)->cFileName, "..") == 0))) {
493             WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
494          }
495       }
496     }
497     else {
498       file_count++;
499       file_size.u.LowPart = (fd+i)->nFileSizeLow;
500       file_size.u.HighPart = (fd+i)->nFileSizeHigh;
501       byte_count.QuadPart += file_size.QuadPart;
502       if (!bare) {
503          WCMD_output ("%10s  %8s    %10s  ", datestring, timestring,
504                       WCMD_filesize64(file_size.QuadPart));
505          if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
506          if (usernames) WCMD_output ("%-23s", username);
507          WCMD_output("%s",(fd+i)->cFileName);
508       } else {
509          WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
510       }
511     }
512    }
513    WCMD_output ("\n");
514    cur_width = 0;
515   }
516
517   if (!bare) {
518      if (file_count == 1) {
519        WCMD_output ("       1 file %25s bytes\n", WCMD_filesize64 (byte_count.QuadPart));
520      }
521      else {
522        WCMD_output ("%8d files %24s bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
523      }
524   }
525   byte_total = byte_total + byte_count.QuadPart;
526   file_total = file_total + file_count;
527   dir_total = dir_total + dir_count;
528
529   if (!bare) {
530      if (dir_count == 1) WCMD_output ("1 directory         ");
531      else WCMD_output ("%8d directories", dir_count);
532   }
533   for (i=0; i<entry_count; i++) {
534     if ((recurse) &&
535           ((fd+i)->cFileName[0] != '.') &&
536           ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
537 #if 0
538       GetFullPathName ((fd+i)->cFileName, sizeof(string), string, NULL);
539 #endif
540       p = strrchr (search_path, '\\');
541       lstrcpyn (string, search_path, (p-search_path+2));
542       lstrcat (string, (fd+i)->cFileName);
543       lstrcat (string, p);
544       WCMD_list_directory (string, 1);
545     }
546   }
547   HeapFree(GetProcessHeap(),0,fd);
548   return;
549 }
550
551 /*****************************************************************************
552  * WCMD_filesize64
553  *
554  * Convert a 64-bit number into a character string, with commas every three digits.
555  * Result is returned in a static string overwritten with each call.
556  * FIXME: There must be a better algorithm!
557  */
558
559 char * WCMD_filesize64 (ULONGLONG n) {
560
561   ULONGLONG q;
562   unsigned int r, i;
563   char *p;
564   static char buff[32];
565
566   p = buff;
567   i = -3;
568   do {
569     if (seperator && ((++i)%3 == 1)) *p++ = ',';
570     q = n / 10;
571     r = n - (q * 10);
572     *p++ = r + '0';
573     *p = '\0';
574     n = q;
575   } while (n != 0);
576   WCMD_strrev (buff);
577   return buff;
578 }
579
580 /*****************************************************************************
581  * WCMD_strrev
582  *
583  * Reverse a character string in-place (strrev() is not available under unixen :-( ).
584  */
585
586 char * WCMD_strrev (char *buff) {
587
588   int r, i;
589   char b;
590
591   r = lstrlen (buff);
592   for (i=0; i<r/2; i++) {
593     b = buff[i];
594     buff[i] = buff[r-i-1];
595     buff[r-i-1] = b;
596   }
597   return (buff);
598 }
599
600
601 /*****************************************************************************
602  * WCMD_dir_sort
603  *
604  * Sort based on the /O options supplied on the command line
605  */
606 int WCMD_dir_sort (const void *a, const void *b)
607 {
608   WIN32_FIND_DATA *filea = (WIN32_FIND_DATA *)a;
609   WIN32_FIND_DATA *fileb = (WIN32_FIND_DATA *)b;
610   int result = 0;
611
612   /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
613      requested sort order for the directory components                   */
614   if (orderGroupDirs &&
615       ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
616        (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
617   {
618     BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
619     if (aDir) result = -1;
620     else result = 1;
621     if (orderGroupDirsReverse) result = -result;
622     return result;
623
624   /* Order by Name: */
625   } else if (dirOrder == Name) {
626     result = lstrcmpi(filea->cFileName, fileb->cFileName);
627
628   /* Order by Size: */
629   } else if (dirOrder == Size) {
630     ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
631     ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
632     if( sizea < sizeb ) result = -1;
633     else if( sizea == sizeb ) result = 0;
634     else result = 1;
635
636   /* Order by Date: (Takes into account which date (/T option) */
637   } else if (dirOrder == Date) {
638
639     FILETIME *ft;
640     ULONG64 timea, timeb;
641
642     if (dirTime == Written) {
643       ft = &filea->ftLastWriteTime;
644       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
645       ft = &fileb->ftLastWriteTime;
646       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
647     } else if (dirTime == Access) {
648       ft = &filea->ftLastAccessTime;
649       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
650       ft = &fileb->ftLastAccessTime;
651       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
652     } else {
653       ft = &filea->ftCreationTime;
654       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
655       ft = &fileb->ftCreationTime;
656       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
657     }
658     if( timea < timeb ) result = -1;
659     else if( timea == timeb ) result = 0;
660     else result = 1;
661
662   /* Order by Extension: (Takes into account which date (/T option) */
663   } else if (dirOrder == Extension) {
664       char drive[10];
665       char dir[MAX_PATH];
666       char fname[MAX_PATH];
667       char extA[MAX_PATH];
668       char extB[MAX_PATH];
669
670       /* Split into components */
671       WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
672       WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
673       result = lstrcmpi(extA, extB);
674   }
675
676   if (orderReverse) result = -result;
677   return result;
678 }
679
680 /*****************************************************************************
681  * WCMD_getfileowner
682  *
683  * Reverse a character string in-place (strrev() is not available under unixen :-( ).
684  */
685 void WCMD_getfileowner(char *filename, char *owner, int ownerlen) {
686
687     ULONG sizeNeeded = 0;
688     DWORD rc;
689     char name[MAXSTRING];
690     char domain[MAXSTRING];
691
692     /* In case of error, return empty string */
693     *owner = 0x00;
694
695     /* Find out how much space we need for the owner security descritpor */
696     GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
697     rc = GetLastError();
698
699     if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
700
701         LPBYTE secBuffer;
702         PSID pSID = NULL;
703         BOOL defaulted = FALSE;
704         ULONG nameLen = MAXSTRING;
705         ULONG domainLen = MAXSTRING;
706         SID_NAME_USE nameuse;
707
708         secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
709         if(!secBuffer) return;
710
711         /* Get the owners security descriptor */
712         if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
713                             sizeNeeded, &sizeNeeded)) {
714             HeapFree(GetProcessHeap(),0,secBuffer);
715             return;
716         }
717
718         /* Get the SID from the SD */
719         if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
720             HeapFree(GetProcessHeap(),0,secBuffer);
721             return;
722         }
723
724         /* Convert to a username */
725         if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
726             snprintf(owner, ownerlen, "%s%c%s", domain, '\\', name);
727         }
728         HeapFree(GetProcessHeap(),0,secBuffer);
729     }
730     return;
731 }