summaryrefslogtreecommitdiff
path: root/zen/resolve_path.cpp
blob: 8b81e184883333d669a28b8a798f83edbe6349d0 (plain)
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
// *****************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under    *
// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0          *
// * Copyright (C) Zenju (zenju AT freefilesync DOT org) - All Rights Reserved *
// *****************************************************************************

#include "resolve_path.h"
#include "time.h"
#include "thread.h"
#include "file_access.h"

    #include <zen/sys_info.h>
    //    #include <stdlib.h> //getenv()
    #include <unistd.h> //getuid()
    #include <pwd.h>    //getpwuid_r()

using namespace zen;


namespace
{
std::optional<Zstring> getEnvironmentVar(const Zchar* name)
{
    assert(runningOnMainThread()); //getenv() is not thread-safe!

    const char* buffer = ::getenv(name); //no ownership transfer + no extended error reporting
    if (!buffer)
        return {};
    Zstring value(buffer);

    //some postprocessing:
    trim(value); //remove leading, trailing blanks

    //remove leading, trailing double-quotes
    if (startsWith(value, Zstr('"')) &&
        endsWith  (value, Zstr('"')) &&
        value.length() >= 2)
        value = Zstring(value.c_str() + 1, value.length() - 2);

    return value;
}


Zstring resolveRelativePath(const Zstring& relativePath)
{
    assert(runningOnMainThread());
    /* MSDN: "Multithreaded applications and shared library code should not use the GetFullPathName function
              and should avoid using relative path names. The current directory state written by the
              SetCurrentDirectory function is stored as a global variable in each process,
              therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads, [...]"

      => Just plain wrong, there is no data corruption. What MSDN really means: GetFullPathName() is *perfectly* thread-safe, but depends
         on the current directory, which is a process-scope global: https://devblogs.microsoft.com/oldnewthing/20210816-00/?p=105562            */

    if (relativePath.empty())
        return relativePath;

    Zstring pathTmp = relativePath;
    //https://linux.die.net/man/2/path_resolution
    if (!startsWith(pathTmp, FILE_NAME_SEPARATOR)) //absolute names are exactly those starting with a '/'
    {
        /* basic support for '~': strictly speaking this is a shell-layer feature, so "realpath()" won't handle it
            https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html               */
        if (startsWith(pathTmp, "~/") || pathTmp == "~")
        {
            try
            {
                const Zstring& homePath = getUserHome(); //throw FileError

                if (startsWith(pathTmp, "~/"))
                    pathTmp = appendPath(homePath, pathTmp.c_str() + 2);
                else //pathTmp == "~"
                    pathTmp = homePath;
            }
            catch (FileError&) {}
            //else: error! no further processing!
        }
        else
        {
            //we cannot use ::realpath() which only resolves *existing* relative paths!
            if (char* dirPath = ::getcwd(nullptr, 0))
            {
                ZEN_ON_SCOPE_EXIT(::free(dirPath));
                pathTmp = appendPath(dirPath, pathTmp);
            }
        }
    }
    //get rid of some cruft (just like GetFullPathName())
    replace(pathTmp, "/./", '/');
    if (endsWith(pathTmp, "/."))
        pathTmp.pop_back(); //keep the "/" => consider pathTmp == "/."

    //what about "/../"? might be relative to symlinks => preserve!

    return pathTmp;
}




//returns value if resolved
std::optional<Zstring> tryResolveMacro(const Zstring& macro) //macro without %-characters
{
    Zstring timeStr;
    auto resolveTimePhrase = [&](const Zchar* phrase, const Zchar* format) -> bool
    {
        if (!equalAsciiNoCase(macro, phrase))
            return false;

        timeStr = formatTime(format);
        return true;
    };

    //https://en.cppreference.com/w/cpp/chrono/c/strftime
    //there exist environment variables named %TIME%, %DATE% so check for our internal macros first!
    if (resolveTimePhrase(Zstr("Date"),        Zstr("%Y-%m-%d")))        return timeStr;
    if (resolveTimePhrase(Zstr("Time"),        Zstr("%H%M%S")))          return timeStr;
    if (resolveTimePhrase(Zstr("TimeStamp"),   Zstr("%Y-%m-%d %H%M%S"))) return timeStr; //e.g. "2012-05-15 131513"
    if (resolveTimePhrase(Zstr("Year"),        Zstr("%Y")))              return timeStr;
    if (resolveTimePhrase(Zstr("Month"),       Zstr("%m")))              return timeStr;
    if (resolveTimePhrase(Zstr("MonthName"),   Zstr("%b")))              return timeStr; //e.g. "Jan"
    if (resolveTimePhrase(Zstr("Day"),         Zstr("%d")))              return timeStr;
    if (resolveTimePhrase(Zstr("Hour"),        Zstr("%H")))              return timeStr;
    if (resolveTimePhrase(Zstr("Min"),         Zstr("%M")))              return timeStr;
    if (resolveTimePhrase(Zstr("Sec"),         Zstr("%S")))              return timeStr;
    if (resolveTimePhrase(Zstr("WeekDayName"), Zstr("%a")))              return timeStr; //e.g. "Mon"
    if (resolveTimePhrase(Zstr("Week"),        Zstr("%V")))              return timeStr; //ISO 8601 week of the year

    if (equalAsciiNoCase(macro, Zstr("WeekDay")))
    {
        const int weekDayStartSunday = stringTo<int>(formatTime(Zstr("%w"))); //[0 (Sunday), 6 (Saturday)] => not localized!
        //alternative 1: use "%u": ISO 8601 weekday as number with Monday as 1 (1-7) => newer standard than %w
        //alternative 2: ::mktime() + std::tm::tm_wday

        const int weekDayStartMonday = (weekDayStartSunday + 6) % 7; //+6 == -1 in Z_7
        // [0-Monday, 6-Sunday]

        const int weekDayStartLocal = ((weekDayStartMonday + 7 - static_cast<int>(getFirstDayOfWeek())) % 7) + 1;
        //[1 (local first day of week), 7 (local last day of week)]

        return numberTo<Zstring>(weekDayStartLocal);
    }

    //try to resolve as environment variables
    if (std::optional<Zstring> value = getEnvironmentVar(macro.c_str()))
        return *value;

    return {};
}

const Zchar MACRO_SEP = Zstr('%');
}


//returns expanded or original string
Zstring zen::expandMacros(const Zstring& text)
{
    if (contains(text, MACRO_SEP))
    {
        Zstring prefix = beforeFirst(text, MACRO_SEP, IfNotFoundReturn::none);
        Zstring rest   = afterFirst (text, MACRO_SEP, IfNotFoundReturn::none);
        if (contains(rest, MACRO_SEP))
        {
            Zstring potentialMacro = beforeFirst(rest, MACRO_SEP, IfNotFoundReturn::none);
            Zstring postfix        = afterFirst (rest, MACRO_SEP, IfNotFoundReturn::none); //text == prefix + MACRO_SEP + potentialMacro + MACRO_SEP + postfix

            if (std::optional<Zstring> value = tryResolveMacro(potentialMacro))
                return prefix + *value + expandMacros(postfix);
            else
                return prefix + MACRO_SEP + potentialMacro + expandMacros(MACRO_SEP + postfix);
        }
    }
    return text;
}


namespace
{


//expand volume name if possible, return original input otherwise
Zstring tryExpandVolumeName(Zstring pathPhrase)  // [volname]:\folder    [volname]\folder    [volname]folder    -> C:\folder
{
    //we only expect the [.*] pattern at the beginning => do not touch dir names like "C:\somedir\[stuff]"
    trim(pathPhrase, true, false);

    if (startsWith(pathPhrase, Zstr('[')))
    {
        return "/.../" + pathPhrase;
    }
    return pathPhrase;
}
}


std::vector<Zstring> zen::getPathPhraseAliases(const Zstring& itemPath)
{
    assert(!itemPath.empty());
    std::vector<Zstring> pathAliases{makePathPhrase(itemPath)};

    {

        //environment variables: C:\Users\<user> -> %UserProfile%
        auto substByMacro = [&](const Zchar* macroName, const Zstring& macroPath)
        {
            //should use a replaceCpy() that considers "local path" case-sensitivity (if only we had one...)
            if (contains(itemPath, macroPath))
                pathAliases.push_back(makePathPhrase(replaceCpyAsciiNoCase(itemPath, macroPath, Zstring() + MACRO_SEP + macroName + MACRO_SEP)));
        };

        for (const Zchar* envName :
             {
                 "HOME", //Linux: /home/<user>  Mac: /Users/<user>
                 //"USER",  -> any benefit?
             })
            if (const std::optional<Zstring> envPath = getEnvironmentVar(envName))
                substByMacro(envName, *envPath);

    }
    //removeDuplicates()? should not be needed...

    std::sort(pathAliases.begin(), pathAliases.end(), LessNaturalSort() /*even on Linux*/);
    return pathAliases;
}


Zstring zen::makePathPhrase(const Zstring& itemPath)
{
    if (endsWith(itemPath, Zstr(' '))) //path phrase concept must survive trimming!
        return itemPath + FILE_NAME_SEPARATOR;
    return itemPath;
}


//coordinate changes with acceptsFolderPathPhraseNative()!
Zstring zen::getResolvedFilePath(const Zstring& pathPhrase) //noexcept
{
    Zstring path = pathPhrase;

    path = expandMacros(path); //expand before trimming!

    trim(path); //remove leading/trailing whitespace before allowing misinterpretation in applyLongPathPrefix()

    {
        path = tryExpandVolumeName(path); //may block for slow USB sticks and idle HDDs!

        /* need to resolve relative paths:
             WINDOWS:
              - \\?\-prefix requires absolute names
              - Volume Shadow Copy: volume name needs to be part of each file path
              - file icon buffer (at least for extensions that are actually read from disk, like "exe")
             WINDOWS/LINUX:
              - detection of dependent directories, e.g. "\" and "C:\test"                       */
        path = resolveRelativePath(path);
    }

    //remove trailing slash, unless volume root:
    if (const std::optional<PathComponents> pc = parsePathComponents(path))
        path = appendPath(pc->rootPath, pc->relPath);

    return path;
}


bgstack15