summaryrefslogtreecommitdiff
path: root/sal/osl/unx/uunxapi.cxx
blob: a6b80daa9e2a71eb8d524a0ac5108d6d9db9eeec (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
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
/* -*- Mode: ObjC; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <config_features.h>

#include "uunxapi.hxx"
#include "system.hxx"
#include <limits.h>
#include <rtl/ustring.hxx>
#include <osl/thread.h>

#ifdef ANDROID
#include <osl/detail/android-bootstrap.h>
#endif

static inline rtl::OString OUStringToOString(const rtl_uString* s)
{
    return rtl::OUStringToOString(rtl::OUString(const_cast<rtl_uString*>(s)),
                                  osl_getThreadTextEncoding());
}

#if HAVE_FEATURE_MACOSX_SANDBOX

#include <Foundation/Foundation.h>
#include <Security/Security.h>
#include <mach-o/dyld.h>

static NSUserDefaults *userDefaults = NULL;
static bool isSandboxed = false;

static void do_once()
{
    SecCodeRef code;
    OSStatus rc = SecCodeCopySelf(kSecCSDefaultFlags, &code);

    SecStaticCodeRef staticCode;
    if (rc == errSecSuccess)
        rc = SecCodeCopyStaticCode(code, kSecCSDefaultFlags, &staticCode);

    CFDictionaryRef signingInformation;
    if (rc == errSecSuccess)
        rc = SecCodeCopySigningInformation(staticCode, kSecCSRequirementInformation, &signingInformation);

    CFDictionaryRef entitlements = NULL;
    if (rc == errSecSuccess)
        entitlements = (CFDictionaryRef) CFDictionaryGetValue(signingInformation, kSecCodeInfoEntitlementsDict);

    if (entitlements != NULL)
        if (CFDictionaryGetValue(entitlements, CFSTR("com.apple.security.app-sandbox")) != NULL)
            isSandboxed = true;

    if (isSandboxed)
        userDefaults = [NSUserDefaults standardUserDefaults];
}

typedef struct {
    NSURL *scopeURL;
    NSAutoreleasePool *pool;
} accessFilePathState;

static accessFilePathState *
prepare_to_access_file_path( const char *cpFilePath )
{
    static pthread_once_t once = PTHREAD_ONCE_INIT;
    pthread_once(&once, &do_once);
    NSURL *fileURL = nil;
    NSData *data = nil;
    BOOL stale;
    accessFilePathState *state;

    if (!isSandboxed)
        return NULL;

    // If malloc() fails we are screwed anyway
    state = (accessFilePathState*) malloc(sizeof(accessFilePathState));

    state->pool = [[NSAutoreleasePool alloc] init];
    state->scopeURL = nil;

    if (userDefaults != nil)
        fileURL = [NSURL fileURLWithPath:[NSString stringWithUTF8String:cpFilePath]];

    if (fileURL != nil)
        data = [userDefaults dataForKey:[@"bookmarkFor:" stringByAppendingString:[fileURL absoluteString]]];

    if (data != nil)
        state->scopeURL = [NSURL URLByResolvingBookmarkData:data
                                                    options:NSURLBookmarkResolutionWithSecurityScope
                                              relativeToURL:nil
                                        bookmarkDataIsStale:&stale
                                                      error:nil];
    if (state->scopeURL != nil)
        [state->scopeURL startAccessingSecurityScopedResource];

    return state;
}

static void
done_accessing_file_path( const char * /*cpFilePath*/, accessFilePathState *state )
{
    if (!isSandboxed)
        return;

    int saved_errno = errno;

    if (state->scopeURL != nil)
        [state->scopeURL stopAccessingSecurityScopedResource];
    [state->pool release];
    free(state);

    errno = saved_errno;
}

#else

typedef void accessFilePathState;

#define prepare_to_access_file_path( cpFilePath ) nullptr

#define done_accessing_file_path( cpFilePath, state ) ((void) cpFilePath, (void) state)

#endif

#ifdef MACOSX
/*
 * Helper function for resolving Mac native alias files (not the same as unix alias files)
 * and to return the resolved alias as rtl::OString
 */
static rtl::OString macxp_resolveAliasAndConvert(rtl::OString const & p)
{
    sal_Char path[PATH_MAX];
    if (p.getLength() < PATH_MAX)
    {
        strcpy(path, p.getStr());
        macxp_resolveAlias(path, PATH_MAX);
        return rtl::OString(path);
    }
    return p;
}
#endif /* MACOSX */

int access_u(const rtl_uString* pustrPath, int mode)
{
    rtl::OString fn = OUStringToOString(pustrPath);
#ifdef ANDROID
    if (fn == "/assets" || fn.startsWith("/assets/"))
    {
        struct stat stat;
        if (lo_apk_lstat(fn.getStr(), &stat) == -1)
            return -1;
        if (mode & W_OK)
        {
            errno = EACCES;
            return -1;
        }
        return 0;
    }
#endif

#ifdef MACOSX
    fn = macxp_resolveAliasAndConvert(fn);
#endif

    accessFilePathState *state = prepare_to_access_file_path(fn.getStr());

    int result = access(fn.getStr(), mode);

    done_accessing_file_path(fn.getStr(), state);

    return result;
}

bool realpath_u(const rtl_uString* pustrFileName, rtl_uString** ppustrResolvedName)
{
    rtl::OString fn = OUStringToOString(pustrFileName);
#ifdef ANDROID
    if (fn == "/assets" || fn.startsWith("/assets/"))
    {
        if (access_u(pustrFileName, F_OK) == -1)
            return false;

        rtl_uString silly(*pustrFileName);
        rtl_uString_assign(ppustrResolvedName, &silly);

        return true;
    }
#endif

#ifdef MACOSX
    fn = macxp_resolveAliasAndConvert(fn);
#endif

    accessFilePathState *state = prepare_to_access_file_path(fn.getStr());

    char  rp[PATH_MAX];
    bool  bRet = realpath(fn.getStr(), rp);

    done_accessing_file_path(fn.getStr(), state);

    if (bRet)
    {
        rtl::OUString resolved = rtl::OStringToOUString(rtl::OString(static_cast<sal_Char*>(rp)),
                                                        osl_getThreadTextEncoding());

        rtl_uString_assign(ppustrResolvedName, resolved.pData);
    }
    return bRet;
}

int stat_c(const char* cpPath, struct stat* buf)
{
#ifdef ANDROID
    if (strncmp(cpPath, "/assets", sizeof("/assets")-1) == 0 &&
        (cpPath[sizeof("/assets")-1] == '\0' ||
         cpPath[sizeof("/assets")-1] == '/'))
        return lo_apk_lstat(cpPath, buf);
#endif

    accessFilePathState *state = prepare_to_access_file_path(cpPath);

    int result = stat(cpPath, buf);

    done_accessing_file_path(cpPath, state);

    return result;
}

int lstat_c(const char* cpPath, struct stat* buf)
{
#ifdef ANDROID
    if (strncmp(cpPath, "/assets", sizeof("/assets")-1) == 0 &&
        (cpPath[sizeof("/assets")-1] == '\0' ||
         cpPath[sizeof("/assets")-1] == '/'))
        return lo_apk_lstat(cpPath, buf);
#endif

    accessFilePathState *state = prepare_to_access_file_path(cpPath);

    int result = lstat(cpPath, buf);

    done_accessing_file_path(cpPath, state);

    return result;
}

int lstat_u(const rtl_uString* pustrPath, struct stat* buf)
{
    rtl::OString fn = OUStringToOString(pustrPath);

#ifdef MACOSX
    fn = macxp_resolveAliasAndConvert(fn);
#endif

    return lstat_c(fn.getStr(), buf);
}

int mkdir_u(const rtl_uString* path, mode_t mode)
{
    rtl::OString fn = OUStringToOString(path);

    accessFilePathState *state = prepare_to_access_file_path(fn.getStr());

    int result = mkdir(OUStringToOString(path).getStr(), mode);

    done_accessing_file_path(fn.getStr(), state);

    return result;
}

int open_c(const char *cpPath, int oflag, int mode)
{
    accessFilePathState *state = prepare_to_access_file_path(cpPath);

    int result = open(cpPath, oflag, mode);

#if HAVE_FEATURE_MACOSX_SANDBOX
    if (isSandboxed && result != -1 && (oflag & O_CREAT) && (oflag & O_EXCL))
    {
        // A new file was created. Check if it is outside the sandbox.
        // (In that case it must be one the user selected as export or
        // save destination in a file dialog, otherwise we wouldn't
        // have been able to create it.) Create and store a security
        // scoped bookmark for it so that we can access the file in
        // the future, too. (For the "Recent Files" functionality.)
        const char *sandbox = [NSHomeDirectory() UTF8String];
        if (!(strncmp(sandbox, cpPath, strlen(sandbox)) == 0 &&
              cpPath[strlen(sandbox)] == '/'))
        {
            NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:cpPath]];
            NSData *data = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
                         includingResourceValuesForKeys:nil
                                          relativeToURL:nil
                                                  error:nil];
            if (data != NULL)
            {
                [userDefaults setObject:data
                                 forKey:[@"bookmarkFor:" stringByAppendingString:[url absoluteString]]];
            }
        }
    }
#endif

    done_accessing_file_path(cpPath, state);

    return result;
}

int utime_c(const char *cpPath, struct utimbuf *times)
{
    accessFilePathState *state = prepare_to_access_file_path(cpPath);

    int result = utime(cpPath, times);

    done_accessing_file_path(cpPath, state);

    return result;
}

int ftruncate_with_name(int fd, sal_uInt64 uSize, rtl_String* path)
{
    /* When sandboxed on OS X, ftruncate(), even if it takes an
     * already open file descriptor which was returned from an open()
     * call already checked by the sandbox, still requires a security
     * scope bookmark for the file to be active in case the file is
     * one that the sandbox doesn't otherwise allow access to. Luckily
     * LibreOffice usually calls ftruncate() through the helpful C++
     * abstraction layer that keeps the pathname around.
     */

    rtl::OString fn = rtl::OString(path);

#ifdef MACOSX
    fn = macxp_resolveAliasAndConvert(fn);
#endif

    accessFilePathState *state = prepare_to_access_file_path(fn.getStr());

    int result = ftruncate(fd, uSize);

    done_accessing_file_path(fn.getStr(), state);

    return result;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */