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