--- parser3/src/main/pa_common.C 2020/11/16 14:52:18 1.314 +++ parser3/src/main/pa_common.C 2026/04/25 13:38:46 1.343 @@ -1,18 +1,18 @@ /** @file Parser: commonly functions. - Copyright (c) 2000-2017 Art. Lebedev Studio (http://www.artlebedev.com) - Author: Alexandr Petrosian (http://paf.design.ru) + Copyright (c) 2000-2026 Art. Lebedev Studio (https://www.artlebedev.com) + Authors: Konstantin Morshnev , Alexandr Petrosian */ #include "pa_common.h" #include "pa_exception.h" #include "pa_hash.h" +#include "pa_inline_hash.h" #include "pa_globals.h" #include "pa_charsets.h" #include "pa_http.h" #include "pa_request_charsets.h" -#include "pcre.h" #include "pa_request.h" #include "pa_idna.h" @@ -23,13 +23,7 @@ #include #endif -#ifdef _MSC_VER -#define pa_mkdir(path, mode) _mkdir(path) -#else -#define pa_mkdir(path, mode) mkdir(path, mode) -#endif - -volatile const char * IDENT_PA_COMMON_C="$Id: pa_common.C,v 1.314 2020/11/16 14:52:18 moko Exp $" IDENT_PA_COMMON_H IDENT_PA_HASH_H IDENT_PA_ARRAY_H IDENT_PA_STACK_H; +volatile const char * IDENT_PA_COMMON_C="$Id: pa_common.C,v 1.343 2026/04/25 13:38:46 moko Exp $" IDENT_PA_COMMON_H IDENT_PA_HASH_H IDENT_PA_INLINE_HASH_H IDENT_PA_ARRAY_H IDENT_PA_STACK_H; // some maybe-undefined constants @@ -73,22 +67,43 @@ const UTF16* pa_utf16_encode(const char* #ifdef _MSC_VER +#define PA_UTF16_ENC(value) (const wchar_t *)pa_utf16_encode(value, pa_thread_request().charsets.source()) + int pa_stat(const char *pathname, struct stat *buffer){ - const UTF16* utf16name=pa_utf16_encode(pathname, pa_thread_request().charsets.source()); - return _wstat64((const wchar_t *)utf16name, buffer); + return _wstat64(PA_UTF16_ENC(pathname), buffer); } int pa_open(const char *pathname, int flags, int mode){ - const UTF16* utf16name=pa_utf16_encode(pathname, pa_thread_request().charsets.source()); - return _wopen((const wchar_t *)utf16name, flags, mode); + return _wopen(PA_UTF16_ENC(pathname), flags, mode); } FILE *pa_fopen(const char *pathname, const char *mode){ - const UTF16* utf16name=pa_utf16_encode(pathname, pa_thread_request().charsets.source()); - const UTF16* utf16mode=pa_utf16_encode(mode, pa_thread_request().charsets.source()); - return _wfopen((const wchar_t *)utf16name, (const wchar_t *)utf16mode); + return _wfopen(PA_UTF16_ENC(pathname), PA_UTF16_ENC(mode)); +} + +int pa_mkdir(const char *pathname, int){ + return _wmkdir(PA_UTF16_ENC(pathname)); } +int pa_rmdir(const char *pathname){ + return _wrmdir(PA_UTF16_ENC(pathname)); +} + +int pa_rename(const char *oldpath, const char *newpath){ + return _wrename(PA_UTF16_ENC(oldpath), PA_UTF16_ENC(newpath)); +} + +int pa_unlink(const char *pathname){ + return _wunlink(PA_UTF16_ENC(pathname)); +} + +#else + +#define pa_mkdir mkdir +#define pa_rmdir rmdir +#define pa_rename rename +#define pa_unlink unlink + #endif /// these options were handled but not checked elsewhere, now check them @@ -110,18 +125,16 @@ int pa_get_valid_file_options_count(Hash #ifndef DOXYGEN struct File_read_action_info { char **data; size_t *data_size; - char* buf; size_t offset; size_t limit; + char* buf; uint64_t offset; size_t limit; }; #endif static void file_read_action(struct stat& finfo, int f, const String& file_spec, void *context) { File_read_action_info& info = *static_cast(context); - size_t to_read_size = info.limit; - if(!to_read_size) - to_read_size = check_file_size(finfo.st_size, &file_spec); + 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); if(to_read_size) { if(info.offset) - lseek(f, info.offset, SEEK_SET); + pa_lseek(f, info.offset, SEEK_SET); // seek never fails as POSIX allows the file offset to be set beyond the EOF *info.data = info.buf ? info.buf : (char *)pa_malloc_atomic(to_read_size+1); ssize_t result = read(f, *info.data, to_read_size); if(result<0) @@ -136,7 +149,7 @@ static void file_read_action(struct stat } } -File_read_result file_read_binary(const String& file_spec, bool fail_on_read_problem, char* buf, size_t offset, size_t limit) { +File_read_result file_read_binary(const String& file_spec, bool fail_on_read_problem, char* buf, uint64_t offset, size_t limit) { File_read_result result = {false, 0, 0, 0}; File_read_action_info info = {&result.str, &result.length, buf, offset, limit}; @@ -240,12 +253,10 @@ void check_safe_mode(struct stat, const #endif +bool file_read_action_under_lock(const String& file_spec, const char* action_name, File_read_action action, void *context, + bool as_text, bool fail_on_read_problem) { -bool file_read_action_under_lock(const String& file_spec, - const char* action_name, File_read_action action, void *context, - bool as_text, - bool fail_on_read_problem) { - const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); + const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); int f; // first open, next stat: @@ -257,10 +268,11 @@ bool file_read_action_under_lock(const S // they delay update till open, so we would receive "!^test[" string // if would do stat, next open. // later: it seems, even this does not help sometimes - if((f=pa_open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) { + if((f=pa_open(fname, O_RDONLY | (as_text ? _O_TEXT : _O_BINARY) ))>=0) { try { - if(pa_lock_shared_blocking(f)!=0) - throw Exception("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname); + int pa_errno=pa_lock_shared_blocking(f); + if(pa_errno!=0) + throw Exception("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(pa_errno), pa_errno, fname); struct stat finfo; if(pa_fstat(f, &finfo)!=0) @@ -288,35 +300,29 @@ bool file_read_action_under_lock(const S } void create_dir_for_file(const String& file_spec) { - size_t pos_after=1; - size_t pos_before; - while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) { - pa_mkdir(file_spec.mid(0, pos_before).taint_cstr(String::L_FILE_SPEC), 0775); - pos_after=pos_before+1; + const char *str=file_spec.taint_cstr(String::L_FILE_SPEC); + if(str[0]){ + const char *pos=str+1; + while((pos=strpbrk(pos, "/\\")) && pos[1]) { // to avoid trailing /, see #1166 + pa_mkdir(pa_strdup(str,pos-str), 0775); + pos++; + } } } -bool file_write_action_under_lock( - const String& file_spec, - const char* action_name, - File_write_action action, - void *context, - bool as_text, - bool do_append, - bool do_block, - bool fail_on_lock_problem) { +bool file_write_action_under_lock(const String& file_spec, const char* action_name, File_write_action action, void *context, + bool as_text, bool do_append, bool do_block, bool fail_on_lock_problem) { + const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); int f; if(access(fname, W_OK)!=0) // no create_dir_for_file(file_spec); - if((f=pa_open(fname, - O_CREAT|O_RDWR - |(as_text?_O_TEXT:_O_BINARY) - |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) { - if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) { - Exception e("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname); - close(f); + if((f=pa_open(fname, O_CREAT | O_RDWR | (as_text ? _O_TEXT : _O_BINARY) | (do_append ? O_APPEND : PA_O_TRUNC), 0664))>=0) { + int pa_errno=do_block ? pa_lock_exclusive_blocking(f) : pa_lock_exclusive_nonblocking(f); + if(pa_errno!=0) { + Exception e("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(pa_errno), pa_errno, fname); + close(f); if(fail_on_lock_problem) throw e; return false; @@ -332,17 +338,17 @@ bool file_write_action_under_lock( } catch(...) { #ifdef HAVE_FTRUNCATE if(!do_append) - ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower + PA_UNUSED int ignore_result=ftruncate(f, lseek(f, 0, SEEK_CUR)); // one cannot use O_TRUNC, read lower #endif - pa_unlock(f);close(f); + pa_unlock(f);close(f); rethrow; } #ifdef HAVE_FTRUNCATE if(!do_append) - ftruncate(f, lseek(f, 0, SEEK_CUR)); // O_TRUNC truncates even exclusevely write-locked file [thanks to Igor Milyakov for discovering] + PA_UNUSED int ignore_result=ftruncate(f, lseek(f, 0, SEEK_CUR)); // O_TRUNC truncates even exclusevely write-locked file [thanks to Igor Milyakov for discovering] #endif - pa_unlock(f);close(f); + pa_unlock(f);close(f); return true; } else throw Exception(errno==EACCES ? "file.access" : 0, &file_spec, "%s failed: %s (%d), actual filename '%s'", action_name, strerror(errno), errno, fname); @@ -451,7 +457,7 @@ static void rmdir(const String& file_spe #ifdef _MSC_VER if(!entry_ifdir(dir_spec, true)) break; - DWORD attrs=GetFileAttributes(dir_spec); + DWORD attrs=GetFileAttributesW(PA_UTF16_ENC(dir_spec)); if( (attrs==INVALID_FILE_ATTRIBUTES) || !(attrs & FILE_ATTRIBUTE_DIRECTORY) @@ -459,14 +465,14 @@ static void rmdir(const String& file_spe ) break; #endif - if( rmdir(dir_spec) ) + if(pa_rmdir(dir_spec)) break; }; } bool file_delete(const String& file_spec, bool fail_on_problem, bool keep_empty_dirs) { const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); - if(unlink(fname)!=0) { + if(pa_unlink(fname)!=0) { if(fail_on_problem) throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, &file_spec, "unlink failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname); @@ -486,7 +492,7 @@ void file_move(const String& old_spec, c create_dir_for_file(new_spec); - if(rename(old_spec_cstr, new_spec_cstr)!=0) + if(pa_rename(old_spec_cstr, new_spec_cstr)!=0) throw Exception(errno==EACCES ? "file.access" : errno==ENOENT ? "file.missing" : 0, &old_spec, "rename failed: %s (%d), actual filename '%s' to '%s'", strerror(errno), errno, old_spec_cstr, new_spec_cstr); @@ -532,7 +538,7 @@ bool file_stat(const String& file_spec, } size_t check_file_size(uint64_t size, const String* file_spec){ - if(size > pa_file_size_limit) + if(size > (uint64_t)pa_file_size_limit) throw Exception(PARSER_RUNTIME, file_spec, "content size of %.15g bytes exceeds the limit (%.15g bytes)", (double)size, (double)pa_file_size_limit); return (size_t)size; } @@ -566,15 +572,15 @@ const char* capitalize(const char* s){ return (const char*)result; } -char *str_lower(const char *s, size_t helper_length){ - char *result=pa_strdup(s, helper_length); +char *str_lower(const char *s, size_t length){ + char *result=pa_strdup(s, length); for(char* c=result; *c; c++) *c=(char)tolower((unsigned char)*c); return result; } -char *str_upper(const char *s, size_t helper_length){ - char *result=pa_strdup(s, helper_length); +char *str_upper(const char *s, size_t length){ + char *result=pa_strdup(s, length); for(char* c=result; *c; c++) *c=(char)toupper((unsigned char)*c); return result; @@ -654,12 +660,25 @@ char* rsplit(char* string, char delim) { return NULL; } +void pa_strncpy(char *dst, const char *src, size_t n){ + size_t left = n; + + if (left != 0 && src) { + while (--left != 0) { + if ((*dst++ = *src++) == '\0') + return; + } + } + if (n != 0) + *dst = '\0'; +} + #define STRCAT_STEP(str, len) if(str) { memcpy(ptr, str, len); ptr += len; } char *pa_strcat(const char *a, const char *b, const char *c) { size_t len_a = a ? strlen(a) : 0; - size_t len_b = a ? strlen(b) : 0; - size_t len_c = a ? strlen(c) : 0; + size_t len_b = b ? strlen(b) : 0; + size_t len_c = c ? strlen(c) : 0; char *result=new(PointerFreeGC) char[len_a + len_b + len_c +1/*0*/]; char *ptr=result; STRCAT_STEP(a, len_a); @@ -669,119 +688,39 @@ char *pa_strcat(const char *a, const cha return result; } - -// format: %[flags][width][.precision]type http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx -// flags: '-', '+', ' ', '#', '0' http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx -// width, precision: non negative decimal number -enum FormatType { - FormatInvalid, - FormatInt, - FormatUInt, - FormatDouble -}; -FormatType format_type(const char* fmt){ - enum FormatState { - Percent, - Flags, - Width, - Precision, - Done - } state=Percent; - - FormatType result=FormatInvalid; - - const char* pos=fmt; - while(char c=*(pos++)){ - switch(state){ - case Percent: - if(c=='%'){ - state=Flags; - } else { - return FormatInvalid; // 1st char must be '%' only - } - break; - case Flags: - if(strchr("-+ #0", c)!=0){ - break; - } - // go to the next step - case Width: - if(c=='.'){ - state=Precision; - break; - } - // go to the next step - case Precision: - if(c>='0' && c<='9'){ - if(state == Flags) state=Width; // no more flags - break; - } else if(c=='d' || c=='i'){ - result=FormatInt; - } else if(strchr("feEgG", c)!=0){ - result=FormatDouble; - } else if(strchr("uoxX", c)!=0){ - result=FormatUInt; - } else { - return FormatInvalid; // invalid char - } - state=Done; - break; - case Done: - return FormatInvalid; // no chars allowed after 'type' - } - } - return result; -} - - -const char* format(double value, const char* fmt) { - char local_buf[MAX_NUMBER]; - int size=-1; - - if(fmt && strlen(fmt)){ - switch(format_type(fmt)){ - case FormatDouble: - size=snprintf(local_buf, sizeof(local_buf), fmt, value); - break; - case FormatInt: - size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); - break; - case FormatUInt: - size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); - break; - case FormatInvalid: - throw Exception(PARSER_RUNTIME, 0, "Incorrect format string '%s' was specified.", fmt); - } - } else - size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value); - - if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing - throw Exception(PARSER_RUNTIME, 0, "Error occurred white executing snprintf with format string '%s'.", fmt); - } - - return pa_strdup(local_buf, (size_t)size); +const char *pa_filename(const char *path){ + if(!path) + return NULL; + for(const char *c = path + strlen(path) - 1; c >= path; c--) { + if(*c == '/' || *c == '\\') + return c+1; + } + return path; } size_t stdout_write(const void *buf, size_t size) { #ifdef WIN32 size_t to_write = size; do{ - int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); + int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); if(chunk_written<=0) break; size-=chunk_written; buf=((const char*)buf)+chunk_written; - } while(size>0); + } while(size>0); + fflush(stdout); return to_write-size; #else - return fwrite(buf, 1, size, stdout); + size_t result=fwrite(buf, 1, size, stdout); + fflush(stdout); + return result; #endif } enum EscapeState { - EscapeRest, - EscapeFirst, + EscapeRest, + EscapeFirst, EscapeSecond, EscapeUnicode }; @@ -789,7 +728,7 @@ enum EscapeState { // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually) char* unescape_chars(const char* cp, int len, Charset* charset, bool js){ char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes) - char* dst=s; + XMLByte* dst=(XMLByte *)s; EscapeState escapeState=EscapeRest; uint escapedValue=0; int srcPos=0; @@ -835,7 +774,7 @@ char* unescape_chars(const char* cp, int escapedValue=(escapedValue << 4) + hex_value[c]; if(++jsCnt==4){ // transcode utf8 char to client charset (we can lost some chars here) - charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?'); + charset->store_Char(dst, (XMLCh)escapedValue, '?'); escapeState=EscapeRest; } } else { @@ -887,7 +826,7 @@ size_t strpos(const char *str, const cha return (p==0)?STRING_NOT_FOUND:p-str; } -int remove_crlf(char* start, char* end) { +size_t remove_crlf(char* start, char* end) { char* from=start; char* to=start; bool skip=false; @@ -933,8 +872,8 @@ const char* hex_string(unsigned char* by return bytes_hex; } -int file_block_read(const int f, unsigned char* buffer, const size_t size){ - int nCount = read(f, buffer, size); +ssize_t file_block_read(const int f, void* buffer, const size_t size){ + ssize_t nCount = read(f, buffer, size); if (nCount < 0) throw Exception("file.read", 0, "read failed: %s (%d)", strerror(errno), errno); return nCount;