Annotation of parser3/src/main/pa_file.C, revision 1.8

1.1       moko        1: /** @file
                      2:        Parser: file and file system related functions.
                      3: 
                      4:        Copyright (c) 2000-2026 Art. Lebedev Studio (https://www.artlebedev.com)
                      5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
                      6: */
                      7: 
                      8: #include "pa_file.h"
                      9: #include "pa_dir.h"
                     10: #include "pa_charsets.h"
                     11: #include "pa_http.h"
                     12: #include "pa_convert_utf.h"
                     13: 
                     14: #ifdef _MSC_VER
                     15: #include <windows.h>
                     16: #include <direct.h>
                     17: #endif
                     18: 
1.8     ! moko       19: volatile const char * IDENT_PA_FILE_C="$Id: pa_file.C,v 1.7 2026/09/30 17:45:25 moko Exp $" IDENT_PA_FILE_H;
        !            20: 
        !            21: // a tainted path scheme (file://, http:// or parser://) would be accepted
        !            22: //#define IGNORE_FILE_PREFIX_LANGUAGES
1.1       moko       23: 
                     24: // some maybe-undefined constants
                     25: 
                     26: #ifndef _O_TEXT
                     27: #      define _O_TEXT 0
                     28: #endif
                     29: #ifndef _O_BINARY
                     30: #      define _O_BINARY 0
                     31: #endif
                     32: 
                     33: #ifdef HAVE_FTRUNCATE
                     34: #      define PA_O_TRUNC 0
                     35: #else
                     36: #      ifdef _O_TRUNC
                     37: #              define PA_O_TRUNC _O_TRUNC
                     38: #      else
                     39: #              error you must have either ftruncate function or _O_TRUNC bit declared
                     40: #      endif
                     41: #endif
                     42: 
                     43: #ifdef WIN32
                     44: 
                     45: bool is_os_absolute_path(const String& path) {
                     46:        return is_os_absolute_path(path.cstr());
                     47: }
                     48: 
                     49: bool is_os_absolute_path(const char* path) {
                     50:        return path[0] && path[0]!=':' && path[1]==':' // DRIVE: (including drive-relative paths, for compatibility)
1.4       moko       51:                || path[0]=='\\' && path[1]=='\\';     // UNC, only '\\' is supported as '//' is a document root relative path
1.1       moko       52: }
                     53: #endif
                     54: 
1.5       moko       55: uint path_scheme(const String& path) {
                     56:        if(path.starts_with("file://"))
                     57:                return PA_SCHEME_FILE;
                     58:        if(path.starts_with("http://"))
                     59:                return PA_SCHEME_HTTP;
                     60:        if(path.starts_with("parser://"))
                     61:                return PA_SCHEME_PARSER;
                     62:        return PA_SCHEME_NONE;
                     63: }
                     64: 
                     65: void check_path_scheme(uint scheme, const String& path, uint allowed) {
                     66:        if(scheme!=PA_SCHEME_FILE && !(allowed&scheme))
                     67:                throw Exception(PARSER_RUNTIME, &path, "unsupported path scheme");
1.8     ! moko       68: #ifndef IGNORE_FILE_PREFIX_LANGUAGES
        !            69:        if(!path.check_lang(String::L_AS_IS, 0, scheme==PA_SCHEME_PARSER ? 9 /* "parser://" */ : 7 /* "file://" or "http://" */))
        !            70:                throw Exception(PARSER_RUNTIME, &path, "tainted path scheme");
        !            71: #endif
1.5       moko       72: }
                     73: 
                     74: const String* file_uri_to_path(const String& uri) {
                     75:        const String* rest=&uri.mid(7 /* "file://" */, uri.length());
                     76:        if(rest->starts_with("localhost/"))
                     77:                rest=&rest->mid(9 /* "localhost", keeping the slash */, rest->length());
                     78:        if(rest->first_char()=='/') {
                     79:                // file:///C:/path and file://localhost/C:/path: the slash before a drive name is not a part of the path
                     80:                const String& disk=rest->mid(1, rest->length());
                     81:                return is_os_absolute_path(disk) ? &disk : rest;
                     82:        }
                     83:        if(is_os_absolute_path(*rest))
                     84:                return rest; // file://C:/path, not a standard form but in use
1.7       moko       85: #ifdef WIN32
                     86:        if(rest->pos('/')!=STRING_NOT_FOUND) { // file://server/share/path is the UNC path \\server\share\path
                     87:                String& result=*new String("//");
                     88:                result << *rest;
                     89:                return &result;
                     90:        }
                     91: #endif
1.5       moko       92:        return 0;
                     93: }
                     94: 
1.1       moko       95: // externs
                     96: 
                     97: const UTF16* pa_utf16_encode(const char* in, Charset& source_charset);
                     98: 
                     99: // functions
                    100: 
                    101: #ifdef _MSC_VER
                    102: 
                    103: #define PA_UTF16_ENC(value) (const wchar_t *)pa_utf16_encode(value, pa_thread_request().charsets.source())
                    104: 
                    105: int pa_stat(const char *pathname, struct stat *buffer){
                    106:        return _wstat64(PA_UTF16_ENC(pathname), buffer);
                    107: }
                    108: 
                    109: int pa_open(const char *pathname, int flags, int mode){
                    110:        return _wopen(PA_UTF16_ENC(pathname), flags, mode);
                    111: }
                    112: 
                    113: FILE *pa_fopen(const char *pathname, const char *mode){
                    114:        return _wfopen(PA_UTF16_ENC(pathname), PA_UTF16_ENC(mode));
                    115: }
                    116: 
                    117: int pa_mkdir(const char *pathname, int){
                    118:        return _wmkdir(PA_UTF16_ENC(pathname));
                    119: }
                    120: 
                    121: int pa_rmdir(const char *pathname){
                    122:        return _wrmdir(PA_UTF16_ENC(pathname));
                    123: }
                    124: 
                    125: int pa_rename(const char *oldpath, const char *newpath){
                    126:        return _wrename(PA_UTF16_ENC(oldpath), PA_UTF16_ENC(newpath));
                    127: }
                    128: 
                    129: int pa_unlink(const char *pathname){
                    130:        return _wunlink(PA_UTF16_ENC(pathname));
                    131: }
                    132: 
                    133: #else
                    134: 
                    135: #define pa_mkdir mkdir
                    136: #define pa_rmdir rmdir
                    137: #define pa_rename rename
                    138: #define pa_unlink unlink
                    139: 
                    140: #endif
                    141: 
                    142: /// these options were handled but not checked elsewhere, now check them
                    143: int pa_get_valid_file_options_count(HashStringValue& options) {
                    144:        int result=0;
                    145:        if(options.get(PA_SQL_LIMIT_NAME))
                    146:                result++;
                    147:        if(options.get(PA_SQL_OFFSET_NAME))
                    148:                result++;
                    149:        if(options.get(PA_COLUMN_SEPARATOR_NAME))
                    150:                result++;
                    151:        if(options.get(PA_COLUMN_ENCLOSER_NAME))
                    152:                result++;
                    153:        if(options.get(PA_CHARSET_NAME))
                    154:                result++;
                    155:        return result;
                    156: }
                    157: 
                    158: #ifndef DOXYGEN
                    159: struct File_read_action_info {
                    160:        char **data; size_t *data_size;
                    161:        char* buf; uint64_t offset; size_t limit;
1.3       moko      162: };
1.1       moko      163: #endif
                    164: 
                    165: static void file_read_action(struct stat& finfo, int f, const String& file_spec, void *context) {
1.3       moko      166:        File_read_action_info& info = *static_cast<File_read_action_info *>(context);
1.1       moko      167:        size_t to_read_size = check_file_size(info.limit && info.limit < (size_t)finfo.st_size ? info.limit : (size_t)finfo.st_size, &file_spec);
                    168:        if(to_read_size) {
                    169:                if(info.offset)
                    170:                         pa_lseek(f, info.offset, SEEK_SET); // seek never fails as POSIX allows the file offset to be set beyond the EOF
                    171:                *info.data = info.buf ? info.buf : (char *)pa_malloc_atomic(to_read_size+1);
                    172:                ssize_t result = read(f, *info.data, to_read_size);
                    173:                if(result<0)
                    174:                        throw Exception("file.read", &file_spec, "read failed: %s (%d)", strerror(errno), errno);
                    175:                *info.data_size = result;
                    176:        } else { // empty file
                    177:                // for both, text and binary: for text we need that terminator, for binary we need nonzero pointer to be able to save such files
                    178:                *info.data = (char *)pa_malloc_atomic(1);
                    179:                *(char*)(*info.data) = 0;
                    180:                *info.data_size = 0;
                    181:                return;
                    182:        }
                    183: }
                    184: 
                    185: File_read_result file_read_binary(const String& file_spec, bool fail_on_read_problem, char* buf, uint64_t offset, size_t limit) {
                    186:        File_read_result result = {false, 0, 0, 0};
                    187:        File_read_action_info info = {&result.str, &result.length, buf, offset, limit};
                    188: 
                    189:        result.success = file_read_action_under_lock(file_spec, "read", file_read_action, &info, 0, fail_on_read_problem);
                    190:        return result;
                    191: }
                    192: 
1.3       moko      193: File_read_result file_read(Request_charsets& charsets, const String& file_spec,
1.1       moko      194:                        bool as_text, HashStringValue *options,
                    195:                        bool fail_on_read_problem,
                    196:                        size_t offset = 0, size_t limit = 0, bool transcode_text_result = true) {
                    197:        File_read_result result = {false, 0, 0, 0};
                    198:        if(options){
                    199:                int valid_options = pa_get_valid_file_options_count(*options);
                    200:                if(valid_options != options->count())
                    201:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    202:        }
                    203: 
1.3       moko      204:        File_read_action_info info = {&result.str, &result.length, 0, offset, limit};
1.1       moko      205: 
1.3       moko      206:        result.success = file_read_action_under_lock(file_spec, "read", file_read_action, &info, as_text, fail_on_read_problem);
1.1       moko      207: 
                    208:        if(as_text){
                    209:                if(result.success){
                    210:                        Charset* asked_charset = 0;
                    211:                        if(options)
                    212:                                if(Value* vcharset_name = options->get(PA_CHARSET_NAME))
                    213:                                        asked_charset = &pa_charsets.get(vcharset_name->as_string());
                    214: 
                    215:                        asked_charset = pa_charsets.checkBOM(result.str, result.length, asked_charset);
                    216: 
                    217:                        if(result.length && transcode_text_result && asked_charset){ // length must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
                    218:                                String::C body = String::C(result.str, result.length);
                    219:                                body=Charset::transcode(body, *asked_charset, charsets.source());
                    220: 
                    221:                                result.str = const_cast<char*>(body.str); // hacking a little
                    222:                                result.length = body.length;
                    223:                        }
                    224:                }
                    225:                if(result.length)
                    226:                        fix_line_breaks(result.str, result.length);
                    227:        }
                    228: 
                    229:        return result;
                    230: }
                    231: 
1.3       moko      232: File_read_result file_load(Request& r, const String& file_spec,
1.1       moko      233:                        bool as_text, HashStringValue *options,
                    234:                        bool fail_on_read_problem,
                    235:                        bool transcode_text_result) {
                    236: 
                    237:        size_t offset = 0;
                    238:        size_t limit = 0;
                    239: 
                    240:        if(options){
                    241:                if(Value *voffset = (Value *)options->get(sql_offset_name))
                    242:                        offset = r.process(*voffset).as_int();
                    243:                if(Value *vlimit = (Value *)options->get(sql_limit_name))
                    244:                        limit = r.process(*vlimit).as_int();
                    245:                // no check on options count here
                    246:        }
                    247: 
                    248:        if(file_spec.starts_with("http://")) {
                    249:                if(offset || limit)
                    250:                        throw Exception(PARSER_RUNTIME, 0, "offset and load options are not supported for HTTP:// file load");
                    251: 
                    252:                // fail on read problem
                    253:                File_read_http_result http = pa_internal_file_read_http(r, file_spec, as_text, options, transcode_text_result);
                    254: 
                    255:                File_read_result result = {true, http.str, http.length, http.headers};
                    256:                return result;
                    257:        } else
                    258:                return file_read(r.charsets, file_spec, as_text, options, fail_on_read_problem, offset, limit, transcode_text_result);
                    259: }
                    260: 
                    261: char* file_read_text(Request_charsets& charsets, const String& file_spec, bool fail_on_read_problem) {
                    262:        File_read_result file = file_read(charsets, file_spec, true, 0, fail_on_read_problem);
                    263:        return file.success ? file.str : 0;
                    264: }
                    265: 
                    266: char* file_load_text(Request& r, const String& file_spec, bool fail_on_read_problem, HashStringValue* options, bool transcode_result) {
                    267:        File_read_result file = file_load(r, file_spec, true, options, fail_on_read_problem, transcode_result);
                    268:        return file.success ? file.str : 0;
                    269: }
                    270: 
                    271: #ifdef PA_SAFE_MODE
                    272: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
                    273:        if(finfo.st_uid/*foreign?*/!=geteuid()
                    274:                && finfo.st_gid/*foreign?*/!=getegid())
                    275:                throw Exception(PARSER_RUNTIME,
                    276:                        &file_spec,
                    277:                        "parser is in safe mode: reading files of foreign group and user disabled "
                    278:                        "[recompile parser with --disable-safe-mode configure option], "
                    279:                        "actual filename '%s', fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
                    280:                        fname, finfo.st_uid, geteuid(), finfo.st_gid, getegid()
                    281:                );
                    282: }
                    283: #else
                    284: void check_safe_mode(struct stat, const String&, const char*) {
                    285: }
                    286: #endif
                    287: 
                    288: 
                    289: bool file_read_action_under_lock(const String& file_spec, const char* action_name, File_read_action action, void *context,
                    290:                                bool as_text, bool fail_on_read_problem) {
                    291: 
                    292:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
                    293:        int f;
                    294: 
                    295:        // first open, next stat:
                    296:        // directory update of NTFS hard links performed on open.
1.3       moko      297:        // ex:
1.1       moko      298:        //   a.html:^test[] and b.html hardlink to a.html
                    299:        //   user inserts ! before ^test in a.html
1.3       moko      300:        //   directory entry of b.html in NTFS not updated at once,
1.1       moko      301:        //   they delay update till open, so we would receive "!^test[" string
                    302:        //   if would do stat, next open.
                    303:        // later: it seems, even this does not help sometimes
                    304:        if((f=pa_open(fname, O_RDONLY | (as_text ? _O_TEXT : _O_BINARY) ))>=0) {
                    305:                try {
                    306:                        int pa_errno=pa_lock_shared_blocking(f);
                    307:                        if(pa_errno!=0)
                    308:                                throw Exception("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(pa_errno), pa_errno, fname);
                    309: 
                    310:                        struct stat finfo;
                    311:                        if(pa_fstat(f, &finfo)!=0)
                    312:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    313:                                        &file_spec, "stat failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname);
                    314: 
                    315:                        check_safe_mode(finfo, file_spec, fname);
                    316: 
1.3       moko      317:                        action(finfo, f, file_spec, context);
1.1       moko      318:                } catch(...) {
1.3       moko      319:                        pa_unlock(f);close(f);
1.1       moko      320:                        if(fail_on_read_problem)
                    321:                                rethrow;
                    322:                        return false;
1.3       moko      323:                }
1.1       moko      324: 
1.3       moko      325:                pa_unlock(f);close(f);
1.1       moko      326:                return true;
                    327:        } else {
                    328:                if(fail_on_read_problem)
                    329:                        throw Exception(errno==EACCES ? "file.access" : (errno==ENOENT || errno==ENOTDIR || errno==ENODEV) ? "file.missing" : 0,
                    330:                                &file_spec, "%s failed: %s (%d), actual filename '%s'", action_name, strerror(errno), errno, fname);
                    331:                return false;
                    332:        }
                    333: }
                    334: 
                    335: void create_dir_for_file(const String& file_spec) {
                    336:        const char *str=file_spec.taint_cstr(String::L_FILE_SPEC);
                    337:        if(str[0]){
                    338:                const char *pos=str+1;
1.6       moko      339:                while((pos=strchr(pos, '/')) && pos[1]) { // to avoid trailing /, see #1166
1.1       moko      340:                        pa_mkdir(pa_strdup(str,pos-str), 0775);
                    341:                        pos++;
                    342:                }
                    343:        }
                    344: }
                    345: 
                    346: bool file_write_action_under_lock(const String& file_spec, const char* action_name, File_write_action action, void *context,
                    347:                                bool as_text, bool do_append, bool do_block, bool fail_on_lock_problem) {
                    348: 
                    349:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
                    350:        int f;
                    351:        if(access(fname, W_OK)!=0) // no
                    352:                create_dir_for_file(file_spec);
                    353: 
                    354:        if((f=pa_open(fname, O_CREAT | O_RDWR | (as_text ? _O_TEXT : _O_BINARY) | (do_append ? O_APPEND : PA_O_TRUNC), 0664))>=0) {
                    355:                int pa_errno=do_block ? pa_lock_exclusive_blocking(f) : pa_lock_exclusive_nonblocking(f);
                    356:                if(pa_errno!=0) {
                    357:                        Exception e("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(pa_errno), pa_errno, fname);
                    358:                        close(f);
                    359:                        if(fail_on_lock_problem)
                    360:                                throw e;
                    361:                        return false;
                    362:                }
                    363: 
                    364:                try {
                    365: #if (defined(HAVE_FCHMOD) && defined(PA_SAFE_MODE))
                    366:                        struct stat finfo;
                    367:                        if(pa_fstat(f, &finfo)==0 && finfo.st_mode & 0111)
                    368:                                fchmod(f, finfo.st_mode & 0666/*clear executable bits*/); // backward: ignore errors if any
                    369: #endif
                    370:                        action(f, context);
                    371:                } catch(...) {
                    372: #ifdef HAVE_FTRUNCATE
                    373:                        if(!do_append)
                    374:                                PA_UNUSED int ignore_result=ftruncate(f, lseek(f, 0, SEEK_CUR)); // one cannot use O_TRUNC, read lower
                    375: #endif
                    376:                        pa_unlock(f);close(f);
                    377:                        rethrow;
                    378:                }
                    379:                
                    380: #ifdef HAVE_FTRUNCATE
                    381:                if(!do_append)
                    382:                        PA_UNUSED int ignore_result=ftruncate(f, lseek(f, 0, SEEK_CUR)); // O_TRUNC truncates even exclusevely write-locked file [thanks to Igor Milyakov <virtan@rotabanner.com> for discovering]
                    383: #endif
                    384:                pa_unlock(f);close(f);
                    385:                return true;
                    386:        } else
                    387:                throw Exception(errno==EACCES ? "file.access" : 0, &file_spec, "%s failed: %s (%d), actual filename '%s'", action_name, strerror(errno), errno, fname);
                    388:        // here should be nothing, see rethrow above
                    389: }
                    390: 
                    391: #ifndef DOXYGEN
                    392: struct File_write_action_info {
                    393:        const char* str;
                    394:        size_t length;
                    395: };
                    396: #endif
                    397: 
                    398: // a single write() must stay below INT_MAX as windows _write() reports written bytes as int
                    399: #define FILE_WRITE_CHUNK_SIZE (256*0x100000)
                    400: 
                    401: static const char* bytes_left(size_t rest) {
                    402:        return rest ? pa_strcat(", ", pa_uitoa(rest), " bytes left") : "";
                    403: }
                    404: 
                    405: static void file_write_action(int f, void *context) {
                    406:        File_write_action_info& info=*static_cast<File_write_action_info *>(context);
                    407: 
                    408:        const char* data=info.str;
                    409:        size_t left=info.length;
                    410: 
                    411:        while(left) {
                    412:                size_t portion=min(left, (size_t)FILE_WRITE_CHUNK_SIZE);
                    413:                ssize_t written=write(f, data, portion);
                    414:                if(written<0)
                    415:                        throw Exception("file.write", 0, "error writing %s bytes: %s (%d)%s", pa_uitoa(portion), strerror(errno), errno, bytes_left(left-portion));
                    416:                if(written==0)
                    417:                        throw Exception("file.write", 0, "error writing %s bytes: zero bytes written%s", pa_uitoa(portion), bytes_left(left-portion));
                    418:                data+=written;
                    419:                left-=written;
                    420:        }
                    421: }
                    422: 
                    423: void file_write(
                    424:                                Request_charsets& charsets,
                    425:                                const String& file_spec,
                    426:                                const char* data,
1.3       moko      427:                                size_t size,
                    428:                                bool as_text,
1.1       moko      429:                                bool do_append,
                    430:                                Charset* asked_charset) {
                    431: 
                    432:        if(as_text && asked_charset){
                    433:                String::C body=String::C(data, size);
                    434:                body=Charset::transcode(body, charsets.source(), *asked_charset);
                    435:                data=body.str;
                    436:                size=body.length;
                    437:        };
                    438: 
                    439:        File_write_action_info info={data, size};
                    440: 
                    441:        file_write_action_under_lock(
                    442:                file_spec,
                    443:                "write",
                    444:                file_write_action,
                    445:                &info,
                    446:                as_text,
                    447:                do_append);
                    448: }
                    449: 
                    450: static size_t get_dir(char* fname, size_t helper_length){
                    451:        bool dir=false;
                    452:        size_t pos=0;
                    453:        for(pos=helper_length; pos; pos--){
                    454:                char c=fname[pos-1];
1.6       moko      455:                if(c=='/'){
1.1       moko      456:                        fname[pos-1]=0;
                    457:                        dir=true;
                    458:                } else if(dir) break;
                    459:        }
                    460:        return pos;
                    461: }
                    462: 
                    463: bool entry_exists(const char* fname, struct stat *afinfo) {
                    464:        struct stat lfinfo;
                    465:        bool result=pa_stat(fname, &lfinfo)==0;
                    466:        if(afinfo)
                    467:                *afinfo=lfinfo;
                    468:        return result;
                    469: }
                    470: 
                    471: bool entry_exists(const String& file_spec) {
1.3       moko      472:        return entry_exists(file_spec.taint_cstr(String::L_FILE_SPEC), 0);
1.1       moko      473: }
                    474: 
                    475: static bool entry_ifdir(char *fname, bool need_dir) {
                    476:        if(need_dir){
                    477:                size_t size=strlen(fname);
                    478:                while(size) {
                    479:                        char c=fname[size-1];
1.6       moko      480:                        if(c=='/')
1.1       moko      481:                                fname[--size]=0;
                    482:                        else
                    483:                                break;
                    484:                }
                    485:        }
                    486: 
                    487:        struct stat finfo;
                    488:        if(entry_exists(fname, &finfo)) {
                    489:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
                    490:                return is_dir==need_dir;
                    491:        }
                    492:        return false;
                    493: }
                    494: 
                    495: static bool entry_ifdir(const String& file_spec, bool need_dir) {
                    496:        return entry_ifdir(file_spec.taint_cstrm(String::L_FILE_SPEC), need_dir);
                    497: }
                    498: 
                    499: // throws nothing! [this is required in file_move & file_delete]
                    500: static void rmdir(const String& file_spec, size_t pos_after) {
                    501:        char* dir_spec=file_spec.taint_cstrm(String::L_FILE_SPEC);
                    502:        size_t length=strlen(dir_spec);
                    503:        while( (length=get_dir(dir_spec, length)) && (length > pos_after) ){
                    504: #ifdef _MSC_VER
                    505:                if(!entry_ifdir(dir_spec, true))
                    506:                        break;
                    507:                DWORD attrs=GetFileAttributesW(PA_UTF16_ENC(dir_spec));
                    508:                if(
                    509:                        (attrs==INVALID_FILE_ATTRIBUTES)
                    510:                        || !(attrs & FILE_ATTRIBUTE_DIRECTORY)
                    511:                        || (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
                    512:                )
                    513:                        break;
                    514: #endif
                    515:                if(pa_rmdir(dir_spec))
                    516:                        break;
                    517:        };
                    518: }
                    519: 
                    520: bool file_delete(const String& file_spec, bool fail_on_problem, bool keep_empty_dirs) {
1.3       moko      521:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.1       moko      522:        if(pa_unlink(fname)!=0) {
                    523:                if(fail_on_problem)
                    524:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
                    525:                                &file_spec, "unlink failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname);
                    526:                else
                    527:                        return false;
                    528:        }
                    529: 
                    530:        if(!keep_empty_dirs)
1.3       moko      531:                rmdir(file_spec, 1);
1.1       moko      532: 
                    533:        return true;
                    534: }
                    535: 
                    536: void file_move(const String& old_spec, const String& new_spec, bool keep_empty_dirs) {
1.3       moko      537:        const char* old_spec_cstr=old_spec.taint_cstr(String::L_FILE_SPEC);
                    538:        const char* new_spec_cstr=new_spec.taint_cstr(String::L_FILE_SPEC);
1.1       moko      539:        
1.3       moko      540:        create_dir_for_file(new_spec);
1.1       moko      541: 
                    542:        if(pa_rename(old_spec_cstr, new_spec_cstr)!=0)
                    543:                throw Exception(errno==EACCES ? "file.access" : errno==ENOENT ? "file.missing" : 0,
                    544:                        &old_spec, "rename failed: %s (%d), actual filename '%s' to '%s'", strerror(errno), errno, old_spec_cstr, new_spec_cstr);
                    545: 
                    546:        if(!keep_empty_dirs)
1.3       moko      547:                rmdir(old_spec, 1);
1.1       moko      548: }
                    549: 
                    550: 
                    551: bool file_exist(const String& file_spec) {
1.3       moko      552:        return entry_ifdir(file_spec, false);
1.1       moko      553: }
                    554: 
                    555: bool dir_exists(const String& file_spec) {
1.3       moko      556:        return entry_ifdir(file_spec, true);
1.1       moko      557: }
                    558: 
                    559: const String* file_exist(const String& path, const String& name) {
                    560:        String& result=*new String(path);
1.6       moko      561:        if(path.last_char() != '/')
1.1       moko      562:                result << "/";
                    563:        result << name;
                    564:        return file_exist(result)?&result:0;
                    565: }
                    566: 
                    567: bool file_executable(const String& file_spec) {
                    568:        return access(file_spec.taint_cstr(String::L_FILE_SPEC), X_OK)==0;
                    569: }
                    570: 
                    571: bool file_stat(const String& file_spec, uint64_t& rsize, time_t& ratime, time_t& rmtime, time_t& rctime, bool fail_on_read_problem) {
1.3       moko      572:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.1       moko      573:        struct stat finfo;
                    574:        if(pa_stat(fname, &finfo)!=0) {
                    575:                if(fail_on_read_problem)
                    576:                        throw Exception("file.missing", &file_spec, "getting file size failed: %s (%d), real filename '%s'", strerror(errno), errno, fname);
                    577:                else
                    578:                        return false;
                    579:        }
                    580:        rsize=finfo.st_size;
                    581:        ratime=(time_t)finfo.st_atime;
                    582:        rmtime=(time_t)finfo.st_mtime;
                    583:        rctime=(time_t)finfo.st_ctime;
                    584:        return true;
                    585: }
                    586: 
                    587: size_t check_file_size(uint64_t size, const String* file_spec){
                    588:        if(size > (uint64_t)pa_file_size_limit)
1.2       moko      589:                throw Exception(PARSER_RUNTIME, file_spec, "content size of %s bytes exceeds the limit (%s bytes)", pa_uitoa(size), pa_uitoa(pa_file_size_limit));
1.1       moko      590:        return (size_t)size;
                    591: }
                    592: 
1.3       moko      593: /**
1.1       moko      594:        String related functions
                    595: */
                    596: 
                    597: const char *pa_filename(const char *path){
                    598:        const char *slash=strrpbrk(path, "/\\");
                    599:        return slash ? slash+1 : path;
                    600: }

E-mail: