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