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;
67 static ULONG showattrs, attrsbits;
69 /*****************************************************************************
72 * List a file directory.
76 void WCMD_directory (void) {
78 char path[MAX_PATH], drive[8];
79 int status, paged_mode;
80 ULARGE_INTEGER avail, total, free;
81 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
83 char string[MAXSTRING];
87 /* Prefill Quals with (uppercased) DIRCMD env var */
88 if (GetEnvironmentVariable ("DIRCMD", string, sizeof(string))) {
90 while ( (*p = toupper(*p)) ) ++p;
92 strcpy(quals, string);
96 file_total = dir_total = 0;
98 /* Initialize all flags to their defaults as if no DIRCMD or quals */
110 orderReverse = FALSE;
111 orderGroupDirs = FALSE;
112 orderGroupDirsReverse = FALSE;
116 /* Handle args - Loop through so right most is the effective one */
117 /* Note: /- appears to be a negate rather than an off, eg. dir
118 /-W is wide, or dir /w /-w /-w is also wide */
120 while (*p && (*p=='/' || *p==' ')) {
122 if (*p++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
129 WINE_TRACE("Processing arg '%c' (in %s)\n", *p, quals);
131 case 'P': if (negate) paged_mode = !paged_mode;
132 else paged_mode = TRUE;
134 case 'S': if (negate) recurse = !recurse;
137 case 'W': if (negate) wide = !wide;
140 case 'B': if (negate) bare = !bare;
143 case 'L': if (negate) lower = !lower;
146 case 'X': if (negate) shortname = !shortname;
147 else shortname = TRUE;
149 case 'Q': if (negate) usernames = !usernames;
150 else usernames = TRUE;
152 case 'D': if (negate) orderByCol = !orderByCol;
153 else orderByCol = TRUE;
155 case 'C': if (negate) seperator = !seperator;
156 else seperator = TRUE;
159 if (*p==':') p++; /* Skip optional : */
161 if (*p == 'A') dirTime = Access;
162 else if (*p == 'C') dirTime = Creation;
163 else if (*p == 'W') dirTime = Written;
165 /* Support /T and /T: with no parms, default to written */
166 else if (*p == 0x00 || *p == '/') {
168 p = p - 1; /* So when step on, move to '/' */
170 SetLastError(ERROR_INVALID_PARAMETER);
177 if (*p==':') p++; /* Skip optional : */
178 while (*p && *p != '/') {
179 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, quals);
181 case 'N': dirOrder = Name; break;
182 case 'E': dirOrder = Extension; break;
183 case 'S': dirOrder = Size; break;
184 case 'D': dirOrder = Date; break;
185 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
186 else orderReverse = TRUE;
188 case 'G': orderGroupDirs = TRUE; break;
190 SetLastError(ERROR_INVALID_PARAMETER);
197 p = p - 1; /* So when step on, move to '/' */
202 if (*p==':') p++; /* Skip optional : */
203 while (*p && *p != '/') {
204 BOOL anegate = FALSE;
207 /* Note /A: - options are 'offs' not toggles */
213 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, quals);
215 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
216 case 'H': mask = FILE_ATTRIBUTE_HIDDEN; break;
217 case 'S': mask = FILE_ATTRIBUTE_SYSTEM; break;
218 case 'R': mask = FILE_ATTRIBUTE_READONLY; break;
219 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE; break;
221 SetLastError(ERROR_INVALID_PARAMETER);
227 /* Keep running list of bits we care about */
230 /* Mask shows what MUST be in the bits we care about */
231 if (anegate) showattrs = showattrs & ~mask;
232 else showattrs |= mask;
236 p = p - 1; /* So when step on, move to '/' */
237 WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
240 SetLastError(ERROR_INVALID_PARAMETER);
248 /* Handle conflicting args and initialization */
249 if (bare || shortname) wide = FALSE;
250 if (bare) shortname = FALSE;
251 if (wide) usernames = FALSE;
252 if (orderByCol) wide = TRUE;
255 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
256 max_width = consoleInfo.dwSize.X;
261 WCMD_enter_paged_mode();
264 if (param1[0] == '\0') strcpy (param1, ".");
265 status = GetFullPathName (param1, sizeof(path), path, NULL);
268 if (paged_mode) WCMD_leave_paged_mode();
272 lstrcpyn (drive, path, 3);
275 status = WCMD_volume (0, drive);
277 if (paged_mode) WCMD_leave_paged_mode();
283 WCMD_list_directory (path, 0);
284 lstrcpyn (drive, path, 4);
285 GetDiskFreeSpaceEx (drive, &avail, &total, &free);
287 if (errorlevel==0 && !bare) {
289 WCMD_output ("\n\n Total files listed:\n%8d files%25s bytes\n",
290 file_total, WCMD_filesize64 (byte_total));
291 WCMD_output ("%8d directories %18s bytes free\n\n",
292 dir_total, WCMD_filesize64 (free.QuadPart));
294 WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free.QuadPart));
297 if (paged_mode) WCMD_leave_paged_mode();
300 /*****************************************************************************
301 * WCMD_list_directory
303 * List a single file directory. This function (and those below it) can be called
304 * recursively when the /S switch is used.
306 * FIXME: Entries sorted by name only. Should we support DIRCMD??
307 * FIXME: Assumes 24-line display for the /P qualifier.
308 * FIXME: Other command qualifiers not supported.
309 * FIXME: DIR /S FILENAME fails if at least one matching file is not found in the top level.
312 void WCMD_list_directory (char *search_path, int level) {
314 char string[1024], datestring[32], timestring[32];
316 char real_path[MAX_PATH];
321 int status, dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
322 int numCols, numRows;
324 ULARGE_INTEGER byte_count, file_size;
329 byte_count.QuadPart = 0;
334 * If the path supplied does not include a wildcard, and the endpoint of the
335 * path references a directory, we need to list the *contents* of that
336 * directory not the directory file itself.
339 if ((strchr(search_path, '*') == NULL) && (strchr(search_path, '%') == NULL)) {
340 status = GetFileAttributes (search_path);
341 if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
342 if (search_path[strlen(search_path)-1] == '\\') {
343 strcat (search_path, "*");
346 strcat (search_path, "\\*");
351 /* Work out the actual current directory name */
352 p = strrchr (search_path, '\\');
353 memset(real_path, 0x00, sizeof(real_path));
354 lstrcpyn (real_path, search_path, (p-search_path+2));
356 /* Load all files into an in memory structure */
357 fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA));
358 hff = FindFirstFile (search_path, fd);
359 if (hff == INVALID_HANDLE_VALUE) {
360 SetLastError (ERROR_FILE_NOT_FOUND);
362 HeapFree(GetProcessHeap(),0,fd);
367 /* Skip any which are filtered out by attribute */
368 if (((fd+entry_count)->dwFileAttributes & attrsbits) != showattrs) continue;
372 /* Keep running track of longest filename for wide output */
373 if (wide || orderByCol) {
374 int tmpLen = strlen((fd+(entry_count-1))->cFileName) + 3;
375 if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
376 if (tmpLen > widest) widest = tmpLen;
379 fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
382 WCMD_output ("Memory Allocation Error");
386 } while (FindNextFile(hff, (fd+entry_count)) != 0);
389 /* Handle case where everything is filtered out */
390 if (entry_count == 0) {
391 SetLastError (ERROR_FILE_NOT_FOUND);
393 HeapFree(GetProcessHeap(),0,fd);
398 /* Sort the list of files */
399 qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
401 /* Output the results */
403 if (level != 0) WCMD_output ("\n\n");
404 WCMD_output ("Directory of %s\n\n", real_path);
407 /* Work out the number of columns */
408 WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
409 if (wide || orderByCol) {
410 numCols = max(1, (int)max_width / widest);
411 numRows = entry_count / numCols;
412 if (entry_count % numCols) numRows++;
415 numRows = entry_count;
417 WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
419 for (rows=0; rows<numRows; rows++) {
420 for (cols=0; cols<numCols; cols++) {
423 /* Work out the index of the entry being pointed to */
425 i = (cols * numRows) + rows;
426 if (i >= entry_count) continue;
428 i = (rows * numCols) + cols;
429 if (i >= entry_count) continue;
432 /* /L convers all names to lower case */
434 char *p = (fd+i)->cFileName;
435 while ( (*p = tolower(*p)) ) ++p;
438 /* /Q gets file ownership information */
440 p = strrchr (search_path, '\\');
441 lstrcpyn (string, search_path, (p-search_path+2));
442 lstrcat (string, (fd+i)->cFileName);
443 WCMD_getfileowner(string, username, sizeof(username));
446 if (dirTime == Written) {
447 FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
448 } else if (dirTime == Access) {
449 FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
451 FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
453 FileTimeToSystemTime (&ft, &st);
454 GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
456 GetTimeFormat (0, TIME_NOSECONDS, &st,
457 NULL, timestring, sizeof(timestring));
461 tmp_width = cur_width;
462 if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
463 WCMD_output ("[%s]", (fd+i)->cFileName);
465 tmp_width = tmp_width + strlen((fd+i)->cFileName) + 2;
467 WCMD_output ("%s", (fd+i)->cFileName);
468 tmp_width = tmp_width + strlen((fd+i)->cFileName) ;
470 file_size.u.LowPart = (fd+i)->nFileSizeLow;
471 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
472 byte_count.QuadPart += file_size.QuadPart;
474 cur_width = cur_width + widest;
476 if ((cur_width + widest) > max_width) {
479 WCMD_output ("%*.s", (tmp_width - cur_width) ,"");
482 } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
486 WCMD_output ("%10s %8s <DIR> ", datestring, timestring);
487 if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
488 if (usernames) WCMD_output ("%-23s", username);
489 WCMD_output("%s",(fd+i)->cFileName);
491 if (!((strcmp((fd+i)->cFileName, ".") == 0) ||
492 (strcmp((fd+i)->cFileName, "..") == 0))) {
493 WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
499 file_size.u.LowPart = (fd+i)->nFileSizeLow;
500 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
501 byte_count.QuadPart += file_size.QuadPart;
503 WCMD_output ("%10s %8s %10s ", datestring, timestring,
504 WCMD_filesize64(file_size.QuadPart));
505 if (shortname) WCMD_output ("%-13s", (fd+i)->cAlternateFileName);
506 if (usernames) WCMD_output ("%-23s", username);
507 WCMD_output("%s",(fd+i)->cFileName);
509 WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
518 if (file_count == 1) {
519 WCMD_output (" 1 file %25s bytes\n", WCMD_filesize64 (byte_count.QuadPart));
522 WCMD_output ("%8d files %24s bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
525 byte_total = byte_total + byte_count.QuadPart;
526 file_total = file_total + file_count;
527 dir_total = dir_total + dir_count;
530 if (dir_count == 1) WCMD_output ("1 directory ");
531 else WCMD_output ("%8d directories", dir_count);
533 for (i=0; i<entry_count; i++) {
535 ((fd+i)->cFileName[0] != '.') &&
536 ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
538 GetFullPathName ((fd+i)->cFileName, sizeof(string), string, NULL);
540 p = strrchr (search_path, '\\');
541 lstrcpyn (string, search_path, (p-search_path+2));
542 lstrcat (string, (fd+i)->cFileName);
544 WCMD_list_directory (string, 1);
547 HeapFree(GetProcessHeap(),0,fd);
551 /*****************************************************************************
554 * Convert a 64-bit number into a character string, with commas every three digits.
555 * Result is returned in a static string overwritten with each call.
556 * FIXME: There must be a better algorithm!
559 char * WCMD_filesize64 (ULONGLONG n) {
564 static char buff[32];
569 if (seperator && ((++i)%3 == 1)) *p++ = ',';
580 /*****************************************************************************
583 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
586 char * WCMD_strrev (char *buff) {
592 for (i=0; i<r/2; i++) {
594 buff[i] = buff[r-i-1];
601 /*****************************************************************************
604 * Sort based on the /O options supplied on the command line
606 int WCMD_dir_sort (const void *a, const void *b)
608 WIN32_FIND_DATA *filea = (WIN32_FIND_DATA *)a;
609 WIN32_FIND_DATA *fileb = (WIN32_FIND_DATA *)b;
612 /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
613 requested sort order for the directory components */
614 if (orderGroupDirs &&
615 ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
616 (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
618 BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
619 if (aDir) result = -1;
621 if (orderGroupDirsReverse) result = -result;
625 } else if (dirOrder == Name) {
626 result = lstrcmpi(filea->cFileName, fileb->cFileName);
629 } else if (dirOrder == Size) {
630 ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
631 ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
632 if( sizea < sizeb ) result = -1;
633 else if( sizea == sizeb ) result = 0;
636 /* Order by Date: (Takes into account which date (/T option) */
637 } else if (dirOrder == Date) {
640 ULONG64 timea, timeb;
642 if (dirTime == Written) {
643 ft = &filea->ftLastWriteTime;
644 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
645 ft = &fileb->ftLastWriteTime;
646 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
647 } else if (dirTime == Access) {
648 ft = &filea->ftLastAccessTime;
649 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
650 ft = &fileb->ftLastAccessTime;
651 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
653 ft = &filea->ftCreationTime;
654 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
655 ft = &fileb->ftCreationTime;
656 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
658 if( timea < timeb ) result = -1;
659 else if( timea == timeb ) result = 0;
662 /* Order by Extension: (Takes into account which date (/T option) */
663 } else if (dirOrder == Extension) {
666 char fname[MAX_PATH];
670 /* Split into components */
671 WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
672 WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
673 result = lstrcmpi(extA, extB);
676 if (orderReverse) result = -result;
680 /*****************************************************************************
683 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
685 void WCMD_getfileowner(char *filename, char *owner, int ownerlen) {
687 ULONG sizeNeeded = 0;
689 char name[MAXSTRING];
690 char domain[MAXSTRING];
692 /* In case of error, return empty string */
695 /* Find out how much space we need for the owner security descritpor */
696 GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
699 if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
703 BOOL defaulted = FALSE;
704 ULONG nameLen = MAXSTRING;
705 ULONG domainLen = MAXSTRING;
706 SID_NAME_USE nameuse;
708 secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
709 if(!secBuffer) return;
711 /* Get the owners security descriptor */
712 if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
713 sizeNeeded, &sizeNeeded)) {
714 HeapFree(GetProcessHeap(),0,secBuffer);
718 /* Get the SID from the SD */
719 if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
720 HeapFree(GetProcessHeap(),0,secBuffer);
724 /* Convert to a username */
725 if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
726 snprintf(owner, ownerlen, "%s%c%s", domain, '\\', name);
728 HeapFree(GetProcessHeap(),0,secBuffer);