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

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

E-mail: