aboutsummaryrefslogtreecommitdiffstats
path: root/util/folder/dirut.cpp
blob: 57bc56003fc5a250b1bb924385caee7789b4ee53 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
100
101
102
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
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
222
223
224
225
226
227
228
229
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
275
276
277
278
279
280
281
282
283
284
285
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
#include "dirut.h"
#include "iterator.h"
#include "filelist.h"
#include "fts.h"
#include "pathsplit.h"
#include "path.h"

#include <util/generic/yexception.h>
#include <util/system/compiler.h>
#include <util/system/fs.h>
#include <util/system/maxlen.h>
#include <util/system/yassert.h>

void SlashFolderLocal(TString& folder) {
    if (!folder)
        return;
#ifdef _win32_
    size_t pos;
    while ((pos = folder.find('/')) != TString::npos)
        folder.replace(pos, 1, LOCSLASH_S);
#endif
    if (folder[folder.size() - 1] != LOCSLASH_C) 
        folder.append(LOCSLASH_S);
}

#ifndef _win32_

bool correctpath(TString& folder) {
    return resolvepath(folder, "/");
}

bool resolvepath(TString& folder, const TString& home) {
    Y_ASSERT(home && home.at(0) == '/');
    if (!folder) {
        return false;
    }
    // may be from windows
    char* ptr = folder.begin();
    while ((ptr = strchr(ptr, '\\')) != nullptr)
        *ptr = '/';

    if (folder.at(0) == '~') {
        if (folder.length() == 1 || folder.at(1) == '/') {
            folder = GetHomeDir() + (folder.data() + 1); 
        } else {
            char* buf = (char*)alloca(folder.length() + 1);
            strcpy(buf, folder.data() + 1); 
            char* p = strchr(buf, '/');
            if (p)
                *p++ = 0;
            passwd* pw = getpwnam(buf);
            if (pw) {
                folder = pw->pw_dir;
                folder += "/";
                if (p)
                    folder += p;
            } else {
                return false; // unknown user
            }
        }
    }
    int len = folder.length() + home.length() + 1;
    char* path = (char*)alloca(len);
    if (folder.at(0) != '/') {
        strcpy(path, home.data()); 
        strcpy(strrchr(path, '/') + 1, folder.data()); // the last char must be '/' if it's a dir 
    } else {
        strcpy(path, folder.data()); 
    }
    len = strlen(path) + 1;
    // grabbed from url.cpp
    char* newpath = (char*)alloca(len + 2);
    const char** pp = (const char**)alloca(len * sizeof(char*));
    int i = 0;
    for (char* s = path; s;) {
        pp[i++] = s;
        s = strchr(s, '/');
        if (s)
            *s++ = 0;
    }

    for (int j = 1; j < i;) {
        const char*& p = pp[j];
        if (strcmp(p, ".") == 0 || strcmp(p, "") == 0) {
            if (j == i - 1) {
                p = "";
                break;
            } else {
                memmove(pp + j, pp + j + 1, (i - j - 1) * sizeof(p));
                --i;
            }
        } else if (strcmp(p, "..") == 0) {
            if (j == i - 1) {
                if (j == 1) {
                    p = "";
                } else {
                    --i;
                    pp[j - 1] = "";
                }
                break;
            } else {
                if (j == 1) {
                    memmove(pp + j, pp + j + 1, (i - j - 1) * sizeof(p));
                    --i;
                } else {
                    memmove(pp + j - 1, pp + j + 1, (i - j - 1) * sizeof(p));
                    i -= 2;
                    --j;
                }
            }
        } else
            ++j;
    }

    char* s = newpath;
    for (int k = 0; k < i; k++) {
        s = strchr(strcpy(s, pp[k]), 0);
        *s++ = '/';
    }
    *(--s) = 0;
    folder = newpath;
    return true;
}

#else

using dir_type = enum {
    dt_empty,
    dt_error,
    dt_up,
    dt_dir
};

// precondition:  *ptr != '\\' || *ptr == 0 (cause dt_error)
// postcondition: *ptr != '\\'
template <typename T>
static int next_dir(T*& ptr) {
    int has_blank = 0;
    int has_dot = 0;
    int has_letter = 0;
    int has_ctrl = 0;

    while (*ptr && *ptr != '\\') {
        int c = (unsigned char)*ptr++;
        switch (c) {
            case ' ':
                ++has_blank;
                break;
            case '.':
                ++has_dot;
                break;
            case '/':
            case ':':
            case '*':
            case '?':
            case '"':
            case '<':
            case '>':
            case '|':
                ++has_ctrl;
                break;
            default:
                if (c == 127 || c < ' ')
                    ++has_ctrl;
                else
                    ++has_letter;
        }
    }
    if (*ptr)
        ++ptr;
    if (has_ctrl)
        return dt_error;
    if (has_letter)
        return dt_dir;
    if (has_dot && has_blank)
        return dt_error;
    if (has_dot == 1)
        return dt_empty;
    if (has_dot == 2)
        return dt_up;
    return dt_error;
}

using disk_type = enum {
    dk_noflags = 0,
    dk_unc = 1,
    dk_hasdrive = 2,
    dk_fromroot = 4,
    dk_error = 8
};

// root slash (if any) - part of disk
template <typename T>
static int skip_disk(T*& ptr) {
    int result = dk_noflags;
    if (!*ptr)
        return result;
    if (ptr[0] == '\\' && ptr[1] == '\\') {
        result |= dk_unc | dk_fromroot;
        ptr += 2;
        if (next_dir(ptr) != dt_dir)
            return dk_error; // has no host name
        if (next_dir(ptr) != dt_dir)
            return dk_error; // has no share name
    } else {
        if (*ptr && *(ptr + 1) == ':') {
            result |= dk_hasdrive;
            ptr += 2;
        }
        if (*ptr == '\\' || *ptr == '/') {
            ++ptr;
            result |= dk_fromroot;
        }
    }
    return result;
}

int correctpath(char* cpath, const char* path) {
    if (!path || !*path) {
        *cpath = 0;
        return 1;
    }
    char* ptr = (char*)path;
    char* cptr = cpath;
    int counter = 0;
    while (*ptr) {
        char c = *ptr;
        if (c == '/')
            c = '\\';
        if (c == '\\')
            ++counter;
        else
            counter = 0;
        if (counter <= 1) {
            *cptr = c;
            ++cptr;
        }
        ++ptr;
    }
    *cptr = 0;
    // replace '/' by '\'
    int dk = skip_disk(cpath);

    if (dk == dk_error)
        return 0;

    char* ptr1 = ptr = cpath;
    int level = 0;
    while (*ptr) {
        switch (next_dir(ptr)) {
            case dt_dir:
                ++level;
                break;
            case dt_empty:
                memmove(ptr1, ptr, strlen(ptr) + 1);
                ptr = ptr1;
                break;
            case dt_up:
                --level;
                if (level >= 0) {
                    *--ptr1 = 0;
                    ptr1 = strrchr(cpath, '\\');
                    if (!ptr1)
                        ptr1 = cpath;
                    else
                        ++ptr1;
                    memmove(ptr1, ptr, strlen(ptr) + 1);
                    ptr = ptr1;
                    break;
                } else if (level == -1 && (dk & dk_hasdrive)) {
                    if (*ptr && *(ptr + 1) == ':' && *(cpath - 2) == ':') {
                        memmove(cpath - 3, ptr, strlen(ptr) + 1);
                        return 1;
                    }
                }
                if (dk & dk_fromroot)
                    return 0;
                break;
            case dt_error:
            default:
                return 0;
        }
        ptr1 = ptr;
    }

    if ((ptr > cpath || ptr == cpath && dk & dk_unc) && *(ptr - 1) == '\\')
        *(ptr - 1) = 0;
    return 1;
}

static inline int normchar(unsigned char c) {
    return (c < 'a' || c > 'z') ? c : c - 32;
}

static inline char* strslashcat(char* a, const char* b) {
    size_t len = strlen(a);
    if (len && a[len - 1] != '\\')
        a[len++] = '\\';
    strcpy(a + len, b);
    return a;
}

int resolvepath(char* apath, const char* rpath, const char* cpath) {
    const char* redisk = rpath;
    if (!rpath || !*rpath)
        return 0;
    int rdt = skip_disk(redisk);
    if (rdt == dk_error)
        return 0;
    if (rdt & dk_unc || rdt & dk_hasdrive && rdt & dk_fromroot) {
        return correctpath(apath, rpath);
    }

    const char* cedisk = cpath;
    if (!cpath || !*cpath)
        return 0;
    int cdt = skip_disk(cedisk);
    if (cdt == dk_error)
        return 0;

    char* tpath = (char*)alloca(strlen(rpath) + strlen(cpath) + 3);

    // rdt&dk_hasdrive && !rdt&dk_fromroot
    if (rdt & dk_hasdrive) {
        if (!(cdt & dk_fromroot))
            return 0;
        if (cdt & dk_hasdrive && normchar(*rpath) != normchar(*cpath))
            return 0;
        memcpy(tpath, rpath, 2);
        memcpy(tpath + 2, cedisk, strlen(cedisk) + 1);
        strslashcat(tpath, redisk);

        // !rdt&dk_hasdrive && rdt&dk_fromroot
    } else if (rdt & dk_fromroot) {
        if (!(cdt & dk_hasdrive) && !(cdt & dk_unc))
            return 0;
        memcpy(tpath, cpath, cedisk - cpath);
        tpath[cedisk - cpath] = 0;
        strslashcat(tpath, redisk);

        // !rdt&dk_hasdrive && !rdt&dk_fromroot
    } else {
        if (!(cdt & dk_fromroot) || !(cdt & dk_hasdrive) && !(cdt & dk_unc))
            return 0;
        strslashcat(strcpy(tpath, cpath), redisk);
    }

    return correctpath(apath, tpath);
}

bool correctpath(TString& filename) {
    char* ptr = (char*)alloca(filename.size() + 2); 
    if (correctpath(ptr, filename.data())) { 
        filename = ptr;
        return true;
    }
    return false;
}

bool resolvepath(TString& folder, const TString& home) {
    char* ptr = (char*)alloca(folder.size() + 3 + home.size()); 
    if (resolvepath(ptr, folder.data(), home.data())) { 
        folder = ptr;
        return true;
    }
    return false;
}

#endif // !defined _win32_

char GetDirectorySeparator() {
    return LOCSLASH_C;
}

const char* GetDirectorySeparatorS() {
    return LOCSLASH_S;
}

void RemoveDirWithContents(TString dirName) {
    SlashFolderLocal(dirName);

    TDirIterator dir(dirName, TDirIterator::TOptions(FTS_NOSTAT));

    for (auto it = dir.begin(); it != dir.end(); ++it) {
        switch (it->fts_info) {
            case FTS_F:
            case FTS_DEFAULT:
            case FTS_DP:
            case FTS_SL:
            case FTS_SLNONE:
                if (!NFs::Remove(it->fts_path))
                    ythrow TSystemError() << "error while removing " << it->fts_path;
                break;
        }
    }
}

int mkpath(char* path, int mode) {
    return NFs::MakeDirectoryRecursive(path, NFs::EFilePermission(mode)) ? 0 : -1;
}

// Implementation of realpath in FreeBSD (version 9.0 and less) and GetFullPathName in Windows
// did not require last component of the file name to exist (other implementations will fail
// if it does not). Use RealLocation if that behaviour is required.
TString RealPath(const TString& path) {
    TTempBuf result;
    Y_ASSERT(result.Size() > MAX_PATH); //TMP_BUF_LEN > MAX_PATH
#ifdef _win_
    if (GetFullPathName(path.data(), result.Size(), result.Data(), nullptr) == 0) 
#else
    if (realpath(path.data(), result.Data()) == nullptr) 
#endif
        ythrow TFileError() << "RealPath failed \"" << path << "\"";
    return result.Data();
}

TString RealLocation(const TString& path) {
    if (NFs::Exists(path))
        return RealPath(path);
    TString dirpath = GetDirName(path);
    if (NFs::Exists(dirpath))
        return RealPath(dirpath) + GetDirectorySeparatorS() + GetFileNameComponent(path.data()); 
    ythrow TFileError() << "RealLocation failed \"" << path << "\"";
}

int MakeTempDir(char path[/*FILENAME_MAX*/], const char* prefix) {
    int ret;

    TString sysTmp;

#ifdef _win32_
    if (!prefix || *prefix == '/') {
#else
    if (!prefix) {
#endif
        sysTmp = GetSystemTempDir();
        prefix = sysTmp.data(); 
    }

    if ((ret = ResolvePath(prefix, nullptr, path, 1)) != 0)
        return ret;
    if (!TFileStat(path).IsDir())
        return ENOENT;
    if ((strlcat(path, "tmpXXXXXX", FILENAME_MAX) > FILENAME_MAX - 100))
        return EINVAL;
    if (!(mkdtemp(path)))
        return errno ? errno : EINVAL;
    strcat(path, LOCSLASH_S);
    return 0;
}

bool IsDir(const TString& path) {
    return TFileStat(path).IsDir();
}

TString GetHomeDir() {
    TString s(getenv("HOME"));
    if (!s) {
#ifndef _win32_
        passwd* pw = nullptr;
        s = getenv("USER");
        if (s)
            pw = getpwnam(s.data()); 
        else
            pw = getpwuid(getuid());
        if (pw)
            s = pw->pw_dir;
        else
#endif
        {
            char* cur_dir = getcwd(nullptr, 0);
            s = cur_dir;
            free(cur_dir);
        }
    }
    return s;
}

void MakeDirIfNotExist(const char* path, int mode) {
    if (!NFs::MakeDirectory(path, NFs::EFilePermission(mode)) && !NFs::Exists(path)) {
        ythrow TSystemError() << "failed to create directory " << path;
    }
}

void MakePathIfNotExist(const char* path, int mode) {
    NFs::MakeDirectoryRecursive(path, NFs::EFilePermission(mode));
    if (!NFs::Exists(path) || !TFileStat(path).IsDir()) {
        ythrow TSystemError() << "failed to create directory " << path;
    }
}

const char* GetFileNameComponent(const char* f) {
    const char* p = strrchr(f, LOCSLASH_C);
#ifdef _win_
    // "/" is also valid char separator on Windows
    const char* p2 = strrchr(f, '/');
    if (p2 > p)
        p = p2;
#endif

    if (p) {
        return p + 1;
    }

    return f;
}

TString GetSystemTempDir() {
#ifdef _win_
    char buffer[1024];
    DWORD size = GetTempPath(1024, buffer);
    if (!size) {
        ythrow TSystemError() << "failed to get system temporary directory";
    }
    return TString(buffer, size);
#else
    const char* var = "TMPDIR";
    const char* def = "/tmp";
    const char* r = getenv(var);
    const char* result = r ? r : def;
    return result[0] == '/' ? result : ResolveDir(result);
#endif
}

TString ResolveDir(const char* path) {
    return ResolvePath(path, true);
}

bool SafeResolveDir(const char* path, TString& result) {
    try {
        result = ResolvePath(path, true);
        return true;
    } catch (...) {
        return false;
    }
}

TString GetDirName(const TString& path) {
    return TFsPath(path).Dirname();
}

#ifdef _win32_

char* realpath(const char* pathname, char resolved_path[MAXPATHLEN]) {
    // partial implementation: no path existence check
    return _fullpath(resolved_path, pathname, MAXPATHLEN - 1);
}

#endif

TString GetBaseName(const TString& path) {
    return TFsPath(path).Basename();
}

static bool IsAbsolutePath(const char* str) {
    return str && TPathSplitTraitsLocal::IsAbsolutePath(TStringBuf(str, NStringPrivate::GetStringLengthWithLimit(str, 3)));
}

int ResolvePath(const char* rel, const char* abs, char res[/*MAXPATHLEN*/], bool isdir) {
    char t[MAXPATHLEN * 2 + 3];
    size_t len;

    *res = 0;
    if (!rel || !*rel)
        return EINVAL;
    if (!IsAbsolutePath(rel) && IsAbsolutePath(abs)) {
        len = strlcpy(t, abs, sizeof(t));
        if (len >= sizeof(t) - 3)
            return EINVAL;
        if (t[len - 1] != LOCSLASH_C)
            t[len++] = LOCSLASH_C;
        len += strlcpy(t + len, rel, sizeof(t) - len);
    } else {
        len = strlcpy(t, rel, sizeof(t));
    }
    if (len >= sizeof(t) - 3)
        return EINVAL;
    if (isdir && t[len - 1] != LOCSLASH_C) {
        t[len++] = LOCSLASH_C;
        t[len] = 0;
    }
    if (!realpath(t, res)) {
        if (!isdir && realpath(GetDirName(t).data(), res)) { 
            len = strlen(res);
            if (res[len - 1] != LOCSLASH_C) {
                res[len++] = LOCSLASH_C;
                res[len] = 0;
            }
            strcpy(res + len, GetBaseName(t).data()); 
            return 0;
        }
        return errno ? errno : ENOENT;
    }
    if (isdir) {
        len = strlen(res);
        if (res[len - 1] != LOCSLASH_C) {
            res[len++] = LOCSLASH_C;
            res[len] = 0;
        }
    }
    return 0;
}

TString ResolvePath(const char* rel, const char* abs, bool isdir) {
    char buf[PATH_MAX];
    if (ResolvePath(rel, abs, buf, isdir))
        ythrow yexception() << "cannot resolve path: \"" << rel << "\"";
    return buf;
}

TString ResolvePath(const char* path, bool isDir) {
    return ResolvePath(path, nullptr, isDir);
}

TString StripFileComponent(const TString& fileName) {
    TString dir = IsDir(fileName) ? fileName : GetDirName(fileName);
    if (!dir.empty() && dir.back() != GetDirectorySeparator()) {
        dir.append(GetDirectorySeparator());
    }
    return dir;
}