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