cmd.exe: Add dir /X support (sort of...).
[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
32 int WCMD_dir_sort (const void *a, const void *b);
33 void WCMD_list_directory (char *path, int level);
34 char * WCMD_filesize64 (ULONGLONG free);
35 char * WCMD_strrev (char *buff);
36 static void WCMD_getfileowner(char *filename, char *owner, int ownerlen);
37
38 extern int echo_mode;
39 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
40 extern DWORD errorlevel;
41
42 typedef enum _DISPLAYTIME
43 {
44     Creation = 0,
45     Access,
46     Written
47 } DISPLAYTIME;
48
49 static int file_total, dir_total, recurse, wide, bare, max_width, lower;
50 static int shortname, usernames;
51 static ULONGLONG byte_total;
52 static DISPLAYTIME dirTime;
53
54 /*****************************************************************************
55  * WCMD_directory
56  *
57  * List a file directory.
58  *
59  */
60
61 void WCMD_directory (void) {
62
63   char path[MAX_PATH], drive[8];
64   int status, paged_mode;
65   ULARGE_INTEGER avail, total, free;
66   CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
67   char *p;
68
69   byte_total = 0;
70   file_total = dir_total = 0;
71   dirTime = Written;
72
73   /* Handle args */
74   paged_mode = (strstr(quals, "/P") != NULL);
75   recurse    = (strstr(quals, "/S") != NULL);
76   wide       = (strstr(quals, "/W") != NULL);
77   bare       = (strstr(quals, "/B") != NULL);
78   lower      = (strstr(quals, "/L") != NULL);
79   shortname  = (strstr(quals, "/X") != NULL);
80   usernames  = (strstr(quals, "/Q") != NULL);
81
82   if ((p = strstr(quals, "/T")) != NULL) {
83     p = p + 2;
84     if (*p==':') p++;  /* Skip optional : */
85
86     if (*p == 'A') dirTime = Access;
87     else if (*p == 'C') dirTime = Creation;
88     else if (*p == 'W') dirTime = Written;
89
90     /* Support /T and /T: with no parms, default to written */
91     else if (*p == '/') dirTime = Written;
92     else {
93       SetLastError(ERROR_INVALID_PARAMETER);
94       WCMD_print_error();
95       return;
96     }
97   }
98
99   /* Handle conflicting args and initialization */
100   if (bare || shortname) wide = FALSE;
101   if (bare) shortname = FALSE;
102   if (wide) usernames = FALSE;
103
104   if (wide) {
105       if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
106           max_width = consoleInfo.dwSize.X;
107       else
108           max_width = 80;
109   }
110   if (paged_mode) {
111      WCMD_enter_paged_mode();
112   }
113
114   if (param1[0] == '\0') strcpy (param1, ".");
115   status = GetFullPathName (param1, sizeof(path), path, NULL);
116   if (!status) {
117     WCMD_print_error();
118     if (paged_mode) WCMD_leave_paged_mode();
119     return;
120   }
121   lstrcpyn (drive, path, 3);
122
123   if (!bare) {
124      status = WCMD_volume (0, drive);
125      if (!status) {
126          if (paged_mode) WCMD_leave_paged_mode();
127        return;
128      }
129   }
130
131   WCMD_list_directory (path, 0);
132   lstrcpyn (drive, path, 4);
133   GetDiskFreeSpaceEx (drive, &avail, &total, &free);
134
135   if (!bare) {
136      if (recurse) {
137        WCMD_output ("\n\n     Total files listed:\n%8d files%25s bytes\n",
138             file_total, WCMD_filesize64 (byte_total));
139        WCMD_output ("%8d directories %18s bytes free\n\n",
140             dir_total, WCMD_filesize64 (free.QuadPart));
141      } else {
142        WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free.QuadPart));
143      }
144   }
145   if (paged_mode) WCMD_leave_paged_mode();
146 }
147
148 /*****************************************************************************
149  * WCMD_list_directory
150  *
151  * List a single file directory. This function (and those below it) can be called
152  * recursively when the /S switch is used.
153  *
154  * FIXME: Entries sorted by name only. Should we support DIRCMD??
155  * FIXME: Assumes 24-line display for the /P qualifier.
156  * FIXME: Other command qualifiers not supported.
157  * FIXME: DIR /S FILENAME fails if at least one matching file is not found in the top level.
158  */
159
160 void WCMD_list_directory (char *search_path, int level) {
161
162   char string[1024], datestring[32], timestring[32];
163   char *p;
164   char real_path[MAX_PATH];
165   WIN32_FIND_DATA *fd;
166   FILETIME ft;
167   SYSTEMTIME st;
168   HANDLE hff;
169   int status, dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
170   ULARGE_INTEGER byte_count, file_size;
171
172   dir_count = 0;
173   file_count = 0;
174   entry_count = 0;
175   byte_count.QuadPart = 0;
176   widest = 0;
177   cur_width = 0;
178
179 /*
180  *  If the path supplied does not include a wildcard, and the endpoint of the
181  *  path references a directory, we need to list the *contents* of that
182  *  directory not the directory file itself.
183  */
184
185   if ((strchr(search_path, '*') == NULL) && (strchr(search_path, '%') == NULL)) {
186     status = GetFileAttributes (search_path);
187     if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
188       if (search_path[strlen(search_path)-1] == '\\') {
189         strcat (search_path, "*");
190       }
191       else {
192         strcat (search_path, "\\*");
193       }
194     }
195   }
196
197   /* Work out the actual current directory name */
198   p = strrchr (search_path, '\\');
199   memset(real_path, 0x00, sizeof(real_path));
200   lstrcpyn (real_path, search_path, (p-search_path+2));
201
202   /* Load all files into an in memory structure */
203   fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA));
204   hff = FindFirstFile (search_path, fd);
205   if (hff == INVALID_HANDLE_VALUE) {
206     SetLastError (ERROR_FILE_NOT_FOUND);
207     WCMD_print_error ();
208     HeapFree(GetProcessHeap(),0,fd);
209     return;
210   }
211   do {
212     entry_count++;
213
214     /* Keep running track of longest filename for wide output */
215     if (wide) {
216        int tmpLen = strlen((fd+(entry_count-1))->cFileName) + 3;
217        if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
218        if (tmpLen > widest) widest = tmpLen;
219     }
220
221     fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
222     if (fd == NULL) {
223       FindClose (hff);
224       WCMD_output ("Memory Allocation Error");
225        return;
226     }
227   } while (FindNextFile(hff, (fd+entry_count)) != 0);
228   FindClose (hff);
229
230   /* Sort the list of files */
231   qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
232
233   /* Output the results */
234   if (!bare) {
235      if (level != 0) WCMD_output ("\n\n");
236      WCMD_output ("Directory of %s\n\n", real_path);
237   }
238
239   for (i=0; i<entry_count; i++) {
240     char username[24];
241
242     /* /L convers all names to lower case */
243     if (lower) {
244         char *p = (fd+i)->cFileName;
245         while ( (*p = tolower(*p)) ) ++p;
246     }
247
248     /* /Q gets file ownership information */
249     if (usernames) {
250         p = strrchr (search_path, '\\');
251         lstrcpyn (string, search_path, (p-search_path+2));
252         lstrcat (string, (fd+i)->cFileName);
253         WCMD_getfileowner(string, username, sizeof(username));
254     }
255
256     if (dirTime == Written) {
257       FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
258     } else if (dirTime == Access) {
259       FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
260     } else {
261       FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
262     }
263     FileTimeToSystemTime (&ft, &st);
264     GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
265                 sizeof(datestring));
266     GetTimeFormat (0, TIME_NOSECONDS, &st,
267                 NULL, timestring, sizeof(timestring));
268
269     if (wide) {
270
271       tmp_width = cur_width;
272       if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
273           WCMD_output ("[%s]", (fd+i)->cFileName);
274           dir_count++;
275           tmp_width = tmp_width + strlen((fd+i)->cFileName) + 2;
276       } else {
277           WCMD_output ("%s", (fd+i)->cFileName);
278           tmp_width = tmp_width + strlen((fd+i)->cFileName) ;
279           file_count++;
280           file_size.u.LowPart = (fd+i)->nFileSizeLow;
281           file_size.u.HighPart = (fd+i)->nFileSizeHigh;
282       byte_count.QuadPart += file_size.QuadPart;
283       }
284       cur_width = cur_width + widest;
285
286       if ((cur_width + widest) > max_width) {
287           WCMD_output ("\n");
288           cur_width = 0;
289       } else {
290           WCMD_output ("%*.s", (tmp_width - cur_width) ,"");
291       }
292
293     } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
294       dir_count++;
295
296       if (!bare) {
297          WCMD_output ("%10s  %8s  <DIR>         ", datestring, timestring);
298          if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
299          if (usernames) WCMD_output ("%-23s", username);
300          WCMD_output("%s\n",(fd+i)->cFileName);
301       } else {
302          if (!((strcmp((fd+i)->cFileName, ".") == 0) ||
303                (strcmp((fd+i)->cFileName, "..") == 0))) {
304             WCMD_output ("%s%s\n", recurse?real_path:"", (fd+i)->cFileName);
305          }
306       }
307     }
308     else {
309       file_count++;
310       file_size.u.LowPart = (fd+i)->nFileSizeLow;
311       file_size.u.HighPart = (fd+i)->nFileSizeHigh;
312       byte_count.QuadPart += file_size.QuadPart;
313       if (!bare) {
314          WCMD_output ("%10s  %8s    %10s  ", datestring, timestring,
315                       WCMD_filesize64(file_size.QuadPart));
316          if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
317          if (usernames) WCMD_output ("%-23s", username);
318          WCMD_output("%s\n",(fd+i)->cFileName);
319       } else {
320          WCMD_output ("%s%s\n", recurse?real_path:"", (fd+i)->cFileName);
321       }
322     }
323   }
324
325   if (wide && cur_width>0) {
326       WCMD_output ("\n");
327   }
328
329   if (!bare) {
330      if (file_count == 1) {
331        WCMD_output ("       1 file %25s bytes\n", WCMD_filesize64 (byte_count.QuadPart));
332      }
333      else {
334        WCMD_output ("%8d files %24s bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
335      }
336   }
337   byte_total = byte_total + byte_count.QuadPart;
338   file_total = file_total + file_count;
339   dir_total = dir_total + dir_count;
340
341   if (!bare) {
342      if (dir_count == 1) WCMD_output ("1 directory         ");
343      else WCMD_output ("%8d directories", dir_count);
344   }
345   for (i=0; i<entry_count; i++) {
346     if ((recurse) &&
347           ((fd+i)->cFileName[0] != '.') &&
348           ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
349 #if 0
350       GetFullPathName ((fd+i)->cFileName, sizeof(string), string, NULL);
351 #endif
352       p = strrchr (search_path, '\\');
353       lstrcpyn (string, search_path, (p-search_path+2));
354       lstrcat (string, (fd+i)->cFileName);
355       lstrcat (string, p);
356       WCMD_list_directory (string, 1);
357     }
358   }
359   HeapFree(GetProcessHeap(),0,fd);
360   return;
361 }
362
363 /*****************************************************************************
364  * WCMD_filesize64
365  *
366  * Convert a 64-bit number into a character string, with commas every three digits.
367  * Result is returned in a static string overwritten with each call.
368  * FIXME: There must be a better algorithm!
369  */
370
371 char * WCMD_filesize64 (ULONGLONG n) {
372
373   ULONGLONG q;
374   unsigned int r, i;
375   char *p;
376   static char buff[32];
377
378   p = buff;
379   i = -3;
380   do {
381     if ((++i)%3 == 1) *p++ = ',';
382     q = n / 10;
383     r = n - (q * 10);
384     *p++ = r + '0';
385     *p = '\0';
386     n = q;
387   } while (n != 0);
388   WCMD_strrev (buff);
389   return buff;
390 }
391
392 /*****************************************************************************
393  * WCMD_strrev
394  *
395  * Reverse a character string in-place (strrev() is not available under unixen :-( ).
396  */
397
398 char * WCMD_strrev (char *buff) {
399
400   int r, i;
401   char b;
402
403   r = lstrlen (buff);
404   for (i=0; i<r/2; i++) {
405     b = buff[i];
406     buff[i] = buff[r-i-1];
407     buff[r-i-1] = b;
408   }
409   return (buff);
410 }
411
412
413 int WCMD_dir_sort (const void *a, const void *b)
414 {
415   return (lstrcmpi(((const WIN32_FIND_DATA *)a)->cFileName,
416                    ((const WIN32_FIND_DATA *)b)->cFileName));
417 }
418
419 /*****************************************************************************
420  * WCMD_getfileowner
421  *
422  * Reverse a character string in-place (strrev() is not available under unixen :-( ).
423  */
424 void WCMD_getfileowner(char *filename, char *owner, int ownerlen) {
425
426     ULONG sizeNeeded = 0;
427     DWORD rc;
428     char name[MAXSTRING];
429     char domain[MAXSTRING];
430
431     /* In case of error, return empty string */
432     *owner = 0x00;
433
434     /* Find out how much space we need for the owner security descritpor */
435     GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
436     rc = GetLastError();
437
438     if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
439
440         LPBYTE secBuffer;
441         PSID pSID = NULL;
442         BOOL defaulted = FALSE;
443         ULONG nameLen = MAXSTRING;
444         ULONG domainLen = MAXSTRING;
445         SID_NAME_USE nameuse;
446
447         secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
448         if(!secBuffer) return;
449
450         /* Get the owners security descriptor */
451         if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
452                             sizeNeeded, &sizeNeeded)) {
453             HeapFree(GetProcessHeap(),0,secBuffer);
454             return;
455         }
456
457         /* Get the SID from the SD */
458         if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
459             HeapFree(GetProcessHeap(),0,secBuffer);
460             return;
461         }
462
463         /* Convert to a username */
464         if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
465             snprintf(owner, ownerlen, "%s%c%s", domain, '\\', name);
466         }
467         HeapFree(GetProcessHeap(),0,secBuffer);
468     }
469     return;
470 }