cmd.exe: Convert cmd to Unicode.
[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 WCHAR * WCMD_filesize64 (ULONGLONG free);
37 WCHAR * WCMD_strrev (WCHAR *buff);
38 static void WCMD_getfileowner(WCHAR *filename, WCHAR *owner, int ownerlen);
39 static void WCMD_dir_trailer(WCHAR drive);
40
41 extern int echo_mode;
42 extern WCHAR 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 DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *parms, int level);
61 static int file_total, dir_total, recurse, wide, bare, max_width, lower;
62 static int shortname, usernames;
63 static ULONGLONG byte_total;
64 static DISPLAYTIME dirTime;
65 static DISPLAYORDER dirOrder;
66 static BOOL orderReverse, orderGroupDirs, orderGroupDirsReverse, orderByCol;
67 static BOOL separator;
68 static ULONG showattrs, attrsbits;
69
70 static const WCHAR dotW[]    = {'.','\0'};
71 static const WCHAR dotdotW[] = {'.','.','\0'};
72 static const WCHAR starW[]   = {'*','\0'};
73 static const WCHAR slashW[]  = {'\\','\0'};
74 static const WCHAR emptyW[]  = {'\0'};
75
76 /*****************************************************************************
77  * WCMD_directory
78  *
79  * List a file directory.
80  *
81  */
82
83 void WCMD_directory (WCHAR *cmd) {
84
85   WCHAR path[MAX_PATH], cwd[MAX_PATH];
86   int status, paged_mode;
87   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
88   WCHAR *p;
89   WCHAR string[MAXSTRING];
90   int   argno         = 0;
91   int   argsProcessed = 0;
92   WCHAR *argN          = cmd;
93   WCHAR  lastDrive;
94   BOOL  trailerReqd = FALSE;
95   DIRECTORY_STACK *fullParms = NULL;
96   DIRECTORY_STACK *prevEntry = NULL;
97   DIRECTORY_STACK *thisEntry = NULL;
98   WCHAR drive[10];
99   WCHAR dir[MAX_PATH];
100   WCHAR fname[MAX_PATH];
101   WCHAR ext[MAX_PATH];
102   static const WCHAR dircmdW[] = {'D','I','R','C','M','D','\0'};
103
104   errorlevel = 0;
105
106   /* Prefill Quals with (uppercased) DIRCMD env var */
107   if (GetEnvironmentVariable (dircmdW, string, sizeof(string)/sizeof(WCHAR))) {
108     p = string;
109     while ( (*p = toupper(*p)) ) ++p;
110     strcatW(string,quals);
111     strcpyW(quals, string);
112   }
113
114   byte_total = 0;
115   file_total = dir_total = 0;
116
117   /* Initialize all flags to their defaults as if no DIRCMD or quals */
118   paged_mode = FALSE;
119   recurse    = FALSE;
120   wide       = FALSE;
121   bare       = FALSE;
122   lower      = FALSE;
123   shortname  = FALSE;
124   usernames  = FALSE;
125   orderByCol = FALSE;
126   separator  = TRUE;
127   dirTime = Written;
128   dirOrder = Name;
129   orderReverse = FALSE;
130   orderGroupDirs = FALSE;
131   orderGroupDirsReverse = FALSE;
132   showattrs  = 0;
133   attrsbits  = 0;
134
135   /* Handle args - Loop through so right most is the effective one */
136   /* Note: /- appears to be a negate rather than an off, eg. dir
137            /-W is wide, or dir /w /-w /-w is also wide             */
138   p = quals;
139   while (*p && (*p=='/' || *p==' ')) {
140     BOOL negate = FALSE;
141     if (*p++==' ') continue;  /* Skip / and blanks introduced through DIRCMD */
142
143     if (*p=='-') {
144       negate = TRUE;
145       p++;
146     }
147
148     WINE_TRACE("Processing arg '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
149     switch (*p) {
150     case 'P': if (negate) paged_mode = !paged_mode;
151               else paged_mode = TRUE;
152               break;
153     case 'S': if (negate) recurse = !recurse;
154               else recurse = TRUE;
155               break;
156     case 'W': if (negate) wide = !wide;
157               else wide = TRUE;
158               break;
159     case 'B': if (negate) bare = !bare;
160               else bare = TRUE;
161               break;
162     case 'L': if (negate) lower = !lower;
163               else lower = TRUE;
164               break;
165     case 'X': if (negate) shortname = !shortname;
166               else shortname = TRUE;
167               break;
168     case 'Q': if (negate) usernames = !usernames;
169               else usernames = TRUE;
170               break;
171     case 'D': if (negate) orderByCol = !orderByCol;
172               else orderByCol = TRUE;
173               break;
174     case 'C': if (negate) separator = !separator;
175               else separator = TRUE;
176               break;
177     case 'T': p = p + 1;
178               if (*p==':') p++;  /* Skip optional : */
179
180               if (*p == 'A') dirTime = Access;
181               else if (*p == 'C') dirTime = Creation;
182               else if (*p == 'W') dirTime = Written;
183
184               /* Support /T and /T: with no parms, default to written */
185               else if (*p == 0x00 || *p == '/') {
186                 dirTime = Written;
187                 p = p - 1; /* So when step on, move to '/' */
188               } else {
189                 SetLastError(ERROR_INVALID_PARAMETER);
190                 WCMD_print_error();
191                 errorlevel = 1;
192                 return;
193               }
194               break;
195     case 'O': p = p + 1;
196               if (*p==':') p++;  /* Skip optional : */
197               while (*p && *p != '/') {
198                 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
199                 switch (*p) {
200                 case 'N': dirOrder = Name;       break;
201                 case 'E': dirOrder = Extension;  break;
202                 case 'S': dirOrder = Size;       break;
203                 case 'D': dirOrder = Date;       break;
204                 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
205                           else orderReverse = TRUE;
206                           break;
207                 case 'G': orderGroupDirs = TRUE; break;
208                 default:
209                     SetLastError(ERROR_INVALID_PARAMETER);
210                     WCMD_print_error();
211                     errorlevel = 1;
212                     return;
213                 }
214                 p++;
215               }
216               p = p - 1; /* So when step on, move to '/' */
217               break;
218     case 'A': p = p + 1;
219               showattrs = 0;
220               attrsbits = 0;
221               if (*p==':') p++;  /* Skip optional : */
222               while (*p && *p != '/') {
223                 BOOL anegate = FALSE;
224                 ULONG mask;
225
226                 /* Note /A: - options are 'offs' not toggles */
227                 if (*p=='-') {
228                   anegate = TRUE;
229                   p++;
230                 }
231
232                 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
233                 switch (*p) {
234                 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
235                 case 'H': mask = FILE_ATTRIBUTE_HIDDEN;    break;
236                 case 'S': mask = FILE_ATTRIBUTE_SYSTEM;    break;
237                 case 'R': mask = FILE_ATTRIBUTE_READONLY;  break;
238                 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE;   break;
239                 default:
240                     SetLastError(ERROR_INVALID_PARAMETER);
241                     WCMD_print_error();
242                     errorlevel = 1;
243                     return;
244                 }
245
246                 /* Keep running list of bits we care about */
247                 attrsbits |= mask;
248
249                 /* Mask shows what MUST be in the bits we care about */
250                 if (anegate) showattrs = showattrs & ~mask;
251                 else showattrs |= mask;
252
253                 p++;
254               }
255               p = p - 1; /* So when step on, move to '/' */
256               WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
257               break;
258     default:
259               SetLastError(ERROR_INVALID_PARAMETER);
260               WCMD_print_error();
261               errorlevel = 1;
262               return;
263     }
264     p = p + 1;
265   }
266
267   /* Handle conflicting args and initialization */
268   if (bare || shortname) wide = FALSE;
269   if (bare) shortname = FALSE;
270   if (wide) usernames = FALSE;
271   if (orderByCol) wide = TRUE;
272
273   if (wide) {
274       if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
275           max_width = consoleInfo.dwSize.X;
276       else
277           max_width = 80;
278   }
279   if (paged_mode) {
280      WCMD_enter_paged_mode(NULL);
281   }
282
283   argno         = 0;
284   argsProcessed = 0;
285   argN          = cmd;
286   GetCurrentDirectory (MAX_PATH, cwd);
287   strcatW(cwd, slashW);
288
289   /* Loop through all args, calculating full effective directory */
290   fullParms = NULL;
291   prevEntry = NULL;
292   while (argN) {
293     WCHAR fullname[MAXSTRING];
294     WCHAR *thisArg = WCMD_parameter (cmd, argno++, &argN);
295     if (argN && argN[0] != '/') {
296
297       WINE_TRACE("Found parm '%s'\n", wine_dbgstr_w(thisArg));
298       if (thisArg[1] == ':' && thisArg[2] == '\\') {
299         strcpyW(fullname, thisArg);
300       } else if (thisArg[1] == ':' && thisArg[2] != '\\') {
301         WCHAR envvar[4];
302         static const WCHAR envFmt[] = {'=','%','c',':','\0'};
303         wsprintf(envvar, envFmt, thisArg[0]);
304         if (!GetEnvironmentVariable(envvar, fullname, MAX_PATH)) {
305           static const WCHAR noEnvFmt[] = {'%','c',':','\0'};
306           wsprintf(fullname, noEnvFmt, thisArg[0]);
307         }
308         strcatW(fullname, slashW);
309         strcatW(fullname, &thisArg[2]);
310       } else if (thisArg[0] == '\\') {
311         memcpy(fullname, cwd, 2 * sizeof(WCHAR));
312         strcpyW(fullname+2, thisArg);
313       } else {
314         strcpyW(fullname, cwd);
315         strcatW(fullname, thisArg);
316       }
317       WINE_TRACE("Using location '%s'\n", wine_dbgstr_w(fullname));
318
319       status = GetFullPathName (fullname, sizeof(path)/sizeof(WCHAR), path, NULL);
320
321       /*
322        *  If the path supplied does not include a wildcard, and the endpoint of the
323        *  path references a directory, we need to list the *contents* of that
324        *  directory not the directory file itself.
325        */
326       if ((strchrW(path, '*') == NULL) && (strchrW(path, '%') == NULL)) {
327         status = GetFileAttributes (path);
328         if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
329           if (path[strlenW(path)-1] == '\\') {
330             strcatW (path, starW);
331           }
332           else {
333             const WCHAR slashStarW[]  = {'\\','*','\0'};
334             strcatW (path, slashStarW);
335           }
336         }
337       } else {
338         /* Special case wildcard search with no extension (ie parameters ending in '.') as
339            GetFullPathName strips off the additional '.'                                  */
340         if (fullname[strlenW(fullname)-1] == '.') strcatW(path, dotW);
341       }
342
343       WINE_TRACE("Using path '%s'\n", wine_dbgstr_w(path));
344       thisEntry = (DIRECTORY_STACK *) HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
345       if (fullParms == NULL) fullParms = thisEntry;
346       if (prevEntry != NULL) prevEntry->next = thisEntry;
347       prevEntry = thisEntry;
348       thisEntry->next = NULL;
349
350       /* Split into components */
351       WCMD_splitpath(path, drive, dir, fname, ext);
352       WINE_TRACE("Path Parts: drive: '%s' dir: '%s' name: '%s' ext:'%s'\n",
353                  wine_dbgstr_w(drive), wine_dbgstr_w(dir),
354                  wine_dbgstr_w(fname), wine_dbgstr_w(ext));
355
356       thisEntry->dirName = HeapAlloc(GetProcessHeap(),0,
357                                      sizeof(WCHAR) * (strlenW(drive)+strlenW(dir)+1));
358       strcpyW(thisEntry->dirName, drive);
359       strcatW(thisEntry->dirName, dir);
360
361       thisEntry->fileName = HeapAlloc(GetProcessHeap(),0,
362                                      sizeof(WCHAR) * (strlenW(fname)+strlenW(ext)+1));
363       strcpyW(thisEntry->fileName, fname);
364       strcatW(thisEntry->fileName, ext);
365
366     }
367   }
368
369   /* If just 'dir' entered, a '*' parameter is assumed */
370   if (fullParms == NULL) {
371     WINE_TRACE("Inserting default '*'\n");
372     fullParms = (DIRECTORY_STACK *) HeapAlloc(GetProcessHeap(),0, sizeof(DIRECTORY_STACK));
373     fullParms->next = NULL;
374     fullParms->dirName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * (strlenW(cwd)+1));
375     strcpyW(fullParms->dirName, cwd);
376     fullParms->fileName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * 2);
377     strcpyW(fullParms->fileName, starW);
378   }
379
380   lastDrive = '?';
381   prevEntry = NULL;
382   thisEntry = fullParms;
383   trailerReqd = FALSE;
384
385   while (thisEntry != NULL) {
386
387     /* Output disk free (trailer) and volume information (header) if the drive
388        letter changes */
389     if (lastDrive != toupper(thisEntry->dirName[0])) {
390
391       /* Trailer Information */
392       if (lastDrive != '?') {
393         trailerReqd = FALSE;
394         WCMD_dir_trailer(prevEntry->dirName[0]);
395       }
396
397       lastDrive = toupper(thisEntry->dirName[0]);
398
399       if (!bare) {
400          WCHAR drive[3];
401
402          WINE_TRACE("Writing volume for '%c:'\n", thisEntry->dirName[0]);
403          memcpy(drive, thisEntry->dirName, 2 * sizeof(WCHAR));
404          drive[2] = 0x00;
405          status = WCMD_volume (0, drive);
406          trailerReqd = TRUE;
407          if (!status) {
408            errorlevel = 1;
409            goto exit;
410          }
411       }
412     } else {
413       static const WCHAR newLine2[] = {'\n','\n','\0'};
414       if (!bare) WCMD_output (newLine2);
415     }
416
417     /* Clear any errors from previous invocations, and process it */
418     errorlevel = 0;
419     prevEntry = thisEntry;
420     thisEntry = WCMD_list_directory (thisEntry, 0);
421   }
422
423   /* Trailer Information */
424   if (trailerReqd) {
425     WCMD_dir_trailer(prevEntry->dirName[0]);
426   }
427
428 exit:
429   if (paged_mode) WCMD_leave_paged_mode();
430
431   /* Free storage allocated for parms */
432   while (fullParms != NULL) {
433     prevEntry = fullParms;
434     fullParms = prevEntry->next;
435     HeapFree(GetProcessHeap(),0,prevEntry->dirName);
436     HeapFree(GetProcessHeap(),0,prevEntry->fileName);
437     HeapFree(GetProcessHeap(),0,prevEntry);
438   }
439 }
440
441 /*****************************************************************************
442  * WCMD_list_directory
443  *
444  * List a single file directory. This function (and those below it) can be called
445  * recursively when the /S switch is used.
446  *
447  * FIXME: Assumes 24-line display for the /P qualifier.
448  */
449
450 static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *inputparms, int level) {
451
452   WCHAR string[1024], datestring[32], timestring[32];
453   WCHAR real_path[MAX_PATH];
454   WIN32_FIND_DATA *fd;
455   FILETIME ft;
456   SYSTEMTIME st;
457   HANDLE hff;
458   int dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
459   int numCols, numRows;
460   int rows, cols;
461   ULARGE_INTEGER byte_count, file_size;
462   DIRECTORY_STACK *parms;
463   int concurrentDirs = 0;
464   BOOL done_header = FALSE;
465
466   static const WCHAR fmtDir[]  = {'%','1','0','s',' ',' ','%','8','s',' ',' ',
467                                   '<','D','I','R','>',' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
468   static const WCHAR fmtFile[] = {'%','1','0','s',' ',' ','%','8','s',' ',' ',
469                                   ' ',' ','%','1','0','s',' ',' ','\0'};
470   static const WCHAR fmt2[]  = {'%','-','1','3','s','\0'};
471   static const WCHAR fmt3[]  = {'%','-','2','3','s','\0'};
472   static const WCHAR fmt4[]  = {'%','s','\0'};
473   static const WCHAR fmt5[]  = {'%','s','%','s','\0'};
474
475   dir_count = 0;
476   file_count = 0;
477   entry_count = 0;
478   byte_count.QuadPart = 0;
479   widest = 0;
480   cur_width = 0;
481
482   /* Loop merging all the files from consecutive parms which relate to the
483      same directory. Note issuing a directory header with no contents
484      mirrors what windows does                                            */
485   parms = inputparms;
486   fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA));
487   while (parms && strcmpW(inputparms->dirName, parms->dirName) == 0) {
488     concurrentDirs++;
489
490     /* Work out the full path + filename */
491     strcpyW(real_path, parms->dirName);
492     strcatW(real_path, parms->fileName);
493
494     /* Load all files into an in memory structure */
495     WINE_TRACE("Looking for matches to '%s'\n", wine_dbgstr_w(real_path));
496     hff = FindFirstFile (real_path, (fd+entry_count));
497     if (hff != INVALID_HANDLE_VALUE) {
498       do {
499         /* Skip any which are filtered out by attribute */
500         if (((fd+entry_count)->dwFileAttributes & attrsbits) != showattrs) continue;
501
502         entry_count++;
503
504         /* Keep running track of longest filename for wide output */
505         if (wide || orderByCol) {
506            int tmpLen = strlenW((fd+(entry_count-1))->cFileName) + 3;
507            if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
508            if (tmpLen > widest) widest = tmpLen;
509         }
510
511         fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
512         if (fd == NULL) {
513           FindClose (hff);
514           WINE_ERR ("Out of memory");
515           errorlevel = 1;
516           return parms->next;
517         }
518       } while (FindNextFile(hff, (fd+entry_count)) != 0);
519       FindClose (hff);
520     }
521
522     /* Work out the actual current directory name without a trailing \ */
523     strcpyW(real_path, parms->dirName);
524     real_path[strlenW(parms->dirName)-1] = 0x00;
525
526     /* Output the results */
527     if (!bare) {
528        if (level != 0 && (entry_count > 0)) WCMD_output (newline);
529        if (!recurse || ((entry_count > 0) && done_header==FALSE)) {
530            static const WCHAR headerW[] = {'D','i','r','e','c','t','o','r','y',' ','o','f',
531                                            ' ','%','s','\n','\n','\0'};
532            WCMD_output (headerW, real_path);
533            done_header = TRUE;
534        }
535     }
536
537     /* Move to next parm */
538     parms = parms->next;
539   }
540
541   /* Handle case where everything is filtered out */
542   if (entry_count > 0) {
543
544     /* Sort the list of files */
545     qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
546
547     /* Work out the number of columns */
548     WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
549     if (wide || orderByCol) {
550       numCols = max(1, (int)max_width / widest);
551       numRows = entry_count / numCols;
552       if (entry_count % numCols) numRows++;
553     } else {
554       numCols = 1;
555       numRows = entry_count;
556     }
557     WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
558
559     for (rows=0; rows<numRows; rows++) {
560      BOOL addNewLine = TRUE;
561      for (cols=0; cols<numCols; cols++) {
562       WCHAR username[24];
563
564       /* Work out the index of the entry being pointed to */
565       if (orderByCol) {
566         i = (cols * numRows) + rows;
567         if (i >= entry_count) continue;
568       } else {
569         i = (rows * numCols) + cols;
570         if (i >= entry_count) continue;
571       }
572
573       /* /L convers all names to lower case */
574       if (lower) {
575           WCHAR *p = (fd+i)->cFileName;
576           while ( (*p = tolower(*p)) ) ++p;
577       }
578
579       /* /Q gets file ownership information */
580       if (usernames) {
581           strcpyW (string, inputparms->dirName);
582           strcatW (string, (fd+i)->cFileName);
583           WCMD_getfileowner(string, username, sizeof(username)/sizeof(WCHAR));
584       }
585
586       if (dirTime == Written) {
587         FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
588       } else if (dirTime == Access) {
589         FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
590       } else {
591         FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
592       }
593       FileTimeToSystemTime (&ft, &st);
594       GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
595                         sizeof(datestring)/sizeof(WCHAR));
596       GetTimeFormat (0, TIME_NOSECONDS, &st,
597                         NULL, timestring, sizeof(timestring)/sizeof(WCHAR));
598
599       if (wide) {
600
601         tmp_width = cur_width;
602         if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
603             static const WCHAR fmt[] = {'[','%','s',']','\0'};
604             WCMD_output (fmt, (fd+i)->cFileName);
605             dir_count++;
606             tmp_width = tmp_width + strlenW((fd+i)->cFileName) + 2;
607         } else {
608             static const WCHAR fmt[] = {'%','s','\0'};
609             WCMD_output (fmt, (fd+i)->cFileName);
610             tmp_width = tmp_width + strlenW((fd+i)->cFileName) ;
611             file_count++;
612             file_size.u.LowPart = (fd+i)->nFileSizeLow;
613             file_size.u.HighPart = (fd+i)->nFileSizeHigh;
614         byte_count.QuadPart += file_size.QuadPart;
615         }
616         cur_width = cur_width + widest;
617
618         if ((cur_width + widest) > max_width) {
619             cur_width = 0;
620         } else {
621             static const WCHAR fmt[]  = {'%','*','.','s','\0'};
622             WCMD_output (fmt, (tmp_width - cur_width), emptyW);
623         }
624
625       } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
626         dir_count++;
627
628         if (!bare) {
629            WCMD_output (fmtDir, datestring, timestring);
630            if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
631            if (usernames) WCMD_output (fmt3, username);
632            WCMD_output(fmt4,(fd+i)->cFileName);
633         } else {
634            if (!((strcmpW((fd+i)->cFileName, dotW) == 0) ||
635                  (strcmpW((fd+i)->cFileName, dotdotW) == 0))) {
636               WCMD_output (fmt5, recurse?inputparms->dirName:emptyW, (fd+i)->cFileName);
637            } else {
638               addNewLine = FALSE;
639            }
640         }
641       }
642       else {
643         file_count++;
644         file_size.u.LowPart = (fd+i)->nFileSizeLow;
645         file_size.u.HighPart = (fd+i)->nFileSizeHigh;
646         byte_count.QuadPart += file_size.QuadPart;
647         if (!bare) {
648            WCMD_output (fmtFile, datestring, timestring,
649                         WCMD_filesize64(file_size.QuadPart));
650            if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
651            if (usernames) WCMD_output (fmt3, username);
652            WCMD_output(fmt4,(fd+i)->cFileName);
653         } else {
654            WCMD_output (fmt5, recurse?inputparms->dirName:emptyW, (fd+i)->cFileName);
655         }
656       }
657      }
658      if (addNewLine) WCMD_output (newline);
659      cur_width = 0;
660     }
661
662     if (!bare) {
663        if (file_count == 1) {
664          static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ',
665                                      '%','2','5','s',' ','b','y','t','e','s','\n','\0'};
666          WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart));
667        }
668        else {
669          static const WCHAR fmt[] = {'%','8','d',' ','f','i','l','e','s',' ','%','2','4','s',
670                                      ' ','b','y','t','e','s','\n','\0'};
671          WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart));
672        }
673     }
674     byte_total = byte_total + byte_count.QuadPart;
675     file_total = file_total + file_count;
676     dir_total = dir_total + dir_count;
677
678     if (!bare && !recurse) {
679        if (dir_count == 1) {
680            static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','y',
681                                        ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
682            WCMD_output (fmt, 1);
683        } else {
684            static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','i',
685                                        'e','s','\0'};
686            WCMD_output (fmt, dir_count);
687        }
688     }
689   }
690   HeapFree(GetProcessHeap(),0,fd);
691
692   /* When recursing, look in all subdirectories for matches */
693   if (recurse) {
694     DIRECTORY_STACK *dirStack = NULL;
695     DIRECTORY_STACK *lastEntry = NULL;
696     WIN32_FIND_DATA finddata;
697
698     /* Build path to search */
699     strcpyW(string, inputparms->dirName);
700     strcatW(string, starW);
701
702     WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
703     hff = FindFirstFile (string, &finddata);
704     if (hff != INVALID_HANDLE_VALUE) {
705       do {
706         if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
707             (strcmpW(finddata.cFileName, dotdotW) != 0) &&
708             (strcmpW(finddata.cFileName, dotW) != 0)) {
709
710           DIRECTORY_STACK *thisDir;
711           int              dirsToCopy = concurrentDirs;
712
713           /* Loop creating list of subdirs for all concurrent entries */
714           parms = inputparms;
715           while (dirsToCopy > 0) {
716             dirsToCopy--;
717
718             /* Work out search parameter in sub dir */
719             strcpyW (string, inputparms->dirName);
720             strcatW (string, finddata.cFileName);
721             strcatW (string, slashW);
722             WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));
723
724             /* Allocate memory, add to list */
725             thisDir = (DIRECTORY_STACK *) HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
726             if (dirStack == NULL) dirStack = thisDir;
727             if (lastEntry != NULL) lastEntry->next = thisDir;
728             lastEntry = thisDir;
729             thisDir->next = NULL;
730             thisDir->dirName = HeapAlloc(GetProcessHeap(),0,
731                                          sizeof(WCHAR) * (strlenW(string)+1));
732             strcpyW(thisDir->dirName, string);
733             thisDir->fileName = HeapAlloc(GetProcessHeap(),0,
734                                           sizeof(WCHAR) * (strlenW(parms->fileName)+1));
735             strcpyW(thisDir->fileName, parms->fileName);
736             parms = parms->next;
737           }
738         }
739       } while (FindNextFile(hff, &finddata) != 0);
740       FindClose (hff);
741
742       while (dirStack != NULL) {
743         DIRECTORY_STACK *thisDir = dirStack;
744         dirStack = WCMD_list_directory (thisDir, 1);
745         while (thisDir != dirStack) {
746           DIRECTORY_STACK *tempDir = thisDir->next;
747           HeapFree(GetProcessHeap(),0,thisDir->dirName);
748           HeapFree(GetProcessHeap(),0,thisDir->fileName);
749           HeapFree(GetProcessHeap(),0,thisDir);
750           thisDir = tempDir;
751         }
752       }
753     }
754   }
755
756   /* Handle case where everything is filtered out */
757   if ((file_total + dir_total == 0) && (level == 0)) {
758     SetLastError (ERROR_FILE_NOT_FOUND);
759     WCMD_print_error ();
760     errorlevel = 1;
761   }
762
763   return parms;
764 }
765
766 /*****************************************************************************
767  * WCMD_filesize64
768  *
769  * Convert a 64-bit number into a WCHARacter string, with commas every three digits.
770  * Result is returned in a static string overwritten with each call.
771  * FIXME: There must be a better algorithm!
772  */
773
774 WCHAR * WCMD_filesize64 (ULONGLONG n) {
775
776   ULONGLONG q;
777   unsigned int r, i;
778   WCHAR *p;
779   static WCHAR buff[32];
780
781   p = buff;
782   i = -3;
783   do {
784     if (separator && ((++i)%3 == 1)) *p++ = ',';
785     q = n / 10;
786     r = n - (q * 10);
787     *p++ = r + '0';
788     *p = '\0';
789     n = q;
790   } while (n != 0);
791   WCMD_strrev (buff);
792   return buff;
793 }
794
795 /*****************************************************************************
796  * WCMD_strrev
797  *
798  * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
799  */
800
801 WCHAR * WCMD_strrev (WCHAR *buff) {
802
803   int r, i;
804   WCHAR b;
805
806   r = strlenW (buff);
807   for (i=0; i<r/2; i++) {
808     b = buff[i];
809     buff[i] = buff[r-i-1];
810     buff[r-i-1] = b;
811   }
812   return (buff);
813 }
814
815
816 /*****************************************************************************
817  * WCMD_dir_sort
818  *
819  * Sort based on the /O options supplied on the command line
820  */
821 int WCMD_dir_sort (const void *a, const void *b)
822 {
823   WIN32_FIND_DATA *filea = (WIN32_FIND_DATA *)a;
824   WIN32_FIND_DATA *fileb = (WIN32_FIND_DATA *)b;
825   int result = 0;
826
827   /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
828      requested sort order for the directory components                   */
829   if (orderGroupDirs &&
830       ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
831        (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
832   {
833     BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
834     if (aDir) result = -1;
835     else result = 1;
836     if (orderGroupDirsReverse) result = -result;
837     return result;
838
839   /* Order by Name: */
840   } else if (dirOrder == Name) {
841     result = lstrcmpiW(filea->cFileName, fileb->cFileName);
842
843   /* Order by Size: */
844   } else if (dirOrder == Size) {
845     ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
846     ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
847     if( sizea < sizeb ) result = -1;
848     else if( sizea == sizeb ) result = 0;
849     else result = 1;
850
851   /* Order by Date: (Takes into account which date (/T option) */
852   } else if (dirOrder == Date) {
853
854     FILETIME *ft;
855     ULONG64 timea, timeb;
856
857     if (dirTime == Written) {
858       ft = &filea->ftLastWriteTime;
859       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
860       ft = &fileb->ftLastWriteTime;
861       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
862     } else if (dirTime == Access) {
863       ft = &filea->ftLastAccessTime;
864       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
865       ft = &fileb->ftLastAccessTime;
866       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
867     } else {
868       ft = &filea->ftCreationTime;
869       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
870       ft = &fileb->ftCreationTime;
871       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
872     }
873     if( timea < timeb ) result = -1;
874     else if( timea == timeb ) result = 0;
875     else result = 1;
876
877   /* Order by Extension: (Takes into account which date (/T option) */
878   } else if (dirOrder == Extension) {
879       WCHAR drive[10];
880       WCHAR dir[MAX_PATH];
881       WCHAR fname[MAX_PATH];
882       WCHAR extA[MAX_PATH];
883       WCHAR extB[MAX_PATH];
884
885       /* Split into components */
886       WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
887       WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
888       result = lstrcmpiW(extA, extB);
889   }
890
891   if (orderReverse) result = -result;
892   return result;
893 }
894
895 /*****************************************************************************
896  * WCMD_getfileowner
897  *
898  * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
899  */
900 void WCMD_getfileowner(WCHAR *filename, WCHAR *owner, int ownerlen) {
901
902     ULONG sizeNeeded = 0;
903     DWORD rc;
904     WCHAR name[MAXSTRING];
905     WCHAR domain[MAXSTRING];
906
907     /* In case of error, return empty string */
908     *owner = 0x00;
909
910     /* Find out how much space we need for the owner security descritpor */
911     GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
912     rc = GetLastError();
913
914     if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
915
916         LPBYTE secBuffer;
917         PSID pSID = NULL;
918         BOOL defaulted = FALSE;
919         ULONG nameLen = MAXSTRING;
920         ULONG domainLen = MAXSTRING;
921         SID_NAME_USE nameuse;
922
923         secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
924         if(!secBuffer) return;
925
926         /* Get the owners security descriptor */
927         if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
928                             sizeNeeded, &sizeNeeded)) {
929             HeapFree(GetProcessHeap(),0,secBuffer);
930             return;
931         }
932
933         /* Get the SID from the SD */
934         if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
935             HeapFree(GetProcessHeap(),0,secBuffer);
936             return;
937         }
938
939         /* Convert to a username */
940         if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
941             static const WCHAR fmt[]  = {'%','s','%','c','%','s','\0'};
942             snprintfW(owner, ownerlen, fmt, domain, '\\', name);
943         }
944         HeapFree(GetProcessHeap(),0,secBuffer);
945     }
946     return;
947 }
948
949 /*****************************************************************************
950  * WCMD_dir_trailer
951  *
952  * Print out the trailer for the supplied drive letter
953  */
954 static void WCMD_dir_trailer(WCHAR drive) {
955     ULARGE_INTEGER avail, total, freebytes;
956     DWORD status;
957     WCHAR driveName[4] = {'c',':','\\','\0'};
958
959     driveName[0] = drive;
960     status = GetDiskFreeSpaceEx (driveName, &avail, &total, &freebytes);
961     WINE_TRACE("Writing trailer for '%s' gave %d(%d)\n", wine_dbgstr_w(driveName),
962                status, GetLastError());
963
964     if (errorlevel==0 && !bare) {
965       if (recurse) {
966         static const WCHAR fmt1[] = {'\n',' ',' ',' ',' ',' ','T','o','t','a','l',' ','f','i','l','e','s',
967                                      ' ','l','i','s','t','e','d',':','\n','%','8','d',' ','f','i','l','e',
968                                      's','%','2','5','s',' ','b','y','t','e','s','\n','\0'};
969         static const WCHAR fmt2[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','i','e','s',' ','%',
970                                      '1','8','s',' ','b','y','t','e','s',' ','f','r','e','e','\n','\n',
971                                      '\0'};
972         WCMD_output (fmt1, file_total, WCMD_filesize64 (byte_total));
973         WCMD_output (fmt2, dir_total, WCMD_filesize64 (freebytes.QuadPart));
974       } else {
975         static const WCHAR fmt[] = {' ','%','1','8','s',' ','b','y','t','e','s',' ','f','r','e','e',
976                                     '\n','\n','\0'};
977         WCMD_output (fmt, WCMD_filesize64 (freebytes.QuadPart));
978       }
979     }
980 }