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