cmd: Bail out when full path name exceeds MAX_PATH.
[wine.git] / programs / cmd / directory.c
blob807f7b386b11aca8cb06354028b0e059b9690ea8
1 /*
2 * CMD - Wine-compatible command line interface - Directory functions.
4 * Copyright (C) 1999 D A Pickles
5 * Copyright (C) 2007 J Edmeades
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #define WIN32_LEAN_AND_MEAN
24 #include "wcmd.h"
25 #include "wine/debug.h"
27 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
29 typedef enum _DISPLAYTIME
31 Creation = 0,
32 Access,
33 Written
34 } DISPLAYTIME;
36 typedef enum _DISPLAYORDER
38 Name = 0,
39 Extension,
40 Size,
41 Date
42 } DISPLAYORDER;
44 static int file_total, dir_total, max_width;
45 static ULONGLONG byte_total;
46 static DISPLAYTIME dirTime;
47 static DISPLAYORDER dirOrder;
48 static BOOL orderReverse, orderGroupDirs, orderGroupDirsReverse, orderByCol;
49 static BOOL paged_mode, recurse, wide, bare, lower, shortname, usernames, separator;
50 static ULONG showattrs, attrsbits;
52 /*****************************************************************************
53 * WCMD_strrev
55 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
57 static WCHAR * WCMD_strrev (WCHAR *buff) {
59 int r, i;
60 WCHAR b;
62 r = lstrlenW (buff);
63 for (i=0; i<r/2; i++) {
64 b = buff[i];
65 buff[i] = buff[r-i-1];
66 buff[r-i-1] = b;
68 return (buff);
71 /*****************************************************************************
72 * WCMD_filesize64
74 * Convert a 64-bit number into a WCHARacter string, with commas every three digits.
75 * Result is returned in a static string overwritten with each call.
76 * FIXME: There must be a better algorithm!
78 static WCHAR * WCMD_filesize64 (ULONGLONG n) {
80 ULONGLONG q;
81 unsigned int r, i;
82 WCHAR *p;
83 static WCHAR buff[32];
85 p = buff;
86 i = -3;
87 do {
88 if (separator && ((++i)%3 == 1)) *p++ = ',';
89 q = n / 10;
90 r = n - (q * 10);
91 *p++ = r + '0';
92 *p = '\0';
93 n = q;
94 } while (n != 0);
95 WCMD_strrev (buff);
96 return buff;
99 /*****************************************************************************
100 * WCMD_dir_sort
102 * Sort based on the /O options supplied on the command line
104 static int __cdecl WCMD_dir_sort (const void *a, const void *b)
106 const WIN32_FIND_DATAW *filea = (const WIN32_FIND_DATAW *)a;
107 const WIN32_FIND_DATAW *fileb = (const WIN32_FIND_DATAW *)b;
108 int result = 0;
110 /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
111 requested sort order for the directory components */
112 if (orderGroupDirs &&
113 ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
114 (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
116 BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
117 if (aDir) result = -1;
118 else result = 1;
119 if (orderGroupDirsReverse) result = -result;
120 return result;
122 /* Order by Name: */
123 } else if (dirOrder == Name) {
124 result = lstrcmpiW(filea->cFileName, fileb->cFileName);
126 /* Order by Size: */
127 } else if (dirOrder == Size) {
128 ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
129 ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
130 if( sizea < sizeb ) result = -1;
131 else if( sizea == sizeb ) result = 0;
132 else result = 1;
134 /* Order by Date: (Takes into account which date (/T option) */
135 } else if (dirOrder == Date) {
137 const FILETIME *ft;
138 ULONG64 timea, timeb;
140 if (dirTime == Written) {
141 ft = &filea->ftLastWriteTime;
142 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
143 ft = &fileb->ftLastWriteTime;
144 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
145 } else if (dirTime == Access) {
146 ft = &filea->ftLastAccessTime;
147 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
148 ft = &fileb->ftLastAccessTime;
149 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
150 } else {
151 ft = &filea->ftCreationTime;
152 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
153 ft = &fileb->ftCreationTime;
154 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
156 if( timea < timeb ) result = -1;
157 else if( timea == timeb ) result = 0;
158 else result = 1;
160 /* Order by Extension: (Takes into account which date (/T option) */
161 } else if (dirOrder == Extension) {
162 WCHAR drive[10];
163 WCHAR dir[MAX_PATH];
164 WCHAR fname[MAX_PATH];
165 WCHAR extA[MAX_PATH];
166 WCHAR extB[MAX_PATH];
168 /* Split into components */
169 _wsplitpath(filea->cFileName, drive, dir, fname, extA);
170 _wsplitpath(fileb->cFileName, drive, dir, fname, extB);
171 result = lstrcmpiW(extA, extB);
174 if (orderReverse) result = -result;
175 return result;
178 /*****************************************************************************
179 * WCMD_getfileowner
181 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
183 static void WCMD_getfileowner(WCHAR *filename, WCHAR *owner, int ownerlen) {
185 ULONG sizeNeeded = 0;
186 DWORD rc;
187 WCHAR name[MAXSTRING];
188 WCHAR domain[MAXSTRING];
190 /* In case of error, return empty string */
191 *owner = 0x00;
193 /* Find out how much space we need for the owner security descriptor */
194 GetFileSecurityW(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
195 rc = GetLastError();
197 if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
199 LPBYTE secBuffer;
200 PSID pSID = NULL;
201 BOOL defaulted = FALSE;
202 ULONG nameLen = MAXSTRING;
203 ULONG domainLen = MAXSTRING;
204 SID_NAME_USE nameuse;
206 secBuffer = heap_xalloc(sizeNeeded * sizeof(BYTE));
208 /* Get the owners security descriptor */
209 if(!GetFileSecurityW(filename, OWNER_SECURITY_INFORMATION, secBuffer,
210 sizeNeeded, &sizeNeeded)) {
211 heap_free(secBuffer);
212 return;
215 /* Get the SID from the SD */
216 if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
217 heap_free(secBuffer);
218 return;
221 /* Convert to a username */
222 if (LookupAccountSidW(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
223 swprintf(owner, ownerlen, L"%s%c%s", domain, '\\', name);
225 heap_free(secBuffer);
227 return;
230 /*****************************************************************************
231 * WCMD_list_directory
233 * List a single file directory. This function (and those below it) can be called
234 * recursively when the /S switch is used.
236 * FIXME: Assumes 24-line display for the /P qualifier.
239 static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *inputparms, int level) {
241 WCHAR string[1024], datestring[32], timestring[32];
242 WCHAR real_path[MAX_PATH];
243 WIN32_FIND_DATAW *fd;
244 FILETIME ft;
245 SYSTEMTIME st;
246 HANDLE hff;
247 int dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
248 int numCols, numRows;
249 int rows, cols;
250 ULARGE_INTEGER byte_count, file_size;
251 DIRECTORY_STACK *parms;
252 int concurrentDirs = 0;
253 BOOL done_header = FALSE;
255 dir_count = 0;
256 file_count = 0;
257 entry_count = 0;
258 byte_count.QuadPart = 0;
259 widest = 0;
260 cur_width = 0;
262 /* Loop merging all the files from consecutive parms which relate to the
263 same directory. Note issuing a directory header with no contents
264 mirrors what windows does */
265 parms = inputparms;
266 fd = heap_xalloc(sizeof(WIN32_FIND_DATAW));
267 while (parms && lstrcmpW(inputparms->dirName, parms->dirName) == 0) {
268 concurrentDirs++;
270 /* Work out the full path + filename */
271 lstrcpyW(real_path, parms->dirName);
272 lstrcatW(real_path, parms->fileName);
274 /* Load all files into an in memory structure */
275 WINE_TRACE("Looking for matches to '%s'\n", wine_dbgstr_w(real_path));
276 hff = FindFirstFileW(real_path, &fd[entry_count]);
277 if (hff != INVALID_HANDLE_VALUE) {
278 do {
279 /* Skip any which are filtered out by attribute */
280 if ((fd[entry_count].dwFileAttributes & attrsbits) != showattrs) continue;
282 entry_count++;
284 /* Keep running track of longest filename for wide output */
285 if (wide || orderByCol) {
286 int tmpLen = lstrlenW(fd[entry_count-1].cFileName) + 3;
287 if (fd[entry_count-1].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
288 if (tmpLen > widest) widest = tmpLen;
291 fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATAW));
292 if (fd == NULL) {
293 FindClose (hff);
294 WINE_ERR("Out of memory\n");
295 errorlevel = 1;
296 return parms->next;
298 } while (FindNextFileW(hff, &fd[entry_count]) != 0);
299 FindClose (hff);
302 /* Work out the actual current directory name without a trailing \ */
303 lstrcpyW(real_path, parms->dirName);
304 real_path[lstrlenW(parms->dirName)-1] = 0x00;
306 /* Output the results */
307 if (!bare) {
308 if (level != 0 && (entry_count > 0)) WCMD_output_asis(L"\r\n");
309 if (!recurse || ((entry_count > 0) && done_header==FALSE)) {
310 WCMD_output (L"Directory of %1\n\n", real_path);
311 done_header = TRUE;
315 /* Move to next parm */
316 parms = parms->next;
319 /* Handle case where everything is filtered out */
320 if (entry_count > 0) {
322 /* Sort the list of files */
323 qsort (fd, entry_count, sizeof(WIN32_FIND_DATAW), WCMD_dir_sort);
325 /* Work out the number of columns */
326 WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
327 if (wide || orderByCol) {
328 numCols = max(1, max_width / widest);
329 numRows = entry_count / numCols;
330 if (entry_count % numCols) numRows++;
331 } else {
332 numCols = 1;
333 numRows = entry_count;
335 WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
337 for (rows=0; rows<numRows; rows++) {
338 BOOL addNewLine = TRUE;
339 for (cols=0; cols<numCols; cols++) {
340 WCHAR username[24];
342 /* Work out the index of the entry being pointed to */
343 if (orderByCol) {
344 i = (cols * numRows) + rows;
345 if (i >= entry_count) continue;
346 } else {
347 i = (rows * numCols) + cols;
348 if (i >= entry_count) continue;
351 /* /L convers all names to lower case */
352 if (lower) {
353 WCHAR *p = fd[i].cFileName;
354 while ( (*p = tolower(*p)) ) ++p;
357 /* /Q gets file ownership information */
358 if (usernames) {
359 lstrcpyW (string, inputparms->dirName);
360 lstrcatW (string, fd[i].cFileName);
361 WCMD_getfileowner(string, username, ARRAY_SIZE(username));
364 if (dirTime == Written) {
365 FileTimeToLocalFileTime (&fd[i].ftLastWriteTime, &ft);
366 } else if (dirTime == Access) {
367 FileTimeToLocalFileTime (&fd[i].ftLastAccessTime, &ft);
368 } else {
369 FileTimeToLocalFileTime (&fd[i].ftCreationTime, &ft);
371 FileTimeToSystemTime (&ft, &st);
372 GetDateFormatW(0, DATE_SHORTDATE, &st, NULL, datestring, ARRAY_SIZE(datestring));
373 GetTimeFormatW(0, TIME_NOSECONDS, &st, NULL, timestring, ARRAY_SIZE(timestring));
375 if (wide) {
377 tmp_width = cur_width;
378 if (fd[i].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
379 WCMD_output (L"[%1]", fd[i].cFileName);
380 dir_count++;
381 tmp_width = tmp_width + lstrlenW(fd[i].cFileName) + 2;
382 } else {
383 WCMD_output (L"%1", fd[i].cFileName);
384 tmp_width = tmp_width + lstrlenW(fd[i].cFileName) ;
385 file_count++;
386 file_size.u.LowPart = fd[i].nFileSizeLow;
387 file_size.u.HighPart = fd[i].nFileSizeHigh;
388 byte_count.QuadPart += file_size.QuadPart;
390 cur_width = cur_width + widest;
392 if ((cur_width + widest) > max_width) {
393 cur_width = 0;
394 } else {
395 WCMD_output(L"%1!*s!", cur_width - tmp_width, L"");
398 } else if (fd[i].dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
399 dir_count++;
401 if (!bare) {
402 WCMD_output (L"%1!10s! %2!8s! <DIR> ", datestring, timestring);
403 if (shortname) WCMD_output(L"%1!-13s!", fd[i].cAlternateFileName);
404 if (usernames) WCMD_output(L"%1!-23s!", username);
405 WCMD_output(L"%1",fd[i].cFileName);
406 } else {
407 if (!((lstrcmpW(fd[i].cFileName, L".") == 0) ||
408 (lstrcmpW(fd[i].cFileName, L"..") == 0))) {
409 WCMD_output(L"%1%2", recurse ? inputparms->dirName : L"", fd[i].cFileName);
410 } else {
411 addNewLine = FALSE;
415 else {
416 file_count++;
417 file_size.u.LowPart = fd[i].nFileSizeLow;
418 file_size.u.HighPart = fd[i].nFileSizeHigh;
419 byte_count.QuadPart += file_size.QuadPart;
420 if (!bare) {
421 WCMD_output (L"%1!10s! %2!8s! %3!10s! ", datestring, timestring,
422 WCMD_filesize64(file_size.QuadPart));
423 if (shortname) WCMD_output(L"%1!-13s!", fd[i].cAlternateFileName);
424 if (usernames) WCMD_output(L"%1!-23s!", username);
425 WCMD_output(L"%1",fd[i].cFileName);
426 } else {
427 WCMD_output(L"%1%2", recurse ? inputparms->dirName : L"", fd[i].cFileName);
431 if (addNewLine) WCMD_output_asis(L"\r\n");
432 cur_width = 0;
435 if (!bare) {
436 if (file_count == 1) {
437 WCMD_output (L" 1 file %1!25s! bytes\n", WCMD_filesize64 (byte_count.QuadPart));
439 else {
440 WCMD_output (L"%1!8d! files %2!24s! bytes\n", file_count, WCMD_filesize64 (byte_count.QuadPart));
443 byte_total = byte_total + byte_count.QuadPart;
444 file_total = file_total + file_count;
445 dir_total = dir_total + dir_count;
447 if (!bare && !recurse) {
448 if (dir_count == 1) {
449 WCMD_output (L"%1!8d! directory ", 1);
450 } else {
451 WCMD_output (L"%1!8d! directories", dir_count);
455 heap_free(fd);
457 /* When recursing, look in all subdirectories for matches */
458 if (recurse) {
459 DIRECTORY_STACK *dirStack = NULL;
460 DIRECTORY_STACK *lastEntry = NULL;
461 WIN32_FIND_DATAW finddata;
463 /* Build path to search */
464 lstrcpyW(string, inputparms->dirName);
465 lstrcatW(string, L"*");
467 WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
468 hff = FindFirstFileW(string, &finddata);
469 if (hff != INVALID_HANDLE_VALUE) {
470 do {
471 if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
472 (lstrcmpW(finddata.cFileName, L"..") != 0) &&
473 (lstrcmpW(finddata.cFileName, L".") != 0)) {
475 DIRECTORY_STACK *thisDir;
476 int dirsToCopy = concurrentDirs;
478 /* Loop creating list of subdirs for all concurrent entries */
479 parms = inputparms;
480 while (dirsToCopy > 0) {
481 dirsToCopy--;
483 /* Work out search parameter in sub dir */
484 lstrcpyW (string, inputparms->dirName);
485 lstrcatW (string, finddata.cFileName);
486 lstrcatW(string, L"\\");
487 WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));
489 /* Allocate memory, add to list */
490 thisDir = heap_xalloc(sizeof(DIRECTORY_STACK));
491 if (dirStack == NULL) dirStack = thisDir;
492 if (lastEntry != NULL) lastEntry->next = thisDir;
493 lastEntry = thisDir;
494 thisDir->next = NULL;
495 thisDir->dirName = heap_strdupW(string);
496 thisDir->fileName = heap_strdupW(parms->fileName);
497 parms = parms->next;
500 } while (FindNextFileW(hff, &finddata) != 0);
501 FindClose (hff);
503 while (dirStack != NULL) {
504 DIRECTORY_STACK *thisDir = dirStack;
505 dirStack = WCMD_list_directory (thisDir, 1);
506 while (thisDir != dirStack) {
507 DIRECTORY_STACK *tempDir = thisDir->next;
508 heap_free(thisDir->dirName);
509 heap_free(thisDir->fileName);
510 heap_free(thisDir);
511 thisDir = tempDir;
517 /* Handle case where everything is filtered out */
518 if ((file_total + dir_total == 0) && (level == 0)) {
519 SetLastError (ERROR_FILE_NOT_FOUND);
520 WCMD_print_error ();
521 errorlevel = 1;
524 return parms;
527 /*****************************************************************************
528 * WCMD_dir_trailer
530 * Print out the trailer for the supplied drive letter
532 static void WCMD_dir_trailer(WCHAR drive) {
533 ULARGE_INTEGER avail, total, freebytes;
534 DWORD status;
535 WCHAR driveName[] = L"c:\\";
537 driveName[0] = drive;
538 status = GetDiskFreeSpaceExW(driveName, &avail, &total, &freebytes);
539 WINE_TRACE("Writing trailer for '%s' gave %d(%d)\n", wine_dbgstr_w(driveName),
540 status, GetLastError());
542 if (errorlevel==0 && !bare) {
543 if (recurse) {
544 WCMD_output (L"\n Total files listed:\n%1!8d! files%2!25s! bytes\n", file_total, WCMD_filesize64 (byte_total));
545 WCMD_output (L"%1!8d! directories %2!18s! bytes free\n\n", dir_total, WCMD_filesize64 (freebytes.QuadPart));
546 } else {
547 WCMD_output (L" %1!18s! bytes free\n\n", WCMD_filesize64 (freebytes.QuadPart));
552 /*****************************************************************************
553 * WCMD_directory
555 * List a file directory.
559 void WCMD_directory (WCHAR *args)
561 WCHAR path[MAX_PATH], cwd[MAX_PATH];
562 DWORD status;
563 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
564 WCHAR *p;
565 WCHAR string[MAXSTRING];
566 int argno = 0;
567 WCHAR *argN = args;
568 WCHAR lastDrive;
569 BOOL trailerReqd = FALSE;
570 DIRECTORY_STACK *fullParms = NULL;
571 DIRECTORY_STACK *prevEntry = NULL;
572 DIRECTORY_STACK *thisEntry = NULL;
573 WCHAR drive[10];
574 WCHAR dir[MAX_PATH];
575 WCHAR fname[MAX_PATH];
576 WCHAR ext[MAX_PATH];
578 errorlevel = 0;
580 /* Prefill quals with (uppercased) DIRCMD env var */
581 if (GetEnvironmentVariableW(L"DIRCMD", string, ARRAY_SIZE(string))) {
582 p = string;
583 while ( (*p = toupper(*p)) ) ++p;
584 lstrcatW(string,quals);
585 lstrcpyW(quals, string);
588 byte_total = 0;
589 file_total = dir_total = 0;
591 /* Initialize all flags to their defaults as if no DIRCMD or quals */
592 paged_mode = FALSE;
593 recurse = FALSE;
594 wide = FALSE;
595 bare = FALSE;
596 lower = FALSE;
597 shortname = FALSE;
598 usernames = FALSE;
599 orderByCol = FALSE;
600 separator = TRUE;
601 dirTime = Written;
602 dirOrder = Name;
603 orderReverse = FALSE;
604 orderGroupDirs = FALSE;
605 orderGroupDirsReverse = FALSE;
606 showattrs = 0;
607 attrsbits = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
609 /* Handle args - Loop through so right most is the effective one */
610 /* Note: /- appears to be a negate rather than an off, eg. dir
611 /-W is wide, or dir /w /-w /-w is also wide */
612 p = quals;
613 while (*p && (*p=='/' || *p==' ')) {
614 BOOL negate = FALSE;
615 if (*p++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
617 if (*p=='-') {
618 negate = TRUE;
619 p++;
622 WINE_TRACE("Processing arg '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
623 switch (*p) {
624 case 'P': if (negate) paged_mode = !paged_mode;
625 else paged_mode = TRUE;
626 break;
627 case 'S': if (negate) recurse = !recurse;
628 else recurse = TRUE;
629 break;
630 case 'W': if (negate) wide = !wide;
631 else wide = TRUE;
632 break;
633 case 'B': if (negate) bare = !bare;
634 else bare = TRUE;
635 break;
636 case 'L': if (negate) lower = !lower;
637 else lower = TRUE;
638 break;
639 case 'X': if (negate) shortname = !shortname;
640 else shortname = TRUE;
641 break;
642 case 'Q': if (negate) usernames = !usernames;
643 else usernames = TRUE;
644 break;
645 case 'D': if (negate) orderByCol = !orderByCol;
646 else orderByCol = TRUE;
647 break;
648 case 'C': if (negate) separator = !separator;
649 else separator = TRUE;
650 break;
651 case 'T': p = p + 1;
652 if (*p==':') p++; /* Skip optional : */
654 if (*p == 'A') dirTime = Access;
655 else if (*p == 'C') dirTime = Creation;
656 else if (*p == 'W') dirTime = Written;
658 /* Support /T and /T: with no parms, default to written */
659 else if (*p == 0x00 || *p == '/') {
660 dirTime = Written;
661 p = p - 1; /* So when step on, move to '/' */
662 } else {
663 SetLastError(ERROR_INVALID_PARAMETER);
664 WCMD_print_error();
665 errorlevel = 1;
666 return;
668 break;
669 case 'O': p = p + 1;
670 if (*p==':') p++; /* Skip optional : */
671 while (*p && *p != '/') {
672 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
673 switch (*p) {
674 case 'N': dirOrder = Name; break;
675 case 'E': dirOrder = Extension; break;
676 case 'S': dirOrder = Size; break;
677 case 'D': dirOrder = Date; break;
678 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
679 else orderReverse = TRUE;
680 break;
681 case 'G': orderGroupDirs = TRUE; break;
682 default:
683 SetLastError(ERROR_INVALID_PARAMETER);
684 WCMD_print_error();
685 errorlevel = 1;
686 return;
688 p++;
690 p = p - 1; /* So when step on, move to '/' */
691 break;
692 case 'A': p = p + 1;
693 showattrs = 0;
694 attrsbits = 0;
695 if (*p==':') p++; /* Skip optional : */
696 while (*p && *p != '/') {
697 BOOL anegate = FALSE;
698 ULONG mask;
700 /* Note /A: - options are 'offs' not toggles */
701 if (*p=='-') {
702 anegate = TRUE;
703 p++;
706 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
707 switch (*p) {
708 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
709 case 'H': mask = FILE_ATTRIBUTE_HIDDEN; break;
710 case 'S': mask = FILE_ATTRIBUTE_SYSTEM; break;
711 case 'R': mask = FILE_ATTRIBUTE_READONLY; break;
712 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE; break;
713 default:
714 SetLastError(ERROR_INVALID_PARAMETER);
715 WCMD_print_error();
716 errorlevel = 1;
717 return;
720 /* Keep running list of bits we care about */
721 attrsbits |= mask;
723 /* Mask shows what MUST be in the bits we care about */
724 if (anegate) showattrs = showattrs & ~mask;
725 else showattrs |= mask;
727 p++;
729 p = p - 1; /* So when step on, move to '/' */
730 WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
731 break;
732 default:
733 SetLastError(ERROR_INVALID_PARAMETER);
734 WCMD_print_error();
735 errorlevel = 1;
736 return;
738 p = p + 1;
741 /* Handle conflicting args and initialization */
742 if (bare || shortname) wide = FALSE;
743 if (bare) shortname = FALSE;
744 if (wide) usernames = FALSE;
745 if (orderByCol) wide = TRUE;
747 if (wide) {
748 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
749 max_width = consoleInfo.dwSize.X;
750 else
751 max_width = 80;
753 if (paged_mode) {
754 WCMD_enter_paged_mode(NULL);
757 argno = 0;
758 argN = args;
759 GetCurrentDirectoryW(MAX_PATH, cwd);
760 lstrcatW(cwd, L"\\");
762 /* Loop through all args, calculating full effective directory */
763 fullParms = NULL;
764 prevEntry = NULL;
765 while (argN) {
766 WCHAR fullname[MAXSTRING];
767 WCHAR *thisArg = WCMD_parameter(args, argno++, &argN, FALSE, FALSE);
768 if (argN && argN[0] != '/') {
770 WINE_TRACE("Found parm '%s'\n", wine_dbgstr_w(thisArg));
771 if (thisArg[1] == ':' && thisArg[2] == '\\') {
772 lstrcpyW(fullname, thisArg);
773 } else if (thisArg[1] == ':' && thisArg[2] != '\\') {
774 WCHAR envvar[4];
775 wsprintfW(envvar, L"=%c:", thisArg[0]);
776 if (!GetEnvironmentVariableW(envvar, fullname, MAX_PATH)) {
777 wsprintfW(fullname, L"%c:", thisArg[0]);
779 lstrcatW(fullname, L"\\");
780 lstrcatW(fullname, &thisArg[2]);
781 } else if (thisArg[0] == '\\') {
782 memcpy(fullname, cwd, 2 * sizeof(WCHAR));
783 lstrcpyW(fullname+2, thisArg);
784 } else {
785 lstrcpyW(fullname, cwd);
786 lstrcatW(fullname, thisArg);
788 WINE_TRACE("Using location '%s'\n", wine_dbgstr_w(fullname));
790 if (!WCMD_get_fullpath(fullname, ARRAY_SIZE(path), path, NULL)) continue;
793 * If the path supplied does not include a wildcard, and the endpoint of the
794 * path references a directory, we need to list the *contents* of that
795 * directory not the directory file itself.
797 if ((wcschr(path, '*') == NULL) && (wcschr(path, '%') == NULL)) {
798 status = GetFileAttributesW(path);
799 if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
800 if (!ends_with_backslash(path)) lstrcatW(path, L"\\");
801 lstrcatW(path, L"*");
803 } else {
804 /* Special case wildcard search with no extension (ie parameters ending in '.') as
805 GetFullPathName strips off the additional '.' */
806 if (fullname[lstrlenW(fullname)-1] == '.') lstrcatW(path, L".");
809 WINE_TRACE("Using path '%s'\n", wine_dbgstr_w(path));
810 thisEntry = heap_xalloc(sizeof(DIRECTORY_STACK));
811 if (fullParms == NULL) fullParms = thisEntry;
812 if (prevEntry != NULL) prevEntry->next = thisEntry;
813 prevEntry = thisEntry;
814 thisEntry->next = NULL;
816 /* Split into components */
817 _wsplitpath(path, drive, dir, fname, ext);
818 WINE_TRACE("Path Parts: drive: '%s' dir: '%s' name: '%s' ext:'%s'\n",
819 wine_dbgstr_w(drive), wine_dbgstr_w(dir),
820 wine_dbgstr_w(fname), wine_dbgstr_w(ext));
822 thisEntry->dirName = heap_xalloc(sizeof(WCHAR) * (lstrlenW(drive)+lstrlenW(dir)+1));
823 lstrcpyW(thisEntry->dirName, drive);
824 lstrcatW(thisEntry->dirName, dir);
826 thisEntry->fileName = heap_xalloc(sizeof(WCHAR) * (lstrlenW(fname)+lstrlenW(ext)+1));
827 lstrcpyW(thisEntry->fileName, fname);
828 lstrcatW(thisEntry->fileName, ext);
833 /* If just 'dir' entered, a '*' parameter is assumed */
834 if (fullParms == NULL) {
835 WINE_TRACE("Inserting default '*'\n");
836 fullParms = heap_xalloc(sizeof(DIRECTORY_STACK));
837 fullParms->next = NULL;
838 fullParms->dirName = heap_strdupW(cwd);
839 fullParms->fileName = heap_strdupW(L"*");
842 lastDrive = '?';
843 prevEntry = NULL;
844 thisEntry = fullParms;
845 trailerReqd = FALSE;
847 while (thisEntry != NULL) {
849 /* Output disk free (trailer) and volume information (header) if the drive
850 letter changes */
851 if (lastDrive != toupper(thisEntry->dirName[0])) {
853 /* Trailer Information */
854 if (lastDrive != '?') {
855 trailerReqd = FALSE;
856 WCMD_dir_trailer(prevEntry->dirName[0]);
859 lastDrive = toupper(thisEntry->dirName[0]);
861 if (!bare) {
862 WCHAR drive[3];
864 WINE_TRACE("Writing volume for '%c:'\n", thisEntry->dirName[0]);
865 memcpy(drive, thisEntry->dirName, 2 * sizeof(WCHAR));
866 drive[2] = 0x00;
867 status = WCMD_volume (0, drive);
868 trailerReqd = TRUE;
869 if (!status) {
870 errorlevel = 1;
871 goto exit;
874 } else {
875 if (!bare) WCMD_output_asis (L"\n\n");
878 /* Clear any errors from previous invocations, and process it */
879 errorlevel = 0;
880 prevEntry = thisEntry;
881 thisEntry = WCMD_list_directory (thisEntry, 0);
884 /* Trailer Information */
885 if (trailerReqd) {
886 WCMD_dir_trailer(prevEntry->dirName[0]);
889 exit:
890 if (paged_mode) WCMD_leave_paged_mode();
892 /* Free storage allocated for parms */
893 while (fullParms != NULL) {
894 prevEntry = fullParms;
895 fullParms = prevEntry->next;
896 heap_free(prevEntry->dirName);
897 heap_free(prevEntry->fileName);
898 heap_free(prevEntry);