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;
67 /*****************************************************************************
70 * List a file directory.
74 void WCMD_directory (void) {
76 char path[MAX_PATH], drive[8];
77 int status, paged_mode;
78 ULARGE_INTEGER avail, total, free;
79 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
83 file_total = dir_total = 0;
87 orderGroupDirs = FALSE;
88 orderGroupDirsReverse = FALSE;
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);
100 if ((p = strstr(quals, "/T")) != NULL) {
102 if (*p==':') p++; /* Skip optional : */
104 if (*p == 'A') dirTime = Access;
105 else if (*p == 'C') dirTime = Creation;
106 else if (*p == 'W') dirTime = Written;
108 /* Support /T and /T: with no parms, default to written */
109 else if (*p == '/') dirTime = Written;
111 SetLastError(ERROR_INVALID_PARAMETER);
117 if ((p = strstr(quals, "/O")) != NULL) {
119 if (*p==':') p++; /* Skip optional : */
120 while (*p && *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;
129 case 'G': orderGroupDirs = TRUE; break;
131 SetLastError(ERROR_INVALID_PARAMETER);
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;
146 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
147 max_width = consoleInfo.dwSize.X;
152 WCMD_enter_paged_mode();
155 if (param1[0] == '\0') strcpy (param1, ".");
156 status = GetFullPathName (param1, sizeof(path), path, NULL);
159 if (paged_mode) WCMD_leave_paged_mode();
162 lstrcpyn (drive, path, 3);
165 status = WCMD_volume (0, drive);
167 if (paged_mode) WCMD_leave_paged_mode();
172 WCMD_list_directory (path, 0);
173 lstrcpyn (drive, path, 4);
174 GetDiskFreeSpaceEx (drive, &avail, &total, &free);
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));
183 WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free.QuadPart));
186 if (paged_mode) WCMD_leave_paged_mode();
189 /*****************************************************************************
190 * WCMD_list_directory
192 * List a single file directory. This function (and those below it) can be called
193 * recursively when the /S switch is used.
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.
201 void WCMD_list_directory (char *search_path, int level) {
203 char string[1024], datestring[32], timestring[32];
205 char real_path[MAX_PATH];
210 int status, dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
211 int numCols, numRows;
213 ULARGE_INTEGER byte_count, file_size;
218 byte_count.QuadPart = 0;
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.
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, "*");
235 strcat (search_path, "\\*");
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));
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);
251 HeapFree(GetProcessHeap(),0,fd);
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;
264 fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
267 WCMD_output ("Memory Allocation Error");
270 } while (FindNextFile(hff, (fd+entry_count)) != 0);
273 /* Sort the list of files */
274 qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
276 /* Output the results */
278 if (level != 0) WCMD_output ("\n\n");
279 WCMD_output ("Directory of %s\n\n", real_path);
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++;
290 numRows = entry_count;
292 WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
294 for (rows=0; rows<numRows; rows++) {
295 for (cols=0; cols<numCols; cols++) {
298 /* Work out the index of the entry being pointed to */
300 i = (cols * numRows) + rows;
301 if (i >= entry_count) continue;
303 i = (rows * numCols) + cols;
304 if (i >= entry_count) continue;
307 /* /L convers all names to lower case */
309 char *p = (fd+i)->cFileName;
310 while ( (*p = tolower(*p)) ) ++p;
313 /* /Q gets file ownership information */
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));
321 if (dirTime == Written) {
322 FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
323 } else if (dirTime == Access) {
324 FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
326 FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
328 FileTimeToSystemTime (&ft, &st);
329 GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
331 GetTimeFormat (0, TIME_NOSECONDS, &st,
332 NULL, timestring, sizeof(timestring));
336 tmp_width = cur_width;
337 if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
338 WCMD_output ("[%s]", (fd+i)->cFileName);
340 tmp_width = tmp_width + strlen((fd+i)->cFileName) + 2;
342 WCMD_output ("%s", (fd+i)->cFileName);
343 tmp_width = tmp_width + strlen((fd+i)->cFileName) ;
345 file_size.u.LowPart = (fd+i)->nFileSizeLow;
346 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
347 byte_count.QuadPart += file_size.QuadPart;
349 cur_width = cur_width + widest;
351 if ((cur_width + widest) > max_width) {
354 WCMD_output ("%*.s", (tmp_width - cur_width) ,"");
357 } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
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);
366 if (!((strcmp((fd+i)->cFileName, ".") == 0) ||
367 (strcmp((fd+i)->cFileName, "..") == 0))) {
368 WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
374 file_size.u.LowPart = (fd+i)->nFileSizeLow;
375 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
376 byte_count.QuadPart += file_size.QuadPart;
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);
384 WCMD_output ("%s%s", recurse?real_path:"", (fd+i)->cFileName);
393 if (file_count == 1) {
394 WCMD_output (" 1 file %25s bytes\n", WCMD_filesize64 (byte_count.QuadPart));
397 WCMD_output ("%8d files %24s bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
400 byte_total = byte_total + byte_count.QuadPart;
401 file_total = file_total + file_count;
402 dir_total = dir_total + dir_count;
405 if (dir_count == 1) WCMD_output ("1 directory ");
406 else WCMD_output ("%8d directories", dir_count);
408 for (i=0; i<entry_count; i++) {
410 ((fd+i)->cFileName[0] != '.') &&
411 ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
413 GetFullPathName ((fd+i)->cFileName, sizeof(string), string, NULL);
415 p = strrchr (search_path, '\\');
416 lstrcpyn (string, search_path, (p-search_path+2));
417 lstrcat (string, (fd+i)->cFileName);
419 WCMD_list_directory (string, 1);
422 HeapFree(GetProcessHeap(),0,fd);
426 /*****************************************************************************
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!
434 char * WCMD_filesize64 (ULONGLONG n) {
439 static char buff[32];
444 if ((++i)%3 == 1) *p++ = ',';
455 /*****************************************************************************
458 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
461 char * WCMD_strrev (char *buff) {
467 for (i=0; i<r/2; i++) {
469 buff[i] = buff[r-i-1];
476 /*****************************************************************************
479 * Sort based on the /O options supplied on the command line
481 int WCMD_dir_sort (const void *a, const void *b)
483 WIN32_FIND_DATA *filea = (WIN32_FIND_DATA *)a;
484 WIN32_FIND_DATA *fileb = (WIN32_FIND_DATA *)b;
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)))
493 BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
494 if (aDir) result = -1;
496 if (orderGroupDirsReverse) result = -result;
500 } else if (dirOrder == Name) {
501 result = lstrcmpi(filea->cFileName, fileb->cFileName);
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;
511 /* Order by Date: (Takes into account which date (/T option) */
512 } else if (dirOrder == Date) {
515 ULONG64 timea, timeb;
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;
528 ft = &filea->ftCreationTime;
529 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
530 ft = &fileb->ftCreationTime;
531 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
533 if( timea < timeb ) result = -1;
534 else if( timea == timeb ) result = 0;
537 /* Order by Extension: (Takes into account which date (/T option) */
538 } else if (dirOrder == Extension) {
541 char fname[MAX_PATH];
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);
551 if (orderReverse) result = -result;
555 /*****************************************************************************
558 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
560 void WCMD_getfileowner(char *filename, char *owner, int ownerlen) {
562 ULONG sizeNeeded = 0;
564 char name[MAXSTRING];
565 char domain[MAXSTRING];
567 /* In case of error, return empty string */
570 /* Find out how much space we need for the owner security descritpor */
571 GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
574 if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
578 BOOL defaulted = FALSE;
579 ULONG nameLen = MAXSTRING;
580 ULONG domainLen = MAXSTRING;
581 SID_NAME_USE nameuse;
583 secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
584 if(!secBuffer) return;
586 /* Get the owners security descriptor */
587 if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
588 sizeNeeded, &sizeNeeded)) {
589 HeapFree(GetProcessHeap(),0,secBuffer);
593 /* Get the SID from the SD */
594 if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
595 HeapFree(GetProcessHeap(),0,secBuffer);
599 /* Convert to a username */
600 if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
601 snprintf(owner, ownerlen, "%s%c%s", domain, '\\', name);
603 HeapFree(GetProcessHeap(),0,secBuffer);