path.c 35.1 KB
Newer Older
1 2 3
/*
 * Ntdll path functions
 *
4
 * Copyright 2002, 2003, 2004 Alexandre Julliard
5
 * Copyright 2003 Eric Pouech
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
20 21 22
 */

#include "config.h"
23
#include "wine/port.h"
24

25
#include <stdarg.h>
26
#include <sys/types.h>
27
#include <errno.h>
28 29 30
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
31 32 33
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
34

35 36
#include "ntstatus.h"
#define WIN32_NO_STATUS
37
#include "windef.h"
38
#include "winioctl.h"
39
#include "wine/unicode.h"
40
#include "wine/debug.h"
41
#include "wine/library.h"
42
#include "thread.h"
43
#include "ntdll_misc.h"
44 45

WINE_DEFAULT_DEBUG_CHANNEL(file);
46

47 48 49 50
static const WCHAR DeviceRootW[] = {'\\','\\','.','\\',0};
static const WCHAR NTDosPrefixW[] = {'\\','?','?','\\',0};
static const WCHAR UncPfxW[] = {'U','N','C','\\',0};

51 52
#define IS_SEPARATOR(ch)  ((ch) == '\\' || (ch) == '/')

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
#define MAX_DOS_DRIVES 26

struct drive_info
{
    dev_t dev;
    ino_t ino;
};

/***********************************************************************
 *           get_drives_info
 *
 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
 */
static inline int get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
{
    const char *config_dir = wine_get_config_dir();
    char *buffer, *p;
    struct stat st;
    int i, ret;

    buffer = RtlAllocateHeap( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/dosdevices/a:") );
    if (!buffer) return 0;
    strcpy( buffer, config_dir );
    strcat( buffer, "/dosdevices/a:" );
    p = buffer + strlen(buffer) - 2;

    for (i = ret = 0; i < MAX_DOS_DRIVES; i++)
    {
        *p = 'a' + i;
        if (!stat( buffer, &st ))
        {
            info[i].dev = st.st_dev;
            info[i].ino = st.st_ino;
            ret++;
        }
        else
        {
            info[i].dev = 0;
            info[i].ino = 0;
        }
    }
    RtlFreeHeap( GetProcessHeap(), 0, buffer );
    return ret;
}


/***********************************************************************
100
 *           remove_last_componentA
101
 *
102
 * Remove the last component of the path. Helper for find_drive_rootA.
103
 */
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
static inline unsigned int remove_last_componentA( const char *path, unsigned int len )
{
    int level = 0;

    while (level < 1)
    {
        /* find start of the last path component */
        unsigned int prev = len;
        if (prev <= 1) break;  /* reached root */
        while (prev > 1 && path[prev - 1] != '/') prev--;
        /* does removing it take us up a level? */
        if (len - prev != 1 || path[prev] != '.')  /* not '.' */
        {
            if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.')  /* is it '..'? */
                level--;
            else
                level++;
        }
        /* strip off trailing slashes */
        while (prev > 1 && path[prev - 1] == '/') prev--;
        len = prev;
    }
    return len;
}


/***********************************************************************
 *           find_drive_rootA
 *
 * Find a drive for which the root matches the beginning of the given path.
 * This can be used to translate a Unix path into a drive + DOS path.
 * Return value is the drive, or -1 on error. On success, ppath is modified
 * to point to the beginning of the DOS path.
 */
static NTSTATUS find_drive_rootA( LPCSTR *ppath, unsigned int len, int *drive_ret )
{
    /* Starting with the full path, check if the device and inode match any of
     * the wine 'drives'. If not then remove the last path component and try
     * again. If the last component was a '..' then skip a normal component
     * since it's a directory that's ascended back out of.
     */
    int drive;
    char *buffer;
    const char *path = *ppath;
    struct stat st;
    struct drive_info info[MAX_DOS_DRIVES];

    /* get device and inode of all drives */
    if (!get_drives_info( info )) return STATUS_OBJECT_PATH_NOT_FOUND;

    /* strip off trailing slashes */
    while (len > 1 && path[len - 1] == '/') len--;

    /* make a copy of the path */
    if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, len + 1 ))) return STATUS_NO_MEMORY;
    memcpy( buffer, path, len );
    buffer[len] = 0;

    for (;;)
    {
        if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
        {
            /* Find the drive */
            for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
            {
                if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
                {
                    if (len == 1) len = 0;  /* preserve root slash in returned path */
                    TRACE( "%s -> drive %c:, root=%s, name=%s\n",
                           debugstr_a(path), 'A' + drive, debugstr_a(buffer), debugstr_a(path + len));
                    *ppath += len;
                    *drive_ret = drive;
                    RtlFreeHeap( GetProcessHeap(), 0, buffer );
                    return STATUS_SUCCESS;
                }
            }
        }
        if (len <= 1) break;  /* reached root */
        len = remove_last_componentA( buffer, len );
        buffer[len] = 0;
    }
    RtlFreeHeap( GetProcessHeap(), 0, buffer );
    return STATUS_OBJECT_PATH_NOT_FOUND;
}


/***********************************************************************
 *           remove_last_componentW
 *
 * Remove the last component of the path. Helper for find_drive_rootW.
 */
static inline int remove_last_componentW( const WCHAR *path, int len )
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
{
    int level = 0;

    while (level < 1)
    {
        /* find start of the last path component */
        int prev = len;
        if (prev <= 1) break;  /* reached root */
        while (prev > 1 && !IS_SEPARATOR(path[prev - 1])) prev--;
        /* does removing it take us up a level? */
        if (len - prev != 1 || path[prev] != '.')  /* not '.' */
        {
            if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.')  /* is it '..'? */
                level--;
            else
                level++;
        }
        /* strip off trailing slashes */
        while (prev > 1 && IS_SEPARATOR(path[prev - 1])) prev--;
        len = prev;
    }
    return len;
}


/***********************************************************************
222
 *           find_drive_rootW
223 224 225 226 227 228
 *
 * Find a drive for which the root matches the beginning of the given path.
 * This can be used to translate a Unix path into a drive + DOS path.
 * Return value is the drive, or -1 on error. On success, ppath is modified
 * to point to the beginning of the DOS path.
 */
229
static int find_drive_rootW( LPCWSTR *ppath )
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
{
    /* Starting with the full path, check if the device and inode match any of
     * the wine 'drives'. If not then remove the last path component and try
     * again. If the last component was a '..' then skip a normal component
     * since it's a directory that's ascended back out of.
     */
    int drive, lenA, lenW;
    char *buffer, *p;
    const WCHAR *path = *ppath;
    struct stat st;
    struct drive_info info[MAX_DOS_DRIVES];

    /* get device and inode of all drives */
    if (!get_drives_info( info )) return -1;

    /* strip off trailing slashes */
    lenW = strlenW(path);
    while (lenW > 1 && IS_SEPARATOR(path[lenW - 1])) lenW--;

    /* convert path to Unix encoding */
    lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
    if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, lenA + 1 ))) return -1;
    lenA = ntdll_wcstoumbs( 0, path, lenW, buffer, lenA, NULL, NULL );
    buffer[lenA] = 0;
    for (p = buffer; *p; p++) if (*p == '\\') *p = '/';

    for (;;)
    {
        if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
        {
            /* Find the drive */
            for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
            {
                if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
                {
                    if (lenW == 1) lenW = 0;  /* preserve root slash in returned path */
                    TRACE( "%s -> drive %c:, root=%s, name=%s\n",
                           debugstr_w(path), 'A' + drive, debugstr_a(buffer), debugstr_w(path + lenW));
                    *ppath += lenW;
                    RtlFreeHeap( GetProcessHeap(), 0, buffer );
                    return drive;
                }
            }
        }
        if (lenW <= 1) break;  /* reached root */
275
        lenW = remove_last_componentW( path, lenW );
276 277 278 279 280 281 282 283 284 285

        /* we only need the new length, buffer already contains the converted string */
        lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
        buffer[lenA] = 0;
    }
    RtlFreeHeap( GetProcessHeap(), 0, buffer );
    return -1;
}


286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
/***********************************************************************
 *             RtlDetermineDosPathNameType_U   (NTDLL.@)
 */
DOS_PATHNAME_TYPE WINAPI RtlDetermineDosPathNameType_U( PCWSTR path )
{
    if (IS_SEPARATOR(path[0]))
    {
        if (!IS_SEPARATOR(path[1])) return ABSOLUTE_PATH;       /* "/foo" */
        if (path[2] != '.') return UNC_PATH;                    /* "//foo" */
        if (IS_SEPARATOR(path[3])) return DEVICE_PATH;          /* "//./foo" */
        if (path[3]) return UNC_PATH;                           /* "//.foo" */
        return UNC_DOT_PATH;                                    /* "//." */
    }
    else
    {
        if (!path[0] || path[1] != ':') return RELATIVE_PATH;   /* "foo" */
        if (IS_SEPARATOR(path[2])) return ABSOLUTE_DRIVE_PATH;  /* "c:/foo" */
        return RELATIVE_DRIVE_PATH;                             /* "c:foo" */
    }
}

/***********************************************************************
 *             RtlIsDosDeviceName_U   (NTDLL.@)
 *
 * Check if the given DOS path contains a DOS device name.
 *
 * Returns the length of the device name in the low word and its
 * position in the high word (both in bytes, not WCHARs), or 0 if no
 * device name is found.
 */
ULONG WINAPI RtlIsDosDeviceName_U( PCWSTR dos_name )
{
    static const WCHAR consoleW[] = {'\\','\\','.','\\','C','O','N',0};
    static const WCHAR auxW[3] = {'A','U','X'};
    static const WCHAR comW[3] = {'C','O','M'};
    static const WCHAR conW[3] = {'C','O','N'};
    static const WCHAR lptW[3] = {'L','P','T'};
    static const WCHAR nulW[3] = {'N','U','L'};
    static const WCHAR prnW[3] = {'P','R','N'};

    const WCHAR *start, *end, *p;

    switch(RtlDetermineDosPathNameType_U( dos_name ))
    {
    case INVALID_PATH:
    case UNC_PATH:
        return 0;
    case DEVICE_PATH:
        if (!strcmpiW( dos_name, consoleW ))
            return MAKELONG( sizeof(conW), 4 * sizeof(WCHAR) );  /* 4 is length of \\.\ prefix */
        return 0;
    default:
        break;
    }

    end = dos_name + strlenW(dos_name) - 1;
342
    while (end >= dos_name && *end == ':') end--;  /* remove all trailing ':' */
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

    /* find start of file name */
    for (start = end; start >= dos_name; start--)
    {
        if (IS_SEPARATOR(start[0])) break;
        /* check for ':' but ignore if before extension (for things like NUL:.txt) */
        if (start[0] == ':' && start[1] != '.') break;
    }
    start++;

    /* remove extension */
    if ((p = strchrW( start, '.' )))
    {
        end = p - 1;
        if (end >= dos_name && *end == ':') end--;  /* remove trailing ':' before extension */
    }
359 360
    /* remove trailing spaces */
    while (end >= dos_name && *end == ' ') end--;
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

    /* now we have a potential device name between start and end, check it */
    switch(end - start + 1)
    {
    case 3:
        if (strncmpiW( start, auxW, 3 ) &&
            strncmpiW( start, conW, 3 ) &&
            strncmpiW( start, nulW, 3 ) &&
            strncmpiW( start, prnW, 3 )) break;
        return MAKELONG( 3 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
    case 4:
        if (strncmpiW( start, comW, 3 ) && strncmpiW( start, lptW, 3 )) break;
        if (*end <= '0' || *end > '9') break;
        return MAKELONG( 4 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
    default:  /* can't match anything */
        break;
    }
    return 0;
}
380 381


382 383 384 385 386 387 388 389 390 391 392 393
/**************************************************************************
 *                 RtlDosPathNameToNtPathName_U		[NTDLL.@]
 *
 * dos_path: a DOS path name (fully qualified or not)
 * ntpath:   pointer to a UNICODE_STRING to hold the converted
 *           path name
 * file_part:will point (in ntpath) to the file part in the path
 * cd:       directory reference (optional)
 *
 * FIXME:
 *      + fill the cd structure
 */
394
BOOLEAN  WINAPI RtlDosPathNameToNtPathName_U(PCWSTR dos_path,
395 396 397 398 399
                                             PUNICODE_STRING ntpath,
                                             PWSTR* file_part,
                                             CURDIR* cd)
{
    static const WCHAR LongFileNamePfxW[4] = {'\\','\\','?','\\'};
400
    ULONG sz, offset;
401 402 403 404 405 406 407 408 409 410 411 412 413 414
    WCHAR local[MAX_PATH];
    LPWSTR ptr;

    TRACE("(%s,%p,%p,%p)\n",
          debugstr_w(dos_path), ntpath, file_part, cd);

    if (cd)
    {
        FIXME("Unsupported parameter\n");
        memset(cd, 0, sizeof(*cd));
    }

    if (!dos_path || !*dos_path) return FALSE;

415
    if (!strncmpW(dos_path, LongFileNamePfxW, 4))
416
    {
417 418 419 420 421 422
        ntpath->Length = strlenW(dos_path) * sizeof(WCHAR);
        ntpath->MaximumLength = ntpath->Length + sizeof(WCHAR);
        ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
        if (!ntpath->Buffer) return FALSE;
        memcpy( ntpath->Buffer, dos_path, ntpath->MaximumLength );
        ntpath->Buffer[1] = '?';  /* change \\?\ to \??\ */
423 424 425 426 427
        if (file_part)
        {
            if ((ptr = strrchrW( ntpath->Buffer, '\\' )) && ptr[1]) *file_part = ptr + 1;
            else *file_part = NULL;
        }
428
        return TRUE;
429
    }
430 431 432

    ptr = local;
    sz = RtlGetFullPathName_U(dos_path, sizeof(local), ptr, file_part);
433
    if (sz == 0) return FALSE;
434
    if (sz > sizeof(local))
435
    {
Alexandre Julliard's avatar
Alexandre Julliard committed
436
        if (!(ptr = RtlAllocateHeap(GetProcessHeap(), 0, sz))) return FALSE;
437 438 439 440
        sz = RtlGetFullPathName_U(dos_path, sz, ptr, file_part);
    }

    ntpath->MaximumLength = sz + (4 /* unc\ */ + 4 /* \??\ */) * sizeof(WCHAR);
441
    ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
442 443
    if (!ntpath->Buffer)
    {
444
        if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
445 446 447 448 449 450 451
        return FALSE;
    }

    strcpyW(ntpath->Buffer, NTDosPrefixW);
    switch (RtlDetermineDosPathNameType_U(ptr))
    {
    case UNC_PATH: /* \\foo */
452 453
        offset = 2;
        strcatW(ntpath->Buffer, UncPfxW);
454 455 456 457
        break;
    case DEVICE_PATH: /* \\.\foo */
        offset = 4;
        break;
458
    default:
Alexandre Julliard's avatar
Alexandre Julliard committed
459 460
        offset = 0;
        break;
461 462 463 464 465 466
    }

    strcatW(ntpath->Buffer, ptr + offset);
    ntpath->Length = strlenW(ntpath->Buffer) * sizeof(WCHAR);

    if (file_part && *file_part)
467
        *file_part = ntpath->Buffer + ntpath->Length / sizeof(WCHAR) - strlenW(*file_part);
468 469 470

    /* FIXME: cd filling */

471
    if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
472 473 474
    return TRUE;
}

Eric Pouech's avatar
Eric Pouech committed
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
/******************************************************************
 *		RtlDosSearchPath_U
 *
 * Searchs a file of name 'name' into a ';' separated list of paths
 * (stored in paths)
 * Doesn't seem to search elsewhere than the paths list
 * Stores the result in buffer (file_part will point to the position
 * of the file name in the buffer)
 * FIXME:
 * - how long shall the paths be ??? (MAX_PATH or larger with \\?\ constructs ???)
 */
ULONG WINAPI RtlDosSearchPath_U(LPCWSTR paths, LPCWSTR search, LPCWSTR ext, 
                                ULONG buffer_size, LPWSTR buffer, 
                                LPWSTR* file_part)
{
    DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U(search);
    ULONG len = 0;

    if (type == RELATIVE_PATH)
    {
        ULONG allocated = 0, needed, filelen;
496
        WCHAR *name = NULL;
Eric Pouech's avatar
Eric Pouech committed
497 498 499

        filelen = 1 /* for \ */ + strlenW(search) + 1 /* \0 */;

500 501
        /* Windows only checks for '.' without worrying about path components */
        if (strchrW( search, '.' )) ext = NULL;
Eric Pouech's avatar
Eric Pouech committed
502 503 504 505 506 507 508 509 510
        if (ext != NULL) filelen += strlenW(ext);

        while (*paths)
        {
            LPCWSTR ptr;

            for (needed = 0, ptr = paths; *ptr != 0 && *ptr++ != ';'; needed++);
            if (needed + filelen > allocated)
            {
511 512 513 514 515 516 517 518 519
                if (!name) name = RtlAllocateHeap(GetProcessHeap(), 0,
                                                  (needed + filelen) * sizeof(WCHAR));
                else
                {
                    WCHAR *newname = RtlReAllocateHeap(GetProcessHeap(), 0, name,
                                                       (needed + filelen) * sizeof(WCHAR));
                    if (!newname) RtlFreeHeap(GetProcessHeap(), 0, name);
                    name = newname;
                }
Eric Pouech's avatar
Eric Pouech committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
                if (!name) return 0;
                allocated = needed + filelen;
            }
            memmove(name, paths, needed * sizeof(WCHAR));
            /* append '\\' if none is present */
            if (needed > 0 && name[needed - 1] != '\\') name[needed++] = '\\';
            strcpyW(&name[needed], search);
            if (ext) strcatW(&name[needed], ext);
            if (RtlDoesFileExists_U(name))
            {
                len = RtlGetFullPathName_U(name, buffer_size, buffer, file_part);
                break;
            }
            paths = ptr;
        }
535
        RtlFreeHeap(GetProcessHeap(), 0, name);
Eric Pouech's avatar
Eric Pouech committed
536 537 538 539 540 541 542 543 544
    }
    else if (RtlDoesFileExists_U(search))
    {
        len = RtlGetFullPathName_U(search, buffer_size, buffer, file_part);
    }

    return len;
}

545 546 547 548 549 550 551

/******************************************************************
 *		collapse_path
 *
 * Helper for RtlGetFullPathName_U.
 * Get rid of . and .. components in the path.
 */
552
static inline void collapse_path( WCHAR *path, UINT mark )
553 554 555
{
    WCHAR *p, *next;

556 557 558 559 560 561 562
    /* convert every / into a \ */
    for (p = path; *p; p++) if (*p == '/') *p = '\\';

    /* collapse duplicate backslashes */
    next = path + max( 1, mark );
    for (p = next; *p; p++) if (*p != '\\' || next[-1] != '\\') *next++ = *p;
    *next = 0;
563

564
    p = path + mark;
565 566 567 568 569 570 571 572 573 574 575
    while (*p)
    {
        if (*p == '.')
        {
            switch(p[1])
            {
            case '\\': /* .\ component */
                next = p + 2;
                memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
                continue;
            case 0:  /* final . */
576
                if (p > path + mark) p--;
577 578 579 580 581 582
                *p = 0;
                continue;
            case '.':
                if (p[2] == '\\')  /* ..\ component */
                {
                    next = p + 3;
583 584 585 586 587
                    if (p > path + mark)
                    {
                        p--;
                        while (p > path + mark && p[-1] != '\\') p--;
                    }
588 589 590 591 592
                    memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
                    continue;
                }
                else if (!p[2])  /* final .. */
                {
593 594 595 596 597 598
                    if (p > path + mark)
                    {
                        p--;
                        while (p > path + mark && p[-1] != '\\') p--;
                        if (p > path + mark) p--;
                    }
599 600 601 602 603 604 605 606
                    *p = 0;
                    continue;
                }
                break;
            }
        }
        /* skip to the next component */
        while (*p && *p != '\\') p++;
607 608 609 610 611 612
        if (*p == '\\')
        {
            /* remove last dot in previous dir name */
            if (p > path + mark && p[-1] == '.') memmove( p-1, p, (strlenW(p) + 1) * sizeof(WCHAR) );
            else p++;
        }
613
    }
614 615 616 617

    /* remove trailing spaces and dots (yes, Windows really does that, don't ask) */
    while (p > path + mark && (p[-1] == ' ' || p[-1] == '.')) p--;
    *p = 0;
618 619
}

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636

/******************************************************************
 *		skip_unc_prefix
 *
 * Skip the \\share\dir\ part of a file name. Helper for RtlGetFullPathName_U.
 */
static const WCHAR *skip_unc_prefix( const WCHAR *ptr )
{
    ptr += 2;
    while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* share name */
    while (IS_SEPARATOR(*ptr)) ptr++;
    while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* dir name */
    while (IS_SEPARATOR(*ptr)) ptr++;
    return ptr;
}


637 638 639 640
/******************************************************************
 *		get_full_path_helper
 *
 * Helper for RtlGetFullPathName_U
641
 * Note: name and buffer are allowed to point to the same memory spot
642 643 644
 */
static ULONG get_full_path_helper(LPCWSTR name, LPWSTR buffer, ULONG size)
{
645
    ULONG                       reqsize = 0, mark = 0, dep = 0, deplen;
646
    DOS_PATHNAME_TYPE           type;
647
    LPWSTR                      ins_str = NULL;
648
    LPCWSTR                     ptr;
649 650
    const UNICODE_STRING*       cd;
    WCHAR                       tmp[4];
651

652 653 654
    /* return error if name only consists of spaces */
    for (ptr = name; *ptr; ptr++) if (*ptr != ' ') break;
    if (!*ptr) return 0;
655

656
    RtlAcquirePebLock();
657

658
    if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
659
        cd = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
660
    else
661
        cd = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
662 663 664 665

    switch (type = RtlDetermineDosPathNameType_U(name))
    {
    case UNC_PATH:              /* \\foo   */
666
        ptr = skip_unc_prefix( name );
667 668 669
        mark = (ptr - name);
        break;

670
    case DEVICE_PATH:           /* \\.\foo */
671
        mark = 4;
672 673 674
        break;

    case ABSOLUTE_DRIVE_PATH:   /* c:\foo  */
675 676 677 678
        reqsize = sizeof(WCHAR);
        tmp[0] = toupperW(name[0]);
        ins_str = tmp;
        dep = 1;
679
        mark = 3;
680 681 682
        break;

    case RELATIVE_DRIVE_PATH:   /* c:foo   */
683
        dep = 2;
684 685 686 687
        if (toupperW(name[0]) != toupperW(cd->Buffer[0]) || cd->Buffer[1] != ':')
        {
            UNICODE_STRING      var, val;

688 689 690 691 692 693 694
            tmp[0] = '=';
            tmp[1] = name[0];
            tmp[2] = ':';
            tmp[3] = '\0';
            var.Length = 3 * sizeof(WCHAR);
            var.MaximumLength = 4 * sizeof(WCHAR);
            var.Buffer = tmp;
695 696
            val.Length = 0;
            val.MaximumLength = size;
697
            val.Buffer = RtlAllocateHeap(GetProcessHeap(), 0, size);
698 699 700 701 702 703 704 705 706 707 708

            switch (RtlQueryEnvironmentVariable_U(NULL, &var, &val))
            {
            case STATUS_SUCCESS:
                /* FIXME: Win2k seems to check that the environment variable actually points 
                 * to an existing directory. If not, root of the drive is used
                 * (this seems also to be the only spot in RtlGetFullPathName that the 
                 * existence of a part of a path is checked)
                 */
                /* fall thru */
            case STATUS_BUFFER_TOO_SMALL:
709 710 711
                reqsize = val.Length + sizeof(WCHAR); /* append trailing '\\' */
                val.Buffer[val.Length / sizeof(WCHAR)] = '\\';
                ins_str = val.Buffer;
712 713
                break;
            case STATUS_VARIABLE_NOT_FOUND:
714 715 716 717 718
                reqsize = 3 * sizeof(WCHAR);
                tmp[0] = name[0];
                tmp[1] = ':';
                tmp[2] = '\\';
                ins_str = tmp;
719 720 721 722 723
                break;
            default:
                ERR("Unsupported status code\n");
                break;
            }
724
            mark = 3;
725 726 727 728 729
            break;
        }
        /* fall through */

    case RELATIVE_PATH:         /* foo     */
730 731
        reqsize = cd->Length;
        ins_str = cd->Buffer;
732 733
        if (cd->Buffer[1] != ':')
        {
734
            ptr = skip_unc_prefix( cd->Buffer );
735 736
            mark = ptr - cd->Buffer;
        }
737
        else mark = 3;
738 739 740
        break;

    case ABSOLUTE_PATH:         /* \xxx    */
741 742 743
        if (name[0] == '/')  /* may be a Unix path */
        {
            const WCHAR *ptr = name;
744
            int drive = find_drive_rootW( &ptr );
745 746 747 748 749 750 751 752 753 754 755 756
            if (drive != -1)
            {
                reqsize = 3 * sizeof(WCHAR);
                tmp[0] = 'A' + drive;
                tmp[1] = ':';
                tmp[2] = '\\';
                ins_str = tmp;
                mark = 3;
                dep = ptr - name;
                break;
            }
        }
757 758
        if (cd->Buffer[1] == ':')
        {
759 760 761 762
            reqsize = 2 * sizeof(WCHAR);
            tmp[0] = cd->Buffer[0];
            tmp[1] = ':';
            ins_str = tmp;
763
            mark = 3;
764 765 766
        }
        else
        {
767
            ptr = skip_unc_prefix( cd->Buffer );
768 769 770
            reqsize = (ptr - cd->Buffer) * sizeof(WCHAR);
            mark = reqsize / sizeof(WCHAR);
            ins_str = cd->Buffer;
771 772 773 774
        }
        break;

    case UNC_DOT_PATH:         /* \\.     */
775 776 777 778 779 780 781
        reqsize = 4 * sizeof(WCHAR);
        dep = 3;
        tmp[0] = '\\';
        tmp[1] = '\\';
        tmp[2] = '.';
        tmp[3] = '\\';
        ins_str = tmp;
782
        mark = 4;
783 784 785 786 787 788
        break;

    case INVALID_PATH:
        goto done;
    }

789
    /* enough space ? */
790
    deplen = strlenW(name + dep) * sizeof(WCHAR);
791 792 793 794 795 796
    if (reqsize + deplen + sizeof(WCHAR) > size)
    {
        /* not enough space, return need size (including terminating '\0') */
        reqsize += deplen + sizeof(WCHAR);
        goto done;
    }
797

798
    memmove(buffer + reqsize / sizeof(WCHAR), name + dep, deplen + sizeof(WCHAR));
799 800
    if (reqsize) memcpy(buffer, ins_str, reqsize);
    reqsize += deplen;
801

802
    if (ins_str != tmp && ins_str != cd->Buffer)
803
        RtlFreeHeap(GetProcessHeap(), 0, ins_str);
804

805
    collapse_path( buffer, mark );
806
    reqsize = strlenW(buffer) * sizeof(WCHAR);
807 808 809 810 811 812 813 814 815 816 817

done:
    RtlReleasePebLock();
    return reqsize;
}

/******************************************************************
 *		RtlGetFullPathName_U  (NTDLL.@)
 *
 * Returns the number of bytes written to buffer (not including the
 * terminating NULL) if the function succeeds, or the required number of bytes
818
 * (including the terminating NULL) if the buffer is too small.
819 820 821 822 823 824 825 826
 *
 * file_part will point to the filename part inside buffer (except if we use
 * DOS device name, in which case file_in_buf is NULL)
 *
 */
DWORD WINAPI RtlGetFullPathName_U(const WCHAR* name, ULONG size, WCHAR* buffer,
                                  WCHAR** file_part)
{
827
    WCHAR*      ptr;
828 829 830
    DWORD       dosdev;
    DWORD       reqsize;

831
    TRACE("(%s %u %p %p)\n", debugstr_w(name), size, buffer, file_part);
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

    if (!name || !*name) return 0;

    if (file_part) *file_part = NULL;

    /* check for DOS device name */
    dosdev = RtlIsDosDeviceName_U(name);
    if (dosdev)
    {
        DWORD   offset = HIWORD(dosdev) / sizeof(WCHAR); /* get it in WCHARs, not bytes */
        DWORD   sz = LOWORD(dosdev); /* in bytes */

        if (8 + sz + 2 > size) return sz + 10;
        strcpyW(buffer, DeviceRootW);
        memmove(buffer + 4, name + offset, sz);
        buffer[4 + sz / sizeof(WCHAR)] = '\0';
        /* file_part isn't set in this case */
        return sz + 8;
    }

    reqsize = get_full_path_helper(name, buffer, size);
853
    if (!reqsize) return 0;
854 855
    if (reqsize > size)
    {
856
        LPWSTR tmp = RtlAllocateHeap(GetProcessHeap(), 0, reqsize);
857 858 859
        reqsize = get_full_path_helper(name, tmp, reqsize);
        if (reqsize > size)  /* it may have worked the second time */
        {
860
            RtlFreeHeap(GetProcessHeap(), 0, tmp);
861 862 863
            return reqsize + sizeof(WCHAR);
        }
        memcpy( buffer, tmp, reqsize + sizeof(WCHAR) );
864
        RtlFreeHeap(GetProcessHeap(), 0, tmp);
865
    }
866 867 868 869

    /* find file part */
    if (file_part && (ptr = strrchrW(buffer, '\\')) != NULL && ptr >= buffer + 2 && *++ptr)
        *file_part = ptr;
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
    return reqsize;
}

/*************************************************************************
 * RtlGetLongestNtPathLength    [NTDLL.@]
 *
 * Get the longest allowed path length
 *
 * PARAMS
 *  None.
 *
 * RETURNS
 *  The longest allowed path length (277 characters under Win2k).
 */
DWORD WINAPI RtlGetLongestNtPathLength(void)
{
886
    return MAX_NT_PATH_LENGTH;
887 888
}

889 890 891 892 893 894 895 896 897 898
/******************************************************************
 *             RtlIsNameLegalDOS8Dot3   (NTDLL.@)
 *
 * Returns TRUE iff unicode is a valid DOS (8+3) name.
 * If the name is valid, oem gets filled with the corresponding OEM string
 * spaces is set to TRUE if unicode contains spaces
 */
BOOLEAN WINAPI RtlIsNameLegalDOS8Dot3( const UNICODE_STRING *unicode,
                                       OEM_STRING *oem, BOOLEAN *spaces )
{
899
    static const char illegal[] = "*?<>|\"+=,;[]:/\\\345";
900
    int dot = -1;
901
    int i;
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
    char buffer[12];
    OEM_STRING oem_str;
    BOOLEAN got_space = FALSE;

    if (!oem)
    {
        oem_str.Length = sizeof(buffer);
        oem_str.MaximumLength = sizeof(buffer);
        oem_str.Buffer = buffer;
        oem = &oem_str;
    }
    if (RtlUpcaseUnicodeStringToCountedOemString( oem, unicode, FALSE ) != STATUS_SUCCESS)
        return FALSE;

    if (oem->Length > 12) return FALSE;

    /* a starting . is invalid, except for . and .. */
    if (oem->Buffer[0] == '.')
    {
        if (oem->Length != 1 && (oem->Length != 2 || oem->Buffer[1] != '.')) return FALSE;
        if (spaces) *spaces = FALSE;
        return TRUE;
    }

    for (i = 0; i < oem->Length; i++)
    {
        switch (oem->Buffer[i])
        {
        case ' ':
            /* leading/trailing spaces not allowed */
            if (!i || i == oem->Length-1 || oem->Buffer[i+1] == '.') return FALSE;
            got_space = TRUE;
            break;
        case '.':
            if (dot != -1) return FALSE;
            dot = i;
            break;
        default:
940
            if (strchr(illegal, oem->Buffer[i])) return FALSE;
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
            break;
        }
    }
    /* check file part is shorter than 8, extension shorter than 3
     * dot cannot be last in string
     */
    if (dot == -1)
    {
        if (oem->Length > 8) return FALSE;
    }
    else
    {
        if (dot > 8 || (oem->Length - dot > 4) || dot == oem->Length - 1) return FALSE;
    }
    if (spaces) *spaces = got_space;
    return TRUE;
}
958 959 960 961 962 963 964 965 966 967

/******************************************************************
 *		RtlGetCurrentDirectory_U (NTDLL.@)
 *
 */
NTSTATUS WINAPI RtlGetCurrentDirectory_U(ULONG buflen, LPWSTR buf)
{
    UNICODE_STRING*     us;
    ULONG               len;

968
    TRACE("(%u %p)\n", buflen, buf);
969 970 971

    RtlAcquirePebLock();

972
    if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
973
        us = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
974
    else
975
        us = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
976

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    len = us->Length / sizeof(WCHAR);
    if (us->Buffer[len - 1] == '\\' && us->Buffer[len - 2] != ':')
        len--;

    if (buflen / sizeof(WCHAR) > len)
    {
        memcpy(buf, us->Buffer, len * sizeof(WCHAR));
        buf[len] = '\0';
    }
    else
    {
        len++;
    }

    RtlReleasePebLock();

    return len * sizeof(WCHAR);
}

/******************************************************************
 *		RtlSetCurrentDirectory_U (NTDLL.@)
 *
 */
NTSTATUS WINAPI RtlSetCurrentDirectory_U(const UNICODE_STRING* dir)
{
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    FILE_FS_DEVICE_INFORMATION device_info;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING newdir;
    IO_STATUS_BLOCK io;
    CURDIR *curdir;
    HANDLE handle;
    NTSTATUS nts;
    ULONG size;
    PWSTR ptr;

    newdir.Buffer = NULL;
1013 1014 1015

    RtlAcquirePebLock();

1016 1017 1018
    if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
        curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
    else
1019
        curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
1020

1021
    if (!RtlDosPathNameToNtPathName_U( dir->Buffer, &newdir, NULL, NULL ))
1022 1023 1024 1025 1026
    {
        nts = STATUS_OBJECT_NAME_INVALID;
        goto out;
    }

1027 1028 1029 1030 1031 1032 1033
    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.Attributes = OBJ_CASE_INSENSITIVE;
    attr.ObjectName = &newdir;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;

Alexandre Julliard's avatar
Alexandre Julliard committed
1034
    nts = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1035 1036 1037 1038 1039 1040
    if (nts != STATUS_SUCCESS) goto out;

    /* don't keep the directory handle open on removable media */
    if (!NtQueryVolumeInformationFile( handle, &io, &device_info,
                                       sizeof(device_info), FileFsDeviceInformation ) &&
        (device_info.Characteristics & FILE_REMOVABLE_MEDIA))
1041
    {
1042 1043
        NtClose( handle );
        handle = 0;
1044 1045
    }

1046 1047
    if (curdir->Handle) NtClose( curdir->Handle );
    curdir->Handle = handle;
1048 1049

    /* append trailing \ if missing */
1050 1051 1052 1053 1054
    size = newdir.Length / sizeof(WCHAR);
    ptr = newdir.Buffer;
    ptr += 4;  /* skip \??\ prefix */
    size -= 4;
    if (size && ptr[size - 1] != '\\') ptr[size++] = '\\';
1055

1056 1057 1058
    memcpy( curdir->DosPath.Buffer, ptr, size * sizeof(WCHAR));
    curdir->DosPath.Buffer[size] = 0;
    curdir->DosPath.Length = size * sizeof(WCHAR);
1059

1060
    TRACE( "curdir now %s %p\n", debugstr_w(curdir->DosPath.Buffer), curdir->Handle );
1061

1062 1063
 out:
    RtlFreeUnicodeString( &newdir );
1064 1065 1066
    RtlReleasePebLock();
    return nts;
}
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135


/******************************************************************
 *           wine_unix_to_nt_file_name  (NTDLL.@) Not a Windows API
 */
NTSTATUS wine_unix_to_nt_file_name( const ANSI_STRING *name, UNICODE_STRING *nt )
{
    static const WCHAR prefixW[] = {'\\','?','?','\\','a',':','\\'};
    unsigned int lenW, lenA = name->Length;
    const char *path = name->Buffer;
    char *cwd;
    WCHAR *p;
    NTSTATUS status;
    int drive;

    if (!lenA || path[0] != '/')
    {
        char *newcwd, *end;
        size_t size;

        if ((status = DIR_get_unix_cwd( &cwd )) != STATUS_SUCCESS) return status;

        size = strlen(cwd) + lenA + 1;
        if (!(newcwd = RtlReAllocateHeap( GetProcessHeap(), 0, cwd, size )))
        {
            status = STATUS_NO_MEMORY;
            goto done;
        }
        cwd = newcwd;
        end = cwd + strlen(cwd);
        if (end > cwd && end[-1] != '/') *end++ = '/';
        memcpy( end, path, lenA );
        lenA += end - cwd;
        path = cwd;

        status = find_drive_rootA( &path, lenA, &drive );
        lenA -= (path - cwd);
    }
    else
    {
        cwd = NULL;
        status = find_drive_rootA( &path, lenA, &drive );
        lenA -= (path - name->Buffer);
    }

    if (status != STATUS_SUCCESS) goto done;
    while (lenA && path[0] == '/') { lenA--; path++; }

    lenW = ntdll_umbstowcs( 0, path, lenA, NULL, 0 );
    if (!(nt->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
                                        (lenW + 1) * sizeof(WCHAR) + sizeof(prefixW) )))
    {
        status = STATUS_NO_MEMORY;
        goto done;
    }

    memcpy( nt->Buffer, prefixW, sizeof(prefixW) );
    nt->Buffer[4] += drive;
    ntdll_umbstowcs( 0, path, lenA, nt->Buffer + sizeof(prefixW)/sizeof(WCHAR), lenW );
    lenW += sizeof(prefixW)/sizeof(WCHAR);
    nt->Buffer[lenW] = 0;
    nt->Length = lenW * sizeof(WCHAR);
    nt->MaximumLength = nt->Length + sizeof(WCHAR);
    for (p = nt->Buffer + sizeof(prefixW)/sizeof(WCHAR); *p; p++) if (*p == '/') *p = '\\';

done:
    RtlFreeHeap( GetProcessHeap(), 0, cwd );
    return status;
}