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
];
85 /* Prefill Quals with (uppercased) DIRCMD env var */
86 if (GetEnvironmentVariable ("DIRCMD", string
, sizeof(string
))) {
88 while ( (*p
= toupper(*p
)) ) ++p
;
90 strcpy(quals
, string
);
94 file_total
= dir_total
= 0;
96 /* Initialize all flags to their defaults as if no DIRCMD or quals */
108 orderReverse
= FALSE
;
109 orderGroupDirs
= FALSE
;
110 orderGroupDirsReverse
= FALSE
;
114 /* Handle args - Loop through so right most is the effective one */
115 /* Note: /- appears to be a negate rather than an off, eg. dir
116 /-W is wide, or dir /w /-w /-w is also wide */
118 while (*p
&& (*p
=='/' || *p
==' ')) {
120 if (*p
++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
127 WINE_TRACE("Processing arg '%c' (in %s)\n", *p
, quals
);
129 case 'P': if (negate
) paged_mode
= !paged_mode
;
130 else paged_mode
= TRUE
;
132 case 'S': if (negate
) recurse
= !recurse
;
135 case 'W': if (negate
) wide
= !wide
;
138 case 'B': if (negate
) bare
= !bare
;
141 case 'L': if (negate
) lower
= !lower
;
144 case 'X': if (negate
) shortname
= !shortname
;
145 else shortname
= TRUE
;
147 case 'Q': if (negate
) usernames
= !usernames
;
148 else usernames
= TRUE
;
150 case 'D': if (negate
) orderByCol
= !orderByCol
;
151 else orderByCol
= TRUE
;
153 case 'C': if (negate
) seperator
= !seperator
;
154 else seperator
= TRUE
;
157 if (*p
==':') p
++; /* Skip optional : */
159 if (*p
== 'A') dirTime
= Access
;
160 else if (*p
== 'C') dirTime
= Creation
;
161 else if (*p
== 'W') dirTime
= Written
;
163 /* Support /T and /T: with no parms, default to written */
164 else if (*p
== 0x00 || *p
== '/') {
166 p
= p
- 1; /* So when step on, move to '/' */
168 SetLastError(ERROR_INVALID_PARAMETER
);
174 if (*p
==':') p
++; /* Skip optional : */
175 while (*p
&& *p
!= '/') {
176 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p
, quals
);
178 case 'N': dirOrder
= Name
; break;
179 case 'E': dirOrder
= Extension
; break;
180 case 'S': dirOrder
= Size
; break;
181 case 'D': dirOrder
= Date
; break;
182 case '-': if (*(p
+1)=='G') orderGroupDirsReverse
=TRUE
;
183 else orderReverse
= TRUE
;
185 case 'G': orderGroupDirs
= TRUE
; break;
187 SetLastError(ERROR_INVALID_PARAMETER
);
193 p
= p
- 1; /* So when step on, move to '/' */
198 if (*p
==':') p
++; /* Skip optional : */
199 while (*p
&& *p
!= '/') {
200 BOOL anegate
= FALSE
;
203 /* Note /A: - options are 'offs' not toggles */
209 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p
, quals
);
211 case 'D': mask
= FILE_ATTRIBUTE_DIRECTORY
; break;
212 case 'H': mask
= FILE_ATTRIBUTE_HIDDEN
; break;
213 case 'S': mask
= FILE_ATTRIBUTE_SYSTEM
; break;
214 case 'R': mask
= FILE_ATTRIBUTE_READONLY
; break;
215 case 'A': mask
= FILE_ATTRIBUTE_ARCHIVE
; break;
217 SetLastError(ERROR_INVALID_PARAMETER
);
222 /* Keep running list of bits we care about */
225 /* Mask shows what MUST be in the bits we care about */
226 if (anegate
) showattrs
= showattrs
& ~mask
;
227 else showattrs
|= mask
;
231 p
= p
- 1; /* So when step on, move to '/' */
232 WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs
, attrsbits
);
235 SetLastError(ERROR_INVALID_PARAMETER
);
242 /* Handle conflicting args and initialization */
243 if (bare
|| shortname
) wide
= FALSE
;
244 if (bare
) shortname
= FALSE
;
245 if (wide
) usernames
= FALSE
;
246 if (orderByCol
) wide
= TRUE
;
249 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &consoleInfo
))
250 max_width
= consoleInfo
.dwSize
.X
;
255 WCMD_enter_paged_mode();
258 if (param1
[0] == '\0') strcpy (param1
, ".");
259 status
= GetFullPathName (param1
, sizeof(path
), path
, NULL
);
262 if (paged_mode
) WCMD_leave_paged_mode();
265 lstrcpyn (drive
, path
, 3);
268 status
= WCMD_volume (0, drive
);
270 if (paged_mode
) WCMD_leave_paged_mode();
275 WCMD_list_directory (path
, 0);
276 lstrcpyn (drive
, path
, 4);
277 GetDiskFreeSpaceEx (drive
, &avail
, &total
, &free
);
281 WCMD_output ("\n\n Total files listed:\n%8d files%25s bytes\n",
282 file_total
, WCMD_filesize64 (byte_total
));
283 WCMD_output ("%8d directories %18s bytes free\n\n",
284 dir_total
, WCMD_filesize64 (free
.QuadPart
));
286 WCMD_output (" %18s bytes free\n\n", WCMD_filesize64 (free
.QuadPart
));
289 if (paged_mode
) WCMD_leave_paged_mode();
292 /*****************************************************************************
293 * WCMD_list_directory
295 * List a single file directory. This function (and those below it) can be called
296 * recursively when the /S switch is used.
298 * FIXME: Entries sorted by name only. Should we support DIRCMD??
299 * FIXME: Assumes 24-line display for the /P qualifier.
300 * FIXME: Other command qualifiers not supported.
301 * FIXME: DIR /S FILENAME fails if at least one matching file is not found in the top level.
304 void WCMD_list_directory (char *search_path
, int level
) {
306 char string
[1024], datestring
[32], timestring
[32];
308 char real_path
[MAX_PATH
];
313 int status
, dir_count
, file_count
, entry_count
, i
, widest
, cur_width
, tmp_width
;
314 int numCols
, numRows
;
316 ULARGE_INTEGER byte_count
, file_size
;
321 byte_count
.QuadPart
= 0;
326 * If the path supplied does not include a wildcard, and the endpoint of the
327 * path references a directory, we need to list the *contents* of that
328 * directory not the directory file itself.
331 if ((strchr(search_path
, '*') == NULL
) && (strchr(search_path
, '%') == NULL
)) {
332 status
= GetFileAttributes (search_path
);
333 if ((status
!= INVALID_FILE_ATTRIBUTES
) && (status
& FILE_ATTRIBUTE_DIRECTORY
)) {
334 if (search_path
[strlen(search_path
)-1] == '\\') {
335 strcat (search_path
, "*");
338 strcat (search_path
, "\\*");
343 /* Work out the actual current directory name */
344 p
= strrchr (search_path
, '\\');
345 memset(real_path
, 0x00, sizeof(real_path
));
346 lstrcpyn (real_path
, search_path
, (p
-search_path
+2));
348 /* Load all files into an in memory structure */
349 fd
= HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA
));
350 hff
= FindFirstFile (search_path
, fd
);
351 if (hff
== INVALID_HANDLE_VALUE
) {
352 SetLastError (ERROR_FILE_NOT_FOUND
);
354 HeapFree(GetProcessHeap(),0,fd
);
358 /* Skip any which are filtered out by attribute */
359 if (((fd
+entry_count
)->dwFileAttributes
& attrsbits
) != showattrs
) continue;
363 /* Keep running track of longest filename for wide output */
364 if (wide
|| orderByCol
) {
365 int tmpLen
= strlen((fd
+(entry_count
-1))->cFileName
) + 3;
366 if ((fd
+(entry_count
-1))->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) tmpLen
= tmpLen
+ 2;
367 if (tmpLen
> widest
) widest
= tmpLen
;
370 fd
= HeapReAlloc(GetProcessHeap(),0,fd
,(entry_count
+1)*sizeof(WIN32_FIND_DATA
));
373 WCMD_output ("Memory Allocation Error");
376 } while (FindNextFile(hff
, (fd
+entry_count
)) != 0);
379 /* Handle case where everything is filtered out */
380 if (entry_count
== 0) {
381 SetLastError (ERROR_FILE_NOT_FOUND
);
383 HeapFree(GetProcessHeap(),0,fd
);
387 /* Sort the list of files */
388 qsort (fd
, entry_count
, sizeof(WIN32_FIND_DATA
), WCMD_dir_sort
);
390 /* Output the results */
392 if (level
!= 0) WCMD_output ("\n\n");
393 WCMD_output ("Directory of %s\n\n", real_path
);
396 /* Work out the number of columns */
397 WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count
, max_width
, widest
);
398 if (wide
|| orderByCol
) {
399 numCols
= max(1, (int)max_width
/ widest
);
400 numRows
= entry_count
/ numCols
;
401 if (entry_count
% numCols
) numRows
++;
404 numRows
= entry_count
;
406 WINE_TRACE("cols=%d, rows=%d\n", numCols
, numRows
);
408 for (rows
=0; rows
<numRows
; rows
++) {
409 for (cols
=0; cols
<numCols
; cols
++) {
412 /* Work out the index of the entry being pointed to */
414 i
= (cols
* numRows
) + rows
;
415 if (i
>= entry_count
) continue;
417 i
= (rows
* numCols
) + cols
;
418 if (i
>= entry_count
) continue;
421 /* /L convers all names to lower case */
423 char *p
= (fd
+i
)->cFileName
;
424 while ( (*p
= tolower(*p
)) ) ++p
;
427 /* /Q gets file ownership information */
429 p
= strrchr (search_path
, '\\');
430 lstrcpyn (string
, search_path
, (p
-search_path
+2));
431 lstrcat (string
, (fd
+i
)->cFileName
);
432 WCMD_getfileowner(string
, username
, sizeof(username
));
435 if (dirTime
== Written
) {
436 FileTimeToLocalFileTime (&(fd
+i
)->ftLastWriteTime
, &ft
);
437 } else if (dirTime
== Access
) {
438 FileTimeToLocalFileTime (&(fd
+i
)->ftLastAccessTime
, &ft
);
440 FileTimeToLocalFileTime (&(fd
+i
)->ftCreationTime
, &ft
);
442 FileTimeToSystemTime (&ft
, &st
);
443 GetDateFormat (0, DATE_SHORTDATE
, &st
, NULL
, datestring
,
445 GetTimeFormat (0, TIME_NOSECONDS
, &st
,
446 NULL
, timestring
, sizeof(timestring
));
450 tmp_width
= cur_width
;
451 if ((fd
+i
)->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
452 WCMD_output ("[%s]", (fd
+i
)->cFileName
);
454 tmp_width
= tmp_width
+ strlen((fd
+i
)->cFileName
) + 2;
456 WCMD_output ("%s", (fd
+i
)->cFileName
);
457 tmp_width
= tmp_width
+ strlen((fd
+i
)->cFileName
) ;
459 file_size
.u
.LowPart
= (fd
+i
)->nFileSizeLow
;
460 file_size
.u
.HighPart
= (fd
+i
)->nFileSizeHigh
;
461 byte_count
.QuadPart
+= file_size
.QuadPart
;
463 cur_width
= cur_width
+ widest
;
465 if ((cur_width
+ widest
) > max_width
) {
468 WCMD_output ("%*.s", (tmp_width
- cur_width
) ,"");
471 } else if ((fd
+i
)->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
475 WCMD_output ("%10s %8s <DIR> ", datestring
, timestring
);
476 if (shortname
) WCMD_output ("%-13s", (fd
+i
)->cAlternateFileName
);
477 if (usernames
) WCMD_output ("%-23s", username
);
478 WCMD_output("%s",(fd
+i
)->cFileName
);
480 if (!((strcmp((fd
+i
)->cFileName
, ".") == 0) ||
481 (strcmp((fd
+i
)->cFileName
, "..") == 0))) {
482 WCMD_output ("%s%s", recurse
?real_path
:"", (fd
+i
)->cFileName
);
488 file_size
.u
.LowPart
= (fd
+i
)->nFileSizeLow
;
489 file_size
.u
.HighPart
= (fd
+i
)->nFileSizeHigh
;
490 byte_count
.QuadPart
+= file_size
.QuadPart
;
492 WCMD_output ("%10s %8s %10s ", datestring
, timestring
,
493 WCMD_filesize64(file_size
.QuadPart
));
494 if (shortname
) WCMD_output ("%-13s", (fd
+i
)->cAlternateFileName
);
495 if (usernames
) WCMD_output ("%-23s", username
);
496 WCMD_output("%s",(fd
+i
)->cFileName
);
498 WCMD_output ("%s%s", recurse
?real_path
:"", (fd
+i
)->cFileName
);
507 if (file_count
== 1) {
508 WCMD_output (" 1 file %25s bytes\n", WCMD_filesize64 (byte_count
.QuadPart
));
511 WCMD_output ("%8d files %24s bytes\n", file_count
, WCMD_filesize64 (byte_count
.QuadPart
));
514 byte_total
= byte_total
+ byte_count
.QuadPart
;
515 file_total
= file_total
+ file_count
;
516 dir_total
= dir_total
+ dir_count
;
519 if (dir_count
== 1) WCMD_output ("1 directory ");
520 else WCMD_output ("%8d directories", dir_count
);
522 for (i
=0; i
<entry_count
; i
++) {
524 ((fd
+i
)->cFileName
[0] != '.') &&
525 ((fd
+i
)->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)) {
527 GetFullPathName ((fd
+i
)->cFileName
, sizeof(string
), string
, NULL
);
529 p
= strrchr (search_path
, '\\');
530 lstrcpyn (string
, search_path
, (p
-search_path
+2));
531 lstrcat (string
, (fd
+i
)->cFileName
);
533 WCMD_list_directory (string
, 1);
536 HeapFree(GetProcessHeap(),0,fd
);
540 /*****************************************************************************
543 * Convert a 64-bit number into a character string, with commas every three digits.
544 * Result is returned in a static string overwritten with each call.
545 * FIXME: There must be a better algorithm!
548 char * WCMD_filesize64 (ULONGLONG n
) {
553 static char buff
[32];
558 if (seperator
&& ((++i
)%3 == 1)) *p
++ = ',';
569 /*****************************************************************************
572 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
575 char * WCMD_strrev (char *buff
) {
581 for (i
=0; i
<r
/2; i
++) {
583 buff
[i
] = buff
[r
-i
-1];
590 /*****************************************************************************
593 * Sort based on the /O options supplied on the command line
595 int WCMD_dir_sort (const void *a
, const void *b
)
597 WIN32_FIND_DATA
*filea
= (WIN32_FIND_DATA
*)a
;
598 WIN32_FIND_DATA
*fileb
= (WIN32_FIND_DATA
*)b
;
601 /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
602 requested sort order for the directory components */
603 if (orderGroupDirs
&&
604 ((filea
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) ||
605 (fileb
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)))
607 BOOL aDir
= filea
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
;
608 if (aDir
) result
= -1;
610 if (orderGroupDirsReverse
) result
= -result
;
614 } else if (dirOrder
== Name
) {
615 result
= lstrcmpi(filea
->cFileName
, fileb
->cFileName
);
618 } else if (dirOrder
== Size
) {
619 ULONG64 sizea
= (((ULONG64
)filea
->nFileSizeHigh
) << 32) + filea
->nFileSizeLow
;
620 ULONG64 sizeb
= (((ULONG64
)fileb
->nFileSizeHigh
) << 32) + fileb
->nFileSizeLow
;
621 if( sizea
< sizeb
) result
= -1;
622 else if( sizea
== sizeb
) result
= 0;
625 /* Order by Date: (Takes into account which date (/T option) */
626 } else if (dirOrder
== Date
) {
629 ULONG64 timea
, timeb
;
631 if (dirTime
== Written
) {
632 ft
= &filea
->ftLastWriteTime
;
633 timea
= (((ULONG64
)ft
->dwHighDateTime
) << 32) + ft
->dwLowDateTime
;
634 ft
= &fileb
->ftLastWriteTime
;
635 timeb
= (((ULONG64
)ft
->dwHighDateTime
) << 32) + ft
->dwLowDateTime
;
636 } else if (dirTime
== Access
) {
637 ft
= &filea
->ftLastAccessTime
;
638 timea
= (((ULONG64
)ft
->dwHighDateTime
) << 32) + ft
->dwLowDateTime
;
639 ft
= &fileb
->ftLastAccessTime
;
640 timeb
= (((ULONG64
)ft
->dwHighDateTime
) << 32) + ft
->dwLowDateTime
;
642 ft
= &filea
->ftCreationTime
;
643 timea
= (((ULONG64
)ft
->dwHighDateTime
) << 32) + ft
->dwLowDateTime
;
644 ft
= &fileb
->ftCreationTime
;
645 timeb
= (((ULONG64
)ft
->dwHighDateTime
) << 32) + ft
->dwLowDateTime
;
647 if( timea
< timeb
) result
= -1;
648 else if( timea
== timeb
) result
= 0;
651 /* Order by Extension: (Takes into account which date (/T option) */
652 } else if (dirOrder
== Extension
) {
655 char fname
[MAX_PATH
];
659 /* Split into components */
660 WCMD_splitpath(filea
->cFileName
, drive
, dir
, fname
, extA
);
661 WCMD_splitpath(fileb
->cFileName
, drive
, dir
, fname
, extB
);
662 result
= lstrcmpi(extA
, extB
);
665 if (orderReverse
) result
= -result
;
669 /*****************************************************************************
672 * Reverse a character string in-place (strrev() is not available under unixen :-( ).
674 void WCMD_getfileowner(char *filename
, char *owner
, int ownerlen
) {
676 ULONG sizeNeeded
= 0;
678 char name
[MAXSTRING
];
679 char domain
[MAXSTRING
];
681 /* In case of error, return empty string */
684 /* Find out how much space we need for the owner security descritpor */
685 GetFileSecurity(filename
, OWNER_SECURITY_INFORMATION
, 0, 0, &sizeNeeded
);
688 if(rc
== ERROR_INSUFFICIENT_BUFFER
&& sizeNeeded
> 0) {
692 BOOL defaulted
= FALSE
;
693 ULONG nameLen
= MAXSTRING
;
694 ULONG domainLen
= MAXSTRING
;
695 SID_NAME_USE nameuse
;
697 secBuffer
= (LPBYTE
) HeapAlloc(GetProcessHeap(),0,sizeNeeded
* sizeof(BYTE
));
698 if(!secBuffer
) return;
700 /* Get the owners security descriptor */
701 if(!GetFileSecurity(filename
, OWNER_SECURITY_INFORMATION
, secBuffer
,
702 sizeNeeded
, &sizeNeeded
)) {
703 HeapFree(GetProcessHeap(),0,secBuffer
);
707 /* Get the SID from the SD */
708 if(!GetSecurityDescriptorOwner(secBuffer
, &pSID
, &defaulted
)) {
709 HeapFree(GetProcessHeap(),0,secBuffer
);
713 /* Convert to a username */
714 if (LookupAccountSid(NULL
, pSID
, name
, &nameLen
, domain
, &domainLen
, &nameuse
)) {
715 snprintf(owner
, ownerlen
, "%s%c%s", domain
, '\\', name
);
717 HeapFree(GetProcessHeap(),0,secBuffer
);