cmd.exe: Add support for DIR /D.
[wine] / programs / cmd / directory.c
1 /*
2  * CMD - Wine-compatible command line interface - Directory functions.
3  *
4  * Copyright (C) 1999 D A Pickles
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /*
22  * NOTES:
23  * On entry, global variables quals, param1, param2 contain
24  * the qualifiers (uppercased and concatenated) and parameters entered, with
25  * environment-variable and batch parameter substitution already done.
26  */
27
28 #define WIN32_LEAN_AND_MEAN
29
30 #include "wcmd.h"
31 #include "wine/debug.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
34
35 int WCMD_dir_sort (const void *a, const void *b);
36 void WCMD_list_directory (char *path, int level);
37 char * WCMD_filesize64 (ULONGLONG free);
38 char * WCMD_strrev (char *buff);
39 static void WCMD_getfileowner(char *filename, char *owner, int ownerlen);
40
41 extern int echo_mode;
42 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
43 extern DWORD errorlevel;
44
45 typedef enum _DISPLAYTIME
46 {
47     Creation = 0,
48     Access,
49     Written
50 } DISPLAYTIME;
51
52 typedef enum _DISPLAYORDER
53 {
54     Name = 0,
55     Extension,
56     Size,
57     Date
58 } DISPLAYORDER;
59
60 static int file_total, dir_total, recurse, wide, bare, max_width, lower;
61 static int shortname, usernames;
62 static ULONGLONG byte_total;
63 static DISPLAYTIME dirTime;
64 static DISPLAYORDER dirOrder;
65 static BOOL orderReverse, orderGroupDirs, orderGroupDirsReverse, orderByCol;
66
67 /*****************************************************************************
68  * WCMD_directory
69  *
70  * List a file directory.
71  *
72  */
73
74 void WCMD_directory (void) {
75
76   char path[MAX_PATH], drive[8];
77   int status, paged_mode;
78   ULARGE_INTEGER avail, total, free;
79   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
80   char *p;
81
82   byte_total = 0;
83   file_total = dir_total = 0;
84   dirTime = Written;
85   dirOrder = Name;
86   orderReverse = FALSE;
87   orderGroupDirs = FALSE;
88   orderGroupDirsReverse = FALSE;
89
90   /* Handle args */
91   paged_mode = (strstr(quals, "/P") != NULL);
92   recurse    = (strstr(quals, "/S") != NULL);
93   wide       = (strstr(quals, "/W") != NULL);
94   bare       = (strstr(quals, "/B") != NULL);
95   lower      = (strstr(quals, "/L") != NULL);
96   shortname  = (strstr(quals, "/X") != NULL);
97   usernames  = (strstr(quals, "/Q") != NULL);
98   orderByCol = (strstr(quals, "/D") != NULL);
99
100   if ((p = strstr(quals, "/T")) != NULL) {
101     p = p + 2;
102     if (*p==':') p++;  /* Skip optional : */
103
104     if (*p == 'A') dirTime = Access;
105     else if (*p == 'C') dirTime = Creation;
106     else if (*p == 'W') dirTime = Written;
107
108     /* Support /T and /T: with no parms, default to written */
109     else if (*p == '/') dirTime = Written;
110     else {
111       SetLastError(ERROR_INVALID_PARAMETER);
112       WCMD_print_error();
113       return;
114     }
115   }
116
117   if ((p = strstr(quals, "/O")) != NULL) {
118     p = p + 2;
119     if (*p==':') p++;  /* Skip optional : */
120     while (*p && *p != '/') {
121       switch (*p) {
122       case 'N': dirOrder = Name;       break;
123       case 'E': dirOrder = Extension;  break;
124       case 'S': dirOrder = Size;       break;
125       case 'D': dirOrder = Date;       break;
126       case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
127                 else orderReverse = TRUE;
128                 break;
129       case 'G': orderGroupDirs = TRUE; break;
130       default:
131           SetLastError(ERROR_INVALID_PARAMETER);
132           WCMD_print_error();
133           return;
134       }
135       p++;
136     }
137   }
138
139   /* Handle conflicting args and initialization */
140   if (bare || shortname) wide = FALSE;
141   if (bare) shortname = FALSE;
142   if (wide) usernames = FALSE;
143   if (orderByCol) wide = TRUE;
144
145   if (wide) {
146       if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
147           max_width = consoleInfo.dwSize.X;
148       else
149           max_width = 80;
150   }
151   if (paged_mode) {
152      WCMD_enter_paged_mode();
153   }
154
155   if (param1[0] == '\0') strcpy (param1, ".");
156   status = GetFullPathName (param1, sizeof(path), path, NULL);
157   if (!status) {
158     WCMD_print_error();
159     if (paged_mode) WCMD_leave_paged_mode();
160     return;
161   }
162   lstrcpyn (drive, path, 3);
163
164   if (!bare) {
165      status = WCMD_volume (0, drive);
166      if (!status) {
167          if (paged_mode) WCMD_leave_paged_mode();
168        return;
169      }
170   }
171
172   WCMD_list_directory (path, 0);
173   lstrcpyn (drive, path, 4);
174   GetDiskFreeSpaceEx (drive, &avail, &total, &free);
175
176   if (!bare) {
177      if (recurse) {
178        WCMD_output ("\n\n     Total files listed:\n%8d files%25s bytes\n",
179             file_total, WCMD_filesize64 (byte_total));
180        WCMD_output ("%8d directories %18s bytes free\n\n",
181             dir_total, WCMD_filesize64 (free.QuadPart));
182      } else {
183        WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free.QuadPart));
184      }
185   }
186   if (paged_mode) WCMD_leave_paged_mode();
187 }
188
189 /*****************************************************************************
190  * WCMD_list_directory
191  *
192  * List a single file directory. This function (and those below it) can be called
193  * recursively when the /S switch is used.
194  *
195  * FIXME: Entries sorted by name only. Should we support DIRCMD??
196  * FIXME: Assumes 24-line display for the /P qualifier.
197  * FIXME: Other command qualifiers not supported.
198  * FIXME: DIR /S FILENAME fails if at least one matching file is not found in the top level.
199  */
200
201 void WCMD_list_directory (char *search_path, int level) {
202
203   char string[1024], datestring[32], timestring[32];
204   char *p;
205   char real_path[MAX_PATH];
206   WIN32_FIND_DATA *fd;
207   FILETIME ft;
208   SYSTEMTIME st;
209   HANDLE hff;
210   int status, dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
211   int numCols, numRows;
212   int rows, cols;
213   ULARGE_INTEGER byte_count, file_size;
214
215   dir_count = 0;
216   file_count = 0;
217   entry_count = 0;
218   byte_count.QuadPart = 0;
219   widest = 0;
220   cur_width = 0;
221
222 /*
223  *  If the path supplied does not include a wildcard, and the endpoint of the
224  *  path references a directory, we need to list the *contents* of that
225  *  directory not the directory file itself.
226  */
227
228   if ((strchr(search_path, '*') == NULL) && (strchr(search_path, '%') == NULL)) {
229     status = GetFileAttributes (search_path);
230     if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
231       if (search_path[strlen(search_path)-1] == '\\') {
232         strcat (search_path, "*");
233       }
234       else {
235         strcat (search_path, "\\*");
236       }
237     }
238   }
239
240   /* Work out the actual current directory name */
241   p = strrchr (search_path, '\\');
242   memset(real_path, 0x00, sizeof(real_path));
243   lstrcpyn (real_path, search_path, (p-search_path+2));
244
245   /* Load all files into an in memory structure */
246   fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA));
247   hff = FindFirstFile (search_path, fd);
248   if (hff == INVALID_HANDLE_VALUE) {
249     SetLastError (ERROR_FILE_NOT_FOUND);
250     WCMD_print_error ();
251     HeapFree(GetProcessHeap(),0,fd);
252     return;
253   }
254   do {
255     entry_count++;
256
257     /* Keep running track of longest filename for wide output */
258     if (wide || orderByCol) {
259        int tmpLen = strlen((fd+(entry_count-1))->cFileName) + 3;
260        if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
261        if (tmpLen > widest) widest = tmpLen;
262     }
263
264     fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
265     if (fd == NULL) {
266       FindClose (hff);
267       WCMD_output ("Memory Allocation Error");
268        return;
269     }
270   } while (FindNextFile(hff, (fd+entry_count)) != 0);
271   FindClose (hff);
272
273   /* Sort the list of files */
274   qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
275
276   /* Output the results */
277   if (!bare) {
278      if (level != 0) WCMD_output ("\n\n");
279      WCMD_output ("Directory of %s\n\n", real_path);
280   }
281
282   /* Work out the number of columns */
283   WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
284   if (wide || orderByCol) {
285     numCols = max(1, (int)max_width / widest);
286     numRows = entry_count / numCols;
287     if (entry_count % numCols) numRows++;
288   } else {
289     numCols = 1;
290     numRows = entry_count;
291   }
292   WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
293
294   for (rows=0; rows<numRows; rows++) {
295    for (cols=0; cols<numCols; cols++) {
296     char username[24];
297
298     /* Work out the index of the entry being pointed to */
299     if (orderByCol) {
300       i = (cols * numRows) + rows;
301       if (i >= entry_count) continue;
302     } else {
303       i = (rows * numCols) + cols;
304       if (i >= entry_count) continue;
305     }
306
307     /* /L convers all names to lower case */
308     if (lower) {
309         char *p = (fd+i)->cFileName;
310         while ( (*p = tolower(*p)) ) ++p;
311     }
312
313     /* /Q gets file ownership information */
314     if (usernames) {
315         p = strrchr (search_path, '\\');
316         lstrcpyn (string, search_path, (p-search_path+2));
317         lstrcat (string, (fd+i)->cFileName);
318         WCMD_getfileowner(string, username, sizeof(username));
319     }
320
321     if (dirTime == Written) {
322       FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
323     } else if (dirTime == Access) {
324       FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
325     } else {
326       FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
327     }
328     FileTimeToSystemTime (&ft, &st);
329     GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
330                 sizeof(datestring));
331     GetTimeFormat (0, TIME_NOSECONDS, &st,
332                 NULL, timestring, sizeof(timestring));
333
334     if (wide) {
335
336       tmp_width = cur_width;
337       if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
338           WCMD_output ("[%s]", (fd+i)->cFileName);
339           dir_count++;
340           tmp_width = tmp_width + strlen((fd+i)->cFileName) + 2;
341       } else {
342           WCMD_output ("%s", (fd+i)->cFileName);
343           tmp_width = tmp_width + strlen((fd+i)->cFileName) ;
344           file_count++;
345           file_size.u.LowPart = (fd+i)->nFileSizeLow;
346           file_size.u.HighPart = (fd+i)->nFileSizeHigh;
347       byte_count.QuadPart += file_size.QuadPart;
348       }
349       cur_width = cur_width + widest;
350
351       if ((cur_width + widest) > max_width) {
352           cur_width = 0;
353       } else {
354           WCMD_output ("%*.s", (tmp_width - cur_width) ,"");
355       }
356
357     } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
358       dir_count++;
359
360       if (!bare) {
361          WCMD_output ("%10s  %8s  <DIR>         ", datestring, timestring);
362          if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
363          if (usernames) WCMD_output ("%-23s", username);
364          WCMD_output("%s",(fd+i)->cFileName);
365       } else {
366          if (!((strcmp((fd+i)->cFileName, ".") == 0) ||
367                (strcmp((fd+i)->cFileName, "..") == 0))) {
368             WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
369          }
370       }
371     }
372     else {
373       file_count++;
374       file_size.u.LowPart = (fd+i)->nFileSizeLow;
375       file_size.u.HighPart = (fd+i)->nFileSizeHigh;
376       byte_count.QuadPart += file_size.QuadPart;
377       if (!bare) {
378          WCMD_output ("%10s  %8s    %10s  ", datestring, timestring,
379                       WCMD_filesize64(file_size.QuadPart));
380          if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
381          if (usernames) WCMD_output ("%-23s", username);
382          WCMD_output("%s",(fd+i)->cFileName);
383       } else {
384          WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
385       }
386     }
387    }
388    WCMD_output ("\n");
389    cur_width = 0;
390   }
391
392   if (!bare) {
393      if (file_count == 1) {
394        WCMD_output ("       1 file %25s bytes\n", WCMD_filesize64 (byte_count.QuadPart));
395      }
396      else {
397        WCMD_output ("%8d files %24s bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
398      }
399   }
400   byte_total = byte_total + byte_count.QuadPart;
401   file_total = file_total + file_count;
402   dir_total = dir_total + dir_count;
403
404   if (!bare) {
405      if (dir_count == 1) WCMD_output ("1 directory         ");
406      else WCMD_output ("%8d directories", dir_count);
407   }
408   for (i=0; i<entry_count; i++) {
409     if ((recurse) &&
410           ((fd+i)->cFileName[0] != '.') &&
411           ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
412 #if 0
413       GetFullPathName ((fd+i)->cFileName, sizeof(string), string, NULL);
414 #endif
415       p = strrchr (search_path, '\\');
416       lstrcpyn (string, search_path, (p-search_path+2));
417       lstrcat (string, (fd+i)->cFileName);
418       lstrcat (string, p);
419       WCMD_list_directory (string, 1);
420     }
421   }
422   HeapFree(GetProcessHeap(),0,fd);
423   return;
424 }
425
426 /*****************************************************************************
427  * WCMD_filesize64
428  *
429  * Convert a 64-bit number into a character string, with commas every three digits.
430  * Result is returned in a static string overwritten with each call.
431  * FIXME: There must be a better algorithm!
432  */
433
434 char * WCMD_filesize64 (ULONGLONG n) {
435
436   ULONGLONG q;
437   unsigned int r, i;
438   char *p;
439   static char buff[32];
440
441   p = buff;
442   i = -3;
443   do {
444     if ((++i)%3 == 1) *p++ = ',';
445     q = n / 10;
446     r = n - (q * 10);
447     *p++ = r + '0';
448     *p = '\0';
449     n = q;
450   } while (n != 0);
451   WCMD_strrev (buff);
452   return buff;
453 }
454
455 /*****************************************************************************
456  * WCMD_strrev
457  *
458  * Reverse a character string in-place (strrev() is not available under unixen :-( ).
459  */
460
461 char * WCMD_strrev (char *buff) {
462
463   int r, i;
464   char b;
465
466   r = lstrlen (buff);
467   for (i=0; i<r/2; i++) {
468     b = buff[i];
469     buff[i] = buff[r-i-1];
470     buff[r-i-1] = b;
471   }
472   return (buff);
473 }
474
475
476 /*****************************************************************************
477  * WCMD_dir_sort
478  *
479  * Sort based on the /O options supplied on the command line
480  */
481 int WCMD_dir_sort (const void *a, const void *b)
482 {
483   WIN32_FIND_DATA *filea = (WIN32_FIND_DATA *)a;
484   WIN32_FIND_DATA *fileb = (WIN32_FIND_DATA *)b;
485   int result = 0;
486
487   /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
488      requested sort order for the directory components                   */
489   if (orderGroupDirs &&
490       ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
491        (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
492   {
493     BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
494     if (aDir) result = -1;
495     else result = 1;
496     if (orderGroupDirsReverse) result = -result;
497     return result;
498
499   /* Order by Name: */
500   } else if (dirOrder == Name) {
501     result = lstrcmpi(filea->cFileName, fileb->cFileName);
502
503   /* Order by Size: */
504   } else if (dirOrder == Size) {
505     ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
506     ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
507     if( sizea < sizeb ) result = -1;
508     else if( sizea == sizeb ) result = 0;
509     else result = 1;
510
511   /* Order by Date: (Takes into account which date (/T option) */
512   } else if (dirOrder == Date) {
513
514     FILETIME *ft;
515     ULONG64 timea, timeb;
516
517     if (dirTime == Written) {
518       ft = &filea->ftLastWriteTime;
519       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
520       ft = &fileb->ftLastWriteTime;
521       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
522     } else if (dirTime == Access) {
523       ft = &filea->ftLastAccessTime;
524       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
525       ft = &fileb->ftLastAccessTime;
526       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
527     } else {
528       ft = &filea->ftCreationTime;
529       timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
530       ft = &fileb->ftCreationTime;
531       timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
532     }
533     if( timea < timeb ) result = -1;
534     else if( timea == timeb ) result = 0;
535     else result = 1;
536
537   /* Order by Extension: (Takes into account which date (/T option) */
538   } else if (dirOrder == Extension) {
539       char drive[10];
540       char dir[MAX_PATH];
541       char fname[MAX_PATH];
542       char extA[MAX_PATH];
543       char extB[MAX_PATH];
544
545       /* Split into components */
546       WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
547       WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
548       result = lstrcmpi(extA, extB);
549   }
550
551   if (orderReverse) result = -result;
552   return result;
553 }
554
555 /*****************************************************************************
556  * WCMD_getfileowner
557  *
558  * Reverse a character string in-place (strrev() is not available under unixen :-( ).
559  */
560 void WCMD_getfileowner(char *filename, char *owner, int ownerlen) {
561
562     ULONG sizeNeeded = 0;
563     DWORD rc;
564     char name[MAXSTRING];
565     char domain[MAXSTRING];
566
567     /* In case of error, return empty string */
568     *owner = 0x00;
569
570     /* Find out how much space we need for the owner security descritpor */
571     GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
572     rc = GetLastError();
573
574     if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
575
576         LPBYTE secBuffer;
577         PSID pSID = NULL;
578         BOOL defaulted = FALSE;
579         ULONG nameLen = MAXSTRING;
580         ULONG domainLen = MAXSTRING;
581         SID_NAME_USE nameuse;
582
583         secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
584         if(!secBuffer) return;
585
586         /* Get the owners security descriptor */
587         if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
588                             sizeNeeded, &sizeNeeded)) {
589             HeapFree(GetProcessHeap(),0,secBuffer);
590             return;
591         }
592
593         /* Get the SID from the SD */
594         if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
595             HeapFree(GetProcessHeap(),0,secBuffer);
596             return;
597         }
598
599         /* Convert to a username */
600         if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
601             snprintf(owner, ownerlen, "%s%c%s", domain, '\\', name);
602         }
603         HeapFree(GetProcessHeap(),0,secBuffer);
604     }
605     return;
606 }