2 * CMD - Wine-compatible command line interface - Directory functions.
4 * Copyright (C) 1999 D A Pickles
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.
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.
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
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.
28 #define WIN32_LEAN_AND_MEAN
31 #include "wine/debug.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
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);
42 extern char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
43 extern DWORD errorlevel;
45 typedef enum _DISPLAYTIME
52 typedef enum _DISPLAYORDER
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 static BOOL seperator;
68 /*****************************************************************************
71 * List a file directory.
75 void WCMD_directory (void) {
77 char path[MAX_PATH], drive[8];
78 int status, paged_mode;
79 ULARGE_INTEGER avail, total, free;
80 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
82 char string[MAXSTRING];
84 /* Prefill Quals with (uppercased) DIRCMD env var */
85 if (GetEnvironmentVariable ("DIRCMD", string, sizeof(string))) {
87 while ( (*p = toupper(*p)) ) ++p;
89 strcpy(quals, string);
93 file_total = dir_total = 0;
95 /* Initialize all flags to their defaults as if no DIRCMD or quals */
107 orderReverse = FALSE;
108 orderGroupDirs = FALSE;
109 orderGroupDirsReverse = FALSE;
111 /* Handle args - Loop through so right most is the effective one */
112 /* Note: /- appears to be a negate rather than an off, eg. dir
113 /-W is wide, or dir /w /-w /-w is also wide */
115 while (*p && (*p=='/' || *p==' ')) {
117 if (*p++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
124 WINE_TRACE("Processing arg '%c' (in %s)\n", *p, quals);
126 case 'P': if (negate) paged_mode = !paged_mode;
127 else paged_mode = TRUE;
129 case 'S': if (negate) recurse = !recurse;
132 case 'W': if (negate) wide = !wide;
135 case 'B': if (negate) bare = !bare;
138 case 'L': if (negate) lower = !lower;
141 case 'X': if (negate) shortname = !shortname;
142 else shortname = TRUE;
144 case 'Q': if (negate) usernames = !usernames;
145 else usernames = TRUE;
147 case 'D': if (negate) orderByCol = !orderByCol;
148 else orderByCol = TRUE;
150 case 'C': if (negate) seperator = !seperator;
151 else seperator = TRUE;
154 if (*p==':') p++; /* Skip optional : */
156 if (*p == 'A') dirTime = Access;
157 else if (*p == 'C') dirTime = Creation;
158 else if (*p == 'W') dirTime = Written;
160 /* Support /T and /T: with no parms, default to written */
161 else if (*p == 0x00 || *p == '/') {
163 p = p - 1; /* So when step on, move to '/' */
165 SetLastError(ERROR_INVALID_PARAMETER);
171 if (*p==':') p++; /* Skip optional : */
172 while (*p && *p != '/') {
173 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, quals);
175 case 'N': dirOrder = Name; break;
176 case 'E': dirOrder = Extension; break;
177 case 'S': dirOrder = Size; break;
178 case 'D': dirOrder = Date; break;
179 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
180 else orderReverse = TRUE;
182 case 'G': orderGroupDirs = TRUE; break;
184 SetLastError(ERROR_INVALID_PARAMETER);
190 p = p - 1; /* So when step on, move to '/' */
193 SetLastError(ERROR_INVALID_PARAMETER);
200 /* Handle conflicting args and initialization */
201 if (bare || shortname) wide = FALSE;
202 if (bare) shortname = FALSE;
203 if (wide) usernames = FALSE;
204 if (orderByCol) wide = TRUE;
207 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
208 max_width = consoleInfo.dwSize.X;
213 WCMD_enter_paged_mode();
216 if (param1[0] == '\0') strcpy (param1, ".");
217 status = GetFullPathName (param1, sizeof(path), path, NULL);
220 if (paged_mode) WCMD_leave_paged_mode();
223 lstrcpyn (drive, path, 3);
226 status = WCMD_volume (0, drive);
228 if (paged_mode) WCMD_leave_paged_mode();
233 WCMD_list_directory (path, 0);
234 lstrcpyn (drive, path, 4);
235 GetDiskFreeSpaceEx (drive, &avail, &total, &free);
239 WCMD_output ("\n\n Total files listed:\n%8d files%25s bytes\n",
240 file_total, WCMD_filesize64 (byte_total));
241 WCMD_output ("%8d directories %18s bytes free\n\n",
242 dir_total, WCMD_filesize64 (free.QuadPart));
244 WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free.QuadPart));
247 if (paged_mode) WCMD_leave_paged_mode();
250 /*****************************************************************************
251 * WCMD_list_directory
253 * List a single file directory. This function (and those below it) can be called
254 * recursively when the /S switch is used.
256 * FIXME: Entries sorted by name only. Should we support DIRCMD??
257 * FIXME: Assumes 24-line display for the /P qualifier.
258 * FIXME: Other command qualifiers not supported.
259 * FIXME: DIR /S FILENAME fails if at least one matching file is not found in the top level.
262 void WCMD_list_directory (char *search_path, int level) {
264 char string[1024], datestring[32], timestring[32];
266 char real_path[MAX_PATH];
271 int status, dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
272 int numCols, numRows;
274 ULARGE_INTEGER byte_count, file_size;
279 byte_count.QuadPart = 0;
284 * If the path supplied does not include a wildcard, and the endpoint of the
285 * path references a directory, we need to list the *contents* of that
286 * directory not the directory file itself.
289 if ((strchr(search_path, '*') == NULL) && (strchr(search_path, '%') == NULL)) {
290 status = GetFileAttributes (search_path);
291 if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
292 if (search_path[strlen(search_path)-1] == '\\') {
293 strcat (search_path, "*");
296 strcat (search_path, "\\*");
301 /* Work out the actual current directory name */
302 p = strrchr (search_path, '\\');
303 memset(real_path, 0x00, sizeof(real_path));
304 lstrcpyn (real_path, search_path, (p-search_path+2));
306 /* Load all files into an in memory structure */
307 fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA));
308 hff = FindFirstFile (search_path, fd);
309 if (hff == INVALID_HANDLE_VALUE) {
310 SetLastError (ERROR_FILE_NOT_FOUND);
312 HeapFree(GetProcessHeap(),0,fd);
318 /* Keep running track of longest filename for wide output */
319 if (wide || orderByCol) {
320 int tmpLen = strlen((fd+(entry_count-1))->cFileName) + 3;
321 if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
322 if (tmpLen > widest) widest = tmpLen;
325 fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
328 WCMD_output ("Memory Allocation Error");
331 } while (FindNextFile(hff, (fd+entry_count)) != 0);
334 /* Sort the list of files */
335 qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
337 /* Output the results */
339 if (level != 0) WCMD_output ("\n\n");
340 WCMD_output ("Directory of %s\n\n", real_path);
343 /* Work out the number of columns */
344 WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
345 if (wide || orderByCol) {
346 numCols = max(1, (int)max_width / widest);
347 numRows = entry_count / numCols;
348 if (entry_count % numCols) numRows++;
351 numRows = entry_count;
353 WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
355 for (rows=0; rows<numRows; rows++) {
356 for (cols=0; cols<numCols; cols++) {
359 /* Work out the index of the entry being pointed to */
361 i = (cols * numRows) + rows;
362 if (i >= entry_count) continue;
364 i = (rows * numCols) + cols;
365 if (i >= entry_count) continue;
368 /* /L convers all names to lower case */
370 char *p = (fd+i)->cFileName;
371 while ( (*p = tolower(*p)) ) ++p;
374 /* /Q gets file ownership information */
376 p = strrchr (search_path, '\\');
377 lstrcpyn (string, search_path, (p-search_path+2));
378 lstrcat (string, (fd+i)->cFileName);
379 WCMD_getfileowner(string, username, sizeof(username));
382 if (dirTime == Written) {
383 FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
384 } else if (dirTime == Access) {
385 FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
387 FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
389 FileTimeToSystemTime (&ft, &st);
390 GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
392 GetTimeFormat (0, TIME_NOSECONDS, &st,
393 NULL, timestring, sizeof(timestring));
397 tmp_width = cur_width;
398 if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
399 WCMD_output ("[%s]", (fd+i)->cFileName);
401 tmp_width = tmp_width + strlen((fd+i)->cFileName) + 2;
403 WCMD_output ("%s", (fd+i)->cFileName);
404 tmp_width = tmp_width + strlen((fd+i)->cFileName) ;
406 file_size.u.LowPart = (fd+i)->nFileSizeLow;
407 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
408 byte_count.QuadPart += file_size.QuadPart;
410 cur_width = cur_width + widest;
412 if ((cur_width + widest) > max_width) {
415 WCMD_output ("%*.s", (tmp_width - cur_width) ,"");
418 } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
422 WCMD_output ("%10s %8s <DIR> ", datestring, timestring);
423 if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
424 if (usernames) WCMD_output ("%-23s", username);
425 WCMD_output("%s",(fd+i)->cFileName);
427 if (!((strcmp((fd+i)->cFileName, ".") == 0) ||
428 (strcmp((fd+i)->cFileName, "..") == 0))) {
429 WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
435 file_size.u.LowPart = (fd+i)->nFileSizeLow;
436 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
437 byte_count.QuadPart += file_size.QuadPart;
439 WCMD_output ("%10s %8s %10s ", datestring, timestring,
440 WCMD_filesize64(file_size.QuadPart));
441 if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
442 if (usernames) WCMD_output ("%-23s", username);
443 WCMD_output("%s",(fd+i)->cFileName);
445 WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
454 if (file_count == 1) {
455 WCMD_output (" 1 file %25s bytes\n", WCMD_filesize64 (byte_count.QuadPart));
458 WCMD_output ("%8d files %24s bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
461 byte_total = byte_total + byte_count.QuadPart;
462 file_total = file_total + file_count;
463 dir_total = dir_total + dir_count;
466 if (dir_count == 1) WCMD_output ("1 directory ");
467 else WCMD_output ("%8d directories", dir_count);
469 for (i=0; i<entry_count; i++) {
471 ((fd+i)->cFileName[0] != '.') &&
472 ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
474 GetFullPathName ((fd+i)->cFileName, sizeof(string), string, NULL);
476 p = strrchr (search_path, '\\');
477 lstrcpyn (string, search_path, (p-search_path+2));
478 lstrcat (string, (fd+i)->cFileName);
480 WCMD_list_directory (string, 1);
483 HeapFree(GetProcessHeap(),0,fd);
487 /*****************************************************************************
490 * Convert a 64-bit number into a character string, with commas every three digits.
491 * Result is returned in a static string overwritten with each call.
492 * FIXME: There must be a better algorithm!
495 char * WCMD_filesize64 (ULONGLONG n) {
500 static char buff[32];
505 if (seperator && ((++i)%3 == 1)) *p++ = ',';
516 /*****************************************************************************
519 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
522 char * WCMD_strrev (char *buff) {
528 for (i=0; i<r/2; i++) {
530 buff[i] = buff[r-i-1];
537 /*****************************************************************************
540 * Sort based on the /O options supplied on the command line
542 int WCMD_dir_sort (const void *a, const void *b)
544 WIN32_FIND_DATA *filea = (WIN32_FIND_DATA *)a;
545 WIN32_FIND_DATA *fileb = (WIN32_FIND_DATA *)b;
548 /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
549 requested sort order for the directory components */
550 if (orderGroupDirs &&
551 ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
552 (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
554 BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
555 if (aDir) result = -1;
557 if (orderGroupDirsReverse) result = -result;
561 } else if (dirOrder == Name) {
562 result = lstrcmpi(filea->cFileName, fileb->cFileName);
565 } else if (dirOrder == Size) {
566 ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
567 ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
568 if( sizea < sizeb ) result = -1;
569 else if( sizea == sizeb ) result = 0;
572 /* Order by Date: (Takes into account which date (/T option) */
573 } else if (dirOrder == Date) {
576 ULONG64 timea, timeb;
578 if (dirTime == Written) {
579 ft = &filea->ftLastWriteTime;
580 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
581 ft = &fileb->ftLastWriteTime;
582 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
583 } else if (dirTime == Access) {
584 ft = &filea->ftLastAccessTime;
585 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
586 ft = &fileb->ftLastAccessTime;
587 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
589 ft = &filea->ftCreationTime;
590 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
591 ft = &fileb->ftCreationTime;
592 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
594 if( timea < timeb ) result = -1;
595 else if( timea == timeb ) result = 0;
598 /* Order by Extension: (Takes into account which date (/T option) */
599 } else if (dirOrder == Extension) {
602 char fname[MAX_PATH];
606 /* Split into components */
607 WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
608 WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
609 result = lstrcmpi(extA, extB);
612 if (orderReverse) result = -result;
616 /*****************************************************************************
619 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
621 void WCMD_getfileowner(char *filename, char *owner, int ownerlen) {
623 ULONG sizeNeeded = 0;
625 char name[MAXSTRING];
626 char domain[MAXSTRING];
628 /* In case of error, return empty string */
631 /* Find out how much space we need for the owner security descritpor */
632 GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
635 if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
639 BOOL defaulted = FALSE;
640 ULONG nameLen = MAXSTRING;
641 ULONG domainLen = MAXSTRING;
642 SID_NAME_USE nameuse;
644 secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
645 if(!secBuffer) return;
647 /* Get the owners security descriptor */
648 if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
649 sizeNeeded, &sizeNeeded)) {
650 HeapFree(GetProcessHeap(),0,secBuffer);
654 /* Get the SID from the SD */
655 if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
656 HeapFree(GetProcessHeap(),0,secBuffer);
660 /* Convert to a username */
661 if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
662 snprintf(owner, ownerlen, "%s%c%s", domain, '\\', name);
664 HeapFree(GetProcessHeap(),0,secBuffer);