cmd: Use FormatMessage() for better internationalization support.
[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 (newline);
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             static const WCHAR empty[] = {'\0'};
414             WCMD_output(padfmt, cur_width - tmp_width, empty);
415         }
416
417       } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
418         dir_count++;
419
420         if (!bare) {
421            WCMD_output (fmtDir, datestring, timestring);
422            if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
423            if (usernames) WCMD_output (fmt3, username);
424            WCMD_output(fmt4,(fd+i)->cFileName);
425         } else {
426            if (!((strcmpW((fd+i)->cFileName, dotW) == 0) ||
427                  (strcmpW((fd+i)->cFileName, dotdotW) == 0))) {
428               WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
429            } else {
430               addNewLine = FALSE;
431            }
432         }
433       }
434       else {
435         file_count++;
436         file_size.u.LowPart = (fd+i)->nFileSizeLow;
437         file_size.u.HighPart = (fd+i)->nFileSizeHigh;
438         byte_count.QuadPart += file_size.QuadPart;
439         if (!bare) {
440            WCMD_output (fmtFile, datestring, timestring,
441                         WCMD_filesize64(file_size.QuadPart));
442            if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
443            if (usernames) WCMD_output (fmt3, username);
444            WCMD_output(fmt4,(fd+i)->cFileName);
445         } else {
446            WCMD_output (fmt5, recurse?inputparms->dirName:nullW, (fd+i)->cFileName);
447         }
448       }
449      }
450      if (addNewLine) WCMD_output_asis (newline);
451      cur_width = 0;
452     }
453
454     if (!bare) {
455        if (file_count == 1) {
456          static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ',
457                                      '%','1','!','2','5','s','!',' ','b','y','t','e','s','\n','\0'};
458          WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart));
459        }
460        else {
461          static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','f','i','l','e','s',' ','%','2','!','2','4','s','!',
462                                      ' ','b','y','t','e','s','\n','\0'};
463          WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart));
464        }
465     }
466     byte_total = byte_total + byte_count.QuadPart;
467     file_total = file_total + file_count;
468     dir_total = dir_total + dir_count;
469
470     if (!bare && !recurse) {
471        if (dir_count == 1) {
472            static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','y',
473                                        ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
474            WCMD_output (fmt, 1);
475        } else {
476            static const WCHAR fmt[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','i',
477                                        'e','s','\0'};
478            WCMD_output (fmt, dir_count);
479        }
480     }
481   }
482   HeapFree(GetProcessHeap(),0,fd);
483
484   /* When recursing, look in all subdirectories for matches */
485   if (recurse) {
486     DIRECTORY_STACK *dirStack = NULL;
487     DIRECTORY_STACK *lastEntry = NULL;
488     WIN32_FIND_DATAW finddata;
489
490     /* Build path to search */
491     strcpyW(string, inputparms->dirName);
492     strcatW(string, starW);
493
494     WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
495     hff = FindFirstFileW(string, &finddata);
496     if (hff != INVALID_HANDLE_VALUE) {
497       do {
498         if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
499             (strcmpW(finddata.cFileName, dotdotW) != 0) &&
500             (strcmpW(finddata.cFileName, dotW) != 0)) {
501
502           DIRECTORY_STACK *thisDir;
503           int              dirsToCopy = concurrentDirs;
504
505           /* Loop creating list of subdirs for all concurrent entries */
506           parms = inputparms;
507           while (dirsToCopy > 0) {
508             dirsToCopy--;
509
510             /* Work out search parameter in sub dir */
511             strcpyW (string, inputparms->dirName);
512             strcatW (string, finddata.cFileName);
513             strcatW (string, slashW);
514             WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));
515
516             /* Allocate memory, add to list */
517             thisDir = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
518             if (dirStack == NULL) dirStack = thisDir;
519             if (lastEntry != NULL) lastEntry->next = thisDir;
520             lastEntry = thisDir;
521             thisDir->next = NULL;
522             thisDir->dirName = HeapAlloc(GetProcessHeap(),0,
523                                          sizeof(WCHAR) * (strlenW(string)+1));
524             strcpyW(thisDir->dirName, string);
525             thisDir->fileName = HeapAlloc(GetProcessHeap(),0,
526                                           sizeof(WCHAR) * (strlenW(parms->fileName)+1));
527             strcpyW(thisDir->fileName, parms->fileName);
528             parms = parms->next;
529           }
530         }
531       } while (FindNextFileW(hff, &finddata) != 0);
532       FindClose (hff);
533
534       while (dirStack != NULL) {
535         DIRECTORY_STACK *thisDir = dirStack;
536         dirStack = WCMD_list_directory (thisDir, 1);
537         while (thisDir != dirStack) {
538           DIRECTORY_STACK *tempDir = thisDir->next;
539           HeapFree(GetProcessHeap(),0,thisDir->dirName);
540           HeapFree(GetProcessHeap(),0,thisDir->fileName);
541           HeapFree(GetProcessHeap(),0,thisDir);
542           thisDir = tempDir;
543         }
544       }
545     }
546   }
547
548   /* Handle case where everything is filtered out */
549   if ((file_total + dir_total == 0) && (level == 0)) {
550     SetLastError (ERROR_FILE_NOT_FOUND);
551     WCMD_print_error ();
552     errorlevel = 1;
553   }
554
555   return parms;
556 }
557
558 /*****************************************************************************
559  * WCMD_dir_trailer
560  *
561  * Print out the trailer for the supplied drive letter
562  */
563 static void WCMD_dir_trailer(WCHAR drive) {
564     ULARGE_INTEGER avail, total, freebytes;
565     DWORD status;
566     WCHAR driveName[4] = {'c',':','\\','\0'};
567
568     driveName[0] = drive;
569     status = GetDiskFreeSpaceExW(driveName, &avail, &total, &freebytes);
570     WINE_TRACE("Writing trailer for '%s' gave %d(%d)\n", wine_dbgstr_w(driveName),
571                status, GetLastError());
572
573     if (errorlevel==0 && !bare) {
574       if (recurse) {
575         static const WCHAR fmt1[] = {'\n',' ',' ',' ',' ',' ','T','o','t','a','l',' ','f','i','l','e','s',
576                                      ' ','l','i','s','t','e','d',':','\n','%','1','!','8','d','!',' ','f','i','l','e',
577                                      's','%','2','!','2','5','s','!',' ','b','y','t','e','s','\n','\0'};
578         static const WCHAR fmt2[] = {'%','1','!','8','d','!',' ','d','i','r','e','c','t','o','r','i','e','s',' ','%',
579                                      '2','!','1','8','s','!',' ','b','y','t','e','s',' ','f','r','e','e','\n','\n',
580                                      '\0'};
581         WCMD_output (fmt1, file_total, WCMD_filesize64 (byte_total));
582         WCMD_output (fmt2, dir_total, WCMD_filesize64 (freebytes.QuadPart));
583       } else {
584         static const WCHAR fmt[] = {' ','%','1','!','1','8','s','!',' ','b','y','t','e','s',' ','f','r','e','e',
585                                     '\n','\n','\0'};
586         WCMD_output (fmt, WCMD_filesize64 (freebytes.QuadPart));
587       }
588     }
589 }
590
591 /*****************************************************************************
592  * WCMD_directory
593  *
594  * List a file directory.
595  *
596  */
597
598 void WCMD_directory (WCHAR *cmd)
599 {
600   WCHAR path[MAX_PATH], cwd[MAX_PATH];
601   DWORD status;
602   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
603   WCHAR *p;
604   WCHAR string[MAXSTRING];
605   int   argno         = 0;
606   WCHAR *argN          = cmd;
607   WCHAR  lastDrive;
608   BOOL  trailerReqd = FALSE;
609   DIRECTORY_STACK *fullParms = NULL;
610   DIRECTORY_STACK *prevEntry = NULL;
611   DIRECTORY_STACK *thisEntry = NULL;
612   WCHAR drive[10];
613   WCHAR dir[MAX_PATH];
614   WCHAR fname[MAX_PATH];
615   WCHAR ext[MAX_PATH];
616   static const WCHAR dircmdW[] = {'D','I','R','C','M','D','\0'};
617
618   errorlevel = 0;
619
620   /* Prefill quals with (uppercased) DIRCMD env var */
621   if (GetEnvironmentVariableW(dircmdW, string, sizeof(string)/sizeof(WCHAR))) {
622     p = string;
623     while ( (*p = toupper(*p)) ) ++p;
624     strcatW(string,quals);
625     strcpyW(quals, string);
626   }
627
628   byte_total = 0;
629   file_total = dir_total = 0;
630
631   /* Initialize all flags to their defaults as if no DIRCMD or quals */
632   paged_mode = FALSE;
633   recurse    = FALSE;
634   wide       = FALSE;
635   bare       = FALSE;
636   lower      = FALSE;
637   shortname  = FALSE;
638   usernames  = FALSE;
639   orderByCol = FALSE;
640   separator  = TRUE;
641   dirTime = Written;
642   dirOrder = Name;
643   orderReverse = FALSE;
644   orderGroupDirs = FALSE;
645   orderGroupDirsReverse = FALSE;
646   showattrs  = 0;
647   attrsbits  = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
648
649   /* Handle args - Loop through so right most is the effective one */
650   /* Note: /- appears to be a negate rather than an off, eg. dir
651            /-W is wide, or dir /w /-w /-w is also wide             */
652   p = quals;
653   while (*p && (*p=='/' || *p==' ')) {
654     BOOL negate = FALSE;
655     if (*p++==' ') continue;  /* Skip / and blanks introduced through DIRCMD */
656
657     if (*p=='-') {
658       negate = TRUE;
659       p++;
660     }
661
662     WINE_TRACE("Processing arg '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
663     switch (*p) {
664     case 'P': if (negate) paged_mode = !paged_mode;
665               else paged_mode = TRUE;
666               break;
667     case 'S': if (negate) recurse = !recurse;
668               else recurse = TRUE;
669               break;
670     case 'W': if (negate) wide = !wide;
671               else wide = TRUE;
672               break;
673     case 'B': if (negate) bare = !bare;
674               else bare = TRUE;
675               break;
676     case 'L': if (negate) lower = !lower;
677               else lower = TRUE;
678               break;
679     case 'X': if (negate) shortname = !shortname;
680               else shortname = TRUE;
681               break;
682     case 'Q': if (negate) usernames = !usernames;
683               else usernames = TRUE;
684               break;
685     case 'D': if (negate) orderByCol = !orderByCol;
686               else orderByCol = TRUE;
687               break;
688     case 'C': if (negate) separator = !separator;
689               else separator = TRUE;
690               break;
691     case 'T': p = p + 1;
692               if (*p==':') p++;  /* Skip optional : */
693
694               if (*p == 'A') dirTime = Access;
695               else if (*p == 'C') dirTime = Creation;
696               else if (*p == 'W') dirTime = Written;
697
698               /* Support /T and /T: with no parms, default to written */
699               else if (*p == 0x00 || *p == '/') {
700                 dirTime = Written;
701                 p = p - 1; /* So when step on, move to '/' */
702               } else {
703                 SetLastError(ERROR_INVALID_PARAMETER);
704                 WCMD_print_error();
705                 errorlevel = 1;
706                 return;
707               }
708               break;
709     case 'O': p = p + 1;
710               if (*p==':') p++;  /* Skip optional : */
711               while (*p && *p != '/') {
712                 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
713                 switch (*p) {
714                 case 'N': dirOrder = Name;       break;
715                 case 'E': dirOrder = Extension;  break;
716                 case 'S': dirOrder = Size;       break;
717                 case 'D': dirOrder = Date;       break;
718                 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
719                           else orderReverse = TRUE;
720                           break;
721                 case 'G': orderGroupDirs = TRUE; break;
722                 default:
723                     SetLastError(ERROR_INVALID_PARAMETER);
724                     WCMD_print_error();
725                     errorlevel = 1;
726                     return;
727                 }
728                 p++;
729               }
730               p = p - 1; /* So when step on, move to '/' */
731               break;
732     case 'A': p = p + 1;
733               showattrs = 0;
734               attrsbits = 0;
735               if (*p==':') p++;  /* Skip optional : */
736               while (*p && *p != '/') {
737                 BOOL anegate = FALSE;
738                 ULONG mask;
739
740                 /* Note /A: - options are 'offs' not toggles */
741                 if (*p=='-') {
742                   anegate = TRUE;
743                   p++;
744                 }
745
746                 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
747                 switch (*p) {
748                 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
749                 case 'H': mask = FILE_ATTRIBUTE_HIDDEN;    break;
750                 case 'S': mask = FILE_ATTRIBUTE_SYSTEM;    break;
751                 case 'R': mask = FILE_ATTRIBUTE_READONLY;  break;
752                 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE;   break;
753                 default:
754                     SetLastError(ERROR_INVALID_PARAMETER);
755                     WCMD_print_error();
756                     errorlevel = 1;
757                     return;
758                 }
759
760                 /* Keep running list of bits we care about */
761                 attrsbits |= mask;
762
763                 /* Mask shows what MUST be in the bits we care about */
764                 if (anegate) showattrs = showattrs & ~mask;
765                 else showattrs |= mask;
766
767                 p++;
768               }
769               p = p - 1; /* So when step on, move to '/' */
770               WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
771               break;
772     default:
773               SetLastError(ERROR_INVALID_PARAMETER);
774               WCMD_print_error();
775               errorlevel = 1;
776               return;
777     }
778     p = p + 1;
779   }
780
781   /* Handle conflicting args and initialization */
782   if (bare || shortname) wide = FALSE;
783   if (bare) shortname = FALSE;
784   if (wide) usernames = FALSE;
785   if (orderByCol) wide = TRUE;
786
787   if (wide) {
788       if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
789           max_width = consoleInfo.dwSize.X;
790       else
791           max_width = 80;
792   }
793   if (paged_mode) {
794      WCMD_enter_paged_mode(NULL);
795   }
796
797   argno         = 0;
798   argN          = cmd;
799   GetCurrentDirectoryW(MAX_PATH, cwd);
800   strcatW(cwd, slashW);
801
802   /* Loop through all args, calculating full effective directory */
803   fullParms = NULL;
804   prevEntry = NULL;
805   while (argN) {
806     WCHAR fullname[MAXSTRING];
807     WCHAR *thisArg = WCMD_parameter(cmd, argno++, &argN, NULL);
808     if (argN && argN[0] != '/') {
809
810       WINE_TRACE("Found parm '%s'\n", wine_dbgstr_w(thisArg));
811       if (thisArg[1] == ':' && thisArg[2] == '\\') {
812         strcpyW(fullname, thisArg);
813       } else if (thisArg[1] == ':' && thisArg[2] != '\\') {
814         WCHAR envvar[4];
815         static const WCHAR envFmt[] = {'=','%','c',':','\0'};
816         wsprintfW(envvar, envFmt, thisArg[0]);
817         if (!GetEnvironmentVariableW(envvar, fullname, MAX_PATH)) {
818           static const WCHAR noEnvFmt[] = {'%','c',':','\0'};
819           wsprintfW(fullname, noEnvFmt, thisArg[0]);
820         }
821         strcatW(fullname, slashW);
822         strcatW(fullname, &thisArg[2]);
823       } else if (thisArg[0] == '\\') {
824         memcpy(fullname, cwd, 2 * sizeof(WCHAR));
825         strcpyW(fullname+2, thisArg);
826       } else {
827         strcpyW(fullname, cwd);
828         strcatW(fullname, thisArg);
829       }
830       WINE_TRACE("Using location '%s'\n", wine_dbgstr_w(fullname));
831
832       status = GetFullPathNameW(fullname, sizeof(path)/sizeof(WCHAR), path, NULL);
833
834       /*
835        *  If the path supplied does not include a wildcard, and the endpoint of the
836        *  path references a directory, we need to list the *contents* of that
837        *  directory not the directory file itself.
838        */
839       if ((strchrW(path, '*') == NULL) && (strchrW(path, '%') == NULL)) {
840         status = GetFileAttributesW(path);
841         if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
842           if (path[strlenW(path)-1] == '\\') {
843             strcatW (path, starW);
844           }
845           else {
846             static const WCHAR slashStarW[]  = {'\\','*','\0'};
847             strcatW (path, slashStarW);
848           }
849         }
850       } else {
851         /* Special case wildcard search with no extension (ie parameters ending in '.') as
852            GetFullPathName strips off the additional '.'                                  */
853         if (fullname[strlenW(fullname)-1] == '.') strcatW(path, dotW);
854       }
855
856       WINE_TRACE("Using path '%s'\n", wine_dbgstr_w(path));
857       thisEntry = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
858       if (fullParms == NULL) fullParms = thisEntry;
859       if (prevEntry != NULL) prevEntry->next = thisEntry;
860       prevEntry = thisEntry;
861       thisEntry->next = NULL;
862
863       /* Split into components */
864       WCMD_splitpath(path, drive, dir, fname, ext);
865       WINE_TRACE("Path Parts: drive: '%s' dir: '%s' name: '%s' ext:'%s'\n",
866                  wine_dbgstr_w(drive), wine_dbgstr_w(dir),
867                  wine_dbgstr_w(fname), wine_dbgstr_w(ext));
868
869       thisEntry->dirName = HeapAlloc(GetProcessHeap(),0,
870                                      sizeof(WCHAR) * (strlenW(drive)+strlenW(dir)+1));
871       strcpyW(thisEntry->dirName, drive);
872       strcatW(thisEntry->dirName, dir);
873
874       thisEntry->fileName = HeapAlloc(GetProcessHeap(),0,
875                                      sizeof(WCHAR) * (strlenW(fname)+strlenW(ext)+1));
876       strcpyW(thisEntry->fileName, fname);
877       strcatW(thisEntry->fileName, ext);
878
879     }
880   }
881
882   /* If just 'dir' entered, a '*' parameter is assumed */
883   if (fullParms == NULL) {
884     WINE_TRACE("Inserting default '*'\n");
885     fullParms = HeapAlloc(GetProcessHeap(),0, sizeof(DIRECTORY_STACK));
886     fullParms->next = NULL;
887     fullParms->dirName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * (strlenW(cwd)+1));
888     strcpyW(fullParms->dirName, cwd);
889     fullParms->fileName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * 2);
890     strcpyW(fullParms->fileName, starW);
891   }
892
893   lastDrive = '?';
894   prevEntry = NULL;
895   thisEntry = fullParms;
896   trailerReqd = FALSE;
897
898   while (thisEntry != NULL) {
899
900     /* Output disk free (trailer) and volume information (header) if the drive
901        letter changes */
902     if (lastDrive != toupper(thisEntry->dirName[0])) {
903
904       /* Trailer Information */
905       if (lastDrive != '?') {
906         trailerReqd = FALSE;
907         WCMD_dir_trailer(prevEntry->dirName[0]);
908       }
909
910       lastDrive = toupper(thisEntry->dirName[0]);
911
912       if (!bare) {
913          WCHAR drive[3];
914
915          WINE_TRACE("Writing volume for '%c:'\n", thisEntry->dirName[0]);
916          memcpy(drive, thisEntry->dirName, 2 * sizeof(WCHAR));
917          drive[2] = 0x00;
918          status = WCMD_volume (0, drive);
919          trailerReqd = TRUE;
920          if (!status) {
921            errorlevel = 1;
922            goto exit;
923          }
924       }
925     } else {
926       static const WCHAR newLine2[] = {'\n','\n','\0'};
927       if (!bare) WCMD_output_asis (newLine2);
928     }
929
930     /* Clear any errors from previous invocations, and process it */
931     errorlevel = 0;
932     prevEntry = thisEntry;
933     thisEntry = WCMD_list_directory (thisEntry, 0);
934   }
935
936   /* Trailer Information */
937   if (trailerReqd) {
938     WCMD_dir_trailer(prevEntry->dirName[0]);
939   }
940
941 exit:
942   if (paged_mode) WCMD_leave_paged_mode();
943
944   /* Free storage allocated for parms */
945   while (fullParms != NULL) {
946     prevEntry = fullParms;
947     fullParms = prevEntry->next;
948     HeapFree(GetProcessHeap(),0,prevEntry->dirName);
949     HeapFree(GetProcessHeap(),0,prevEntry->fileName);
950     HeapFree(GetProcessHeap(),0,prevEntry);
951   }
952 }