/* Barracuda App Server Amalgamated This file is an amalgamation of many separate C source files from the Barracuda App Server (BAS) library. By combining all the individual C code files into this single large file, the entire code can be compiled as a single unit. This file is easy to compile, but very difficult to read. Contact Real Time Logic should you require the full (standard) source code. The amalgamation includes the following components: 1: Lua (MIT License) 2: ZLIB (zlib License) 3: BAS-Amalgamated (GPLv2, or custom; See LICENSE file) Ref: https://realtimelogic.com/products/barracuda-application-server/ */ /* Set USE_BA_LUA=0 if you do not want to use the embedded Lua version */ #ifndef USE_BA_LUA #define USE_BA_LUA 1 #endif #ifdef _WIN32 #else /* _WIN32 */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #endif /* _WIN32 */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Wchar-subscripts" #ifndef __clang__ #pragma GCC diagnostic ignored "-Wimplicit-fallthrough=" #endif #pragma GCC diagnostic ignored "-Wmisleading-indentation" #endif #ifdef MAKO #include /* Not implemented */ void sendFatalError(const char* eMsg, BaFatalErrorCodes ecode1, unsigned int ecode2, const char* file, int line) { (void)eMsg; (void)ecode1; (void)ecode2; (void)file; (void)line; } #endif #include #include /******************************* BEGIN LUA ***********************************/ #if USE_BA_LUA typedef struct CallInfo CallInfo; /* ** $Id: llimits.h $ ** Limits, basic types, and some other 'installation-dependent' definitions ** See Copyright Notice in lua.h */ #ifndef llimits_h #define llimits_h #include #include #include "lua.h" #define l_numbits(t) cast_int(sizeof(t) * CHAR_BIT) /* ** 'l_mem' is a signed integer big enough to count the total memory ** used by Lua. (It is signed due to the use of debt in several ** computations.) 'lu_mem' is a corresponding unsigned type. Usually, ** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines. */ #if defined(LUAI_MEM) /* { external definitions? */ typedef LUAI_MEM l_mem; typedef LUAI_UMEM lu_mem; #elif LUAI_IS32INT /* }{ */ typedef ptrdiff_t l_mem; typedef size_t lu_mem; #else /* 16-bit ints */ /* }{ */ typedef long l_mem; typedef unsigned long lu_mem; #endif /* } */ #define MAX_LMEM \ cast(l_mem, (cast(lu_mem, 1) << (l_numbits(l_mem) - 1)) - 1) /* chars used as small naturals (so that 'char' is reserved for characters) */ typedef unsigned char lu_byte; typedef signed char ls_byte; /* Type for thread status/error codes */ typedef lu_byte TStatus; /* The C API still uses 'int' for status/error codes */ #define APIstatus(st) cast_int(st) /* maximum value for size_t */ #define MAX_SIZET ((size_t)(~(size_t)0)) /* ** Maximum size for strings and userdata visible for Lua; should be ** representable as a lua_Integer and as a size_t. */ #define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \ : cast_sizet(LUA_MAXINTEGER)) /* ** test whether an unsigned value is a power of 2 (or zero) */ #define ispow2(x) (((x) & ((x) - 1)) == 0) /* number of chars of a literal string without the ending \0 */ #define LL(x) (sizeof(x)/sizeof(char) - 1) /* ** conversion of pointer to unsigned integer: this is for hashing only; ** there is no problem if the integer cannot hold the whole pointer ** value. (In strict ISO C this may cause undefined behavior, but no ** actual machine seems to bother.) */ #if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ __STDC_VERSION__ >= 199901L #include #if defined(UINTPTR_MAX) /* even in C99 this type is optional */ #define L_P2I uintptr_t #else /* no 'intptr'? */ #define L_P2I uintmax_t /* use the largest available integer */ #endif #else /* C89 option */ #define L_P2I size_t #endif #define point2uint(p) cast_uint((L_P2I)(p) & UINT_MAX) /* types of 'usual argument conversions' for lua_Number and lua_Integer */ typedef LUAI_UACNUMBER l_uacNumber; typedef LUAI_UACINT l_uacInt; /* ** Internal assertions for in-house debugging */ #if defined LUAI_ASSERT #undef NDEBUG #include #define lua_assert(c) assert(c) #define assert_code(c) c #endif #if defined(lua_assert) #else #define lua_assert(c) ((void)0) #define assert_code(c) ((void)0) #endif #define check_exp(c,e) (lua_assert(c), (e)) /* to avoid problems with conditions too long */ #define lua_longassert(c) assert_code((c) ? (void)0 : lua_assert(0)) /* macro to avoid warnings about unused variables */ #if !defined(UNUSED) #define UNUSED(x) ((void)(x)) #endif /* type casts (a macro highlights casts in the code) */ #define cast(t, exp) ((t)(exp)) #define cast_void(i) cast(void, (i)) #define cast_voidp(i) cast(void *, (i)) #define cast_num(i) cast(lua_Number, (i)) #define cast_int(i) cast(int, (i)) #define cast_short(i) cast(short, (i)) #define cast_uint(i) cast(unsigned int, (i)) #define cast_byte(i) cast(lu_byte, (i)) #define cast_uchar(i) cast(unsigned char, (i)) #define cast_char(i) cast(char, (i)) #define cast_charp(i) cast(char *, (i)) #define cast_sizet(i) cast(size_t, (i)) #define cast_Integer(i) cast(lua_Integer, (i)) #define cast_Inst(i) cast(Instruction, (i)) /* cast a signed lua_Integer to lua_Unsigned */ #if !defined(l_castS2U) #define l_castS2U(i) ((lua_Unsigned)(i)) #endif /* ** cast a lua_Unsigned to a signed lua_Integer; this cast is ** not strict ISO C, but two-complement architectures should ** work fine. */ #if !defined(l_castU2S) #define l_castU2S(i) ((lua_Integer)(i)) #endif /* ** cast a size_t to lua_Integer: These casts are always valid for ** sizes of Lua objects (see MAX_SIZE) */ #define cast_st2S(sz) ((lua_Integer)(sz)) /* Cast a ptrdiff_t to size_t, when it is known that the minuend ** comes from the subtrahend (the base) */ #define ct_diff2sz(df) ((size_t)(df)) /* ptrdiff_t to lua_Integer */ #define ct_diff2S(df) cast_st2S(ct_diff2sz(df)) /* ** Special type equivalent to '(void*)' for functions (to suppress some ** warnings when converting function pointers) */ typedef void (*voidf)(void); /* ** Macro to convert pointer-to-void* to pointer-to-function. This cast ** is undefined according to ISO C, but POSIX assumes that it works. ** (The '__extension__' in gnu compilers is only to avoid warnings.) */ #if defined(__GNUC__) #define cast_func(p) (__extension__ (voidf)(p)) #else #define cast_func(p) ((voidf)(p)) #endif /* ** non-return type */ #if !defined(l_noret) #if defined(__GNUC__) #define l_noret void __attribute__((noreturn)) #elif defined(_MSC_VER) && _MSC_VER >= 1200 #define l_noret void __declspec(noreturn) #else #define l_noret void #endif #endif /* ** Inline functions */ #if !defined(LUA_USE_C89) #define l_inline inline #elif defined(__GNUC__) #define l_inline __inline__ #else #define l_inline /* empty */ #endif #define l_sinline static l_inline /* ** An unsigned with (at least) 4 bytes */ #if LUAI_IS32INT typedef unsigned int l_uint32; #else typedef unsigned long l_uint32; #endif /* ** The luai_num* macros define the primitive operations over numbers. */ /* floor division (defined as 'floor(a/b)') */ #if !defined(luai_numidiv) #define luai_numidiv(L,a,b) ((void)L, l_floor(luai_numdiv(L,a,b))) #endif /* float division */ #if !defined(luai_numdiv) #define luai_numdiv(L,a,b) ((a)/(b)) #endif /* ** modulo: defined as 'a - floor(a/b)*b'; the direct computation ** using this definition has several problems with rounding errors, ** so it is better to use 'fmod'. 'fmod' gives the result of ** 'a - trunc(a/b)*b', and therefore must be corrected when ** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a ** non-integer negative result: non-integer result is equivalent to ** a non-zero remainder 'm'; negative result is equivalent to 'a' and ** 'b' with different signs, or 'm' and 'b' with different signs ** (as the result 'm' of 'fmod' has the same sign of 'a'). */ #if !defined(luai_nummod) #define luai_nummod(L,a,b,m) \ { (void)L; (m) = l_mathop(fmod)(a,b); \ if (((m) > 0) ? (b) < 0 : ((m) < 0 && (b) > 0)) (m) += (b); } #endif /* exponentiation */ #if !defined(luai_numpow) #define luai_numpow(L,a,b) \ ((void)L, (b == 2) ? (a)*(a) : l_mathop(pow)(a,b)) #endif /* the others are quite standard operations */ #if !defined(luai_numadd) #define luai_numadd(L,a,b) ((a)+(b)) #define luai_numsub(L,a,b) ((a)-(b)) #define luai_nummul(L,a,b) ((a)*(b)) #define luai_numunm(L,a) (-(a)) #define luai_numeq(a,b) ((a)==(b)) #define luai_numlt(a,b) ((a)<(b)) #define luai_numle(a,b) ((a)<=(b)) #define luai_numgt(a,b) ((a)>(b)) #define luai_numge(a,b) ((a)>=(b)) #define luai_numisnan(a) (!luai_numeq((a), (a))) #endif /* ** lua_numbertointeger converts a float number with an integral value ** to an integer, or returns 0 if the float is not within the range of ** a lua_Integer. (The range comparisons are tricky because of ** rounding. The tests here assume a two-complement representation, ** where MININTEGER always has an exact representation as a float; ** MAXINTEGER may not have one, and therefore its conversion to float ** may have an ill-defined value.) */ #define lua_numbertointeger(n,p) \ ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ (*(p) = (LUA_INTEGER)(n), 1)) /* ** LUAI_FUNC is a mark for all extern functions that are not to be ** exported to outside modules. ** LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables, ** none of which to be exported to outside modules (LUAI_DDEF for ** definitions and LUAI_DDEC for declarations). ** Elf and MACH/gcc (versions 3.2 and later) mark them as "hidden" to ** optimize access when Lua is compiled as a shared library. Not all elf ** targets support this attribute. Unfortunately, gcc does not offer ** a way to check whether the target offers that support, and those ** without support give a warning about it. To avoid these warnings, ** change to the default definition. */ #if !defined(LUAI_FUNC) #if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ (defined(__ELF__) || defined(__MACH__)) #define LUAI_FUNC __attribute__((visibility("internal"))) extern #else #define LUAI_FUNC extern #endif #define LUAI_DDEC(dec) LUAI_FUNC dec #define LUAI_DDEF /* empty */ #endif /* Give these macros simpler names for internal use */ #define l_likely(x) luai_likely(x) #define l_unlikely(x) luai_unlikely(x) /* ** {================================================================== ** "Abstraction Layer" for basic report of messages and errors ** =================================================================== */ /* print a string */ #if !defined(lua_writestring) #define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) #endif /* print a newline and flush the output */ #if !defined(lua_writeline) #define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) #endif /* print an error message */ #if !defined(lua_writestringerror) #define lua_writestringerror(s,p) \ (fprintf(stderr, (s), (p)), fflush(stderr)) #endif /* }================================================================== */ #endif /* ** $Id: lobject.h $ ** Type definitions for Lua objects ** See Copyright Notice in lua.h */ #ifndef lobject_h #define lobject_h #include #include "lua.h" /* ** Extra types for collectable non-values */ #define LUA_TUPVAL LUA_NUMTYPES /* upvalues */ #define LUA_TPROTO (LUA_NUMTYPES+1) /* function prototypes */ #define LUA_TDEADKEY (LUA_NUMTYPES+2) /* removed keys in tables */ /* ** number of all possible types (including LUA_TNONE but excluding DEADKEY) */ #define LUA_TOTALTYPES (LUA_TPROTO + 2) /* ** tags for Tagged Values have the following use of bits: ** bits 0-3: actual tag (a LUA_T* constant) ** bits 4-5: variant bits ** bit 6: whether value is collectable */ /* add variant bits to a type */ #define makevariant(t,v) ((t) | ((v) << 4)) /* ** Union of all Lua values */ typedef union LuaValue { struct GCObject *gc; /* collectable objects */ void *p; /* light userdata */ lua_CFunction f; /* light C functions */ lua_Integer i; /* integer numbers */ lua_Number n; /* float numbers */ /* not used, but may avoid warnings for uninitialized value */ lu_byte ub; } LuaValue; /* ** Tagged Values. This is the basic representation of values in Lua: ** an actual value plus a tag with its type. */ #define TValuefields LuaValue value_; lu_byte tt_ typedef struct TValue { TValuefields; } TValue; #define val_(o) ((o)->value_) #define valraw(o) (val_(o)) /* raw type tag of a TValue */ #define rawtt(o) ((o)->tt_) /* tag with no variants (bits 0-3) */ #define novariant(t) ((t) & 0x0F) /* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */ #define withvariant(t) ((t) & 0x3F) #define ttypetag(o) withvariant(rawtt(o)) /* type of a TValue */ #define ttype(o) (novariant(rawtt(o))) /* Macros to test type */ #define checktag(o,t) (rawtt(o) == (t)) #define checktype(o,t) (ttype(o) == (t)) /* Macros for internal tests */ /* collectable object has the same tag as the original value */ #define righttt(obj) (ttypetag(obj) == gcvalue(obj)->tt) /* ** Any value being manipulated by the program either is non ** collectable, or the collectable object has the right tag ** and it is not dead. The option 'L == NULL' allows other ** macros using this one to be used where L is not available. */ #define checkliveness(L,obj) \ ((void)L, lua_longassert(!iscollectable(obj) || \ (righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)))))) /* Macros to set values */ /* set a value's tag */ #define settt_(o,t) ((o)->tt_=(t)) /* main macro to copy values (from 'obj2' to 'obj1') */ #define setobj(L,obj1,obj2) \ { TValue *io1=(obj1); const TValue *io2=(obj2); \ io1->value_ = io2->value_; settt_(io1, io2->tt_); \ checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); } /* ** Different types of assignments, according to source and destination. ** (They are mostly equal now, but may be different in the future.) */ /* from stack to stack */ #define setobjs2s(L,o1,o2) setobj(L,s2v(o1),s2v(o2)) /* to stack (not from same stack) */ #define setobj2s(L,o1,o2) setobj(L,s2v(o1),o2) /* from table to same table */ #define setobjt2t setobj /* to new object */ #define setobj2n setobj /* to table */ #define setobj2t setobj /* ** Entries in a Lua stack. Field 'tbclist' forms a list of all ** to-be-closed variables active in this stack. Dummy entries are ** used when the distance between two tbc variables does not fit ** in an unsigned short. They are represented by delta==0, and ** their real delta is always the maximum value that fits in ** that field. */ typedef union StackValue { TValue val; struct { TValuefields; unsigned short delta; } tbclist; } StackValue; /* index to stack elements */ typedef StackValue *StkId; /* ** When reallocating the stack, change all pointers to the stack into ** proper offsets. */ typedef union { StkId p; /* actual pointer */ ptrdiff_t offset; /* used while the stack is being reallocated */ } StkIdRel; /* convert a 'StackValue' to a 'TValue' */ #define s2v(o) (&(o)->val) /* ** {================================================================== ** Nil ** =================================================================== */ /* Standard nil */ #define LUA_VNIL makevariant(LUA_TNIL, 0) /* Empty slot (which might be different from a slot containing nil) */ #define LUA_VEMPTY makevariant(LUA_TNIL, 1) /* LuaValue returned for a key not found in a table (absent key) */ #define LUA_VABSTKEY makevariant(LUA_TNIL, 2) /* Special variant to signal that a fast get is accessing a non-table */ #define LUA_VNOTABLE makevariant(LUA_TNIL, 3) /* macro to test for (any kind of) nil */ #define ttisnil(v) checktype((v), LUA_TNIL) /* ** Macro to test the result of a table access. Formally, it should ** distinguish between LUA_VEMPTY/LUA_VABSTKEY/LUA_VNOTABLE and ** other tags. As currently nil is equivalent to LUA_VEMPTY, it is ** simpler to just test whether the value is nil. */ #define tagisempty(tag) (novariant(tag) == LUA_TNIL) /* macro to test for a standard nil */ #define ttisstrictnil(o) checktag((o), LUA_VNIL) #define setnilvalue(obj) settt_(obj, LUA_VNIL) #define isabstkey(v) checktag((v), LUA_VABSTKEY) /* ** macro to detect non-standard nils (used only in assertions) */ #define isnonstrictnil(v) (ttisnil(v) && !ttisstrictnil(v)) /* ** By default, entries with any kind of nil are considered empty. ** (In any definition, values associated with absent keys must also ** be accepted as empty.) */ #define isempty(v) ttisnil(v) /* macro defining a value corresponding to an absent key */ #define ABSTKEYCONSTANT {NULL}, LUA_VABSTKEY /* mark an entry as empty */ #define setempty(v) settt_(v, LUA_VEMPTY) /* }================================================================== */ /* ** {================================================================== ** Booleans ** =================================================================== */ #define LUA_VFALSE makevariant(LUA_TBOOLEAN, 0) #define LUA_VTRUE makevariant(LUA_TBOOLEAN, 1) #define ttisboolean(o) checktype((o), LUA_TBOOLEAN) #define ttisfalse(o) checktag((o), LUA_VFALSE) #define ttistrue(o) checktag((o), LUA_VTRUE) #define l_isfalse(o) (ttisfalse(o) || ttisnil(o)) #define tagisfalse(t) ((t) == LUA_VFALSE || novariant(t) == LUA_TNIL) #define setbfvalue(obj) settt_(obj, LUA_VFALSE) #define setbtvalue(obj) settt_(obj, LUA_VTRUE) /* }================================================================== */ /* ** {================================================================== ** Threads ** =================================================================== */ #define LUA_VTHREAD makevariant(LUA_TTHREAD, 0) #define ttisthread(o) checktag((o), ctb(LUA_VTHREAD)) #define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc)) #define setthvalue(L,obj,x) \ { TValue *io = (obj); lua_State *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \ checkliveness(L,io); } #define setthvalue2s(L,o,t) setthvalue(L,s2v(o),t) /* }================================================================== */ /* ** {================================================================== ** Collectable Objects ** =================================================================== */ /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ #define CommonHeader struct GCObject *next; lu_byte tt; lu_byte marked /* Common type for all collectable objects */ typedef struct GCObject { CommonHeader; } GCObject; /* Bit mark for collectable types */ #define BIT_ISCOLLECTABLE (1 << 6) #define iscollectable(o) (rawtt(o) & BIT_ISCOLLECTABLE) /* mark a tag as collectable */ #define ctb(t) ((t) | BIT_ISCOLLECTABLE) #define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) #define gcvalueraw(v) ((v).gc) #define setgcovalue(L,obj,x) \ { TValue *io = (obj); GCObject *i_g=(x); \ val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); } /* }================================================================== */ /* ** {================================================================== ** Numbers ** =================================================================== */ /* Variant tags for numbers */ #define LUA_VNUMINT makevariant(LUA_TNUMBER, 0) /* integer numbers */ #define LUA_VNUMFLT makevariant(LUA_TNUMBER, 1) /* float numbers */ #define ttisnumber(o) checktype((o), LUA_TNUMBER) #define ttisfloat(o) checktag((o), LUA_VNUMFLT) #define ttisinteger(o) checktag((o), LUA_VNUMINT) #define nvalue(o) check_exp(ttisnumber(o), \ (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o))) #define fltvalue(o) check_exp(ttisfloat(o), val_(o).n) #define ivalue(o) check_exp(ttisinteger(o), val_(o).i) #define fltvalueraw(v) ((v).n) #define ivalueraw(v) ((v).i) #define setfltvalue(obj,x) \ { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); } #define chgfltvalue(obj,x) \ { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); } #define setivalue(obj,x) \ { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); } #define chgivalue(obj,x) \ { TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); } /* }================================================================== */ /* ** {================================================================== ** Strings ** =================================================================== */ /* Variant tags for strings */ #define LUA_VSHRSTR makevariant(LUA_TSTRING, 0) /* short strings */ #define LUA_VLNGSTR makevariant(LUA_TSTRING, 1) /* long strings */ #define ttisstring(o) checktype((o), LUA_TSTRING) #define ttisshrstring(o) checktag((o), ctb(LUA_VSHRSTR)) #define ttislngstring(o) checktag((o), ctb(LUA_VLNGSTR)) #define tsvalueraw(v) (gco2ts((v).gc)) #define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc)) #define setsvalue(L,obj,x) \ { TValue *io = (obj); TString *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \ checkliveness(L,io); } /* set a string to the stack */ #define setsvalue2s(L,o,s) setsvalue(L,s2v(o),s) /* set a string to a new object */ #define setsvalue2n setsvalue /* Kinds of long strings (stored in 'shrlen') */ #define LSTRREG -1 /* regular long string */ #define LSTRFIX -2 /* fixed external long string */ #define LSTRMEM -3 /* external long string with deallocation */ /* ** Header for a string value. */ typedef struct TString { CommonHeader; lu_byte extra; /* reserved words for short strings; "has hash" for longs */ ls_byte shrlen; /* length for short strings, negative for long strings */ unsigned int hash; union { size_t lnglen; /* length for long strings */ struct TString *hnext; /* linked list for hash table */ } u; char *contents; /* pointer to content in long strings */ lua_Alloc falloc; /* deallocation function for external strings */ void *ud; /* user data for external strings */ } TString; #define strisshr(ts) ((ts)->shrlen >= 0) #define isextstr(ts) (ttislngstring(ts) && tsvalue(ts)->shrlen != LSTRREG) /* ** Get the actual string (array of bytes) from a 'TString'. (Generic ** version and specialized versions for long and short strings.) */ #define rawgetshrstr(ts) (cast_charp(&(ts)->contents)) #define getshrstr(ts) check_exp(strisshr(ts), rawgetshrstr(ts)) #define getlngstr(ts) check_exp(!strisshr(ts), (ts)->contents) #define getstr(ts) (strisshr(ts) ? rawgetshrstr(ts) : (ts)->contents) /* get string length from 'TString *ts' */ #define tsslen(ts) \ (strisshr(ts) ? cast_sizet((ts)->shrlen) : (ts)->u.lnglen) /* ** Get string and length */ #define getlstr(ts, len) \ (strisshr(ts) \ ? (cast_void((len) = cast_sizet((ts)->shrlen)), rawgetshrstr(ts)) \ : (cast_void((len) = (ts)->u.lnglen), (ts)->contents)) /* }================================================================== */ /* ** {================================================================== ** Userdata ** =================================================================== */ /* ** Light userdata should be a variant of userdata, but for compatibility ** reasons they are also different types. */ #define LUA_VLIGHTUSERDATA makevariant(LUA_TLIGHTUSERDATA, 0) #define LUA_VUSERDATA makevariant(LUA_TUSERDATA, 0) #define ttislightuserdata(o) checktag((o), LUA_VLIGHTUSERDATA) #define ttisfulluserdata(o) checktag((o), ctb(LUA_VUSERDATA)) #define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) #define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc)) #define pvalueraw(v) ((v).p) #define setpvalue(obj,x) \ { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); } #define setuvalue(L,obj,x) \ { TValue *io = (obj); Udata *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \ checkliveness(L,io); } /* Ensures that addresses after this type are always fully aligned. */ typedef union UValue { TValue uv; LUAI_MAXALIGN; /* ensures maximum alignment for udata bytes */ } UValue; /* ** Header for userdata with user values; ** memory area follows the end of this structure. */ typedef struct Udata { CommonHeader; unsigned short nuvalue; /* number of user values */ size_t len; /* number of bytes */ struct Table *metatable; GCObject *gclist; UValue uv[1]; /* user values */ } Udata; /* ** Header for userdata with no user values. These userdata do not need ** to be gray during GC, and therefore do not need a 'gclist' field. ** To simplify, the code always use 'Udata' for both kinds of userdata, ** making sure it never accesses 'gclist' on userdata with no user values. ** This structure here is used only to compute the correct size for ** this representation. (The 'bindata' field in its end ensures correct ** alignment for binary data following this header.) */ typedef struct Udata0 { CommonHeader; unsigned short nuvalue; /* number of user values */ size_t len; /* number of bytes */ struct Table *metatable; union {LUAI_MAXALIGN;} bindata; } Udata0; /* compute the offset of the memory area of a userdata */ #define udatamemoffset(nuv) \ ((nuv) == 0 ? offsetof(Udata0, bindata) \ : offsetof(Udata, uv) + (sizeof(UValue) * (nuv))) /* get the address of the memory block inside 'Udata' */ #define getudatamem(u) (cast_charp(u) + udatamemoffset((u)->nuvalue)) /* compute the size of a userdata */ #define sizeudata(nuv,nb) (udatamemoffset(nuv) + (nb)) /* }================================================================== */ /* ** {================================================================== ** Prototypes ** =================================================================== */ #define LUA_VPROTO makevariant(LUA_TPROTO, 0) typedef l_uint32 Instruction; /* ** Description of an upvalue for function prototypes */ typedef struct Upvaldesc { TString *name; /* upvalue name (for debug information) */ lu_byte instack; /* whether it is in stack (register) */ lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ lu_byte kind; /* kind of corresponding variable */ } Upvaldesc; /* ** Description of a local variable for function prototypes ** (used for debug information) */ typedef struct LocVar { TString *varname; int startpc; /* first point where variable is active */ int endpc; /* first point where variable is dead */ } LocVar; /* ** Associates the absolute line source for a given instruction ('pc'). ** The array 'lineinfo' gives, for each instruction, the difference in ** lines from the previous instruction. When that difference does not ** fit into a byte, Lua saves the absolute line for that instruction. ** (Lua also saves the absolute line periodically, to speed up the ** computation of a line number: we can use binary search in the ** absolute-line array, but we must traverse the 'lineinfo' array ** linearly to compute a line.) */ typedef struct AbsLineInfo { int pc; int line; } AbsLineInfo; /* ** Flags in Prototypes */ #define PF_VAHID 1 /* function has hidden vararg arguments */ #define PF_VATAB 2 /* function has vararg table */ #define PF_FIXED 4 /* prototype has parts in fixed memory */ /* a vararg function either has hidden args. or a vararg table */ #define isvararg(p) ((p)->flag & (PF_VAHID | PF_VATAB)) /* ** mark that a function needs a vararg table. (The flag PF_VAHID will ** be cleared later.) */ #define needvatab(p) ((p)->flag |= PF_VATAB) /* ** Function Prototypes */ typedef struct Proto { CommonHeader; lu_byte numparams; /* number of fixed (named) parameters */ lu_byte flag; lu_byte maxstacksize; /* number of registers needed by this function */ int sizeupvalues; /* size of 'upvalues' */ int sizek; /* size of 'k' */ int sizecode; int sizelineinfo; int sizep; /* size of 'p' */ int sizelocvars; int sizeabslineinfo; /* size of 'abslineinfo' */ int linedefined; /* debug information */ int lastlinedefined; /* debug information */ TValue *k; /* constants used by the function */ Instruction *code; /* opcodes */ struct Proto **p; /* functions defined inside the function */ Upvaldesc *upvalues; /* upvalue information */ ls_byte *lineinfo; /* information about source lines (debug information) */ AbsLineInfo *abslineinfo; /* idem */ LocVar *locvars; /* information about local variables (debug information) */ TString *source; /* used for debug information */ GCObject *gclist; } Proto; /* }================================================================== */ /* ** {================================================================== ** Functions ** =================================================================== */ #define LUA_VUPVAL makevariant(LUA_TUPVAL, 0) /* Variant tags for functions */ #define LUA_VLCL makevariant(LUA_TFUNCTION, 0) /* Lua closure */ #define LUA_VLCF makevariant(LUA_TFUNCTION, 1) /* light C function */ #define LUA_VCCL makevariant(LUA_TFUNCTION, 2) /* C closure */ #define ttisfunction(o) checktype(o, LUA_TFUNCTION) #define ttisLclosure(o) checktag((o), ctb(LUA_VLCL)) #define ttislcf(o) checktag((o), LUA_VLCF) #define ttisCclosure(o) checktag((o), ctb(LUA_VCCL)) #define ttisclosure(o) (ttisLclosure(o) || ttisCclosure(o)) #define isLfunction(o) ttisLclosure(o) #define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc)) #define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc)) #define fvalue(o) check_exp(ttislcf(o), val_(o).f) #define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc)) #define fvalueraw(v) ((v).f) #define setclLvalue(L,obj,x) \ { TValue *io = (obj); LClosure *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \ checkliveness(L,io); } #define setclLvalue2s(L,o,cl) setclLvalue(L,s2v(o),cl) #define setfvalue(obj,x) \ { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); } #define setclCvalue(L,obj,x) \ { TValue *io = (obj); CClosure *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \ checkliveness(L,io); } /* ** Upvalues for Lua closures */ typedef struct UpVal { CommonHeader; union { TValue *p; /* points to stack or to its own value */ ptrdiff_t offset; /* used while the stack is being reallocated */ } v; union { struct { /* (when open) */ struct UpVal *next; /* linked list */ struct UpVal **previous; } open; TValue value; /* the value (when closed) */ } u; } UpVal; #define ClosureHeader \ CommonHeader; lu_byte nupvalues; GCObject *gclist typedef struct CClosure { ClosureHeader; lua_CFunction f; TValue upvalue[1]; /* list of upvalues */ } CClosure; typedef struct LClosure { ClosureHeader; struct Proto *p; UpVal *upvals[1]; /* list of upvalues */ } LClosure; typedef union Closure { CClosure c; LClosure l; } Closure; #define getproto(o) (clLvalue(o)->p) /* }================================================================== */ /* ** {================================================================== ** Tables ** =================================================================== */ #define LUA_VTABLE makevariant(LUA_TTABLE, 0) #define ttistable(o) checktag((o), ctb(LUA_VTABLE)) #define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc)) #define sethvalue(L,obj,x) \ { TValue *io = (obj); Table *x_ = (x); \ val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \ checkliveness(L,io); } #define sethvalue2s(L,o,h) sethvalue(L,s2v(o),h) /* ** Nodes for Hash tables: A pack of two TValue's (key-value pairs) ** plus a 'next' field to link colliding entries. The distribution ** of the key's fields ('key_tt' and 'key_val') not forming a proper ** 'TValue' allows for a smaller size for 'Node' both in 4-byte ** and 8-byte alignments. */ typedef union Node { struct NodeKey { TValuefields; /* fields for value */ lu_byte key_tt; /* key type */ int next; /* for chaining */ LuaValue key_val; /* key value */ } u; TValue i_val; /* direct access to node's value as a proper 'TValue' */ } Node; /* copy a value into a key */ #define setnodekey(node,obj) \ { Node *n_=(node); const TValue *io_=(obj); \ n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; } /* copy a value from a key */ #define getnodekey(L,obj,node) \ { TValue *io_=(obj); const Node *n_=(node); \ io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \ checkliveness(L,io_); } typedef struct Table { CommonHeader; lu_byte flags; /* 1<

u.key_tt) #define keyval(node) ((node)->u.key_val) #define keyisnil(node) (keytt(node) == LUA_TNIL) #define keyisinteger(node) (keytt(node) == LUA_VNUMINT) #define keyival(node) (keyval(node).i) #define keyisshrstr(node) (keytt(node) == ctb(LUA_VSHRSTR)) #define keystrval(node) (gco2ts(keyval(node).gc)) #define setnilkey(node) (keytt(node) = LUA_TNIL) #define keyiscollectable(n) (keytt(n) & BIT_ISCOLLECTABLE) #define gckey(n) (keyval(n).gc) #define gckeyN(n) (keyiscollectable(n) ? gckey(n) : NULL) /* ** Dead keys in tables have the tag DEADKEY but keep their original ** gcvalue. This distinguishes them from regular keys but allows them to ** be found when searched in a special way. ('next' needs that to find ** keys removed from a table during a traversal.) */ #define setdeadkey(node) (keytt(node) = LUA_TDEADKEY) #define keyisdead(node) (keytt(node) == LUA_TDEADKEY) /* }================================================================== */ /* ** 'module' operation for hashing (size is always a power of 2) */ #define lmod(s,size) \ (check_exp((size&(size-1))==0, (cast_uint(s) & cast_uint((size)-1)))) #define twoto(x) (1u<<(x)) #define sizenode(t) (twoto((t)->lsizenode)) /* size of buffer for 'luaO_utf8esc' function */ #define UTF8BUFFSZ 8 /* macro to call 'luaO_pushvfstring' correctly */ #define pushvfstring(L, argp, fmt, msg) \ { va_start(argp, fmt); \ msg = luaO_pushvfstring(L, fmt, argp); \ va_end(argp); \ if (msg == NULL) luaD_throw(L, LUA_ERRMEM); /* only after 'va_end' */ } LUAI_FUNC int luaO_utf8esc (char *buff, l_uint32 x); LUAI_FUNC lu_byte luaO_ceillog2 (unsigned int x); LUAI_FUNC lu_byte luaO_codeparam (unsigned int p); LUAI_FUNC l_mem luaO_applyparam (lu_byte p, l_mem x); LUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2, TValue *res); LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, StkId res); LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o); LUAI_FUNC unsigned luaO_tostringbuff (const TValue *obj, char *buff); LUAI_FUNC lu_byte luaO_hexavalue (int c); LUAI_FUNC void luaO_tostring (lua_State *L, TValue *obj); LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp); LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t srclen); #endif /* ** $Id: lzio.h $ ** Buffered streams ** See Copyright Notice in lua.h */ #ifndef lzio_h #define lzio_h #include "lua.h" #define EOZ (-1) /* end of stream */ typedef struct Zio ZIO; #define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z)) typedef struct Mbuffer { char *buffer; size_t n; size_t buffsize; } Mbuffer; #define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) #define luaZ_buffer(buff) ((buff)->buffer) #define luaZ_sizebuffer(buff) ((buff)->buffsize) #define luaZ_bufflen(buff) ((buff)->n) #define luaZ_buffremove(buff,i) ((buff)->n -= cast_sizet(i)) #define luaZ_resetbuffer(buff) ((buff)->n = 0) #define luaZ_resizebuffer(L, buff, size) \ ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \ (buff)->buffsize, size), \ (buff)->buffsize = size) #define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data); LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */ LUAI_FUNC const void *luaZ_getaddr (ZIO* z, size_t n); /* --------- Private Part ------------------ */ struct Zio { size_t n; /* bytes still unread */ const char *p; /* current position in buffer */ lua_Reader reader; /* reader function */ void *data; /* additional data */ lua_State *L; /* Lua state (for reader) */ }; LUAI_FUNC int luaZ_fill (ZIO *z); #endif /* ** $Id: lparser.h $ ** Lua Parser ** See Copyright Notice in lua.h */ #ifndef lparser_h #define lparser_h /* ** Expression and variable descriptor. ** Code generation for variables and expressions can be delayed to allow ** optimizations; An 'expdesc' structure describes a potentially-delayed ** variable/expression. It has a description of its "main" value plus a ** list of conditional jumps that can also produce its value (generated ** by short-circuit operators 'and'/'or'). */ /* kinds of variables/expressions */ typedef enum { VVOID, /* when 'expdesc' describes the last expression of a list, this kind means an empty list (so, no expression) */ VNIL, /* constant nil */ VTRUE, /* constant true */ VFALSE, /* constant false */ VK, /* constant in 'k'; info = index of constant in 'k' */ VKFLT, /* floating constant; nval = numerical float value */ VKINT, /* integer constant; ival = numerical integer value */ VKSTR, /* string constant; strval = TString address; (string is fixed by the scanner) */ VNONRELOC, /* expression has its value in a fixed register; info = result register */ VLOCAL, /* local variable; var.ridx = register index; var.vidx = relative index in 'actvar.arr' */ VVARGVAR, /* vararg parameter; var.ridx = register index; var.vidx = relative index in 'actvar.arr' */ VGLOBAL, /* global variable; info = relative index in 'actvar.arr' (or -1 for implicit declaration) */ VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */ VCONST, /* compile-time variable; info = absolute index in 'actvar.arr' */ VINDEXED, /* indexed variable; ind.t = table register; ind.idx = key's R index; ind.ro = true if it represents a read-only global; ind.keystr = if key is a string, index in 'k' of that string; -1 if key is not a string */ VVARGIND, /* indexed vararg parameter; ind.* as in VINDEXED */ VINDEXUP, /* indexed upvalue; ind.idx = key's K index; ind.* as in VINDEXED */ VINDEXI, /* indexed variable with constant integer; ind.t = table register; ind.idx = key's value */ VINDEXSTR, /* indexed variable with literal string; ind.idx = key's K index; ind.* as in VINDEXED */ VJMP, /* expression is a test/comparison; info = pc of corresponding jump instruction */ VRELOC, /* expression can put result in any register; info = instruction pc */ VCALL, /* expression is a function call; info = instruction pc */ VVARARG /* vararg expression; info = instruction pc */ } expkind; #define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXSTR) #define vkisindexed(k) (VINDEXED <= (k) && (k) <= VINDEXSTR) typedef struct expdesc { expkind k; union { lua_Integer ival; /* for VKINT */ lua_Number nval; /* for VKFLT */ TString *strval; /* for VKSTR */ int info; /* for generic use */ struct { /* for indexed variables */ short idx; /* index (R or "long" K) */ lu_byte t; /* table (register or upvalue) */ lu_byte ro; /* true if variable is read-only */ int keystr; /* index in 'k' of string key, or -1 if not a string */ } ind; struct { /* for local variables */ lu_byte ridx; /* register holding the variable */ short vidx; /* index in 'actvar.arr' */ } var; } u; int t; /* patch list of 'exit when true' */ int f; /* patch list of 'exit when false' */ } expdesc; /* kinds of variables */ #define VDKREG 0 /* regular local */ #define RDKCONST 1 /* local constant */ #define RDKVAVAR 2 /* vararg parameter */ #define RDKTOCLOSE 3 /* to-be-closed */ #define RDKCTC 4 /* local compile-time constant */ #define GDKREG 5 /* regular global */ #define GDKCONST 6 /* global constant */ /* variables that live in registers */ #define varinreg(v) ((v)->vd.kind <= RDKTOCLOSE) /* test for global variables */ #define varglobal(v) ((v)->vd.kind >= GDKREG) /* description of an active variable */ typedef union Vardesc { struct { TValuefields; /* constant value (if it is a compile-time constant) */ lu_byte kind; lu_byte ridx; /* register holding the variable */ short pidx; /* index of the variable in the Proto's 'locvars' array */ TString *name; /* variable name */ } vd; TValue k; /* constant value (if any) */ } Vardesc; /* description of pending goto statements and label statements */ typedef struct Labeldesc { TString *name; /* label identifier */ int pc; /* position in code */ int line; /* line where it appeared */ short nactvar; /* number of active variables in that position */ lu_byte close; /* true for goto that escapes upvalues */ } Labeldesc; /* list of labels or gotos */ typedef struct Labellist { Labeldesc *arr; /* array */ int n; /* number of entries in use */ int size; /* array size */ } Labellist; /* dynamic structures used by the parser */ typedef struct Dyndata { struct { /* list of all active local variables */ Vardesc *arr; int n; int size; } actvar; Labellist gt; /* list of pending gotos */ Labellist label; /* list of active labels */ } Dyndata; /* control of blocks */ struct BlockCnt; /* defined in lparser.c */ /* state needed to generate code for a given function */ typedef struct FuncState { Proto *f; /* current function header */ struct FuncState *prev; /* enclosing function */ struct LexState *ls; /* lexical state */ struct BlockCnt *bl; /* chain of current blocks */ Table *kcache; /* cache for reusing constants */ int pc; /* next position to code (equivalent to 'ncode') */ int lasttarget; /* 'label' of last 'jump label' */ int previousline; /* last line that was saved in 'lineinfo' */ int nk; /* number of elements in 'k' */ int np; /* number of elements in 'p' */ int nabslineinfo; /* number of elements in 'abslineinfo' */ int firstlocal; /* index of first local var (in Dyndata array) */ int firstlabel; /* index of first label (in 'dyd->label->arr') */ short ndebugvars; /* number of elements in 'f->locvars' */ short nactvar; /* number of active variable declarations */ lu_byte nups; /* number of upvalues */ lu_byte freereg; /* first free register */ lu_byte iwthabs; /* instructions issued since last absolute line info */ lu_byte needclose; /* function needs to close upvalues when returning */ } FuncState; LUAI_FUNC lu_byte luaY_nvarstack (FuncState *fs); LUAI_FUNC void luaY_checklimit (FuncState *fs, int v, int l, const char *what); LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Dyndata *dyd, const char *name, int firstchar); #endif /* ** $Id: lopcodes.h $ ** Opcodes for Lua virtual machine ** See Copyright Notice in lua.h */ #ifndef lopcodes_h #define lopcodes_h /*=========================================================================== We assume that instructions are unsigned 32-bit integers. All instructions have an opcode in the first 7 bits. Instructions can have the following formats: 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 iABC C(8) | B(8) |k| A(8) | Op(7) | ivABC vC(10) | vB(6) |k| A(8) | Op(7) | iABx Bx(17) | A(8) | Op(7) | iAsBx sBx (signed)(17) | A(8) | Op(7) | iAx Ax(25) | Op(7) | isJ sJ (signed)(25) | Op(7) | ('v' stands for "variant", 's' for "signed", 'x' for "extended".) A signed argument is represented in excess K: The represented value is the written unsigned value minus K, where K is half (rounded down) the maximum value for the corresponding unsigned argument. ===========================================================================*/ /* basic instruction formats */ enum OpMode {iABC, ivABC, iABx, iAsBx, iAx, isJ}; /* ** size and position of opcode arguments. */ #undef SIZE_C /* QNX conflict */ #define SIZE_C 8 #define SIZE_vC 10 #define SIZE_B 8 #define SIZE_vB 6 #define SIZE_Bx (SIZE_C + SIZE_B + 1) #define SIZE_A 8 #define SIZE_Ax (SIZE_Bx + SIZE_A) #define SIZE_sJ (SIZE_Bx + SIZE_A) #define SIZE_OP 7 #define POS_OP 0 #define POS_A (POS_OP + SIZE_OP) #define POS_k (POS_A + SIZE_A) #define POS_B (POS_k + 1) #define POS_vB (POS_k + 1) #define POS_C (POS_B + SIZE_B) #define POS_vC (POS_vB + SIZE_vB) #define POS_Bx POS_k #define POS_Ax POS_A #define POS_sJ POS_A /* ** limits for opcode arguments. ** we use (signed) 'int' to manipulate most arguments, ** so they must fit in ints. */ /* ** Check whether type 'int' has at least 'b' + 1 bits. ** 'b' < 32; +1 for the sign bit. */ #define L_INTHASBITS(b) ((UINT_MAX >> (b)) >= 1) #if L_INTHASBITS(SIZE_Bx) #define MAXARG_Bx ((1<>1) /* 'sBx' is signed */ #if L_INTHASBITS(SIZE_Ax) #define MAXARG_Ax ((1<> 1) #define MAXARG_A ((1<> 1) #define int2sC(i) ((i) + OFFSET_sC) #define sC2int(i) ((i) - OFFSET_sC) /* creates a mask with 'n' 1 bits at position 'p' */ #define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p)) /* creates a mask with 'n' 0 bits at position 'p' */ #define MASK0(n,p) (~MASK1(n,p)) /* ** the following macros help to manipulate instructions */ #define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0))) #define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ ((cast_Inst(o)<>(pos)) & MASK1(size,0))) #define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \ ((cast_Inst(v)<> sC */ OP_ADD,/* A B C R[A] := R[B] + R[C] */ OP_SUB,/* A B C R[A] := R[B] - R[C] */ OP_MUL,/* A B C R[A] := R[B] * R[C] */ OP_MOD,/* A B C R[A] := R[B] % R[C] */ OP_POW,/* A B C R[A] := R[B] ^ R[C] */ OP_DIV,/* A B C R[A] := R[B] / R[C] */ OP_IDIV,/* A B C R[A] := R[B] // R[C] */ OP_BAND,/* A B C R[A] := R[B] & R[C] */ OP_BOR,/* A B C R[A] := R[B] | R[C] */ OP_BXOR,/* A B C R[A] := R[B] ~ R[C] */ OP_SHL,/* A B C R[A] := R[B] << R[C] */ OP_SHR,/* A B C R[A] := R[B] >> R[C] */ OP_MMBIN,/* A B C call C metamethod over R[A] and R[B] */ OP_MMBINI,/* A sB C k call C metamethod over R[A] and sB */ OP_MMBINK,/* A B C k call C metamethod over R[A] and K[B] */ OP_UNM,/* A B R[A] := -R[B] */ OP_BNOT,/* A B R[A] := ~R[B] */ OP_NOT,/* A B R[A] := not R[B] */ OP_LEN,/* A B R[A] := #R[B] (length operator) */ OP_CONCAT,/* A B R[A] := R[A].. ... ..R[A + B - 1] */ OP_CLOSE,/* A close all upvalues >= R[A] */ OP_TBC,/* A mark variable A "to be closed" */ OP_JMP,/* sJ pc += sJ */ OP_EQ,/* A B k if ((R[A] == R[B]) ~= k) then pc++ */ OP_LT,/* A B k if ((R[A] < R[B]) ~= k) then pc++ */ OP_LE,/* A B k if ((R[A] <= R[B]) ~= k) then pc++ */ OP_EQK,/* A B k if ((R[A] == K[B]) ~= k) then pc++ */ OP_EQI,/* A sB k if ((R[A] == sB) ~= k) then pc++ */ OP_LTI,/* A sB k if ((R[A] < sB) ~= k) then pc++ */ OP_LEI,/* A sB k if ((R[A] <= sB) ~= k) then pc++ */ OP_GTI,/* A sB k if ((R[A] > sB) ~= k) then pc++ */ OP_GEI,/* A sB k if ((R[A] >= sB) ~= k) then pc++ */ OP_TEST,/* A k if (not R[A] == k) then pc++ */ OP_TESTSET,/* A B k if (not R[B] == k) then pc++ else R[A] := R[B] */ OP_CALL,/* A B C R[A], ... ,R[A+C-2] := R[A](R[A+1], ... ,R[A+B-1]) */ OP_TAILCALL,/* A B C k return R[A](R[A+1], ... ,R[A+B-1]) */ OP_RETURN,/* A B C k return R[A], ... ,R[A+B-2] */ OP_RETURN0,/* return */ OP_RETURN1,/* A return R[A] */ OP_FORLOOP,/* A Bx update counters; if loop continues then pc-=Bx; */ OP_FORPREP,/* A Bx ; if not to run then pc+=Bx+1; */ OP_TFORPREP,/* A Bx create upvalue for R[A + 3]; pc+=Bx */ OP_TFORCALL,/* A C R[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]); */ OP_TFORLOOP,/* A Bx if R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx } */ OP_SETLIST,/* A vB vC k R[A][vC+i] := R[A+i], 1 <= i <= vB */ OP_CLOSURE,/* A Bx R[A] := closure(KPROTO[Bx]) */ OP_VARARG,/* A B C k R[A], ..., R[A+C-2] = varargs */ OP_GETVARG, /* A B C R[A] := R[B][R[C]], R[B] is vararg parameter */ OP_ERRNNIL,/* A Bx raise error if R[A] ~= nil (K[Bx - 1] is global name)*/ OP_VARARGPREP,/* (adjust varargs) */ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ } OpCode; #define NUM_OPCODES ((int)(OP_EXTRAARG) + 1) /*=========================================================================== Notes: (*) Opcode OP_LFALSESKIP is used to convert a condition to a boolean value, in a code equivalent to (not cond ? false : true). (It produces false and skips the next instruction producing true.) (*) Opcodes OP_MMBIN and variants follow each arithmetic and bitwise opcode. If the operation succeeds, it skips this next opcode. Otherwise, this opcode calls the corresponding metamethod. (*) Opcode OP_TESTSET is used in short-circuit expressions that need both to jump and to produce a value, such as (a = b or c). (*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then 'top' is set to last_result+1, so next open instruction (OP_CALL, OP_RETURN*, OP_SETLIST) may use 'top'. (*) In OP_VARARG, if (C == 0) then use actual number of varargs and set top (like in OP_CALL with C == 0). 'k' means function has a vararg table, which is in R[B]. (*) In OP_RETURN, if (B == 0) then return up to 'top'. (*) In OP_LOADKX and OP_NEWTABLE, the next instruction is always OP_EXTRAARG. (*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the bits of C). (*) In OP_NEWTABLE, vB is log2 of the hash size (which is always a power of 2) plus 1, or zero for size zero. If not k, the array size is vC. Otherwise, the array size is EXTRAARG _ vC. (*) In OP_ERRNNIL, (Bx == 0) means index of global name doesn't fit in Bx. (So, that name is not available for the error message.) (*) For comparisons, k specifies what condition the test should accept (true or false). (*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped (the constant is the first operand). (*) All comparison and test instructions assume that the instruction being skipped (pc++) is a jump. (*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the function builds upvalues, which may need to be closed. C > 0 means the function has hidden vararg arguments, so that its 'func' must be corrected before returning; in this case, (C - 1) is its number of fixed parameters. (*) In comparisons with an immediate operand, C signals whether the original operand was a float. (It must be corrected in case of metamethods.) ===========================================================================*/ /* ** masks for instruction properties. The format is: ** bits 0-2: op mode ** bit 3: instruction set register A ** bit 4: operator is a test (next instruction must be a jump) ** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0) ** bit 6: instruction sets 'L->top' for next instruction (when C == 0) ** bit 7: instruction is an MM instruction (call a metamethod) */ LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];) #define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 7)) #define testAMode(m) (luaP_opmodes[m] & (1 << 3)) #define testTMode(m) (luaP_opmodes[m] & (1 << 4)) #define testITMode(m) (luaP_opmodes[m] & (1 << 5)) #define testOTMode(m) (luaP_opmodes[m] & (1 << 6)) #define testMMMode(m) (luaP_opmodes[m] & (1 << 7)) LUAI_FUNC int luaP_isOT (Instruction i); LUAI_FUNC int luaP_isIT (Instruction i); #endif /* ** $Id: llex.h $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ #ifndef llex_h #define llex_h #include /* ** Single-char tokens (terminal symbols) are represented by their own ** numeric code. Other tokens start at the following value. */ #define FIRST_RESERVED (UCHAR_MAX + 1) #if !defined(LUA_ENV) #define LUA_ENV "_ENV" #endif /* * WARNING: if you change the order of this enumeration, * grep "ORDER RESERVED" */ enum RESERVED { /* terminal symbols denoted by reserved words */ TK_AND = FIRST_RESERVED, TK_BREAK, TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, TK_GLOBAL, TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, /* other terminal symbols */ TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_SHL, TK_SHR, TK_DBCOLON, TK_EOS, TK_FLT, TK_INT, TK_NAME, TK_STRING }; /* number of reserved words */ #define NUM_RESERVED (cast_int(TK_WHILE-FIRST_RESERVED + 1)) typedef union { lua_Number r; lua_Integer i; TString *ts; } SemInfo; /* semantics information */ typedef struct Token { int token; SemInfo seminfo; } Token; /* state of the scanner plus state of the parser when shared by all functions */ typedef struct LexState { int current; /* current character (charint) */ int linenumber; /* input line counter */ int lastline; /* line of last token 'consumed' */ Token t; /* current token */ Token lookahead; /* look ahead token */ struct FuncState *fs; /* current function (parser) */ struct lua_State *L; ZIO *z; /* input stream */ Mbuffer *buff; /* buffer for tokens */ Table *h; /* to avoid collection/reuse strings */ struct Dyndata *dyd; /* dynamic structures used by the parser */ TString *source; /* current source name */ TString *envn; /* environment variable name */ TString *brkn; /* "break" name (used as a label) */ TString *glbn; /* "global" name (when not a reserved word) */ } LexState; LUAI_FUNC void luaX_init (lua_State *L); LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, int firstchar); LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l); LUAI_FUNC void luaX_next (LexState *ls); LUAI_FUNC int luaX_lookahead (LexState *ls); LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s); LUAI_FUNC const char *luaX_token2str (LexState *ls, int token); #endif /* ** $Id: ltm.h $ ** Tag methods ** See Copyright Notice in lua.h */ #ifndef ltm_h #define ltm_h /* * WARNING: if you change the order of this enumeration, * grep "ORDER TM" and "ORDER OP" */ typedef enum { TM_INDEX, TM_NEWINDEX, TM_GC, TM_MODE, TM_LEN, TM_EQ, /* last tag method with fast access */ TM_ADD, TM_SUB, TM_MUL, TM_MOD, TM_POW, TM_DIV, TM_IDIV, TM_BAND, TM_BOR, TM_BXOR, TM_SHL, TM_SHR, TM_UNM, TM_BNOT, TM_LT, TM_LE, TM_CONCAT, TM_CALL, TM_CLOSE, TM_N /* number of elements in the enum */ } TMS; /* ** Mask with 1 in all fast-access methods. A 1 in any of these bits ** in the flag of a (meta)table means the metatable does not have the ** corresponding metamethod field. (Bit 6 of the flag indicates that ** the table is using the dummy node; bit 7 is used for 'isrealasize'.) */ #define maskflags cast_byte(~(~0u << (TM_EQ + 1))) /* ** Test whether there is no tagmethod. ** (Because tagmethods use raw accesses, the result may be an "empty" nil.) */ #define notm(tm) ttisnil(tm) #define checknoTM(mt,e) ((mt) == NULL || (mt)->flags & (1u<<(e))) #define gfasttm(g,mt,e) \ (checknoTM(mt, e) ? NULL : luaT_gettm(mt, e, (g)->tmname[e])) #define fasttm(l,mt,e) gfasttm(G(l), mt, e) #define ttypename(x) luaT_typenames_[(x) + 1] LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];) LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o); LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename); LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event); LUAI_FUNC void luaT_init (lua_State *L); LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, const TValue *p3); LUAI_FUNC lu_byte luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, StkId p3); LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, StkId res, TMS event); LUAI_FUNC void luaT_tryconcatTM (lua_State *L); LUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2, int inv, StkId res, TMS event); LUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2, int inv, StkId res, TMS event); LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2, TMS event); LUAI_FUNC int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2, int inv, int isfloat, TMS event); LUAI_FUNC void luaT_adjustvarargs (lua_State *L, struct CallInfo *ci, const Proto *p); LUAI_FUNC void luaT_getvararg (CallInfo *ci, StkId ra, TValue *rc); LUAI_FUNC void luaT_getvarargs (lua_State *L, struct CallInfo *ci, StkId where, int wanted, int vatab); #endif /* ** $Id: lstate.h $ ** Global State ** See Copyright Notice in lua.h */ #ifndef lstate_h #define lstate_h #include "lua.h" /* Some header files included here need this definition */ typedef struct CallInfo CallInfo; /* ** Some notes about garbage-collected objects: All objects in Lua must ** be kept somehow accessible until being freed, so all objects always ** belong to one (and only one) of these lists, using field 'next' of ** the 'CommonHeader' for the link: ** ** 'allgc': all objects not marked for finalization; ** 'finobj': all objects marked for finalization; ** 'tobefnz': all objects ready to be finalized; ** 'fixedgc': all objects that are not to be collected (currently ** only small strings, such as reserved words). ** ** For the generational collector, some of these lists have marks for ** generations. Each mark points to the first element in the list for ** that particular generation; that generation goes until the next mark. ** ** 'allgc' -> 'survival': new objects; ** 'survival' -> 'old': objects that survived one collection; ** 'old1' -> 'reallyold': objects that became old in last collection; ** 'reallyold' -> NULL: objects old for more than one cycle. ** ** 'finobj' -> 'finobjsur': new objects marked for finalization; ** 'finobjsur' -> 'finobjold1': survived """"; ** 'finobjold1' -> 'finobjrold': just old """"; ** 'finobjrold' -> NULL: really old """". ** ** All lists can contain elements older than their main ages, due ** to 'luaC_checkfinalizer' and 'udata2finalize', which move ** objects between the normal lists and the "marked for finalization" ** lists. Moreover, barriers can age young objects in young lists as ** OLD0, which then become OLD1. However, a list never contains ** elements younger than their main ages. ** ** The generational collector also uses a pointer 'firstold1', which ** points to the first OLD1 object in the list. It is used to optimize ** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc' ** and 'reallyold', but often the list has no OLD1 objects or they are ** after 'old1'.) Note the difference between it and 'old1': ** 'firstold1': no OLD1 objects before this point; there can be all ** ages after it. ** 'old1': no objects younger than OLD1 after this point. */ /* ** Moreover, there is another set of lists that control gray objects. ** These lists are linked by fields 'gclist'. (All objects that ** can become gray have such a field. The field is not the same ** in all objects, but it always has this name.) Any gray object ** must belong to one of these lists, and all objects in these lists ** must be gray (with two exceptions explained below): ** ** 'gray': regular gray objects, still waiting to be visited. ** 'grayagain': objects that must be revisited at the atomic phase. ** That includes ** - black objects got in a write barrier; ** - all kinds of weak tables during propagation phase; ** - all threads. ** 'weak': tables with weak values to be cleared; ** 'ephemeron': ephemeron tables with white->white entries; ** 'allweak': tables with weak keys and/or weak values to be cleared. ** ** The exceptions to that "gray rule" are: ** - TOUCHED2 objects in generational mode stay in a gray list (because ** they must be visited again at the end of the cycle), but they are ** marked black because assignments to them must activate barriers (to ** move them back to TOUCHED1). ** - Open upvalues are kept gray to avoid barriers, but they stay out ** of gray lists. (They don't even have a 'gclist' field.) */ /* ** About 'nCcalls': This count has two parts: the lower 16 bits counts ** the number of recursive invocations in the C stack; the higher ** 16 bits counts the number of non-yieldable calls in the stack. ** (They are together so that we can change and save both with one ** instruction.) */ /* true if this thread does not have non-yieldable calls in the stack */ #define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0) /* real number of C calls */ #define getCcalls(L) ((L)->nCcalls & 0xffff) /* Increment the number of non-yieldable calls */ #define incnny(L) ((L)->nCcalls += 0x10000) /* Decrement the number of non-yieldable calls */ #define decnny(L) ((L)->nCcalls -= 0x10000) /* Non-yieldable call increment */ #define nyci (0x10000 | 1) struct lua_longjmp; /* defined in ldo.c */ /* ** Atomic type (relative to signals) to better ensure that 'lua_sethook' ** is thread safe */ #if !defined(l_signalT) #include #define l_signalT sig_atomic_t #endif /* ** Extra stack space to handle TM calls and some other extras. This ** space is not included in 'stack_last'. It is used only to avoid stack ** checks, either because the element will be promptly popped or because ** there will be a stack check soon after the push. Function frames ** never use this extra space, so it does not need to be kept clean. */ #define EXTRA_STACK 5 /* ** Size of cache for strings in the API. 'N' is the number of ** sets (better be a prime) and "M" is the size of each set. ** (M == 1 makes a direct cache.) */ #if !defined(STRCACHE_N) #define STRCACHE_N 53 #define STRCACHE_M 2 #endif #define BASIC_STACK_SIZE (2*LUA_MINSTACK) #define stacksize(th) cast_int((th)->stack_last.p - (th)->stack.p) /* kinds of Garbage Collection */ #define KGC_INC 0 /* incremental gc */ #define KGC_GENMINOR 1 /* generational gc in minor (regular) mode */ #define KGC_GENMAJOR 2 /* generational in major mode */ typedef struct stringtable { TString **hash; /* array of buckets (linked lists of strings) */ int nuse; /* number of elements */ int size; /* number of buckets */ } stringtable; /* ** Information about a call. ** About union 'u': ** - field 'l' is used only for Lua functions; ** - field 'c' is used only for C functions. ** About union 'u2': ** - field 'funcidx' is used only by C functions while doing a ** protected call; ** - field 'nyield' is used only while a function is "doing" an ** yield (from the yield until the next resume); ** - field 'nres' is used only while closing tbc variables when ** returning from a function; */ struct CallInfo { StkIdRel func; /* function index in the stack */ StkIdRel top; /* top for this function */ struct CallInfo *previous, *next; /* dynamic call link */ union { struct { /* only for Lua functions */ const Instruction *savedpc; volatile l_signalT trap; /* function is tracing lines/counts */ int nextraargs; /* # of extra arguments in vararg functions */ } l; struct { /* only for C functions */ lua_KFunction k; /* continuation in case of yields */ ptrdiff_t old_errfunc; lua_KContext ctx; /* context info. in case of yields */ } c; } u; union { int funcidx; /* called-function index */ int nyield; /* number of values yielded */ int nres; /* number of values returned */ } u2; l_uint32 callstatus; }; /* ** Maximum expected number of results from a function ** (must fit in CIST_NRESULTS). */ #define MAXRESULTS 250 /* ** Bits in CallInfo status */ /* bits 0-7 are the expected number of results from this function + 1 */ #define CIST_NRESULTS 0xffu /* bits 8-11 count call metamethods (and their extra arguments) */ #define CIST_CCMT 8 /* the offset, not the mask */ #define MAX_CCMT (0xfu << CIST_CCMT) /* Bits 12-14 are used for CIST_RECST (see below) */ #define CIST_RECST 12 /* the offset, not the mask */ /* call is running a C function (still in first 16 bits) */ #define CIST_C (1u << (CIST_RECST + 3)) /* call is on a fresh "luaV_execute" frame */ #define CIST_FRESH (cast(l_uint32, CIST_C) << 1) /* function is closing tbc variables */ #define CIST_CLSRET (CIST_FRESH << 1) /* function has tbc variables to close */ #define CIST_TBC (CIST_CLSRET << 1) /* original value of 'allowhook' */ #define CIST_OAH (CIST_TBC << 1) /* call is running a debug hook */ #define CIST_HOOKED (CIST_OAH << 1) /* doing a yieldable protected call */ #define CIST_YPCALL (CIST_HOOKED << 1) /* call was tail called */ #define CIST_TAIL (CIST_YPCALL << 1) /* last hook called yielded */ #define CIST_HOOKYIELD (CIST_TAIL << 1) /* function "called" a finalizer */ #define CIST_FIN (CIST_HOOKYIELD << 1) #define get_nresults(cs) (cast_int((cs) & CIST_NRESULTS) - 1) /* ** Field CIST_RECST stores the "recover status", used to keep the error ** status while closing to-be-closed variables in coroutines, so that ** Lua can correctly resume after an yield from a __close method called ** because of an error. (Three bits are enough for error status.) */ #define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7) #define setcistrecst(ci,st) \ check_exp(((st) & 7) == (st), /* status must fit in three bits */ \ ((ci)->callstatus = ((ci)->callstatus & ~(7u << CIST_RECST)) \ | (cast(l_uint32, st) << CIST_RECST))) /* active function is a Lua function */ #define isLua(ci) (!((ci)->callstatus & CIST_C)) /* call is running Lua code (not a hook) */ #define isLuacode(ci) (!((ci)->callstatus & (CIST_C | CIST_HOOKED))) #define setoah(ci,v) \ ((ci)->callstatus = ((v) ? (ci)->callstatus | CIST_OAH \ : (ci)->callstatus & ~CIST_OAH)) #define getoah(ci) (((ci)->callstatus & CIST_OAH) ? 1 : 0) /* ** 'per thread' state */ struct lua_State { CommonHeader; lu_byte allowhook; TStatus status; StkIdRel top; /* first free slot in the stack */ struct global_State *l_G; CallInfo *ci; /* call info for current function */ StkIdRel stack_last; /* end of stack (last element + 1) */ StkIdRel stack; /* stack base */ UpVal *openupval; /* list of open upvalues in this stack */ StkIdRel tbclist; /* list of to-be-closed variables */ GCObject *gclist; struct lua_State *twups; /* list of threads with open upvalues */ struct lua_longjmp *errorJmp; /* current error recover point */ CallInfo base_ci; /* CallInfo for first level (C host) */ volatile lua_Hook hook; ptrdiff_t errfunc; /* current error handling function (stack index) */ l_uint32 nCcalls; /* number of nested non-yieldable or C calls */ int oldpc; /* last pc traced */ int nci; /* number of items in 'ci' list */ int basehookcount; int hookcount; volatile l_signalT hookmask; struct { /* info about transferred values (for call/return hooks) */ int ftransfer; /* offset of first value transferred */ int ntransfer; /* number of values transferred */ } transferinfo; }; /* ** thread state + extra space */ typedef struct LX { lu_byte extra_[LUA_EXTRASPACE]; lua_State l; } LX; /* ** 'global state', shared by all threads of this state */ typedef struct global_State { lua_Alloc frealloc; /* function to reallocate memory */ void *ud; /* auxiliary data to 'frealloc' */ l_mem GCtotalbytes; /* number of bytes currently allocated + debt */ l_mem GCdebt; /* bytes counted but not yet allocated */ l_mem GCmarked; /* number of objects marked in a GC cycle */ l_mem GCmajorminor; /* auxiliary counter to control major-minor shifts */ stringtable strt; /* hash table for strings */ TValue l_registry; TValue nilvalue; /* a nil value */ unsigned int seed; /* randomized seed for hashes */ lu_byte gcparams[LUA_GCPN]; lu_byte currentwhite; lu_byte gcstate; /* state of garbage collector */ lu_byte gckind; /* kind of GC running */ lu_byte gcstopem; /* stops emergency collections */ lu_byte gcstp; /* control whether GC is running */ lu_byte gcemergency; /* true if this is an emergency collection */ GCObject *allgc; /* list of all collectable objects */ GCObject **sweepgc; /* current position of sweep in list */ GCObject *finobj; /* list of collectable objects with finalizers */ GCObject *gray; /* list of gray objects */ GCObject *grayagain; /* list of objects to be traversed atomically */ GCObject *weak; /* list of tables with weak values */ GCObject *ephemeron; /* list of ephemeron tables (weak keys) */ GCObject *allweak; /* list of all-weak tables */ GCObject *tobefnz; /* list of userdata to be GC */ GCObject *fixedgc; /* list of objects not to be collected */ /* fields for generational collector */ GCObject *survival; /* start of objects that survived one GC cycle */ GCObject *old1; /* start of old1 objects */ GCObject *reallyold; /* objects more than one cycle old ("really old") */ GCObject *firstold1; /* first OLD1 object in the list (if any) */ GCObject *finobjsur; /* list of survival objects with finalizers */ GCObject *finobjold1; /* list of old1 objects with finalizers */ GCObject *finobjrold; /* list of really old objects with finalizers */ struct lua_State *twups; /* list of threads with open upvalues */ lua_CFunction panic; /* to be called in unprotected errors */ TString *memerrmsg; /* message for memory-allocation errors */ TString *tmname[TM_N]; /* array with tag-method names */ struct Table *mt[LUA_NUMTYPES]; /* metatables for basic types */ TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */ lua_WarnFunction warnf; /* warning function */ void *ud_warn; /* auxiliary data to 'warnf' */ LX mainth; /* main thread of this state */ } global_State; #define G(L) (L->l_G) #define mainthread(G) (&(G)->mainth.l) /* ** 'g->nilvalue' being a nil value flags that the state was completely ** build. */ #define completestate(g) ttisnil(&g->nilvalue) /* ** Union of all collectable objects (only for conversions) ** ISO C99, 6.5.2.3 p.5: ** "if a union contains several structures that share a common initial ** sequence [...], and if the union object currently contains one ** of these structures, it is permitted to inspect the common initial ** part of any of them anywhere that a declaration of the complete type ** of the union is visible." */ union GCUnion { GCObject gc; /* common header */ struct TString ts; struct Udata u; union Closure cl; struct Table h; struct Proto p; struct lua_State th; /* thread */ struct UpVal upv; }; /* ** ISO C99, 6.7.2.1 p.14: ** "A pointer to a union object, suitably converted, points to each of ** its members [...], and vice versa." */ #define cast_u(o) cast(union GCUnion *, (o)) /* macros to convert a GCObject into a specific value */ #define gco2ts(o) \ check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts)) #define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u)) #define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l)) #define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c)) #define gco2cl(o) \ check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl)) #define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h)) #define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p)) #define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th)) #define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv)) /* ** macro to convert a Lua object into a GCObject */ #define obj2gco(v) \ check_exp(novariant((v)->tt) >= LUA_TSTRING, &(cast_u(v)->gc)) /* actual number of total memory allocated */ #define gettotalbytes(g) ((g)->GCtotalbytes - (g)->GCdebt) LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); LUAI_FUNC lu_mem luaE_threadsize (lua_State *L); LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L); LUAI_FUNC void luaE_shrinkCI (lua_State *L); LUAI_FUNC void luaE_checkcstack (lua_State *L); LUAI_FUNC void luaE_incCstack (lua_State *L); LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont); LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where); LUAI_FUNC TStatus luaE_resetthread (lua_State *L, TStatus status); #endif /* ** $Id: lapi.h $ ** Auxiliary functions from Lua API ** See Copyright Notice in lua.h */ #ifndef lapi_h #define lapi_h #if defined(LUA_USE_APICHECK) #include #define api_check(l,e,msg) assert(e) #else /* for testing */ #define api_check(l,e,msg) ((void)(l), lua_assert((e) && msg)) #endif /* Increments 'L->top.p', checking for stack overflows */ #define api_incr_top(L) \ (L->top.p++, api_check(L, L->top.p <= L->ci->top.p, "stack overflow")) /* ** macros that are executed whenever program enters the Lua core ** ('lua_lock') and leaves the core ('lua_unlock') */ #if !defined(lua_lock) #define lua_lock(L) ((void) 0) #define lua_unlock(L) ((void) 0) #endif /* ** If a call returns too many multiple returns, the callee may not have ** stack space to accommodate all results. In this case, this macro ** increases its stack space ('L->ci->top.p'). */ #define adjustresults(L,nres) \ { if ((nres) <= LUA_MULTRET && L->ci->top.p < L->top.p) \ L->ci->top.p = L->top.p; } /* Ensure the stack has at least 'n' elements */ #define api_checknelems(L,n) \ api_check(L, (n) < (L->top.p - L->ci->func.p), \ "not enough elements in the stack") /* Ensure the stack has at least 'n' elements to be popped. (Some ** functions only update a slot after checking it for popping, but that ** is only an optimization for a pop followed by a push.) */ #define api_checkpop(L,n) \ api_check(L, (n) < L->top.p - L->ci->func.p && \ L->tbclist.p < L->top.p - (n), \ "not enough free elements in the stack") #endif /* ** $Id: lcode.h $ ** Code generator for Lua ** See Copyright Notice in lua.h */ #ifndef lcode_h #define lcode_h /* ** Marks the end of a patch list. It is an invalid value both as an absolute ** address, and as a list link (would link an element to itself). */ #define NO_JUMP (-1) /* ** grep "ORDER OPR" if you change these enums (ORDER OP) */ typedef enum BinOpr { /* arithmetic operators */ OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW, OPR_DIV, OPR_IDIV, /* bitwise operators */ OPR_BAND, OPR_BOR, OPR_BXOR, OPR_SHL, OPR_SHR, /* string operator */ OPR_CONCAT, /* comparison operators */ OPR_EQ, OPR_LT, OPR_LE, OPR_NE, OPR_GT, OPR_GE, /* logical operators */ OPR_AND, OPR_OR, OPR_NOBINOPR } BinOpr; /* true if operation is foldable (that is, it is arithmetic or bitwise) */ #define foldbinop(op) ((op) <= OPR_SHR) #define luaK_codeABC(fs,o,a,b,c) luaK_codeABCk(fs,o,a,b,c,0) typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; /* get (pointer to) instruction of given 'expdesc' */ #define getinstruction(fs,e) ((fs)->f->code[(e)->u.info]) #define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) #define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) LUAI_FUNC int luaK_code (FuncState *fs, Instruction i); LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, int Bx); LUAI_FUNC int luaK_codeABCk (FuncState *fs, OpCode o, int A, int B, int C, int k); LUAI_FUNC int luaK_codevABCk (FuncState *fs, OpCode o, int A, int B, int C, int k); LUAI_FUNC int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v); LUAI_FUNC void luaK_fixline (FuncState *fs, int line); LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); LUAI_FUNC void luaK_codecheckglobal (FuncState *fs, expdesc *var, int k, int line); LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); LUAI_FUNC void luaK_int (FuncState *fs, int reg, lua_Integer n); LUAI_FUNC void luaK_vapar2local (FuncState *fs, expdesc *var); LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); LUAI_FUNC int luaK_jump (FuncState *fs); LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); LUAI_FUNC int luaK_getlabel (FuncState *fs); LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2, int line); LUAI_FUNC void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize); LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); LUAI_FUNC void luaK_finish (FuncState *fs); LUAI_FUNC l_noret luaK_semerror (LexState *ls, const char *fmt, ...); #endif /* ** $Id: lctype.h $ ** 'ctype' functions for Lua ** See Copyright Notice in lua.h */ #ifndef lctype_h #define lctype_h #include "lua.h" /* ** WARNING: the functions defined here do not necessarily correspond ** to the similar functions in the standard C ctype.h. They are ** optimized for the specific needs of Lua. */ #if !defined(LUA_USE_CTYPE) #if 'A' == 65 && '0' == 48 /* ASCII case: can use its own tables; faster and fixed */ #define LUA_USE_CTYPE 0 #else /* must use standard C ctype */ #define LUA_USE_CTYPE 1 #endif #endif #if !LUA_USE_CTYPE /* { */ #include #define ALPHABIT 0 #define DIGITBIT 1 #define PRINTBIT 2 #define SPACEBIT 3 #define XDIGITBIT 4 #define MASK(B) (1 << (B)) /* ** add 1 to char to allow index -1 (EOZ) */ #define testprop(c,p) (luai_ctype_[(c)+1] & (p)) /* ** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_' */ #define lislalpha(c) testprop(c, MASK(ALPHABIT)) #define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT))) #define lisdigit(c) testprop(c, MASK(DIGITBIT)) #define lisspace(c) testprop(c, MASK(SPACEBIT)) #define lisprint(c) testprop(c, MASK(PRINTBIT)) #define lisxdigit(c) testprop(c, MASK(XDIGITBIT)) /* ** In ASCII, this 'ltolower' is correct for alphabetic characters and ** for '.'. That is enough for Lua needs. ('check_exp' ensures that ** the character either is an upper-case letter or is unchanged by ** the transformation, which holds for lower-case letters and '.'.) */ #define ltolower(c) \ check_exp(('A' <= (c) && (c) <= 'Z') || (c) == ((c) | ('A' ^ 'a')), \ (c) | ('A' ^ 'a')) /* one entry for each character and for -1 (EOZ) */ LUAI_DDEC(const lu_byte luai_ctype_[UCHAR_MAX + 2];) #else /* }{ */ /* ** use standard C ctypes */ #include #define lislalpha(c) (isalpha(c) || (c) == '_') #define lislalnum(c) (isalnum(c) || (c) == '_') #define lisdigit(c) (isdigit(c)) #define lisspace(c) (isspace(c)) #define lisprint(c) (isprint(c)) #define lisxdigit(c) (isxdigit(c)) #define ltolower(c) (tolower(c)) #endif /* } */ #endif /* ** $Id: ldebug.h $ ** Auxiliary functions from Debug Interface module ** See Copyright Notice in lua.h */ #ifndef ldebug_h #define ldebug_h #define pcRel(pc, p) (cast_int((pc) - (p)->code) - 1) /* Active Lua function (given call info) */ #define ci_func(ci) (clLvalue(s2v((ci)->func.p))) #define resethookcount(L) (L->hookcount = L->basehookcount) /* ** mark for entries in 'lineinfo' array that has absolute information in ** 'abslineinfo' array */ #define ABSLINEINFO (-0x80) /* ** MAXimum number of successive Instructions WiTHout ABSolute line ** information. (A power of two allows fast divisions.) */ #if !defined(MAXIWTHABS) #define MAXIWTHABS 128 #endif LUAI_FUNC int luaG_getfuncline (const Proto *f, int pc); LUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos); LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *opname); LUAI_FUNC l_noret luaG_callerror (lua_State *L, const TValue *o); LUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what); LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, const TValue *p2, const char *msg); LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_errnnil (lua_State *L, LClosure *cl, int k); LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, int line); LUAI_FUNC l_noret luaG_errormsg (lua_State *L); LUAI_FUNC int luaG_traceexec (lua_State *L, const Instruction *pc); LUAI_FUNC int luaG_tracecall (lua_State *L); #endif /* ** $Id: ldo.h $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #ifndef ldo_h #define ldo_h /* ** Macro to check stack size and grow stack if needed. Parameters ** 'pre'/'pos' allow the macro to preserve a pointer into the ** stack across reallocations, doing the work only when needed. ** It also allows the running of one GC step when the stack is ** reallocated. ** 'condmovestack' is used in heavy tests to force a stack reallocation ** at every check. */ #if !defined(HARDSTACKTESTS) #define condmovestack(L,pre,pos) ((void)0) #else /* realloc stack keeping its size */ #define condmovestack(L,pre,pos) \ { int sz_ = stacksize(L); pre; luaD_reallocstack((L), sz_, 0); pos; } #endif #define luaD_checkstackaux(L,n,pre,pos) \ if (l_unlikely(L->stack_last.p - L->top.p <= (n))) \ { pre; luaD_growstack(L, n, 1); pos; } \ else { condmovestack(L,pre,pos); } /* In general, 'pre'/'pos' are empty (nothing to save) */ #define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0) #define savestack(L,pt) (cast_charp(pt) - cast_charp(L->stack.p)) #define restorestack(L,n) cast(StkId, cast_charp(L->stack.p) + (n)) /* macro to check stack size, preserving 'p' */ #define checkstackp(L,n,p) \ luaD_checkstackaux(L, n, \ ptrdiff_t t__ = savestack(L, p), /* save 'p' */ \ p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ /* ** Maximum depth for nested C calls, syntactical nested non-terminals, ** and other features implemented through recursion in C. (Value must ** fit in a 16-bit unsigned integer. It must also be compatible with ** the size of the C stack.) */ #if !defined(LUAI_MAXCCALLS) #define LUAI_MAXCCALLS 200 #endif /* type of protected functions, to be ran by 'runprotected' */ typedef void (*Pfunc) (lua_State *L, void *ud); LUAI_FUNC l_noret luaD_errerr (lua_State *L); LUAI_FUNC void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop); LUAI_FUNC TStatus luaD_protectedparser (lua_State *L, ZIO *z, const char *name, const char *mode); LUAI_FUNC void luaD_hook (lua_State *L, int event, int line, int fTransfer, int nTransfer); LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci); LUAI_FUNC int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1, int delta); LUAI_FUNC CallInfo *luaD_precall (lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); LUAI_FUNC TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level, TStatus status); LUAI_FUNC TStatus luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t oldtop, ptrdiff_t ef); LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres); LUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror); LUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror); LUAI_FUNC void luaD_shrinkstack (lua_State *L); LUAI_FUNC void luaD_inctop (lua_State *L); LUAI_FUNC int luaD_checkminstack (lua_State *L); LUAI_FUNC l_noret luaD_throw (lua_State *L, TStatus errcode); LUAI_FUNC l_noret luaD_throwbaselevel (lua_State *L, TStatus errcode); LUAI_FUNC TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); #endif /* ** $Id: lfunc.h $ ** Auxiliary functions to manipulate prototypes and closures ** See Copyright Notice in lua.h */ #ifndef lfunc_h #define lfunc_h #define sizeCclosure(n) \ (offsetof(CClosure, upvalue) + sizeof(TValue) * cast_uint(n)) #define sizeLclosure(n) \ (offsetof(LClosure, upvals) + sizeof(UpVal *) * cast_uint(n)) /* test whether thread is in 'twups' list */ #define isintwups(L) (L->twups != L) /* ** maximum number of upvalues in a closure (both C and Lua). (Value ** must fit in a VM register.) */ #define MAXUPVAL 255 #define upisopen(up) ((up)->v.p != &(up)->u.value) #define uplevel(up) check_exp(upisopen(up), cast(StkId, (up)->v.p)) /* ** maximum number of misses before giving up the cache of closures ** in prototypes */ #define MAXMISS 10 /* special status to close upvalues preserving the top of the stack */ #define CLOSEKTOP (LUA_ERRERR + 1) LUAI_FUNC Proto *luaF_newproto (lua_State *L); LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals); LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals); LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl); LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); LUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level); LUAI_FUNC void luaF_closeupval (lua_State *L, StkId level); LUAI_FUNC StkId luaF_close (lua_State *L, StkId level, TStatus status, int yy); LUAI_FUNC void luaF_unlinkupval (UpVal *uv); LUAI_FUNC lu_mem luaF_protosize (Proto *p); LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, int pc); #endif /* ** $Id: lgc.h $ ** Garbage Collector ** See Copyright Notice in lua.h */ #ifndef lgc_h #define lgc_h #include /* ** Collectable objects may have one of three colors: white, which means ** the object is not marked; gray, which means the object is marked, but ** its references may be not marked; and black, which means that the ** object and all its references are marked. The main invariant of the ** garbage collector, while marking objects, is that a black object can ** never point to a white one. Moreover, any gray object must be in a ** "gray list" (gray, grayagain, weak, allweak, ephemeron) so that it ** can be visited again before finishing the collection cycle. (Open ** upvalues are an exception to this rule, as they are attached to ** a corresponding thread.) These lists have no meaning when the ** invariant is not being enforced (e.g., sweep phase). */ /* ** Possible states of the Garbage Collector */ #define GCSpropagate 0 #define GCSenteratomic 1 #define GCSatomic 2 #define GCSswpallgc 3 #define GCSswpfinobj 4 #define GCSswptobefnz 5 #define GCSswpend 6 #define GCScallfin 7 #define GCSpause 8 #define issweepphase(g) \ (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend) /* ** macro to tell when main invariant (white objects cannot point to black ** ones) must be kept. During a collection, the sweep phase may break ** the invariant, as objects turned white may point to still-black ** objects. The invariant is restored when sweep ends and all objects ** are white again. */ #define keepinvariant(g) ((g)->gcstate <= GCSatomic) /* ** some useful bit tricks */ #define resetbits(x,m) ((x) &= cast_byte(~(m))) #define setbits(x,m) ((x) |= (m)) #define testbits(x,m) ((x) & (m)) #define bitmask(b) (1<<(b)) #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) #define l_setbit(x,b) setbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b)) /* ** Layout for bit use in 'marked' field. First three bits are ** used for object "age" in generational mode. Last bit is used ** by tests. */ #define WHITE0BIT 3 /* object is white (type 0) */ #define WHITE1BIT 4 /* object is white (type 1) */ #define BLACKBIT 5 /* object is black */ #define FINALIZEDBIT 6 /* object has been marked for finalization */ #define TESTBIT 7 #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) #define iswhite(x) testbits((x)->marked, WHITEBITS) #define isblack(x) testbit((x)->marked, BLACKBIT) #define isgray(x) /* neither white nor black */ \ (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT))) #define tofinalize(x) testbit((x)->marked, FINALIZEDBIT) #define otherwhite(g) ((g)->currentwhite ^ WHITEBITS) #define isdeadm(ow,m) ((m) & (ow)) #define isdead(g,v) isdeadm(otherwhite(g), (v)->marked) #define changewhite(x) ((x)->marked ^= WHITEBITS) #define nw2black(x) \ check_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT)) #define luaC_white(g) cast_byte((g)->currentwhite & WHITEBITS) /* object age in generational mode */ #define G_NEW 0 /* created in current cycle */ #define G_SURVIVAL 1 /* created in previous cycle */ #define G_OLD0 2 /* marked old by frw. barrier in this cycle */ #define G_OLD1 3 /* first full cycle as old */ #define G_OLD 4 /* really old object (not to be visited) */ #define G_TOUCHED1 5 /* old object touched this cycle */ #define G_TOUCHED2 6 /* old object touched in previous cycle */ #define AGEBITS 7 /* all age bits (111) */ #define getage(o) ((o)->marked & AGEBITS) #define setage(o,a) ((o)->marked = cast_byte(((o)->marked & (~AGEBITS)) | a)) #define isold(o) (getage(o) > G_SURVIVAL) /* ** In generational mode, objects are created 'new'. After surviving one ** cycle, they become 'survival'. Both 'new' and 'survival' can point ** to any other object, as they are traversed at the end of the cycle. ** We call them both 'young' objects. ** If a survival object survives another cycle, it becomes 'old1'. ** 'old1' objects can still point to survival objects (but not to ** new objects), so they still must be traversed. After another cycle ** (that, being old, 'old1' objects will "survive" no matter what) ** finally the 'old1' object becomes really 'old', and then they ** are no more traversed. ** ** To keep its invariants, the generational mode uses the same barriers ** also used by the incremental mode. If a young object is caught in a ** forward barrier, it cannot become old immediately, because it can ** still point to other young objects. Instead, it becomes 'old0', ** which in the next cycle becomes 'old1'. So, 'old0' objects is ** old but can point to new and survival objects; 'old1' is old ** but cannot point to new objects; and 'old' cannot point to any ** young object. ** ** If any old object ('old0', 'old1', 'old') is caught in a back ** barrier, it becomes 'touched1' and goes into a gray list, to be ** visited at the end of the cycle. There it evolves to 'touched2', ** which can point to survivals but not to new objects. In yet another ** cycle then it becomes 'old' again. ** ** The generational mode must also control the colors of objects, ** because of the barriers. While the mutator is running, young objects ** are kept white. 'old', 'old1', and 'touched2' objects are kept black, ** as they cannot point to new objects; exceptions are threads and open ** upvalues, which age to 'old1' and 'old' but are kept gray. 'old0' ** objects may be gray or black, as in the incremental mode. 'touched1' ** objects are kept gray, as they must be visited again at the end of ** the cycle. */ /* ** {====================================================== ** Default Values for GC parameters ** ======================================================= */ /* ** Minor collections will shift to major ones after LUAI_MINORMAJOR% ** bytes become old. */ #define LUAI_MINORMAJOR 70 /* ** Major collections will shift to minor ones after a collection ** collects at least LUAI_MAJORMINOR% of the new bytes. */ #define LUAI_MAJORMINOR 50 /* ** A young (minor) collection will run after creating LUAI_GENMINORMUL% ** new bytes. */ #define LUAI_GENMINORMUL 20 /* incremental */ /* Number of bytes must be LUAI_GCPAUSE% before starting new cycle */ #define LUAI_GCPAUSE 250 /* ** Step multiplier: The collector handles LUAI_GCMUL% work units for ** each new allocated word. (Each "work unit" corresponds roughly to ** sweeping one object or traversing one slot.) */ #define LUAI_GCMUL 200 /* How many bytes to allocate before next GC step */ #define LUAI_GCSTEPSIZE (200 * sizeof(Table)) #define setgcparam(g,p,v) (g->gcparams[LUA_GCP##p] = luaO_codeparam(v)) #define applygcparam(g,p,x) luaO_applyparam(g->gcparams[LUA_GCP##p], x) /* }====================================================== */ /* ** Control when GC is running: */ #define GCSTPUSR 1 /* bit true when GC stopped by user */ #define GCSTPGC 2 /* bit true when GC stopped by itself */ #define GCSTPCLS 4 /* bit true when closing Lua state */ #define gcrunning(g) ((g)->gcstp == 0) /* ** Does one step of collection when debt becomes zero. 'pre'/'pos' ** allows some adjustments to be done only when needed. macro ** 'condchangemem' is used only for heavy tests (forcing a full ** GC cycle on every opportunity) */ #if !defined(HARDMEMTESTS) #define condchangemem(L,pre,pos,emg) ((void)0) #else #define condchangemem(L,pre,pos,emg) \ { if (gcrunning(G(L))) { pre; luaC_fullgc(L, emg); pos; } } #endif #define luaC_condGC(L,pre,pos) \ { if (G(L)->GCdebt <= 0) { pre; luaC_step(L); pos;}; \ condchangemem(L,pre,pos,0); } /* more often than not, 'pre'/'pos' are empty */ #define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) #define luaC_objbarrier(L,p,o) ( \ (isblack(p) && iswhite(o)) ? \ luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) #define luaC_barrier(L,p,v) ( \ iscollectable(v) ? luaC_objbarrier(L,p,gcvalue(v)) : cast_void(0)) #define luaC_objbarrierback(L,p,o) ( \ (isblack(p) && iswhite(o)) ? luaC_barrierback_(L,p) : cast_void(0)) #define luaC_barrierback(L,p,v) ( \ iscollectable(v) ? luaC_objbarrierback(L, p, gcvalue(v)) : cast_void(0)) LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); LUAI_FUNC void luaC_freeallobjects (lua_State *L); LUAI_FUNC void luaC_step (lua_State *L); LUAI_FUNC void luaC_runtilstate (lua_State *L, int state, int fast); LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); LUAI_FUNC GCObject *luaC_newobj (lua_State *L, lu_byte tt, size_t sz); LUAI_FUNC GCObject *luaC_newobjdt (lua_State *L, lu_byte tt, size_t sz, size_t offset); LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o); LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); LUAI_FUNC void luaC_changemode (lua_State *L, int newmode); #endif /* ** $Id: lmem.h $ ** Interface to Memory Manager ** See Copyright Notice in lua.h */ #ifndef lmem_h #define lmem_h #include #include "lua.h" #define luaM_error(L) luaD_throw(L, LUA_ERRMEM) /* ** This macro tests whether it is safe to multiply 'n' by the size of ** type 't' without overflows. Because 'e' is always constant, it avoids ** the runtime division MAX_SIZET/(e). ** (The macro is somewhat complex to avoid warnings: The 'sizeof' ** comparison avoids a runtime comparison when overflow cannot occur. ** The compiler should be able to optimize the real test by itself, but ** when it does it, it may give a warning about "comparison is always ** false due to limited range of data type"; the +1 tricks the compiler, ** avoiding this warning but also this optimization.) */ #define luaM_testsize(n,e) \ (sizeof(n) >= sizeof(size_t) && cast_sizet((n)) + 1 > MAX_SIZET/(e)) #define luaM_checksize(L,n,e) \ (luaM_testsize(n,e) ? luaM_toobig(L) : cast_void(0)) /* ** Computes the minimum between 'n' and 'MAX_SIZET/sizeof(t)', so that ** the result is not larger than 'n' and cannot overflow a 'size_t' ** when multiplied by the size of type 't'. (Assumes that 'n' is an ** 'int' and that 'int' is not larger than 'size_t'.) */ #define luaM_limitN(n,t) \ ((cast_sizet(n) <= MAX_SIZET/sizeof(t)) ? (n) : \ cast_int((MAX_SIZET/sizeof(t)))) /* ** Arrays of chars do not need any test */ #define luaM_reallocvchar(L,b,on,n) \ cast_charp(luaM_saferealloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char))) #define luaM_freemem(L, b, s) luaM_free_(L, (b), (s)) #define luaM_free(L, b) luaM_free_(L, (b), sizeof(*(b))) #define luaM_freearray(L, b, n) luaM_free_(L, (b), (n)*sizeof(*(b))) #define luaM_new(L,t) cast(t*, luaM_malloc_(L, sizeof(t), 0)) #define luaM_newvector(L,n,t) \ cast(t*, luaM_malloc_(L, cast_sizet(n)*sizeof(t), 0)) #define luaM_newvectorchecked(L,n,t) \ (luaM_checksize(L,n,sizeof(t)), luaM_newvector(L,n,t)) #define luaM_newobject(L,tag,s) luaM_malloc_(L, (s), tag) #define luaM_newblock(L, size) luaM_newvector(L, size, char) #define luaM_growvector(L,v,nelems,size,t,limit,e) \ ((v)=cast(t *, luaM_growaux_(L,v,nelems,&(size),sizeof(t), \ luaM_limitN(limit,t),e))) #define luaM_reallocvector(L, v,oldn,n,t) \ (cast(t *, luaM_realloc_(L, v, cast_sizet(oldn) * sizeof(t), \ cast_sizet(n) * sizeof(t)))) #define luaM_shrinkvector(L,v,size,fs,t) \ ((v)=cast(t *, luaM_shrinkvector_(L, v, &(size), fs, sizeof(t)))) LUAI_FUNC l_noret luaM_toobig (lua_State *L); /* not to be called directly */ LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, size_t size); LUAI_FUNC void *luaM_saferealloc_ (lua_State *L, void *block, size_t oldsize, size_t size); LUAI_FUNC void luaM_free_ (lua_State *L, void *block, size_t osize); LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *size, unsigned size_elem, int limit, const char *what); LUAI_FUNC void *luaM_shrinkvector_ (lua_State *L, void *block, int *nelem, int final_n, unsigned size_elem); LUAI_FUNC void *luaM_malloc_ (lua_State *L, size_t size, int tag); #endif /* ** $Id: lprefix.h $ ** Definitions for Lua code that must come before any other header file ** See Copyright Notice in lua.h */ #ifndef lprefix_h #define lprefix_h /* ** Allows POSIX/XSI stuff */ #if !defined(LUA_USE_C89) /* { */ #if !defined(_XOPEN_SOURCE) #define _XOPEN_SOURCE 600 #elif _XOPEN_SOURCE == 0 #undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */ #endif /* ** Allows manipulation of large files in gcc and some other compilers */ #if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS) #define _LARGEFILE_SOURCE 1 #define _FILE_OFFSET_BITS 64 #endif #endif /* } */ /* ** Windows stuff */ #if defined(_WIN32) /* { */ #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */ #endif #endif /* } */ #endif /* ** $Id: lstring.h $ ** String table (keep all strings handled by Lua) ** See Copyright Notice in lua.h */ #ifndef lstring_h #define lstring_h /* ** Memory-allocation error message must be preallocated (it cannot ** be created after memory is exhausted) */ #define MEMERRMSG "not enough memory" /* ** Maximum length for short strings, that is, strings that are ** internalized. (Cannot be smaller than reserved words or tags for ** metamethods, as these strings must be internalized; ** #("function") = 8, #("__newindex") = 10.) */ #if !defined(LUAI_MAXSHORTLEN) #define LUAI_MAXSHORTLEN 40 #endif /* ** Size of a short TString: Size of the header plus space for the string ** itself (including final '\0'). */ #define sizestrshr(l) \ (offsetof(TString, contents) + ((l) + 1) * sizeof(char)) #define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ (sizeof(s)/sizeof(char))-1)) /* ** test whether a string is a reserved word */ #define isreserved(s) (strisshr(s) && (s)->extra > 0) /* ** equality for short strings, which are always internalized */ #define eqshrstr(a,b) check_exp((a)->tt == LUA_VSHRSTR, (a) == (b)) LUAI_FUNC unsigned luaS_hashlongstr (TString *ts); LUAI_FUNC int luaS_eqstr (TString *a, TString *b); LUAI_FUNC void luaS_resize (lua_State *L, int newsize); LUAI_FUNC void luaS_clearcache (global_State *g); LUAI_FUNC void luaS_init (lua_State *L); LUAI_FUNC void luaS_remove (lua_State *L, TString *ts); LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, unsigned short nuvalue); LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); LUAI_FUNC TString *luaS_new (lua_State *L, const char *str); LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l); LUAI_FUNC TString *luaS_newextlstr (lua_State *L, const char *s, size_t len, lua_Alloc falloc, void *ud); LUAI_FUNC size_t luaS_sizelngstr (size_t len, int kind); LUAI_FUNC TString *luaS_normstr (lua_State *L, TString *ts); #endif /* ** $Id: ltable.h $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ #ifndef ltable_h #define ltable_h #define gnode(t,i) (&(t)->node[i]) #define gval(n) (&(n)->i_val) #define gnext(n) ((n)->u.next) /* ** Clear all bits of fast-access metamethods, which means that the table ** may have any of these metamethods. (First access that fails after the ** clearing will set the bit again.) */ #define invalidateTMcache(t) ((t)->flags &= cast_byte(~maskflags)) /* ** Bit BITDUMMY set in 'flags' means the table is using the dummy node ** for its hash part. */ #define BITDUMMY (1 << 6) #define NOTBITDUMMY cast_byte(~BITDUMMY) #define isdummy(t) ((t)->flags & BITDUMMY) #define setnodummy(t) ((t)->flags &= NOTBITDUMMY) #define setdummy(t) ((t)->flags |= BITDUMMY) /* allocated size for hash nodes */ #define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t)) /* returns the Node, given the value of a table entry */ #define nodefromval(v) cast(Node *, (v)) #define luaH_fastgeti(t,k,res,tag) \ { Table *h = t; lua_Unsigned u = l_castS2U(k) - 1u; \ if ((u < h->asize)) { \ tag = *getArrTag(h, u); \ if (!tagisempty(tag)) { farr2val(h, u, tag, res); }} \ else { tag = luaH_getint(h, (k), res); }} #define luaH_fastseti(t,k,val,hres) \ { Table *h = t; lua_Unsigned u = l_castS2U(k) - 1u; \ if ((u < h->asize)) { \ lu_byte *tag = getArrTag(h, u); \ if (checknoTM(h->metatable, TM_NEWINDEX) || !tagisempty(*tag)) \ { fval2arr(h, u, tag, val); hres = HOK; } \ else hres = ~cast_int(u); } \ else { hres = luaH_psetint(h, k, val); }} /* results from pset */ #define HOK 0 #define HNOTFOUND 1 #define HNOTATABLE 2 #define HFIRSTNODE 3 /* ** 'luaH_get*' operations set 'res', unless the value is absent, and ** return the tag of the result. ** The 'luaH_pset*' (pre-set) operations set the given value and return ** HOK, unless the original value is absent. In that case, if the key ** is really absent, they return HNOTFOUND. Otherwise, if there is a ** slot with that key but with no value, 'luaH_pset*' return an encoding ** of where the key is (usually called 'hres'). (pset cannot set that ** value because there might be a metamethod.) If the slot is in the ** hash part, the encoding is (HFIRSTNODE + hash index); if the slot is ** in the array part, the encoding is (~array index), a negative value. ** The value HNOTATABLE is used by the fast macros to signal that the ** value being indexed is not a table. ** (The size for the array part is limited by the maximum power of two ** that fits in an unsigned integer; that is INT_MAX+1. So, the C-index ** ranges from 0, which encodes to -1, to INT_MAX, which encodes to ** INT_MIN. The size of the hash part is limited by the maximum power of ** two that fits in a signed integer; that is (INT_MAX+1)/2. So, it is ** safe to add HFIRSTNODE to any index there.) */ /* ** The array part of a table is represented by an inverted array of ** values followed by an array of tags, to avoid wasting space with ** padding. In between them there is an unsigned int, explained later. ** The 'array' pointer points between the two arrays, so that values are ** indexed with negative indices and tags with non-negative indices. Values Tags -------------------------------------------------------- ... | Value 1 | Value 0 |unsigned|0|1|... -------------------------------------------------------- ^ t->array ** All accesses to 't->array' should be through the macros 'getArrTag' ** and 'getArrVal'. */ /* Computes the address of the tag for the abstract C-index 'k' */ #define getArrTag(t,k) (cast(lu_byte*, (t)->array) + sizeof(unsigned) + (k)) /* Computes the address of the value for the abstract C-index 'k' */ #define getArrVal(t,k) ((t)->array - 1 - (k)) /* ** The unsigned between the two arrays is used as a hint for #t; ** see luaH_getn. It is stored there to avoid wasting space in ** the structure Table for tables with no array part. */ #define lenhint(t) cast(unsigned*, (t)->array) /* ** Move TValues to/from arrays, using C indices */ #define arr2obj(h,k,val) \ ((val)->tt_ = *getArrTag(h,(k)), (val)->value_ = *getArrVal(h,(k))) #define obj2arr(h,k,val) \ (*getArrTag(h,(k)) = (val)->tt_, *getArrVal(h,(k)) = (val)->value_) /* ** Often, we need to check the tag of a value before moving it. The ** following macros also move TValues to/from arrays, but receive the ** precomputed tag value or address as an extra argument. */ #define farr2val(h,k,tag,res) \ ((res)->tt_ = tag, (res)->value_ = *getArrVal(h,(k))) #define fval2arr(h,k,tag,val) \ (*tag = (val)->tt_, *getArrVal(h,(k)) = (val)->value_) LUAI_FUNC lu_byte luaH_get (Table *t, const TValue *key, TValue *res); LUAI_FUNC lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res); LUAI_FUNC lu_byte luaH_getstr (Table *t, TString *key, TValue *res); LUAI_FUNC lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res); /* Special get for metamethods */ LUAI_FUNC const TValue *luaH_Hgetshortstr (Table *t, TString *key); LUAI_FUNC int luaH_psetint (Table *t, lua_Integer key, TValue *val); LUAI_FUNC int luaH_psetshortstr (Table *t, TString *key, TValue *val); LUAI_FUNC int luaH_psetstr (Table *t, TString *key, TValue *val); LUAI_FUNC int luaH_pset (Table *t, const TValue *key, TValue *val); LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value); LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value); LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key, TValue *value, int hres); LUAI_FUNC Table *luaH_new (lua_State *L); LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned nasize, unsigned nhsize); LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned nasize); LUAI_FUNC lu_mem luaH_size (Table *t); LUAI_FUNC void luaH_free (lua_State *L, Table *t); LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); LUAI_FUNC lua_Unsigned luaH_getn (lua_State *L, Table *t); #if defined(LUA_DEBUG) LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); #endif #endif /* ** $Id: lundump.h $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ #ifndef lundump_h #define lundump_h #include /* data to catch conversion errors */ #define LUAC_DATA "\x19\x93\r\n\x1a\n" #define LUAC_INT -0x5678 #define LUAC_INST 0x12345678 #define LUAC_NUM cast_num(-370.5) /* ** Encode major-minor version in one byte, one nibble for each */ #define LUAC_VERSION (LUA_VERSION_MAJOR_N*16+LUA_VERSION_MINOR_N) #define LUAC_FORMAT 0 /* this is the official format */ /* load one chunk; from lundump.c */ LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name, int fixed); /* dump one chunk; from ldump.c */ LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); #endif /* ** $Id: lvm.h $ ** Lua virtual machine ** See Copyright Notice in lua.h */ #ifndef lvm_h #define lvm_h #if !defined(LUA_NOCVTN2S) #define cvt2str(o) ttisnumber(o) #else #define cvt2str(o) 0 /* no conversion from numbers to strings */ #endif #if !defined(LUA_NOCVTS2N) #define cvt2num(o) ttisstring(o) #else #define cvt2num(o) 0 /* no conversion from strings to numbers */ #endif /* ** You can define LUA_FLOORN2I if you want to convert floats to integers ** by flooring them (instead of raising an error if they are not ** integral values) */ #if !defined(LUA_FLOORN2I) #define LUA_FLOORN2I F2Ieq #endif /* ** Rounding modes for float->integer coercion */ typedef enum { F2Ieq, /* no rounding; accepts only integral values */ F2Ifloor, /* takes the floor of the number */ F2Iceil /* takes the ceiling of the number */ } F2Imod; /* convert an object to a float (including string coercion) */ #define tonumber(o,n) \ (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n)) /* convert an object to a float (without string coercion) */ #define tonumberns(o,n) \ (ttisfloat(o) ? ((n) = fltvalue(o), 1) : \ (ttisinteger(o) ? ((n) = cast_num(ivalue(o)), 1) : 0)) /* convert an object to an integer (including string coercion) */ #define tointeger(o,i) \ (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \ : luaV_tointeger(o,i,LUA_FLOORN2I)) /* convert an object to an integer (without string coercion) */ #define tointegerns(o,i) \ (l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \ : luaV_tointegerns(o,i,LUA_FLOORN2I)) #define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2)) #define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2) /* ** fast track for 'gettable' */ #define luaV_fastget(t,k,res,f, tag) \ (tag = (!ttistable(t) ? LUA_VNOTABLE : f(hvalue(t), k, res))) /* ** Special case of 'luaV_fastget' for integers, inlining the fast case ** of 'luaH_getint'. */ #define luaV_fastgeti(t,k,res,tag) \ if (!ttistable(t)) tag = LUA_VNOTABLE; \ else { luaH_fastgeti(hvalue(t), k, res, tag); } #define luaV_fastset(t,k,val,hres,f) \ (hres = (!ttistable(t) ? HNOTATABLE : f(hvalue(t), k, val))) #define luaV_fastseti(t,k,val,hres) \ if (!ttistable(t)) hres = HNOTATABLE; \ else { luaH_fastseti(hvalue(t), k, val, hres); } /* ** Finish a fast set operation (when fast set succeeds). */ #define luaV_finishfastset(L,t,v) luaC_barrierback(L, gcvalue(t), v) /* ** Shift right is the same as shift left with a negative 'y' */ #define luaV_shiftr(x,y) luaV_shiftl(x,intop(-, 0, y)) LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2); LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r); LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r); LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n); LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode); LUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode); LUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode); LUAI_FUNC lu_byte luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val, lu_byte tag); LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key, TValue *val, int aux); LUAI_FUNC void luaV_finishOp (lua_State *L); LUAI_FUNC void luaV_execute (lua_State *L, CallInfo *ci); LUAI_FUNC void luaV_concat (lua_State *L, int total); LUAI_FUNC lua_Integer luaV_idiv (lua_State *L, lua_Integer x, lua_Integer y); LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y); LUAI_FUNC lua_Number luaV_modf (lua_State *L, lua_Number x, lua_Number y); LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y); LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb); #endif /* ** $Id: ltable.c $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ #define ltable_c #define LUA_CORE /* ** Implementation of tables (aka arrays, objects, or hash tables). ** Tables keep its elements in two parts: an array part and a hash part. ** Non-negative integer keys are all candidates to be kept in the array ** part. The actual size of the array is the largest 'n' such that ** more than half the slots between 1 and n are in use. ** Hash uses a mix of chained scatter table with Brent's variation. ** A main invariant of these tables is that, if an element is not ** in its main position (i.e. the 'original' position that its hash gives ** to it), then the colliding element is in its own main position. ** Hence even when the load factor reaches 100%, performance remains good. */ #include #include #include #include "lua.h" /* ** Only hash parts with at least 2^LIMFORLAST have a 'lastfree' field ** that optimizes finding a free slot. That field is stored just before ** the array of nodes, in the same block. Smaller tables do a complete ** search when looking for a free slot. */ #define LIMFORLAST 3 /* log2 of real limit (8) */ /* ** The union 'Limbox' stores 'lastfree' and ensures that what follows it ** is properly aligned to store a Node. */ typedef struct { Node *dummy; Node follows_pNode; } Limbox_aux; typedef union { Node *lastfree; char padding[offsetof(Limbox_aux, follows_pNode)]; } Limbox; #define haslastfree(t) ((t)->lsizenode >= LIMFORLAST) #define getlastfree(t) ((cast(Limbox *, (t)->node) - 1)->lastfree) /* ** MAXABITS is the largest integer such that 2^MAXABITS fits in an ** unsigned int. */ #define MAXABITS (l_numbits(int) - 1) /* ** MAXASIZEB is the maximum number of elements in the array part such ** that the size of the array fits in 'size_t'. */ #define MAXASIZEB (MAX_SIZET/(sizeof(LuaValue) + 1)) /* ** MAXASIZE is the maximum size of the array part. It is the minimum ** between 2^MAXABITS and MAXASIZEB. */ #define MAXASIZE \ (((1u << MAXABITS) < MAXASIZEB) ? (1u << MAXABITS) : cast_uint(MAXASIZEB)) /* ** MAXHBITS is the largest integer such that 2^MAXHBITS fits in a ** signed int. */ #define MAXHBITS (MAXABITS - 1) /* ** MAXHSIZE is the maximum size of the hash part. It is the minimum ** between 2^MAXHBITS and the maximum size such that, measured in bytes, ** it fits in a 'size_t'. */ #define MAXHSIZE luaM_limitN(1 << MAXHBITS, Node) /* ** When the original hash value is good, hashing by a power of 2 ** avoids the cost of '%'. */ #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) /* ** for other types, it is better to avoid modulo by power of 2, as ** they can have many 2 factors. */ #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1u)|1u)))) #define hashstr(t,str) hashpow2(t, (str)->hash) #define hashboolean(t,p) hashpow2(t, p) #define hashpointer(t,p) hashmod(t, point2uint(p)) #define dummynode (&dummynode_) /* ** Common hash part for tables with empty hash parts. That allows all ** tables to have a hash part, avoiding an extra check ("is there a hash ** part?") when indexing. Its sole node has an empty value and a key ** (DEADKEY, NULL) that is different from any valid TValue. */ static const Node dummynode_ = { {{NULL}, LUA_VEMPTY, /* value's value and type */ LUA_TDEADKEY, 0, {NULL}} /* key type, next, and key value */ }; static const TValue absentkey = {ABSTKEYCONSTANT}; /* ** Hash for integers. To allow a good hash, use the remainder operator ** ('%'). If integer fits as a non-negative int, compute an int ** remainder, which is faster. Otherwise, use an unsigned-integer ** remainder, which uses all bits and ensures a non-negative result. */ static Node *hashint (const Table *t, lua_Integer i) { lua_Unsigned ui = l_castS2U(i); if (ui <= cast_uint(INT_MAX)) return gnode(t, cast_int(ui) % cast_int((sizenode(t)-1) | 1)); else return hashmod(t, ui); } /* ** Hash for floating-point numbers. ** The main computation should be just ** n = frexp(n, &i); return (n * INT_MAX) + i ** but there are some numerical subtleties. ** In a two-complement representation, INT_MAX may not have an exact ** representation as a float, but INT_MIN does; because the absolute ** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the ** absolute value of the product 'frexp * -INT_MIN' is smaller or equal ** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when ** adding 'i'; the use of '~u' (instead of '-u') avoids problems with ** INT_MIN. */ #if !defined(l_hashfloat) static unsigned l_hashfloat (lua_Number n) { int i; lua_Integer ni; n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN); if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */ lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL)); return 0; } else { /* normal case */ unsigned int u = cast_uint(i) + cast_uint(ni); return (u <= cast_uint(INT_MAX) ? u : ~u); } } #endif /* ** returns the 'main' position of an element in a table (that is, ** the index of its hash value). */ static Node *mainpositionTV (const Table *t, const TValue *key) { switch (ttypetag(key)) { case LUA_VNUMINT: { lua_Integer i = ivalue(key); return hashint(t, i); } case LUA_VNUMFLT: { lua_Number n = fltvalue(key); return hashmod(t, l_hashfloat(n)); } case LUA_VSHRSTR: { TString *ts = tsvalue(key); return hashstr(t, ts); } case LUA_VLNGSTR: { TString *ts = tsvalue(key); return hashpow2(t, luaS_hashlongstr(ts)); } case LUA_VFALSE: return hashboolean(t, 0); case LUA_VTRUE: return hashboolean(t, 1); case LUA_VLIGHTUSERDATA: { void *p = pvalue(key); return hashpointer(t, p); } case LUA_VLCF: { lua_CFunction f = fvalue(key); return hashpointer(t, f); } default: { GCObject *o = gcvalue(key); return hashpointer(t, o); } } } l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) { TValue key; getnodekey(cast(lua_State *, NULL), &key, nd); return mainpositionTV(t, &key); } /* ** Check whether key 'k1' is equal to the key in node 'n2'. This ** equality is raw, so there are no metamethods. Floats with integer ** values have been normalized, so integers cannot be equal to ** floats. It is assumed that 'eqshrstr' is simply pointer equality, ** so that short strings are handled in the default case. The flag ** 'deadok' means to accept dead keys as equal to their original values. ** (Only collectable objects can produce dead keys.) Note that dead ** long strings are also compared by identity. Once a key is dead, ** its corresponding value may be collected, and then another value ** can be created with the same address. If this other value is given ** to 'next', 'equalkey' will signal a false positive. In a regular ** traversal, this situation should never happen, as all keys given to ** 'next' came from the table itself, and therefore could not have been ** collected. Outside a regular traversal, we have garbage in, garbage ** out. What is relevant is that this false positive does not break ** anything. (In particular, 'next' will return some other valid item ** on the table or nil.) */ static int equalkey (const TValue *k1, const Node *n2, int deadok) { if (rawtt(k1) != keytt(n2)) { /* not the same variants? */ if (keyisshrstr(n2) && ttislngstring(k1)) { /* an external string can be equal to a short-string key */ return luaS_eqstr(tsvalue(k1), keystrval(n2)); } else if (deadok && keyisdead(n2) && iscollectable(k1)) { /* a collectable value can be equal to a dead key */ return gcvalue(k1) == gcvalueraw(keyval(n2)); } else return 0; /* otherwise, different variants cannot be equal */ } else { /* equal variants */ switch (keytt(n2)) { case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: return 1; case LUA_VNUMINT: return (ivalue(k1) == keyival(n2)); case LUA_VNUMFLT: return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2))); case LUA_VLIGHTUSERDATA: return pvalue(k1) == pvalueraw(keyval(n2)); case LUA_VLCF: return fvalue(k1) == fvalueraw(keyval(n2)); case ctb(LUA_VLNGSTR): return luaS_eqstr(tsvalue(k1), keystrval(n2)); default: return gcvalue(k1) == gcvalueraw(keyval(n2)); } } } /* ** "Generic" get version. (Not that generic: not valid for integers, ** which may be in array part, nor for floats with integral values.) ** See explanation about 'deadok' in function 'equalkey'. */ static const TValue *getgeneric (Table *t, const TValue *key, int deadok) { Node *n = mainpositionTV(t, key); for (;;) { /* check whether 'key' is somewhere in the chain */ if (equalkey(key, n, deadok)) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) return &absentkey; /* not found */ n += nx; } } } /* ** Return the index 'k' (converted to an unsigned) if it is inside ** the range [1, limit]. */ static unsigned checkrange (lua_Integer k, unsigned limit) { return (l_castS2U(k) - 1u < limit) ? cast_uint(k) : 0; } /* ** Return the index 'k' if 'k' is an appropriate key to live in the ** array part of a table, 0 otherwise. */ #define arrayindex(k) checkrange(k, MAXASIZE) /* ** Check whether an integer key is in the array part of a table and ** return its index there, or zero. */ #define ikeyinarray(t,k) checkrange(k, t->asize) /* ** Check whether a key is in the array part of a table and return its ** index there, or zero. */ static unsigned keyinarray (Table *t, const TValue *key) { return (ttisinteger(key)) ? ikeyinarray(t, ivalue(key)) : 0; } /* ** returns the index of a 'key' for table traversals. First goes all ** elements in the array part, then elements in the hash part. The ** beginning of a traversal is signaled by 0. */ static unsigned findindex (lua_State *L, Table *t, TValue *key, unsigned asize) { unsigned int i; if (ttisnil(key)) return 0; /* first iteration */ i = keyinarray(t, key); if (i != 0) /* is 'key' inside array part? */ return i; /* yes; that's the index */ else { const TValue *n = getgeneric(t, key, 1); if (l_unlikely(isabstkey(n))) luaG_runerror(L, "invalid key to 'next'"); /* key not found */ i = cast_uint(nodefromval(n) - gnode(t, 0)); /* key index in hash table */ /* hash elements are numbered after array ones */ return (i + 1) + asize; } } int luaH_next (lua_State *L, Table *t, StkId key) { unsigned int asize = t->asize; unsigned int i = findindex(L, t, s2v(key), asize); /* find original key */ for (; i < asize; i++) { /* try first array part */ lu_byte tag = *getArrTag(t, i); if (!tagisempty(tag)) { /* a non-empty entry? */ setivalue(s2v(key), cast_int(i) + 1); farr2val(t, i, tag, s2v(key + 1)); return 1; } } for (i -= asize; i < sizenode(t); i++) { /* hash part */ if (!isempty(gval(gnode(t, i)))) { /* a non-empty entry? */ Node *n = gnode(t, i); getnodekey(L, s2v(key), n); setobj2s(L, key + 1, gval(n)); return 1; } } return 0; /* no more elements */ } /* Extra space in Node array if it has a lastfree entry */ #define extraLastfree(t) (haslastfree(t) ? sizeof(Limbox) : 0) /* 'node' size in bytes */ static size_t sizehash (Table *t) { return cast_sizet(sizenode(t)) * sizeof(Node) + extraLastfree(t); } static void freehash (lua_State *L, Table *t) { if (!isdummy(t)) { /* get pointer to the beginning of Node array */ char *arr = cast_charp(t->node) - extraLastfree(t); luaM_freearray(L, arr, sizehash(t)); } } /* ** {============================================================= ** Rehash ** ============================================================== */ static int insertkey (Table *t, const TValue *key, TValue *value); static void newcheckedkey (Table *t, const TValue *key, TValue *value); /* ** Structure to count the keys in a table. ** 'total' is the total number of keys in the table. ** 'na' is the number of *array indices* in the table (see 'arrayindex'). ** 'deleted' is true if there are deleted nodes in the hash part. ** 'nums' is a "count array" where 'nums[i]' is the number of integer ** keys between 2^(i - 1) + 1 and 2^i. Note that 'na' is the summation ** of 'nums'. */ typedef struct { unsigned total; unsigned na; int deleted; unsigned nums[MAXABITS + 1]; } Counters; /* ** Check whether it is worth to use 'na' array entries instead of 'nh' ** hash nodes. (A hash node uses ~3 times more memory than an array ** entry: Two values plus 'next' versus one value.) Evaluate with size_t ** to avoid overflows. */ #define arrayXhash(na,nh) (cast_sizet(na) <= cast_sizet(nh) * 3) /* ** Compute the optimal size for the array part of table 't'. ** This size maximizes the number of elements going to the array part ** while satisfying the condition 'arrayXhash' with the use of memory if ** all those elements went to the hash part. ** 'ct->na' enters with the total number of array indices in the table ** and leaves with the number of keys that will go to the array part; ** return the optimal size for the array part. */ static unsigned computesizes (Counters *ct) { int i; unsigned int twotoi; /* 2^i (candidate for optimal size) */ unsigned int a = 0; /* number of elements smaller than 2^i */ unsigned int na = 0; /* number of elements to go to array part */ unsigned int optimal = 0; /* optimal size for array part */ /* traverse slices while 'twotoi' does not overflow and total of array indices still can satisfy 'arrayXhash' against the array size */ for (i = 0, twotoi = 1; twotoi > 0 && arrayXhash(twotoi, ct->na); i++, twotoi *= 2) { unsigned nums = ct->nums[i]; a += nums; if (nums > 0 && /* grows array only if it gets more elements... */ arrayXhash(twotoi, a)) { /* ...while using "less memory" */ optimal = twotoi; /* optimal size (till now) */ na = a; /* all elements up to 'optimal' will go to array part */ } } ct->na = na; return optimal; } static void countint (lua_Integer key, Counters *ct) { unsigned int k = arrayindex(key); if (k != 0) { /* is 'key' an array index? */ ct->nums[luaO_ceillog2(k)]++; /* count as such */ ct->na++; } } l_sinline int arraykeyisempty (const Table *t, unsigned key) { int tag = *getArrTag(t, key - 1); return tagisempty(tag); } /* ** Count keys in array part of table 't'. */ static void numusearray (const Table *t, Counters *ct) { int lg; unsigned int ttlg; /* 2^lg */ unsigned int ause = 0; /* summation of 'nums' */ unsigned int i = 1; /* index to traverse all array keys */ unsigned int asize = t->asize; /* traverse each slice */ for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) { unsigned int lc = 0; /* counter */ unsigned int lim = ttlg; if (lim > asize) { lim = asize; /* adjust upper limit */ if (i > lim) break; /* no more elements to count */ } /* count elements in range (2^(lg - 1), 2^lg] */ for (; i <= lim; i++) { if (!arraykeyisempty(t, i)) lc++; } ct->nums[lg] += lc; ause += lc; } ct->total += ause; ct->na += ause; } /* ** Count keys in hash part of table 't'. As this only happens during ** a rehash, all nodes have been used. A node can have a nil value only ** if it was deleted after being created. */ static void numusehash (const Table *t, Counters *ct) { unsigned i = sizenode(t); unsigned total = 0; while (i--) { Node *n = &t->node[i]; if (isempty(gval(n))) { lua_assert(!keyisnil(n)); /* entry was deleted; key cannot be nil */ ct->deleted = 1; } else { total++; if (keyisinteger(n)) countint(keyival(n), ct); } } ct->total += total; } /* ** Convert an "abstract size" (number of slots in an array) to ** "concrete size" (number of bytes in the array). */ static size_t concretesize (unsigned int size) { if (size == 0) return 0; else /* space for the two arrays plus an unsigned in between */ return size * (sizeof(LuaValue) + 1) + sizeof(unsigned); } /* ** Resize the array part of a table. If new size is equal to the old, ** do nothing. Else, if new size is zero, free the old array. (It must ** be present, as the sizes are different.) Otherwise, allocate a new ** array, move the common elements to new proper position, and then ** frees the old array. ** We could reallocate the array, but we still would need to move the ** elements to their new position, so the copy implicit in realloc is a ** waste. Moreover, most allocators will move the array anyway when the ** new size is double the old one (the most common case). */ static LuaValue *resizearray (lua_State *L , Table *t, unsigned oldasize, unsigned newasize) { if (oldasize == newasize) return t->array; /* nothing to be done */ else if (newasize == 0) { /* erasing array? */ LuaValue *op = t->array - oldasize; /* original array's real address */ luaM_freemem(L, op, concretesize(oldasize)); /* free it */ return NULL; } else { size_t newasizeb = concretesize(newasize); LuaValue *np = cast(LuaValue *, luaM_reallocvector(L, NULL, 0, newasizeb, lu_byte)); if (np == NULL) /* allocation error? */ return NULL; np += newasize; /* shift pointer to the end of value segment */ if (oldasize > 0) { /* move common elements to new position */ size_t oldasizeb = concretesize(oldasize); LuaValue *op = t->array; /* original array */ unsigned tomove = (oldasize < newasize) ? oldasize : newasize; size_t tomoveb = (oldasize < newasize) ? oldasizeb : newasizeb; lua_assert(tomoveb > 0); memcpy(np - tomove, op - tomove, tomoveb); luaM_freemem(L, op - oldasize, oldasizeb); /* free old block */ } return np; } } /* ** Creates an array for the hash part of a table with the given ** size, or reuses the dummy node if size is zero. ** The computation for size overflow is in two steps: the first ** comparison ensures that the shift in the second one does not ** overflow. */ static void setnodevector (lua_State *L, Table *t, unsigned size) { if (size == 0) { /* no elements to hash part? */ t->node = cast(Node *, dummynode); /* use common 'dummynode' */ t->lsizenode = 0; setdummy(t); /* signal that it is using dummy node */ } else { int i; int lsize = luaO_ceillog2(size); if (lsize > MAXHBITS || (1 << lsize) > MAXHSIZE) luaG_runerror(L, "table overflow"); size = twoto(lsize); if (lsize < LIMFORLAST) /* no 'lastfree' field? */ t->node = luaM_newvector(L, size, Node); else { size_t bsize = size * sizeof(Node) + sizeof(Limbox); char *node = luaM_newblock(L, bsize); t->node = cast(Node *, node + sizeof(Limbox)); getlastfree(t) = gnode(t, size); /* all positions are free */ } t->lsizenode = cast_byte(lsize); setnodummy(t); for (i = 0; i < cast_int(size); i++) { Node *n = gnode(t, i); gnext(n) = 0; setnilkey(n); setempty(gval(n)); } } } /* ** (Re)insert all elements from the hash part of 'ot' into table 't'. */ static void reinserthash (lua_State *L, Table *ot, Table *t) { unsigned j; unsigned size = sizenode(ot); for (j = 0; j < size; j++) { Node *old = gnode(ot, j); if (!isempty(gval(old))) { /* doesn't need barrier/invalidate cache, as entry was already present in the table */ TValue k; getnodekey(L, &k, old); newcheckedkey(t, &k, gval(old)); } } } /* ** Exchange the hash part of 't1' and 't2'. (In 'flags', only the ** dummy bit must be exchanged: The 'isrealasize' is not related ** to the hash part, and the metamethod bits do not change during ** a resize, so the "real" table can keep their values.) */ static void exchangehashpart (Table *t1, Table *t2) { lu_byte lsizenode = t1->lsizenode; Node *node = t1->node; int bitdummy1 = t1->flags & BITDUMMY; t1->lsizenode = t2->lsizenode; t1->node = t2->node; t1->flags = cast_byte((t1->flags & NOTBITDUMMY) | (t2->flags & BITDUMMY)); t2->lsizenode = lsizenode; t2->node = node; t2->flags = cast_byte((t2->flags & NOTBITDUMMY) | bitdummy1); } /* ** Re-insert into the new hash part of a table the elements from the ** vanishing slice of the array part. */ static void reinsertOldSlice (Table *t, unsigned oldasize, unsigned newasize) { unsigned i; for (i = newasize; i < oldasize; i++) { /* traverse vanishing slice */ lu_byte tag = *getArrTag(t, i); if (!tagisempty(tag)) { /* a non-empty entry? */ TValue key, aux; setivalue(&key, l_castU2S(i) + 1); /* make the key */ farr2val(t, i, tag, &aux); /* copy value into 'aux' */ insertkey(t, &key, &aux); /* insert entry into the hash part */ } } } /* ** Clear new slice of the array. */ static void clearNewSlice (Table *t, unsigned oldasize, unsigned newasize) { for (; oldasize < newasize; oldasize++) *getArrTag(t, oldasize) = LUA_VEMPTY; } /* ** Resize table 't' for the new given sizes. Both allocations (for ** the hash part and for the array part) can fail, which creates some ** subtleties. If the first allocation, for the hash part, fails, an ** error is raised and that is it. Otherwise, it copies the elements from ** the shrinking part of the array (if it is shrinking) into the new ** hash. Then it reallocates the array part. If that fails, the table ** is in its original state; the function frees the new hash part and then ** raises the allocation error. Otherwise, it sets the new hash part ** into the table, initializes the new part of the array (if any) with ** nils and reinserts the elements of the old hash back into the new ** parts of the table. ** Note that if the new size for the array part ('newasize') is equal to ** the old one ('oldasize'), this function will do nothing with that ** part. */ void luaH_resize (lua_State *L, Table *t, unsigned newasize, unsigned nhsize) { Table newt; /* to keep the new hash part */ unsigned oldasize = t->asize; LuaValue *newarray; if (newasize > MAXASIZE) luaG_runerror(L, "table overflow"); /* create new hash part with appropriate size into 'newt' */ newt.flags = 0; setnodevector(L, &newt, nhsize); if (newasize < oldasize) { /* will array shrink? */ /* re-insert into the new hash the elements from vanishing slice */ exchangehashpart(t, &newt); /* pretend table has new hash */ reinsertOldSlice(t, oldasize, newasize); exchangehashpart(t, &newt); /* restore old hash (in case of errors) */ } /* allocate new array */ newarray = resizearray(L, t, oldasize, newasize); if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */ freehash(L, &newt); /* release new hash part */ luaM_error(L); /* raise error (with array unchanged) */ } /* allocation ok; initialize new part of the array */ exchangehashpart(t, &newt); /* 't' has the new hash ('newt' has the old) */ t->array = newarray; /* set new array part */ t->asize = newasize; if (newarray != NULL) *lenhint(t) = newasize / 2u; /* set an initial hint */ clearNewSlice(t, oldasize, newasize); /* re-insert elements from old hash part into new parts */ reinserthash(L, &newt, t); /* 'newt' now has the old hash */ freehash(L, &newt); /* free old hash part */ } void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) { unsigned nsize = allocsizenode(t); luaH_resize(L, t, nasize, nsize); } /* ** Rehash a table. First, count its keys. If there are array indices ** outside the array part, compute the new best size for that part. ** Then, resize the table. */ static void rehash (lua_State *L, Table *t, const TValue *ek) { unsigned asize; /* optimal size for array part */ Counters ct; unsigned i; unsigned nsize; /* size for the hash part */ /* reset counts */ for (i = 0; i <= MAXABITS; i++) ct.nums[i] = 0; ct.na = 0; ct.deleted = 0; ct.total = 1; /* count extra key */ if (ttisinteger(ek)) countint(ivalue(ek), &ct); /* extra key may go to array */ numusehash(t, &ct); /* count keys in hash part */ if (ct.na == 0) { /* no new keys to enter array part; keep it with the same size */ asize = t->asize; } else { /* compute best size for array part */ numusearray(t, &ct); /* count keys in array part */ asize = computesizes(&ct); /* compute new size for array part */ } /* all keys not in the array part go to the hash part */ nsize = ct.total - ct.na; if (ct.deleted) { /* table has deleted entries? */ /* insertion-deletion-insertion: give hash some extra size to avoid repeated resizings */ nsize += nsize >> 2; } /* resize the table to new computed sizes */ luaH_resize(L, t, asize, nsize); } /* ** }============================================================= */ Table *luaH_new (lua_State *L) { GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table)); Table *t = gco2t(o); t->metatable = NULL; t->flags = maskflags; /* table has no metamethod fields */ t->array = NULL; t->asize = 0; setnodevector(L, t, 0); return t; } lu_mem luaH_size (Table *t) { lu_mem sz = cast(lu_mem, sizeof(Table)) + concretesize(t->asize); if (!isdummy(t)) sz += sizehash(t); return sz; } /* ** Frees a table. */ void luaH_free (lua_State *L, Table *t) { freehash(L, t); resizearray(L, t, t->asize, 0); luaM_free(L, t); } static Node *getfreepos (Table *t) { if (haslastfree(t)) { /* does it have 'lastfree' information? */ /* look for a spot before 'lastfree', updating 'lastfree' */ while (getlastfree(t) > t->node) { Node *free = --getlastfree(t); if (keyisnil(free)) return free; } } else { /* no 'lastfree' information */ unsigned i = sizenode(t); while (i--) { /* do a linear search */ Node *free = gnode(t, i); if (keyisnil(free)) return free; } } return NULL; /* could not find a free place */ } /* ** Inserts a new key into a hash table; first, check whether key's main ** position is free. If not, check whether colliding node is in its main ** position or not: if it is not, move colliding node to an empty place ** and put new key in its main position; otherwise (colliding node is in ** its main position), new key goes to an empty position. Return 0 if ** could not insert key (could not find a free space). */ static int insertkey (Table *t, const TValue *key, TValue *value) { Node *mp = mainpositionTV(t, key); /* table cannot already contain the key */ lua_assert(isabstkey(getgeneric(t, key, 0))); if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */ Node *othern; Node *f = getfreepos(t); /* get a free place */ if (f == NULL) /* cannot find a free place? */ return 0; lua_assert(!isdummy(t)); othern = mainpositionfromnode(t, mp); if (othern != mp) { /* is colliding node out of its main position? */ /* yes; move colliding node into free position */ while (othern + gnext(othern) != mp) /* find previous */ othern += gnext(othern); gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */ *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */ if (gnext(mp) != 0) { gnext(f) += cast_int(mp - f); /* correct 'next' */ gnext(mp) = 0; /* now 'mp' is free */ } setempty(gval(mp)); } else { /* colliding node is in its own main position */ /* new node will go into free position */ if (gnext(mp) != 0) gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */ else lua_assert(gnext(f) == 0); gnext(mp) = cast_int(f - mp); mp = f; } } setnodekey(mp, key); lua_assert(isempty(gval(mp))); setobj2t(cast(lua_State *, 0), gval(mp), value); return 1; } /* ** Insert a key in a table where there is space for that key, the ** key is valid, and the value is not nil. */ static void newcheckedkey (Table *t, const TValue *key, TValue *value) { unsigned i = keyinarray(t, key); if (i > 0) /* is key in the array part? */ obj2arr(t, i - 1, value); /* set value in the array */ else { int done = insertkey(t, key, value); /* insert key in the hash part */ lua_assert(done); /* it cannot fail */ cast(void, done); /* to avoid warnings */ } } static void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value) { if (!ttisnil(value)) { /* do not insert nil values */ int done = insertkey(t, key, value); if (!done) { /* could not find a free place? */ rehash(L, t, key); /* grow table */ newcheckedkey(t, key, value); /* insert key in grown table */ } luaC_barrierback(L, obj2gco(t), key); /* for debugging only: any new key may force an emergency collection */ condchangemem(L, (void)0, (void)0, 1); } } static const TValue *getintfromhash (Table *t, lua_Integer key) { Node *n = hashint(t, key); lua_assert(!ikeyinarray(t, key)); for (;;) { /* check whether 'key' is somewhere in the chain */ if (keyisinteger(n) && keyival(n) == key) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) break; n += nx; } } return &absentkey; } static int hashkeyisempty (Table *t, lua_Unsigned key) { const TValue *val = getintfromhash(t, l_castU2S(key)); return isempty(val); } static lu_byte finishnodeget (const TValue *val, TValue *res) { if (!ttisnil(val)) { setobj(((lua_State*)NULL), res, val); } return ttypetag(val); } lu_byte luaH_getint (Table *t, lua_Integer key, TValue *res) { unsigned k = ikeyinarray(t, key); if (k > 0) { lu_byte tag = *getArrTag(t, k - 1); if (!tagisempty(tag)) farr2val(t, k - 1, tag, res); return tag; } else return finishnodeget(getintfromhash(t, key), res); } /* ** search function for short strings */ const TValue *luaH_Hgetshortstr (Table *t, TString *key) { Node *n = hashstr(t, key); lua_assert(strisshr(key)); for (;;) { /* check whether 'key' is somewhere in the chain */ if (keyisshrstr(n) && eqshrstr(keystrval(n), key)) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) return &absentkey; /* not found */ n += nx; } } } lu_byte luaH_getshortstr (Table *t, TString *key, TValue *res) { return finishnodeget(luaH_Hgetshortstr(t, key), res); } static const TValue *Hgetlongstr (Table *t, TString *key) { TValue ko; lua_assert(!strisshr(key)); setsvalue(cast(lua_State *, NULL), &ko, key); return getgeneric(t, &ko, 0); /* for long strings, use generic case */ } static const TValue *Hgetstr (Table *t, TString *key) { if (strisshr(key)) return luaH_Hgetshortstr(t, key); else return Hgetlongstr(t, key); } lu_byte luaH_getstr (Table *t, TString *key, TValue *res) { return finishnodeget(Hgetstr(t, key), res); } /* ** main search function */ lu_byte luaH_get (Table *t, const TValue *key, TValue *res) { const TValue *slot; switch (ttypetag(key)) { case LUA_VSHRSTR: slot = luaH_Hgetshortstr(t, tsvalue(key)); break; case LUA_VNUMINT: return luaH_getint(t, ivalue(key), res); case LUA_VNIL: slot = &absentkey; break; case LUA_VNUMFLT: { lua_Integer k; if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */ return luaH_getint(t, k, res); /* use specialized version */ /* else... */ } /* FALLTHROUGH */ default: slot = getgeneric(t, key, 0); break; } return finishnodeget(slot, res); } /* ** When a 'pset' cannot be completed, this function returns an encoding ** of its result, to be used by 'luaH_finishset'. */ static int retpsetcode (Table *t, const TValue *slot) { if (isabstkey(slot)) return HNOTFOUND; /* no slot with that key */ else /* return node encoded */ return cast_int((cast(Node*, slot) - t->node)) + HFIRSTNODE; } static int finishnodeset (Table *t, const TValue *slot, TValue *val) { if (!ttisnil(slot)) { setobj(((lua_State*)NULL), cast(TValue*, slot), val); return HOK; /* success */ } else return retpsetcode(t, slot); } static int rawfinishnodeset (const TValue *slot, TValue *val) { if (isabstkey(slot)) return 0; /* no slot with that key */ else { setobj(((lua_State*)NULL), cast(TValue*, slot), val); return 1; /* success */ } } int luaH_psetint (Table *t, lua_Integer key, TValue *val) { lua_assert(!ikeyinarray(t, key)); return finishnodeset(t, getintfromhash(t, key), val); } static int psetint (Table *t, lua_Integer key, TValue *val) { int hres; luaH_fastseti(t, key, val, hres); return hres; } /* ** This function could be just this: ** return finishnodeset(t, luaH_Hgetshortstr(t, key), val); ** However, it optimizes the common case created by constructors (e.g., ** {x=1, y=2}), which creates a key in a table that has no metatable, ** it is not old/black, and it already has space for the key. */ int luaH_psetshortstr (Table *t, TString *key, TValue *val) { const TValue *slot = luaH_Hgetshortstr(t, key); if (!ttisnil(slot)) { /* key already has a value? (all too common) */ setobj(((lua_State*)NULL), cast(TValue*, slot), val); /* update it */ return HOK; /* done */ } else if (checknoTM(t->metatable, TM_NEWINDEX)) { /* no metamethod? */ if (ttisnil(val)) /* new value is nil? */ return HOK; /* done (value is already nil/absent) */ if (isabstkey(slot) && /* key is absent? */ !(isblack(t) && iswhite(key))) { /* and don't need barrier? */ TValue tk; /* key as a TValue */ setsvalue(cast(lua_State *, NULL), &tk, key); if (insertkey(t, &tk, val)) { /* insert key, if there is space */ invalidateTMcache(t); return HOK; } } } /* Else, either table has new-index metamethod, or it needs barrier, or it needs to rehash for the new key. In any of these cases, the operation cannot be completed here. Return a code for the caller. */ return retpsetcode(t, slot); } int luaH_psetstr (Table *t, TString *key, TValue *val) { if (strisshr(key)) return luaH_psetshortstr(t, key, val); else return finishnodeset(t, Hgetlongstr(t, key), val); } int luaH_pset (Table *t, const TValue *key, TValue *val) { switch (ttypetag(key)) { case LUA_VSHRSTR: return luaH_psetshortstr(t, tsvalue(key), val); case LUA_VNUMINT: return psetint(t, ivalue(key), val); case LUA_VNIL: return HNOTFOUND; case LUA_VNUMFLT: { lua_Integer k; if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */ return psetint(t, k, val); /* use specialized version */ /* else... */ } /* FALLTHROUGH */ default: return finishnodeset(t, getgeneric(t, key, 0), val); } } /* ** Finish a raw "set table" operation, where 'hres' encodes where the ** value should have been (the result of a previous 'pset' operation). ** Beware: when using this function the caller probably need to check a ** GC barrier and invalidate the TM cache. */ void luaH_finishset (lua_State *L, Table *t, const TValue *key, TValue *value, int hres) { lua_assert(hres != HOK); if (hres == HNOTFOUND) { TValue aux; if (l_unlikely(ttisnil(key))) luaG_runerror(L, "table index is nil"); else if (ttisfloat(key)) { lua_Number f = fltvalue(key); lua_Integer k; if (luaV_flttointeger(f, &k, F2Ieq)) { setivalue(&aux, k); /* key is equal to an integer */ key = &aux; /* insert it as an integer */ } else if (l_unlikely(luai_numisnan(f))) luaG_runerror(L, "table index is NaN"); } else if (isextstr(key)) { /* external string? */ /* If string is short, must internalize it to be used as table key */ TString *ts = luaS_normstr(L, tsvalue(key)); setsvalue2s(L, L->top.p++, ts); /* anchor 'ts' (EXTRA_STACK) */ luaH_newkey(L, t, s2v(L->top.p - 1), value); L->top.p--; return; } luaH_newkey(L, t, key, value); } else if (hres > 0) { /* regular Node? */ setobj2t(L, gval(gnode(t, hres - HFIRSTNODE)), value); } else { /* array entry */ hres = ~hres; /* real index */ obj2arr(t, cast_uint(hres), value); } } /* ** beware: when using this function you probably need to check a GC ** barrier and invalidate the TM cache. */ void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) { int hres = luaH_pset(t, key, value); if (hres != HOK) luaH_finishset(L, t, key, value, hres); } /* ** Ditto for a GC barrier. (No need to invalidate the TM cache, as ** integers cannot be keys to metamethods.) */ void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) { unsigned ik = ikeyinarray(t, key); if (ik > 0) obj2arr(t, ik - 1, value); else { int ok = rawfinishnodeset(getintfromhash(t, key), value); if (!ok) { TValue k; setivalue(&k, key); luaH_newkey(L, t, &k, value); } } } /* ** Try to find a boundary in the hash part of table 't'. From the ** caller, we know that 'asize + 1' is present. We want to find a larger ** key that is absent from the table, so that we can do a binary search ** between the two keys to find a boundary. We keep doubling 'j' until ** we get an absent index. If the doubling would overflow, we try ** LUA_MAXINTEGER. If it is absent, we are ready for the binary search. ** ('j', being max integer, is larger or equal to 'i', but it cannot be ** equal because it is absent while 'i' is present.) Otherwise, 'j' is a ** boundary. ('j + 1' cannot be a present integer key because it is not ** a valid integer in Lua.) ** About 'rnd': If we used a fixed algorithm, a bad actor could fill ** a table with only the keys that would be probed, in such a way that ** a small table could result in a huge length. To avoid that, we use ** the state's seed as a source of randomness. For the first probe, ** we "randomly double" 'i' by adding to it a random number roughly its ** width. */ static lua_Unsigned hash_search (lua_State *L, Table *t, unsigned asize) { lua_Unsigned i = asize + 1; /* caller ensures t[i] is present */ unsigned rnd = G(L)->seed; int n = (asize > 0) ? luaO_ceillog2(asize) : 0; /* width of 'asize' */ unsigned mask = (1u << n) - 1; /* 11...111 with the width of 'asize' */ unsigned incr = (rnd & mask) + 1; /* first increment (at least 1) */ lua_Unsigned j = (incr <= l_castS2U(LUA_MAXINTEGER) - i) ? i + incr : i + 1; rnd >>= n; /* used 'n' bits from 'rnd' */ while (!hashkeyisempty(t, j)) { /* repeat until an absent t[j] */ i = j; /* 'i' is a present index */ if (j <= l_castS2U(LUA_MAXINTEGER)/2 - 1) { j = j*2 + (rnd & 1); /* try again with 2j or 2j+1 */ rnd >>= 1; } else { j = LUA_MAXINTEGER; if (hashkeyisempty(t, j)) /* t[j] not present? */ break; /* 'j' now is an absent index */ else /* weird case */ return j; /* well, max integer is a boundary... */ } } /* i < j && t[i] present && t[j] absent */ while (j - i > 1u) { /* do a binary search between them */ lua_Unsigned m = (i + j) / 2; if (hashkeyisempty(t, m)) j = m; else i = m; } return i; } static unsigned int binsearch (Table *array, unsigned int i, unsigned int j) { lua_assert(i <= j); while (j - i > 1u) { /* binary search */ unsigned int m = (i + j) / 2; if (arraykeyisempty(array, m)) j = m; else i = m; } return i; } /* return a border, saving it as a hint for next call */ static lua_Unsigned newhint (Table *t, unsigned hint) { lua_assert(hint <= t->asize); *lenhint(t) = hint; return hint; } /* ** Try to find a border in table 't'. (A 'border' is an integer index ** such that t[i] is present and t[i+1] is absent, or 0 if t[1] is absent, ** or 'maxinteger' if t[maxinteger] is present.) ** If there is an array part, try to find a border there. First try ** to find it in the vicinity of the previous result (hint), to handle ** cases like 't[#t + 1] = val' or 't[#t] = nil', that move the border ** by one entry. Otherwise, do a binary search to find the border. ** If there is no array part, or its last element is non empty, the ** border may be in the hash part. */ lua_Unsigned luaH_getn (lua_State *L, Table *t) { unsigned asize = t->asize; if (asize > 0) { /* is there an array part? */ const unsigned maxvicinity = 4; unsigned limit = *lenhint(t); /* start with the hint */ if (limit == 0) limit = 1; /* make limit a valid index in the array */ if (arraykeyisempty(t, limit)) { /* t[limit] empty? */ /* there must be a border before 'limit' */ unsigned i; /* look for a border in the vicinity of the hint */ for (i = 0; i < maxvicinity && limit > 1; i++) { limit--; if (!arraykeyisempty(t, limit)) return newhint(t, limit); /* 'limit' is a border */ } /* t[limit] still empty; search for a border in [0, limit) */ return newhint(t, binsearch(t, 0, limit)); } else { /* 'limit' is present in table; look for a border after it */ unsigned i; /* look for a border in the vicinity of the hint */ for (i = 0; i < maxvicinity && limit < asize; i++) { limit++; if (arraykeyisempty(t, limit)) return newhint(t, limit - 1); /* 'limit - 1' is a border */ } if (arraykeyisempty(t, asize)) { /* last element empty? */ /* t[limit] not empty; search for a border in [limit, asize) */ return newhint(t, binsearch(t, limit, asize)); } } /* last element non empty; set a hint to speed up finding that again */ /* (keys in the hash part cannot be hints) */ *lenhint(t) = asize; } /* no array part or t[asize] is not empty; check the hash part */ lua_assert(asize == 0 || !arraykeyisempty(t, asize)); if (isdummy(t) || hashkeyisempty(t, asize + 1)) return asize; /* 'asize + 1' is empty */ else /* 'asize + 1' is also non empty */ return hash_search(L, t, asize); } #if defined(LUA_DEBUG) /* export this function for the test library */ Node *luaH_mainposition (const Table *t, const TValue *key) { return mainpositionTV(t, key); } #endif /* ** $Id: lapi.c $ ** Lua API ** See Copyright Notice in lua.h */ #define lapi_c #define LUA_CORE #include #include #include #include "lua.h" const char lua_ident[] = "$LuaVersion: " LUA_COPYRIGHT " $" "$LuaAuthors: " LUA_AUTHORS " $"; /* ** Test for a valid index (one that is not the 'nilvalue'). */ #define isvalid(L, o) ((o) != &G(L)->nilvalue) /* test for pseudo index */ #define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) /* test for upvalue */ #define isupvalue(i) ((i) < LUA_REGISTRYINDEX) /* ** Convert an acceptable index to a pointer to its respective value. ** Non-valid indices return the special nil value 'G(L)->nilvalue'. */ static TValue *index2value (lua_State *L, int idx) { CallInfo *ci = L->ci; if (idx > 0) { StkId o = ci->func.p + idx; api_check(L, idx <= ci->top.p - (ci->func.p + 1), "unacceptable index"); if (o >= L->top.p) return &G(L)->nilvalue; else return s2v(o); } else if (!ispseudo(idx)) { /* negative index */ api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1), "invalid index"); return s2v(L->top.p + idx); } else if (idx == LUA_REGISTRYINDEX) return &G(L)->l_registry; else { /* upvalues */ idx = LUA_REGISTRYINDEX - idx; api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); if (ttisCclosure(s2v(ci->func.p))) { /* C closure? */ CClosure *func = clCvalue(s2v(ci->func.p)); return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : &G(L)->nilvalue; } else { /* light C function or Lua function (through a hook)?) */ api_check(L, ttislcf(s2v(ci->func.p)), "caller not a C function"); return &G(L)->nilvalue; /* no upvalues */ } } } /* ** Convert a valid actual index (not a pseudo-index) to its address. */ static StkId index2stack (lua_State *L, int idx) { CallInfo *ci = L->ci; if (idx > 0) { StkId o = ci->func.p + idx; api_check(L, o < L->top.p, "invalid index"); return o; } else { /* non-positive index */ api_check(L, idx != 0 && -idx <= L->top.p - (ci->func.p + 1), "invalid index"); api_check(L, !ispseudo(idx), "invalid index"); return L->top.p + idx; } } LUA_API int lua_checkstack (lua_State *L, int n) { int res; CallInfo *ci; lua_lock(L); ci = L->ci; api_check(L, n >= 0, "negative 'n'"); if (L->stack_last.p - L->top.p > n) /* stack large enough? */ res = 1; /* yes; check is OK */ else /* need to grow stack */ res = luaD_growstack(L, n, 0); if (res && ci->top.p < L->top.p + n) ci->top.p = L->top.p + n; /* adjust frame top */ lua_unlock(L); return res; } LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { int i; if (from == to) return; lua_lock(to); api_checkpop(from, n); api_check(from, G(from) == G(to), "moving among independent states"); api_check(from, to->ci->top.p - to->top.p >= n, "stack overflow"); from->top.p -= n; for (i = 0; i < n; i++) { setobjs2s(to, to->top.p, from->top.p + i); to->top.p++; /* stack already checked by previous 'api_check' */ } lua_unlock(to); } LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { lua_CFunction old; lua_lock(L); old = G(L)->panic; G(L)->panic = panicf; lua_unlock(L); return old; } LUA_API lua_Number lua_version (lua_State *L) { UNUSED(L); return LUA_VERSION_NUM; } /* ** basic stack manipulation */ /* ** convert an acceptable stack index into an absolute index */ LUA_API int lua_absindex (lua_State *L, int idx) { return (idx > 0 || ispseudo(idx)) ? idx : cast_int(L->top.p - L->ci->func.p) + idx; } LUA_API int lua_gettop (lua_State *L) { return cast_int(L->top.p - (L->ci->func.p + 1)); } LUA_API void lua_settop (lua_State *L, int idx) { CallInfo *ci; StkId func, newtop; ptrdiff_t diff; /* difference for new top */ lua_lock(L); ci = L->ci; func = ci->func.p; if (idx >= 0) { api_check(L, idx <= ci->top.p - (func + 1), "new top too large"); diff = ((func + 1) + idx) - L->top.p; for (; diff > 0; diff--) setnilvalue(s2v(L->top.p++)); /* clear new slots */ } else { api_check(L, -(idx+1) <= (L->top.p - (func + 1)), "invalid new top"); diff = idx + 1; /* will "subtract" index (as it is negative) */ } newtop = L->top.p + diff; if (diff < 0 && L->tbclist.p >= newtop) { lua_assert(ci->callstatus & CIST_TBC); newtop = luaF_close(L, newtop, CLOSEKTOP, 0); } L->top.p = newtop; /* correct top only after closing any upvalue */ lua_unlock(L); } LUA_API void lua_closeslot (lua_State *L, int idx) { StkId level; lua_lock(L); level = index2stack(L, idx); api_check(L, (L->ci->callstatus & CIST_TBC) && (L->tbclist.p == level), "no variable to close at given level"); level = luaF_close(L, level, CLOSEKTOP, 0); setnilvalue(s2v(level)); lua_unlock(L); } /* ** Reverse the stack segment from 'from' to 'to' ** (auxiliary to 'lua_rotate') ** Note that we move(copy) only the value inside the stack. ** (We do not move additional fields that may exist.) */ static void reverse (lua_State *L, StkId from, StkId to) { for (; from < to; from++, to--) { TValue temp; setobj(L, &temp, s2v(from)); setobjs2s(L, from, to); setobj2s(L, to, &temp); } } /* ** Let x = AB, where A is a prefix of length 'n'. Then, ** rotate x n == BA. But BA == (A^r . B^r)^r. */ LUA_API void lua_rotate (lua_State *L, int idx, int n) { StkId p, t, m; lua_lock(L); t = L->top.p - 1; /* end of stack segment being rotated */ p = index2stack(L, idx); /* start of segment */ api_check(L, L->tbclist.p < p, "moving a to-be-closed slot"); api_check(L, (n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'"); m = (n >= 0 ? t - n : p - n - 1); /* end of prefix */ reverse(L, p, m); /* reverse the prefix with length 'n' */ reverse(L, m + 1, t); /* reverse the suffix */ reverse(L, p, t); /* reverse the entire segment */ lua_unlock(L); } LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) { TValue *fr, *to; lua_lock(L); fr = index2value(L, fromidx); to = index2value(L, toidx); api_check(L, isvalid(L, to), "invalid index"); setobj(L, to, fr); if (isupvalue(toidx)) /* function upvalue? */ luaC_barrier(L, clCvalue(s2v(L->ci->func.p)), fr); /* LUA_REGISTRYINDEX does not need gc barrier (collector revisits it before finishing collection) */ lua_unlock(L); } LUA_API void lua_pushvalue (lua_State *L, int idx) { lua_lock(L); setobj2s(L, L->top.p, index2value(L, idx)); api_incr_top(L); lua_unlock(L); } /* ** access functions (stack -> C) */ LUA_API int lua_type (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return (isvalid(L, o) ? ttype(o) : LUA_TNONE); } LUA_API const char *lua_typename (lua_State *L, int t) { UNUSED(L); api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, "invalid type"); return ttypename(t); } LUA_API int lua_iscfunction (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return (ttislcf(o) || (ttisCclosure(o))); } LUA_API int lua_isinteger (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return ttisinteger(o); } LUA_API int lua_isnumber (lua_State *L, int idx) { lua_Number n; const TValue *o = index2value(L, idx); return tonumber(o, &n); } LUA_API int lua_isstring (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return (ttisstring(o) || cvt2str(o)); } LUA_API int lua_isuserdata (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return (ttisfulluserdata(o) || ttislightuserdata(o)); } LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { const TValue *o1 = index2value(L, index1); const TValue *o2 = index2value(L, index2); return (isvalid(L, o1) && isvalid(L, o2)) ? luaV_rawequalobj(o1, o2) : 0; } LUA_API void lua_arith (lua_State *L, int op) { lua_lock(L); if (op != LUA_OPUNM && op != LUA_OPBNOT) api_checkpop(L, 2); /* all other operations expect two operands */ else { /* for unary operations, add fake 2nd operand */ api_checkpop(L, 1); setobjs2s(L, L->top.p, L->top.p - 1); api_incr_top(L); } /* first operand at top - 2, second at top - 1; result go to top - 2 */ luaO_arith(L, op, s2v(L->top.p - 2), s2v(L->top.p - 1), L->top.p - 2); L->top.p--; /* pop second operand */ lua_unlock(L); } LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { const TValue *o1; const TValue *o2; int i = 0; lua_lock(L); /* may call tag method */ o1 = index2value(L, index1); o2 = index2value(L, index2); if (isvalid(L, o1) && isvalid(L, o2)) { switch (op) { case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break; case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; default: api_check(L, 0, "invalid option"); } } lua_unlock(L); return i; } LUA_API unsigned (lua_numbertocstring) (lua_State *L, int idx, char *buff) { const TValue *o = index2value(L, idx); if (ttisnumber(o)) { unsigned len = luaO_tostringbuff(o, buff); buff[len++] = '\0'; /* add final zero */ return len; } else return 0; } LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) { size_t sz = luaO_str2num(s, s2v(L->top.p)); if (sz != 0) api_incr_top(L); return sz; } LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) { lua_Number n = 0; const TValue *o = index2value(L, idx); int isnum = tonumber(o, &n); if (pisnum) *pisnum = isnum; return n; } LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) { lua_Integer res = 0; const TValue *o = index2value(L, idx); int isnum = tointeger(o, &res); if (pisnum) *pisnum = isnum; return res; } LUA_API int lua_toboolean (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return !l_isfalse(o); } LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { TValue *o; lua_lock(L); o = index2value(L, idx); if (!ttisstring(o)) { if (!cvt2str(o)) { /* not convertible? */ if (len != NULL) *len = 0; lua_unlock(L); return NULL; } luaO_tostring(L, o); luaC_checkGC(L); o = index2value(L, idx); /* previous call may reallocate the stack */ } lua_unlock(L); if (len != NULL) return getlstr(tsvalue(o), *len); else return getstr(tsvalue(o)); } LUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) { const TValue *o = index2value(L, idx); switch (ttypetag(o)) { case LUA_VSHRSTR: return cast(lua_Unsigned, tsvalue(o)->shrlen); case LUA_VLNGSTR: return cast(lua_Unsigned, tsvalue(o)->u.lnglen); case LUA_VUSERDATA: return cast(lua_Unsigned, uvalue(o)->len); case LUA_VTABLE: { lua_Unsigned res; lua_lock(L); res = luaH_getn(L, hvalue(o)); lua_unlock(L); return res; } default: return 0; } } LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { const TValue *o = index2value(L, idx); if (ttislcf(o)) return fvalue(o); else if (ttisCclosure(o)) return clCvalue(o)->f; else return NULL; /* not a C function */ } l_sinline void *touserdata (const TValue *o) { switch (ttype(o)) { case LUA_TUSERDATA: return getudatamem(uvalue(o)); case LUA_TLIGHTUSERDATA: return pvalue(o); default: return NULL; } } LUA_API void *lua_touserdata (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return touserdata(o); } LUA_API lua_State *lua_tothread (lua_State *L, int idx) { const TValue *o = index2value(L, idx); return (!ttisthread(o)) ? NULL : thvalue(o); } /* ** Returns a pointer to the internal representation of an object. ** Note that ISO C does not allow the conversion of a pointer to ** function to a 'void*', so the conversion here goes through ** a 'size_t'. (As the returned pointer is only informative, this ** conversion should not be a problem.) */ LUA_API const void *lua_topointer (lua_State *L, int idx) { const TValue *o = index2value(L, idx); switch (ttypetag(o)) { case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o))); case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA: return touserdata(o); default: { if (iscollectable(o)) return gcvalue(o); else return NULL; } } } /* ** push functions (C -> stack) */ LUA_API void lua_pushnil (lua_State *L) { lua_lock(L); setnilvalue(s2v(L->top.p)); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { lua_lock(L); setfltvalue(s2v(L->top.p), n); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { lua_lock(L); setivalue(s2v(L->top.p), n); api_incr_top(L); lua_unlock(L); } /* ** Pushes on the stack a string with given length. Avoid using 's' when ** 'len' == 0 (as 's' can be NULL in that case), due to later use of ** 'memcmp' and 'memcpy'. */ LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { TString *ts; lua_lock(L); ts = (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len); setsvalue2s(L, L->top.p, ts); api_incr_top(L); luaC_checkGC(L); lua_unlock(L); return getstr(ts); } LUA_API const char *lua_pushexternalstring (lua_State *L, const char *s, size_t len, lua_Alloc falloc, void *ud) { TString *ts; lua_lock(L); api_check(L, len <= MAX_SIZE, "string too large"); api_check(L, s[len] == '\0', "string not ending with zero"); ts = luaS_newextlstr (L, s, len, falloc, ud); setsvalue2s(L, L->top.p, ts); api_incr_top(L); luaC_checkGC(L); lua_unlock(L); return getstr(ts); } LUA_API const char *lua_pushstring (lua_State *L, const char *s) { lua_lock(L); if (s == NULL) setnilvalue(s2v(L->top.p)); else { TString *ts; ts = luaS_new(L, s); setsvalue2s(L, L->top.p, ts); s = getstr(ts); /* internal copy's address */ } api_incr_top(L); luaC_checkGC(L); lua_unlock(L); return s; } LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp) { const char *ret; lua_lock(L); ret = luaO_pushvfstring(L, fmt, argp); luaC_checkGC(L); lua_unlock(L); return ret; } LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { const char *ret; va_list argp; lua_lock(L); pushvfstring(L, argp, fmt, ret); luaC_checkGC(L); lua_unlock(L); return ret; } LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { lua_lock(L); if (n == 0) { setfvalue(s2v(L->top.p), fn); api_incr_top(L); } else { int i; CClosure *cl; api_checkpop(L, n); api_check(L, n <= MAXUPVAL, "upvalue index too large"); cl = luaF_newCclosure(L, n); cl->f = fn; for (i = 0; i < n; i++) { setobj2n(L, &cl->upvalue[i], s2v(L->top.p - n + i)); /* does not need barrier because closure is white */ lua_assert(iswhite(cl)); } L->top.p -= n; setclCvalue(L, s2v(L->top.p), cl); api_incr_top(L); luaC_checkGC(L); } lua_unlock(L); } LUA_API void lua_pushboolean (lua_State *L, int b) { lua_lock(L); if (b) setbtvalue(s2v(L->top.p)); else setbfvalue(s2v(L->top.p)); api_incr_top(L); lua_unlock(L); } LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { lua_lock(L); setpvalue(s2v(L->top.p), p); api_incr_top(L); lua_unlock(L); } LUA_API int lua_pushthread (lua_State *L) { lua_lock(L); setthvalue(L, s2v(L->top.p), L); api_incr_top(L); lua_unlock(L); return (mainthread(G(L)) == L); } /* ** get functions (Lua -> stack) */ static int auxgetstr (lua_State *L, const TValue *t, const char *k) { lu_byte tag; TString *str = luaS_new(L, k); luaV_fastget(t, str, s2v(L->top.p), luaH_getstr, tag); if (!tagisempty(tag)) api_incr_top(L); else { setsvalue2s(L, L->top.p, str); api_incr_top(L); tag = luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, tag); } lua_unlock(L); return novariant(tag); } /* ** The following function assumes that the registry cannot be a weak ** table; so, an emergency collection while using the global table ** cannot collect it. */ static void getGlobalTable (lua_State *L, TValue *gt) { Table *registry = hvalue(&G(L)->l_registry); lu_byte tag = luaH_getint(registry, LUA_RIDX_GLOBALS, gt); (void)tag; /* avoid not-used warnings when checks are off */ api_check(L, novariant(tag) == LUA_TTABLE, "global table must exist"); } LUA_API int lua_getglobal (lua_State *L, const char *name) { TValue gt; lua_lock(L); getGlobalTable(L, >); return auxgetstr(L, >, name); } LUA_API int lua_gettable (lua_State *L, int idx) { lu_byte tag; TValue *t; lua_lock(L); api_checkpop(L, 1); t = index2value(L, idx); luaV_fastget(t, s2v(L->top.p - 1), s2v(L->top.p - 1), luaH_get, tag); if (tagisempty(tag)) tag = luaV_finishget(L, t, s2v(L->top.p - 1), L->top.p - 1, tag); lua_unlock(L); return novariant(tag); } LUA_API int lua_getfield (lua_State *L, int idx, const char *k) { lua_lock(L); return auxgetstr(L, index2value(L, idx), k); } LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) { TValue *t; lu_byte tag; lua_lock(L); t = index2value(L, idx); luaV_fastgeti(t, n, s2v(L->top.p), tag); if (tagisempty(tag)) { TValue key; setivalue(&key, n); tag = luaV_finishget(L, t, &key, L->top.p, tag); } api_incr_top(L); lua_unlock(L); return novariant(tag); } static int finishrawget (lua_State *L, lu_byte tag) { if (tagisempty(tag)) /* avoid copying empty items to the stack */ setnilvalue(s2v(L->top.p)); api_incr_top(L); lua_unlock(L); return novariant(tag); } l_sinline Table *gettable (lua_State *L, int idx) { TValue *t = index2value(L, idx); api_check(L, ttistable(t), "table expected"); return hvalue(t); } LUA_API int lua_rawget (lua_State *L, int idx) { Table *t; lu_byte tag; lua_lock(L); api_checkpop(L, 1); t = gettable(L, idx); tag = luaH_get(t, s2v(L->top.p - 1), s2v(L->top.p - 1)); L->top.p--; /* pop key */ return finishrawget(L, tag); } LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) { Table *t; lu_byte tag; lua_lock(L); t = gettable(L, idx); luaH_fastgeti(t, n, s2v(L->top.p), tag); return finishrawget(L, tag); } LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) { Table *t; TValue k; lua_lock(L); t = gettable(L, idx); setpvalue(&k, cast_voidp(p)); return finishrawget(L, luaH_get(t, &k, s2v(L->top.p))); } LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { Table *t; lua_lock(L); t = luaH_new(L); sethvalue2s(L, L->top.p, t); api_incr_top(L); if (narray > 0 || nrec > 0) luaH_resize(L, t, cast_uint(narray), cast_uint(nrec)); luaC_checkGC(L); lua_unlock(L); } LUA_API int lua_getmetatable (lua_State *L, int objindex) { const TValue *obj; Table *mt; int res = 0; lua_lock(L); obj = index2value(L, objindex); switch (ttype(obj)) { case LUA_TTABLE: mt = hvalue(obj)->metatable; break; case LUA_TUSERDATA: mt = uvalue(obj)->metatable; break; default: mt = G(L)->mt[ttype(obj)]; break; } if (mt != NULL) { sethvalue2s(L, L->top.p, mt); api_incr_top(L); res = 1; } lua_unlock(L); return res; } LUA_API int lua_getiuservalue (lua_State *L, int idx, int n) { TValue *o; int t; lua_lock(L); o = index2value(L, idx); api_check(L, ttisfulluserdata(o), "full userdata expected"); if (n <= 0 || n > uvalue(o)->nuvalue) { setnilvalue(s2v(L->top.p)); t = LUA_TNONE; } else { setobj2s(L, L->top.p, &uvalue(o)->uv[n - 1].uv); t = ttype(s2v(L->top.p)); } api_incr_top(L); lua_unlock(L); return t; } /* ** set functions (stack -> Lua) */ /* ** t[k] = value at the top of the stack (where 'k' is a string) */ static void auxsetstr (lua_State *L, const TValue *t, const char *k) { int hres; TString *str = luaS_new(L, k); api_checkpop(L, 1); luaV_fastset(t, str, s2v(L->top.p - 1), hres, luaH_psetstr); if (hres == HOK) { luaV_finishfastset(L, t, s2v(L->top.p - 1)); L->top.p--; /* pop value */ } else { setsvalue2s(L, L->top.p, str); /* push 'str' (to make it a TValue) */ api_incr_top(L); luaV_finishset(L, t, s2v(L->top.p - 1), s2v(L->top.p - 2), hres); L->top.p -= 2; /* pop value and key */ } lua_unlock(L); /* lock done by caller */ } LUA_API void lua_setglobal (lua_State *L, const char *name) { TValue gt; lua_lock(L); /* unlock done in 'auxsetstr' */ getGlobalTable(L, >); auxsetstr(L, >, name); } LUA_API void lua_settable (lua_State *L, int idx) { TValue *t; int hres; lua_lock(L); api_checkpop(L, 2); t = index2value(L, idx); luaV_fastset(t, s2v(L->top.p - 2), s2v(L->top.p - 1), hres, luaH_pset); if (hres == HOK) luaV_finishfastset(L, t, s2v(L->top.p - 1)); else luaV_finishset(L, t, s2v(L->top.p - 2), s2v(L->top.p - 1), hres); L->top.p -= 2; /* pop index and value */ lua_unlock(L); } LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { lua_lock(L); /* unlock done in 'auxsetstr' */ auxsetstr(L, index2value(L, idx), k); } LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) { TValue *t; int hres; lua_lock(L); api_checkpop(L, 1); t = index2value(L, idx); luaV_fastseti(t, n, s2v(L->top.p - 1), hres); if (hres == HOK) luaV_finishfastset(L, t, s2v(L->top.p - 1)); else { TValue temp; setivalue(&temp, n); luaV_finishset(L, t, &temp, s2v(L->top.p - 1), hres); } L->top.p--; /* pop value */ lua_unlock(L); } static void aux_rawset (lua_State *L, int idx, TValue *key, int n) { Table *t; lua_lock(L); api_checkpop(L, n); t = gettable(L, idx); luaH_set(L, t, key, s2v(L->top.p - 1)); invalidateTMcache(t); luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1)); L->top.p -= n; lua_unlock(L); } LUA_API void lua_rawset (lua_State *L, int idx) { aux_rawset(L, idx, s2v(L->top.p - 2), 2); } LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { TValue k; setpvalue(&k, cast_voidp(p)); aux_rawset(L, idx, &k, 1); } LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) { Table *t; lua_lock(L); api_checkpop(L, 1); t = gettable(L, idx); luaH_setint(L, t, n, s2v(L->top.p - 1)); luaC_barrierback(L, obj2gco(t), s2v(L->top.p - 1)); L->top.p--; lua_unlock(L); } LUA_API int lua_setmetatable (lua_State *L, int objindex) { TValue *obj; Table *mt; lua_lock(L); api_checkpop(L, 1); obj = index2value(L, objindex); if (ttisnil(s2v(L->top.p - 1))) mt = NULL; else { api_check(L, ttistable(s2v(L->top.p - 1)), "table expected"); mt = hvalue(s2v(L->top.p - 1)); } switch (ttype(obj)) { case LUA_TTABLE: { hvalue(obj)->metatable = mt; if (mt) { luaC_objbarrier(L, gcvalue(obj), mt); luaC_checkfinalizer(L, gcvalue(obj), mt); } break; } case LUA_TUSERDATA: { uvalue(obj)->metatable = mt; if (mt) { luaC_objbarrier(L, uvalue(obj), mt); luaC_checkfinalizer(L, gcvalue(obj), mt); } break; } default: { G(L)->mt[ttype(obj)] = mt; break; } } L->top.p--; lua_unlock(L); return 1; } LUA_API int lua_setiuservalue (lua_State *L, int idx, int n) { TValue *o; int res; lua_lock(L); api_checkpop(L, 1); o = index2value(L, idx); api_check(L, ttisfulluserdata(o), "full userdata expected"); if (!(cast_uint(n) - 1u < cast_uint(uvalue(o)->nuvalue))) res = 0; /* 'n' not in [1, uvalue(o)->nuvalue] */ else { setobj(L, &uvalue(o)->uv[n - 1].uv, s2v(L->top.p - 1)); luaC_barrierback(L, gcvalue(o), s2v(L->top.p - 1)); res = 1; } L->top.p--; lua_unlock(L); return res; } /* ** 'load' and 'call' functions (run Lua code) */ #define checkresults(L,na,nr) \ (api_check(L, (nr) == LUA_MULTRET \ || (L->ci->top.p - L->top.p >= (nr) - (na)), \ "results from function overflow current stack size"), \ api_check(L, LUA_MULTRET <= (nr) && (nr) <= MAXRESULTS, \ "invalid number of results")) LUA_API void lua_callk (lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) { StkId func; lua_lock(L); api_check(L, k == NULL || !isLua(L->ci), "cannot use continuations inside hooks"); api_checkpop(L, nargs + 1); api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); checkresults(L, nargs, nresults); func = L->top.p - (nargs+1); if (k != NULL && yieldable(L)) { /* need to prepare continuation? */ L->ci->u.c.k = k; /* save continuation */ L->ci->u.c.ctx = ctx; /* save context */ luaD_call(L, func, nresults); /* do the call */ } else /* no continuation or no yieldable */ luaD_callnoyield(L, func, nresults); /* just do the call */ adjustresults(L, nresults); lua_unlock(L); } /* ** Execute a protected call. */ struct CallS { /* data to 'f_call' */ StkId func; int nresults; }; static void f_call (lua_State *L, void *ud) { struct CallS *c = cast(struct CallS *, ud); luaD_callnoyield(L, c->func, c->nresults); } LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) { struct CallS c; TStatus status; ptrdiff_t func; lua_lock(L); api_check(L, k == NULL || !isLua(L->ci), "cannot use continuations inside hooks"); api_checkpop(L, nargs + 1); api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); checkresults(L, nargs, nresults); if (errfunc == 0) func = 0; else { StkId o = index2stack(L, errfunc); api_check(L, ttisfunction(s2v(o)), "error handler must be a function"); func = savestack(L, o); } c.func = L->top.p - (nargs+1); /* function to be called */ if (k == NULL || !yieldable(L)) { /* no continuation or no yieldable? */ c.nresults = nresults; /* do a 'conventional' protected call */ status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); } else { /* prepare continuation (call is already protected by 'resume') */ CallInfo *ci = L->ci; ci->u.c.k = k; /* save continuation */ ci->u.c.ctx = ctx; /* save context */ /* save information for error recovery */ ci->u2.funcidx = cast_int(savestack(L, c.func)); ci->u.c.old_errfunc = L->errfunc; L->errfunc = func; setoah(ci, L->allowhook); /* save value of 'allowhook' */ ci->callstatus |= CIST_YPCALL; /* function can do error recovery */ luaD_call(L, c.func, nresults); /* do the call */ ci->callstatus &= ~CIST_YPCALL; L->errfunc = ci->u.c.old_errfunc; status = LUA_OK; /* if it is here, there were no errors */ } adjustresults(L, nresults); lua_unlock(L); return APIstatus(status); } LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname, const char *mode) { ZIO z; TStatus status; lua_lock(L); if (!chunkname) chunkname = "?"; luaZ_init(L, &z, reader, data); status = luaD_protectedparser(L, &z, chunkname, mode); if (status == LUA_OK) { /* no errors? */ LClosure *f = clLvalue(s2v(L->top.p - 1)); /* get new function */ if (f->nupvalues >= 1) { /* does it have an upvalue? */ /* get global table from registry */ TValue gt; getGlobalTable(L, >); /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ setobj(L, f->upvals[0]->v.p, >); luaC_barrier(L, f->upvals[0], >); } } lua_unlock(L); return APIstatus(status); } /* ** Dump a Lua function, calling 'writer' to write its parts. Ensure ** the stack returns with its original size. */ LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) { int status; ptrdiff_t otop = savestack(L, L->top.p); /* original top */ TValue *f = s2v(L->top.p - 1); /* function to be dumped */ lua_lock(L); api_checkpop(L, 1); api_check(L, isLfunction(f), "Lua function expected"); status = luaU_dump(L, clLvalue(f)->p, writer, data, strip); L->top.p = restorestack(L, otop); /* restore top */ lua_unlock(L); return status; } LUA_API int lua_status (lua_State *L) { return APIstatus(L->status); } /* ** Garbage-collection function */ LUA_API int lua_vgc(lua_State *L, int what, va_list argp) { int res = 0; global_State *g = G(L); if (g->gcstp & (GCSTPGC | GCSTPCLS)) /* internal stop? */ return -1; /* all options are invalid when stopped */ lua_lock(L); switch (what) { case LUA_GCSTOP: { g->gcstp = GCSTPUSR; /* stopped by the user */ break; } case LUA_GCRESTART: { luaE_setdebt(g, 0); g->gcstp = 0; /* (other bits must be zero here) */ break; } case LUA_GCCOLLECT: { luaC_fullgc(L, 0); break; } case LUA_GCCOUNT: { /* GC values are expressed in Kbytes: #bytes/2^10 */ res = cast_int(gettotalbytes(g) >> 10); break; } case LUA_GCCOUNTB: { res = cast_int(gettotalbytes(g) & 0x3ff); break; } case LUA_GCSTEP: { lu_byte oldstp = g->gcstp; l_mem n = cast(l_mem, va_arg(argp, size_t)); int work = 0; /* true if GC did some work */ g->gcstp = 0; /* allow GC to run (other bits must be zero here) */ if (n <= 0) n = g->GCdebt; /* force to run one basic step */ luaE_setdebt(g, g->GCdebt - n); luaC_condGC(L, (void)0, work = 1); if (work && g->gcstate == GCSpause) /* end of cycle? */ res = 1; /* signal it */ g->gcstp = oldstp; /* restore previous state */ break; } case LUA_GCISRUNNING: { res = gcrunning(g); break; } case LUA_GCGEN: { res = (g->gckind == KGC_INC) ? LUA_GCINC : LUA_GCGEN; luaC_changemode(L, KGC_GENMINOR); break; } case LUA_GCINC: { res = (g->gckind == KGC_INC) ? LUA_GCINC : LUA_GCGEN; luaC_changemode(L, KGC_INC); break; } case LUA_GCPARAM: { int param = va_arg(argp, int); int value = va_arg(argp, int); api_check(L, 0 <= param && param < LUA_GCPN, "invalid parameter"); res = cast_int(luaO_applyparam(g->gcparams[param], 100)); if (value >= 0) g->gcparams[param] = luaO_codeparam(cast_uint(value)); break; } default: res = -1; /* invalid option */ } lua_unlock(L); return res; } LUA_API int lua_gc(lua_State* L, int what, ...) { int rsp; va_list argp; va_start(argp, what); rsp=lua_vgc(L, what, argp); va_end(argp); return rsp; } /* ** miscellaneous functions */ LUA_API int lua_error (lua_State *L) { TValue *errobj; lua_lock(L); errobj = s2v(L->top.p - 1); api_checkpop(L, 1); /* error object is the memory error message? */ if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg)) luaM_error(L); /* raise a memory error */ else luaG_errormsg(L); /* raise a regular error */ /* code unreachable; will unlock when control actually leaves the kernel */ return 0; /* to avoid warnings */ } LUA_API int lua_next (lua_State *L, int idx) { Table *t; int more; lua_lock(L); api_checkpop(L, 1); t = gettable(L, idx); more = luaH_next(L, t, L->top.p - 1); if (more) api_incr_top(L); else /* no more elements */ L->top.p--; /* pop key */ lua_unlock(L); return more; } LUA_API void lua_toclose (lua_State *L, int idx) { StkId o; lua_lock(L); o = index2stack(L, idx); api_check(L, L->tbclist.p < o, "given index below or equal a marked one"); luaF_newtbcupval(L, o); /* create new to-be-closed upvalue */ L->ci->callstatus |= CIST_TBC; /* mark that function has TBC slots */ lua_unlock(L); } LUA_API void lua_concat (lua_State *L, int n) { lua_lock(L); api_checknelems(L, n); if (n > 0) { luaV_concat(L, n); luaC_checkGC(L); } else { /* nothing to concatenate */ setsvalue2s(L, L->top.p, luaS_newlstr(L, "", 0)); /* push empty string */ api_incr_top(L); } lua_unlock(L); } LUA_API void lua_len (lua_State *L, int idx) { TValue *t; lua_lock(L); t = index2value(L, idx); luaV_objlen(L, L->top.p, t); api_incr_top(L); lua_unlock(L); } LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { lua_Alloc f; lua_lock(L); if (ud) *ud = G(L)->ud; f = G(L)->frealloc; lua_unlock(L); return f; } LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { lua_lock(L); G(L)->ud = ud; G(L)->frealloc = f; lua_unlock(L); } void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud) { lua_lock(L); G(L)->ud_warn = ud; G(L)->warnf = f; lua_unlock(L); } void lua_warning (lua_State *L, const char *msg, int tocont) { lua_lock(L); luaE_warning(L, msg, tocont); lua_unlock(L); } LUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) { Udata *u; lua_lock(L); api_check(L, 0 <= nuvalue && nuvalue < SHRT_MAX, "invalid value"); u = luaS_newudata(L, size, cast(unsigned short, nuvalue)); setuvalue(L, s2v(L->top.p), u); api_incr_top(L); luaC_checkGC(L); lua_unlock(L); return getudatamem(u); } static const char *aux_upvalue (TValue *fi, int n, TValue **val, GCObject **owner) { switch (ttypetag(fi)) { case LUA_VCCL: { /* C closure */ CClosure *f = clCvalue(fi); if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues))) return NULL; /* 'n' not in [1, f->nupvalues] */ *val = &f->upvalue[n-1]; if (owner) *owner = obj2gco(f); return ""; } case LUA_VLCL: { /* Lua closure */ LClosure *f = clLvalue(fi); TString *name; Proto *p = f->p; if (!(cast_uint(n) - 1u < cast_uint(p->sizeupvalues))) return NULL; /* 'n' not in [1, p->sizeupvalues] */ *val = f->upvals[n-1]->v.p; if (owner) *owner = obj2gco(f->upvals[n - 1]); name = p->upvalues[n-1].name; return (name == NULL) ? "(no name)" : getstr(name); } default: return NULL; /* not a closure */ } } LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { const char *name; TValue *val = NULL; /* to avoid warnings */ lua_lock(L); name = aux_upvalue(index2value(L, funcindex), n, &val, NULL); if (name) { setobj2s(L, L->top.p, val); api_incr_top(L); } lua_unlock(L); return name; } LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { const char *name; TValue *val = NULL; /* to avoid warnings */ GCObject *owner = NULL; /* to avoid warnings */ TValue *fi; lua_lock(L); fi = index2value(L, funcindex); api_checknelems(L, 1); name = aux_upvalue(fi, n, &val, &owner); if (name) { L->top.p--; setobj(L, val, s2v(L->top.p)); luaC_barrier(L, owner, val); } lua_unlock(L); return name; } static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) { static const UpVal *const nullup = NULL; LClosure *f; TValue *fi = index2value(L, fidx); api_check(L, ttisLclosure(fi), "Lua function expected"); f = clLvalue(fi); if (pf) *pf = f; if (1 <= n && n <= f->p->sizeupvalues) return &f->upvals[n - 1]; /* get its upvalue pointer */ else return (UpVal**)&nullup; } LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { TValue *fi = index2value(L, fidx); switch (ttypetag(fi)) { case LUA_VLCL: { /* lua closure */ return *getupvalref(L, fidx, n, NULL); } case LUA_VCCL: { /* C closure */ CClosure *f = clCvalue(fi); if (1 <= n && n <= f->nupvalues) return &f->upvalue[n - 1]; /* else */ } /* FALLTHROUGH */ case LUA_VLCF: return NULL; /* light C functions have no upvalues */ default: { api_check(L, 0, "function expected"); return NULL; } } } LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, int fidx2, int n2) { LClosure *f1; UpVal **up1 = getupvalref(L, fidx1, n1, &f1); UpVal **up2 = getupvalref(L, fidx2, n2, NULL); api_check(L, *up1 != NULL && *up2 != NULL, "invalid upvalue index"); *up1 = *up2; luaC_objbarrier(L, f1, *up1); } /* ** $Id: lauxlib.c $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ #define lauxlib_c #define LUA_LIB #include #include #include #include #include /* ** This file uses only the official API of Lua. ** Any function declared here could be written as an application function. */ #include "lua.h" #include "lauxlib.h" /* ** {====================================================== ** Traceback ** ======================================================= */ #define LEVELS1 10 /* size of the first part of the stack */ #define LEVELS2 11 /* size of the second part of the stack */ /* ** Search for 'objidx' in table at index -1. ('objidx' must be an ** absolute index.) Return 1 + string at top if it found a good name. */ static int findfield (lua_State *L, int objidx, int level) { if (level == 0 || !lua_istable(L, -1)) return 0; /* not found */ lua_pushnil(L); /* start 'next' loop */ while (lua_next(L, -2)) { /* for each pair in table */ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ if (lua_rawequal(L, objidx, -1)) { /* found object? */ lua_pop(L, 1); /* remove value (but keep name) */ return 1; } else if (findfield(L, objidx, level - 1)) { /* try recursively */ /* stack: lib_name, lib_table, field_name (top) */ lua_pushliteral(L, "."); /* place '.' between the two names */ lua_replace(L, -3); /* (in the slot occupied by table) */ lua_concat(L, 3); /* lib_name.field_name */ return 1; } } lua_pop(L, 1); /* remove value */ } return 0; /* not found */ } /* ** Search for a name for a function in all loaded modules */ static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { int top = lua_gettop(L); lua_getinfo(L, "f", ar); /* push function */ lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); luaL_checkstack(L, 6, "not enough stack"); /* slots for 'findfield' */ if (findfield(L, top + 1, 2)) { const char *name = lua_tostring(L, -1); if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */ lua_pushstring(L, name + 3); /* push name without prefix */ lua_remove(L, -2); /* remove original name */ } lua_copy(L, -1, top + 1); /* copy name to proper place */ lua_settop(L, top + 1); /* remove table "loaded" and name copy */ return 1; } else { lua_settop(L, top); /* remove function and global table */ return 0; } } static void pushfuncname (lua_State *L, lua_Debug *ar) { if (*ar->namewhat != '\0') /* is there a name from code? */ lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */ else if (*ar->what == 'm') /* main? */ lua_pushliteral(L, "main chunk"); else if (pushglobalfuncname(L, ar)) { /* try a global name */ lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); lua_remove(L, -2); /* remove name */ } else if (*ar->what != 'C') /* for Lua functions, use */ lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); else /* nothing left... */ lua_pushliteral(L, "?"); } static int lastlevel (lua_State *L) { lua_Debug ar; int li = 1, le = 1; /* find an upper bound */ while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } /* do a binary search */ while (li < le) { int m = (li + le)/2; if (lua_getstack(L, m, &ar)) li = m + 1; else le = m; } return le - 1; } LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level) { luaL_Buffer b; lua_Debug ar; int last = lastlevel(L1); int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1; luaL_buffinit(L, &b); if (msg) { luaL_addstring(&b, msg); luaL_addchar(&b, '\n'); } luaL_addstring(&b, "stack traceback:"); while (lua_getstack(L1, level++, &ar)) { if (limit2show-- == 0) { /* too many levels? */ int n = last - level - LEVELS2 + 1; /* number of levels to skip */ lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n); luaL_addvalue(&b); /* add warning about skip */ level += n; /* and skip to last levels */ } else { lua_getinfo(L1, "Slnt", &ar); if (ar.currentline <= 0) lua_pushfstring(L, "\n\t%s: in ", ar.short_src); else lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline); luaL_addvalue(&b); pushfuncname(L, &ar); luaL_addvalue(&b); if (ar.istailcall) luaL_addstring(&b, "\n\t(...tail calls...)"); } } luaL_pushresult(&b); } /* }====================================================== */ /* ** {====================================================== ** Error-report functions ** ======================================================= */ LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) { lua_Debug ar; const char *argword; if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ return luaL_error(L, "bad argument #%d (%s)", arg, extramsg); lua_getinfo(L, "nt", &ar); if (arg <= ar.extraargs) /* error in an extra argument? */ argword = "extra argument"; else { arg -= ar.extraargs; /* do not count extra arguments */ if (strcmp(ar.namewhat, "method") == 0) { /* colon syntax? */ arg--; /* do not count (extra) self argument */ if (arg == 0) /* error in self argument? */ return luaL_error(L, "calling '%s' on bad self (%s)", ar.name, extramsg); /* else go through; error in a regular argument */ } argword = "argument"; } if (ar.name == NULL) ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; return luaL_error(L, "bad %s #%d to '%s' (%s)", argword, arg, ar.name, extramsg); } LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) { const char *msg; const char *typearg; /* name for the type of the actual argument */ if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING) typearg = lua_tostring(L, -1); /* use the given type name */ else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA) typearg = "light userdata"; /* special name for messages */ else typearg = luaL_typename(L, arg); /* standard name */ msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg); return luaL_argerror(L, arg, msg); } static void tag_error (lua_State *L, int arg, int tag) { luaL_typeerror(L, arg, lua_typename(L, tag)); } /* ** The use of 'lua_pushfstring' ensures this function does not ** need reserved stack space when called. */ LUALIB_API void luaL_where (lua_State *L, int level) { lua_Debug ar; if (lua_getstack(L, level, &ar)) { /* check function at level */ lua_getinfo(L, "Sl", &ar); /* get info about it */ if (ar.currentline > 0) { /* is there info? */ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); return; } } lua_pushfstring(L, ""); /* else, no information available... */ } /* ** Again, the use of 'lua_pushvfstring' ensures this function does ** not need reserved stack space when called. (At worst, it generates ** a memory error instead of the given message.) */ LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { va_list argp; va_start(argp, fmt); luaL_where(L, 1); lua_pushvfstring(L, fmt, argp); va_end(argp); lua_concat(L, 2); return lua_error(L); } #ifndef BA_MINIOSLIB LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { int en = errno; /* calls to Lua API may change this value */ if (stat) { lua_pushboolean(L, 1); return 1; } else { const char *msg; luaL_pushfail(L); msg = (en != 0) ? strerror(en) : "(no extra info)"; if (fname) lua_pushfstring(L, "%s: %s", fname, msg); else lua_pushstring(L, msg); lua_pushinteger(L, en); return 3; } } #endif #if !defined(l_inspectstat) /* { */ #if defined(LUA_USE_POSIX) #include /* ** use appropriate macros to interpret 'pclose' return status */ #define l_inspectstat(stat,what) \ if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } #else #define l_inspectstat(stat,what) /* no op */ #endif #endif /* } */ #ifndef BA_MINIOSLIB LUALIB_API int luaL_execresult (lua_State *L, int stat) { if (stat != 0 && errno != 0) /* error with an 'errno'? */ return luaL_fileresult(L, 0, NULL); else { const char *what = "exit"; /* type of termination */ l_inspectstat(stat, what); /* interpret result */ if (*what == 'e' && stat == 0) /* successful termination? */ lua_pushboolean(L, 1); else luaL_pushfail(L); lua_pushstring(L, what); lua_pushinteger(L, stat); return 3; /* return true/fail,what,code */ } } #endif /* }====================================================== */ /* ** {====================================================== ** Userdata's metatable manipulation ** ======================================================= */ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ lua_pop(L, 1); lua_createtable(L, 0, 2); /* create metatable */ lua_pushstring(L, tname); lua_setfield(L, -2, "__name"); /* metatable.__name = tname */ lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ return 1; } LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { luaL_getmetatable(L, tname); lua_setmetatable(L, -2); } LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { void *p = lua_touserdata(L, ud); if (p != NULL) { /* value is a userdata? */ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ luaL_getmetatable(L, tname); /* get correct metatable */ if (!lua_rawequal(L, -1, -2)) /* not the same? */ p = NULL; /* value is a userdata with wrong metatable */ lua_pop(L, 2); /* remove both metatables */ return p; } } return NULL; /* value is not a userdata with a metatable */ } LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { void *p = luaL_testudata(L, ud, tname); luaL_argexpected(L, p != NULL, ud, tname); return p; } /* }====================================================== */ /* ** {====================================================== ** Argument check functions ** ======================================================= */ LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def, const char *const lst[]) { const char *name = (def) ? luaL_optstring(L, arg, def) : luaL_checkstring(L, arg); int i; for (i=0; lst[i]; i++) if (strcmp(lst[i], name) == 0) return i; return luaL_argerror(L, arg, lua_pushfstring(L, "invalid option '%s'", name)); } /* ** Ensures the stack has at least 'space' extra slots, raising an error ** if it cannot fulfill the request. (The error handling needs a few ** extra slots to format the error message. In case of an error without ** this extra space, Lua will generate the same 'stack overflow' error, ** but without 'msg'.) */ LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { if (l_unlikely(!lua_checkstack(L, space))) { if (msg) luaL_error(L, "stack overflow (%s)", msg); else luaL_error(L, "stack overflow"); } } LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) { if (l_unlikely(lua_type(L, arg) != t)) tag_error(L, arg, t); } LUALIB_API void luaL_checkany (lua_State *L, int arg) { if (l_unlikely(lua_type(L, arg) == LUA_TNONE)) luaL_argerror(L, arg, "value expected"); } LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) { const char *s = lua_tolstring(L, arg, len); if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING); return s; } LUALIB_API const char *luaL_optlstring (lua_State *L, int arg, const char *def, size_t *len) { if (lua_isnoneornil(L, arg)) { if (len) *len = (def ? strlen(def) : 0); return def; } else return luaL_checklstring(L, arg, len); } LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) { int isnum; lua_Number d = lua_tonumberx(L, arg, &isnum); if (l_unlikely(!isnum)) tag_error(L, arg, LUA_TNUMBER); return d; } LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) { return luaL_opt(L, luaL_checknumber, arg, def); } static void interror (lua_State *L, int arg) { if (lua_isnumber(L, arg)) luaL_argerror(L, arg, "number has no integer representation"); else tag_error(L, arg, LUA_TNUMBER); } LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) { int isnum; lua_Integer d = lua_tointegerx(L, arg, &isnum); if (l_unlikely(!isnum)) { interror(L, arg); } return d; } LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg, lua_Integer def) { return luaL_opt(L, luaL_checkinteger, arg, def); } /* }====================================================== */ /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ /* userdata to box arbitrary data */ typedef struct UBox { void *box; size_t bsize; } UBox; /* Resize the buffer used by a box. Optimize for the common case of ** resizing to the old size. (For instance, __gc will resize the box ** to 0 even after it was closed. 'pushresult' may also resize it to a ** final size that is equal to the one set when the buffer was created.) */ static void *resizebox (lua_State *L, int idx, size_t newsize) { UBox *box = (UBox *)lua_touserdata(L, idx); if (box->bsize == newsize) /* not changing size? */ return box->box; /* keep the buffer */ else { void *ud; lua_Alloc allocf = lua_getallocf(L, &ud); void *temp = allocf(ud, box->box, box->bsize, newsize); if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */ lua_pushliteral(L, "not enough memory"); lua_error(L); /* raise a memory error */ } box->box = temp; box->bsize = newsize; return temp; } } static int boxgc (lua_State *L) { resizebox(L, 1, 0); return 0; } static const luaL_Reg boxmt[] = { /* box metamethods */ {"__gc", boxgc}, {"__close", boxgc}, {NULL, NULL} }; static void newbox (lua_State *L) { UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0); box->box = NULL; box->bsize = 0; if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */ luaL_setfuncs(L, boxmt, 0); /* set its metamethods */ lua_setmetatable(L, -2); } /* ** check whether buffer is using a userdata on the stack as a temporary ** buffer */ #define buffonstack(B) ((B)->b != (B)->init.b) /* ** Whenever buffer is accessed, slot 'idx' must either be a box (which ** cannot be NULL) or it is a placeholder for the buffer. */ #define checkbufferlevel(B,idx) \ lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \ : lua_touserdata(B->L, idx) == (void*)B) /* ** Compute new size for buffer 'B', enough to accommodate extra 'sz' ** bytes plus one for a terminating zero. */ static size_t newbuffsize (luaL_Buffer *B, size_t sz) { size_t newsize = B->size; if (l_unlikely(sz >= MAX_SIZE - B->n)) return cast_sizet(luaL_error(B->L, "resulting string too large")); /* else B->n + sz + 1 <= MAX_SIZE */ if (newsize <= MAX_SIZE/3 * 2) /* no overflow? */ newsize += (newsize >> 1); /* new size *= 1.5 */ if (newsize < B->n + sz + 1) /* not big enough? */ newsize = B->n + sz + 1; return newsize; } /* ** Returns a pointer to a free area with at least 'sz' bytes in buffer ** 'B'. 'boxidx' is the relative position in the stack where is the ** buffer's box or its placeholder. */ static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) { checkbufferlevel(B, boxidx); if (B->size - B->n >= sz) /* enough space? */ return B->b + B->n; else { lua_State *L = B->L; char *newbuff; size_t newsize = newbuffsize(B, sz); /* create larger buffer */ if (buffonstack(B)) /* buffer already has a box? */ newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */ else { /* no box yet */ lua_remove(L, boxidx); /* remove placeholder */ newbox(L); /* create a new box */ lua_insert(L, boxidx); /* move box to its intended position */ lua_toclose(L, boxidx); newbuff = (char *)resizebox(L, boxidx, newsize); memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */ } B->b = newbuff; B->size = newsize; return newbuff + B->n; } } /* ** returns a pointer to a free area with at least 'sz' bytes */ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { return prepbuffsize(B, sz, -1); } LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */ char *b = prepbuffsize(B, l, -1); memcpy(b, s, l * sizeof(char)); luaL_addsize(B, l); } } LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { luaL_addlstring(B, s, strlen(s)); } LUALIB_API void luaL_pushresult (luaL_Buffer *B) { lua_State *L = B->L; checkbufferlevel(B, -1); if (!buffonstack(B)) /* using static buffer? */ lua_pushlstring(L, B->b, B->n); /* save result as regular string */ else { /* reuse buffer already allocated */ UBox *box = (UBox *)lua_touserdata(L, -1); void *ud; lua_Alloc allocf = lua_getallocf(L, &ud); /* function to free buffer */ size_t len = B->n; /* final string length */ char *s; resizebox(L, -1, len + 1); /* adjust box size to content size */ s = (char*)box->box; /* final buffer address */ s[len] = '\0'; /* add ending zero */ /* clear box, as Lua will take control of the buffer */ box->bsize = 0; box->box = NULL; lua_pushexternalstring(L, s, len, allocf, ud); lua_closeslot(L, -2); /* close the box */ lua_gc(L, LUA_GCSTEP, len); } lua_remove(L, -2); /* remove box or placeholder from the stack */ } LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { luaL_addsize(B, sz); luaL_pushresult(B); } /* ** 'luaL_addvalue' is the only function in the Buffer system where the ** box (if existent) is not on the top of the stack. So, instead of ** calling 'luaL_addlstring', it replicates the code using -2 as the ** last argument to 'prepbuffsize', signaling that the box is (or will ** be) below the string being added to the buffer. (Box creation can ** trigger an emergency GC, so we should not remove the string from the ** stack before we have the space guaranteed.) */ LUALIB_API void luaL_addvalue (luaL_Buffer *B) { lua_State *L = B->L; size_t len; const char *s = lua_tolstring(L, -1, &len); char *b = prepbuffsize(B, len, -2); memcpy(b, s, len * sizeof(char)); luaL_addsize(B, len); lua_pop(L, 1); /* pop string */ } LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { B->L = L; B->b = B->init.b; B->n = 0; B->size = LUAL_BUFFERSIZE; lua_pushlightuserdata(L, (void*)B); /* push placeholder */ } LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { luaL_buffinit(L, B); return prepbuffsize(B, sz, -1); } /* }====================================================== */ /* ** {====================================================== ** Reference system ** ======================================================= */ /* ** The previously freed references form a linked list: t[1] is the index ** of a first free index, t[t[1]] is the index of the second element, ** etc. A zero signals the end of the list. */ LUALIB_API int luaL_ref (lua_State *L, int t) { int ref; if (lua_isnil(L, -1)) { lua_pop(L, 1); /* remove from stack */ return LUA_REFNIL; /* 'nil' has a unique fixed reference */ } t = lua_absindex(L, t); if (lua_rawgeti(L, t, 1) == LUA_TNUMBER) /* already initialized? */ ref = (int)lua_tointeger(L, -1); /* ref = t[1] */ else { /* first access */ lua_assert(!lua_toboolean(L, -1)); /* must be nil or false */ ref = 0; /* list is empty */ lua_pushinteger(L, 0); /* initialize as an empty list */ lua_rawseti(L, t, 1); /* ref = t[1] = 0 */ } lua_pop(L, 1); /* remove element from stack */ if (ref != 0) { /* any free element? */ lua_rawgeti(L, t, ref); /* remove it from list */ lua_rawseti(L, t, 1); /* (t[1] = t[ref]) */ } else /* no free elements */ ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ lua_rawseti(L, t, ref); return ref; } LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { if (ref >= 0) { t = lua_absindex(L, t); lua_rawgeti(L, t, 1); lua_assert(lua_isinteger(L, -1)); lua_rawseti(L, t, ref); /* t[ref] = t[1] */ lua_pushinteger(L, ref); lua_rawseti(L, t, 1); /* t[1] = ref */ } } /* }====================================================== */ /* ** {====================================================== ** Load functions ** ======================================================= */ #ifndef LUA_NOIOLIB typedef struct LoadF { unsigned n; /* number of pre-read characters */ FILE *f; /* file being read */ char buff[BUFSIZ]; /* area for reading file */ } LoadF; static const char *getF (lua_State *L, void *ud, size_t *size) { LoadF *lf = (LoadF *)ud; UNUSED(L); if (lf->n > 0) { /* are there pre-read characters to be read? */ *size = lf->n; /* return them (chars already in buffer) */ lf->n = 0; /* no more pre-read characters */ } else { /* read a block from file */ /* 'fread' can return > 0 *and* set the EOF flag. If next call to 'getF' called 'fread', it might still wait for user input. The next check avoids this problem. */ if (feof(lf->f)) return NULL; *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ } return lf->buff; } static int errfile (lua_State *L, const char *what, int fnameindex) { int err = errno; const char *filename = lua_tostring(L, fnameindex) + 1; if (err != 0) lua_pushfstring(L, "cannot %s %s: %s", what, filename, strerror(err)); else lua_pushfstring(L, "cannot %s %s", what, filename); lua_remove(L, fnameindex); return LUA_ERRFILE; } /* ** Skip an optional BOM at the start of a stream. If there is an ** incomplete BOM (the first character is correct but the rest is ** not), returns the first character anyway to force an error ** (as no chunk can start with 0xEF). */ static int skipBOM (FILE *f) { int c = getc(f); /* read first character */ if (c == 0xEF && getc(f) == 0xBB && getc(f) == 0xBF) /* correct BOM? */ return getc(f); /* ignore BOM and return next char */ else /* no (valid) BOM */ return c; /* return first character */ } /* ** reads the first character of file 'f' and skips an optional BOM mark ** in its beginning plus its first line if it starts with '#'. Returns ** true if it skipped the first line. In any case, '*cp' has the ** first "valid" character of the file (after the optional BOM and ** a first-line comment). */ static int skipcomment (FILE *f, int *cp) { int c = *cp = skipBOM(f); if (c == '#') { /* first line is a comment (Unix exec. file)? */ do { /* skip first line */ c = getc(f); } while (c != EOF && c != '\n'); *cp = getc(f); /* next character after comment, if present */ return 1; /* there was a comment */ } else return 0; /* no comment */ } LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, const char *mode) { LoadF lf; int status, readstatus; int c; int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ if (filename == NULL) { lua_pushliteral(L, "=stdin"); lf.f = stdin; } else { lua_pushfstring(L, "@%s", filename); errno = 0; lf.f = fopen(filename, "r"); if (lf.f == NULL) return errfile(L, "open", fnameindex); } lf.n = 0; if (skipcomment(lf.f, &c)) /* read initial portion */ lf.buff[lf.n++] = '\n'; /* add newline to correct line numbers */ if (c == LUA_SIGNATURE[0]) { /* binary file? */ lf.n = 0; /* remove possible newline */ if (filename) { /* "real" file? */ errno = 0; lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ if (lf.f == NULL) return errfile(L, "reopen", fnameindex); skipcomment(lf.f, &c); /* re-read initial portion */ } } if (c != EOF) lf.buff[lf.n++] = cast_char(c); /* 'c' is the first character */ status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); readstatus = ferror(lf.f); errno = 0; /* no useful error number until here */ if (filename) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus) { lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ return errfile(L, "read", fnameindex); } lua_remove(L, fnameindex); return status; } #else LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, const char *mode) { (void)filename; (void)mode; lua_pushliteral(L, "loadfile not supported"); return LUA_ERRFILE; } #endif typedef struct LoadS { const char *s; size_t size; } LoadS; static const char *getS (lua_State *L, void *ud, size_t *size) { LoadS *ls = (LoadS *)ud; UNUSED(L); if (ls->size == 0) return NULL; *size = ls->size; ls->size = 0; return ls->s; } LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, const char *name, const char *mode) { LoadS ls; ls.s = buff; ls.size = size; return lua_load(L, getS, &ls, name, mode); } LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { return luaL_loadbuffer(L, s, strlen(s), s); } /* }====================================================== */ LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { if (!lua_getmetatable(L, obj)) /* no metatable? */ return LUA_TNIL; else { int tt; lua_pushstring(L, event); tt = lua_rawget(L, -2); if (tt == LUA_TNIL) /* is metafield nil? */ lua_pop(L, 2); /* remove metatable and metafield */ else lua_remove(L, -2); /* remove only metatable */ return tt; /* return metafield type */ } } LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { obj = lua_absindex(L, obj); if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */ return 0; lua_pushvalue(L, obj); lua_call(L, 1, 1); return 1; } LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) { lua_Integer l; int isnum; lua_len(L, idx); l = lua_tointegerx(L, -1, &isnum); if (l_unlikely(!isnum)) luaL_error(L, "object length is not an integer"); lua_pop(L, 1); /* remove object */ return l; } LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { idx = lua_absindex(L,idx); if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */ if (!lua_isstring(L, -1)) luaL_error(L, "'__tostring' must return a string"); } else { switch (lua_type(L, idx)) { case LUA_TNUMBER: { char buff[LUA_N2SBUFFSZ]; lua_numbertocstring(L, idx, buff); lua_pushstring(L, buff); break; } case LUA_TSTRING: lua_pushvalue(L, idx); break; case LUA_TBOOLEAN: lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); break; case LUA_TNIL: lua_pushliteral(L, "nil"); break; default: { int tt = luaL_getmetafield(L, idx, "__name"); /* try name */ const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) : luaL_typename(L, idx); lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx)); if (tt != LUA_TNIL) lua_remove(L, -2); /* remove '__name' */ break; } } } return lua_tolstring(L, -1, len); } /* ** set functions from list 'l' into table at top - 'nup'; each ** function gets the 'nup' elements at the top as upvalues. ** Returns with only the table at the stack. */ LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { luaL_checkstack(L, nup, "too many upvalues"); for (; l->name != NULL; l++) { /* fill the table with given functions */ if (l->func == NULL) /* placeholder? */ lua_pushboolean(L, 0); else { int i; for (i = 0; i < nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -nup); lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ } lua_setfield(L, -(nup + 2), l->name); } lua_pop(L, nup); /* remove upvalues */ } /* ** ensure that stack[idx][fname] has a table and push that table ** into the stack */ LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { if (lua_getfield(L, idx, fname) == LUA_TTABLE) return 1; /* table already there */ else { lua_pop(L, 1); /* remove previous result */ idx = lua_absindex(L, idx); lua_newtable(L); lua_pushvalue(L, -1); /* copy to be left at top */ lua_setfield(L, idx, fname); /* assign new table to field */ return 0; /* false, because did not find table there */ } } /* ** Stripped-down 'require': After checking "loaded" table, calls 'openf' ** to open a module, registers the result in 'package.loaded' table and, ** if 'glb' is true, also registers the result in the global table. ** Leaves resulting module on the top. */ LUALIB_API void luaL_requiref (lua_State *L, const char *modname, lua_CFunction openf, int glb) { luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_getfield(L, -1, modname); /* LOADED[modname] */ if (!lua_toboolean(L, -1)) { /* package not already loaded? */ lua_pop(L, 1); /* remove field */ lua_pushcfunction(L, openf); lua_pushstring(L, modname); /* argument to open function */ lua_call(L, 1, 1); /* call 'openf' to open module */ lua_pushvalue(L, -1); /* make copy of module (call result) */ lua_setfield(L, -3, modname); /* LOADED[modname] = module */ } lua_remove(L, -2); /* remove LOADED table */ if (glb) { lua_pushvalue(L, -1); /* copy of module */ lua_setglobal(L, modname); /* _G[modname] = module */ } } LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s, const char *p, const char *r) { const char *wild; size_t l = strlen(p); while ((wild = strstr(s, p)) != NULL) { luaL_addlstring(b, s, ct_diff2sz(wild - s)); /* push prefix */ luaL_addstring(b, r); /* push replacement in place of pattern */ s = wild + l; /* continue after 'p' */ } luaL_addstring(b, s); /* push last suffix */ } LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r) { luaL_Buffer b; luaL_buffinit(L, &b); luaL_addgsub(&b, s, p, r); luaL_pushresult(&b); return lua_tostring(L, -1); } LUALIB_API void * luaL_alloc(void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { baFree(ptr); return NULL; } else return baRealloc(ptr, nsize); } /* ** Standard panic function just prints an error message. The test ** with 'lua_type' avoids possible memory errors in 'lua_tostring'. */ static int panic (lua_State *L) { const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1) : "error object is not a string"; lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", msg); return 0; /* return to Lua to abort */ } /* ** Warning functions: ** warnfoff: warning system is off ** warnfon: ready to start a new message ** warnfcont: previous message is to be continued */ static void warnfoff (void *ud, const char *message, int tocont); static void warnfon (void *ud, const char *message, int tocont); static void warnfcont (void *ud, const char *message, int tocont); /* ** Check whether message is a control message. If so, execute the ** control or ignore it if unknown. */ static int checkcontrol (lua_State *L, const char *message, int tocont) { if (tocont || *(message++) != '@') /* not a control message? */ return 0; else { if (strcmp(message, "off") == 0) lua_setwarnf(L, warnfoff, L); /* turn warnings off */ else if (strcmp(message, "on") == 0) lua_setwarnf(L, warnfon, L); /* turn warnings on */ return 1; /* it was a control message */ } } static void warnfoff (void *ud, const char *message, int tocont) { checkcontrol((lua_State *)ud, message, tocont); } /* ** Writes the message and handle 'tocont', finishing the message ** if needed and setting the next warn function. */ static void warnfcont (void *ud, const char *message, int tocont) { lua_State *L = (lua_State *)ud; lua_writestringerror("%s", message); /* write message */ if (tocont) /* not the last part? */ lua_setwarnf(L, warnfcont, L); /* to be continued */ else { /* last part */ lua_writestringerror("%s", "\n"); /* finish message with end-of-line */ lua_setwarnf(L, warnfon, L); /* next call is a new message */ } } static void warnfon (void *ud, const char *message, int tocont) { if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */ return; /* nothing else to be done */ lua_writestringerror("%s", "Lua warning: "); /* start a new warning */ warnfcont(ud, message, tocont); /* finish processing */ } /* ** A function to compute an unsigned int with some level of ** randomness. Rely on Address Space Layout Randomization (if present) ** and the current time. */ #if !defined(luai_makeseed) #include /* Size for the buffer, in bytes */ #define BUFSEEDB (sizeof(void*) + sizeof(time_t)) /* Size for the buffer in int's, rounded up */ #define BUFSEED ((BUFSEEDB + sizeof(int) - 1) / sizeof(int)) /* ** Copy the contents of variable 'v' into the buffer pointed by 'b'. ** (The '&b[0]' disguises 'b' to fix an absurd warning from clang.) */ #define addbuff(b,v) (memcpy(&b[0], &(v), sizeof(v)), b += sizeof(v)) static unsigned int luai_makeseed (void) { unsigned int buff[BUFSEED]; unsigned int res; unsigned int i; time_t t = time(NULL); char *b = (char*)buff; addbuff(b, b); /* local variable's address */ addbuff(b, t); /* time */ /* fill (rare but possible) remain of the buffer with zeros */ memset(b, 0, sizeof(buff) - BUFSEEDB); res = buff[0]; for (i = 1; i < BUFSEED; i++) res ^= (res >> 3) + (res << 7) + buff[i]; return res; } #endif LUALIB_API unsigned int luaL_makeseed (lua_State *L) { UNUSED(L); return luai_makeseed(); } /* ** Use the name with parentheses so that headers can redefine it ** as a macro. */ LUALIB_API lua_State *(luaL_newstate) (void) { lua_State *L = lua_newstate(luaL_alloc, NULL, luaL_makeseed(NULL)); if (l_likely(L)) { lua_atpanic(L, &panic); lua_setwarnf(L, warnfon, L); } return L; } LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) { lua_Number v = lua_version(L); if (sz != LUAL_NUMSIZES) /* check numeric types */ luaL_error(L, "core and library have incompatible numeric types"); else if (v != ver) luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v); } /* ** $Id: lbaselib.c $ ** Basic library ** See Copyright Notice in lua.h */ #define lbaselib_c #define LUA_LIB #include #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" static int luaB_print (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; for (i = 1; i <= n; i++) { /* for each argument */ size_t l; const char *s = luaL_tolstring(L, i, &l); /* convert it to string */ if (i > 1) /* not the first element? */ lua_writestring("\t", 1); /* add a tab before it */ lua_writestring(s, l); /* print it */ lua_pop(L, 1); /* pop result */ } lua_writeline(); return 0; } /* ** Creates a warning with all given arguments. ** Check first for errors; otherwise an error may interrupt ** the composition of a warning, leaving it unfinished. */ static int luaB_warn (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; luaL_checkstring(L, 1); /* at least one argument */ for (i = 2; i <= n; i++) luaL_checkstring(L, i); /* make sure all arguments are strings */ for (i = 1; i < n; i++) /* compose warning */ lua_warning(L, lua_tostring(L, i), 1); lua_warning(L, lua_tostring(L, n), 0); /* close warning */ return 0; } #define SPACECHARS " \f\n\r\t\v" static const char *b_str2int (const char *s, unsigned base, lua_Integer *pn) { lua_Unsigned n = 0; int neg = 0; s += strspn(s, SPACECHARS); /* skip initial spaces */ if (*s == '-') { s++; neg = 1; } /* handle sign */ else if (*s == '+') s++; if (!isalnum(cast_uchar(*s))) /* no digit? */ return NULL; do { unsigned digit = cast_uint(isdigit(cast_uchar(*s)) ? *s - '0' : (toupper(cast_uchar(*s)) - 'A') + 10); if (digit >= base) return NULL; /* invalid numeral */ n = n * base + digit; s++; } while (isalnum(cast_uchar(*s))); s += strspn(s, SPACECHARS); /* skip trailing spaces */ *pn = (lua_Integer)((neg) ? (0u - n) : n); return s; } static int luaB_tonumber (lua_State *L) { if (lua_isnoneornil(L, 2)) { /* standard conversion? */ if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */ lua_settop(L, 1); /* yes; return it */ return 1; } else { size_t l; const char *s = lua_tolstring(L, 1, &l); if (s != NULL && lua_stringtonumber(L, s) == l + 1) return 1; /* successful conversion to number */ /* else not a number */ luaL_checkany(L, 1); /* (but there must be some parameter) */ } } else { size_t l; const char *s; lua_Integer n = 0; /* to avoid warnings */ lua_Integer base = luaL_checkinteger(L, 2); luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */ s = lua_tolstring(L, 1, &l); luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); if (b_str2int(s, cast_uint(base), &n) == s + l) { lua_pushinteger(L, n); return 1; } /* else not a number */ } /* else not a number */ luaL_pushfail(L); /* not a number */ return 1; } static int luaB_error (lua_State *L) { int level = (int)luaL_optinteger(L, 2, 1); lua_settop(L, 1); if (lua_type(L, 1) == LUA_TSTRING && level > 0) { luaL_where(L, level); /* add extra information */ lua_pushvalue(L, 1); lua_concat(L, 2); } return lua_error(L); } static int luaB_getmetatable (lua_State *L) { luaL_checkany(L, 1); if (!lua_getmetatable(L, 1)) { lua_pushnil(L); return 1; /* no metatable */ } luaL_getmetafield(L, 1, "__metatable"); return 1; /* returns either __metatable field (if present) or metatable */ } static int luaB_setmetatable (lua_State *L) { int t = lua_type(L, 2); luaL_checktype(L, 1, LUA_TTABLE); luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table"); if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)) return luaL_error(L, "cannot change a protected metatable"); lua_settop(L, 2); lua_setmetatable(L, 1); return 1; } static int luaB_rawequal (lua_State *L) { luaL_checkany(L, 1); luaL_checkany(L, 2); lua_pushboolean(L, lua_rawequal(L, 1, 2)); return 1; } static int luaB_rawlen (lua_State *L) { int t = lua_type(L, 1); luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, "table or string"); lua_pushinteger(L, l_castU2S(lua_rawlen(L, 1))); return 1; } static int luaB_rawget (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checkany(L, 2); lua_settop(L, 2); lua_rawget(L, 1); return 1; } static int luaB_rawset (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checkany(L, 2); luaL_checkany(L, 3); lua_settop(L, 3); lua_rawset(L, 1); return 1; } static int pushmode (lua_State *L, int oldmode) { if (oldmode == -1) luaL_pushfail(L); /* invalid call to 'lua_gc' */ else lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental" : "generational"); return 1; } /* ** check whether call to 'lua_gc' was valid (not inside a finalizer) */ #define checkvalres(res) { if (res == -1) break; } static int luaB_collectgarbage (lua_State *L) { static const char *const opts[] = {"stop", "restart", "collect", "count", "step", "isrunning", "generational", "incremental", "param", NULL}; static const char optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, LUA_GCCOUNT, LUA_GCSTEP, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC, LUA_GCPARAM}; int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; switch (o) { case LUA_GCCOUNT: { int k = lua_gc(L, o); int b = lua_gc(L, LUA_GCCOUNTB); checkvalres(k); lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024)); return 1; } case LUA_GCSTEP: { lua_Integer n = luaL_optinteger(L, 2, 0); int res = lua_gc(L, o, cast_sizet(n)); checkvalres(res); lua_pushboolean(L, res); return 1; } case LUA_GCISRUNNING: { int res = lua_gc(L, o); checkvalres(res); lua_pushboolean(L, res); return 1; } case LUA_GCGEN: { return pushmode(L, lua_gc(L, o)); } case LUA_GCINC: { return pushmode(L, lua_gc(L, o)); } case LUA_GCPARAM: { static const char *const params[] = { "minormul", "majorminor", "minormajor", "pause", "stepmul", "stepsize", NULL}; static const char pnum[] = { LUA_GCPMINORMUL, LUA_GCPMAJORMINOR, LUA_GCPMINORMAJOR, LUA_GCPPAUSE, LUA_GCPSTEPMUL, LUA_GCPSTEPSIZE}; int p = pnum[luaL_checkoption(L, 2, NULL, params)]; lua_Integer value = luaL_optinteger(L, 3, -1); lua_pushinteger(L, lua_gc(L, o, p, (int)value)); return 1; } default: { int res = lua_gc(L, o); checkvalres(res); lua_pushinteger(L, res); return 1; } } luaL_pushfail(L); /* invalid call (inside a finalizer) */ return 1; } static int luaB_type (lua_State *L) { int t = lua_type(L, 1); luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); lua_pushstring(L, lua_typename(L, t)); return 1; } static int luaB_next (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 2); /* create a 2nd argument if there isn't one */ if (lua_next(L, 1)) return 2; else { lua_pushnil(L); return 1; } } static int pairscont (lua_State *L, int status, lua_KContext k) { (void)L; (void)status; (void)k; /* unused */ return 4; /* __pairs did all the work, just return its results */ } static int luaB_pairs (lua_State *L) { luaL_checkany(L, 1); if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */ lua_pushcfunction(L, luaB_next); /* will return generator and */ lua_pushvalue(L, 1); /* state */ lua_pushnil(L); /* initial value */ lua_pushnil(L); /* to-be-closed object */ } else { lua_pushvalue(L, 1); /* argument 'self' to metamethod */ lua_callk(L, 1, 4, 0, pairscont); /* get 4 values from metamethod */ } return 4; } /* ** Traversal function for 'ipairs' */ static int ipairsaux (lua_State *L) { lua_Integer i = luaL_checkinteger(L, 2); i = luaL_intop(+, i, 1); lua_pushinteger(L, i); return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; } /* ** 'ipairs' function. Returns 'ipairsaux', given "table", 0. ** (The given "table" may not be a table.) */ static int luaB_ipairs (lua_State *L) { luaL_checkany(L, 1); lua_pushcfunction(L, ipairsaux); /* iteration function */ lua_pushvalue(L, 1); /* state */ lua_pushinteger(L, 0); /* initial value */ return 3; } static int load_aux (lua_State *L, int status, int envidx) { if (l_likely(status == LUA_OK)) { if (envidx != 0) { /* 'env' parameter? */ lua_pushvalue(L, envidx); /* environment for loaded function */ if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ lua_pop(L, 1); /* remove 'env' if not used by previous call */ } return 1; } else { /* error (message is on top of the stack) */ luaL_pushfail(L); lua_insert(L, -2); /* put before error message */ return 2; /* return fail plus error message */ } } static const char *getMode (lua_State *L, int idx) { const char *mode = luaL_optstring(L, idx, "bt"); if (strchr(mode, 'B') != NULL) /* Lua code cannot use fixed buffers */ luaL_argerror(L, idx, "invalid mode"); return mode; } static int luaB_loadfile (lua_State *L) { const char *fname = luaL_optstring(L, 1, NULL); const char *mode = getMode(L, 2); int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ int status = luaL_loadfilex(L, fname, mode); return load_aux(L, status, env); } /* ** {====================================================== ** Generic Read function ** ======================================================= */ /* ** reserved slot, above all arguments, to hold a copy of the returned ** string to avoid it being collected while parsed. 'load' has four ** optional arguments (chunk, source name, mode, and environment). */ #define RESERVEDSLOT 5 /* ** Reader for generic 'load' function: 'lua_load' uses the ** stack for internal stuff, so the reader cannot change the ** stack top. Instead, it keeps its resulting string in a ** reserved slot inside the stack. */ static const char *generic_reader (lua_State *L, void *ud, size_t *size) { (void)(ud); /* not used */ luaL_checkstack(L, 2, "too many nested functions"); lua_pushvalue(L, 1); /* get function */ lua_call(L, 0, 1); /* call it */ if (lua_isnil(L, -1)) { lua_pop(L, 1); /* pop result */ *size = 0; return NULL; } else if (l_unlikely(!lua_isstring(L, -1))) luaL_error(L, "reader function must return a string"); lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ return lua_tolstring(L, RESERVEDSLOT, size); } static int luaB_load (lua_State *L) { int status; size_t l; const char *s = lua_tolstring(L, 1, &l); const char *mode = getMode(L, 3); int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ if (s != NULL) { /* loading a string? */ const char *chunkname = luaL_optstring(L, 2, s); status = luaL_loadbufferx(L, s, l, chunkname, mode); } else { /* loading from a reader function */ const char *chunkname = luaL_optstring(L, 2, "=(load)"); luaL_checktype(L, 1, LUA_TFUNCTION); lua_settop(L, RESERVEDSLOT); /* create reserved slot */ status = lua_load(L, generic_reader, NULL, chunkname, mode); } return load_aux(L, status, env); } /* }====================================================== */ static int dofilecont (lua_State *L, int d1, lua_KContext d2) { (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */ return lua_gettop(L) - 1; } static int luaB_dofile (lua_State *L) { const char *fname = luaL_optstring(L, 1, NULL); lua_settop(L, 1); if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK)) return lua_error(L); lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); return dofilecont(L, 0, 0); } static int luaB_assert (lua_State *L) { if (l_likely(lua_toboolean(L, 1))) /* condition is true? */ return lua_gettop(L); /* return all arguments */ else { /* error */ luaL_checkany(L, 1); /* there must be a condition */ lua_remove(L, 1); /* remove it */ lua_pushliteral(L, "assertion failed!"); /* default message */ lua_settop(L, 1); /* leave only message (default if no other one) */ return luaB_error(L); /* call 'error' */ } } static int luaB_select (lua_State *L) { int n = lua_gettop(L); if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { lua_pushinteger(L, n-1); return 1; } else { lua_Integer i = luaL_checkinteger(L, 1); if (i < 0) i = n + i; else if (i > n) i = n; luaL_argcheck(L, 1 <= i, 1, "index out of range"); return n - (int)i; } } /* ** Continuation function for 'pcall' and 'xpcall'. Both functions ** already pushed a 'true' before doing the call, so in case of success ** 'finishpcall' only has to return everything in the stack minus ** 'extra' values (where 'extra' is exactly the number of items to be ** ignored). */ static int finishpcall (lua_State *L, int status, lua_KContext extra) { if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */ lua_pushboolean(L, 0); /* first result (false) */ lua_pushvalue(L, -2); /* error message */ return 2; /* return false, msg */ } else return lua_gettop(L) - (int)extra; /* return all results */ } static int luaB_pcall (lua_State *L) { int status; luaL_checkany(L, 1); lua_pushboolean(L, 1); /* first result if no errors */ lua_insert(L, 1); /* put it in place */ status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall); return finishpcall(L, status, 0); } /* ** Do a protected call with error handling. After 'lua_rotate', the ** stack will have ; so, the function passes ** 2 to 'finishpcall' to skip the 2 first values when returning results. */ static int luaB_xpcall (lua_State *L) { int status; int n = lua_gettop(L); luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */ lua_pushboolean(L, 1); /* first result */ lua_pushvalue(L, 1); /* function */ lua_rotate(L, 3, 2); /* move them below function's arguments */ status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall); return finishpcall(L, status, 2); } static int luaB_tostring (lua_State *L) { luaL_checkany(L, 1); luaL_tolstring(L, 1, NULL); return 1; } static const luaL_Reg base_funcs[] = { {"assert", luaB_assert}, {"collectgarbage", luaB_collectgarbage}, {"dofile", luaB_dofile}, {"error", luaB_error}, {"getmetatable", luaB_getmetatable}, {"ipairs", luaB_ipairs}, {"loadfile", luaB_loadfile}, {"load", luaB_load}, {"next", luaB_next}, {"pairs", luaB_pairs}, {"pcall", luaB_pcall}, {"print", luaB_print}, {"warn", luaB_warn}, {"rawequal", luaB_rawequal}, {"rawlen", luaB_rawlen}, {"rawget", luaB_rawget}, {"rawset", luaB_rawset}, {"select", luaB_select}, {"setmetatable", luaB_setmetatable}, {"tonumber", luaB_tonumber}, {"tostring", luaB_tostring}, {"type", luaB_type}, {"xpcall", luaB_xpcall}, /* placeholders */ {LUA_GNAME, NULL}, {"_VERSION", NULL}, {NULL, NULL} }; LUAMOD_API int luaopen_base (lua_State *L) { /* open lib into global table */ lua_pushglobaltable(L); luaL_setfuncs(L, base_funcs, 0); /* set global _G */ lua_pushvalue(L, -1); lua_setfield(L, -2, LUA_GNAME); /* set global _VERSION */ lua_pushliteral(L, LUA_VERSION); lua_setfield(L, -2, "_VERSION"); return 1; } /* ** $Id: lutf8lib.c $ ** Standard library for UTF-8 manipulation ** See Copyright Notice in lua.h */ #define lutf8lib_c #define LUA_LIB #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" #define MAXUNICODE 0x10FFFFu #define MAXUTF 0x7FFFFFFFu #define MSGInvalid "invalid UTF-8 code" #define iscont(c) (((c) & 0xC0) == 0x80) #define iscontp(p) iscont(*(p)) /* from strlib */ /* translate a relative string position: negative means back from end */ static lua_Integer u_posrelat (lua_Integer pos, size_t len) { if (pos >= 0) return pos; else if (0u - (size_t)pos > len) return 0; else return (lua_Integer)len + pos + 1; } /* ** Decode one UTF-8 sequence, returning NULL if byte sequence is ** invalid. The array 'limits' stores the minimum value for each ** sequence length, to check for overlong representations. Its first ** entry forces an error for non-ASCII bytes with no continuation ** bytes (count == 0). */ static const char *utf8_decode (const char *s, l_uint32 *val, int strict) { static const l_uint32 limits[] = {~(l_uint32)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u}; unsigned int c = (unsigned char)s[0]; l_uint32 res = 0; /* final result */ if (c < 0x80) /* ASCII? */ res = c; else { int count = 0; /* to count number of continuation bytes */ for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */ unsigned int cc = (unsigned char)s[++count]; /* read next byte */ if (!iscont(cc)) /* not a continuation byte? */ return NULL; /* invalid byte sequence */ res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ } res |= ((l_uint32)(c & 0x7F) << (count * 5)); /* add first byte */ if (count > 5 || res > MAXUTF || res < limits[count]) return NULL; /* invalid byte sequence */ s += count; /* skip continuation bytes read */ } if (strict) { /* check for invalid code points; too large or surrogates */ if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu)) return NULL; } if (val) *val = res; return s + 1; /* +1 to include first byte */ } /* ** utf8len(s [, i [, j [, lax]]]) --> number of characters that ** start in the range [i,j], or nil + current position if 's' is not ** well formed in that interval */ static int utflen (lua_State *L) { lua_Integer n = 0; /* counter for the number of characters */ size_t len; /* string length in bytes */ const char *s = luaL_checklstring(L, 1, &len); lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len); int lax = lua_toboolean(L, 4); luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2, "initial position out of bounds"); luaL_argcheck(L, --posj < (lua_Integer)len, 3, "final position out of bounds"); while (posi <= posj) { const char *s1 = utf8_decode(s + posi, NULL, !lax); if (s1 == NULL) { /* conversion error? */ luaL_pushfail(L); /* return fail ... */ lua_pushinteger(L, posi + 1); /* ... and current position */ return 2; } posi = ct_diff2S(s1 - s); n++; } lua_pushinteger(L, n); return 1; } /* ** codepoint(s, [i, [j [, lax]]]) -> returns codepoints for all ** characters that start in the range [i,j] */ static int codepoint (lua_State *L) { size_t len; const char *s = luaL_checklstring(L, 1, &len); lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len); lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len); int lax = lua_toboolean(L, 4); int n; const char *se; luaL_argcheck(L, posi >= 1, 2, "out of bounds"); luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of bounds"); if (posi > pose) return 0; /* empty interval; return no values */ if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */ return luaL_error(L, "string slice too long"); n = (int)(pose - posi) + 1; /* upper bound for number of returns */ luaL_checkstack(L, n, "string slice too long"); n = 0; /* count the number of returns */ se = s + pose; /* string end */ for (s += posi - 1; s < se;) { l_uint32 code; s = utf8_decode(s, &code, !lax); if (s == NULL) return luaL_error(L, MSGInvalid); lua_pushinteger(L, l_castU2S(code)); n++; } return n; } static void pushutfchar (lua_State *L, int arg) { lua_Unsigned code = (lua_Unsigned)luaL_checkinteger(L, arg); luaL_argcheck(L, code <= MAXUTF, arg, "value out of range"); lua_pushfstring(L, "%U", (long)code); } /* ** utfchar(n1, n2, ...) -> char(n1)..char(n2)... */ static int utfchar (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ if (n == 1) /* optimize common case of single char */ pushutfchar(L, 1); else { int i; luaL_Buffer b; luaL_buffinit(L, &b); for (i = 1; i <= n; i++) { pushutfchar(L, i); luaL_addvalue(&b); } luaL_pushresult(&b); } return 1; } /* ** offset(s, n, [i]) -> indices where n-th character counting from ** position 'i' starts and ends; 0 means character at 'i'. */ static int byteoffset (lua_State *L) { size_t len; const char *s = luaL_checklstring(L, 1, &len); lua_Integer n = luaL_checkinteger(L, 2); lua_Integer posi = (n >= 0) ? 1 : cast_st2S(len) + 1; posi = u_posrelat(luaL_optinteger(L, 3, posi), len); luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3, "position out of bounds"); if (n == 0) { /* find beginning of current byte sequence */ while (posi > 0 && iscontp(s + posi)) posi--; } else { if (iscontp(s + posi)) return luaL_error(L, "initial position is a continuation byte"); if (n < 0) { while (n < 0 && posi > 0) { /* move back */ do { /* find beginning of previous character */ posi--; } while (posi > 0 && iscontp(s + posi)); n++; } } else { n--; /* do not move for 1st character */ while (n > 0 && posi < (lua_Integer)len) { do { /* find beginning of next character */ posi++; } while (iscontp(s + posi)); /* (cannot pass final '\0') */ n--; } } } if (n != 0) { /* did not find given character? */ luaL_pushfail(L); return 1; } lua_pushinteger(L, posi + 1); /* initial position */ if ((s[posi] & 0x80) != 0) { /* multi-byte character? */ if (iscont(s[posi])) return luaL_error(L, "initial position is a continuation byte"); while (iscontp(s + posi + 1)) posi++; /* skip to last continuation byte */ } /* else one-byte character: final position is the initial one */ lua_pushinteger(L, posi + 1); /* 'posi' now is the final position */ return 2; } static int iter_aux (lua_State *L, int strict) { size_t len; const char *s = luaL_checklstring(L, 1, &len); lua_Unsigned n = (lua_Unsigned)lua_tointeger(L, 2); if (n < len) { while (iscontp(s + n)) n++; /* go to next character */ } if (n >= len) /* (also handles original 'n' being negative) */ return 0; /* no more codepoints */ else { l_uint32 code; const char *next = utf8_decode(s + n, &code, strict); if (next == NULL || iscontp(next)) return luaL_error(L, MSGInvalid); lua_pushinteger(L, l_castU2S(n + 1)); lua_pushinteger(L, l_castU2S(code)); return 2; } } static int iter_auxstrict (lua_State *L) { return iter_aux(L, 1); } static int iter_auxlax (lua_State *L) { return iter_aux(L, 0); } static int iter_codes (lua_State *L) { int lax = lua_toboolean(L, 2); const char *s = luaL_checkstring(L, 1); luaL_argcheck(L, !iscontp(s), 1, MSGInvalid); lua_pushcfunction(L, lax ? iter_auxlax : iter_auxstrict); lua_pushvalue(L, 1); lua_pushinteger(L, 0); return 3; } /* pattern to match a single UTF-8 character */ #define UTF8PATT "[\0-\x7F\xC2-\xFD][\x80-\xBF]*" static const luaL_Reg funcs[] = { {"offset", byteoffset}, {"codepoint", codepoint}, {"char", utfchar}, {"len", utflen}, {"codes", iter_codes}, /* placeholders */ {"charpattern", NULL}, {NULL, NULL} }; LUAMOD_API int luaopen_utf8 (lua_State *L) { luaL_newlib(L, funcs); lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1); lua_setfield(L, -2, "charpattern"); return 1; } /* ** $Id: lcode.c $ ** Code generator for Lua ** See Copyright Notice in lua.h */ #define lcode_c #define LUA_CORE #include #include #include #include #include "lua.h" /* (note that expressions VJMP also have jumps.) */ #define hasjumps(e) ((e)->t != (e)->f) static int codesJ (FuncState *fs, OpCode o, int sj, int k); /* semantic error */ l_noret luaK_semerror (LexState *ls, const char *fmt, ...) { const char *msg; va_list argp; pushvfstring(ls->L, argp, fmt, msg); ls->t.token = 0; /* remove "near " from final message */ ls->linenumber = ls->lastline; /* back to line of last used token */ luaX_syntaxerror(ls, msg); } /* ** If expression is a numeric constant, fills 'v' with its value ** and returns 1. Otherwise, returns 0. */ static int tonumeral (const expdesc *e, TValue *v) { if (hasjumps(e)) return 0; /* not a numeral */ switch (e->k) { case VKINT: if (v) setivalue(v, e->u.ival); return 1; case VKFLT: if (v) setfltvalue(v, e->u.nval); return 1; default: return 0; } } /* ** Get the constant value from a constant expression */ static TValue *const2val (FuncState *fs, const expdesc *e) { lua_assert(e->k == VCONST); return &fs->ls->dyd->actvar.arr[e->u.info].k; } /* ** If expression is a constant, fills 'v' with its value ** and returns 1. Otherwise, returns 0. */ int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) { if (hasjumps(e)) return 0; /* not a constant */ switch (e->k) { case VFALSE: setbfvalue(v); return 1; case VTRUE: setbtvalue(v); return 1; case VNIL: setnilvalue(v); return 1; case VKSTR: { setsvalue(fs->ls->L, v, e->u.strval); return 1; } case VCONST: { setobj(fs->ls->L, v, const2val(fs, e)); return 1; } default: return tonumeral(e, v); } } /* ** Return the previous instruction of the current code. If there ** may be a jump target between the current instruction and the ** previous one, return an invalid instruction (to avoid wrong ** optimizations). */ static Instruction *previousinstruction (FuncState *fs) { static const Instruction invalidinstruction = ~(Instruction)0; if (fs->pc > fs->lasttarget) return &fs->f->code[fs->pc - 1]; /* previous instruction */ else return cast(Instruction*, &invalidinstruction); } /* ** Create a OP_LOADNIL instruction, but try to optimize: if the previous ** instruction is also OP_LOADNIL and ranges are compatible, adjust ** range of previous instruction instead of emitting a new one. (For ** instance, 'local a; local b' will generate a single opcode.) */ void luaK_nil (FuncState *fs, int from, int n) { int l = from + n - 1; /* last register to set nil */ Instruction *previous = previousinstruction(fs); if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ int pfrom = GETARG_A(*previous); /* get previous range */ int pl = pfrom + GETARG_B(*previous); if ((pfrom <= from && from <= pl + 1) || (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ if (pl > l) l = pl; /* l = max(l, pl) */ SETARG_A(*previous, from); SETARG_B(*previous, l - from); return; } /* else go through */ } luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ } /* ** Gets the destination address of a jump instruction. Used to traverse ** a list of jumps. */ static int getjump (FuncState *fs, int pc) { int offset = GETARG_sJ(fs->f->code[pc]); if (offset == NO_JUMP) /* point to itself represents end of list */ return NO_JUMP; /* end of list */ else return (pc+1)+offset; /* turn offset into absolute position */ } /* ** Fix jump instruction at position 'pc' to jump to 'dest'. ** (Jump addresses are relative in Lua) */ static void fixjump (FuncState *fs, int pc, int dest) { Instruction *jmp = &fs->f->code[pc]; int offset = dest - (pc + 1); lua_assert(dest != NO_JUMP); if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ)) luaX_syntaxerror(fs->ls, "control structure too long"); lua_assert(GET_OPCODE(*jmp) == OP_JMP); SETARG_sJ(*jmp, offset); } /* ** Concatenate jump-list 'l2' into jump-list 'l1' */ void luaK_concat (FuncState *fs, int *l1, int l2) { if (l2 == NO_JUMP) return; /* nothing to concatenate? */ else if (*l1 == NO_JUMP) /* no original list? */ *l1 = l2; /* 'l1' points to 'l2' */ else { int list = *l1; int next; while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ list = next; fixjump(fs, list, l2); /* last element links to 'l2' */ } } /* ** Create a jump instruction and return its position, so its destination ** can be fixed later (with 'fixjump'). */ int luaK_jump (FuncState *fs) { return codesJ(fs, OP_JMP, NO_JUMP, 0); } /* ** Code a 'return' instruction */ void luaK_ret (FuncState *fs, int first, int nret) { OpCode op; switch (nret) { case 0: op = OP_RETURN0; break; case 1: op = OP_RETURN1; break; default: op = OP_RETURN; break; } luaY_checklimit(fs, nret + 1, MAXARG_B, "returns"); luaK_codeABC(fs, op, first, nret + 1, 0); } /* ** Code a "conditional jump", that is, a test or comparison opcode ** followed by a jump. Return jump position. */ static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) { luaK_codeABCk(fs, op, A, B, C, k); return luaK_jump(fs); } /* ** returns current 'pc' and marks it as a jump target (to avoid wrong ** optimizations with consecutive instructions not in the same basic block). */ int luaK_getlabel (FuncState *fs) { fs->lasttarget = fs->pc; return fs->pc; } /* ** Returns the position of the instruction "controlling" a given ** jump (that is, its condition), or the jump itself if it is ** unconditional. */ static Instruction *getjumpcontrol (FuncState *fs, int pc) { Instruction *pi = &fs->f->code[pc]; if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) return pi-1; else return pi; } /* ** Patch destination register for a TESTSET instruction. ** If instruction in position 'node' is not a TESTSET, return 0 ("fails"). ** Otherwise, if 'reg' is not 'NO_REG', set it as the destination ** register. Otherwise, change instruction to a simple 'TEST' (produces ** no register value) */ static int patchtestreg (FuncState *fs, int node, int reg) { Instruction *i = getjumpcontrol(fs, node); if (GET_OPCODE(*i) != OP_TESTSET) return 0; /* cannot patch other instructions */ if (reg != NO_REG && reg != GETARG_B(*i)) SETARG_A(*i, reg); else { /* no register to put value or register already has the value; change instruction to simple test */ *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i)); } return 1; } /* ** Traverse a list of tests ensuring no one produces a value */ static void removevalues (FuncState *fs, int list) { for (; list != NO_JUMP; list = getjump(fs, list)) patchtestreg(fs, list, NO_REG); } /* ** Traverse a list of tests, patching their destination address and ** registers: tests producing values jump to 'vtarget' (and put their ** values in 'reg'), other tests jump to 'dtarget'. */ static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, int dtarget) { while (list != NO_JUMP) { int next = getjump(fs, list); if (patchtestreg(fs, list, reg)) fixjump(fs, list, vtarget); else fixjump(fs, list, dtarget); /* jump to default target */ list = next; } } /* ** Path all jumps in 'list' to jump to 'target'. ** (The assert means that we cannot fix a jump to a forward address ** because we only know addresses once code is generated.) */ void luaK_patchlist (FuncState *fs, int list, int target) { lua_assert(target <= fs->pc); patchlistaux(fs, list, target, NO_REG, target); } void luaK_patchtohere (FuncState *fs, int list) { int hr = luaK_getlabel(fs); /* mark "here" as a jump target */ luaK_patchlist(fs, list, hr); } /* limit for difference between lines in relative line info. */ #define LIMLINEDIFF 0x80 /* ** Save line info for a new instruction. If difference from last line ** does not fit in a byte, of after that many instructions, save a new ** absolute line info; (in that case, the special value 'ABSLINEINFO' ** in 'lineinfo' signals the existence of this absolute information.) ** Otherwise, store the difference from last line in 'lineinfo'. */ static void savelineinfo (FuncState *fs, Proto *f, int line) { int linedif = line - fs->previousline; int pc = fs->pc - 1; /* last instruction coded */ if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) { luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo, f->sizeabslineinfo, AbsLineInfo, INT_MAX, "lines"); f->abslineinfo[fs->nabslineinfo].pc = pc; f->abslineinfo[fs->nabslineinfo++].line = line; linedif = ABSLINEINFO; /* signal that there is absolute information */ fs->iwthabs = 1; /* restart counter */ } luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte, INT_MAX, "opcodes"); f->lineinfo[pc] = cast(ls_byte, linedif); fs->previousline = line; /* last line saved */ } /* ** Remove line information from the last instruction. ** If line information for that instruction is absolute, set 'iwthabs' ** above its max to force the new (replacing) instruction to have ** absolute line info, too. */ static void removelastlineinfo (FuncState *fs) { Proto *f = fs->f; int pc = fs->pc - 1; /* last instruction coded */ if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */ fs->previousline -= f->lineinfo[pc]; /* correct last line saved */ fs->iwthabs--; /* undo previous increment */ } else { /* absolute line information */ lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc); fs->nabslineinfo--; /* remove it */ fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */ } } /* ** Remove the last instruction created, correcting line information ** accordingly. */ static void removelastinstruction (FuncState *fs) { removelastlineinfo(fs); fs->pc--; } /* ** Emit instruction 'i', checking for array sizes and saving also its ** line information. Return 'i' position. */ int luaK_code (FuncState *fs, Instruction i) { Proto *f = fs->f; /* put new instruction in code array */ luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, INT_MAX, "opcodes"); f->code[fs->pc++] = i; savelineinfo(fs, f, fs->ls->lastline); return fs->pc - 1; /* index of new instruction */ } /* ** Format and emit an 'iABC' instruction. (Assertions check consistency ** of parameters versus opcode.) */ int luaK_codeABCk (FuncState *fs, OpCode o, int A, int B, int C, int k) { lua_assert(getOpMode(o) == iABC); lua_assert(A <= MAXARG_A && B <= MAXARG_B && C <= MAXARG_C && (k & ~1) == 0); return luaK_code(fs, CREATE_ABCk(o, A, B, C, k)); } int luaK_codevABCk (FuncState *fs, OpCode o, int A, int B, int C, int k) { lua_assert(getOpMode(o) == ivABC); lua_assert(A <= MAXARG_A && B <= MAXARG_vB && C <= MAXARG_vC && (k & ~1) == 0); return luaK_code(fs, CREATE_vABCk(o, A, B, C, k)); } /* ** Format and emit an 'iABx' instruction. */ int luaK_codeABx (FuncState *fs, OpCode o, int A, int Bc) { lua_assert(getOpMode(o) == iABx); lua_assert(A <= MAXARG_A && Bc <= MAXARG_Bx); return luaK_code(fs, CREATE_ABx(o, A, Bc)); } /* ** Format and emit an 'iAsBx' instruction. */ static int codeAsBx (FuncState *fs, OpCode o, int A, int Bc) { int b = Bc + OFFSET_sBx; lua_assert(getOpMode(o) == iAsBx); lua_assert(A <= MAXARG_A && b <= MAXARG_Bx); return luaK_code(fs, CREATE_ABx(o, A, b)); } /* ** Format and emit an 'isJ' instruction. */ static int codesJ (FuncState *fs, OpCode o, int sj, int k) { int j = sj + OFFSET_sJ; lua_assert(getOpMode(o) == isJ); lua_assert(j <= MAXARG_sJ && (k & ~1) == 0); return luaK_code(fs, CREATE_sJ(o, j, k)); } /* ** Emit an "extra argument" instruction (format 'iAx') */ static int codeextraarg (FuncState *fs, int A) { lua_assert(A <= MAXARG_Ax); return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, A)); } /* ** Emit a "load constant" instruction, using either 'OP_LOADK' ** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' ** instruction with "extra argument". */ static int luaK_codek (FuncState *fs, int reg, int k) { if (k <= MAXARG_Bx) return luaK_codeABx(fs, OP_LOADK, reg, k); else { int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); codeextraarg(fs, k); return p; } } /* ** Check register-stack level, keeping track of its maximum size ** in field 'maxstacksize' */ void luaK_checkstack (FuncState *fs, int n) { int newstack = fs->freereg + n; if (newstack > fs->f->maxstacksize) { luaY_checklimit(fs, newstack, MAX_FSTACK, "registers"); fs->f->maxstacksize = cast_byte(newstack); } } /* ** Reserve 'n' registers in register stack */ void luaK_reserveregs (FuncState *fs, int n) { luaK_checkstack(fs, n); fs->freereg = cast_byte(fs->freereg + n); } /* ** Free register 'reg', if it is neither a constant index nor ** a local variable. ) */ static void freereg (FuncState *fs, int reg) { if (reg >= luaY_nvarstack(fs)) { fs->freereg--; lua_assert(reg == fs->freereg); } } /* ** Free two registers in proper order */ static void freeregs (FuncState *fs, int r1, int r2) { if (r1 > r2) { freereg(fs, r1); freereg(fs, r2); } else { freereg(fs, r2); freereg(fs, r1); } } /* ** Free register used by expression 'e' (if any) */ static void freeexp (FuncState *fs, expdesc *e) { if (e->k == VNONRELOC) freereg(fs, e->u.info); } /* ** Free registers used by expressions 'e1' and 'e2' (if any) in proper ** order. */ static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; freeregs(fs, r1, r2); } /* ** Add constant 'v' to prototype's list of constants (field 'k'). */ static int addk (FuncState *fs, Proto *f, TValue *v) { lua_State *L = fs->ls->L; int oldsize = f->sizek; int k = fs->nk; luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); setobj(L, &f->k[k], v); fs->nk++; luaC_barrier(L, f, v); return k; } /* ** Use scanner's table to cache position of constants in constant list ** and try to reuse constants. Because some values should not be used ** as keys (nil cannot be a key, integer keys can collapse with float ** keys), the caller must provide a useful 'key' for indexing the cache. */ static int k2proto (FuncState *fs, TValue *key, TValue *v) { TValue val; Proto *f = fs->f; int tag = luaH_get(fs->kcache, key, &val); /* query scanner table */ if (!tagisempty(tag)) { /* is there an index there? */ int k = cast_int(ivalue(&val)); /* collisions can happen only for float keys */ lua_assert(ttisfloat(key) || luaV_rawequalobj(&f->k[k], v)); return k; /* reuse index */ } else { /* constant not found; create a new entry */ int k = addk(fs, f, v); /* cache it for reuse; numerical value does not need GC barrier; table is not a metatable, so it does not need to invalidate cache */ setivalue(&val, k); luaH_set(fs->ls->L, fs->kcache, key, &val); return k; } } /* ** Add a string to list of constants and return its index. */ static int stringK (FuncState *fs, TString *s) { TValue o; setsvalue(fs->ls->L, &o, s); return k2proto(fs, &o, &o); /* use string itself as key */ } /* ** Add an integer to list of constants and return its index. */ static int luaK_intK (FuncState *fs, lua_Integer n) { TValue o; setivalue(&o, n); return k2proto(fs, &o, &o); /* use integer itself as key */ } /* ** Add a float to list of constants and return its index. Floats ** with integral values need a different key, to avoid collision ** with actual integers. To that end, we add to the number its smaller ** power-of-two fraction that is still significant in its scale. ** (For doubles, the fraction would be 2^-52). ** This method is not bulletproof: different numbers may generate the ** same key (e.g., very large numbers will overflow to 'inf') and for ** floats larger than 2^53 the result is still an integer. For those ** cases, just generate a new entry. At worst, this only wastes an entry ** with a duplicate. */ static int luaK_numberK (FuncState *fs, lua_Number r) { TValue o, kv; setfltvalue(&o, r); /* value as a TValue */ if (r == 0) { /* handle zero as a special case */ setpvalue(&kv, fs); /* use FuncState as index */ return k2proto(fs, &kv, &o); /* cannot collide */ } else { const int nbm = l_floatatt(MANT_DIG); const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1); const lua_Number k = r * (1 + q); /* key */ lua_Integer ik; setfltvalue(&kv, k); /* key as a TValue */ if (!luaV_flttointeger(k, &ik, F2Ieq)) { /* not an integer value? */ int n = k2proto(fs, &kv, &o); /* use key */ if (luaV_rawequalobj(&fs->f->k[n], &o)) /* correct value? */ return n; } /* else, either key is still an integer or there was a collision; anyway, do not try to reuse constant; instead, create a new one */ return addk(fs, fs->f, &o); } } /* ** Add a false to list of constants and return its index. */ static int boolF (FuncState *fs) { TValue o; setbfvalue(&o); return k2proto(fs, &o, &o); /* use boolean itself as key */ } /* ** Add a true to list of constants and return its index. */ static int boolT (FuncState *fs) { TValue o; setbtvalue(&o); return k2proto(fs, &o, &o); /* use boolean itself as key */ } /* ** Add nil to list of constants and return its index. */ static int nilK (FuncState *fs) { TValue k, v; setnilvalue(&v); /* cannot use nil as key; instead use table itself */ sethvalue(fs->ls->L, &k, fs->kcache); return k2proto(fs, &k, &v); } /* ** Check whether 'i' can be stored in an 'sC' operand. Equivalent to ** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of ** overflows in the hidden addition inside 'int2sC'. */ static int fitsC (lua_Integer i) { return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C)); } /* ** Check whether 'i' can be stored in an 'sBx' operand. */ static int fitsBx (lua_Integer i) { return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx); } void luaK_int (FuncState *fs, int reg, lua_Integer i) { if (fitsBx(i)) codeAsBx(fs, OP_LOADI, reg, cast_int(i)); else luaK_codek(fs, reg, luaK_intK(fs, i)); } static void luaK_float (FuncState *fs, int reg, lua_Number f) { lua_Integer fi; if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi)) codeAsBx(fs, OP_LOADF, reg, cast_int(fi)); else luaK_codek(fs, reg, luaK_numberK(fs, f)); } /* ** Get the value of 'var' in a register and generate an opcode to check ** whether that register is nil. 'k' is the index of the variable name ** in the list of constants. If its value cannot be encoded in Bx, a 0 ** will use '?' for the name. */ void luaK_codecheckglobal (FuncState *fs, expdesc *var, int k, int line) { luaK_exp2anyreg(fs, var); luaK_fixline(fs, line); k = (k >= MAXARG_Bx) ? 0 : k + 1; luaK_codeABx(fs, OP_ERRNNIL, var->u.info, k); luaK_fixline(fs, line); freeexp(fs, var); } /* ** Convert a constant in 'v' into an expression description 'e' */ static void const2exp (TValue *v, expdesc *e) { switch (ttypetag(v)) { case LUA_VNUMINT: e->k = VKINT; e->u.ival = ivalue(v); break; case LUA_VNUMFLT: e->k = VKFLT; e->u.nval = fltvalue(v); break; case LUA_VFALSE: e->k = VFALSE; break; case LUA_VTRUE: e->k = VTRUE; break; case LUA_VNIL: e->k = VNIL; break; case LUA_VSHRSTR: case LUA_VLNGSTR: e->k = VKSTR; e->u.strval = tsvalue(v); break; default: lua_assert(0); } } /* ** Fix an expression to return the number of results 'nresults'. ** 'e' must be a multi-ret expression (function call or vararg). */ void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { Instruction *pc = &getinstruction(fs, e); luaY_checklimit(fs, nresults + 1, MAXARG_C, "multiple results"); if (e->k == VCALL) /* expression is an open function call? */ SETARG_C(*pc, nresults + 1); else { lua_assert(e->k == VVARARG); SETARG_C(*pc, nresults + 1); SETARG_A(*pc, fs->freereg); luaK_reserveregs(fs, 1); } } /* ** Convert a VKSTR to a VK */ static int str2K (FuncState *fs, expdesc *e) { lua_assert(e->k == VKSTR); e->u.info = stringK(fs, e->u.strval); e->k = VK; return e->u.info; } /* ** Fix an expression to return one result. ** If expression is not a multi-ret expression (function call or ** vararg), it already returns one result, so nothing needs to be done. ** Function calls become VNONRELOC expressions (as its result comes ** fixed in the base register of the call), while vararg expressions ** become VRELOC (as OP_VARARG puts its results where it wants). ** (Calls are created returning one result, so that does not need ** to be fixed.) */ void luaK_setoneret (FuncState *fs, expdesc *e) { if (e->k == VCALL) { /* expression is an open function call? */ /* already returns 1 value */ lua_assert(GETARG_C(getinstruction(fs, e)) == 2); e->k = VNONRELOC; /* result has fixed position */ e->u.info = GETARG_A(getinstruction(fs, e)); } else if (e->k == VVARARG) { SETARG_C(getinstruction(fs, e), 2); e->k = VRELOC; /* can relocate its simple result */ } } /* ** Change a vararg parameter into a regular local variable */ void luaK_vapar2local (FuncState *fs, expdesc *var) { needvatab(fs->f); /* function will need a vararg table */ /* now a vararg parameter is equivalent to a regular local variable */ var->k = VLOCAL; } /* ** Ensure that expression 'e' is not a variable (nor a ). ** (Expression still may have jump lists.) */ void luaK_dischargevars (FuncState *fs, expdesc *e) { switch (e->k) { case VCONST: { const2exp(const2val(fs, e), e); break; } case VVARGVAR: { luaK_vapar2local(fs, e); /* turn it into a local variable */ } /* FALLTHROUGH */ case VLOCAL: { /* already in a register */ int temp = e->u.var.ridx; e->u.info = temp; /* (can't do a direct assignment; values overlap) */ e->k = VNONRELOC; /* becomes a non-relocatable value */ break; } case VUPVAL: { /* move value to some (pending) register */ e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); e->k = VRELOC; break; } case VINDEXUP: { e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VINDEXI: { freereg(fs, e->u.ind.t); e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VINDEXSTR: { freereg(fs, e->u.ind.t); e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VINDEXED: { freeregs(fs, e->u.ind.t, e->u.ind.idx); e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VVARGIND: { freeregs(fs, e->u.ind.t, e->u.ind.idx); e->u.info = luaK_codeABC(fs, OP_GETVARG, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOC; break; } case VVARARG: case VCALL: { luaK_setoneret(fs, e); break; } default: break; /* there is one value available (somewhere) */ } } /* ** Ensure expression value is in register 'reg', making 'e' a ** non-relocatable expression. ** (Expression still may have jump lists.) */ static void discharge2reg (FuncState *fs, expdesc *e, int reg) { luaK_dischargevars(fs, e); switch (e->k) { case VNIL: { luaK_nil(fs, reg, 1); break; } case VFALSE: { luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0); break; } case VTRUE: { luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0); break; } case VKSTR: { str2K(fs, e); } /* FALLTHROUGH */ case VK: { luaK_codek(fs, reg, e->u.info); break; } case VKFLT: { luaK_float(fs, reg, e->u.nval); break; } case VKINT: { luaK_int(fs, reg, e->u.ival); break; } case VRELOC: { Instruction *pc = &getinstruction(fs, e); SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ break; } case VNONRELOC: { if (reg != e->u.info) luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); break; } default: { lua_assert(e->k == VJMP); return; /* nothing to do... */ } } e->u.info = reg; e->k = VNONRELOC; } /* ** Ensure expression value is in a register, making 'e' a ** non-relocatable expression. ** (Expression still may have jump lists.) */ static void discharge2anyreg (FuncState *fs, expdesc *e) { if (e->k != VNONRELOC) { /* no fixed register yet? */ luaK_reserveregs(fs, 1); /* get a register */ discharge2reg(fs, e, fs->freereg-1); /* put value there */ } } static int code_loadbool (FuncState *fs, int A, OpCode op) { luaK_getlabel(fs); /* those instructions may be jump targets */ return luaK_codeABC(fs, op, A, 0, 0); } /* ** check whether list has any jump that do not produce a value ** or produce an inverted value */ static int need_value (FuncState *fs, int list) { for (; list != NO_JUMP; list = getjump(fs, list)) { Instruction i = *getjumpcontrol(fs, list); if (GET_OPCODE(i) != OP_TESTSET) return 1; } return 0; /* not found */ } /* ** Ensures final expression result (which includes results from its ** jump lists) is in register 'reg'. ** If expression has jumps, need to patch these jumps either to ** its final position or to "load" instructions (for those tests ** that do not produce values). */ static void exp2reg (FuncState *fs, expdesc *e, int reg) { discharge2reg(fs, e, reg); if (e->k == VJMP) /* expression itself is a test? */ luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ if (hasjumps(e)) { int final; /* position after whole expression */ int p_f = NO_JUMP; /* position of an eventual LOAD false */ int p_t = NO_JUMP; /* position of an eventual LOAD true */ if (need_value(fs, e->t) || need_value(fs, e->f)) { int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */ p_t = code_loadbool(fs, reg, OP_LOADTRUE); /* jump around these booleans if 'e' is not a test */ luaK_patchtohere(fs, fj); } final = luaK_getlabel(fs); patchlistaux(fs, e->f, final, reg, p_f); patchlistaux(fs, e->t, final, reg, p_t); } e->f = e->t = NO_JUMP; e->u.info = reg; e->k = VNONRELOC; } /* ** Ensures final expression result is in next available register. */ void luaK_exp2nextreg (FuncState *fs, expdesc *e) { luaK_dischargevars(fs, e); freeexp(fs, e); luaK_reserveregs(fs, 1); exp2reg(fs, e, fs->freereg - 1); } /* ** Ensures final expression result is in some (any) register ** and return that register. */ int luaK_exp2anyreg (FuncState *fs, expdesc *e) { luaK_dischargevars(fs, e); if (e->k == VNONRELOC) { /* expression already has a register? */ if (!hasjumps(e)) /* no jumps? */ return e->u.info; /* result is already in a register */ if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */ exp2reg(fs, e, e->u.info); /* put final result in it */ return e->u.info; } /* else expression has jumps and cannot change its register to hold the jump values, because it is a local variable. Go through to the default case. */ } luaK_exp2nextreg(fs, e); /* default: use next available register */ return e->u.info; } /* ** Ensures final expression result is either in a register, ** in an upvalue, or it is the vararg parameter. */ void luaK_exp2anyregup (FuncState *fs, expdesc *e) { if ((e->k != VUPVAL && e->k != VVARGVAR) || hasjumps(e)) luaK_exp2anyreg(fs, e); } /* ** Ensures final expression result is either in a register ** or it is a constant. */ void luaK_exp2val (FuncState *fs, expdesc *e) { if (e->k == VJMP || hasjumps(e)) luaK_exp2anyreg(fs, e); else luaK_dischargevars(fs, e); } /* ** Try to make 'e' a K expression with an index in the range of R/K ** indices. Return true iff succeeded. */ static int luaK_exp2K (FuncState *fs, expdesc *e) { if (!hasjumps(e)) { int info; switch (e->k) { /* move constants to 'k' */ case VTRUE: info = boolT(fs); break; case VFALSE: info = boolF(fs); break; case VNIL: info = nilK(fs); break; case VKINT: info = luaK_intK(fs, e->u.ival); break; case VKFLT: info = luaK_numberK(fs, e->u.nval); break; case VKSTR: info = stringK(fs, e->u.strval); break; case VK: info = e->u.info; break; default: return 0; /* not a constant */ } if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */ e->k = VK; /* make expression a 'K' expression */ e->u.info = info; return 1; } } /* else, expression doesn't fit; leave it unchanged */ return 0; } /* ** Ensures final expression result is in a valid R/K index ** (that is, it is either in a register or in 'k' with an index ** in the range of R/K indices). ** Returns 1 iff expression is K. */ static int exp2RK (FuncState *fs, expdesc *e) { if (luaK_exp2K(fs, e)) return 1; else { /* not a constant in the right range: put it in a register */ luaK_exp2anyreg(fs, e); return 0; } } static void codeABRK (FuncState *fs, OpCode o, int A, int B, expdesc *ec) { int k = exp2RK(fs, ec); luaK_codeABCk(fs, o, A, B, ec->u.info, k); } /* ** Generate code to store result of expression 'ex' into variable 'var'. */ void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { switch (var->k) { case VLOCAL: { freeexp(fs, ex); exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */ return; } case VUPVAL: { int e = luaK_exp2anyreg(fs, ex); luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); break; } case VINDEXUP: { codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex); break; } case VINDEXI: { codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex); break; } case VINDEXSTR: { codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex); break; } case VVARGIND: { needvatab(fs->f); /* function will need a vararg table */ /* now, assignment is to a regular table */ } /* FALLTHROUGH */ case VINDEXED: { codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex); break; } default: lua_assert(0); /* invalid var kind to store */ } freeexp(fs, ex); } /* ** Negate condition 'e' (where 'e' is a comparison). */ static void negatecondition (FuncState *fs, expdesc *e) { Instruction *pc = getjumpcontrol(fs, e->u.info); lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && GET_OPCODE(*pc) != OP_TEST); SETARG_k(*pc, (GETARG_k(*pc) ^ 1)); } /* ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' ** is true, code will jump if 'e' is true.) Return jump position. ** Optimize when 'e' is 'not' something, inverting the condition ** and removing the 'not'. */ static int jumponcond (FuncState *fs, expdesc *e, int cond) { if (e->k == VRELOC) { Instruction ie = getinstruction(fs, e); if (GET_OPCODE(ie) == OP_NOT) { removelastinstruction(fs); /* remove previous OP_NOT */ return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond); } /* else go through */ } discharge2anyreg(fs, e); freeexp(fs, e); return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond); } /* ** Emit code to go through if 'e' is true, jump otherwise. */ void luaK_goiftrue (FuncState *fs, expdesc *e) { int pc; /* pc of new jump */ luaK_dischargevars(fs, e); switch (e->k) { case VJMP: { /* condition? */ negatecondition(fs, e); /* jump when it is false */ pc = e->u.info; /* save jump position */ break; } case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { pc = NO_JUMP; /* always true; do nothing */ break; } default: { pc = jumponcond(fs, e, 0); /* jump when false */ break; } } luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ e->t = NO_JUMP; } /* ** Emit code to go through if 'e' is false, jump otherwise. */ static void luaK_goiffalse (FuncState *fs, expdesc *e) { int pc; /* pc of new jump */ luaK_dischargevars(fs, e); switch (e->k) { case VJMP: { pc = e->u.info; /* already jump if true */ break; } case VNIL: case VFALSE: { pc = NO_JUMP; /* always false; do nothing */ break; } default: { pc = jumponcond(fs, e, 1); /* jump if true */ break; } } luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ e->f = NO_JUMP; } /* ** Code 'not e', doing constant folding. */ static void codenot (FuncState *fs, expdesc *e) { switch (e->k) { case VNIL: case VFALSE: { e->k = VTRUE; /* true == not nil == not false */ break; } case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: { e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */ break; } case VJMP: { negatecondition(fs, e); break; } case VRELOC: case VNONRELOC: { discharge2anyreg(fs, e); freeexp(fs, e); e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); e->k = VRELOC; break; } default: lua_assert(0); /* cannot happen */ } /* interchange true and false lists */ { int temp = e->f; e->f = e->t; e->t = temp; } removevalues(fs, e->f); /* values are useless when negated */ removevalues(fs, e->t); } /* ** Check whether expression 'e' is a short literal string */ static int isKstr (FuncState *fs, expdesc *e) { return (e->k == VK && !hasjumps(e) && e->u.info <= MAXINDEXRK && ttisshrstring(&fs->f->k[e->u.info])); } /* ** Check whether expression 'e' is a literal integer. */ static int isKint (expdesc *e) { return (e->k == VKINT && !hasjumps(e)); } /* ** Check whether expression 'e' is a literal integer in ** proper range to fit in register C */ static int isCint (expdesc *e) { return isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C)); } /* ** Check whether expression 'e' is a literal integer in ** proper range to fit in register sC */ static int isSCint (expdesc *e) { return isKint(e) && fitsC(e->u.ival); } /* ** Check whether expression 'e' is a literal integer or float in ** proper range to fit in a register (sB or sC). */ static int isSCnumber (expdesc *e, int *pi, int *isfloat) { lua_Integer i; if (e->k == VKINT) i = e->u.ival; else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq)) *isfloat = 1; else return 0; /* not a number */ if (!hasjumps(e) && fitsC(i)) { *pi = int2sC(cast_int(i)); return 1; } else return 0; } /* ** Emit SELF instruction or equivalent: the code will convert ** expression 'e' into 'e.key(e,'. */ void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { int ereg, base; luaK_exp2anyreg(fs, e); ereg = e->u.info; /* register where 'e' (the receiver) was placed */ freeexp(fs, e); base = e->u.info = fs->freereg; /* base register for op_self */ e->k = VNONRELOC; /* self expression has a fixed register */ luaK_reserveregs(fs, 2); /* method and 'self' produced by op_self */ lua_assert(key->k == VKSTR); /* is method name a short string in a valid K index? */ if (strisshr(key->u.strval) && luaK_exp2K(fs, key)) { /* can use 'self' opcode */ luaK_codeABCk(fs, OP_SELF, base, ereg, key->u.info, 0); } else { /* cannot use 'self' opcode; use move+gettable */ luaK_exp2anyreg(fs, key); /* put method name in a register */ luaK_codeABC(fs, OP_MOVE, base + 1, ereg, 0); /* copy self to base+1 */ luaK_codeABC(fs, OP_GETTABLE, base, ereg, key->u.info); /* get method */ } freeexp(fs, key); } /* auxiliary function to define indexing expressions */ static void fillidxk (expdesc *t, int idx, expkind k) { t->u.ind.idx = cast_byte(idx); t->k = k; } /* ** Create expression 't[k]'. 't' must have its final result already in a ** register or upvalue. Upvalues can only be indexed by literal strings. ** Keys can be literal strings in the constant table or arbitrary ** values in registers. */ void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { int keystr = -1; if (k->k == VKSTR) keystr = str2K(fs, k); lua_assert(!hasjumps(t) && (t->k == VLOCAL || t->k == VVARGVAR || t->k == VNONRELOC || t->k == VUPVAL)); if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */ luaK_exp2anyreg(fs, t); /* put it in a register */ if (t->k == VUPVAL) { lu_byte temp = cast_byte(t->u.info); /* upvalue index */ t->u.ind.t = temp; /* (can't do a direct assignment; values overlap) */ lua_assert(isKstr(fs, k)); fillidxk(t, k->u.info, VINDEXUP); /* literal short string */ } else if (t->k == VVARGVAR) { /* indexing the vararg parameter? */ int kreg = luaK_exp2anyreg(fs, k); /* put key in some register */ lu_byte vreg = cast_byte(t->u.var.ridx); /* register with vararg param. */ lua_assert(vreg == fs->f->numparams); t->u.ind.t = vreg; /* (avoid a direct assignment; values may overlap) */ fillidxk(t, kreg, VVARGIND); /* 't' represents 'vararg[k]' */ } else { /* register index of the table */ t->u.ind.t = cast_byte((t->k == VLOCAL) ? t->u.var.ridx: t->u.info); if (isKstr(fs, k)) fillidxk(t, k->u.info, VINDEXSTR); /* literal short string */ else if (isCint(k)) /* int. constant in proper range? */ fillidxk(t, cast_int(k->u.ival), VINDEXI); else fillidxk(t, luaK_exp2anyreg(fs, k), VINDEXED); /* register */ } t->u.ind.keystr = keystr; /* string index in 'k' */ t->u.ind.ro = 0; /* by default, not read-only */ } /* ** Return false if folding can raise an error. ** Bitwise operations need operands convertible to integers; division ** operations cannot have 0 as divisor. */ static int validop (int op, TValue *v1, TValue *v2) { switch (op) { case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ lua_Integer i; return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) && luaV_tointegerns(v2, &i, LUA_FLOORN2I)); } case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ return (nvalue(v2) != 0); default: return 1; /* everything else is valid */ } } /* ** Try to "constant-fold" an operation; return 1 iff successful. ** (In this case, 'e1' has the final result.) */ static int constfolding (FuncState *fs, int op, expdesc *e1, const expdesc *e2) { TValue v1, v2, res; if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) return 0; /* non-numeric operands or not safe to fold */ luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ if (ttisinteger(&res)) { e1->k = VKINT; e1->u.ival = ivalue(&res); } else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ lua_Number n = fltvalue(&res); if (luai_numisnan(n) || n == 0) return 0; e1->k = VKFLT; e1->u.nval = n; } return 1; } /* ** Convert a BinOpr to an OpCode (ORDER OPR - ORDER OP) */ l_sinline OpCode binopr2op (BinOpr opr, BinOpr baser, OpCode base) { lua_assert(baser <= opr && ((baser == OPR_ADD && opr <= OPR_SHR) || (baser == OPR_LT && opr <= OPR_LE))); return cast(OpCode, (cast_int(opr) - cast_int(baser)) + cast_int(base)); } /* ** Convert a UnOpr to an OpCode (ORDER OPR - ORDER OP) */ l_sinline OpCode unopr2op (UnOpr opr) { return cast(OpCode, (cast_int(opr) - cast_int(OPR_MINUS)) + cast_int(OP_UNM)); } /* ** Convert a BinOpr to a tag method (ORDER OPR - ORDER TM) */ l_sinline TMS binopr2TM (BinOpr opr) { lua_assert(OPR_ADD <= opr && opr <= OPR_SHR); return cast(TMS, (cast_int(opr) - cast_int(OPR_ADD)) + cast_int(TM_ADD)); } /* ** Emit code for unary expressions that "produce values" ** (everything but 'not'). ** Expression to produce final result will be encoded in 'e'. */ static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ freeexp(fs, e); e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ e->k = VRELOC; /* all those operations are relocatable */ luaK_fixline(fs, line); } /* ** Emit code for binary expressions that "produce values" ** (everything but logical operators 'and'/'or' and comparison ** operators). ** Expression to produce final result will be encoded in 'e1'. */ static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2, OpCode op, int v2, int flip, int line, OpCode mmop, TMS event) { int v1 = luaK_exp2anyreg(fs, e1); int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0); freeexps(fs, e1, e2); e1->u.info = pc; e1->k = VRELOC; /* all those operations are relocatable */ luaK_fixline(fs, line); luaK_codeABCk(fs, mmop, v1, v2, cast_int(event), flip); /* metamethod */ luaK_fixline(fs, line); } /* ** Emit code for binary expressions that "produce values" over ** two registers. */ static void codebinexpval (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int line) { OpCode op = binopr2op(opr, OPR_ADD, OP_ADD); int v2 = luaK_exp2anyreg(fs, e2); /* make sure 'e2' is in a register */ /* 'e1' must be already in a register or it is a constant */ lua_assert((VNIL <= e1->k && e1->k <= VKSTR) || e1->k == VNONRELOC || e1->k == VRELOC); lua_assert(OP_ADD <= op && op <= OP_SHR); finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN, binopr2TM(opr)); } /* ** Code binary operators with immediate operands. */ static void codebini (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2, int flip, int line, TMS event) { int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */ lua_assert(e2->k == VKINT); finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event); } /* ** Code binary operators with K operand. */ static void codebinK (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int flip, int line) { TMS event = binopr2TM(opr); int v2 = e2->u.info; /* K index */ OpCode op = binopr2op(opr, OPR_ADD, OP_ADDK); finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event); } /* Try to code a binary operator negating its second operand. ** For the metamethod, 2nd operand must keep its original value. */ static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2, OpCode op, int line, TMS event) { if (!isKint(e2)) return 0; /* not an integer constant */ else { lua_Integer i2 = e2->u.ival; if (!(fitsC(i2) && fitsC(-i2))) return 0; /* not in the proper range */ else { /* operating a small integer constant */ int v2 = cast_int(i2); finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event); /* correct metamethod argument */ SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2)); return 1; /* successfully coded */ } } } static void swapexps (expdesc *e1, expdesc *e2) { expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */ } /* ** Code binary operators with no constant operand. */ static void codebinNoK (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int flip, int line) { if (flip) swapexps(e1, e2); /* back to original order */ codebinexpval(fs, opr, e1, e2, line); /* use standard operators */ } /* ** Code arithmetic operators ('+', '-', ...). If second operand is a ** constant in the proper range, use variant opcodes with K operands. */ static void codearith (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int flip, int line) { if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) /* K operand? */ codebinK(fs, opr, e1, e2, flip, line); else /* 'e2' is neither an immediate nor a K operand */ codebinNoK(fs, opr, e1, e2, flip, line); } /* ** Code commutative operators ('+', '*'). If first operand is a ** numeric constant, change order of operands to try to use an ** immediate or K operator. */ static void codecommutative (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2, int line) { int flip = 0; if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */ swapexps(e1, e2); /* change order */ flip = 1; } if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */ codebini(fs, OP_ADDI, e1, e2, flip, line, TM_ADD); else codearith(fs, op, e1, e2, flip, line); } /* ** Code bitwise operations; they are all commutative, so the function ** tries to put an integer constant as the 2nd operand (a K operand). */ static void codebitwise (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int line) { int flip = 0; if (e1->k == VKINT) { swapexps(e1, e2); /* 'e2' will be the constant operand */ flip = 1; } if (e2->k == VKINT && luaK_exp2K(fs, e2)) /* K operand? */ codebinK(fs, opr, e1, e2, flip, line); else /* no constants */ codebinNoK(fs, opr, e1, e2, flip, line); } /* ** Emit code for order comparisons. When using an immediate operand, ** 'isfloat' tells whether the original value was a float. */ static void codeorder (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { int r1, r2; int im; int isfloat = 0; OpCode op; if (isSCnumber(e2, &im, &isfloat)) { /* use immediate operand */ r1 = luaK_exp2anyreg(fs, e1); r2 = im; op = binopr2op(opr, OPR_LT, OP_LTI); } else if (isSCnumber(e1, &im, &isfloat)) { /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */ r1 = luaK_exp2anyreg(fs, e2); r2 = im; op = binopr2op(opr, OPR_LT, OP_GTI); } else { /* regular case, compare two registers */ r1 = luaK_exp2anyreg(fs, e1); r2 = luaK_exp2anyreg(fs, e2); op = binopr2op(opr, OPR_LT, OP_LT); } freeexps(fs, e1, e2); e1->u.info = condjump(fs, op, r1, r2, isfloat, 1); e1->k = VJMP; } /* ** Emit code for equality comparisons ('==', '~='). ** 'e1' was already put as RK by 'luaK_infix'. */ static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { int r1, r2; int im; int isfloat = 0; /* not needed here, but kept for symmetry */ OpCode op; if (e1->k != VNONRELOC) { lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT); swapexps(e1, e2); } r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */ if (isSCnumber(e2, &im, &isfloat)) { op = OP_EQI; r2 = im; /* immediate operand */ } else if (exp2RK(fs, e2)) { /* 2nd expression is constant? */ op = OP_EQK; r2 = e2->u.info; /* constant index */ } else { op = OP_EQ; /* will compare two registers */ r2 = luaK_exp2anyreg(fs, e2); } freeexps(fs, e1, e2); e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ)); e1->k = VJMP; } /* ** Apply prefix operation 'op' to expression 'e'. */ void luaK_prefix (FuncState *fs, UnOpr opr, expdesc *e, int line) { static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; luaK_dischargevars(fs, e); switch (opr) { case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ if (constfolding(fs, cast_int(opr + LUA_OPUNM), e, &ef)) break; /* else */ /* FALLTHROUGH */ case OPR_LEN: codeunexpval(fs, unopr2op(opr), e, line); break; case OPR_NOT: codenot(fs, e); break; default: lua_assert(0); } } /* ** Process 1st operand 'v' of binary operation 'op' before reading ** 2nd operand. */ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { luaK_dischargevars(fs, v); switch (op) { case OPR_AND: { luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ break; } case OPR_OR: { luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ break; } case OPR_CONCAT: { luaK_exp2nextreg(fs, v); /* operand must be on the stack */ break; } case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: case OPR_BAND: case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR: { if (!tonumeral(v, NULL)) luaK_exp2anyreg(fs, v); /* else keep numeral, which may be folded or used as an immediate operand */ break; } case OPR_EQ: case OPR_NE: { if (!tonumeral(v, NULL)) exp2RK(fs, v); /* else keep numeral, which may be an immediate operand */ break; } case OPR_LT: case OPR_LE: case OPR_GT: case OPR_GE: { int dummy, dummy2; if (!isSCnumber(v, &dummy, &dummy2)) luaK_exp2anyreg(fs, v); /* else keep numeral, which may be an immediate operand */ break; } default: lua_assert(0); } } /* ** Create code for '(e1 .. e2)'. ** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))', ** because concatenation is right associative), merge both CONCATs. */ static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) { Instruction *ie2 = previousinstruction(fs); if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */ int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */ lua_assert(e1->u.info + 1 == GETARG_A(*ie2)); freeexp(fs, e2); SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */ SETARG_B(*ie2, n + 1); /* will concatenate one more element */ } else { /* 'e2' is not a concatenation */ luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */ freeexp(fs, e2); luaK_fixline(fs, line); } } /* ** Finalize code for binary operation, after reading 2nd operand. */ void luaK_posfix (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2, int line) { luaK_dischargevars(fs, e2); if (foldbinop(opr) && constfolding(fs, cast_int(opr + LUA_OPADD), e1, e2)) return; /* done by folding */ switch (opr) { case OPR_AND: { lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */ luaK_concat(fs, &e2->f, e1->f); *e1 = *e2; break; } case OPR_OR: { lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */ luaK_concat(fs, &e2->t, e1->t); *e1 = *e2; break; } case OPR_CONCAT: { /* e1 .. e2 */ luaK_exp2nextreg(fs, e2); codeconcat(fs, e1, e2, line); break; } case OPR_ADD: case OPR_MUL: { codecommutative(fs, opr, e1, e2, line); break; } case OPR_SUB: { if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB)) break; /* coded as (r1 + -I) */ /* ELSE */ } /* FALLTHROUGH */ case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: { codearith(fs, opr, e1, e2, 0, line); break; } case OPR_BAND: case OPR_BOR: case OPR_BXOR: { codebitwise(fs, opr, e1, e2, line); break; } case OPR_SHL: { if (isSCint(e1)) { swapexps(e1, e2); codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */ } else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) { /* coded as (r1 >> -I) */; } else /* regular case (two registers) */ codebinexpval(fs, opr, e1, e2, line); break; } case OPR_SHR: { if (isSCint(e2)) codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */ else /* regular case (two registers) */ codebinexpval(fs, opr, e1, e2, line); break; } case OPR_EQ: case OPR_NE: { codeeq(fs, opr, e1, e2); break; } case OPR_GT: case OPR_GE: { /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */ swapexps(e1, e2); opr = cast(BinOpr, (opr - OPR_GT) + OPR_LT); } /* FALLTHROUGH */ case OPR_LT: case OPR_LE: { codeorder(fs, opr, e1, e2); break; } default: lua_assert(0); } } /* ** Change line information associated with current position, by removing ** previous info and adding it again with new line. */ void luaK_fixline (FuncState *fs, int line) { removelastlineinfo(fs); savelineinfo(fs, fs->f, line); } void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) { Instruction *inst = &fs->f->code[pc]; int extra = asize / (MAXARG_vC + 1); /* higher bits of array size */ int rc = asize % (MAXARG_vC + 1); /* lower bits of array size */ int k = (extra > 0); /* true iff needs extra argument */ hsize = (hsize != 0) ? luaO_ceillog2(cast_uint(hsize)) + 1 : 0; *inst = CREATE_vABCk(OP_NEWTABLE, ra, hsize, rc, k); *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra); } /* ** Emit a SETLIST instruction. ** 'base' is register that keeps table; ** 'nelems' is #table plus those to be stored now; ** 'tostore' is number of values (in registers 'base + 1',...) to add to ** table (or LUA_MULTRET to add up to stack top). */ void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { lua_assert(tostore != 0); if (tostore == LUA_MULTRET) tostore = 0; if (nelems <= MAXARG_vC) luaK_codevABCk(fs, OP_SETLIST, base, tostore, nelems, 0); else { int extra = nelems / (MAXARG_vC + 1); nelems %= (MAXARG_vC + 1); luaK_codevABCk(fs, OP_SETLIST, base, tostore, nelems, 1); codeextraarg(fs, extra); } fs->freereg = cast_byte(base + 1); /* free registers with list values */ } /* ** return the final target of a jump (skipping jumps to jumps) */ static int finaltarget (Instruction *code, int i) { int count; for (count = 0; count < 100; count++) { /* avoid infinite loops */ Instruction pc = code[i]; if (GET_OPCODE(pc) != OP_JMP) break; else i += GETARG_sJ(pc) + 1; } return i; } /* ** Do a final pass over the code of a function, doing small peephole ** optimizations and adjustments. */ void luaK_finish (FuncState *fs) { int i; Proto *p = fs->f; if (p->flag & PF_VATAB) /* will it use a vararg table? */ p->flag &= cast_byte(~PF_VAHID); /* then it will not use hidden args. */ for (i = 0; i < fs->pc; i++) { Instruction *pc = &p->code[i]; /* avoid "not used" warnings when assert is off (for 'onelua.c') */ (void)luaP_isOT; (void)luaP_isIT; lua_assert(i == 0 || luaP_isOT(*(pc - 1)) == luaP_isIT(*pc)); switch (GET_OPCODE(*pc)) { case OP_RETURN0: case OP_RETURN1: { if (!(fs->needclose || (p->flag & PF_VAHID))) break; /* no extra work */ /* else use OP_RETURN to do the extra work */ SET_OPCODE(*pc, OP_RETURN); } /* FALLTHROUGH */ case OP_RETURN: case OP_TAILCALL: { if (fs->needclose) SETARG_k(*pc, 1); /* signal that it needs to close */ if (p->flag & PF_VAHID) /* does it use hidden arguments? */ SETARG_C(*pc, p->numparams + 1); /* signal that */ break; } case OP_GETVARG: { if (p->flag & PF_VATAB) /* function has a vararg table? */ SET_OPCODE(*pc, OP_GETTABLE); /* must get vararg there */ break; } case OP_VARARG: { if (p->flag & PF_VATAB) /* function has a vararg table? */ SETARG_k(*pc, 1); /* must get vararg there */ break; } case OP_JMP: { /* to optimize jumps to jumps */ int target = finaltarget(p->code, i); fixjump(fs, i, target); /* jump directly to final target */ break; } default: break; } } } /* ** $Id: lcorolib.c $ ** Coroutine Library ** See Copyright Notice in lua.h */ #define lcorolib_c #define LUA_LIB #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" static lua_State *getco (lua_State *L) { lua_State *co = lua_tothread(L, 1); luaL_argexpected(L, co, 1, "thread"); return co; } /* ** Resumes a coroutine. Returns the number of results for non-error ** cases or -1 for errors. */ static int auxresume (lua_State *L, lua_State *co, int narg) { int status, nres; if (l_unlikely(!lua_checkstack(co, narg))) { lua_pushliteral(L, "too many arguments to resume"); return -1; /* error flag */ } lua_xmove(L, co, narg); status = lua_resume(co, L, narg, &nres); if (l_likely(status == LUA_OK || status == LUA_YIELD)) { if (l_unlikely(!lua_checkstack(L, nres + 1))) { lua_pop(co, nres); /* remove results anyway */ lua_pushliteral(L, "too many results to resume"); return -1; /* error flag */ } lua_xmove(co, L, nres); /* move yielded values */ return nres; } else { lua_xmove(co, L, 1); /* move error message */ return -1; /* error flag */ } } static int luaB_coresume (lua_State *L) { lua_State *co = getco(L); int r; r = auxresume(L, co, lua_gettop(L) - 1); if (l_unlikely(r < 0)) { lua_pushboolean(L, 0); lua_insert(L, -2); return 2; /* return false + error message */ } else { lua_pushboolean(L, 1); lua_insert(L, -(r + 1)); return r + 1; /* return true + 'resume' returns */ } } static int luaB_auxwrap (lua_State *L) { lua_State *co = lua_tothread(L, lua_upvalueindex(1)); int r = auxresume(L, co, lua_gettop(L)); if (l_unlikely(r < 0)) { /* error? */ int stat = lua_status(co); if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */ stat = lua_closethread(co, L); /* close its tbc variables */ lua_assert(stat != LUA_OK); lua_xmove(co, L, 1); /* move error message to the caller */ } if (stat != LUA_ERRMEM && /* not a memory error and ... */ lua_type(L, -1) == LUA_TSTRING) { /* ... error object is a string? */ luaL_where(L, 1); /* add extra info, if available */ lua_insert(L, -2); lua_concat(L, 2); } return lua_error(L); /* propagate error */ } return r; } static int luaB_cocreate (lua_State *L) { lua_State *NL; luaL_checktype(L, 1, LUA_TFUNCTION); NL = lua_newthread(L); lua_pushvalue(L, 1); /* move function to top */ lua_xmove(L, NL, 1); /* move function from L to NL */ return 1; } static int luaB_cowrap (lua_State *L) { luaB_cocreate(L); lua_pushcclosure(L, luaB_auxwrap, 1); return 1; } static int luaB_yield (lua_State *L) { return lua_yield(L, lua_gettop(L)); } #define COS_RUN 0 #define COS_DEAD 1 #define COS_YIELD 2 #define COS_NORM 3 static const char *const statname[] = {"running", "dead", "suspended", "normal"}; static int auxstatus (lua_State *L, lua_State *co) { if (L == co) return COS_RUN; else { switch (lua_status(co)) { case LUA_YIELD: return COS_YIELD; case LUA_OK: { lua_Debug ar; if (lua_getstack(co, 0, &ar)) /* does it have frames? */ return COS_NORM; /* it is running */ else if (lua_gettop(co) == 0) return COS_DEAD; else return COS_YIELD; /* initial state */ } default: /* some error occurred */ return COS_DEAD; } } } static int luaB_costatus (lua_State *L) { lua_State *co = getco(L); lua_pushstring(L, statname[auxstatus(L, co)]); return 1; } static lua_State *getoptco (lua_State *L) { return (lua_isnone(L, 1) ? L : getco(L)); } static int luaB_yieldable (lua_State *L) { lua_State *co = getoptco(L); lua_pushboolean(L, lua_isyieldable(co)); return 1; } static int luaB_corunning (lua_State *L) { int ismain = lua_pushthread(L); lua_pushboolean(L, ismain); return 2; } static int luaB_close (lua_State *L) { lua_State *co = getoptco(L); int status = auxstatus(L, co); switch (status) { case COS_DEAD: case COS_YIELD: { status = lua_closethread(co, L); if (status == LUA_OK) { lua_pushboolean(L, 1); return 1; } else { lua_pushboolean(L, 0); lua_xmove(co, L, 1); /* move error message */ return 2; } } case COS_NORM: return luaL_error(L, "cannot close a %s coroutine", statname[status]); case COS_RUN: lua_geti(L, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD); /* get main */ if (lua_tothread(L, -1) == co) return luaL_error(L, "cannot close main thread"); lua_closethread(co, L); /* close itself */ /* previous call does not return *//* FALLTHROUGH */ default: lua_assert(0); return 0; } } static const luaL_Reg co_funcs[] = { {"create", luaB_cocreate}, {"resume", luaB_coresume}, {"running", luaB_corunning}, {"status", luaB_costatus}, {"wrap", luaB_cowrap}, {"yield", luaB_yield}, {"isyieldable", luaB_yieldable}, {"close", luaB_close}, {NULL, NULL} }; LUAMOD_API int luaopen_coroutine (lua_State *L) { luaL_newlib(L, co_funcs); return 1; } /* ** $Id: lctype.c $ ** 'ctype' functions for Lua ** See Copyright Notice in lua.h */ #define lctype_c #define LUA_CORE #if !LUA_USE_CTYPE /* { */ #include #if defined (LUA_UCID) /* accept UniCode IDentifiers? */ /* consider all non-ASCII codepoints to be alphabetic */ #define NONA 0x01 #else #define NONA 0x00 /* default */ #endif LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = { 0x00, /* EOZ */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */ 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */ 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */ 0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */ 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05, 0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */ 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */ 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 8. */ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 9. */ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* a. */ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* b. */ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, 0x00, 0x00, NONA, NONA, NONA, NONA, NONA, NONA, /* c. */ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* d. */ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* e. */ NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, 0x00, 0x00, 0x00, /* f. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; #endif /* } */ #ifndef NO_LDEBUG /* ** $Id: ldblib.c $ ** Interface from Lua to its debug API ** See Copyright Notice in lua.h */ #define ldblib_c #define LUA_LIB #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** The hook table at registry[HOOKKEY] maps threads to their current ** hook function. */ static const char *const HOOKKEY = "_HOOKKEY"; /* ** If L1 != L, L1 can be in any state, and therefore there are no ** guarantees about its stack space; any push in L1 must be ** checked. */ static void checkstack (lua_State *L, lua_State *L1, int n) { if (l_unlikely(L != L1 && !lua_checkstack(L1, n))) luaL_error(L, "stack overflow"); } static int db_getregistry (lua_State *L) { lua_pushvalue(L, LUA_REGISTRYINDEX); return 1; } static int db_getmetatable (lua_State *L) { luaL_checkany(L, 1); if (!lua_getmetatable(L, 1)) { lua_pushnil(L); /* no metatable */ } return 1; } static int db_setmetatable (lua_State *L) { int t = lua_type(L, 2); luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table"); lua_settop(L, 2); lua_setmetatable(L, 1); return 1; /* return 1st argument */ } static int db_getuservalue (lua_State *L) { int n = (int)luaL_optinteger(L, 2, 1); if (lua_type(L, 1) != LUA_TUSERDATA) luaL_pushfail(L); else if (lua_getiuservalue(L, 1, n) != LUA_TNONE) { lua_pushboolean(L, 1); return 2; } return 1; } static int db_setuservalue (lua_State *L) { int n = (int)luaL_optinteger(L, 3, 1); luaL_checktype(L, 1, LUA_TUSERDATA); luaL_checkany(L, 2); lua_settop(L, 2); if (!lua_setiuservalue(L, 1, n)) luaL_pushfail(L); return 1; } /* ** Auxiliary function used by several library functions: check for ** an optional thread as function's first argument and set 'arg' with ** 1 if this argument is present (so that functions can skip it to ** access their other arguments) */ static lua_State *getthread (lua_State *L, int *arg) { if (lua_isthread(L, 1)) { *arg = 1; return lua_tothread(L, 1); } else { *arg = 0; return L; /* function will operate over current thread */ } } /* ** Variations of 'lua_settable', used by 'db_getinfo' to put results ** from 'lua_getinfo' into result table. Key is always a string; ** value can be a string, an int, or a boolean. */ static void settabss (lua_State *L, const char *k, const char *v) { lua_pushstring(L, v); lua_setfield(L, -2, k); } static void settabsi (lua_State *L, const char *k, int v) { lua_pushinteger(L, v); lua_setfield(L, -2, k); } static void settabsb (lua_State *L, const char *k, int v) { lua_pushboolean(L, v); lua_setfield(L, -2, k); } /* ** In function 'db_getinfo', the call to 'lua_getinfo' may push ** results on the stack; later it creates the result table to put ** these objects. Function 'treatstackoption' puts the result from ** 'lua_getinfo' on top of the result table so that it can call ** 'lua_setfield'. */ static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { if (L == L1) lua_rotate(L, -2, 1); /* exchange object and table */ else lua_xmove(L1, L, 1); /* move object to the "main" stack */ lua_setfield(L, -2, fname); /* put object into table */ } /* ** Calls 'lua_getinfo' and collects all results in a new table. ** L1 needs stack space for an optional input (function) plus ** two optional outputs (function and line table) from function ** 'lua_getinfo'. */ static int db_getinfo (lua_State *L) { lua_Debug ar; int arg; lua_State *L1 = getthread(L, &arg); const char *options = luaL_optstring(L, arg+2, "flnSrtu"); checkstack(L, L1, 3); luaL_argcheck(L, options[0] != '>', arg + 2, "invalid option '>'"); if (lua_isfunction(L, arg + 1)) { /* info about a function? */ options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */ lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */ lua_xmove(L, L1, 1); } else { /* stack level */ if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) { luaL_pushfail(L); /* level out of range */ return 1; } } if (!lua_getinfo(L1, options, &ar)) return luaL_argerror(L, arg+2, "invalid option"); lua_newtable(L); /* table to collect results */ if (strchr(options, 'S')) { lua_pushlstring(L, ar.source, ar.srclen); lua_setfield(L, -2, "source"); settabss(L, "short_src", ar.short_src); settabsi(L, "linedefined", ar.linedefined); settabsi(L, "lastlinedefined", ar.lastlinedefined); settabss(L, "what", ar.what); } if (strchr(options, 'l')) settabsi(L, "currentline", ar.currentline); if (strchr(options, 'u')) { settabsi(L, "nups", ar.nups); settabsi(L, "nparams", ar.nparams); settabsb(L, "isvararg", ar.isvararg); } if (strchr(options, 'n')) { settabss(L, "name", ar.name); settabss(L, "namewhat", ar.namewhat); } if (strchr(options, 'r')) { settabsi(L, "ftransfer", ar.ftransfer); settabsi(L, "ntransfer", ar.ntransfer); } if (strchr(options, 't')) { settabsb(L, "istailcall", ar.istailcall); settabsi(L, "extraargs", ar.extraargs); } if (strchr(options, 'L')) treatstackoption(L, L1, "activelines"); if (strchr(options, 'f')) treatstackoption(L, L1, "func"); return 1; /* return table */ } static int db_getlocal (lua_State *L) { int arg; lua_State *L1 = getthread(L, &arg); int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */ if (lua_isfunction(L, arg + 1)) { /* function argument? */ lua_pushvalue(L, arg + 1); /* push function */ lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */ return 1; /* return only name (there is no value) */ } else { /* stack-level argument */ lua_Debug ar; const char *name; int level = (int)luaL_checkinteger(L, arg + 1); if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */ return luaL_argerror(L, arg+1, "level out of range"); checkstack(L, L1, 1); name = lua_getlocal(L1, &ar, nvar); if (name) { lua_xmove(L1, L, 1); /* move local value */ lua_pushstring(L, name); /* push name */ lua_rotate(L, -2, 1); /* re-order */ return 2; } else { luaL_pushfail(L); /* no name (nor value) */ return 1; } } } static int db_setlocal (lua_State *L) { int arg; const char *name; lua_State *L1 = getthread(L, &arg); lua_Debug ar; int level = (int)luaL_checkinteger(L, arg + 1); int nvar = (int)luaL_checkinteger(L, arg + 2); if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */ return luaL_argerror(L, arg+1, "level out of range"); luaL_checkany(L, arg+3); lua_settop(L, arg+3); checkstack(L, L1, 1); lua_xmove(L, L1, 1); name = lua_setlocal(L1, &ar, nvar); if (name == NULL) lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */ lua_pushstring(L, name); return 1; } /* ** get (if 'get' is true) or set an upvalue from a closure */ static int auxupvalue (lua_State *L, int get) { const char *name; int n = (int)luaL_checkinteger(L, 2); /* upvalue index */ luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */ name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); if (name == NULL) return 0; lua_pushstring(L, name); lua_insert(L, -(get+1)); /* no-op if get is false */ return get + 1; } static int db_getupvalue (lua_State *L) { return auxupvalue(L, 1); } static int db_setupvalue (lua_State *L) { luaL_checkany(L, 3); return auxupvalue(L, 0); } /* ** Check whether a given upvalue from a given closure exists and ** returns its index */ static void *checkupval (lua_State *L, int argf, int argnup, int *pnup) { void *id; int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */ luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */ id = lua_upvalueid(L, argf, nup); if (pnup) { luaL_argcheck(L, id != NULL, argnup, "invalid upvalue index"); *pnup = nup; } return id; } static int db_upvalueid (lua_State *L) { void *id = checkupval(L, 1, 2, NULL); if (id != NULL) lua_pushlightuserdata(L, id); else luaL_pushfail(L); return 1; } static int db_upvaluejoin (lua_State *L) { int n1, n2; checkupval(L, 1, 2, &n1); checkupval(L, 3, 4, &n2); luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected"); luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected"); lua_upvaluejoin(L, 1, n1, 3, n2); return 0; } /* ** Call hook function registered at hook table for the current ** thread (if there is one) */ static void hookf (lua_State *L, lua_Debug *ar) { static const char *const hooknames[] = {"call", "return", "line", "count", "tail call"}; lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY); lua_pushthread(L); if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */ lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */ if (ar->currentline >= 0) lua_pushinteger(L, ar->currentline); /* push current line */ else lua_pushnil(L); lua_assert(lua_getinfo(L, "lS", ar)); lua_call(L, 2, 0); /* call hook function */ } } /* ** Convert a string mask (for 'sethook') into a bit mask */ static int makemask (const char *smask, int count) { int mask = 0; if (strchr(smask, 'c')) mask |= LUA_MASKCALL; if (strchr(smask, 'r')) mask |= LUA_MASKRET; if (strchr(smask, 'l')) mask |= LUA_MASKLINE; if (count > 0) mask |= LUA_MASKCOUNT; return mask; } /* ** Convert a bit mask (for 'gethook') into a string mask */ static char *unmakemask (int mask, char *smask) { int i = 0; if (mask & LUA_MASKCALL) smask[i++] = 'c'; if (mask & LUA_MASKRET) smask[i++] = 'r'; if (mask & LUA_MASKLINE) smask[i++] = 'l'; smask[i] = '\0'; return smask; } static int db_sethook (lua_State *L) { int arg, mask, count; lua_Hook func; lua_State *L1 = getthread(L, &arg); if (lua_isnoneornil(L, arg+1)) { /* no hook? */ lua_settop(L, arg+1); func = NULL; mask = 0; count = 0; /* turn off hooks */ } else { const char *smask = luaL_checkstring(L, arg+2); luaL_checktype(L, arg+1, LUA_TFUNCTION); count = (int)luaL_optinteger(L, arg + 3, 0); func = hookf; mask = makemask(smask, count); } if (!luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)) { /* table just created; initialize it */ lua_pushliteral(L, "k"); lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ lua_pushvalue(L, -1); lua_setmetatable(L, -2); /* metatable(hooktable) = hooktable */ } checkstack(L, L1, 1); lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */ lua_pushvalue(L, arg + 1); /* value (hook function) */ lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */ lua_sethook(L1, func, mask, count); return 0; } static int db_gethook (lua_State *L) { int arg; lua_State *L1 = getthread(L, &arg); char buff[5]; int mask = lua_gethookmask(L1); lua_Hook hook = lua_gethook(L1); if (hook == NULL) { /* no hook? */ luaL_pushfail(L); return 1; } else if (hook != hookf) /* external hook? */ lua_pushliteral(L, "external hook"); else { /* hook table must exist */ lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY); checkstack(L, L1, 1); lua_pushthread(L1); lua_xmove(L1, L, 1); lua_rawget(L, -2); /* 1st result = hooktable[L1] */ lua_remove(L, -2); /* remove hook table */ } lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */ lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */ return 3; } #ifdef NO_BA_SERVER static int db_debug (lua_State *L) { for (;;) { char buffer[250]; lua_writestringerror("%s", "lua_debug> "); if (fgets(buffer, sizeof(buffer), stdin) == NULL || strcmp(buffer, "cont\n") == 0) return 0; if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || lua_pcall(L, 0, 0, 0)) lua_writestringerror("%s\n", luaL_tolstring(L, -1, NULL)); lua_settop(L, 0); /* remove eventual returns */ } } #endif static int db_traceback (lua_State *L) { int arg; lua_State *L1 = getthread(L, &arg); const char *msg = lua_tostring(L, arg + 1); if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */ lua_pushvalue(L, arg + 1); /* return it untouched */ else { int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0); luaL_traceback(L, L1, msg, level); } return 1; } static const luaL_Reg dblib[] = { #ifdef NO_BA_SERVER {"debug", db_debug}, #endif {"getuservalue", db_getuservalue}, {"gethook", db_gethook}, {"getinfo", db_getinfo}, {"getlocal", db_getlocal}, {"getregistry", db_getregistry}, {"getmetatable", db_getmetatable}, {"getupvalue", db_getupvalue}, {"upvaluejoin", db_upvaluejoin}, {"upvalueid", db_upvalueid}, {"setuservalue", db_setuservalue}, {"sethook", db_sethook}, {"setlocal", db_setlocal}, {"setmetatable", db_setmetatable}, {"setupvalue", db_setupvalue}, {"traceback", db_traceback}, {NULL, NULL} }; LUAMOD_API int luaopen_debug (lua_State *L) { luaL_newlib(L, dblib); return 1; } #endif /* ** $Id: ldebug.c $ ** Debug Interface ** See Copyright Notice in lua.h */ #define ldebug_c #define LUA_CORE #include #include #include #include "lua.h" #define LuaClosure(f) ((f) != NULL && (f)->c.tt == LUA_VLCL) static const char strlocal[] = "local"; static const char strupval[] = "upvalue"; static const char *funcnamefromcall (lua_State *L, CallInfo *ci, const char **name); static int currentpc (CallInfo *ci) { lua_assert(isLua(ci)); return pcRel(ci->u.l.savedpc, ci_func(ci)->p); } /* ** Get a "base line" to find the line corresponding to an instruction. ** Base lines are regularly placed at MAXIWTHABS intervals, so usually ** an integer division gets the right place. When the source file has ** large sequences of empty/comment lines, it may need extra entries, ** so the original estimate needs a correction. ** If the original estimate is -1, the initial 'if' ensures that the ** 'while' will run at least once. ** The assertion that the estimate is a lower bound for the correct base ** is valid as long as the debug info has been generated with the same ** value for MAXIWTHABS or smaller. (Previous releases use a little ** smaller value.) */ static int getbaseline (const Proto *f, int pc, int *basepc) { if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) { *basepc = -1; /* start from the beginning */ return f->linedefined; } else { int i = pc / MAXIWTHABS - 1; /* get an estimate */ /* estimate must be a lower bound of the correct base */ lua_assert(i < 0 || (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc)); while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc) i++; /* low estimate; adjust it */ *basepc = f->abslineinfo[i].pc; return f->abslineinfo[i].line; } } /* ** Get the line corresponding to instruction 'pc' in function 'f'; ** first gets a base line and from there does the increments until ** the desired instruction. */ int luaG_getfuncline (const Proto *f, int pc) { if (f->lineinfo == NULL) /* no debug information? */ return -1; else { int basepc; int baseline = getbaseline(f, pc, &basepc); while (basepc++ < pc) { /* walk until given instruction */ lua_assert(f->lineinfo[basepc] != ABSLINEINFO); baseline += f->lineinfo[basepc]; /* correct line */ } return baseline; } } static int getcurrentline (CallInfo *ci) { return luaG_getfuncline(ci_func(ci)->p, currentpc(ci)); } /* ** Set 'trap' for all active Lua frames. ** This function can be called during a signal, under "reasonable" ** assumptions. A new 'ci' is completely linked in the list before it ** becomes part of the "active" list, and we assume that pointers are ** atomic; see comment in next function. ** (A compiler doing interprocedural optimizations could, theoretically, ** reorder memory writes in such a way that the list could be ** temporarily broken while inserting a new element. We simply assume it ** has no good reasons to do that.) */ static void settraps (CallInfo *ci) { for (; ci != NULL; ci = ci->previous) if (isLua(ci)) ci->u.l.trap = 1; } /* ** This function can be called during a signal, under "reasonable" ** assumptions. ** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount') ** are for debug only, and it is no problem if they get arbitrary ** values (causes at most one wrong hook call). 'hookmask' is an atomic ** value. We assume that pointers are atomic too (e.g., gcc ensures that ** for all platforms where it runs). Moreover, 'hook' is always checked ** before being called (see 'luaD_hook'). */ LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { if (func == NULL || mask == 0) { /* turn off hooks? */ mask = 0; func = NULL; } L->hook = func; L->basehookcount = count; resethookcount(L); L->hookmask = cast_byte(mask); if (mask) settraps(L->ci); /* to trace inside 'luaV_execute' */ } LUA_API lua_Hook lua_gethook (lua_State *L) { return L->hook; } LUA_API int lua_gethookmask (lua_State *L) { return L->hookmask; } LUA_API int lua_gethookcount (lua_State *L) { return L->basehookcount; } LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { int status; CallInfo *ci; if (level < 0) return 0; /* invalid (negative) level */ lua_lock(L); for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) level--; if (level == 0 && ci != &L->base_ci) { /* level found? */ status = 1; ar->i_ci = ci; } else status = 0; /* no such level */ lua_unlock(L); return status; } static const char *upvalname (const Proto *p, int uv) { TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); if (s == NULL) return "?"; else return getstr(s); } static const char *findvararg (CallInfo *ci, int n, StkId *pos) { if (clLvalue(s2v(ci->func.p))->p->flag & PF_VAHID) { int nextra = ci->u.l.nextraargs; if (n >= -nextra) { /* 'n' is negative */ *pos = ci->func.p - nextra - (n + 1); return "(vararg)"; /* generic name for any vararg */ } } return NULL; /* no such vararg */ } const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) { StkId base = ci->func.p + 1; const char *name = NULL; if (isLua(ci)) { if (n < 0) /* access to vararg values? */ return findvararg(ci, n, pos); else name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); } if (name == NULL) { /* no 'standard' name? */ StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p; if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */ /* generic name for any valid slot */ name = isLua(ci) ? "(temporary)" : "(C temporary)"; } else return NULL; /* no name */ } if (pos) *pos = base + (n - 1); return name; } LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { const char *name; lua_lock(L); if (ar == NULL) { /* information about non-active function? */ if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */ name = NULL; else /* consider live variables at function start (parameters) */ name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0); } else { /* active function; get information through 'ar' */ StkId pos = NULL; /* to avoid warnings */ name = luaG_findlocal(L, ar->i_ci, n, &pos); if (name) { setobjs2s(L, L->top.p, pos); api_incr_top(L); } } lua_unlock(L); return name; } LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { StkId pos = NULL; /* to avoid warnings */ const char *name; lua_lock(L); name = luaG_findlocal(L, ar->i_ci, n, &pos); if (name) { api_checkpop(L, 1); setobjs2s(L, pos, L->top.p - 1); L->top.p--; /* pop value */ } lua_unlock(L); return name; } static void funcinfo (lua_Debug *ar, Closure *cl) { if (!LuaClosure(cl)) { ar->source = "=[C]"; ar->srclen = LL("=[C]"); ar->linedefined = -1; ar->lastlinedefined = -1; ar->what = "C"; } else { const Proto *p = cl->l.p; if (p->source) { ar->source = getlstr(p->source, ar->srclen); } else { ar->source = "=?"; ar->srclen = LL("=?"); } ar->linedefined = p->linedefined; ar->lastlinedefined = p->lastlinedefined; ar->what = (ar->linedefined == 0) ? "main" : "Lua"; } luaO_chunkid(ar->short_src, ar->source, ar->srclen); } static int nextline (const Proto *p, int currentline, int pc) { if (p->lineinfo[pc] != ABSLINEINFO) return currentline + p->lineinfo[pc]; else return luaG_getfuncline(p, pc); } static void collectvalidlines (lua_State *L, Closure *f) { if (!LuaClosure(f)) { setnilvalue(s2v(L->top.p)); api_incr_top(L); } else { const Proto *p = f->l.p; int currentline = p->linedefined; Table *t = luaH_new(L); /* new table to store active lines */ sethvalue2s(L, L->top.p, t); /* push it on stack */ api_incr_top(L); if (p->lineinfo != NULL) { /* proto with debug information? */ int i; TValue v; setbtvalue(&v); /* boolean 'true' to be the value of all indices */ if (!(isvararg(p))) /* regular function? */ i = 0; /* consider all instructions */ else { /* vararg function */ lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP); currentline = nextline(p, currentline, 0); i = 1; /* skip first instruction (OP_VARARGPREP) */ } for (; i < p->sizelineinfo; i++) { /* for each instruction */ currentline = nextline(p, currentline, i); /* get its line */ luaH_setint(L, t, currentline, &v); /* table[line] = true */ } } } } static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { /* calling function is a known function? */ if (ci != NULL && !(ci->callstatus & CIST_TAIL)) return funcnamefromcall(L, ci->previous, name); else return NULL; /* no way to find a name */ } static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, Closure *f, CallInfo *ci) { int status = 1; for (; *what; what++) { switch (*what) { case 'S': { funcinfo(ar, f); break; } case 'l': { ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1; break; } case 'u': { ar->nups = (f == NULL) ? 0 : f->c.nupvalues; if (!LuaClosure(f)) { ar->isvararg = 1; ar->nparams = 0; } else { ar->isvararg = (isvararg(f->l.p)) ? 1 : 0; ar->nparams = f->l.p->numparams; } break; } case 't': { if (ci != NULL) { ar->istailcall = !!(ci->callstatus & CIST_TAIL); ar->extraargs = cast_uchar((ci->callstatus & MAX_CCMT) >> CIST_CCMT); } else { ar->istailcall = 0; ar->extraargs = 0; } break; } case 'n': { ar->namewhat = getfuncname(L, ci, &ar->name); if (ar->namewhat == NULL) { ar->namewhat = ""; /* not found */ ar->name = NULL; } break; } case 'r': { if (ci == NULL || !(ci->callstatus & CIST_HOOKED)) ar->ftransfer = ar->ntransfer = 0; else { ar->ftransfer = L->transferinfo.ftransfer; ar->ntransfer = L->transferinfo.ntransfer; } break; } case 'L': case 'f': /* handled by lua_getinfo */ break; default: status = 0; /* invalid option */ } } return status; } LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { int status; Closure *cl; CallInfo *ci; TValue *func; lua_lock(L); if (*what == '>') { ci = NULL; func = s2v(L->top.p - 1); api_check(L, ttisfunction(func), "function expected"); what++; /* skip the '>' */ L->top.p--; /* pop function */ } else { ci = ar->i_ci; func = s2v(ci->func.p); lua_assert(ttisfunction(func)); } cl = ttisclosure(func) ? clvalue(func) : NULL; status = auxgetinfo(L, what, ar, cl, ci); if (strchr(what, 'f')) { setobj2s(L, L->top.p, func); api_incr_top(L); } if (strchr(what, 'L')) collectvalidlines(L, cl); lua_unlock(L); return status; } /* ** {====================================================== ** Symbolic Execution ** ======================================================= */ static int filterpc (int pc, int jmptarget) { if (pc < jmptarget) /* is code conditional (inside a jump)? */ return -1; /* cannot know who sets that register */ else return pc; /* current position sets that register */ } /* ** Try to find last instruction before 'lastpc' that modified register 'reg'. */ static int findsetreg (const Proto *p, int lastpc, int reg) { int pc; int setreg = -1; /* keep last instruction that changed 'reg' */ int jmptarget = 0; /* any code before this address is conditional */ if (testMMMode(GET_OPCODE(p->code[lastpc]))) lastpc--; /* previous instruction was not actually executed */ for (pc = 0; pc < lastpc; pc++) { Instruction i = p->code[pc]; OpCode op = GET_OPCODE(i); int a = GETARG_A(i); int change; /* true if current instruction changed 'reg' */ switch (op) { case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */ int b = GETARG_B(i); change = (a <= reg && reg <= a + b); break; } case OP_TFORCALL: { /* affect all regs above its base */ change = (reg >= a + 2); break; } case OP_CALL: case OP_TAILCALL: { /* affect all registers above base */ change = (reg >= a); break; } case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */ int b = GETARG_sJ(i); int dest = pc + 1 + b; /* jump does not skip 'lastpc' and is larger than current one? */ if (dest <= lastpc && dest > jmptarget) jmptarget = dest; /* update 'jmptarget' */ change = 0; break; } default: /* any instruction that sets A */ change = (testAMode(op) && reg == a); break; } if (change) setreg = filterpc(pc, jmptarget); } return setreg; } /* ** Find a "name" for the constant 'c'. */ static const char *kname (const Proto *p, int index, const char **name) { TValue *kvalue = &p->k[index]; if (ttisstring(kvalue)) { *name = getstr(tsvalue(kvalue)); return "constant"; } else { *name = "?"; return NULL; } } static const char *basicgetobjname (const Proto *p, int *ppc, int reg, const char **name) { int pc = *ppc; *name = luaF_getlocalname(p, reg + 1, pc); if (*name) /* is a local? */ return strlocal; /* else try symbolic execution */ *ppc = pc = findsetreg(p, pc, reg); if (pc != -1) { /* could find instruction? */ Instruction i = p->code[pc]; OpCode op = GET_OPCODE(i); switch (op) { case OP_MOVE: { int b = GETARG_B(i); /* move from 'b' to 'a' */ if (b < GETARG_A(i)) return basicgetobjname(p, ppc, b, name); /* get name for 'b' */ break; } case OP_GETUPVAL: { *name = upvalname(p, GETARG_B(i)); return strupval; } case OP_LOADK: return kname(p, GETARG_Bx(i), name); case OP_LOADKX: return kname(p, GETARG_Ax(p->code[pc + 1]), name); default: break; } } return NULL; /* could not find reasonable name */ } /* ** Find a "name" for the register 'c'. */ static void rname (const Proto *p, int pc, int c, const char **name) { const char *what = basicgetobjname(p, &pc, c, name); /* search for 'c' */ if (!(what && *what == 'c')) /* did not find a constant name? */ *name = "?"; } /* ** Check whether table being indexed by instruction 'i' is the ** environment '_ENV' */ static const char *isEnv (const Proto *p, int pc, Instruction i, int isup) { int t = GETARG_B(i); /* table index */ const char *name; /* name of indexed variable */ if (isup) /* is 't' an upvalue? */ name = upvalname(p, t); else { /* 't' is a register */ const char *what = basicgetobjname(p, &pc, t, &name); /* 'name' must be the name of a local variable (at the current level or an upvalue) */ if (what != strlocal && what != strupval) name = NULL; /* cannot be the variable _ENV */ } return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field"; } /* ** Extend 'basicgetobjname' to handle table accesses */ static const char *getobjname (const Proto *p, int lastpc, int reg, const char **name) { const char *kind = basicgetobjname(p, &lastpc, reg, name); if (kind != NULL) return kind; else if (lastpc != -1) { /* could find instruction? */ Instruction i = p->code[lastpc]; OpCode op = GET_OPCODE(i); switch (op) { case OP_GETTABUP: { int k = GETARG_C(i); /* key index */ kname(p, k, name); return isEnv(p, lastpc, i, 1); } case OP_GETTABLE: { int k = GETARG_C(i); /* key index */ rname(p, lastpc, k, name); return isEnv(p, lastpc, i, 0); } case OP_GETI: { *name = "integer index"; return "field"; } case OP_GETFIELD: { int k = GETARG_C(i); /* key index */ kname(p, k, name); return isEnv(p, lastpc, i, 0); } case OP_SELF: { int k = GETARG_C(i); /* key index */ kname(p, k, name); return "method"; } default: break; /* go through to return NULL */ } } return NULL; /* could not find reasonable name */ } /* ** Try to find a name for a function based on the code that called it. ** (Only works when function was called by a Lua function.) ** Returns what the name is (e.g., "for iterator", "method", ** "metamethod") and sets '*name' to point to the name. */ static const char *funcnamefromcode (lua_State *L, const Proto *p, int pc, const char **name) { TMS tm = (TMS)0; /* (initial value avoids warnings) */ Instruction i = p->code[pc]; /* calling instruction */ switch (GET_OPCODE(i)) { case OP_CALL: case OP_TAILCALL: return getobjname(p, pc, GETARG_A(i), name); /* get function name */ case OP_TFORCALL: { /* for iterator */ *name = "for iterator"; return "for iterator"; } /* other instructions can do calls through metamethods */ case OP_SELF: case OP_GETTABUP: case OP_GETTABLE: case OP_GETI: case OP_GETFIELD: tm = TM_INDEX; break; case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD: tm = TM_NEWINDEX; break; case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: { tm = cast(TMS, GETARG_C(i)); break; } case OP_UNM: tm = TM_UNM; break; case OP_BNOT: tm = TM_BNOT; break; case OP_LEN: tm = TM_LEN; break; case OP_CONCAT: tm = TM_CONCAT; break; case OP_EQ: tm = TM_EQ; break; /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */ case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break; case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break; case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break; default: return NULL; /* cannot find a reasonable name */ } *name = getshrstr(G(L)->tmname[tm]) + 2; return "metamethod"; } /* ** Try to find a name for a function based on how it was called. */ static const char *funcnamefromcall (lua_State *L, CallInfo *ci, const char **name) { if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */ *name = "?"; return "hook"; } else if (ci->callstatus & CIST_FIN) { /* was it called as a finalizer? */ *name = "__gc"; return "metamethod"; /* report it as such */ } else if (isLua(ci)) return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name); else return NULL; } /* }====================================================== */ /* ** Check whether pointer 'o' points to some value in the stack frame of ** the current function and, if so, returns its index. Because 'o' may ** not point to a value in this stack, we cannot compare it with the ** region boundaries (undefined behavior in ISO C). */ static int instack (CallInfo *ci, const TValue *o) { int pos; StkId base = ci->func.p + 1; for (pos = 0; base + pos < ci->top.p; pos++) { if (o == s2v(base + pos)) return pos; } return -1; /* not found */ } /* ** Checks whether value 'o' came from an upvalue. (That can only happen ** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on ** upvalues.) */ static const char *getupvalname (CallInfo *ci, const TValue *o, const char **name) { LClosure *c = ci_func(ci); int i; for (i = 0; i < c->nupvalues; i++) { if (c->upvals[i]->v.p == o) { *name = upvalname(c->p, i); return strupval; } } return NULL; } static const char *formatvarinfo (lua_State *L, const char *kind, const char *name) { if (kind == NULL) return ""; /* no information */ else return luaO_pushfstring(L, " (%s '%s')", kind, name); } /* ** Build a string with a "description" for the value 'o', such as ** "variable 'x'" or "upvalue 'y'". */ static const char *varinfo (lua_State *L, const TValue *o) { CallInfo *ci = L->ci; const char *name = NULL; /* to avoid warnings */ const char *kind = NULL; if (isLua(ci)) { kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ if (!kind) { /* not an upvalue? */ int reg = instack(ci, o); /* try a register */ if (reg >= 0) /* is 'o' a register? */ kind = getobjname(ci_func(ci)->p, currentpc(ci), reg, &name); } } return formatvarinfo(L, kind, name); } /* ** Raise a type error */ static l_noret typeerror (lua_State *L, const TValue *o, const char *op, const char *extra) { const char *t = luaT_objtypename(L, o); luaG_runerror(L, "attempt to %s a %s value%s", op, t, extra); } /* ** Raise a type error with "standard" information about the faulty ** object 'o' (using 'varinfo'). */ l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { typeerror(L, o, op, varinfo(L, o)); } /* ** Raise an error for calling a non-callable object. Try to find a name ** for the object based on how it was called ('funcnamefromcall'); if it ** cannot get a name there, try 'varinfo'. */ l_noret luaG_callerror (lua_State *L, const TValue *o) { CallInfo *ci = L->ci; const char *name = NULL; /* to avoid warnings */ const char *kind = funcnamefromcall(L, ci, &name); const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o); typeerror(L, o, "call", extra); } l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) { luaG_runerror(L, "bad 'for' %s (number expected, got %s)", what, luaT_objtypename(L, o)); } l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) { if (ttisstring(p1) || cvt2str(p1)) p1 = p2; luaG_typeerror(L, p1, "concatenate"); } l_noret luaG_opinterror (lua_State *L, const TValue *p1, const TValue *p2, const char *msg) { if (!ttisnumber(p1)) /* first operand is wrong? */ p2 = p1; /* now second is wrong */ luaG_typeerror(L, p2, msg); } /* ** Error when both values are convertible to numbers, but not to integers */ l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) { lua_Integer temp; if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I)) p2 = p1; luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2)); } l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { const char *t1 = luaT_objtypename(L, p1); const char *t2 = luaT_objtypename(L, p2); if (strcmp(t1, t2) == 0) luaG_runerror(L, "attempt to compare two %s values", t1); else luaG_runerror(L, "attempt to compare %s with %s", t1, t2); } l_noret luaG_errnnil (lua_State *L, LClosure *cl, int k) { const char *globalname = "?"; /* default name if k == 0 */ if (k > 0) kname(cl->p, k - 1, &globalname); luaG_runerror(L, "global '%s' already defined", globalname); } /* add src:line information to 'msg' */ const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, int line) { if (src == NULL) /* no debug information? */ return luaO_pushfstring(L, "?:?: %s", msg); else { char buff[LUA_IDSIZE]; size_t idlen; const char *id = getlstr(src, idlen); luaO_chunkid(buff, id, idlen); return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); } } l_noret luaG_errormsg (lua_State *L) { if (L->errfunc != 0) { /* is there an error handling function? */ StkId errfunc = restorestack(L, L->errfunc); lua_assert(ttisfunction(s2v(errfunc))); setobjs2s(L, L->top.p, L->top.p - 1); /* move argument */ setobjs2s(L, L->top.p - 1, errfunc); /* push function */ L->top.p++; /* assume EXTRA_STACK */ luaD_callnoyield(L, L->top.p - 2, 1); /* call it */ } if (ttisnil(s2v(L->top.p - 1))) { /* error object is nil? */ /* change it to a proper message */ setsvalue2s(L, L->top.p - 1, luaS_newliteral(L, "")); } luaD_throw(L, LUA_ERRRUN); } l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { CallInfo *ci = L->ci; const char *msg; va_list argp; luaC_checkGC(L); /* error message uses memory */ pushvfstring(L, argp, fmt, msg); if (isLua(ci)) { /* Lua function? */ /* add source:line information */ luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci)); setobjs2s(L, L->top.p - 2, L->top.p - 1); /* remove 'msg' */ L->top.p--; } luaG_errormsg(L); } /* ** Check whether new instruction 'newpc' is in a different line from ** previous instruction 'oldpc'. More often than not, 'newpc' is only ** one or a few instructions after 'oldpc' (it must be after, see ** caller), so try to avoid calling 'luaG_getfuncline'. If they are ** too far apart, there is a good chance of a ABSLINEINFO in the way, ** so it goes directly to 'luaG_getfuncline'. */ static int changedline (const Proto *p, int oldpc, int newpc) { if (p->lineinfo == NULL) /* no debug information? */ return 0; if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */ int delta = 0; /* line difference */ int pc = oldpc; for (;;) { int lineinfo = p->lineinfo[++pc]; if (lineinfo == ABSLINEINFO) break; /* cannot compute delta; fall through */ delta += lineinfo; if (pc == newpc) return (delta != 0); /* delta computed successfully */ } } /* either instructions are too far apart or there is an absolute line info in the way; compute line difference explicitly */ return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc)); } /* ** Traces Lua calls. If code is running the first instruction of a function, ** and function is not vararg, and it is not coming from an yield, ** calls 'luaD_hookcall'. (Vararg functions will call 'luaD_hookcall' ** after adjusting its variable arguments; otherwise, they could call ** a line/count hook before the call hook. Functions coming from ** an yield already called 'luaD_hookcall' before yielding.) */ int luaG_tracecall (lua_State *L) { CallInfo *ci = L->ci; Proto *p = ci_func(ci)->p; ci->u.l.trap = 1; /* ensure hooks will be checked */ if (ci->u.l.savedpc == p->code) { /* first instruction (not resuming)? */ if (isvararg(p)) return 0; /* hooks will start at VARARGPREP instruction */ else if (!(ci->callstatus & CIST_HOOKYIELD)) /* not yielded? */ luaD_hookcall(L, ci); /* check 'call' hook */ } return 1; /* keep 'trap' on */ } /* ** Traces the execution of a Lua function. Called before the execution ** of each opcode, when debug is on. 'L->oldpc' stores the last ** instruction traced, to detect line changes. When entering a new ** function, 'npci' will be zero and will test as a new line whatever ** the value of 'oldpc'. Some exceptional conditions may return to ** a function without setting 'oldpc'. In that case, 'oldpc' may be ** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc' ** at most causes an extra call to a line hook.) ** This function is not "Protected" when called, so it should correct ** 'L->top.p' before calling anything that can run the GC. */ int luaG_traceexec (lua_State *L, const Instruction *pc) { CallInfo *ci = L->ci; lu_byte mask = cast_byte(L->hookmask); const Proto *p = ci_func(ci)->p; int counthook; if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */ ci->u.l.trap = 0; /* don't need to stop again */ return 0; /* turn off 'trap' */ } pc++; /* reference is always next instruction */ ci->u.l.savedpc = pc; /* save 'pc' */ counthook = (mask & LUA_MASKCOUNT) && (--L->hookcount == 0); if (counthook) resethookcount(L); /* reset count */ else if (!(mask & LUA_MASKLINE)) return 1; /* no line hook and count != 0; nothing to be done now */ if (ci->callstatus & CIST_HOOKYIELD) { /* hook yielded last time? */ ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ return 1; /* do not call hook again (VM yielded, so it did not move) */ } if (!luaP_isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */ L->top.p = ci->top.p; /* correct top */ if (counthook) luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */ if (mask & LUA_MASKLINE) { /* 'L->oldpc' may be invalid; use zero in this case */ int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0; int npci = pcRel(pc, p); if (npci <= oldpc || /* call hook when jump back (loop), */ changedline(p, oldpc, npci)) { /* or when enter new line */ int newline = luaG_getfuncline(p, npci); luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */ } L->oldpc = npci; /* 'pc' of last call to line hook */ } if (L->status == LUA_YIELD) { /* did hook yield? */ if (counthook) L->hookcount = 1; /* undo decrement to zero */ ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ luaD_throw(L, LUA_YIELD); } return 1; /* keep 'trap' on */ } /* ** $Id: ldo.c $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #define ldo_c #define LUA_CORE #include "lua.h" #include #include #include #define errorstatus(s) ((s) > LUA_YIELD) /* ** these macros allow user-specific actions when a thread is ** resumed/yielded. */ #if !defined(luai_userstateresume) #define luai_userstateresume(L,n) ((void)L) #endif #if !defined(luai_userstateyield) #define luai_userstateyield(L,n) ((void)L) #endif /* ** {====================================================== ** Error-recovery functions ** ======================================================= */ /* chained list of long jump buffers */ typedef struct lua_longjmp { struct lua_longjmp *previous; jmp_buf b; volatile TStatus status; /* error code */ } lua_longjmp; /* ** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By ** default, Lua handles errors with exceptions when compiling as ** C++ code, with _longjmp/_setjmp when available (POSIX), and with ** longjmp/setjmp otherwise. */ #if !defined(LUAI_THROW) /* { */ #if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */ /* C++ exceptions */ #define LUAI_THROW(L,c) throw(c) static void LUAI_TRY (lua_State *L, lua_longjmp *c, Pfunc f, void *ud) { try { f(L, ud); /* call function protected */ } catch (lua_longjmp *c1) { /* Lua error */ if (c1 != c) /* not the correct level? */ throw; /* rethrow to upper level */ } catch (...) { /* non-Lua exception */ c->status = -1; /* create some error code */ } } #elif defined(LUA_USE_POSIX) /* }{ */ /* in POSIX, use _longjmp/_setjmp (more efficient) */ #define LUAI_THROW(L,c) _longjmp((c)->b, 1) #define LUAI_TRY(L,c,f,ud) if (_setjmp((c)->b) == 0) ((f)(L, ud)) #else /* }{ */ /* ISO C handling with long jumps */ #define LUAI_THROW(L,c) longjmp((c)->b, 1) #define LUAI_TRY(L,c,f,ud) if (setjmp((c)->b) == 0) ((f)(L, ud)) #endif /* } */ #endif /* } */ void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop) { if (errcode == LUA_ERRMEM) { /* memory error? */ setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */ } else { lua_assert(errorstatus(errcode)); /* must be a real error */ lua_assert(!ttisnil(s2v(L->top.p - 1))); /* with a non-nil object */ setobjs2s(L, oldtop, L->top.p - 1); /* move it to 'oldtop' */ } L->top.p = oldtop + 1; /* top goes back to old top plus error object */ } l_noret luaD_throw (lua_State *L, TStatus errcode) { if (L->errorJmp) { /* thread has an error handler? */ L->errorJmp->status = errcode; /* set status */ LUAI_THROW(L, L->errorJmp); /* jump to it */ } else { /* thread has no error handler */ global_State *g = G(L); lua_State *mainth = mainthread(g); errcode = luaE_resetthread(L, errcode); /* close all upvalues */ L->status = errcode; if (mainth->errorJmp) { /* main thread has a handler? */ setobjs2s(L, mainth->top.p++, L->top.p - 1); /* copy error obj. */ luaD_throw(mainth, errcode); /* re-throw in main thread */ } else { /* no handler at all; abort */ if (g->panic) { /* panic function? */ lua_unlock(L); g->panic(L); /* call panic function (last chance to jump out) */ } abort(); } } } l_noret luaD_throwbaselevel (lua_State *L, TStatus errcode) { if (L->errorJmp) { /* unroll error entries up to the first level */ while (L->errorJmp->previous != NULL) L->errorJmp = L->errorJmp->previous; } luaD_throw(L, errcode); } TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { l_uint32 oldnCcalls = L->nCcalls; lua_longjmp lj; lj.status = LUA_OK; lj.previous = L->errorJmp; /* chain new error handler */ L->errorJmp = &lj; LUAI_TRY(L, &lj, f, ud); /* call 'f' catching errors */ L->errorJmp = lj.previous; /* restore old error handler */ L->nCcalls = oldnCcalls; return lj.status; } /* }====================================================== */ /* ** {================================================================== ** Stack reallocation ** =================================================================== */ /* some stack space for error handling */ #define STACKERRSPACE 200 /* ** LUAI_MAXSTACK limits the size of the Lua stack. ** It must fit into INT_MAX/2. */ #if !defined(LUAI_MAXSTACK) #if 1000000 < (INT_MAX / 2) #define LUAI_MAXSTACK 1000000 #else #define LUAI_MAXSTACK (INT_MAX / 2u) #endif #endif /* maximum stack size that respects size_t */ #define MAXSTACK_BYSIZET ((MAX_SIZET / sizeof(StackValue)) - STACKERRSPACE) /* ** Minimum between LUAI_MAXSTACK and MAXSTACK_BYSIZET ** (Maximum size for the stack must respect size_t.) */ #define MAXSTACK cast_int(LUAI_MAXSTACK < MAXSTACK_BYSIZET \ ? LUAI_MAXSTACK : MAXSTACK_BYSIZET) /* stack size with extra space for error handling */ #define ERRORSTACKSIZE (MAXSTACK + STACKERRSPACE) /* raise a stack error while running the message handler */ l_noret luaD_errerr (lua_State *L) { TString *msg = luaS_newliteral(L, "error in error handling"); setsvalue2s(L, L->top.p, msg); L->top.p++; /* assume EXTRA_STACK */ luaD_throw(L, LUA_ERRERR); } /* ** Check whether stack has enough space to run a simple function (such ** as a finalizer): At least BASIC_STACK_SIZE in the Lua stack and ** 2 slots in the C stack. */ int luaD_checkminstack (lua_State *L) { return ((stacksize(L) < MAXSTACK - BASIC_STACK_SIZE) && (getCcalls(L) < LUAI_MAXCCALLS - 2)); } /* ** In ISO C, any pointer use after the pointer has been deallocated is ** undefined behavior. So, before a stack reallocation, all pointers ** should be changed to offsets, and after the reallocation they should ** be changed back to pointers. As during the reallocation the pointers ** are invalid, the reallocation cannot run emergency collections. ** Alternatively, we can use the old address after the deallocation. ** That is not strict ISO C, but seems to work fine everywhere. ** The following macro chooses how strict is the code. */ #if !defined(LUAI_STRICT_ADDRESS) #define LUAI_STRICT_ADDRESS 1 #endif #if LUAI_STRICT_ADDRESS /* ** Change all pointers to the stack into offsets. */ static void relstack (lua_State *L) { CallInfo *ci; UpVal *up; L->top.offset = savestack(L, L->top.p); L->tbclist.offset = savestack(L, L->tbclist.p); for (up = L->openupval; up != NULL; up = up->u.open.next) up->v.offset = savestack(L, uplevel(up)); for (ci = L->ci; ci != NULL; ci = ci->previous) { ci->top.offset = savestack(L, ci->top.p); ci->func.offset = savestack(L, ci->func.p); } } /* ** Change back all offsets into pointers. */ static void correctstack (lua_State *L, StkId oldstack) { CallInfo *ci; UpVal *up; UNUSED(oldstack); L->top.p = restorestack(L, L->top.offset); L->tbclist.p = restorestack(L, L->tbclist.offset); for (up = L->openupval; up != NULL; up = up->u.open.next) up->v.p = s2v(restorestack(L, up->v.offset)); for (ci = L->ci; ci != NULL; ci = ci->previous) { ci->top.p = restorestack(L, ci->top.offset); ci->func.p = restorestack(L, ci->func.offset); if (isLua(ci)) ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */ } } #else /* ** Assume that it is fine to use an address after its deallocation, ** as long as we do not dereference it. */ static void relstack (lua_State *L) { UNUSED(L); } /* do nothing */ /* ** Correct pointers into 'oldstack' to point into 'L->stack'. */ static void correctstack (lua_State *L, StkId oldstack) { CallInfo *ci; UpVal *up; StkId newstack = L->stack.p; if (oldstack == newstack) return; L->top.p = L->top.p - oldstack + newstack; L->tbclist.p = L->tbclist.p - oldstack + newstack; for (up = L->openupval; up != NULL; up = up->u.open.next) up->v.p = s2v(uplevel(up) - oldstack + newstack); for (ci = L->ci; ci != NULL; ci = ci->previous) { ci->top.p = ci->top.p - oldstack + newstack; ci->func.p = ci->func.p - oldstack + newstack; if (isLua(ci)) ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */ } } #endif /* ** Reallocate the stack to a new size, correcting all pointers into it. ** In case of allocation error, raise an error or return false according ** to 'raiseerror'. */ int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) { int oldsize = stacksize(L); int i; StkId newstack; StkId oldstack = L->stack.p; lu_byte oldgcstop = G(L)->gcstopem; lua_assert(newsize <= MAXSTACK || newsize == ERRORSTACKSIZE); relstack(L); /* change pointers to offsets */ G(L)->gcstopem = 1; /* stop emergency collection */ newstack = luaM_reallocvector(L, oldstack, oldsize + EXTRA_STACK, newsize + EXTRA_STACK, StackValue); G(L)->gcstopem = oldgcstop; /* restore emergency collection */ if (l_unlikely(newstack == NULL)) { /* reallocation failed? */ correctstack(L, oldstack); /* change offsets back to pointers */ if (raiseerror) luaM_error(L); else return 0; /* do not raise an error */ } L->stack.p = newstack; correctstack(L, oldstack); /* change offsets back to pointers */ L->stack_last.p = L->stack.p + newsize; for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++) setnilvalue(s2v(newstack + i)); /* erase new segment */ return 1; } /* ** Try to grow the stack by at least 'n' elements. When 'raiseerror' ** is true, raises any error; otherwise, return 0 in case of errors. */ int luaD_growstack (lua_State *L, int n, int raiseerror) { int size = stacksize(L); if (l_unlikely(size > MAXSTACK)) { /* if stack is larger than maximum, thread is already using the extra space reserved for errors, that is, thread is handling a stack error; cannot grow further than that. */ lua_assert(stacksize(L) == ERRORSTACKSIZE); if (raiseerror) luaD_errerr(L); /* stack error inside message handler */ return 0; /* if not 'raiseerror', just signal it */ } else if (n < MAXSTACK) { /* avoids arithmetic overflows */ int newsize = size + (size >> 1); /* tentative new size (size * 1.5) */ int needed = cast_int(L->top.p - L->stack.p) + n; if (newsize > MAXSTACK) /* cannot cross the limit */ newsize = MAXSTACK; if (newsize < needed) /* but must respect what was asked for */ newsize = needed; if (l_likely(newsize <= MAXSTACK)) return luaD_reallocstack(L, newsize, raiseerror); } /* else stack overflow */ /* add extra size to be able to handle the error message */ luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror); if (raiseerror) luaG_runerror(L, "stack overflow"); return 0; } /* ** Compute how much of the stack is being used, by computing the ** maximum top of all call frames in the stack and the current top. */ static int stackinuse (lua_State *L) { CallInfo *ci; int res; StkId lim = L->top.p; for (ci = L->ci; ci != NULL; ci = ci->previous) { if (lim < ci->top.p) lim = ci->top.p; } lua_assert(lim <= L->stack_last.p + EXTRA_STACK); res = cast_int(lim - L->stack.p) + 1; /* part of stack in use */ if (res < LUA_MINSTACK) res = LUA_MINSTACK; /* ensure a minimum size */ return res; } /* ** If stack size is more than 3 times the current use, reduce that size ** to twice the current use. (So, the final stack size is at most 2/3 the ** previous size, and half of its entries are empty.) ** As a particular case, if stack was handling a stack overflow and now ** it is not, 'max' (limited by MAXSTACK) will be smaller than ** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack ** will be reduced to a "regular" size. */ void luaD_shrinkstack (lua_State *L) { int inuse = stackinuse(L); int max = (inuse > MAXSTACK / 3) ? MAXSTACK : inuse * 3; /* if thread is currently not handling a stack overflow and its size is larger than maximum "reasonable" size, shrink it */ if (inuse <= MAXSTACK && stacksize(L) > max) { int nsize = (inuse > MAXSTACK / 2) ? MAXSTACK : inuse * 2; luaD_reallocstack(L, nsize, 0); /* ok if that fails */ } else /* don't change stack */ condmovestack(L,(void)0,(void)0); /* (change only for debugging) */ luaE_shrinkCI(L); /* shrink CI list */ } void luaD_inctop (lua_State *L) { L->top.p++; luaD_checkstack(L, 1); } /* }================================================================== */ /* ** Call a hook for the given event. Make sure there is a hook to be ** called. (Both 'L->hook' and 'L->hookmask', which trigger this ** function, can be changed asynchronously by signals.) */ void luaD_hook (lua_State *L, int event, int line, int ftransfer, int ntransfer) { lua_Hook hook = L->hook; if (hook && L->allowhook) { /* make sure there is a hook */ CallInfo *ci = L->ci; ptrdiff_t top = savestack(L, L->top.p); /* preserve original 'top' */ ptrdiff_t ci_top = savestack(L, ci->top.p); /* idem for 'ci->top' */ lua_Debug ar; ar.event = event; ar.currentline = line; ar.i_ci = ci; L->transferinfo.ftransfer = ftransfer; L->transferinfo.ntransfer = ntransfer; if (isLua(ci) && L->top.p < ci->top.p) L->top.p = ci->top.p; /* protect entire activation register */ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ if (ci->top.p < L->top.p + LUA_MINSTACK) ci->top.p = L->top.p + LUA_MINSTACK; L->allowhook = 0; /* cannot call hooks inside a hook */ ci->callstatus |= CIST_HOOKED; lua_unlock(L); (*hook)(L, &ar); lua_lock(L); lua_assert(!L->allowhook); L->allowhook = 1; ci->top.p = restorestack(L, ci_top); L->top.p = restorestack(L, top); ci->callstatus &= ~CIST_HOOKED; } } /* ** Executes a call hook for Lua functions. This function is called ** whenever 'hookmask' is not zero, so it checks whether call hooks are ** active. */ void luaD_hookcall (lua_State *L, CallInfo *ci) { L->oldpc = 0; /* set 'oldpc' for new function */ if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */ int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL : LUA_HOOKCALL; Proto *p = ci_func(ci)->p; ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ luaD_hook(L, event, -1, 1, p->numparams); ci->u.l.savedpc--; /* correct 'pc' */ } } /* ** Executes a return hook for Lua and C functions and sets/corrects ** 'oldpc'. (Note that this correction is needed by the line hook, so it ** is done even when return hooks are off.) */ static void rethook (lua_State *L, CallInfo *ci, int nres) { if (L->hookmask & LUA_MASKRET) { /* is return hook on? */ StkId firstres = L->top.p - nres; /* index of first result */ int delta = 0; /* correction for vararg functions */ int ftransfer; if (isLua(ci)) { Proto *p = ci_func(ci)->p; if (p->flag & PF_VAHID) delta = ci->u.l.nextraargs + p->numparams + 1; } ci->func.p += delta; /* if vararg, back to virtual 'func' */ ftransfer = cast_int(firstres - ci->func.p); luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */ ci->func.p -= delta; } if (isLua(ci = ci->previous)) L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */ } /* ** Check whether 'func' has a '__call' metafield. If so, put it in the ** stack, below original 'func', so that 'luaD_precall' can call it. ** Raise an error if there is no '__call' metafield. ** Bits CIST_CCMT in status count how many _call metamethods were ** invoked and how many corresponding extra arguments were pushed. ** (This count will be saved in the 'callstatus' of the call). ** Raise an error if this counter overflows. */ static unsigned tryfuncTM (lua_State *L, StkId func, unsigned status) { const TValue *tm; StkId p; tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); if (l_unlikely(ttisnil(tm))) /* no metamethod? */ luaG_callerror(L, s2v(func)); for (p = L->top.p; p > func; p--) /* open space for metamethod */ setobjs2s(L, p, p-1); L->top.p++; /* stack space pre-allocated by the caller */ setobj2s(L, func, tm); /* metamethod is the new function to be called */ if ((status & MAX_CCMT) == MAX_CCMT) /* is counter full? */ luaG_runerror(L, "'__call' chain too long"); return status + (1u << CIST_CCMT); /* increment counter */ } /* Generic case for 'moveresult' */ l_sinline void genmoveresults (lua_State *L, StkId res, int nres, int wanted) { StkId firstresult = L->top.p - nres; /* index of first result */ int i; if (nres > wanted) /* extra results? */ nres = wanted; /* don't need them */ for (i = 0; i < nres; i++) /* move all results to correct place */ setobjs2s(L, res + i, firstresult + i); for (; i < wanted; i++) /* complete wanted number of results */ setnilvalue(s2v(res + i)); L->top.p = res + wanted; /* top points after the last result */ } /* ** Given 'nres' results at 'firstResult', move 'fwanted-1' of them ** to 'res'. Handle most typical cases (zero results for commands, ** one result for expressions, multiple results for tail calls/single ** parameters) separated. The flag CIST_TBC in 'fwanted', if set, ** forces the switch to go to the default case. */ l_sinline void moveresults (lua_State *L, StkId res, int nres, l_uint32 fwanted) { switch (fwanted) { /* handle typical cases separately */ case 0 + 1: /* no values needed */ L->top.p = res; return; case 1 + 1: /* one value needed */ if (nres == 0) /* no results? */ setnilvalue(s2v(res)); /* adjust with nil */ else /* at least one result */ setobjs2s(L, res, L->top.p - nres); /* move it to proper place */ L->top.p = res + 1; return; case LUA_MULTRET + 1: genmoveresults(L, res, nres, nres); /* we want all results */ break; default: { /* two/more results and/or to-be-closed variables */ int wanted = get_nresults(fwanted); if (fwanted & CIST_TBC) { /* to-be-closed variables? */ L->ci->u2.nres = nres; L->ci->callstatus |= CIST_CLSRET; /* in case of yields */ res = luaF_close(L, res, CLOSEKTOP, 1); L->ci->callstatus &= ~CIST_CLSRET; if (L->hookmask) { /* if needed, call hook after '__close's */ ptrdiff_t savedres = savestack(L, res); rethook(L, L->ci, nres); res = restorestack(L, savedres); /* hook can move stack */ } if (wanted == LUA_MULTRET) wanted = nres; /* we want all results */ } genmoveresults(L, res, nres, wanted); break; } } } /* ** Finishes a function call: calls hook if necessary, moves current ** number of results to proper place, and returns to previous call ** info. If function has to close variables, hook must be called after ** that. */ void luaD_poscall (lua_State *L, CallInfo *ci, int nres) { l_uint32 fwanted = ci->callstatus & (CIST_TBC | CIST_NRESULTS); if (l_unlikely(L->hookmask) && !(fwanted & CIST_TBC)) rethook(L, ci, nres); /* move results to proper place */ moveresults(L, ci->func.p, nres, fwanted); /* function cannot be in any of these cases when returning */ lua_assert(!(ci->callstatus & (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_CLSRET))); L->ci = ci->previous; /* back to caller (after closing variables) */ } #define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L)) /* ** Allocate and initialize CallInfo structure. At this point, the ** only valid fields in the call status are number of results, ** CIST_C (if it's a C function), and number of extra arguments. ** (All these bit-fields fit in 16-bit values.) */ l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, unsigned status, StkId top) { CallInfo *ci = L->ci = next_ci(L); /* new frame */ ci->func.p = func; lua_assert((status & ~(CIST_NRESULTS | CIST_C | MAX_CCMT)) == 0); ci->callstatus = status; ci->top.p = top; return ci; } /* ** precall for C functions */ l_sinline int precallC (lua_State *L, StkId func, unsigned status, lua_CFunction f) { int n; /* number of returns */ CallInfo *ci; checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */ L->ci = ci = prepCallInfo(L, func, status | CIST_C, L->top.p + LUA_MINSTACK); lua_assert(ci->top.p <= L->stack_last.p); if (l_unlikely(L->hookmask & LUA_MASKCALL)) { int narg = cast_int(L->top.p - func) - 1; luaD_hook(L, LUA_HOOKCALL, -1, 1, narg); } lua_unlock(L); n = (*f)(L); /* do the actual call */ lua_lock(L); api_checknelems(L, n); luaD_poscall(L, ci, n); return n; } /* ** Prepare a function for a tail call, building its call info on top ** of the current call info. 'narg1' is the number of arguments plus 1 ** (so that it includes the function itself). Return the number of ** results, if it was a C function, or -1 for a Lua function. */ int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1, int delta) { unsigned status = LUA_MULTRET + 1; retry: switch (ttypetag(s2v(func))) { case LUA_VCCL: /* C closure */ return precallC(L, func, status, clCvalue(s2v(func))->f); case LUA_VLCF: /* light C function */ return precallC(L, func, status, fvalue(s2v(func))); case LUA_VLCL: { /* Lua function */ Proto *p = clLvalue(s2v(func))->p; int fsize = p->maxstacksize; /* frame size */ int nfixparams = p->numparams; int i; checkstackp(L, fsize - delta, func); ci->func.p -= delta; /* restore 'func' (if vararg) */ for (i = 0; i < narg1; i++) /* move down function and arguments */ setobjs2s(L, ci->func.p + i, func + i); func = ci->func.p; /* moved-down function */ for (; narg1 <= nfixparams; narg1++) setnilvalue(s2v(func + narg1)); /* complete missing arguments */ ci->top.p = func + 1 + fsize; /* top for new function */ lua_assert(ci->top.p <= L->stack_last.p); ci->u.l.savedpc = p->code; /* starting point */ ci->callstatus |= CIST_TAIL; L->top.p = func + narg1; /* set top */ return -1; } default: { /* not a function */ checkstackp(L, 1, func); /* space for metamethod */ status = tryfuncTM(L, func, status); /* try '__call' metamethod */ narg1++; goto retry; /* try again */ } } } /* ** Prepares the call to a function (C or Lua). For C functions, also do ** the call. The function to be called is at '*func'. The arguments ** are on the stack, right after the function. Returns the CallInfo ** to be executed, if it was a Lua function. Otherwise (a C function) ** returns NULL, with all the results on the stack, starting at the ** original function position. */ CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) { unsigned status = cast_uint(nresults + 1); lua_assert(status <= MAXRESULTS + 1); retry: switch (ttypetag(s2v(func))) { case LUA_VCCL: /* C closure */ precallC(L, func, status, clCvalue(s2v(func))->f); return NULL; case LUA_VLCF: /* light C function */ precallC(L, func, status, fvalue(s2v(func))); return NULL; case LUA_VLCL: { /* Lua function */ CallInfo *ci; Proto *p = clLvalue(s2v(func))->p; int narg = cast_int(L->top.p - func) - 1; /* number of real arguments */ int nfixparams = p->numparams; int fsize = p->maxstacksize; /* frame size */ checkstackp(L, fsize, func); L->ci = ci = prepCallInfo(L, func, status, func + 1 + fsize); ci->u.l.savedpc = p->code; /* starting point */ for (; narg < nfixparams; narg++) setnilvalue(s2v(L->top.p++)); /* complete missing arguments */ lua_assert(ci->top.p <= L->stack_last.p); return ci; } default: { /* not a function */ checkstackp(L, 1, func); /* space for metamethod */ status = tryfuncTM(L, func, status); /* try '__call' metamethod */ goto retry; /* try again with metamethod */ } } } /* ** Call a function (C or Lua) through C. 'inc' can be 1 (increment ** number of recursive invocations in the C stack) or nyci (the same ** plus increment number of non-yieldable calls). ** This function can be called with some use of EXTRA_STACK, so it should ** check the stack before doing anything else. 'luaD_precall' already ** does that. */ l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) { CallInfo *ci; L->nCcalls += inc; if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) { checkstackp(L, 0, func); /* free any use of EXTRA_STACK */ luaE_checkcstack(L); } if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */ ci->callstatus |= CIST_FRESH; /* mark that it is a "fresh" execute */ luaV_execute(L, ci); /* call it */ } L->nCcalls -= inc; } /* ** External interface for 'ccall' */ void luaD_call (lua_State *L, StkId func, int nResults) { ccall(L, func, nResults, 1); } /* ** Similar to 'luaD_call', but does not allow yields during the call. */ void luaD_callnoyield (lua_State *L, StkId func, int nResults) { ccall(L, func, nResults, nyci); } /* ** Finish the job of 'lua_pcallk' after it was interrupted by an yield. ** (The caller, 'finishCcall', does the final call to 'adjustresults'.) ** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'. ** If a '__close' method yields here, eventually control will be back ** to 'finishCcall' (when that '__close' method finally returns) and ** 'finishpcallk' will run again and close any still pending '__close' ** methods. Similarly, if a '__close' method errs, 'precover' calls ** 'unroll' which calls ''finishCcall' and we are back here again, to ** close any pending '__close' methods. ** Note that, up to the call to 'luaF_close', the corresponding ** 'CallInfo' is not modified, so that this repeated run works like the ** first one (except that it has at least one less '__close' to do). In ** particular, field CIST_RECST preserves the error status across these ** multiple runs, changing only if there is a new error. */ static TStatus finishpcallk (lua_State *L, CallInfo *ci) { TStatus status = getcistrecst(ci); /* get original status */ if (l_likely(status == LUA_OK)) /* no error? */ status = LUA_YIELD; /* was interrupted by an yield */ else { /* error */ StkId func = restorestack(L, ci->u2.funcidx); L->allowhook = getoah(ci); /* restore 'allowhook' */ func = luaF_close(L, func, status, 1); /* can yield or raise an error */ luaD_seterrorobj(L, status, func); luaD_shrinkstack(L); /* restore stack size in case of overflow */ setcistrecst(ci, LUA_OK); /* clear original status */ } ci->callstatus &= ~CIST_YPCALL; L->errfunc = ci->u.c.old_errfunc; /* if it is here, there were errors or yields; unlike 'lua_pcallk', do not change status */ return status; } /* ** Completes the execution of a C function interrupted by an yield. ** The interruption must have happened while the function was either ** closing its tbc variables in 'moveresults' or executing ** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes ** 'luaD_poscall'. In the second case, the call to 'finishpcallk' ** finishes the interrupted execution of 'lua_pcallk'. After that, it ** calls the continuation of the interrupted function and finally it ** completes the job of the 'luaD_call' that called the function. In ** the call to 'adjustresults', we do not know the number of results ** of the function called by 'lua_callk'/'lua_pcallk', so we are ** conservative and use LUA_MULTRET (always adjust). */ static void finishCcall (lua_State *L, CallInfo *ci) { int n; /* actual number of results from C function */ if (ci->callstatus & CIST_CLSRET) { /* was closing TBC variable? */ lua_assert(ci->callstatus & CIST_TBC); n = ci->u2.nres; /* just redo 'luaD_poscall' */ /* don't need to reset CIST_CLSRET, as it will be set again anyway */ } else { TStatus status = LUA_YIELD; /* default if there were no errors */ lua_KFunction kf = ci->u.c.k; /* continuation function */ /* must have a continuation and must be able to call it */ lua_assert(kf != NULL && yieldable(L)); if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */ status = finishpcallk(L, ci); /* finish it */ adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */ lua_unlock(L); n = (*kf)(L, APIstatus(status), ci->u.c.ctx); /* call continuation */ lua_lock(L); api_checknelems(L, n); } luaD_poscall(L, ci, n); /* finish 'luaD_call' */ } /* ** Executes "full continuation" (everything in the stack) of a ** previously interrupted coroutine until the stack is empty (or another ** interruption long-jumps out of the loop). */ static void unroll (lua_State *L, void *ud) { CallInfo *ci; UNUSED(ud); while ((ci = L->ci) != &L->base_ci) { /* something in the stack */ if (!isLua(ci)) /* C function? */ finishCcall(L, ci); /* complete its execution */ else { /* Lua function */ luaV_finishOp(L); /* finish interrupted instruction */ luaV_execute(L, ci); /* execute down to higher C 'boundary' */ } } } /* ** Try to find a suspended protected call (a "recover point") for the ** given thread. */ static CallInfo *findpcall (lua_State *L) { CallInfo *ci; for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */ if (ci->callstatus & CIST_YPCALL) return ci; } return NULL; /* no pending pcall */ } /* ** Signal an error in the call to 'lua_resume', not in the execution ** of the coroutine itself. (Such errors should not be handled by any ** coroutine error handler and should not kill the coroutine.) */ static int resume_error (lua_State *L, const char *msg, int narg) { api_checkpop(L, narg); L->top.p -= narg; /* remove args from the stack */ setsvalue2s(L, L->top.p, luaS_new(L, msg)); /* push error message */ api_incr_top(L); lua_unlock(L); return LUA_ERRRUN; } /* ** Do the work for 'lua_resume' in protected mode. Most of the work ** depends on the status of the coroutine: initial state, suspended ** inside a hook, or regularly suspended (optionally with a continuation ** function), plus erroneous cases: non-suspended coroutine or dead ** coroutine. */ static void resume (lua_State *L, void *ud) { int n = *(cast(int*, ud)); /* number of arguments */ StkId firstArg = L->top.p - n; /* first argument */ CallInfo *ci = L->ci; if (L->status == LUA_OK) /* starting a coroutine? */ ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */ else { /* resuming from previous yield */ lua_assert(L->status == LUA_YIELD); L->status = LUA_OK; /* mark that it is running (again) */ if (isLua(ci)) { /* yielded inside a hook? */ /* undo increment made by 'luaG_traceexec': instruction was not executed yet */ lua_assert(ci->callstatus & CIST_HOOKYIELD); ci->u.l.savedpc--; L->top.p = firstArg; /* discard arguments */ luaV_execute(L, ci); /* just continue running Lua code */ } else { /* 'common' yield */ if (ci->u.c.k != NULL) { /* does it have a continuation function? */ lua_unlock(L); n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */ lua_lock(L); api_checknelems(L, n); } luaD_poscall(L, ci, n); /* finish 'luaD_call' */ } unroll(L, NULL); /* run continuation */ } } /* ** Unrolls a coroutine in protected mode while there are recoverable ** errors, that is, errors inside a protected call. (Any error ** interrupts 'unroll', and this loop protects it again so it can ** continue.) Stops with a normal end (status == LUA_OK), an yield ** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't ** find a recover point). */ static TStatus precover (lua_State *L, TStatus status) { CallInfo *ci; while (errorstatus(status) && (ci = findpcall(L)) != NULL) { L->ci = ci; /* go down to recovery functions */ setcistrecst(ci, status); /* status to finish 'pcall' */ status = luaD_rawrunprotected(L, unroll, NULL); } return status; } LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs, int *nresults) { TStatus status; lua_lock(L); if (L->status == LUA_OK) { /* may be starting a coroutine */ if (L->ci != &L->base_ci) /* not in base level? */ return resume_error(L, "cannot resume non-suspended coroutine", nargs); else if (L->top.p - (L->ci->func.p + 1) == nargs) /* no function? */ return resume_error(L, "cannot resume dead coroutine", nargs); } else if (L->status != LUA_YIELD) /* ended with errors? */ return resume_error(L, "cannot resume dead coroutine", nargs); L->nCcalls = (from) ? getCcalls(from) : 0; if (getCcalls(L) >= LUAI_MAXCCALLS) return resume_error(L, "C stack overflow", nargs); L->nCcalls++; luai_userstateresume(L, nargs); api_checkpop(L, (L->status == LUA_OK) ? nargs + 1 : nargs); status = luaD_rawrunprotected(L, resume, &nargs); /* continue running after recoverable errors */ status = precover(L, status); if (l_likely(!errorstatus(status))) lua_assert(status == L->status); /* normal end or yield */ else { /* unrecoverable error */ L->status = status; /* mark thread as 'dead' */ luaD_seterrorobj(L, status, L->top.p); /* push error message */ L->ci->top.p = L->top.p; } *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield : cast_int(L->top.p - (L->ci->func.p + 1)); lua_unlock(L); return APIstatus(status); } LUA_API int lua_isyieldable (lua_State *L) { return yieldable(L); } LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k) { CallInfo *ci; luai_userstateyield(L, nresults); lua_lock(L); ci = L->ci; api_checkpop(L, nresults); if (l_unlikely(!yieldable(L))) { if (L != mainthread(G(L))) luaG_runerror(L, "attempt to yield across a C-call boundary"); else luaG_runerror(L, "attempt to yield from outside a coroutine"); } L->status = LUA_YIELD; ci->u2.nyield = nresults; /* save number of results */ if (isLua(ci)) { /* inside a hook? */ lua_assert(!isLuacode(ci)); api_check(L, nresults == 0, "hooks cannot yield values"); api_check(L, k == NULL, "hooks cannot continue after yielding"); } else { if ((ci->u.c.k = k) != NULL) /* is there a continuation? */ ci->u.c.ctx = ctx; /* save context */ luaD_throw(L, LUA_YIELD); } lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */ lua_unlock(L); return 0; /* return to 'luaD_hook' */ } /* ** Auxiliary structure to call 'luaF_close' in protected mode. */ struct CloseP { StkId level; TStatus status; }; /* ** Auxiliary function to call 'luaF_close' in protected mode. */ static void closepaux (lua_State *L, void *ud) { struct CloseP *pcl = cast(struct CloseP *, ud); luaF_close(L, pcl->level, pcl->status, 0); } /* ** Calls 'luaF_close' in protected mode. Return the original status ** or, in case of errors, the new status. */ TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level, TStatus status) { CallInfo *old_ci = L->ci; lu_byte old_allowhooks = L->allowhook; for (;;) { /* keep closing upvalues until no more errors */ struct CloseP pcl; pcl.level = restorestack(L, level); pcl.status = status; status = luaD_rawrunprotected(L, &closepaux, &pcl); if (l_likely(status == LUA_OK)) /* no more errors? */ return pcl.status; else { /* an error occurred; restore saved state and repeat */ L->ci = old_ci; L->allowhook = old_allowhooks; } } } /* ** Call the C function 'func' in protected mode, restoring basic ** thread information ('allowhook', etc.) and in particular ** its stack level in case of errors. */ TStatus luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t old_top, ptrdiff_t ef) { TStatus status; CallInfo *old_ci = L->ci; lu_byte old_allowhooks = L->allowhook; ptrdiff_t old_errfunc = L->errfunc; L->errfunc = ef; status = luaD_rawrunprotected(L, func, u); if (l_unlikely(status != LUA_OK)) { /* an error occurred? */ L->ci = old_ci; L->allowhook = old_allowhooks; status = luaD_closeprotected(L, old_top, status); luaD_seterrorobj(L, status, restorestack(L, old_top)); luaD_shrinkstack(L); /* restore stack size in case of overflow */ } L->errfunc = old_errfunc; return status; } /* ** Execute a protected parser. */ struct SParser { /* data to 'f_parser' */ ZIO *z; Mbuffer buff; /* dynamic structure used by the scanner */ Dyndata dyd; /* dynamic structures used by the parser */ const char *mode; const char *name; }; static void checkmode (lua_State *L, const char *mode, const char *x) { if (strchr(mode, x[0]) == NULL) { luaO_pushfstring(L, "attempt to load a %s chunk (mode is '%s')", x, mode); luaD_throw(L, LUA_ERRSYNTAX); } } static void f_parser (lua_State *L, void *ud) { LClosure *cl; struct SParser *p = cast(struct SParser *, ud); const char *mode = p->mode ? p->mode : "bt"; int c = zgetc(p->z); /* read first character */ if (c == LUA_SIGNATURE[0]) { int fixed = 0; if (strchr(mode, 'B') != NULL) fixed = 1; else checkmode(L, mode, "binary"); cl = luaU_undump(L, p->z, p->name, fixed); } else { checkmode(L, mode, "text"); cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); } lua_assert(cl->nupvalues == cl->p->sizeupvalues); luaF_initupvals(L, cl); } TStatus luaD_protectedparser (lua_State *L, ZIO *z, const char *name, const char *mode) { struct SParser p; TStatus status; incnny(L); /* cannot yield during parsing */ p.z = z; p.name = name; p.mode = mode; p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0; p.dyd.gt.arr = NULL; p.dyd.gt.size = 0; p.dyd.label.arr = NULL; p.dyd.label.size = 0; luaZ_initbuffer(L, &p.buff); status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc); luaZ_freebuffer(L, &p.buff); luaM_freearray(L, p.dyd.actvar.arr, cast_sizet(p.dyd.actvar.size)); luaM_freearray(L, p.dyd.gt.arr, cast_sizet(p.dyd.gt.size)); luaM_freearray(L, p.dyd.label.arr, cast_sizet(p.dyd.label.size)); decnny(L); return status; } /* ** $Id: ldump.c $ ** save precompiled Lua chunks ** See Copyright Notice in lua.h */ #define ldump_c #define LUA_CORE #include #include #include "lua.h" typedef struct { lua_State *L; lua_Writer writer; void *data; size_t offset; /* current position relative to beginning of dump */ int strip; int status; Table *h; /* table to track saved strings */ lua_Unsigned nstr; /* counter for counting saved strings */ } DumpState; /* ** All high-level dumps go through dumpVector; you can change it to ** change the endianness of the result */ #define dumpVector(D,v,n) dumpBlock(D,v,(n)*sizeof((v)[0])) #define dumpLiteral(D, s) dumpBlock(D,s,sizeof(s) - sizeof(char)) /* ** Dump the block of memory pointed by 'b' with given 'size'. ** 'b' should not be NULL, except for the last call signaling the end ** of the dump. */ static void dumpBlock (DumpState *D, const void *b, size_t size) { if (D->status == 0) { /* do not write anything after an error */ lua_unlock(D->L); D->status = (*D->writer)(D->L, b, size, D->data); lua_lock(D->L); D->offset += size; } } /* ** Dump enough zeros to ensure that current position is a multiple of ** 'align'. */ static void dumpAlign (DumpState *D, unsigned align) { unsigned padding = align - cast_uint(D->offset % align); if (padding < align) { /* padding == align means no padding */ static lua_Integer paddingContent = 0; lua_assert(align <= sizeof(lua_Integer)); dumpBlock(D, &paddingContent, padding); } lua_assert(D->offset % align == 0); } #define dumpVar(D,x) dumpVector(D,&x,1) static void dumpByte (DumpState *D, int y) { lu_byte x = (lu_byte)y; dumpVar(D, x); } /* ** size for 'dumpVarint' buffer: each byte can store up to 7 bits. ** (The "+6" rounds up the division.) */ #define DIBS ((l_numbits(lua_Unsigned) + 6) / 7) /* ** Dumps an unsigned integer using the MSB Varint encoding */ static void dumpVarint (DumpState *D, lua_Unsigned x) { lu_byte buff[DIBS]; unsigned n = 1; buff[DIBS - 1] = x & 0x7f; /* fill least-significant byte */ while ((x >>= 7) != 0) /* fill other bytes in reverse order */ buff[DIBS - (++n)] = cast_byte((x & 0x7f) | 0x80); dumpVector(D, buff + DIBS - n, n); } static void dumpSize (DumpState *D, size_t sz) { dumpVarint(D, cast(lua_Unsigned, sz)); } static void dumpInt (DumpState *D, int x) { lua_assert(x >= 0); dumpVarint(D, cast_uint(x)); } static void dumpNumber (DumpState *D, lua_Number x) { dumpVar(D, x); } /* ** Signed integers are coded to keep small values small. (Coding -1 as ** 0xfff...fff would use too many bytes to save a quite common value.) ** A non-negative x is coded as 2x; a negative x is coded as -2x - 1. ** (0 => 0; -1 => 1; 1 => 2; -2 => 3; 2 => 4; ...) */ static void dumpInteger (DumpState *D, lua_Integer x) { lua_Unsigned cx = (x >= 0) ? 2u * l_castS2U(x) : (2u * ~l_castS2U(x)) + 1; dumpVarint(D, cx); } /* ** Dump a String. First dump its "size": ** size==0 is followed by an index and means "reuse saved string with ** that index"; index==0 means NULL. ** size>=1 is followed by the string contents with real size==size-1 and ** means that string, which will be saved with the next available index. ** The real size does not include the ending '\0' (which is not dumped), ** so adding 1 to it cannot overflow a size_t. */ static void dumpString (DumpState *D, TString *ts) { if (ts == NULL) { dumpVarint(D, 0); /* will "reuse" NULL */ dumpVarint(D, 0); /* special index for NULL */ } else { TValue idx; int tag = luaH_getstr(D->h, ts, &idx); if (!tagisempty(tag)) { /* string already saved? */ dumpVarint(D, 0); /* reuse a saved string */ dumpVarint(D, l_castS2U(ivalue(&idx))); /* index of saved string */ } else { /* must write and save the string */ TValue key, value; /* to save the string in the hash */ size_t size; const char *s = getlstr(ts, size); dumpSize(D, size + 1); dumpVector(D, s, size + 1); /* include ending '\0' */ D->nstr++; /* one more saved string */ setsvalue(D->L, &key, ts); /* the string is the key */ setivalue(&value, l_castU2S(D->nstr)); /* its index is the value */ luaH_set(D->L, D->h, &key, &value); /* h[ts] = nstr */ /* integer value does not need barrier */ } } } static void dumpCode (DumpState *D, const Proto *f) { dumpInt(D, f->sizecode); dumpAlign(D, sizeof(f->code[0])); lua_assert(f->code != NULL); dumpVector(D, f->code, cast_uint(f->sizecode)); } static void dumpFunction (DumpState *D, const Proto *f); static void dumpConstants (DumpState *D, const Proto *f) { int i; int n = f->sizek; dumpInt(D, n); for (i = 0; i < n; i++) { const TValue *o = &f->k[i]; int tt = ttypetag(o); dumpByte(D, tt); switch (tt) { case LUA_VNUMFLT: dumpNumber(D, fltvalue(o)); break; case LUA_VNUMINT: dumpInteger(D, ivalue(o)); break; case LUA_VSHRSTR: case LUA_VLNGSTR: dumpString(D, tsvalue(o)); break; default: lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE); } } } static void dumpProtos (DumpState *D, const Proto *f) { int i; int n = f->sizep; dumpInt(D, n); for (i = 0; i < n; i++) dumpFunction(D, f->p[i]); } static void dumpUpvalues (DumpState *D, const Proto *f) { int i, n = f->sizeupvalues; dumpInt(D, n); for (i = 0; i < n; i++) { dumpByte(D, f->upvalues[i].instack); dumpByte(D, f->upvalues[i].idx); dumpByte(D, f->upvalues[i].kind); } } static void dumpDebug (DumpState *D, const Proto *f) { int i, n; n = (D->strip) ? 0 : f->sizelineinfo; dumpInt(D, n); if (f->lineinfo != NULL) dumpVector(D, f->lineinfo, cast_uint(n)); n = (D->strip) ? 0 : f->sizeabslineinfo; dumpInt(D, n); if (n > 0) { /* 'abslineinfo' is an array of structures of int's */ dumpAlign(D, sizeof(int)); dumpVector(D, f->abslineinfo, cast_uint(n)); } n = (D->strip) ? 0 : f->sizelocvars; dumpInt(D, n); for (i = 0; i < n; i++) { dumpString(D, f->locvars[i].varname); dumpInt(D, f->locvars[i].startpc); dumpInt(D, f->locvars[i].endpc); } n = (D->strip) ? 0 : f->sizeupvalues; dumpInt(D, n); for (i = 0; i < n; i++) dumpString(D, f->upvalues[i].name); } static void dumpFunction (DumpState *D, const Proto *f) { dumpInt(D, f->linedefined); dumpInt(D, f->lastlinedefined); dumpByte(D, f->numparams); dumpByte(D, f->flag); dumpByte(D, f->maxstacksize); dumpCode(D, f); dumpConstants(D, f); dumpUpvalues(D, f); dumpProtos(D, f); dumpString(D, D->strip ? NULL : f->source); dumpDebug(D, f); } #define dumpNumInfo(D, tvar, value) \ { tvar i = value; dumpByte(D, sizeof(tvar)); dumpVar(D, i); } static void dumpHeader (DumpState *D) { dumpLiteral(D, LUA_SIGNATURE); dumpByte(D, LUAC_VERSION); dumpByte(D, LUAC_FORMAT); dumpLiteral(D, LUAC_DATA); dumpNumInfo(D, int, LUAC_INT); dumpNumInfo(D, Instruction, LUAC_INST); dumpNumInfo(D, lua_Integer, LUAC_INT); dumpNumInfo(D, lua_Number, LUAC_NUM); } /* ** dump Lua function as precompiled chunk */ int luaU_dump (lua_State *L, const Proto *f, lua_Writer w, void *data, int strip) { DumpState D; D.h = luaH_new(L); /* aux. table to keep strings already dumped */ sethvalue2s(L, L->top.p, D.h); /* anchor it */ L->top.p++; D.L = L; D.writer = w; D.offset = 0; D.data = data; D.strip = strip; D.status = 0; D.nstr = 0; dumpHeader(&D); dumpByte(&D, f->sizeupvalues); dumpFunction(&D, f); dumpBlock(&D, NULL, 0); /* signal end of dump */ return D.status; } /* ** $Id: lfunc.c $ ** Auxiliary functions to manipulate prototypes and closures ** See Copyright Notice in lua.h */ #define lfunc_c #define LUA_CORE #include #include "lua.h" CClosure *luaF_newCclosure (lua_State *L, int nupvals) { GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals)); CClosure *c = gco2ccl(o); c->nupvalues = cast_byte(nupvals); return c; } LClosure *luaF_newLclosure (lua_State *L, int nupvals) { GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals)); LClosure *c = gco2lcl(o); c->p = NULL; c->nupvalues = cast_byte(nupvals); while (nupvals--) c->upvals[nupvals] = NULL; return c; } /* ** fill a closure with new closed upvalues */ void luaF_initupvals (lua_State *L, LClosure *cl) { int i; for (i = 0; i < cl->nupvalues; i++) { GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal)); UpVal *uv = gco2upv(o); uv->v.p = &uv->u.value; /* make it closed */ setnilvalue(uv->v.p); cl->upvals[i] = uv; luaC_objbarrier(L, cl, uv); } } /* ** Create a new upvalue at the given level, and link it to the list of ** open upvalues of 'L' after entry 'prev'. **/ static UpVal *newupval (lua_State *L, StkId level, UpVal **prev) { GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal)); UpVal *uv = gco2upv(o); UpVal *next = *prev; uv->v.p = s2v(level); /* current value lives in the stack */ uv->u.open.next = next; /* link it to list of open upvalues */ uv->u.open.previous = prev; if (next) next->u.open.previous = &uv->u.open.next; *prev = uv; if (!isintwups(L)) { /* thread not in list of threads with upvalues? */ L->twups = G(L)->twups; /* link it to the list */ G(L)->twups = L; } return uv; } /* ** Find and reuse, or create if it does not exist, an upvalue ** at the given level. */ UpVal *luaF_findupval (lua_State *L, StkId level) { UpVal **pp = &L->openupval; UpVal *p; lua_assert(isintwups(L) || L->openupval == NULL); while ((p = *pp) != NULL && uplevel(p) >= level) { /* search for it */ lua_assert(!isdead(G(L), p)); if (uplevel(p) == level) /* corresponding upvalue? */ return p; /* return it */ pp = &p->u.open.next; } /* not found: create a new upvalue after 'pp' */ return newupval(L, level, pp); } /* ** Call closing method for object 'obj' with error object 'err'. The ** boolean 'yy' controls whether the call is yieldable. ** (This function assumes EXTRA_STACK.) */ static void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) { StkId top = L->top.p; StkId func = top; const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE); setobj2s(L, top++, tm); /* will call metamethod... */ setobj2s(L, top++, obj); /* with 'self' as the 1st argument */ if (err != NULL) /* if there was an error... */ setobj2s(L, top++, err); /* then error object will be 2nd argument */ L->top.p = top; /* add function and arguments */ if (yy) luaD_call(L, func, 0); else luaD_callnoyield(L, func, 0); } /* ** Check whether object at given level has a close metamethod and raise ** an error if not. */ static void checkclosemth (lua_State *L, StkId level) { const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE); if (ttisnil(tm)) { /* no metamethod? */ int idx = cast_int(level - L->ci->func.p); /* variable index */ const char *vname = luaG_findlocal(L, L->ci, idx, NULL); if (vname == NULL) vname = "?"; luaG_runerror(L, "variable '%s' got a non-closable value", vname); } } /* ** Prepare and call a closing method. ** If status is CLOSEKTOP, the call to the closing method will be pushed ** at the top of the stack. Otherwise, values can be pushed right after ** the 'level' of the upvalue being closed, as everything after that ** won't be used again. */ static void prepcallclosemth (lua_State *L, StkId level, TStatus status, int yy) { TValue *uv = s2v(level); /* value being closed */ TValue *errobj; switch (status) { case LUA_OK: L->top.p = level + 1; /* call will be at this level */ /* FALLTHROUGH */ case CLOSEKTOP: /* don't need to change top */ errobj = NULL; /* no error object */ break; default: /* 'luaD_seterrorobj' will set top to level + 2 */ errobj = s2v(level + 1); /* error object goes after 'uv' */ luaD_seterrorobj(L, status, level + 1); /* set error object */ break; } callclosemethod(L, uv, errobj, yy); } /* Maximum value for deltas in 'tbclist' */ #define MAXDELTA USHRT_MAX /* ** Insert a variable in the list of to-be-closed variables. */ void luaF_newtbcupval (lua_State *L, StkId level) { lua_assert(level > L->tbclist.p); if (l_isfalse(s2v(level))) return; /* false doesn't need to be closed */ checkclosemth(L, level); /* value must have a close method */ while (cast_uint(level - L->tbclist.p) > MAXDELTA) { L->tbclist.p += MAXDELTA; /* create a dummy node at maximum delta */ L->tbclist.p->tbclist.delta = 0; } level->tbclist.delta = cast(unsigned short, level - L->tbclist.p); L->tbclist.p = level; } void luaF_unlinkupval (UpVal *uv) { lua_assert(upisopen(uv)); *uv->u.open.previous = uv->u.open.next; if (uv->u.open.next) uv->u.open.next->u.open.previous = uv->u.open.previous; } /* ** Close all upvalues up to the given stack level. */ void luaF_closeupval (lua_State *L, StkId level) { UpVal *uv; while ((uv = L->openupval) != NULL && uplevel(uv) >= level) { TValue *slot = &uv->u.value; /* new position for value */ lua_assert(uplevel(uv) < L->top.p); luaF_unlinkupval(uv); /* remove upvalue from 'openupval' list */ setobj(L, slot, uv->v.p); /* move value to upvalue slot */ uv->v.p = slot; /* now current value lives here */ if (!iswhite(uv)) { /* neither white nor dead? */ nw2black(uv); /* closed upvalues cannot be gray */ luaC_barrier(L, uv, slot); } } } /* ** Remove first element from the tbclist plus its dummy nodes. */ static void poptbclist (lua_State *L) { StkId tbc = L->tbclist.p; lua_assert(tbc->tbclist.delta > 0); /* first element cannot be dummy */ tbc -= tbc->tbclist.delta; while (tbc > L->stack.p && tbc->tbclist.delta == 0) tbc -= MAXDELTA; /* remove dummy nodes */ L->tbclist.p = tbc; } /* ** Close all upvalues and to-be-closed variables up to the given stack ** level. Return restored 'level'. */ StkId luaF_close (lua_State *L, StkId level, TStatus status, int yy) { ptrdiff_t levelrel = savestack(L, level); luaF_closeupval(L, level); /* first, close the upvalues */ while (L->tbclist.p >= level) { /* traverse tbc's down to that level */ StkId tbc = L->tbclist.p; /* get variable index */ poptbclist(L); /* remove it from list */ prepcallclosemth(L, tbc, status, yy); /* close variable */ level = restorestack(L, levelrel); } return level; } Proto *luaF_newproto (lua_State *L) { GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto)); Proto *f = gco2p(o); f->k = NULL; f->sizek = 0; f->p = NULL; f->sizep = 0; f->code = NULL; f->sizecode = 0; f->lineinfo = NULL; f->sizelineinfo = 0; f->abslineinfo = NULL; f->sizeabslineinfo = 0; f->upvalues = NULL; f->sizeupvalues = 0; f->numparams = 0; f->flag = 0; f->maxstacksize = 0; f->locvars = NULL; f->sizelocvars = 0; f->linedefined = 0; f->lastlinedefined = 0; f->source = NULL; return f; } lu_mem luaF_protosize (Proto *p) { lu_mem sz = cast(lu_mem, sizeof(Proto)) + cast_uint(p->sizep) * sizeof(Proto*) + cast_uint(p->sizek) * sizeof(TValue) + cast_uint(p->sizelocvars) * sizeof(LocVar) + cast_uint(p->sizeupvalues) * sizeof(Upvaldesc); if (!(p->flag & PF_FIXED)) { sz += cast_uint(p->sizecode) * sizeof(Instruction); sz += cast_uint(p->sizelineinfo) * sizeof(lu_byte); sz += cast_uint(p->sizeabslineinfo) * sizeof(AbsLineInfo); } return sz; } void luaF_freeproto (lua_State *L, Proto *f) { if (!(f->flag & PF_FIXED)) { luaM_freearray(L, f->code, cast_sizet(f->sizecode)); luaM_freearray(L, f->lineinfo, cast_sizet(f->sizelineinfo)); luaM_freearray(L, f->abslineinfo, cast_sizet(f->sizeabslineinfo)); } luaM_freearray(L, f->p, cast_sizet(f->sizep)); luaM_freearray(L, f->k, cast_sizet(f->sizek)); luaM_freearray(L, f->locvars, cast_sizet(f->sizelocvars)); luaM_freearray(L, f->upvalues, cast_sizet(f->sizeupvalues)); luaM_free(L, f); } /* ** Look for n-th local variable at line 'line' in function 'func'. ** Returns NULL if not found. */ const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { int i; for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { if (pc < f->locvars[i].endpc) { /* is variable active? */ local_number--; if (local_number == 0) return getstr(f->locvars[i].varname); } } return NULL; /* not found */ } /* ** $Id: lgc.c $ ** Garbage Collector ** See Copyright Notice in lua.h */ #define lgc_c #define LUA_CORE #include #include "lua.h" /* ** Maximum number of elements to sweep in each single step. ** (Large enough to dissipate fixed overheads but small enough ** to allow small steps for the collector.) */ #define GCSWEEPMAX 20 /* ** Cost (in work units) of running one finalizer. */ #define CWUFIN 10 /* mask with all color bits */ #define maskcolors (bitmask(BLACKBIT) | WHITEBITS) /* mask with all GC bits */ #define maskgcbits (maskcolors | AGEBITS) /* macro to erase all color bits then set only the current white bit */ #define makewhite(g,x) \ (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g))) /* make an object gray (neither white nor black) */ #define set2gray(x) resetbits(x->marked, maskcolors) /* make an object black (coming from any color) */ #define set2black(x) \ (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT))) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n))) /* ** Protected access to objects in values */ #define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL) /* ** Access to collectable objects in array part of tables */ #define gcvalarr(t,i) \ ((*getArrTag(t,i) & BIT_ISCOLLECTABLE) ? getArrVal(t,i)->gc : NULL) #define markvalue(g,o) { checkliveness(mainthread(g),o); \ if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } #define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); } #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); } /* ** mark an object that can be NULL (either because it is really optional, ** or it was stripped as debug info, or inside an uncompleted structure) */ #define markobjectN(g,t) { if (t) markobject(g,t); } static void reallymarkobject (global_State *g, GCObject *o); static void atomic (lua_State *L); static void entersweep (lua_State *L); /* ** {====================================================== ** Generic functions ** ======================================================= */ /* ** one after last element in a hash array */ #define gnodelast(h) gnode(h, cast_sizet(sizenode(h))) static l_mem objsize (GCObject *o) { lu_mem res; switch (o->tt) { case LUA_VTABLE: { res = luaH_size(gco2t(o)); break; } case LUA_VLCL: { LClosure *cl = gco2lcl(o); res = sizeLclosure(cl->nupvalues); break; } case LUA_VCCL: { CClosure *cl = gco2ccl(o); res = sizeCclosure(cl->nupvalues); break; } case LUA_VUSERDATA: { Udata *u = gco2u(o); res = sizeudata(u->nuvalue, u->len); break; } case LUA_VPROTO: { res = luaF_protosize(gco2p(o)); break; } case LUA_VTHREAD: { res = luaE_threadsize(gco2th(o)); break; } case LUA_VSHRSTR: { TString *ts = gco2ts(o); res = sizestrshr(cast_uint(ts->shrlen)); break; } case LUA_VLNGSTR: { TString *ts = gco2ts(o); res = luaS_sizelngstr(ts->u.lnglen, ts->shrlen); break; } case LUA_VUPVAL: { res = sizeof(UpVal); break; } default: res = 0; lua_assert(0); } return cast(l_mem, res); } static GCObject **getgclist (GCObject *o) { switch (o->tt) { case LUA_VTABLE: return &gco2t(o)->gclist; case LUA_VLCL: return &gco2lcl(o)->gclist; case LUA_VCCL: return &gco2ccl(o)->gclist; case LUA_VTHREAD: return &gco2th(o)->gclist; case LUA_VPROTO: return &gco2p(o)->gclist; case LUA_VUSERDATA: { Udata *u = gco2u(o); lua_assert(u->nuvalue > 0); return &u->gclist; } default: lua_assert(0); return 0; } } /* ** Link a collectable object 'o' with a known type into the list 'p'. ** (Must be a macro to access the 'gclist' field in different types.) */ #define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p)) static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) { lua_assert(!isgray(o)); /* cannot be in a gray list */ *pnext = *list; *list = o; set2gray(o); /* now it is */ } /* ** Link a generic collectable object 'o' into the list 'p'. */ #define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p)) /* ** Clear keys for empty entries in tables. If entry is empty, mark its ** entry as dead. This allows the collection of the key, but keeps its ** entry in the table: its removal could break a chain and could break ** a table traversal. Other places never manipulate dead keys, because ** its associated empty value is enough to signal that the entry is ** logically empty. */ static void clearkey (Node *n) { lua_assert(isempty(gval(n))); if (keyiscollectable(n)) setdeadkey(n); /* unused key; remove it */ } /* ** tells whether a key or value can be cleared from a weak ** table. Non-collectable objects are never removed from weak ** tables. Strings behave as 'values', so are never removed too. for ** other objects: if really collected, cannot keep them; for objects ** being finalized, keep them in keys, but not in values */ static int iscleared (global_State *g, const GCObject *o) { if (o == NULL) return 0; /* non-collectable value */ else if (novariant(o->tt) == LUA_TSTRING) { markobject(g, o); /* strings are 'values', so are never weak */ return 0; } else return iswhite(o); } /* ** Barrier that moves collector forward, that is, marks the white object ** 'v' being pointed by the black object 'o'. In the generational ** mode, 'v' must also become old, if 'o' is old; however, it cannot ** be changed directly to OLD, because it may still point to non-old ** objects. So, it is marked as OLD0. In the next cycle it will become ** OLD1, and in the next it will finally become OLD (regular old). By ** then, any object it points to will also be old. If called in the ** incremental sweep phase, it clears the black object to white (sweep ** it) to avoid other barrier calls for this same object. (That cannot ** be done is generational mode, as its sweep does not distinguish ** white from dead.) */ void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { global_State *g = G(L); lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); if (keepinvariant(g)) { /* must keep invariant? */ reallymarkobject(g, v); /* restore invariant */ if (isold(o)) { lua_assert(!isold(v)); /* white object could not be old */ setage(v, G_OLD0); /* restore generational invariant */ } } else { /* sweep phase */ lua_assert(issweepphase(g)); if (g->gckind != KGC_GENMINOR) /* incremental mode? */ makewhite(g, o); /* mark 'o' as white to avoid other barriers */ } } /* ** barrier that moves collector backward, that is, mark the black object ** pointing to a white object as gray again. */ void luaC_barrierback_ (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(isblack(o) && !isdead(g, o)); lua_assert((g->gckind != KGC_GENMINOR) || (isold(o) && getage(o) != G_TOUCHED1)); if (getage(o) == G_TOUCHED2) /* already in gray list? */ set2gray(o); /* make it gray to become touched1 */ else /* link it in 'grayagain' and paint it gray */ linkobjgclist(o, g->grayagain); if (isold(o)) /* generational mode? */ setage(o, G_TOUCHED1); /* touched in current cycle */ } void luaC_fix (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */ set2gray(o); /* they will be gray forever */ setage(o, G_OLD); /* and old forever */ g->allgc = o->next; /* remove object from 'allgc' list */ o->next = g->fixedgc; /* link it to 'fixedgc' list */ g->fixedgc = o; } /* ** create a new collectable object (with given type, size, and offset) ** and link it to 'allgc' list. */ GCObject *luaC_newobjdt (lua_State *L, lu_byte tt, size_t sz, size_t offset) { global_State *g = G(L); char *p = cast_charp(luaM_newobject(L, novariant(tt), sz)); GCObject *o = cast(GCObject *, p + offset); o->marked = luaC_white(g); o->tt = tt; o->next = g->allgc; g->allgc = o; return o; } /* ** create a new collectable object with no offset. */ GCObject *luaC_newobj (lua_State *L, lu_byte tt, size_t sz) { return luaC_newobjdt(L, tt, sz, 0); } /* }====================================================== */ /* ** {====================================================== ** Mark functions ** ======================================================= */ /* ** Mark an object. Userdata with no user values, strings, and closed ** upvalues are visited and turned black here. Open upvalues are ** already indirectly linked through their respective threads in the ** 'twups' list, so they don't go to the gray list; nevertheless, they ** are kept gray to avoid barriers, as their values will be revisited ** by the thread or by 'remarkupvals'. Other objects are added to the ** gray list to be visited (and turned black) later. Both userdata and ** upvalues can call this function recursively, but this recursion goes ** for at most two levels: An upvalue cannot refer to another upvalue ** (only closures can), and a userdata's metatable must be a table. */ static void reallymarkobject (global_State *g, GCObject *o) { g->GCmarked += objsize(o); switch (o->tt) { case LUA_VSHRSTR: case LUA_VLNGSTR: { set2black(o); /* nothing to visit */ break; } case LUA_VUPVAL: { UpVal *uv = gco2upv(o); if (upisopen(uv)) set2gray(uv); /* open upvalues are kept gray */ else set2black(uv); /* closed upvalues are visited here */ markvalue(g, uv->v.p); /* mark its content */ break; } case LUA_VUSERDATA: { Udata *u = gco2u(o); if (u->nuvalue == 0) { /* no user values? */ markobjectN(g, u->metatable); /* mark its metatable */ set2black(u); /* nothing else to mark */ break; } /* else... */ } /* FALLTHROUGH */ case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE: case LUA_VTHREAD: case LUA_VPROTO: { linkobjgclist(o, g->gray); /* to be visited later */ break; } default: lua_assert(0); break; } } /* ** mark metamethods for basic types */ static void markmt (global_State *g) { int i; for (i=0; i < LUA_NUMTYPES; i++) markobjectN(g, g->mt[i]); } /* ** mark all objects in list of being-finalized */ static void markbeingfnz (global_State *g) { GCObject *o; for (o = g->tobefnz; o != NULL; o = o->next) markobject(g, o); } /* ** For each non-marked thread, simulates a barrier between each open ** upvalue and its value. (If the thread is collected, the value will be ** assigned to the upvalue, but then it can be too late for the barrier ** to act. The "barrier" does not need to check colors: A non-marked ** thread must be young; upvalues cannot be older than their threads; so ** any visited upvalue must be young too.) Also removes the thread from ** the list, as it was already visited. Removes also threads with no ** upvalues, as they have nothing to be checked. (If the thread gets an ** upvalue later, it will be linked in the list again.) */ static void remarkupvals (global_State *g) { lua_State *thread; lua_State **p = &g->twups; while ((thread = *p) != NULL) { if (!iswhite(thread) && thread->openupval != NULL) p = &thread->twups; /* keep marked thread with upvalues in the list */ else { /* thread is not marked or without upvalues */ UpVal *uv; lua_assert(!isold(thread) || thread->openupval == NULL); *p = thread->twups; /* remove thread from the list */ thread->twups = thread; /* mark that it is out of list */ for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) { lua_assert(getage(uv) <= getage(thread)); if (!iswhite(uv)) { /* upvalue already visited? */ lua_assert(upisopen(uv) && isgray(uv)); markvalue(g, uv->v.p); /* mark its value */ } } } } } static void cleargraylists (global_State *g) { g->gray = g->grayagain = NULL; g->weak = g->allweak = g->ephemeron = NULL; } /* ** mark root set and reset all gray lists, to start a new collection. ** 'GCmarked' is initialized to count the total number of live bytes ** during a cycle. */ static void restartcollection (global_State *g) { cleargraylists(g); g->GCmarked = 0; markobject(g, mainthread(g)); markvalue(g, &g->l_registry); markmt(g); markbeingfnz(g); /* mark any finalizing object left from previous cycle */ } /* }====================================================== */ /* ** {====================================================== ** Traverse functions ** ======================================================= */ /* ** Check whether object 'o' should be kept in the 'grayagain' list for ** post-processing by 'correctgraylist'. (It could put all old objects ** in the list and leave all the work to 'correctgraylist', but it is ** more efficient to avoid adding elements that will be removed.) Only ** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go ** back to a gray list, but then it must become OLD. (That is what ** 'correctgraylist' does when it finds a TOUCHED2 object.) ** This function is a no-op in incremental mode, as objects cannot be ** marked as touched in that mode. */ static void genlink (global_State *g, GCObject *o) { lua_assert(isblack(o)); if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */ linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */ } /* everything else do not need to be linked back */ else if (getage(o) == G_TOUCHED2) setage(o, G_OLD); /* advance age */ } /* ** Traverse a table with weak values and link it to proper list. During ** propagate phase, keep it in 'grayagain' list, to be revisited in the ** atomic phase. In the atomic phase, if table has any white value, ** put it in 'weak' list, to be cleared; otherwise, call 'genlink' ** to check table age in generational mode. */ static void traverseweakvalue (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); /* if there is array part, assume it may have white values (it is not worth traversing it now just to check) */ int hasclears = (h->asize > 0); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */ hasclears = 1; /* table will have to be cleared */ } } if (g->gcstate == GCSpropagate) linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ else if (hasclears) linkgclist(h, g->weak); /* has to be cleared later */ else genlink(g, obj2gco(h)); } /* ** Traverse the array part of a table. */ static int traversearray (global_State *g, Table *h) { unsigned asize = h->asize; int marked = 0; /* true if some object is marked in this traversal */ unsigned i; for (i = 0; i < asize; i++) { GCObject *o = gcvalarr(h, i); if (o != NULL && iswhite(o)) { marked = 1; reallymarkobject(g, o); } } return marked; } /* ** Traverse an ephemeron table and link it to proper list. Returns true ** iff any object was marked during this traversal (which implies that ** convergence has to continue). During propagation phase, keep table ** in 'grayagain' list, to be visited again in the atomic phase. In ** the atomic phase, if table has any white->white entry, it has to ** be revisited during ephemeron convergence (as that key may turn ** black). Otherwise, if it has any white key, table has to be cleared ** (in the atomic phase). In generational mode, some tables ** must be kept in some gray list for post-processing; this is done ** by 'genlink'. */ static int traverseephemeron (global_State *g, Table *h, int inv) { int hasclears = 0; /* true if table has white keys */ int hasww = 0; /* true if table has entry "white-key -> white-value" */ unsigned int i; unsigned int nsize = sizenode(h); int marked = traversearray(g, h); /* traverse array part */ /* traverse hash part; if 'inv', traverse descending (see 'convergeephemerons') */ for (i = 0; i < nsize; i++) { Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i); if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */ hasclears = 1; /* table must be cleared */ if (valiswhite(gval(n))) /* value not marked yet? */ hasww = 1; /* white-white entry */ } else if (valiswhite(gval(n))) { /* value not marked yet? */ marked = 1; reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ } } /* link table into proper list */ if (g->gcstate == GCSpropagate) linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ else if (hasww) /* table has white->white entries? */ linkgclist(h, g->ephemeron); /* have to propagate again */ else if (hasclears) /* table has white keys? */ linkgclist(h, g->allweak); /* may have to clean white keys */ else genlink(g, obj2gco(h)); /* check whether collector still needs to see it */ return marked; } static void traversestrongtable (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); traversearray(g, h); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); markvalue(g, gval(n)); } } genlink(g, obj2gco(h)); } /* ** (result & 1) iff weak values; (result & 2) iff weak keys. */ static int getmode (global_State *g, Table *h) { const TValue *mode = gfasttm(g, h->metatable, TM_MODE); if (mode == NULL || !ttisstring(mode)) return 0; /* ignore non-string modes */ else { const char *smode = getstr(tsvalue(mode)); const char *weakkey = strchr(smode, 'k'); const char *weakvalue = strchr(smode, 'v'); return ((weakkey != NULL) << 1) | (weakvalue != NULL); } } static l_mem traversetable (global_State *g, Table *h) { markobjectN(g, h->metatable); switch (getmode(g, h)) { case 0: /* not weak */ traversestrongtable(g, h); break; case 1: /* weak values */ traverseweakvalue(g, h); break; case 2: /* weak keys */ traverseephemeron(g, h, 0); break; case 3: /* all weak; nothing to traverse */ if (g->gcstate == GCSpropagate) linkgclist(h, g->grayagain); /* must visit again its metatable */ else linkgclist(h, g->allweak); /* must clear collected entries */ break; } return cast(l_mem, 1 + 2*sizenode(h) + h->asize); } static l_mem traverseudata (global_State *g, Udata *u) { int i; markobjectN(g, u->metatable); /* mark its metatable */ for (i = 0; i < u->nuvalue; i++) markvalue(g, &u->uv[i].uv); genlink(g, obj2gco(u)); return 1 + u->nuvalue; } /* ** Traverse a prototype. (While a prototype is being build, its ** arrays can be larger than needed; the extra slots are filled with ** NULL, so the use of 'markobjectN') */ static l_mem traverseproto (global_State *g, Proto *f) { int i; markobjectN(g, f->source); for (i = 0; i < f->sizek; i++) /* mark literals */ markvalue(g, &f->k[i]); for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ markobjectN(g, f->upvalues[i].name); for (i = 0; i < f->sizep; i++) /* mark nested protos */ markobjectN(g, f->p[i]); for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ markobjectN(g, f->locvars[i].varname); return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars; } static l_mem traverseCclosure (global_State *g, CClosure *cl) { int i; for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ markvalue(g, &cl->upvalue[i]); return 1 + cl->nupvalues; } /* ** Traverse a Lua closure, marking its prototype and its upvalues. ** (Both can be NULL while closure is being created.) */ static l_mem traverseLclosure (global_State *g, LClosure *cl) { int i; markobjectN(g, cl->p); /* mark its prototype */ for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */ UpVal *uv = cl->upvals[i]; markobjectN(g, uv); /* mark upvalue */ } return 1 + cl->nupvalues; } /* ** Traverse a thread, marking the elements in the stack up to its top ** and cleaning the rest of the stack in the final traversal. That ** ensures that the entire stack have valid (non-dead) objects. ** Threads have no barriers. In gen. mode, old threads must be visited ** at every cycle, because they might point to young objects. In inc. ** mode, the thread can still be modified before the end of the cycle, ** and therefore it must be visited again in the atomic phase. To ensure ** these visits, threads must return to a gray list if they are not new ** (which can only happen in generational mode) or if the traverse is in ** the propagate phase (which can only happen in incremental mode). */ static l_mem traversethread (global_State *g, lua_State *th) { UpVal *uv; StkId o = th->stack.p; if (isold(th) || g->gcstate == GCSpropagate) linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ if (o == NULL) return 0; /* stack not completely built yet */ lua_assert(g->gcstate == GCSatomic || th->openupval == NULL || isintwups(th)); for (; o < th->top.p; o++) /* mark live elements in the stack */ markvalue(g, s2v(o)); for (uv = th->openupval; uv != NULL; uv = uv->u.open.next) markobject(g, uv); /* open upvalues cannot be collected */ if (g->gcstate == GCSatomic) { /* final traversal? */ if (!g->gcemergency) luaD_shrinkstack(th); /* do not change stack in emergency cycle */ for (o = th->top.p; o < th->stack_last.p + EXTRA_STACK; o++) setnilvalue(s2v(o)); /* clear dead stack slice */ /* 'remarkupvals' may have removed thread from 'twups' list */ if (!isintwups(th) && th->openupval != NULL) { th->twups = g->twups; /* link it back to the list */ g->twups = th; } } return 1 + (th->top.p - th->stack.p); } /* ** traverse one gray object, turning it to black. Return an estimate ** of the number of slots traversed. */ static l_mem propagatemark (global_State *g) { GCObject *o = g->gray; nw2black(o); g->gray = *getgclist(o); /* remove from 'gray' list */ switch (o->tt) { case LUA_VTABLE: return traversetable(g, gco2t(o)); case LUA_VUSERDATA: return traverseudata(g, gco2u(o)); case LUA_VLCL: return traverseLclosure(g, gco2lcl(o)); case LUA_VCCL: return traverseCclosure(g, gco2ccl(o)); case LUA_VPROTO: return traverseproto(g, gco2p(o)); case LUA_VTHREAD: return traversethread(g, gco2th(o)); default: lua_assert(0); return 0; } } static void propagateall (global_State *g) { while (g->gray) propagatemark(g); } /* ** Traverse all ephemeron tables propagating marks from keys to values. ** Repeat until it converges, that is, nothing new is marked. 'dir' ** inverts the direction of the traversals, trying to speed up ** convergence on chains in the same table. */ static void convergeephemerons (global_State *g) { int changed; int dir = 0; do { GCObject *w; GCObject *next = g->ephemeron; /* get ephemeron list */ g->ephemeron = NULL; /* tables may return to this list when traversed */ changed = 0; while ((w = next) != NULL) { /* for each ephemeron table */ Table *h = gco2t(w); next = h->gclist; /* list is rebuilt during loop */ nw2black(h); /* out of the list (for now) */ if (traverseephemeron(g, h, dir)) { /* marked some value? */ propagateall(g); /* propagate changes */ changed = 1; /* will have to revisit all ephemeron tables */ } } dir = !dir; /* invert direction next time */ } while (changed); /* repeat until no more changes */ } /* }====================================================== */ /* ** {====================================================== ** Sweep Functions ** ======================================================= */ /* ** clear entries with unmarked keys from all weaktables in list 'l' */ static void clearbykeys (global_State *g, GCObject *l) { for (; l; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *limit = gnodelast(h); Node *n; for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gckeyN(n))) /* unmarked key? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } /* ** clear entries with unmarked values from all weaktables in list 'l' up ** to element 'f' */ static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) { for (; l != f; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *n, *limit = gnodelast(h); unsigned int i; unsigned int asize = h->asize; for (i = 0; i < asize; i++) { GCObject *o = gcvalarr(h, i); if (iscleared(g, o)) /* value was collected? */ *getArrTag(h, i) = LUA_VEMPTY; /* remove entry */ } for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } static void freeupval (lua_State *L, UpVal *uv) { if (upisopen(uv)) luaF_unlinkupval(uv); luaM_free(L, uv); } static void freeobj (lua_State *L, GCObject *o) { assert_code(l_mem newmem = gettotalbytes(G(L)) - objsize(o)); switch (o->tt) { case LUA_VPROTO: luaF_freeproto(L, gco2p(o)); break; case LUA_VUPVAL: freeupval(L, gco2upv(o)); break; case LUA_VLCL: { LClosure *cl = gco2lcl(o); luaM_freemem(L, cl, sizeLclosure(cl->nupvalues)); break; } case LUA_VCCL: { CClosure *cl = gco2ccl(o); luaM_freemem(L, cl, sizeCclosure(cl->nupvalues)); break; } case LUA_VTABLE: luaH_free(L, gco2t(o)); break; case LUA_VTHREAD: luaE_freethread(L, gco2th(o)); break; case LUA_VUSERDATA: { Udata *u = gco2u(o); luaM_freemem(L, o, sizeudata(u->nuvalue, u->len)); break; } case LUA_VSHRSTR: { TString *ts = gco2ts(o); luaS_remove(L, ts); /* remove it from hash table */ luaM_freemem(L, ts, sizestrshr(cast_uint(ts->shrlen))); break; } case LUA_VLNGSTR: { TString *ts = gco2ts(o); if (ts->shrlen == LSTRMEM) /* must free external string? */ (*ts->falloc)(ts->ud, ts->contents, ts->u.lnglen + 1, 0); luaM_freemem(L, ts, luaS_sizelngstr(ts->u.lnglen, ts->shrlen)); break; } default: lua_assert(0); } lua_assert(gettotalbytes(G(L)) == newmem); } /* ** sweep at most 'countin' elements from a list of GCObjects erasing dead ** objects, where a dead object is one marked with the old (non current) ** white; change all non-dead objects back to white (and new), preparing ** for next collection cycle. Return where to continue the traversal or ** NULL if list is finished. */ static GCObject **sweeplist (lua_State *L, GCObject **p, l_mem countin) { global_State *g = G(L); int ow = otherwhite(g); int white = luaC_white(g); /* current white */ while (*p != NULL && countin-- > 0) { GCObject *curr = *p; int marked = curr->marked; if (isdeadm(ow, marked)) { /* is 'curr' dead? */ *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* change mark to 'white' and age to 'new' */ curr->marked = cast_byte((marked & ~maskgcbits) | white | G_NEW); p = &curr->next; /* go to next element */ } } return (*p == NULL) ? NULL : p; } /* ** sweep a list until a live object (or end of list) */ static GCObject **sweeptolive (lua_State *L, GCObject **p) { GCObject **old = p; do { p = sweeplist(L, p, 1); } while (p == old); return p; } /* }====================================================== */ /* ** {====================================================== ** Finalization ** ======================================================= */ /* ** If possible, shrink string table. */ static void checkSizes (lua_State *L, global_State *g) { if (!g->gcemergency) { if (g->strt.nuse < g->strt.size / 4) /* string table too big? */ luaS_resize(L, g->strt.size / 2); } } /* ** Get the next udata to be finalized from the 'tobefnz' list, and ** link it back into the 'allgc' list. */ static GCObject *udata2finalize (global_State *g) { GCObject *o = g->tobefnz; /* get first element */ lua_assert(tofinalize(o)); g->tobefnz = o->next; /* remove it from 'tobefnz' list */ o->next = g->allgc; /* return it to 'allgc' list */ g->allgc = o; resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */ if (issweepphase(g)) makewhite(g, o); /* "sweep" object */ else if (getage(o) == G_OLD1) g->firstold1 = o; /* it is the first OLD1 object in the list */ return o; } static void dothecall (lua_State *L, void *ud) { UNUSED(ud); luaD_callnoyield(L, L->top.p - 2, 0); } static void GCTM (lua_State *L) { global_State *g = G(L); const TValue *tm; TValue v; lua_assert(!g->gcemergency); setgcovalue(L, &v, udata2finalize(g)); tm = luaT_gettmbyobj(L, &v, TM_GC); if (!notm(tm)) { /* is there a finalizer? */ TStatus status; lu_byte oldah = L->allowhook; lu_byte oldgcstp = g->gcstp; g->gcstp |= GCSTPGC; /* avoid GC steps */ L->allowhook = 0; /* stop debug hooks during GC metamethod */ setobj2s(L, L->top.p++, tm); /* push finalizer... */ setobj2s(L, L->top.p++, &v); /* ... and its argument */ L->ci->callstatus |= CIST_FIN; /* will run a finalizer */ status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top.p - 2), 0); L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */ L->allowhook = oldah; /* restore hooks */ g->gcstp = oldgcstp; /* restore state */ if (l_unlikely(status != LUA_OK)) { /* error while running __gc? */ luaE_warnerror(L, "__gc"); L->top.p--; /* pops error object */ } } } /* ** call all pending finalizers */ static void callallpendingfinalizers (lua_State *L) { global_State *g = G(L); while (g->tobefnz) GCTM(L); } /* ** find last 'next' field in list 'p' list (to add elements in its end) */ static GCObject **findlast (GCObject **p) { while (*p != NULL) p = &(*p)->next; return p; } /* ** Move all unreachable objects (or 'all' objects) that need ** finalization from list 'finobj' to list 'tobefnz' (to be finalized). ** (Note that objects after 'finobjold1' cannot be white, so they ** don't need to be traversed. In incremental mode, 'finobjold1' is NULL, ** so the whole list is traversed.) */ static void separatetobefnz (global_State *g, int all) { GCObject *curr; GCObject **p = &g->finobj; GCObject **lastnext = findlast(&g->tobefnz); while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */ lua_assert(tofinalize(curr)); if (!(iswhite(curr) || all)) /* not being collected? */ p = &curr->next; /* don't bother with it */ else { if (curr == g->finobjsur) /* removing 'finobjsur'? */ g->finobjsur = curr->next; /* correct it */ *p = curr->next; /* remove 'curr' from 'finobj' list */ curr->next = *lastnext; /* link at the end of 'tobefnz' list */ *lastnext = curr; lastnext = &curr->next; } } } /* ** If pointer 'p' points to 'o', move it to the next element. */ static void checkpointer (GCObject **p, GCObject *o) { if (o == *p) *p = o->next; } /* ** Correct pointers to objects inside 'allgc' list when ** object 'o' is being removed from the list. */ static void correctpointers (global_State *g, GCObject *o) { checkpointer(&g->survival, o); checkpointer(&g->old1, o); checkpointer(&g->reallyold, o); checkpointer(&g->firstold1, o); } /* ** if object 'o' has a finalizer, remove it from 'allgc' list (must ** search the list to find it) and link it in 'finobj' list. */ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { global_State *g = G(L); if (tofinalize(o) || /* obj. is already marked... */ gfasttm(g, mt, TM_GC) == NULL || /* or has no finalizer... */ (g->gcstp & GCSTPCLS)) /* or closing state? */ return; /* nothing to be done */ else { /* move 'o' to 'finobj' list */ GCObject **p; if (issweepphase(g)) { makewhite(g, o); /* "sweep" object 'o' */ if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */ g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */ } else correctpointers(g, o); /* search for pointer pointing to 'o' */ for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ } *p = o->next; /* remove 'o' from 'allgc' list */ o->next = g->finobj; /* link it in 'finobj' list */ g->finobj = o; l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */ } } /* }====================================================== */ /* ** {====================================================== ** Generational Collector ** ======================================================= */ /* ** Fields 'GCmarked' and 'GCmajorminor' are used to control the pace and ** the mode of the collector. They play several roles, depending on the ** mode of the collector: ** * KGC_INC: ** GCmarked: number of marked bytes during a cycle. ** GCmajorminor: not used. ** * KGC_GENMINOR ** GCmarked: number of bytes that became old since last major collection. ** GCmajorminor: number of bytes marked in last major collection. ** * KGC_GENMAJOR ** GCmarked: number of bytes that became old since last major collection. ** GCmajorminor: number of bytes marked in last major collection. */ /* ** Set the "time" to wait before starting a new incremental cycle; ** cycle will start when number of bytes in use hits the threshold of ** approximately (marked * pause / 100). */ static void setpause (global_State *g) { l_mem threshold = applygcparam(g, PAUSE, g->GCmarked); l_mem debt = threshold - gettotalbytes(g); if (debt < 0) debt = 0; luaE_setdebt(g, debt); } /* ** Sweep a list of objects to enter generational mode. Deletes dead ** objects and turns the non dead to old. All non-dead threads---which ** are now old---must be in a gray list. Everything else is not in a ** gray list. Open upvalues are also kept gray. */ static void sweep2old (lua_State *L, GCObject **p) { GCObject *curr; global_State *g = G(L); while ((curr = *p) != NULL) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(isdead(g, curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* all surviving objects become old */ setage(curr, G_OLD); if (curr->tt == LUA_VTHREAD) { /* threads must be watched */ lua_State *th = gco2th(curr); linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ } else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr))) set2gray(curr); /* open upvalues are always gray */ else /* everything else is black */ nw2black(curr); p = &curr->next; /* go to next element */ } } } /* ** Sweep for generational mode. Delete dead objects. (Because the ** collection is not incremental, there are no "new white" objects ** during the sweep. So, any white object must be dead.) For ** non-dead objects, advance their ages and clear the color of ** new objects. (Old objects keep their colors.) ** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced ** here, because these old-generation objects are usually not swept ** here. They will all be advanced in 'correctgraylist'. That function ** will also remove objects turned white here from any gray list. */ static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p, GCObject *limit, GCObject **pfirstold1, l_mem *paddedold) { static const lu_byte nextage[] = { G_SURVIVAL, /* from G_NEW */ G_OLD1, /* from G_SURVIVAL */ G_OLD1, /* from G_OLD0 */ G_OLD, /* from G_OLD1 */ G_OLD, /* from G_OLD (do not change) */ G_TOUCHED1, /* from G_TOUCHED1 (do not change) */ G_TOUCHED2 /* from G_TOUCHED2 (do not change) */ }; l_mem addedold = 0; int white = luaC_white(g); GCObject *curr; while ((curr = *p) != limit) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(!isold(curr) && isdead(g, curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* correct mark and age */ int age = getage(curr); if (age == G_NEW) { /* new objects go back to white */ int marked = curr->marked & ~maskgcbits; /* erase GC bits */ curr->marked = cast_byte(marked | G_SURVIVAL | white); } else { /* all other objects will be old, and so keep their color */ lua_assert(age != G_OLD1); /* advanced in 'markold' */ setage(curr, nextage[age]); if (getage(curr) == G_OLD1) { addedold += objsize(curr); /* bytes becoming old */ if (*pfirstold1 == NULL) *pfirstold1 = curr; /* first OLD1 object in the list */ } } p = &curr->next; /* go to next element */ } } *paddedold += addedold; return p; } /* ** Correct a list of gray objects. Return a pointer to the last element ** left on the list, so that we can link another list to the end of ** this one. ** Because this correction is done after sweeping, young objects might ** be turned white and still be in the list. They are only removed. ** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list; ** Non-white threads also remain on the list. 'TOUCHED2' objects and ** anything else become regular old, are marked black, and are removed ** from the list. */ static GCObject **correctgraylist (GCObject **p) { GCObject *curr; while ((curr = *p) != NULL) { GCObject **next = getgclist(curr); if (iswhite(curr)) goto remove; /* remove all white objects */ else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */ lua_assert(isgray(curr)); nw2black(curr); /* make it black, for next barrier */ setage(curr, G_TOUCHED2); goto remain; /* keep it in the list and go to next element */ } else if (curr->tt == LUA_VTHREAD) { lua_assert(isgray(curr)); goto remain; /* keep non-white threads on the list */ } else { /* everything else is removed */ lua_assert(isold(curr)); /* young objects should be white here */ if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */ setage(curr, G_OLD); /* ... to OLD */ nw2black(curr); /* make object black (to be removed) */ goto remove; } remove: *p = *next; continue; remain: p = next; continue; } return p; } /* ** Correct all gray lists, coalescing them into 'grayagain'. */ static void correctgraylists (global_State *g) { GCObject **list = correctgraylist(&g->grayagain); *list = g->weak; g->weak = NULL; list = correctgraylist(list); *list = g->allweak; g->allweak = NULL; list = correctgraylist(list); *list = g->ephemeron; g->ephemeron = NULL; correctgraylist(list); } /* ** Mark black 'OLD1' objects when starting a new young collection. ** Gray objects are already in some gray list, and so will be visited in ** the atomic step. */ static void markold (global_State *g, GCObject *from, GCObject *to) { GCObject *p; for (p = from; p != to; p = p->next) { if (getage(p) == G_OLD1) { lua_assert(!iswhite(p)); setage(p, G_OLD); /* now they are old */ if (isblack(p)) reallymarkobject(g, p); } } } /* ** Finish a young-generation collection. */ static void finishgencycle (lua_State *L, global_State *g) { correctgraylists(g); checkSizes(L, g); g->gcstate = GCSpropagate; /* skip restart */ if (!g->gcemergency && luaD_checkminstack(L)) callallpendingfinalizers(L); } /* ** Shifts from a minor collection to major collections. It starts in ** the "sweep all" state to clear all objects, which are mostly black ** in generational mode. */ static void minor2inc (lua_State *L, global_State *g, lu_byte kind) { g->GCmajorminor = g->GCmarked; /* number of live bytes */ g->gckind = kind; g->reallyold = g->old1 = g->survival = NULL; g->finobjrold = g->finobjold1 = g->finobjsur = NULL; entersweep(L); /* continue as an incremental cycle */ /* set a debt equal to the step size */ luaE_setdebt(g, applygcparam(g, STEPSIZE, 100)); } /* ** Decide whether to shift to major mode. It shifts if the accumulated ** number of added old bytes (counted in 'GCmarked') is larger than ** 'minormajor'% of the number of lived bytes after the last major ** collection. (This number is kept in 'GCmajorminor'.) */ static int checkminormajor (global_State *g) { l_mem limit = applygcparam(g, MINORMAJOR, g->GCmajorminor); if (limit == 0) return 0; /* special case: 'minormajor' 0 stops major collections */ return (g->GCmarked >= limit); } /* ** Does a young collection. First, mark 'OLD1' objects. Then does the ** atomic step. Then, check whether to continue in minor mode. If so, ** sweep all lists and advance pointers. Finally, finish the collection. */ static void youngcollection (lua_State *L, global_State *g) { l_mem addedold1 = 0; l_mem marked = g->GCmarked; /* preserve 'g->GCmarked' */ GCObject **psurvival; /* to point to first non-dead survival object */ GCObject *dummy; /* dummy out parameter to 'sweepgen' */ lua_assert(g->gcstate == GCSpropagate); if (g->firstold1) { /* are there regular OLD1 objects? */ markold(g, g->firstold1, g->reallyold); /* mark them */ g->firstold1 = NULL; /* no more OLD1 objects (for now) */ } markold(g, g->finobj, g->finobjrold); markold(g, g->tobefnz, NULL); atomic(L); /* will lose 'g->marked' */ /* sweep nursery and get a pointer to its last live element */ g->gcstate = GCSswpallgc; psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1, &addedold1); /* sweep 'survival' */ sweepgen(L, g, psurvival, g->old1, &g->firstold1, &addedold1); g->reallyold = g->old1; g->old1 = *psurvival; /* 'survival' survivals are old now */ g->survival = g->allgc; /* all news are survivals */ /* repeat for 'finobj' lists */ dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */ psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy, &addedold1); /* sweep 'survival' */ sweepgen(L, g, psurvival, g->finobjold1, &dummy, &addedold1); g->finobjrold = g->finobjold1; g->finobjold1 = *psurvival; /* 'survival' survivals are old now */ g->finobjsur = g->finobj; /* all news are survivals */ sweepgen(L, g, &g->tobefnz, NULL, &dummy, &addedold1); /* keep total number of added old1 bytes */ g->GCmarked = marked + addedold1; /* decide whether to shift to major mode */ if (checkminormajor(g)) { minor2inc(L, g, KGC_GENMAJOR); /* go to major mode */ g->GCmarked = 0; /* avoid pause in first major cycle (see 'setpause') */ } else finishgencycle(L, g); /* still in minor mode; finish it */ } /* ** Clears all gray lists, sweeps objects, and prepare sublists to enter ** generational mode. The sweeps remove dead objects and turn all ** surviving objects to old. Threads go back to 'grayagain'; everything ** else is turned black (not in any gray list). */ static void atomic2gen (lua_State *L, global_State *g) { cleargraylists(g); /* sweep all elements making them old */ g->gcstate = GCSswpallgc; sweep2old(L, &g->allgc); /* everything alive now is old */ g->reallyold = g->old1 = g->survival = g->allgc; g->firstold1 = NULL; /* there are no OLD1 objects anywhere */ /* repeat for 'finobj' lists */ sweep2old(L, &g->finobj); g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj; sweep2old(L, &g->tobefnz); g->gckind = KGC_GENMINOR; g->GCmajorminor = g->GCmarked; /* "base" for number of bytes */ g->GCmarked = 0; /* to count the number of added old1 bytes */ finishgencycle(L, g); } /* ** Set debt for the next minor collection, which will happen when ** total number of bytes grows 'genminormul'% in relation to ** the base, GCmajorminor, which is the number of bytes being used ** after the last major collection. */ static void setminordebt (global_State *g) { luaE_setdebt(g, applygcparam(g, MINORMUL, g->GCmajorminor)); } /* ** Enter generational mode. Must go until the end of an atomic cycle ** to ensure that all objects are correctly marked and weak tables ** are cleared. Then, turn all objects into old and finishes the ** collection. */ static void entergen (lua_State *L, global_State *g) { luaC_runtilstate(L, GCSpause, 1); /* prepare to start a new cycle */ luaC_runtilstate(L, GCSpropagate, 1); /* start new cycle */ atomic(L); /* propagates all and then do the atomic stuff */ atomic2gen(L, g); setminordebt(g); /* set debt assuming next cycle will be minor */ } /* ** Change collector mode to 'newmode'. */ void luaC_changemode (lua_State *L, int newmode) { global_State *g = G(L); if (g->gckind == KGC_GENMAJOR) /* doing major collections? */ g->gckind = KGC_INC; /* already incremental but in name */ if (newmode != g->gckind) { /* does it need to change? */ if (newmode == KGC_INC) /* entering incremental mode? */ minor2inc(L, g, KGC_INC); /* entering incremental mode */ else { lua_assert(newmode == KGC_GENMINOR); entergen(L, g); } } } /* ** Does a full collection in generational mode. */ static void fullgen (lua_State *L, global_State *g) { minor2inc(L, g, KGC_INC); entergen(L, g); } /* ** After an atomic incremental step from a major collection, ** check whether collector could return to minor collections. ** It checks whether the number of bytes 'tobecollected' ** is greater than 'majorminor'% of the number of bytes added ** since the last collection ('addedbytes'). */ static int checkmajorminor (lua_State *L, global_State *g) { if (g->gckind == KGC_GENMAJOR) { /* generational mode? */ l_mem numbytes = gettotalbytes(g); l_mem addedbytes = numbytes - g->GCmajorminor; l_mem limit = applygcparam(g, MAJORMINOR, addedbytes); l_mem tobecollected = numbytes - g->GCmarked; if (tobecollected > limit) { atomic2gen(L, g); /* return to generational mode */ setminordebt(g); return 1; /* exit incremental collection */ } } g->GCmajorminor = g->GCmarked; /* prepare for next collection */ return 0; /* stay doing incremental collections */ } /* }====================================================== */ /* ** {====================================================== ** GC control ** ======================================================= */ /* ** Enter first sweep phase. ** The call to 'sweeptolive' makes the pointer point to an object ** inside the list (instead of to the header), so that the real sweep do ** not need to skip objects created between "now" and the start of the ** real sweep. */ static void entersweep (lua_State *L) { global_State *g = G(L); g->gcstate = GCSswpallgc; lua_assert(g->sweepgc == NULL); g->sweepgc = sweeptolive(L, &g->allgc); } /* ** Delete all objects in list 'p' until (but not including) object ** 'limit'. */ static void deletelist (lua_State *L, GCObject *p, GCObject *limit) { while (p != limit) { GCObject *next = p->next; freeobj(L, p); p = next; } } /* ** Call all finalizers of the objects in the given Lua state, and ** then free all objects, except for the main thread. */ void luaC_freeallobjects (lua_State *L) { global_State *g = G(L); g->gcstp = GCSTPCLS; /* no extra finalizers after here */ luaC_changemode(L, KGC_INC); separatetobefnz(g, 1); /* separate all objects with finalizers */ lua_assert(g->finobj == NULL); callallpendingfinalizers(L); deletelist(L, g->allgc, obj2gco(mainthread(g))); lua_assert(g->finobj == NULL); /* no new finalizers */ deletelist(L, g->fixedgc, NULL); /* collect fixed objects */ lua_assert(g->strt.nuse == 0); } static void atomic (lua_State *L) { global_State *g = G(L); GCObject *origweak, *origall; GCObject *grayagain = g->grayagain; /* save original list */ g->grayagain = NULL; lua_assert(g->ephemeron == NULL && g->weak == NULL); lua_assert(!iswhite(mainthread(g))); g->gcstate = GCSatomic; markobject(g, L); /* mark running thread */ /* registry and global metatables may be changed by API */ markvalue(g, &g->l_registry); markmt(g); /* mark global metatables */ propagateall(g); /* empties 'gray' list */ /* remark occasional upvalues of (maybe) dead threads */ remarkupvals(g); propagateall(g); /* propagate changes */ g->gray = grayagain; propagateall(g); /* traverse 'grayagain' list */ convergeephemerons(g); /* at this point, all strongly accessible objects are marked. */ /* Clear values from weak tables, before checking finalizers */ clearbyvalues(g, g->weak, NULL); clearbyvalues(g, g->allweak, NULL); origweak = g->weak; origall = g->allweak; separatetobefnz(g, 0); /* separate objects to be finalized */ markbeingfnz(g); /* mark objects that will be finalized */ propagateall(g); /* remark, to propagate 'resurrection' */ convergeephemerons(g); /* at this point, all resurrected objects are marked. */ /* remove dead objects from weak tables */ clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron */ clearbykeys(g, g->allweak); /* clear keys from all 'allweak' */ /* clear values from resurrected weak tables */ clearbyvalues(g, g->weak, origweak); clearbyvalues(g, g->allweak, origall); luaS_clearcache(g); g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ lua_assert(g->gray == NULL); } /* ** Do a sweep step. The normal case (not fast) sweeps at most GCSWEEPMAX ** elements. The fast case sweeps the whole list. */ static void sweepstep (lua_State *L, global_State *g, lu_byte nextstate, GCObject **nextlist, int fast) { if (g->sweepgc) g->sweepgc = sweeplist(L, g->sweepgc, fast ? MAX_LMEM : GCSWEEPMAX); else { /* enter next state */ g->gcstate = nextstate; g->sweepgc = nextlist; } } /* ** Performs one incremental "step" in an incremental garbage collection. ** For indivisible work, a step goes to the next state. When marking ** (propagating), a step traverses one object. When sweeping, a step ** sweeps GCSWEEPMAX objects, to avoid a big overhead for sweeping ** objects one by one. (Sweeping is inexpensive, no matter the ** object.) When 'fast' is true, 'singlestep' tries to finish a state ** "as fast as possible". In particular, it skips the propagation ** phase and leaves all objects to be traversed by the atomic phase: ** That avoids traversing twice some objects, such as threads and ** weak tables. */ #define step2pause -3 /* finished collection; entered pause state */ #define atomicstep -2 /* atomic step */ #define step2minor -1 /* moved to minor collections */ static l_mem singlestep (lua_State *L, int fast) { global_State *g = G(L); l_mem stepresult; lua_assert(!g->gcstopem); /* collector is not reentrant */ g->gcstopem = 1; /* no emergency collections while collecting */ switch (g->gcstate) { case GCSpause: { restartcollection(g); g->gcstate = GCSpropagate; stepresult = 1; break; } case GCSpropagate: { if (fast || g->gray == NULL) { g->gcstate = GCSenteratomic; /* finish propagate phase */ stepresult = 1; } else stepresult = propagatemark(g); /* traverse one gray object */ break; } case GCSenteratomic: { atomic(L); if (checkmajorminor(L, g)) stepresult = step2minor; else { entersweep(L); stepresult = atomicstep; } break; } case GCSswpallgc: { /* sweep "regular" objects */ sweepstep(L, g, GCSswpfinobj, &g->finobj, fast); stepresult = GCSWEEPMAX; break; } case GCSswpfinobj: { /* sweep objects with finalizers */ sweepstep(L, g, GCSswptobefnz, &g->tobefnz, fast); stepresult = GCSWEEPMAX; break; } case GCSswptobefnz: { /* sweep objects to be finalized */ sweepstep(L, g, GCSswpend, NULL, fast); stepresult = GCSWEEPMAX; break; } case GCSswpend: { /* finish sweeps */ checkSizes(L, g); g->gcstate = GCScallfin; stepresult = GCSWEEPMAX; break; } case GCScallfin: { /* call finalizers */ if (g->tobefnz && !g->gcemergency && luaD_checkminstack(L)) { g->gcstopem = 0; /* ok collections during finalizers */ GCTM(L); /* call one finalizer */ stepresult = CWUFIN; } else { /* no more finalizers or emergency mode or no enough stack to run finalizers */ g->gcstate = GCSpause; /* finish collection */ stepresult = step2pause; } break; } default: lua_assert(0); return 0; } g->gcstopem = 0; return stepresult; } /* ** Advances the garbage collector until it reaches the given state. ** (The option 'fast' is only for testing; in normal code, 'fast' ** here is always true.) */ void luaC_runtilstate (lua_State *L, int state, int fast) { global_State *g = G(L); lua_assert(g->gckind == KGC_INC); while (state != g->gcstate) singlestep(L, fast); } /* ** Performs a basic incremental step. The step size is ** converted from bytes to "units of work"; then the function loops ** running single steps until adding that many units of work or ** finishing a cycle (pause state). Finally, it sets the debt that ** controls when next step will be performed. */ static void incstep (lua_State *L, global_State *g) { l_mem stepsize = applygcparam(g, STEPSIZE, 100); l_mem work2do = applygcparam(g, STEPMUL, stepsize / cast_int(sizeof(void*))); l_mem stres; int fast = (work2do == 0); /* special case: do a full collection */ do { /* repeat until enough work */ stres = singlestep(L, fast); /* perform one single step */ if (stres == step2minor) /* returned to minor collections? */ return; /* nothing else to be done here */ else if (stres == step2pause || (stres == atomicstep && !fast)) break; /* end of cycle or atomic */ else work2do -= stres; } while (fast || work2do > 0); if (g->gcstate == GCSpause) setpause(g); /* pause until next cycle */ else luaE_setdebt(g, stepsize); } #if !defined(luai_tracegc) #define luai_tracegc(L,f) ((void)0) #endif /* ** Performs a basic GC step if collector is running. (If collector was ** stopped by the user, set a reasonable debt to avoid it being called ** at every single check.) */ void luaC_step (lua_State *L) { global_State *g = G(L); lua_assert(!g->gcemergency); if (!gcrunning(g)) { /* not running? */ if (g->gcstp & GCSTPUSR) /* stopped by the user? */ luaE_setdebt(g, 20000); } else { luai_tracegc(L, 1); /* for internal debugging */ switch (g->gckind) { case KGC_INC: case KGC_GENMAJOR: incstep(L, g); break; case KGC_GENMINOR: youngcollection(L, g); setminordebt(g); break; } luai_tracegc(L, 0); /* for internal debugging */ } } /* ** Perform a full collection in incremental mode. ** Before running the collection, check 'keepinvariant'; if it is true, ** there may be some objects marked as black, so the collector has ** to sweep all objects to turn them back to white (as white has not ** changed, nothing will be collected). */ static void fullinc (lua_State *L, global_State *g) { if (keepinvariant(g)) /* black objects? */ entersweep(L); /* sweep everything to turn them back to white */ /* finish any pending sweep phase to start a new cycle */ luaC_runtilstate(L, GCSpause, 1); luaC_runtilstate(L, GCScallfin, 1); /* run up to finalizers */ luaC_runtilstate(L, GCSpause, 1); /* finish collection */ setpause(g); } /* ** Performs a full GC cycle; if 'isemergency', set a flag to avoid ** some operations which could change the interpreter state in some ** unexpected ways (running finalizers and shrinking some structures). */ void luaC_fullgc (lua_State *L, int isemergency) { global_State *g = G(L); lua_assert(!g->gcemergency); g->gcemergency = cast_byte(isemergency); /* set flag */ switch (g->gckind) { case KGC_GENMINOR: fullgen(L, g); break; case KGC_INC: fullinc(L, g); break; case KGC_GENMAJOR: g->gckind = KGC_INC; fullinc(L, g); g->gckind = KGC_GENMAJOR; break; } g->gcemergency = 0; } /* }====================================================== */ /* ** $Id: linit.c $ ** Initialization of libraries for lua.c and other clients ** See Copyright Notice in lua.h */ #define linit_c #define LUA_LIB #include #include "lua.h" #include "lualib.h" #include "lauxlib.h" /* ** Standard Libraries. (Must be listed in the same ORDER of their ** respective constants LUA_K.) */ static const luaL_Reg stdlibs[] = { {LUA_GNAME, luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_COLIBNAME, luaopen_coroutine}, #ifndef NO_LDEBUG {LUA_DBLIBNAME, luaopen_debug}, #endif {LUA_IOLIBNAME, luaopen_io}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_OSLIBNAME, luaopen_os}, {LUA_STRLIBNAME, luaopen_string}, {LUA_TABLIBNAME, luaopen_table}, {LUA_UTF8LIBNAME, luaopen_utf8}, {NULL, NULL} }; /* ** require and preload selected standard libraries */ LUALIB_API void luaL_openselectedlibs (lua_State *L, int load, int preload) { int mask; const luaL_Reg *lib; luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); for (lib = stdlibs, mask = 1; lib->name != NULL; lib++, mask <<= 1) { if (load & mask) { /* selected? */ luaL_requiref(L, lib->name, lib->func, 1); /* require library */ lua_pop(L, 1); /* remove result from the stack */ } else if (preload & mask) { /* selected? */ lua_pushcfunction(L, lib->func); lua_setfield(L, -2, lib->name); /* add library to PRELOAD table */ } } lua_assert((mask >> 1) == LUA_UTF8LIBK); lua_pop(L, 1); /* remove PRELOAD table */ } /* ** $Id: llex.c $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ #define llex_c #define LUA_CORE #include #include #include "lua.h" #define next(ls) (ls->current = zgetc(ls->z)) /* minimum size for string buffer */ #if !defined(LUA_MINBUFFER) #define LUA_MINBUFFER 32 #endif #define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') /* ORDER RESERVED */ static const char *const luaX_tokens [] = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "global", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "//", "..", "...", "==", ">=", "<=", "~=", "<<", ">>", "::", "", "", "", "", "" }; #define save_and_next(ls) (save(ls, ls->current), next(ls)) static l_noret lexerror (LexState *ls, const char *msg, int token); static void save (LexState *ls, int c) { Mbuffer *b = ls->buff; if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { size_t newsize = luaZ_sizebuffer(b); /* get old size */; if (newsize >= (MAX_SIZE/3 * 2)) /* larger than MAX_SIZE/1.5 ? */ lexerror(ls, "lexical element too long", 0); newsize += (newsize >> 1); /* new size is 1.5 times the old one */ luaZ_resizebuffer(ls->L, b, newsize); } b->buffer[luaZ_bufflen(b)++] = cast_char(c); } void luaX_init (lua_State *L) { int i; TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */ luaC_fix(L, obj2gco(e)); /* never collect this name */ for (i=0; iextra = cast_byte(i+1); /* reserved word */ } } const char *luaX_token2str (LexState *ls, int token) { if (token < FIRST_RESERVED) { /* single-byte symbols? */ if (lisprint(token)) return luaO_pushfstring(ls->L, "'%c'", token); else /* control character */ return luaO_pushfstring(ls->L, "'<\\%d>'", token); } else { const char *s = luaX_tokens[token - FIRST_RESERVED]; if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ return luaO_pushfstring(ls->L, "'%s'", s); else /* names, strings, and numerals */ return s; } } static const char *txtToken (LexState *ls, int token) { switch (token) { case TK_NAME: case TK_STRING: case TK_FLT: case TK_INT: save(ls, '\0'); return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff)); default: return luaX_token2str(ls, token); } } static l_noret lexerror (LexState *ls, const char *msg, int token) { msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber); if (token) luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); luaD_throw(ls->L, LUA_ERRSYNTAX); } l_noret luaX_syntaxerror (LexState *ls, const char *msg) { lexerror(ls, msg, ls->t.token); } /* ** Anchors a string in scanner's table so that it will not be collected ** until the end of the compilation; by that time it should be anchored ** somewhere. It also internalizes long strings, ensuring there is only ** one copy of each unique string. */ static TString *anchorstr (LexState *ls, TString *ts) { lua_State *L = ls->L; TValue oldts; int tag = luaH_getstr(ls->h, ts, &oldts); if (!tagisempty(tag)) /* string already present? */ return tsvalue(&oldts); /* use stored value */ else { /* create a new entry */ TValue *stv = s2v(L->top.p++); /* reserve stack space for string */ setsvalue(L, stv, ts); /* push (anchor) the string on the stack */ luaH_set(L, ls->h, stv, stv); /* t[string] = string */ /* table is not a metatable, so it does not need to invalidate cache */ luaC_checkGC(L); L->top.p--; /* remove string from stack */ return ts; } } /* ** Creates a new string and anchors it in scanner's table. */ TString *luaX_newstring (LexState *ls, const char *str, size_t l) { return anchorstr(ls, luaS_newlstr(ls->L, str, l)); } /* ** increment line number and skips newline sequence (any of ** \n, \r, \n\r, or \r\n) */ static void inclinenumber (LexState *ls) { int old = ls->current; lua_assert(currIsNewline(ls)); next(ls); /* skip '\n' or '\r' */ if (currIsNewline(ls) && ls->current != old) next(ls); /* skip '\n\r' or '\r\n' */ if (++ls->linenumber >= INT_MAX) lexerror(ls, "chunk has too many lines", 0); } void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, int firstchar) { ls->t.token = 0; ls->L = L; ls->current = firstchar; ls->lookahead.token = TK_EOS; /* no look-ahead token */ ls->z = z; ls->fs = NULL; ls->linenumber = 1; ls->lastline = 1; ls->source = source; /* all three strings here ("_ENV", "break", "global") were fixed, so they cannot be collected */ ls->envn = luaS_newliteral(L, LUA_ENV); /* get env string */ ls->brkn = luaS_newliteral(L, "break"); /* get "break" string */ #if defined(LUA_COMPAT_GLOBAL) /* compatibility mode: "global" is not a reserved word */ ls->glbn = luaS_newliteral(L, "global"); /* get "global" string */ ls->glbn->extra = 0; /* mark it as not reserved */ #endif luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ } /* ** ======================================================= ** LEXICAL ANALYZER ** ======================================================= */ static int check_next1 (LexState *ls, int c) { if (ls->current == c) { next(ls); return 1; } else return 0; } /* ** Check whether current char is in set 'set' (with two chars) and ** saves it */ static int check_next2 (LexState *ls, const char *set) { lua_assert(set[2] == '\0'); if (ls->current == set[0] || ls->current == set[1]) { save_and_next(ls); return 1; } else return 0; } /* LUA_NUMBER */ /* ** This function is quite liberal in what it accepts, as 'luaO_str2num' ** will reject ill-formed numerals. Roughly, it accepts the following ** pattern: ** ** %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))* ** ** The only tricky part is to accept [+-] only after a valid exponent ** mark, to avoid reading '3-4' or '0xe+1' as a single number. ** ** The caller might have already read an initial dot. */ static int read_numeral (LexState *ls, SemInfo *seminfo) { TValue obj; const char *expo = "Ee"; int first = ls->current; lua_assert(lisdigit(ls->current)); save_and_next(ls); if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */ expo = "Pp"; for (;;) { if (check_next2(ls, expo)) /* exponent mark? */ check_next2(ls, "-+"); /* optional exponent sign */ else if (lisxdigit(ls->current) || ls->current == '.') /* '%x|%.' */ save_and_next(ls); else break; } if (lislalpha(ls->current)) /* is numeral touching a letter? */ save_and_next(ls); /* force an error */ save(ls, '\0'); if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */ lexerror(ls, "malformed number", TK_FLT); if (ttisinteger(&obj)) { seminfo->i = ivalue(&obj); return TK_INT; } else { lua_assert(ttisfloat(&obj)); seminfo->r = fltvalue(&obj); return TK_FLT; } } /* ** read a sequence '[=*[' or ']=*]', leaving the last bracket. If ** sequence is well formed, return its number of '='s + 2; otherwise, ** return 1 if it is a single bracket (no '='s and no 2nd bracket); ** otherwise (an unfinished '[==...') return 0. */ static size_t skip_sep (LexState *ls) { size_t count = 0; int s = ls->current; lua_assert(s == '[' || s == ']'); save_and_next(ls); while (ls->current == '=') { save_and_next(ls); count++; } return (ls->current == s) ? count + 2 : (count == 0) ? 1 : 0; } static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) { int line = ls->linenumber; /* initial line (for error message) */ save_and_next(ls); /* skip 2nd '[' */ if (currIsNewline(ls)) /* string starts with a newline? */ inclinenumber(ls); /* skip it */ for (;;) { switch (ls->current) { case EOZ: { /* error */ const char *what = (seminfo ? "string" : "comment"); const char *msg = luaO_pushfstring(ls->L, "unfinished long %s (starting at line %d)", what, line); lexerror(ls, msg, TK_EOS); break; /* to avoid warnings */ } case ']': { if (skip_sep(ls) == sep) { save_and_next(ls); /* skip 2nd ']' */ goto endloop; } break; } case '\n': case '\r': { save(ls, '\n'); inclinenumber(ls); if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ break; } default: { if (seminfo) save_and_next(ls); else next(ls); } } } endloop: if (seminfo) seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep, luaZ_bufflen(ls->buff) - 2 * sep); } static void esccheck (LexState *ls, int c, const char *msg) { if (!c) { if (ls->current != EOZ) save_and_next(ls); /* add current to buffer for error message */ lexerror(ls, msg, TK_STRING); } } static int gethexa (LexState *ls) { save_and_next(ls); esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected"); return luaO_hexavalue(ls->current); } static int readhexaesc (LexState *ls) { int r = gethexa(ls); r = (r << 4) + gethexa(ls); luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */ return r; } /* ** When reading a UTF-8 escape sequence, save everything to the buffer ** for error reporting in case of errors; 'i' counts the number of ** saved characters, so that they can be removed if case of success. */ static l_uint32 readutf8esc (LexState *ls) { l_uint32 r; int i = 4; /* number of chars to be removed: start with #"\u{X" */ save_and_next(ls); /* skip 'u' */ esccheck(ls, ls->current == '{', "missing '{'"); r = cast_uint(gethexa(ls)); /* must have at least one digit */ while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) { i++; esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large"); r = (r << 4) + luaO_hexavalue(ls->current); } esccheck(ls, ls->current == '}', "missing '}'"); next(ls); /* skip '}' */ luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */ return r; } static void utf8esc (LexState *ls) { char buff[UTF8BUFFSZ]; int n = luaO_utf8esc(buff, readutf8esc(ls)); for (; n > 0; n--) /* add 'buff' to string */ save(ls, buff[UTF8BUFFSZ - n]); } static int readdecesc (LexState *ls) { int i; int r = 0; /* result accumulator */ for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ r = 10*r + ls->current - '0'; save_and_next(ls); } esccheck(ls, r <= UCHAR_MAX, "decimal escape too large"); luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */ return r; } static void read_string (LexState *ls, int del, SemInfo *seminfo) { save_and_next(ls); /* keep delimiter (for error messages) */ while (ls->current != del) { switch (ls->current) { case EOZ: lexerror(ls, "unfinished string", TK_EOS); break; /* to avoid warnings */ case '\n': case '\r': lexerror(ls, "unfinished string", TK_STRING); break; /* to avoid warnings */ case '\\': { /* escape sequences */ int c; /* final character to be saved */ save_and_next(ls); /* keep '\\' for error messages */ switch (ls->current) { case 'a': c = '\a'; goto read_save; case 'b': c = '\b'; goto read_save; case 'f': c = '\f'; goto read_save; case 'n': c = '\n'; goto read_save; case 'r': c = '\r'; goto read_save; case 't': c = '\t'; goto read_save; case 'v': c = '\v'; goto read_save; case 'x': c = readhexaesc(ls); goto read_save; case 'u': utf8esc(ls); goto no_save; case '\n': case '\r': inclinenumber(ls); c = '\n'; goto only_save; case '\\': case '\"': case '\'': c = ls->current; goto read_save; case EOZ: goto no_save; /* will raise an error next loop */ case 'z': { /* zap following span of spaces */ luaZ_buffremove(ls->buff, 1); /* remove '\\' */ next(ls); /* skip the 'z' */ while (lisspace(ls->current)) { if (currIsNewline(ls)) inclinenumber(ls); else next(ls); } goto no_save; } default: { esccheck(ls, lisdigit(ls->current), "invalid escape sequence"); c = readdecesc(ls); /* digital escape '\ddd' */ goto only_save; } } read_save: next(ls); /* go through */ only_save: luaZ_buffremove(ls->buff, 1); /* remove '\\' */ save(ls, c); /* go through */ no_save: break; } default: save_and_next(ls); } } save_and_next(ls); /* skip delimiter */ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, luaZ_bufflen(ls->buff) - 2); } static int llex (LexState *ls, SemInfo *seminfo) { luaZ_resetbuffer(ls->buff); for (;;) { switch (ls->current) { case '\n': case '\r': { /* line breaks */ inclinenumber(ls); break; } case ' ': case '\f': case '\t': case '\v': { /* spaces */ next(ls); break; } case '-': { /* '-' or '--' (comment) */ next(ls); if (ls->current != '-') return '-'; /* else is a comment */ next(ls); if (ls->current == '[') { /* long comment? */ size_t sep = skip_sep(ls); luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ if (sep >= 2) { read_long_string(ls, NULL, sep); /* skip long comment */ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ break; } } /* else short comment */ while (!currIsNewline(ls) && ls->current != EOZ) next(ls); /* skip until end of line (or end of file) */ break; } case '[': { /* long string or simply '[' */ size_t sep = skip_sep(ls); if (sep >= 2) { read_long_string(ls, seminfo, sep); return TK_STRING; } else if (sep == 0) /* '[=...' missing second bracket? */ lexerror(ls, "invalid long string delimiter", TK_STRING); return '['; } case '=': { next(ls); if (check_next1(ls, '=')) return TK_EQ; /* '==' */ else return '='; } case '<': { next(ls); if (check_next1(ls, '=')) return TK_LE; /* '<=' */ else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */ else return '<'; } case '>': { next(ls); if (check_next1(ls, '=')) return TK_GE; /* '>=' */ else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */ else return '>'; } case '/': { next(ls); if (check_next1(ls, '/')) return TK_IDIV; /* '//' */ else return '/'; } case '~': { next(ls); if (check_next1(ls, '=')) return TK_NE; /* '~=' */ else return '~'; } case ':': { next(ls); if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */ else return ':'; } case '"': case '\'': { /* short literal strings */ read_string(ls, ls->current, seminfo); return TK_STRING; } case '.': { /* '.', '..', '...', or number */ save_and_next(ls); if (check_next1(ls, '.')) { if (check_next1(ls, '.')) return TK_DOTS; /* '...' */ else return TK_CONCAT; /* '..' */ } else if (!lisdigit(ls->current)) return '.'; else return read_numeral(ls, seminfo); } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { return read_numeral(ls, seminfo); } case EOZ: { return TK_EOS; } default: { if (lislalpha(ls->current)) { /* identifier or reserved word? */ TString *ts; do { save_and_next(ls); } while (lislalnum(ls->current)); /* find or create string */ ts = luaS_newlstr(ls->L, luaZ_buffer(ls->buff), luaZ_bufflen(ls->buff)); if (isreserved(ts)) /* reserved word? */ return ts->extra - 1 + FIRST_RESERVED; else { seminfo->ts = anchorstr(ls, ts); return TK_NAME; } } else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */ int c = ls->current; next(ls); return c; } } } } } void luaX_next (LexState *ls) { ls->lastline = ls->linenumber; if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ ls->t = ls->lookahead; /* use this one */ ls->lookahead.token = TK_EOS; /* and discharge it */ } else ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ } int luaX_lookahead (LexState *ls) { lua_assert(ls->lookahead.token == TK_EOS); ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); return ls->lookahead.token; } /* ** $Id: lmem.c $ ** Interface to Memory Manager ** See Copyright Notice in lua.h */ #define lmem_c #define LUA_CORE #include #include "lua.h" /* ** About the realloc function: ** void *frealloc (void *ud, void *ptr, size_t osize, size_t nsize); ** ('osize' is the old size, 'nsize' is the new size) ** ** - frealloc(ud, p, x, 0) frees the block 'p' and returns NULL. ** Particularly, frealloc(ud, NULL, 0, 0) does nothing, ** which is equivalent to free(NULL) in ISO C. ** ** - frealloc(ud, NULL, x, s) creates a new block of size 's' ** (no matter 'x'). Returns NULL if it cannot create the new block. ** ** - otherwise, frealloc(ud, b, x, y) reallocates the block 'b' from ** size 'x' to size 'y'. Returns NULL if it cannot reallocate the ** block to the new size. */ /* ** Macro to call the allocation function. */ #define callfrealloc(g,block,os,ns) ((*g->frealloc)(g->ud, block, os, ns)) /* ** When an allocation fails, it will try again after an emergency ** collection, except when it cannot run a collection. The GC should ** not be called while the state is not fully built, as the collector ** is not yet fully initialized. Also, it should not be called when ** 'gcstopem' is true, because then the interpreter is in the middle of ** a collection step. */ #define cantryagain(g) (completestate(g) && !g->gcstopem) #if defined(EMERGENCYGCTESTS) /* ** First allocation will fail except when freeing a block (frees never ** fail) and when it cannot try again; this fail will trigger 'tryagain' ** and a full GC cycle at every allocation. */ static void *firsttry (global_State *g, void *block, size_t os, size_t ns) { if (ns > 0 && cantryagain(g)) return NULL; /* fail */ else /* normal allocation */ return callfrealloc(g, block, os, ns); } #else #define firsttry(g,block,os,ns) callfrealloc(g, block, os, ns) #endif /* ** {================================================================== ** Functions to allocate/deallocate arrays for the Parser ** =================================================================== */ /* ** Minimum size for arrays during parsing, to avoid overhead of ** reallocating to size 1, then 2, and then 4. All these arrays ** will be reallocated to exact sizes or erased when parsing ends. */ #define MINSIZEARRAY 4 void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize, unsigned size_elems, int limit, const char *what) { void *newblock; int size = *psize; if (nelems + 1 <= size) /* does one extra element still fit? */ return block; /* nothing to be done */ if (size >= limit / 2) { /* cannot double it? */ if (l_unlikely(size >= limit)) /* cannot grow even a little? */ luaG_runerror(L, "too many %s (limit is %d)", what, limit); size = limit; /* still have at least one free place */ } else { size *= 2; if (size < MINSIZEARRAY) size = MINSIZEARRAY; /* minimum size */ } lua_assert(nelems + 1 <= size && size <= limit); /* 'limit' ensures that multiplication will not overflow */ newblock = luaM_saferealloc_(L, block, cast_sizet(*psize) * size_elems, cast_sizet(size) * size_elems); *psize = size; /* update only when everything else is OK */ return newblock; } /* ** In prototypes, the size of the array is also its number of ** elements (to save memory). So, if it cannot shrink an array ** to its number of elements, the only option is to raise an ** error. */ void *luaM_shrinkvector_ (lua_State *L, void *block, int *size, int final_n, unsigned size_elem) { void *newblock; size_t oldsize = cast_sizet(*size) * size_elem; size_t newsize = cast_sizet(final_n) * size_elem; lua_assert(newsize <= oldsize); newblock = luaM_saferealloc_(L, block, oldsize, newsize); *size = final_n; return newblock; } /* }================================================================== */ l_noret luaM_toobig (lua_State *L) { luaG_runerror(L, "memory allocation error: block too big"); } /* ** Free memory */ void luaM_free_ (lua_State *L, void *block, size_t osize) { global_State *g = G(L); lua_assert((osize == 0) == (block == NULL)); callfrealloc(g, block, osize, 0); g->GCdebt += cast(l_mem, osize); } /* ** In case of allocation fail, this function will do an emergency ** collection to free some memory and then try the allocation again. */ static void *tryagain (lua_State *L, void *block, size_t osize, size_t nsize) { global_State *g = G(L); if (cantryagain(g)) { luaC_fullgc(L, 1); /* try to free some memory... */ return callfrealloc(g, block, osize, nsize); /* try again */ } else return NULL; /* cannot run an emergency collection */ } /* ** Generic allocation routine. */ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { void *newblock; global_State *g = G(L); lua_assert((osize == 0) == (block == NULL)); newblock = firsttry(g, block, osize, nsize); if (l_unlikely(newblock == NULL && nsize > 0)) { newblock = tryagain(L, block, osize, nsize); if (newblock == NULL) /* still no memory? */ return NULL; /* do not update 'GCdebt' */ } lua_assert((nsize == 0) == (newblock == NULL)); g->GCdebt -= cast(l_mem, nsize) - cast(l_mem, osize); return newblock; } void *luaM_saferealloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { void *newblock = luaM_realloc_(L, block, osize, nsize); if (l_unlikely(newblock == NULL && nsize > 0)) /* allocation failed? */ luaM_error(L); return newblock; } void *luaM_malloc_ (lua_State *L, size_t size, int tag) { if (size == 0) return NULL; /* that's all */ else { global_State *g = G(L); void *newblock = firsttry(g, NULL, cast_sizet(tag), size); if (l_unlikely(newblock == NULL)) { newblock = tryagain(L, NULL, cast_sizet(tag), size); if (newblock == NULL) luaM_error(L); } g->GCdebt -= cast(l_mem, size); return newblock; } } /* ** $Id: loadlib.c $ ** Dynamic library loader for Lua ** See Copyright Notice in lua.h ** ** This module contains an implementation of loadlib for Unix systems ** that have dlfcn, an implementation for Windows, and a stub for other ** systems. */ #define loadlib_c #define LUA_LIB #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" #ifdef USE_LUAINTF /* In $BAROOT/examples/MakoServer/MakoModuleExample/src/lua/internal Enable: http://makoserver.net/documentation/c-modules/ */ #include #endif /* ** LUA_CSUBSEP is the character that replaces dots in submodule names ** when searching for a C loader. ** LUA_LSUBSEP is the character that replaces dots in submodule names ** when searching for a Lua loader. */ #if !defined(LUA_CSUBSEP) #define LUA_CSUBSEP LUA_DIRSEP #endif #if !defined(LUA_LSUBSEP) #define LUA_LSUBSEP LUA_DIRSEP #endif /* prefix for open functions in C libraries */ #define LUA_POF "luaopen_" /* separator for open functions in C libraries */ #define LUA_OFSEP "_" /* ** key for table in the registry that keeps handles ** for all loaded C libraries */ static const char *const CLIBS = "_CLIBS"; #define LIB_FAIL "open" #define setprogdir(L) ((void)0) /* cast void* to a Lua function */ #define cast_Lfunc(p) cast(lua_CFunction, cast_func(p)) /* ** system-dependent functions */ /* ** unload library 'lib' */ static void lsys_unloadlib (void *lib); /* ** load C library in file 'path'. If 'seeglb', load with all names in ** the library global. ** Returns the library; in case of error, returns NULL plus an ** error string in the stack. */ static void *lsys_load (lua_State *L, const char *path, int seeglb); /* ** Try to find a function named 'sym' in library 'lib'. ** Returns the function; in case of error, returns NULL plus an ** error string in the stack. */ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym); #if defined(LUA_USE_DLOPEN) /* { */ /* ** {======================================================================== ** This is an implementation of loadlib based on the dlfcn interface, ** which is available in all POSIX systems. ** ========================================================================= */ #include static void lsys_unloadlib (void *lib) { dlclose(lib); } static void *lsys_load (lua_State *L, const char *path, int seeglb) { void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); if (l_unlikely(lib == NULL)) lua_pushstring(L, dlerror()); return lib; } static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { lua_CFunction f = cast_Lfunc(dlsym(lib, sym)); if (l_unlikely(f == NULL)) lua_pushstring(L, dlerror()); return f; } /* }====================================================== */ #elif defined(LUA_DL_DLL) /* }{ */ /* ** {====================================================================== ** This is an implementation of loadlib for Windows using native functions. ** ======================================================================= */ #include /* ** optional flags for LoadLibraryEx */ #if !defined(LUA_LLE_FLAGS) #define LUA_LLE_FLAGS 0 #endif #undef setprogdir /* ** Replace in the path (on the top of the stack) any occurrence ** of LUA_EXEC_DIR with the executable's path. */ static void setprogdir (lua_State *L) { char buff[MAX_PATH + 1]; char *lb; DWORD nsize = sizeof(buff)/sizeof(char); DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */ if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) luaL_error(L, "unable to get ModuleFileName"); else { *lb = '\0'; /* cut name on the last '\\' to get the path */ luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); lua_remove(L, -2); /* remove original string */ } } static void pusherror (lua_State *L) { int error = GetLastError(); char buffer[128]; if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) lua_pushstring(L, buffer); else lua_pushfstring(L, "system error %d\n", error); } static void lsys_unloadlib (void *lib) { FreeLibrary((HMODULE)lib); } static void *lsys_load (lua_State *L, const char *path, int seeglb) { HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); (void)(seeglb); /* not used: symbols are 'global' by default */ if (lib == NULL) pusherror(L); return lib; } static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { lua_CFunction f = cast_Lfunc(GetProcAddress((HMODULE)lib, sym)); if (f == NULL) pusherror(L); return f; } /* }====================================================== */ #else /* }{ */ /* ** {====================================================== ** Fallback for other systems ** ======================================================= */ #undef LIB_FAIL #define LIB_FAIL "absent" #define DLMSG "dynamic libraries not enabled; check your Lua installation" static void lsys_unloadlib (void *lib) { (void)(lib); /* not used */ } static void *lsys_load (lua_State *L, const char *path, int seeglb) { (void)(path); (void)(seeglb); /* not used */ lua_pushliteral(L, DLMSG); return NULL; } static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { (void)(lib); (void)(sym); /* not used */ lua_pushliteral(L, DLMSG); return NULL; } /* }====================================================== */ #endif /* } */ /* ** {================================================================== ** Set Paths ** =================================================================== */ /* ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment ** variables that Lua check to set its paths. */ #if !defined(LUA_PATH_VAR) #define LUA_PATH_VAR "LUA_PATH" #endif #if !defined(LUA_CPATH_VAR) #define LUA_CPATH_VAR "LUA_CPATH" #endif /* ** return registry.LUA_NOENV as a boolean */ static int noenv (lua_State *L) { int b; lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); b = lua_toboolean(L, -1); lua_pop(L, 1); /* remove value */ return b; } /* ** Set a path. (If using the default path, assume it is a string ** literal in C and create it as an external string.) */ static void setpath (lua_State *L, const char *fieldname, const char *envname, const char *dft) { const char *dftmark; const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX); const char *path = getenv(nver); /* try versioned name */ if (path == NULL) /* no versioned environment variable? */ path = getenv(envname); /* try unversioned name */ if (path == NULL || noenv(L)) /* no environment variable? */ lua_pushexternalstring(L, dft, strlen(dft), NULL, NULL); /* use default */ else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL) lua_pushstring(L, path); /* nothing to change */ else { /* path contains a ";;": insert default path in its place */ size_t len = strlen(path); luaL_Buffer b; luaL_buffinit(L, &b); if (path < dftmark) { /* is there a prefix before ';;'? */ luaL_addlstring(&b, path, ct_diff2sz(dftmark - path)); /* add it */ luaL_addchar(&b, *LUA_PATH_SEP); } luaL_addstring(&b, dft); /* add default */ if (dftmark < path + len - 2) { /* is there a suffix after ';;'? */ luaL_addchar(&b, *LUA_PATH_SEP); luaL_addlstring(&b, dftmark + 2, ct_diff2sz((path + len - 2) - dftmark)); } luaL_pushresult(&b); } setprogdir(L); lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */ lua_pop(L, 1); /* pop versioned variable name ('nver') */ } /* }================================================================== */ /* ** External strings created by DLLs may need the DLL code to be ** deallocated. This implies that a DLL can only be unloaded after all ** its strings were deallocated. To ensure that, we create a 'library ** string' to represent each DLL, and when this string is deallocated ** it closes its corresponding DLL. ** (The string itself is irrelevant; its userdata is the DLL pointer.) */ /* ** return registry.CLIBS[path] */ static void *checkclib (lua_State *L, const char *path) { void *plib; lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); lua_getfield(L, -1, path); plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ lua_pop(L, 2); /* pop CLIBS table and 'plib' */ return plib; } /* ** Deallocate function for library strings. ** Unload the DLL associated with the string being deallocated. */ static void *freelib (void *ud, void *ptr, size_t osize, size_t nsize) { /* string itself is irrelevant and static */ (void)ptr; (void)osize; (void)nsize; lsys_unloadlib(ud); /* unload library represented by the string */ return NULL; } /* ** Create a library string that, when deallocated, will unload 'plib' */ static void createlibstr (lua_State *L, void *plib) { /* common content for all library strings */ static const char dummy[] = "01234567890"; lua_pushexternalstring(L, dummy, sizeof(dummy) - 1, freelib, plib); } /* ** registry.CLIBS[path] = plib -- for queries. ** Also create a reference to strlib, so that the library string will ** only be collected when registry.CLIBS is collected. */ static void addtoclib (lua_State *L, const char *path, void *plib) { lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); lua_pushlightuserdata(L, plib); lua_setfield(L, -2, path); /* CLIBS[path] = plib */ createlibstr(L, plib); luaL_ref(L, -2); /* keep library string in CLIBS */ lua_pop(L, 1); /* pop CLIBS table */ } /* error codes for 'lookforfunc' */ #define ERRLIB 1 #define ERRFUNC 2 /* ** Look for a C function named 'sym' in a dynamically loaded library ** 'path'. ** First, check whether the library is already loaded; if not, try ** to load it. ** Then, if 'sym' is '*', return true (as library has been loaded). ** Otherwise, look for symbol 'sym' in the library and push a ** C function with that symbol. ** Return 0 with 'true' or a function in the stack; in case of ** errors, return an error code with an error message in the stack. */ static int lookforfunc (lua_State *L, const char *path, const char *sym) { void *reg = checkclib(L, path); /* check loaded C libraries */ if (reg == NULL) { /* must load library? */ reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */ if (reg == NULL) return ERRLIB; /* unable to load library */ addtoclib(L, path, reg); } if (*sym == '*') { /* loading only library (no function)? */ lua_pushboolean(L, 1); /* return 'true' */ return 0; /* no errors */ } else { lua_CFunction f = lsys_sym(L, reg, sym); if (f == NULL) return ERRFUNC; /* unable to find function */ /* Mod RTL */ #ifdef USE_LUAINTF lua_pushlightuserdata(L,(void*)&luaFuncs); lua_pushcclosure(L, f, 1); /* else create new function */ #else lua_pushcfunction(L, f); /* else create new function */ #endif return 0; /* no errors */ } } static int ll_loadlib (lua_State *L) { const char *path = luaL_checkstring(L, 1); const char *init = luaL_checkstring(L, 2); int stat = lookforfunc(L, path, init); if (l_likely(stat == 0)) /* no errors? */ return 1; /* return the loaded function */ else { /* error; error message is on stack top */ luaL_pushfail(L); lua_insert(L, -2); lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); return 3; /* return fail, error message, and where */ } } /* ** {====================================================== ** 'require' function ** ======================================================= */ #ifdef BA_HAS_ANSI_IO static int readable (const char *filename) { FILE *f = fopen(filename, "r"); /* try to open file */ if (f == NULL) return 0; /* open failed */ fclose(f); return 1; } #else static int readable (const char *filename) { (void)filename; return 0; /* Not found */ } #endif /* ** Get the next name in '*path' = 'name1;name2;name3;...', changing ** the ending ';' to '\0' to create a zero-terminated string. Return ** NULL when list ends. */ static const char *getnextfilename (char **path, char *end) { char *sep; char *name = *path; if (name == end) return NULL; /* no more names */ else if (*name == '\0') { /* from previous iteration? */ *name = *LUA_PATH_SEP; /* restore separator */ name++; /* skip it */ } sep = strchr(name, *LUA_PATH_SEP); /* find next separator */ if (sep == NULL) /* separator not found? */ sep = end; /* name goes until the end */ *sep = '\0'; /* finish file name */ *path = sep; /* will start next search from here */ return name; } /* ** Given a path such as ";blabla.so;blublu.so", pushes the string ** ** no file 'blabla.so' ** no file 'blublu.so' */ static void pusherrornotfound (lua_State *L, const char *path) { luaL_Buffer b; luaL_buffinit(L, &b); luaL_addstring(&b, "no file '"); luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '"); luaL_addstring(&b, "'"); luaL_pushresult(&b); } static const char *searchpath (lua_State *L, const char *name, const char *path, const char *sep, const char *dirsep) { luaL_Buffer buff; char *pathname; /* path with name inserted */ char *endpathname; /* its end */ const char *filename; /* separator is non-empty and appears in 'name'? */ if (*sep != '\0' && strchr(name, *sep) != NULL) name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ luaL_buffinit(L, &buff); /* add path to the buffer, replacing marks ('?') with the file name */ luaL_addgsub(&buff, path, LUA_PATH_MARK, name); luaL_addchar(&buff, '\0'); pathname = luaL_buffaddr(&buff); /* writable list of file names */ endpathname = pathname + luaL_bufflen(&buff) - 1; while ((filename = getnextfilename(&pathname, endpathname)) != NULL) { if (readable(filename)) /* does file exist and is readable? */ return lua_pushstring(L, filename); /* save and return name */ } luaL_pushresult(&buff); /* push path to create error message */ pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */ return NULL; /* not found */ } static int ll_searchpath (lua_State *L) { const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2), luaL_optstring(L, 3, "."), luaL_optstring(L, 4, LUA_DIRSEP)); if (f != NULL) return 1; else { /* error message is on top of the stack */ luaL_pushfail(L); lua_insert(L, -2); return 2; /* return fail + error message */ } } static const char *findfile (lua_State *L, const char *name, const char *pname, const char *dirsep) { const char *path; lua_getfield(L, lua_upvalueindex(1), pname); path = lua_tostring(L, -1); if (l_unlikely(path == NULL)) luaL_error(L, "'package.%s' must be a string", pname); return searchpath(L, name, path, ".", dirsep); } static int checkload (lua_State *L, int stat, const char *filename) { if (l_likely(stat)) { /* module loaded successfully? */ lua_pushstring(L, filename); /* will be 2nd argument to module */ return 2; /* return open function and file name */ } else return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s", lua_tostring(L, 1), filename, lua_tostring(L, -1)); } static int searcher_Lua (lua_State *L) { const char *filename; const char *name = luaL_checkstring(L, 1); filename = findfile(L, name, "path", LUA_LSUBSEP); if (filename == NULL) return 1; /* module not found in this path */ return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); } /* ** Try to find a load function for module 'modname' at file 'filename'. ** First, change '.' to '_' in 'modname'; then, if 'modname' has ** the form X-Y (that is, it has an "ignore mark"), build a function ** name "luaopen_X" and look for it. (For compatibility, if that ** fails, it also tries "luaopen_Y".) If there is no ignore mark, ** look for a function named "luaopen_modname". */ static int loadfunc (lua_State *L, const char *filename, const char *modname) { const char *openfunc; const char *mark; modname = luaL_gsub(L, modname, ".", LUA_OFSEP); mark = strchr(modname, *LUA_IGMARK); if (mark) { int stat; openfunc = lua_pushlstring(L, modname, ct_diff2sz(mark - modname)); openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc); stat = lookforfunc(L, filename, openfunc); if (stat != ERRFUNC) return stat; modname = mark + 1; /* else go ahead and try old-style name */ } openfunc = lua_pushfstring(L, LUA_POF"%s", modname); return lookforfunc(L, filename, openfunc); } static int searcher_C (lua_State *L) { const char *name = luaL_checkstring(L, 1); const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); if (filename == NULL) return 1; /* module not found in this path */ return checkload(L, (loadfunc(L, filename, name) == 0), filename); } static int searcher_Croot (lua_State *L) { const char *filename; const char *name = luaL_checkstring(L, 1); const char *p = strchr(name, '.'); int stat; if (p == NULL) return 0; /* is root */ lua_pushlstring(L, name, ct_diff2sz(p - name)); filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); if (filename == NULL) return 1; /* root not found */ if ((stat = loadfunc(L, filename, name)) != 0) { if (stat != ERRFUNC) return checkload(L, 0, filename); /* real error */ else { /* open function not found */ lua_pushfstring(L, "no module '%s' in file '%s'", name, filename); return 1; } } lua_pushstring(L, filename); /* will be 2nd argument to module */ return 2; } static int searcher_preload (lua_State *L) { const char *name = luaL_checkstring(L, 1); lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */ lua_pushfstring(L, "no field package.preload['%s']", name); return 1; } else { lua_pushliteral(L, ":preload:"); return 2; } } static void findloader (lua_State *L, const char *name) { int i; luaL_Buffer msg; /* to build error message */ /* push 'package.searchers' to index 3 in the stack */ if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE)) luaL_error(L, "'package.searchers' must be a table"); luaL_buffinit(L, &msg); luaL_addstring(&msg, "\n\t"); /* error-message prefix for first message */ /* iterate over available searchers to find a loader */ for (i = 1; ; i++) { if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */ lua_pop(L, 1); /* remove nil */ luaL_buffsub(&msg, 2); /* remove last prefix */ luaL_pushresult(&msg); /* create error message */ luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1)); } lua_pushstring(L, name); lua_call(L, 1, 2); /* call it */ if (lua_isfunction(L, -2)) /* did it find a loader? */ return; /* module loader found */ else if (lua_isstring(L, -2)) { /* searcher returned error message? */ lua_pop(L, 1); /* remove extra return */ luaL_addvalue(&msg); /* concatenate error message */ luaL_addstring(&msg, "\n\t"); /* prefix for next message */ } else /* no error message */ lua_pop(L, 2); /* remove both returns */ } } static int ll_require (lua_State *L) { const char *name = luaL_checkstring(L, 1); lua_settop(L, 1); /* LOADED table will be at index 2 */ lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_getfield(L, 2, name); /* LOADED[name] */ if (lua_toboolean(L, -1)) /* is it there? */ return 1; /* package is already loaded */ /* else must load package */ lua_pop(L, 1); /* remove 'getfield' result */ findloader(L, name); lua_rotate(L, -2, 1); /* function <-> loader data */ lua_pushvalue(L, 1); /* name is 1st argument to module loader */ lua_pushvalue(L, -3); /* loader data is 2nd argument */ /* stack: ...; loader data; loader function; mod. name; loader data */ lua_call(L, 2, 1); /* run loader to load module */ /* stack: ...; loader data; result from loader */ if (!lua_isnil(L, -1)) /* non-nil return? */ lua_setfield(L, 2, name); /* LOADED[name] = returned value */ else lua_pop(L, 1); /* pop nil */ if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */ lua_pushboolean(L, 1); /* use true as result */ lua_copy(L, -1, -2); /* replace loader result */ lua_setfield(L, 2, name); /* LOADED[name] = true */ } lua_rotate(L, -2, 1); /* loader data <-> module result */ return 2; /* return module result and loader data */ } /* }====================================================== */ static const luaL_Reg pk_funcs[] = { {"loadlib", ll_loadlib}, {"searchpath", ll_searchpath}, /* placeholders */ {"preload", NULL}, {"cpath", NULL}, {"path", NULL}, {"searchers", NULL}, {"loaded", NULL}, {NULL, NULL} }; static const luaL_Reg ll_funcs[] = { {"require", ll_require}, {NULL, NULL} }; static void createsearcherstable (lua_State *L) { static const lua_CFunction searchers[] = { searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL }; int i; /* create 'searchers' table */ lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); /* fill it with predefined searchers */ for (i=0; searchers[i] != NULL; i++) { lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ lua_pushcclosure(L, searchers[i], 1); lua_rawseti(L, -2, i+1); } lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ } LUAMOD_API int luaopen_package (lua_State *L) { luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */ lua_pop(L, 1); /* will not use it now */ luaL_newlib(L, pk_funcs); /* create 'package' table */ createsearcherstable(L); /* set paths */ setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); /* store config information */ lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); lua_setfield(L, -2, "config"); /* set field 'loaded' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_setfield(L, -2, "loaded"); /* set field 'preload' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); lua_setfield(L, -2, "preload"); lua_pushglobaltable(L); lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ lua_pop(L, 1); /* pop global table */ return 1; /* return 'package' table */ } /* ** $Id: lobject.c $ ** Some generic functions over Lua objects ** See Copyright Notice in lua.h */ #define lobject_c #define LUA_CORE #include #include #include #include #include #include #include #include "lua.h" /* ** Computes ceil(log2(x)), which is the smallest integer n such that ** x <= (1 << n). */ lu_byte luaO_ceillog2 (unsigned int x) { static const lu_byte log_2[256] = { /* log_2[i - 1] = ceil(log2(i)) */ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 }; int l = 0; x--; while (x >= 256) { l += 8; x >>= 8; } return cast_byte(l + log_2[x]); } /* ** Encodes 'p'% as a floating-point byte, represented as (eeeexxxx). ** The exponent is represented using excess-7. Mimicking IEEE 754, the ** representation normalizes the number when possible, assuming an extra ** 1 before the mantissa (xxxx) and adding one to the exponent (eeee) ** to signal that. So, the real value is (1xxxx) * 2^(eeee - 7 - 1) if ** eeee != 0, and (xxxx) * 2^-7 otherwise (subnormal numbers). */ lu_byte luaO_codeparam (unsigned int p) { if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u) /* overflow? */ return 0xFF; /* return maximum value */ else { p = (cast(l_uint32, p) * 128 + 99) / 100; /* round up the division */ if (p < 0x10) { /* subnormal number? */ /* exponent bits are already zero; nothing else to do */ return cast_byte(p); } else { /* p >= 0x10 implies ceil(log2(p + 1)) >= 5 */ /* preserve 5 bits in 'p' */ unsigned log = luaO_ceillog2(p + 1) - 5u; return cast_byte(((p >> log) - 0x10) | ((log + 1) << 4)); } } } /* ** Computes 'p' times 'x', where 'p' is a floating-point byte. Roughly, ** we have to multiply 'x' by the mantissa and then shift accordingly to ** the exponent. If the exponent is positive, both the multiplication ** and the shift increase 'x', so we have to care only about overflows. ** For negative exponents, however, multiplying before the shift keeps ** more significant bits, as long as the multiplication does not ** overflow, so we check which order is best. */ l_mem luaO_applyparam (lu_byte p, l_mem x) { int m = p & 0xF; /* mantissa */ int e = (p >> 4); /* exponent */ if (e > 0) { /* normalized? */ e--; /* correct exponent */ m += 0x10; /* correct mantissa; maximum value is 0x1F */ } e -= 7; /* correct excess-7 */ if (e >= 0) { if (x < (MAX_LMEM / 0x1F) >> e) /* no overflow? */ return (x * m) << e; /* order doesn't matter here */ else /* real overflow */ return MAX_LMEM; } else { /* negative exponent */ e = -e; if (x < MAX_LMEM / 0x1F) /* multiplication cannot overflow? */ return (x * m) >> e; /* multiplying first gives more precision */ else if ((x >> e) < MAX_LMEM / 0x1F) /* cannot overflow after shift? */ return (x >> e) * m; else /* real overflow */ return MAX_LMEM; } } static lua_Integer intarith (lua_State *L, int op, lua_Integer v1, lua_Integer v2) { switch (op) { case LUA_OPADD: return intop(+, v1, v2); case LUA_OPSUB:return intop(-, v1, v2); case LUA_OPMUL:return intop(*, v1, v2); case LUA_OPMOD: return luaV_mod(L, v1, v2); case LUA_OPIDIV: return luaV_idiv(L, v1, v2); case LUA_OPBAND: return intop(&, v1, v2); case LUA_OPBOR: return intop(|, v1, v2); case LUA_OPBXOR: return intop(^, v1, v2); case LUA_OPSHL: return luaV_shiftl(v1, v2); case LUA_OPSHR: return luaV_shiftr(v1, v2); case LUA_OPUNM: return intop(-, 0, v1); case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1); default: lua_assert(0); return 0; } } static lua_Number numarith (lua_State *L, int op, lua_Number v1, lua_Number v2) { switch (op) { case LUA_OPADD: return luai_numadd(L, v1, v2); case LUA_OPSUB: return luai_numsub(L, v1, v2); case LUA_OPMUL: return luai_nummul(L, v1, v2); case LUA_OPDIV: return luai_numdiv(L, v1, v2); case LUA_OPPOW: return luai_numpow(L, v1, v2); case LUA_OPIDIV: return luai_numidiv(L, v1, v2); case LUA_OPUNM: return luai_numunm(L, v1); case LUA_OPMOD: return luaV_modf(L, v1, v2); default: lua_assert(0); return 0; } } int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2, TValue *res) { switch (op) { case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* operate only on integers */ lua_Integer i1; lua_Integer i2; if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) { setivalue(res, intarith(L, op, i1, i2)); return 1; } else return 0; /* fail */ } case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */ lua_Number n1; lua_Number n2; if (tonumberns(p1, n1) && tonumberns(p2, n2)) { setfltvalue(res, numarith(L, op, n1, n2)); return 1; } else return 0; /* fail */ } default: { /* other operations */ lua_Number n1; lua_Number n2; if (ttisinteger(p1) && ttisinteger(p2)) { setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2))); return 1; } else if (tonumberns(p1, n1) && tonumberns(p2, n2)) { setfltvalue(res, numarith(L, op, n1, n2)); return 1; } else return 0; /* fail */ } } } void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, StkId res) { if (!luaO_rawarith(L, op, p1, p2, s2v(res))) { /* could not perform raw operation; try metamethod */ luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD)); } } lu_byte luaO_hexavalue (int c) { lua_assert(lisxdigit(c)); if (lisdigit(c)) return cast_byte(c - '0'); else return cast_byte((ltolower(c) - 'a') + 10); } static int isneg (const char **s) { if (**s == '-') { (*s)++; return 1; } else if (**s == '+') (*s)++; return 0; } /* ** {================================================================== ** Lua's implementation for 'lua_strx2number' ** =================================================================== */ #if !defined(lua_strx2number) /* maximum number of significant digits to read (to avoid overflows even with single floats) */ #define MAXSIGDIG 30 /* ** convert a hexadecimal numeric string to a number, following ** C99 specification for 'strtod' */ static lua_Number lua_strx2number (const char *s, char **endptr) { int dot = lua_getlocaledecpoint(); lua_Number r = l_mathop(0.0); /* result (accumulator) */ int sigdig = 0; /* number of significant digits */ int nosigdig = 0; /* number of non-significant digits */ int e = 0; /* exponent correction */ int neg; /* 1 if number is negative */ int hasdot = 0; /* true after seen a dot */ *endptr = cast_charp(s); /* nothing is valid yet */ while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ neg = isneg(&s); /* check sign */ if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ return l_mathop(0.0); /* invalid format (no '0x') */ for (s += 2; ; s++) { /* skip '0x' and read numeral */ if (*s == dot) { if (hasdot) break; /* second dot? stop loop */ else hasdot = 1; } else if (lisxdigit(cast_uchar(*s))) { if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */ nosigdig++; else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */ r = (r * l_mathop(16.0)) + luaO_hexavalue(*s); else e++; /* too many digits; ignore, but still count for exponent */ if (hasdot) e--; /* decimal digit? correct exponent */ } else break; /* neither a dot nor a digit */ } if (nosigdig + sigdig == 0) /* no digits? */ return l_mathop(0.0); /* invalid format */ *endptr = cast_charp(s); /* valid up to here */ e *= 4; /* each digit multiplies/divides value by 2^4 */ if (*s == 'p' || *s == 'P') { /* exponent part? */ int exp1 = 0; /* exponent value */ int neg1; /* exponent sign */ s++; /* skip 'p' */ neg1 = isneg(&s); /* sign */ if (!lisdigit(cast_uchar(*s))) return l_mathop(0.0); /* invalid; must have at least one digit */ while (lisdigit(cast_uchar(*s))) /* read exponent */ exp1 = exp1 * 10 + *(s++) - '0'; if (neg1) exp1 = -exp1; e += exp1; *endptr = cast_charp(s); /* valid up to here */ } if (neg) r = -r; return l_mathop(ldexp)(r, e); } #endif /* }====================================================== */ /* maximum length of a numeral to be converted to a number */ #if !defined (L_MAXLENNUM) #define L_MAXLENNUM 200 #endif /* ** Convert string 's' to a Lua number (put in 'result'). Return NULL on ** fail or the address of the ending '\0' on success. ('mode' == 'x') ** means a hexadecimal numeral. */ static const char *l_str2dloc (const char *s, lua_Number *result, int mode) { char *endptr; *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */ : lua_str2number(s, &endptr); if (endptr == s) return NULL; /* nothing recognized? */ while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */ return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */ } /* ** Convert string 's' to a Lua number (put in 'result') handling the ** current locale. ** This function accepts both the current locale or a dot as the radix ** mark. If the conversion fails, it may mean number has a dot but ** locale accepts something else. In that case, the code copies 's' ** to a buffer (because 's' is read-only), changes the dot to the ** current locale radix mark, and tries to convert again. ** The variable 'mode' checks for special characters in the string: ** - 'n' means 'inf' or 'nan' (which should be rejected) ** - 'x' means a hexadecimal numeral ** - '.' just optimizes the search for the common case (no special chars) */ static const char *l_str2d (const char *s, lua_Number *result) { const char *endptr; const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */ int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0; if (mode == 'n') /* reject 'inf' and 'nan' */ return NULL; endptr = l_str2dloc(s, result, mode); /* try to convert */ if (endptr == NULL) { /* failed? may be a different locale */ char buff[L_MAXLENNUM + 1]; const char *pdot = strchr(s, '.'); if (pdot == NULL || strlen(s) > L_MAXLENNUM) return NULL; /* string too long or no dot; fail */ strcpy(buff, s); /* copy string to buffer */ buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */ endptr = l_str2dloc(buff, result, mode); /* try again */ if (endptr != NULL) endptr = s + (endptr - buff); /* make relative to 's' */ } return endptr; } #define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10) #define MAXLASTD cast_int(LUA_MAXINTEGER % 10) static const char *l_str2int (const char *s, lua_Integer *result) { lua_Unsigned a = 0; int empty = 1; int neg; while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ neg = isneg(&s); if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) { /* hex? */ s += 2; /* skip '0x' */ for (; lisxdigit(cast_uchar(*s)); s++) { a = a * 16 + luaO_hexavalue(*s); empty = 0; } } else { /* decimal */ for (; lisdigit(cast_uchar(*s)); s++) { int d = *s - '0'; if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */ return NULL; /* do not accept it (as integer) */ a = a * 10 + cast_uint(d); empty = 0; } } while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */ if (empty || *s != '\0') return NULL; /* something wrong in the numeral */ else { *result = l_castU2S((neg) ? 0u - a : a); return s; } } size_t luaO_str2num (const char *s, TValue *o) { lua_Integer i; lua_Number n; const char *e; if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */ setivalue(o, i); } else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */ setfltvalue(o, n); } else return 0; /* conversion failed */ return ct_diff2sz(e - s) + 1; /* success; return string size */ } int luaO_utf8esc (char *buff, l_uint32 x) { int n = 1; /* number of bytes put in buffer (backwards) */ lua_assert(x <= 0x7FFFFFFFu); if (x < 0x80) /* ASCII? */ buff[UTF8BUFFSZ - 1] = cast_char(x); else { /* need continuation bytes */ unsigned int mfb = 0x3f; /* maximum that fits in first byte */ do { /* add continuation bytes */ buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f)); x >>= 6; /* remove added bits */ mfb >>= 1; /* now there is one less bit available in first byte */ } while (x > mfb); /* still needs continuation byte? */ buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */ } return n; } /* ** The size of the buffer for the conversion of a number to a string ** 'LUA_N2SBUFFSZ' must be enough to accommodate both LUA_INTEGER_FMT ** and LUA_NUMBER_FMT. For a long long int, this is 19 digits plus a ** sign and a final '\0', adding to 21. For a long double, it can go to ** a sign, the dot, an exponent letter, an exponent sign, 4 exponent ** digits, the final '\0', plus the significant digits, which are ** approximately the *_DIG attribute. */ #if LUA_N2SBUFFSZ < (20 + l_floatatt(DIG)) #error "invalid value for LUA_N2SBUFFSZ" #endif /* ** Convert a float to a string, adding it to a buffer. First try with ** a not too large number of digits, to avoid noise (for instance, ** 1.1 going to "1.1000000000000001"). If that lose precision, so ** that reading the result back gives a different number, then do the ** conversion again with extra precision. Moreover, if the numeral looks ** like an integer (without a decimal point or an exponent), add ".0" to ** its end. */ static int tostringbuffFloat (lua_Number n, char *buff) { /* first conversion */ int len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT, (LUAI_UACNUMBER)n); lua_Number check = lua_str2number(buff, NULL); /* read it back */ if (check != n) { /* not enough precision? */ /* convert again with more precision */ len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT_N, (LUAI_UACNUMBER)n); } /* looks like an integer? */ if (buff[strspn(buff, "-0123456789")] == '\0') { buff[len++] = lua_getlocaledecpoint(); buff[len++] = '0'; /* adds '.0' to result */ } return len; } /* ** Convert a number object to a string, adding it to a buffer. */ unsigned luaO_tostringbuff (const TValue *obj, char *buff) { int len; lua_assert(ttisnumber(obj)); if (ttisinteger(obj)) len = lua_integer2str(buff, LUA_N2SBUFFSZ, ivalue(obj)); else len = tostringbuffFloat(fltvalue(obj), buff); lua_assert(len < LUA_N2SBUFFSZ); return cast_uint(len); } /* ** Convert a number object to a Lua string, replacing the value at 'obj' */ void luaO_tostring (lua_State *L, TValue *obj) { char buff[LUA_N2SBUFFSZ]; unsigned len = luaO_tostringbuff(obj, buff); setsvalue(L, obj, luaS_newlstr(L, buff, len)); } /* ** {================================================================== ** 'luaO_pushvfstring' ** =================================================================== */ /* ** Size for buffer space used by 'luaO_pushvfstring'. It should be ** (LUA_IDSIZE + LUA_N2SBUFFSZ) + a minimal space for basic messages, ** so that 'luaG_addinfo' can work directly on the static buffer. */ #define BUFVFS cast_uint(LUA_IDSIZE + LUA_N2SBUFFSZ + 95) /* ** Buffer used by 'luaO_pushvfstring'. 'err' signals an error while ** building result (memory error [1] or buffer overflow [2]). */ typedef struct BuffFS { lua_State *L; char *b; size_t buffsize; size_t blen; /* length of string in 'buff' */ int err; char space[BUFVFS]; /* initial buffer */ } BuffFS; static void initbuff (lua_State *L, BuffFS *buff) { buff->L = L; buff->b = buff->space; buff->buffsize = sizeof(buff->space); buff->blen = 0; buff->err = 0; } /* ** Push final result from 'luaO_pushvfstring'. This function may raise ** errors explicitly or through memory errors, so it must run protected. */ static void pushbuff (lua_State *L, void *ud) { BuffFS *buff = cast(BuffFS*, ud); switch (buff->err) { case 1: /* memory error */ luaD_throw(L, LUA_ERRMEM); break; case 2: /* length overflow: Add "..." at the end of result */ if (buff->buffsize - buff->blen < 3) strcpy(buff->b + buff->blen - 3, "..."); /* 'blen' must be > 3 */ else { /* there is enough space left for the "..." */ strcpy(buff->b + buff->blen, "..."); buff->blen += 3; } /* FALLTHROUGH */ default: { /* no errors, but it can raise one creating the new string */ TString *ts = luaS_newlstr(L, buff->b, buff->blen); setsvalue2s(L, L->top.p, ts); L->top.p++; } } } static const char *clearbuff (BuffFS *buff) { lua_State *L = buff->L; const char *res; if (luaD_rawrunprotected(L, pushbuff, buff) != LUA_OK) /* errors? */ res = NULL; /* error message is on the top of the stack */ else res = getstr(tsvalue(s2v(L->top.p - 1))); if (buff->b != buff->space) /* using dynamic buffer? */ luaM_freearray(L, buff->b, buff->buffsize); /* free it */ return res; } static void addstr2buff (BuffFS *buff, const char *str, size_t slen) { size_t left = buff->buffsize - buff->blen; /* space left in the buffer */ if (buff->err) /* do nothing else after an error */ return; if (slen > left) { /* new string doesn't fit into current buffer? */ if (slen > ((MAX_SIZE/2) - buff->blen)) { /* overflow? */ memcpy(buff->b + buff->blen, str, left); /* copy what it can */ buff->blen = buff->buffsize; buff->err = 2; /* doesn't add anything else */ return; } else { size_t newsize = buff->buffsize + slen; /* limited to MAX_SIZE/2 */ char *newb = (buff->b == buff->space) /* still using static space? */ ? luaM_reallocvector(buff->L, NULL, 0, newsize, char) : luaM_reallocvector(buff->L, buff->b, buff->buffsize, newsize, char); if (newb == NULL) { /* allocation error? */ buff->err = 1; /* signal a memory error */ return; } if (buff->b == buff->space) /* new buffer (not reallocated)? */ memcpy(newb, buff->b, buff->blen); /* copy previous content */ buff->b = newb; /* set new (larger) buffer... */ buff->buffsize = newsize; /* ...and its new size */ } } memcpy(buff->b + buff->blen, str, slen); /* copy new content */ buff->blen += slen; } /* ** Add a numeral to the buffer. */ static void addnum2buff (BuffFS *buff, TValue *num) { char numbuff[LUA_N2SBUFFSZ]; unsigned len = luaO_tostringbuff(num, numbuff); addstr2buff(buff, numbuff, len); } /* ** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%' conventional formats, plus Lua-specific '%I' and '%U' */ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { BuffFS buff; /* holds last part of the result */ const char *e; /* points to next '%' */ initbuff(L, &buff); while ((e = strchr(fmt, '%')) != NULL) { addstr2buff(&buff, fmt, ct_diff2sz(e - fmt)); /* add 'fmt' up to '%' */ switch (*(e + 1)) { /* conversion specifier */ case 's': { /* zero-terminated string */ const char *s = va_arg(argp, char *); if (s == NULL) s = "(null)"; addstr2buff(&buff, s, strlen(s)); break; } case 'c': { /* an 'int' as a character */ char c = cast_char(va_arg(argp, int)); addstr2buff(&buff, &c, sizeof(char)); break; } case 'd': { /* an 'int' */ TValue num; setivalue(&num, va_arg(argp, int)); addnum2buff(&buff, &num); break; } case 'I': { /* a 'lua_Integer' */ TValue num; setivalue(&num, cast_Integer(va_arg(argp, l_uacInt))); addnum2buff(&buff, &num); break; } case 'f': { /* a 'lua_Number' */ TValue num; setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber))); addnum2buff(&buff, &num); break; } case 'p': { /* a pointer */ char bf[LUA_N2SBUFFSZ]; /* enough space for '%p' */ void *p = va_arg(argp, void *); int len = lua_pointer2str(bf, LUA_N2SBUFFSZ, p); addstr2buff(&buff, bf, cast_uint(len)); break; } case 'U': { /* an 'unsigned long' as a UTF-8 sequence */ char bf[UTF8BUFFSZ]; unsigned long arg = va_arg(argp, unsigned long); int len = luaO_utf8esc(bf, cast(l_uint32, arg)); addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len)); break; } case '%': { addstr2buff(&buff, "%", 1); break; } default: { addstr2buff(&buff, e, 2); /* keep unknown format in the result */ break; } } fmt = e + 2; /* skip '%' and the specifier */ } addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */ return clearbuff(&buff); /* empty buffer into a new string */ } const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { const char *msg; va_list argp; va_start(argp, fmt); msg = luaO_pushvfstring(L, fmt, argp); va_end(argp); if (msg == NULL) /* error? */ luaD_throw(L, LUA_ERRMEM); return msg; } /* }================================================================== */ #define RETS "..." #define PRE "[string \"" #define POS "\"]" #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) void luaO_chunkid (char *out, const char *source, size_t srclen) { size_t bufflen = LUA_IDSIZE; /* free space in buffer */ if (*source == '=') { /* 'literal' source */ if (srclen <= bufflen) /* small enough? */ memcpy(out, source + 1, srclen * sizeof(char)); else { /* truncate it */ addstr(out, source + 1, bufflen - 1); *out = '\0'; } } else if (*source == '@') { /* file name */ if (srclen <= bufflen) /* small enough? */ memcpy(out, source + 1, srclen * sizeof(char)); else { /* add '...' before rest of name */ addstr(out, RETS, LL(RETS)); bufflen -= LL(RETS); memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char)); } } else { /* string; format as [string "source"] */ const char *nl = strchr(source, '\n'); /* find first new line (if any) */ addstr(out, PRE, LL(PRE)); /* add prefix */ bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ if (srclen < bufflen && nl == NULL) { /* small one-line source? */ addstr(out, source, srclen); /* keep it */ } else { if (nl != NULL) srclen = ct_diff2sz(nl - source); /* stop at first newline */ if (srclen > bufflen) srclen = bufflen; addstr(out, source, srclen); addstr(out, RETS, LL(RETS)); } memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); } } /* ** $Id: lopcodes.c $ ** Opcodes for Lua virtual machine ** See Copyright Notice in lua.h */ #define lopcodes_c #define LUA_CORE #define opmode(mm,ot,it,t,a,m) \ (((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m)) /* ORDER OP */ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { /* MM OT IT T A mode opcode */ opmode(0, 0, 0, 0, 1, iABC) /* OP_MOVE */ ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADI */ ,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADF */ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADK */ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADKX */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADFALSE */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LFALSESKIP */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADTRUE */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADNIL */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETUPVAL */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABUP */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABLE */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETI */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETFIELD */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABUP */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABLE */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETI */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETFIELD */ ,opmode(0, 0, 0, 0, 1, ivABC) /* OP_NEWTABLE */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SELF */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDI */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUBK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MULK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MODK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POWK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIVK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIVK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BANDK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BORK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXORK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHLI */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHRI */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADD */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUB */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MUL */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_MOD */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_POW */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIV */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIV */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BAND */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BOR */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXOR */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHL */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHR */ ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBIN */ ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINI */ ,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINK */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_UNM */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_BNOT */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_NOT */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_LEN */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_CONCAT */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_CLOSE */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TBC */ ,opmode(0, 0, 0, 0, 0, isJ) /* OP_JMP */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQ */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LT */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LE */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQK */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQI */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LTI */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_LEI */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GTI */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_GEI */ ,opmode(0, 0, 0, 1, 0, iABC) /* OP_TEST */ ,opmode(0, 0, 0, 1, 1, iABC) /* OP_TESTSET */ ,opmode(0, 1, 1, 0, 1, iABC) /* OP_CALL */ ,opmode(0, 1, 1, 0, 1, iABC) /* OP_TAILCALL */ ,opmode(0, 0, 1, 0, 0, iABC) /* OP_RETURN */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN0 */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN1 */ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORLOOP */ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORPREP */ ,opmode(0, 0, 0, 0, 0, iABx) /* OP_TFORPREP */ ,opmode(0, 0, 0, 0, 0, iABC) /* OP_TFORCALL */ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_TFORLOOP */ ,opmode(0, 0, 1, 0, 0, ivABC) /* OP_SETLIST */ ,opmode(0, 0, 0, 0, 1, iABx) /* OP_CLOSURE */ ,opmode(0, 1, 0, 0, 1, iABC) /* OP_VARARG */ ,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETVARG */ ,opmode(0, 0, 0, 0, 0, iABx) /* OP_ERRNNIL */ ,opmode(0, 0, 1, 0, 1, iABC) /* OP_VARARGPREP */ ,opmode(0, 0, 0, 0, 0, iAx) /* OP_EXTRAARG */ }; /* ** Check whether instruction sets top for next instruction, that is, ** it results in multiple values. */ int luaP_isOT (Instruction i) { OpCode op = GET_OPCODE(i); switch (op) { case OP_TAILCALL: return 1; default: return testOTMode(op) && GETARG_C(i) == 0; } } /* ** Check whether instruction uses top from previous instruction, that is, ** it accepts multiple results. */ int luaP_isIT (Instruction i) { OpCode op = GET_OPCODE(i); switch (op) { case OP_SETLIST: return testITMode(GET_OPCODE(i)) && GETARG_vB(i) == 0; default: return testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0; } } /* ** $Id: lparser.c $ ** Lua Parser ** See Copyright Notice in lua.h */ #define lparser_c #define LUA_CORE #include #include #include "lua.h" /* maximum number of variable declarations per function (must be smaller than 250, due to the bytecode format) */ #define MAXVARS 200 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG) /* because all strings are unified by the scanner, the parser can use pointer equality for string equality */ #define eqstr(a,b) ((a) == (b)) /* ** nodes for block list (list of active blocks) */ typedef struct BlockCnt { struct BlockCnt *previous; /* chain */ int firstlabel; /* index of first label in this block */ int firstgoto; /* index of first pending goto in this block */ short nactvar; /* number of active declarations at block entry */ lu_byte upval; /* true if some variable in the block is an upvalue */ lu_byte isloop; /* 1 if 'block' is a loop; 2 if it has pending breaks */ lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */ } BlockCnt; /* ** prototypes for recursive non-terminal functions */ static void statement (LexState *ls); static void expr (LexState *ls, expdesc *v); static l_noret error_expected (LexState *ls, int token) { luaX_syntaxerror(ls, luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); } static l_noret errorlimit (FuncState *fs, int limit, const char *what) { lua_State *L = fs->ls->L; const char *msg; int line = fs->f->linedefined; const char *where = (line == 0) ? "main function" : luaO_pushfstring(L, "function at line %d", line); msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", what, limit, where); luaX_syntaxerror(fs->ls, msg); } void luaY_checklimit (FuncState *fs, int v, int l, const char *what) { if (l_unlikely(v > l)) errorlimit(fs, l, what); } /* ** Test whether next token is 'c'; if so, skip it. */ static int testnext (LexState *ls, int c) { if (ls->t.token == c) { luaX_next(ls); return 1; } else return 0; } /* ** Check that next token is 'c'. */ static void check (LexState *ls, int c) { if (ls->t.token != c) error_expected(ls, c); } /* ** Check that next token is 'c' and skip it. */ static void checknext (LexState *ls, int c) { check(ls, c); luaX_next(ls); } #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } /* ** Check that next token is 'what' and skip it. In case of error, ** raise an error that the expected 'what' should match a 'who' ** in line 'where' (if that is not the current line). */ static void check_match (LexState *ls, int what, int who, int where) { if (l_unlikely(!testnext(ls, what))) { if (where == ls->linenumber) /* all in the same line? */ error_expected(ls, what); /* do not need a complex message */ else { luaX_syntaxerror(ls, luaO_pushfstring(ls->L, "%s expected (to close %s at line %d)", luaX_token2str(ls, what), luaX_token2str(ls, who), where)); } } } static TString *str_checkname (LexState *ls) { TString *ts; check(ls, TK_NAME); ts = ls->t.seminfo.ts; luaX_next(ls); return ts; } static void init_exp (expdesc *e, expkind k, int i) { e->f = e->t = NO_JUMP; e->k = k; e->u.info = i; } static void codestring (expdesc *e, TString *s) { e->f = e->t = NO_JUMP; e->k = VKSTR; e->u.strval = s; } static void codename (LexState *ls, expdesc *e) { codestring(e, str_checkname(ls)); } /* ** Register a new local variable in the active 'Proto' (for debug ** information). */ static short registerlocalvar (LexState *ls, FuncState *fs, TString *varname) { Proto *f = fs->f; int oldsize = f->sizelocvars; luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars, LocVar, SHRT_MAX, "local variables"); while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; f->locvars[fs->ndebugvars].varname = varname; f->locvars[fs->ndebugvars].startpc = fs->pc; luaC_objbarrier(ls->L, f, varname); return fs->ndebugvars++; } /* ** Create a new variable with the given 'name' and given 'kind'. ** Return its index in the function. */ static int new_varkind (LexState *ls, TString *name, lu_byte kind) { lua_State *L = ls->L; FuncState *fs = ls->fs; Dyndata *dyd = ls->dyd; Vardesc *var; luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1, dyd->actvar.size, Vardesc, SHRT_MAX, "variable declarations"); var = &dyd->actvar.arr[dyd->actvar.n++]; var->vd.kind = kind; /* default */ var->vd.name = name; return dyd->actvar.n - 1 - fs->firstlocal; } /* ** Create a new local variable with the given 'name' and regular kind. */ static int new_localvar (LexState *ls, TString *name) { return new_varkind(ls, name, VDKREG); } #define new_localvarliteral(ls,v) \ new_localvar(ls, \ luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1)); /* ** Return the "variable description" (Vardesc) of a given variable. ** (Unless noted otherwise, all variables are referred to by their ** compiler indices.) */ static Vardesc *getlocalvardesc (FuncState *fs, int vidx) { return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx]; } /* ** Convert 'nvar', a compiler index level, to its corresponding ** register. For that, search for the highest variable below that level ** that is in a register and uses its register index ('ridx') plus one. */ static lu_byte reglevel (FuncState *fs, int nvar) { while (nvar-- > 0) { Vardesc *vd = getlocalvardesc(fs, nvar); /* get previous variable */ if (varinreg(vd)) /* is in a register? */ return cast_byte(vd->vd.ridx + 1); } return 0; /* no variables in registers */ } /* ** Return the number of variables in the register stack for the given ** function. */ lu_byte luaY_nvarstack (FuncState *fs) { return reglevel(fs, fs->nactvar); } /* ** Get the debug-information entry for current variable 'vidx'. */ static LocVar *localdebuginfo (FuncState *fs, int vidx) { Vardesc *vd = getlocalvardesc(fs, vidx); if (!varinreg(vd)) return NULL; /* no debug info. for constants */ else { int idx = vd->vd.pidx; lua_assert(idx < fs->ndebugvars); return &fs->f->locvars[idx]; } } /* ** Create an expression representing variable 'vidx' */ static void init_var (FuncState *fs, expdesc *e, int vidx) { e->f = e->t = NO_JUMP; e->k = VLOCAL; e->u.var.vidx = cast_short(vidx); e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx; } /* ** Raises an error if variable described by 'e' is read only; moreover, ** if 'e' is t[exp] where t is the vararg parameter, change it to index ** a real table. (Virtual vararg tables cannot be changed.) */ static void check_readonly (LexState *ls, expdesc *e) { FuncState *fs = ls->fs; TString *varname = NULL; /* to be set if variable is const */ switch (e->k) { case VCONST: { varname = ls->dyd->actvar.arr[e->u.info].vd.name; break; } case VLOCAL: case VVARGVAR: { Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx); if (vardesc->vd.kind != VDKREG) /* not a regular variable? */ varname = vardesc->vd.name; break; } case VUPVAL: { Upvaldesc *up = &fs->f->upvalues[e->u.info]; if (up->kind != VDKREG) varname = up->name; break; } case VVARGIND: { needvatab(fs->f); /* function will need a vararg table */ e->k = VINDEXED; } /* FALLTHROUGH */ case VINDEXUP: case VINDEXSTR: case VINDEXED: { /* global variable */ if (e->u.ind.ro) /* read-only? */ varname = tsvalue(&fs->f->k[e->u.ind.keystr]); break; } default: lua_assert(e->k == VINDEXI); /* this one doesn't need any check */ return; /* integer index cannot be read-only */ } if (varname) luaK_semerror(ls, "attempt to assign to const variable '%s'", getstr(varname)); } /* ** Start the scope for the last 'nvars' created variables. */ static void adjustlocalvars (LexState *ls, int nvars) { FuncState *fs = ls->fs; int reglevel = luaY_nvarstack(fs); int i; for (i = 0; i < nvars; i++) { int vidx = fs->nactvar++; Vardesc *var = getlocalvardesc(fs, vidx); var->vd.ridx = cast_byte(reglevel++); var->vd.pidx = registerlocalvar(ls, fs, var->vd.name); luaY_checklimit(fs, reglevel, MAXVARS, "local variables"); } } /* ** Close the scope for all variables up to level 'tolevel'. ** (debug info.) */ static void removevars (FuncState *fs, int tolevel) { fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); while (fs->nactvar > tolevel) { LocVar *var = localdebuginfo(fs, --fs->nactvar); if (var) /* does it have debug information? */ var->endpc = fs->pc; } } /* ** Search the upvalues of the function 'fs' for one ** with the given 'name'. */ static int searchupvalue (FuncState *fs, TString *name) { int i; Upvaldesc *up = fs->f->upvalues; for (i = 0; i < fs->nups; i++) { if (eqstr(up[i].name, name)) return i; } return -1; /* not found */ } static Upvaldesc *allocupvalue (FuncState *fs) { Proto *f = fs->f; int oldsize = f->sizeupvalues; luaY_checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, Upvaldesc, MAXUPVAL, "upvalues"); while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL; return &f->upvalues[fs->nups++]; } static int newupvalue (FuncState *fs, TString *name, expdesc *v) { Upvaldesc *up = allocupvalue(fs); FuncState *prev = fs->prev; if (v->k == VLOCAL) { up->instack = 1; up->idx = v->u.var.ridx; up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind; lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name)); } else { up->instack = 0; up->idx = cast_byte(v->u.info); up->kind = prev->f->upvalues[v->u.info].kind; lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name)); } up->name = name; luaC_objbarrier(fs->ls->L, fs->f, name); return fs->nups - 1; } /* ** Look for an active variable with the name 'n' in the ** function 'fs'. If found, initialize 'var' with it and return ** its expression kind; otherwise return -1. While searching, ** var->u.info==-1 means that the preambular global declaration is ** active (the default while there is no other global declaration); ** var->u.info==-2 means there is no active collective declaration ** (some previous global declaration but no collective declaration); ** and var->u.info>=0 points to the inner-most (the first one found) ** collective declaration, if there is one. */ static int searchvar (FuncState *fs, TString *n, expdesc *var) { int i; for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { Vardesc *vd = getlocalvardesc(fs, i); if (varglobal(vd)) { /* global declaration? */ if (vd->vd.name == NULL) { /* collective declaration? */ if (var->u.info < 0) /* no previous collective declaration? */ var->u.info = fs->firstlocal + i; /* this is the first one */ } else { /* global name */ if (eqstr(n, vd->vd.name)) { /* found? */ init_exp(var, VGLOBAL, fs->firstlocal + i); return VGLOBAL; } else if (var->u.info == -1) /* active preambular declaration? */ var->u.info = -2; /* invalidate preambular declaration */ } } else if (eqstr(n, vd->vd.name)) { /* found? */ if (vd->vd.kind == RDKCTC) /* compile-time constant? */ init_exp(var, VCONST, fs->firstlocal + i); else { /* local variable */ init_var(fs, var, i); if (vd->vd.kind == RDKVAVAR) /* vararg parameter? */ var->k = VVARGVAR; } return cast_int(var->k); } } return -1; /* not found */ } /* ** Mark block where variable at given level was defined ** (to emit close instructions later). */ static void markupval (FuncState *fs, int level) { BlockCnt *bl = fs->bl; while (bl->nactvar > level) bl = bl->previous; bl->upval = 1; fs->needclose = 1; } /* ** Mark that current block has a to-be-closed variable. */ static void marktobeclosed (FuncState *fs) { BlockCnt *bl = fs->bl; bl->upval = 1; bl->insidetbc = 1; fs->needclose = 1; } /* ** Find a variable with the given name 'n'. If it is an upvalue, add ** this upvalue into all intermediate functions. If it is a global, set ** 'var' as 'void' as a flag. */ static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { int v = searchvar(fs, n, var); /* look up variables at current level */ if (v >= 0) { /* found? */ if (!base) { if (var->k == VVARGVAR) /* vararg parameter? */ luaK_vapar2local(fs, var); /* change it to a regular local */ if (var->k == VLOCAL) markupval(fs, var->u.var.vidx); /* will be used as an upvalue */ } /* else nothing else to be done */ } else { /* not found at current level; try upvalues */ int idx = searchupvalue(fs, n); /* try existing upvalues */ if (idx < 0) { /* not found? */ if (fs->prev != NULL) /* more levels? */ singlevaraux(fs->prev, n, var, 0); /* try upper levels */ if (var->k == VLOCAL || var->k == VUPVAL) /* local or upvalue? */ idx = newupvalue(fs, n, var); /* will be a new upvalue */ else /* it is a global or a constant */ return; /* don't need to do anything at this level */ } init_exp(var, VUPVAL, idx); /* new or old upvalue */ } } static void buildglobal (LexState *ls, TString *varname, expdesc *var) { FuncState *fs = ls->fs; expdesc key; init_exp(var, VGLOBAL, -1); /* global by default */ singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ if (var->k == VGLOBAL) luaK_semerror(ls, "%s is global when accessing variable '%s'", LUA_ENV, getstr(varname)); luaK_exp2anyregup(fs, var); /* _ENV could be a constant */ codestring(&key, varname); /* key is variable name */ luaK_indexed(fs, var, &key); /* 'var' represents _ENV[varname] */ } /* ** Find a variable with the given name 'n', handling global variables ** too. */ static void buildvar (LexState *ls, TString *varname, expdesc *var) { FuncState *fs = ls->fs; init_exp(var, VGLOBAL, -1); /* global by default */ singlevaraux(fs, varname, var, 1); if (var->k == VGLOBAL) { /* global name? */ int info = var->u.info; /* global by default in the scope of a global declaration? */ if (info == -2) luaK_semerror(ls, "variable '%s' not declared", getstr(varname)); buildglobal(ls, varname, var); if (info != -1 && ls->dyd->actvar.arr[info].vd.kind == GDKCONST) var->u.ind.ro = 1; /* mark variable as read-only */ else /* anyway must be a global */ lua_assert(info == -1 || ls->dyd->actvar.arr[info].vd.kind == GDKREG); } } static void singlevar (LexState *ls, expdesc *var) { buildvar(ls, str_checkname(ls), var); } /* ** Adjust the number of results from an expression list 'e' with 'nexps' ** expressions to 'nvars' values. */ static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { FuncState *fs = ls->fs; int needed = nvars - nexps; /* extra values needed */ luaK_checkstack(fs, needed); if (hasmultret(e->k)) { /* last expression has multiple returns? */ int extra = needed + 1; /* discount last expression itself */ if (extra < 0) extra = 0; luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ } else { if (e->k != VVOID) /* at least one expression? */ luaK_exp2nextreg(fs, e); /* close last expression */ if (needed > 0) /* missing values? */ luaK_nil(fs, fs->freereg, needed); /* complete with nils */ } if (needed > 0) luaK_reserveregs(fs, needed); /* registers for extra values */ else /* adding 'needed' is actually a subtraction */ fs->freereg = cast_byte(fs->freereg + needed); /* remove extra values */ } #define enterlevel(ls) luaE_incCstack(ls->L) #define leavelevel(ls) ((ls)->L->nCcalls--) /* ** Generates an error that a goto jumps into the scope of some ** variable declaration. */ static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) { TString *tsname = getlocalvardesc(ls->fs, gt->nactvar)->vd.name; const char *varname = (tsname != NULL) ? getstr(tsname) : "*"; luaK_semerror(ls, " at line %d jumps into the scope of '%s'", getstr(gt->name), gt->line, varname); /* raise the error */ } /* ** Closes the goto at index 'g' to given 'label' and removes it ** from the list of pending gotos. ** If it jumps into the scope of some variable, raises an error. ** The goto needs a CLOSE if it jumps out of a block with upvalues, ** or out of the scope of some variable and the block has upvalues ** (signaled by parameter 'bup'). */ static void closegoto (LexState *ls, int g, Labeldesc *label, int bup) { int i; FuncState *fs = ls->fs; Labellist *gl = &ls->dyd->gt; /* list of gotos */ Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */ lua_assert(eqstr(gt->name, label->name)); if (l_unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */ jumpscopeerror(ls, gt); if (gt->close || (label->nactvar < gt->nactvar && bup)) { /* needs close? */ lu_byte stklevel = reglevel(fs, label->nactvar); /* move jump to CLOSE position */ fs->f->code[gt->pc + 1] = fs->f->code[gt->pc]; /* put CLOSE instruction at original position */ fs->f->code[gt->pc] = CREATE_ABCk(OP_CLOSE, stklevel, 0, 0, 0); gt->pc++; /* must point to jump instruction */ } luaK_patchlist(ls->fs, gt->pc, label->pc); /* goto jumps to label */ for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */ gl->arr[i] = gl->arr[i + 1]; gl->n--; } /* ** Search for an active label with the given name, starting at ** index 'ilb' (so that it can search for all labels in current block ** or all labels in current function). */ static Labeldesc *findlabel (LexState *ls, TString *name, int ilb) { Dyndata *dyd = ls->dyd; for (; ilb < dyd->label.n; ilb++) { Labeldesc *lb = &dyd->label.arr[ilb]; if (eqstr(lb->name, name)) /* correct label? */ return lb; } return NULL; /* label not found */ } /* ** Adds a new label/goto in the corresponding list. */ static int newlabelentry (LexState *ls, Labellist *l, TString *name, int line, int pc) { int n = l->n; luaM_growvector(ls->L, l->arr, n, l->size, Labeldesc, SHRT_MAX, "labels/gotos"); l->arr[n].name = name; l->arr[n].line = line; l->arr[n].nactvar = ls->fs->nactvar; l->arr[n].close = 0; l->arr[n].pc = pc; l->n = n + 1; return n; } /* ** Create an entry for the goto and the code for it. As it is not known ** at this point whether the goto may need a CLOSE, the code has a jump ** followed by an CLOSE. (As the CLOSE comes after the jump, it is a ** dead instruction; it works as a placeholder.) When the goto is closed ** against a label, if it needs a CLOSE, the two instructions swap ** positions, so that the CLOSE comes before the jump. */ static int newgotoentry (LexState *ls, TString *name, int line) { FuncState *fs = ls->fs; int pc = luaK_jump(fs); /* create jump */ luaK_codeABC(fs, OP_CLOSE, 0, 1, 0); /* spaceholder, marked as dead */ return newlabelentry(ls, &ls->dyd->gt, name, line, pc); } /* ** Create a new label with the given 'name' at the given 'line'. ** 'last' tells whether label is the last non-op statement in its ** block. Solves all pending gotos to this new label and adds ** a close instruction if necessary. ** Returns true iff it added a close instruction. */ static void createlabel (LexState *ls, TString *name, int line, int last) { FuncState *fs = ls->fs; Labellist *ll = &ls->dyd->label; int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs)); if (last) { /* label is last no-op statement in the block? */ /* assume that locals are already out of scope */ ll->arr[l].nactvar = fs->bl->nactvar; } } /* ** Traverse the pending gotos of the finishing block checking whether ** each match some label of that block. Those that do not match are ** "exported" to the outer block, to be solved there. In particular, ** its 'nactvar' is updated with the level of the inner block, ** as the variables of the inner block are now out of scope. */ static void solvegotos (FuncState *fs, BlockCnt *bl) { LexState *ls = fs->ls; Labellist *gl = &ls->dyd->gt; int outlevel = reglevel(fs, bl->nactvar); /* level outside the block */ int igt = bl->firstgoto; /* first goto in the finishing block */ while (igt < gl->n) { /* for each pending goto */ Labeldesc *gt = &gl->arr[igt]; /* search for a matching label in the current block */ Labeldesc *lb = findlabel(ls, gt->name, bl->firstlabel); if (lb != NULL) /* found a match? */ closegoto(ls, igt, lb, bl->upval); /* close and remove goto */ else { /* adjust 'goto' for outer block */ /* block has variables to be closed and goto escapes the scope of some variable? */ if (bl->upval && reglevel(fs, gt->nactvar) > outlevel) gt->close = 1; /* jump may need a close */ gt->nactvar = bl->nactvar; /* correct level for outer block */ igt++; /* go to next goto */ } } ls->dyd->label.n = bl->firstlabel; /* remove local labels */ } static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { bl->isloop = isloop; bl->nactvar = fs->nactvar; bl->firstlabel = fs->ls->dyd->label.n; bl->firstgoto = fs->ls->dyd->gt.n; bl->upval = 0; /* inherit 'insidetbc' from enclosing block */ bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc); bl->previous = fs->bl; /* link block in function's block list */ fs->bl = bl; lua_assert(fs->freereg == luaY_nvarstack(fs)); } /* ** generates an error for an undefined 'goto'. */ static l_noret undefgoto (LexState *ls, Labeldesc *gt) { /* breaks are checked when created, cannot be undefined */ lua_assert(!eqstr(gt->name, ls->brkn)); luaK_semerror(ls, "no visible label '%s' for at line %d", getstr(gt->name), gt->line); } static void leaveblock (FuncState *fs) { BlockCnt *bl = fs->bl; LexState *ls = fs->ls; lu_byte stklevel = reglevel(fs, bl->nactvar); /* level outside block */ if (bl->previous && bl->upval) /* need a 'close'? */ luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0); fs->freereg = stklevel; /* free registers */ removevars(fs, bl->nactvar); /* remove block locals */ lua_assert(bl->nactvar == fs->nactvar); /* back to level on entry */ if (bl->isloop == 2) /* has to fix pending breaks? */ createlabel(ls, ls->brkn, 0, 0); solvegotos(fs, bl); if (bl->previous == NULL) { /* was it the last block? */ if (bl->firstgoto < ls->dyd->gt.n) /* still pending gotos? */ undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ } fs->bl = bl->previous; /* current block now is previous one */ } /* ** adds a new prototype into list of prototypes */ static Proto *addprototype (LexState *ls) { Proto *clp; lua_State *L = ls->L; FuncState *fs = ls->fs; Proto *f = fs->f; /* prototype of current function */ if (fs->np >= f->sizep) { int oldsize = f->sizep; luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); while (oldsize < f->sizep) f->p[oldsize++] = NULL; } f->p[fs->np++] = clp = luaF_newproto(L); luaC_objbarrier(L, f, clp); return clp; } /* ** codes instruction to create new closure in parent function. ** The OP_CLOSURE instruction uses the last available register, ** so that, if it invokes the GC, the GC knows which registers ** are in use at that time. */ static void codeclosure (LexState *ls, expdesc *v) { FuncState *fs = ls->fs->prev; init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); luaK_exp2nextreg(fs, v); /* fix it at the last register */ } static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { lua_State *L = ls->L; Proto *f = fs->f; fs->prev = ls->fs; /* linked list of funcstates */ fs->ls = ls; ls->fs = fs; fs->pc = 0; fs->previousline = f->linedefined; fs->iwthabs = 0; fs->lasttarget = 0; fs->freereg = 0; fs->nk = 0; fs->nabslineinfo = 0; fs->np = 0; fs->nups = 0; fs->ndebugvars = 0; fs->nactvar = 0; fs->needclose = 0; fs->firstlocal = ls->dyd->actvar.n; fs->firstlabel = ls->dyd->label.n; fs->bl = NULL; f->source = ls->source; luaC_objbarrier(L, f, f->source); f->maxstacksize = 2; /* registers 0/1 are always valid */ fs->kcache = luaH_new(L); /* create table for function */ sethvalue2s(L, L->top.p, fs->kcache); /* anchor it */ luaD_inctop(L); enterblock(fs, bl, 0); } static void close_func (LexState *ls) { lua_State *L = ls->L; FuncState *fs = ls->fs; Proto *f = fs->f; luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */ leaveblock(fs); lua_assert(fs->bl == NULL); luaK_finish(fs); luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction); luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte); luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo, fs->nabslineinfo, AbsLineInfo); luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue); luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *); luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar); luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); ls->fs = fs->prev; L->top.p--; /* pop kcache table */ luaC_checkGC(L); } /* ** {====================================================================== ** GRAMMAR RULES ** ======================================================================= */ /* ** check whether current token is in the follow set of a block. ** 'until' closes syntactical blocks, but do not close scope, ** so it is handled in separate. */ static int block_follow (LexState *ls, int withuntil) { switch (ls->t.token) { case TK_ELSE: case TK_ELSEIF: case TK_END: case TK_EOS: return 1; case TK_UNTIL: return withuntil; default: return 0; } } static void statlist (LexState *ls) { /* statlist -> { stat [';'] } */ while (!block_follow(ls, 1)) { if (ls->t.token == TK_RETURN) { statement(ls); return; /* 'return' must be last statement */ } statement(ls); } } static void fieldsel (LexState *ls, expdesc *v) { /* fieldsel -> ['.' | ':'] NAME */ FuncState *fs = ls->fs; expdesc key; luaK_exp2anyregup(fs, v); luaX_next(ls); /* skip the dot or colon */ codename(ls, &key); luaK_indexed(fs, v, &key); } static void yindex (LexState *ls, expdesc *v) { /* index -> '[' expr ']' */ luaX_next(ls); /* skip the '[' */ expr(ls, v); luaK_exp2val(ls->fs, v); checknext(ls, ']'); } /* ** {====================================================================== ** Rules for Constructors ** ======================================================================= */ typedef struct ConsControl { expdesc v; /* last list item read */ expdesc *t; /* table descriptor */ int nh; /* total number of 'record' elements */ int na; /* number of array elements already stored */ int tostore; /* number of array elements pending to be stored */ int maxtostore; /* maximum number of pending elements */ } ConsControl; /* ** Maximum number of elements in a constructor, to control the following: ** * counter overflows; ** * overflows in 'extra' for OP_NEWTABLE and OP_SETLIST; ** * overflows when adding multiple returns in OP_SETLIST. */ #define MAX_CNST (INT_MAX/2) #if MAX_CNST/(MAXARG_vC + 1) > MAXARG_Ax #undef MAX_CNST #define MAX_CNST (MAXARG_Ax * (MAXARG_vC + 1)) #endif static void recfield (LexState *ls, ConsControl *cc) { /* recfield -> (NAME | '['exp']') = exp */ FuncState *fs = ls->fs; lu_byte reg = ls->fs->freereg; expdesc tab, key, val; if (ls->t.token == TK_NAME) codename(ls, &key); else /* ls->t.token == '[' */ yindex(ls, &key); cc->nh++; checknext(ls, '='); tab = *cc->t; luaK_indexed(fs, &tab, &key); expr(ls, &val); luaK_storevar(fs, &tab, &val); fs->freereg = reg; /* free registers */ } static void closelistfield (FuncState *fs, ConsControl *cc) { lua_assert(cc->tostore > 0); luaK_exp2nextreg(fs, &cc->v); cc->v.k = VVOID; if (cc->tostore >= cc->maxtostore) { luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ cc->na += cc->tostore; cc->tostore = 0; /* no more items pending */ } } static void lastlistfield (FuncState *fs, ConsControl *cc) { if (cc->tostore == 0) return; if (hasmultret(cc->v.k)) { luaK_setmultret(fs, &cc->v); luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); cc->na--; /* do not count last expression (unknown number of elements) */ } else { if (cc->v.k != VVOID) luaK_exp2nextreg(fs, &cc->v); luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); } cc->na += cc->tostore; } static void listfield (LexState *ls, ConsControl *cc) { /* listfield -> exp */ expr(ls, &cc->v); cc->tostore++; } static void field (LexState *ls, ConsControl *cc) { /* field -> listfield | recfield */ switch(ls->t.token) { case TK_NAME: { /* may be 'listfield' or 'recfield' */ if (luaX_lookahead(ls) != '=') /* expression? */ listfield(ls, cc); else recfield(ls, cc); break; } case '[': { recfield(ls, cc); break; } default: { listfield(ls, cc); break; } } } /* ** Compute a limit for how many registers a constructor can use before ** emitting a 'SETLIST' instruction, based on how many registers are ** available. */ static int maxtostore (FuncState *fs) { int numfreeregs = MAX_FSTACK - fs->freereg; if (numfreeregs >= 160) /* "lots" of registers? */ return numfreeregs / 5; /* use up to 1/5 of them */ else if (numfreeregs >= 80) /* still "enough" registers? */ return 10; /* one 'SETLIST' instruction for each 10 values */ else /* save registers for potential more nesting */ return 1; } static void constructor (LexState *ls, expdesc *t) { /* constructor -> '{' [ field { sep field } [sep] ] '}' sep -> ',' | ';' */ FuncState *fs = ls->fs; int line = ls->linenumber; int pc = luaK_codevABCk(fs, OP_NEWTABLE, 0, 0, 0, 0); ConsControl cc; luaK_code(fs, 0); /* space for extra arg. */ cc.na = cc.nh = cc.tostore = 0; cc.t = t; init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */ luaK_reserveregs(fs, 1); init_exp(&cc.v, VVOID, 0); /* no value (yet) */ checknext(ls, '{' /*}*/); cc.maxtostore = maxtostore(fs); do { if (ls->t.token == /*{*/ '}') break; if (cc.v.k != VVOID) /* is there a previous list item? */ closelistfield(fs, &cc); /* close it */ field(ls, &cc); luaY_checklimit(fs, cc.tostore + cc.na + cc.nh, MAX_CNST, "items in a constructor"); } while (testnext(ls, ',') || testnext(ls, ';')); check_match(ls, /*{*/ '}', '{' /*}*/, line); lastlistfield(fs, &cc); luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh); } /* }====================================================================== */ static void setvararg (FuncState *fs) { fs->f->flag |= PF_VAHID; /* by default, use hidden vararg arguments */ luaK_codeABC(fs, OP_VARARGPREP, 0, 0, 0); } static void parlist (LexState *ls) { /* parlist -> [ {NAME ','} (NAME | '...') ] */ FuncState *fs = ls->fs; Proto *f = fs->f; int nparams = 0; int varargk = 0; if (ls->t.token != ')') { /* is 'parlist' not empty? */ do { switch (ls->t.token) { case TK_NAME: { new_localvar(ls, str_checkname(ls)); nparams++; break; } case TK_DOTS: { varargk = 1; luaX_next(ls); /* skip '...' */ if (ls->t.token == TK_NAME) new_varkind(ls, str_checkname(ls), RDKVAVAR); else new_localvarliteral(ls, "(vararg table)"); break; } default: luaX_syntaxerror(ls, " or '...' expected"); } } while (!varargk && testnext(ls, ',')); } adjustlocalvars(ls, nparams); f->numparams = cast_byte(fs->nactvar); if (varargk) { setvararg(fs); /* declared vararg */ adjustlocalvars(ls, 1); /* vararg parameter */ } /* reserve registers for parameters (plus vararg parameter, if present) */ luaK_reserveregs(fs, fs->nactvar); } static void body (LexState *ls, expdesc *e, int ismethod, int line) { /* body -> '(' parlist ')' block END */ FuncState new_fs; BlockCnt bl; new_fs.f = addprototype(ls); new_fs.f->linedefined = line; open_func(ls, &new_fs, &bl); checknext(ls, '('); if (ismethod) { new_localvarliteral(ls, "self"); /* create 'self' parameter */ adjustlocalvars(ls, 1); } parlist(ls); checknext(ls, ')'); statlist(ls); new_fs.f->lastlinedefined = ls->linenumber; check_match(ls, TK_END, TK_FUNCTION, line); codeclosure(ls, e); close_func(ls); } static int explist (LexState *ls, expdesc *v) { /* explist -> expr { ',' expr } */ int n = 1; /* at least one expression */ expr(ls, v); while (testnext(ls, ',')) { luaK_exp2nextreg(ls->fs, v); expr(ls, v); n++; } return n; } static void funcargs (LexState *ls, expdesc *f) { FuncState *fs = ls->fs; expdesc args; int base, nparams; int line = ls->linenumber; switch (ls->t.token) { case '(': { /* funcargs -> '(' [ explist ] ')' */ luaX_next(ls); if (ls->t.token == ')') /* arg list is empty? */ args.k = VVOID; else { explist(ls, &args); if (hasmultret(args.k)) luaK_setmultret(fs, &args); } check_match(ls, ')', '(', line); break; } case '{' /*}*/: { /* funcargs -> constructor */ constructor(ls, &args); break; } case TK_STRING: { /* funcargs -> STRING */ codestring(&args, ls->t.seminfo.ts); luaX_next(ls); /* must use 'seminfo' before 'next' */ break; } default: { luaX_syntaxerror(ls, "function arguments expected"); } } lua_assert(f->k == VNONRELOC); base = f->u.info; /* base register for call */ if (hasmultret(args.k)) nparams = LUA_MULTRET; /* open call */ else { if (args.k != VVOID) luaK_exp2nextreg(fs, &args); /* close last argument */ nparams = fs->freereg - (base+1); } init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); luaK_fixline(fs, line); /* call removes function and arguments and leaves one result (unless changed later) */ fs->freereg = cast_byte(base + 1); } /* ** {====================================================================== ** Expression parsing ** ======================================================================= */ static void primaryexp (LexState *ls, expdesc *v) { /* primaryexp -> NAME | '(' expr ')' */ switch (ls->t.token) { case '(': { int line = ls->linenumber; luaX_next(ls); expr(ls, v); check_match(ls, ')', '(', line); luaK_dischargevars(ls->fs, v); return; } case TK_NAME: { singlevar(ls, v); return; } default: { luaX_syntaxerror(ls, "unexpected symbol"); } } } static void suffixedexp (LexState *ls, expdesc *v) { /* suffixedexp -> primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ FuncState *fs = ls->fs; primaryexp(ls, v); for (;;) { switch (ls->t.token) { case '.': { /* fieldsel */ fieldsel(ls, v); break; } case '[': { /* '[' exp ']' */ expdesc key; luaK_exp2anyregup(fs, v); yindex(ls, &key); luaK_indexed(fs, v, &key); break; } case ':': { /* ':' NAME funcargs */ expdesc key; luaX_next(ls); codename(ls, &key); luaK_self(fs, v, &key); funcargs(ls, v); break; } case '(': case TK_STRING: case '{' /*}*/: { /* funcargs */ luaK_exp2nextreg(fs, v); funcargs(ls, v); break; } default: return; } } } static void simpleexp (LexState *ls, expdesc *v) { /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... | constructor | FUNCTION body | suffixedexp */ switch (ls->t.token) { case TK_FLT: { init_exp(v, VKFLT, 0); v->u.nval = ls->t.seminfo.r; break; } case TK_INT: { init_exp(v, VKINT, 0); v->u.ival = ls->t.seminfo.i; break; } case TK_STRING: { codestring(v, ls->t.seminfo.ts); break; } case TK_NIL: { init_exp(v, VNIL, 0); break; } case TK_TRUE: { init_exp(v, VTRUE, 0); break; } case TK_FALSE: { init_exp(v, VFALSE, 0); break; } case TK_DOTS: { /* vararg */ FuncState *fs = ls->fs; check_condition(ls, isvararg(fs->f), "cannot use '...' outside a vararg function"); init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, fs->f->numparams, 1)); break; } case '{' /*}*/: { /* constructor */ constructor(ls, v); return; } case TK_FUNCTION: { luaX_next(ls); body(ls, v, 0, ls->linenumber); return; } default: { suffixedexp(ls, v); return; } } luaX_next(ls); } static UnOpr getunopr (int op) { switch (op) { case TK_NOT: return OPR_NOT; case '-': return OPR_MINUS; case '~': return OPR_BNOT; case '#': return OPR_LEN; default: return OPR_NOUNOPR; } } static BinOpr getbinopr (int op) { switch (op) { case '+': return OPR_ADD; case '-': return OPR_SUB; case '*': return OPR_MUL; case '%': return OPR_MOD; case '^': return OPR_POW; case '/': return OPR_DIV; case TK_IDIV: return OPR_IDIV; case '&': return OPR_BAND; case '|': return OPR_BOR; case '~': return OPR_BXOR; case TK_SHL: return OPR_SHL; case TK_SHR: return OPR_SHR; case TK_CONCAT: return OPR_CONCAT; case TK_NE: return OPR_NE; case TK_EQ: return OPR_EQ; case '<': return OPR_LT; case TK_LE: return OPR_LE; case '>': return OPR_GT; case TK_GE: return OPR_GE; case TK_AND: return OPR_AND; case TK_OR: return OPR_OR; default: return OPR_NOBINOPR; } } /* ** Priority table for binary operators. */ static const struct { lu_byte left; /* left priority for each binary operator */ lu_byte right; /* right priority */ } priority[] = { /* ORDER OPR */ {10, 10}, {10, 10}, /* '+' '-' */ {11, 11}, {11, 11}, /* '*' '%' */ {14, 13}, /* '^' (right associative) */ {11, 11}, {11, 11}, /* '/' '//' */ {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */ {7, 7}, {7, 7}, /* '<<' '>>' */ {9, 8}, /* '..' (right associative) */ {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ {2, 2}, {1, 1} /* and, or */ }; #define UNARY_PRIORITY 12 /* priority for unary operators */ /* ** subexpr -> (simpleexp | unop subexpr) { binop subexpr } ** where 'binop' is any binary operator with a priority higher than 'limit' */ static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { BinOpr op; UnOpr uop; enterlevel(ls); uop = getunopr(ls->t.token); if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */ int line = ls->linenumber; luaX_next(ls); /* skip operator */ subexpr(ls, v, UNARY_PRIORITY); luaK_prefix(ls->fs, uop, v, line); } else simpleexp(ls, v); /* expand while operators have priorities higher than 'limit' */ op = getbinopr(ls->t.token); while (op != OPR_NOBINOPR && priority[op].left > limit) { expdesc v2; BinOpr nextop; int line = ls->linenumber; luaX_next(ls); /* skip operator */ luaK_infix(ls->fs, op, v); /* read sub-expression with higher priority */ nextop = subexpr(ls, &v2, priority[op].right); luaK_posfix(ls->fs, op, v, &v2, line); op = nextop; } leavelevel(ls); return op; /* return first untreated operator */ } static void expr (LexState *ls, expdesc *v) { subexpr(ls, v, 0); } /* }==================================================================== */ /* ** {====================================================================== ** Rules for Statements ** ======================================================================= */ static void block (LexState *ls) { /* block -> statlist */ FuncState *fs = ls->fs; BlockCnt bl; enterblock(fs, &bl, 0); statlist(ls); leaveblock(fs); } /* ** structure to chain all variables in the left-hand side of an ** assignment */ struct LHS_assign { struct LHS_assign *prev; expdesc v; /* variable (global, local, upvalue, or indexed) */ }; /* ** check whether, in an assignment to an upvalue/local variable, the ** upvalue/local variable is begin used in a previous assignment to a ** table. If so, save original upvalue/local value in a safe place and ** use this safe copy in the previous assignment. */ static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { FuncState *fs = ls->fs; lu_byte extra = fs->freereg; /* eventual position to save local variable */ int conflict = 0; for (; lh; lh = lh->prev) { /* check all previous assignments */ if (vkisindexed(lh->v.k)) { /* assignment to table field? */ if (lh->v.k == VINDEXUP) { /* is table an upvalue? */ if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) { conflict = 1; /* table is the upvalue being assigned now */ lh->v.k = VINDEXSTR; lh->v.u.ind.t = extra; /* assignment will use safe copy */ } } else { /* table is a register */ if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) { conflict = 1; /* table is the local being assigned now */ lh->v.u.ind.t = extra; /* assignment will use safe copy */ } /* is index the local being assigned? */ if (lh->v.k == VINDEXED && v->k == VLOCAL && lh->v.u.ind.idx == v->u.var.ridx) { conflict = 1; lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ } } } } if (conflict) { /* copy upvalue/local value to a temporary (in position 'extra') */ if (v->k == VLOCAL) luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0); else luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0); luaK_reserveregs(fs, 1); } } /* Create code to store the "top" register in 'var' */ static void storevartop (FuncState *fs, expdesc *var) { expdesc e; init_exp(&e, VNONRELOC, fs->freereg - 1); luaK_storevar(fs, var, &e); /* will also free the top register */ } /* ** Parse and compile a multiple assignment. The first "variable" ** (a 'suffixedexp') was already read by the caller. ** ** assignment -> suffixedexp restassign ** restassign -> ',' suffixedexp restassign | '=' explist */ static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) { expdesc e; check_condition(ls, vkisvar(lh->v.k), "syntax error"); check_readonly(ls, &lh->v); if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */ struct LHS_assign nv; nv.prev = lh; suffixedexp(ls, &nv.v); if (!vkisindexed(nv.v.k)) check_conflict(ls, lh, &nv.v); enterlevel(ls); /* control recursion depth */ restassign(ls, &nv, nvars+1); leavelevel(ls); } else { /* restassign -> '=' explist */ int nexps; checknext(ls, '='); nexps = explist(ls, &e); if (nexps != nvars) adjust_assign(ls, nvars, nexps, &e); else { luaK_setoneret(ls->fs, &e); /* close last expression */ luaK_storevar(ls->fs, &lh->v, &e); return; /* avoid default */ } } storevartop(ls->fs, &lh->v); /* default assignment */ } static int cond (LexState *ls) { /* cond -> exp */ expdesc v; expr(ls, &v); /* read condition */ if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ luaK_goiftrue(ls->fs, &v); return v.f; } static void gotostat (LexState *ls, int line) { TString *name = str_checkname(ls); /* label's name */ newgotoentry(ls, name, line); } /* ** Break statement. Semantically equivalent to "goto break". */ static void breakstat (LexState *ls, int line) { BlockCnt *bl; /* to look for an enclosing loop */ for (bl = ls->fs->bl; bl != NULL; bl = bl->previous) { if (bl->isloop) /* found one? */ goto ok; } luaX_syntaxerror(ls, "break outside loop"); ok: bl->isloop = 2; /* signal that block has pending breaks */ luaX_next(ls); /* skip break */ newgotoentry(ls, ls->brkn, line); } /* ** Check whether there is already a label with the given 'name' at ** current function. */ static void checkrepeated (LexState *ls, TString *name) { Labeldesc *lb = findlabel(ls, name, ls->fs->firstlabel); if (l_unlikely(lb != NULL)) /* already defined? */ luaK_semerror(ls, "label '%s' already defined on line %d", getstr(name), lb->line); /* error */ } static void labelstat (LexState *ls, TString *name, int line) { /* label -> '::' NAME '::' */ checknext(ls, TK_DBCOLON); /* skip double colon */ while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) statement(ls); /* skip other no-op statements */ checkrepeated(ls, name); /* check for repeated labels */ createlabel(ls, name, line, block_follow(ls, 0)); } static void whilestat (LexState *ls, int line) { /* whilestat -> WHILE cond DO block END */ FuncState *fs = ls->fs; int whileinit; int condexit; BlockCnt bl; luaX_next(ls); /* skip WHILE */ whileinit = luaK_getlabel(fs); condexit = cond(ls); enterblock(fs, &bl, 1); checknext(ls, TK_DO); block(ls); luaK_jumpto(fs, whileinit); check_match(ls, TK_END, TK_WHILE, line); leaveblock(fs); luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ } static void repeatstat (LexState *ls, int line) { /* repeatstat -> REPEAT block UNTIL cond */ int condexit; FuncState *fs = ls->fs; int repeat_init = luaK_getlabel(fs); BlockCnt bl1, bl2; enterblock(fs, &bl1, 1); /* loop block */ enterblock(fs, &bl2, 0); /* scope block */ luaX_next(ls); /* skip REPEAT */ statlist(ls); check_match(ls, TK_UNTIL, TK_REPEAT, line); condexit = cond(ls); /* read condition (inside scope block) */ leaveblock(fs); /* finish scope */ if (bl2.upval) { /* upvalues? */ int exit = luaK_jump(fs); /* normal exit must jump over fix */ luaK_patchtohere(fs, condexit); /* repetition must close upvalues */ luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0); condexit = luaK_jump(fs); /* repeat after closing upvalues */ luaK_patchtohere(fs, exit); /* normal exit comes to here */ } luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ leaveblock(fs); /* finish loop */ } /* ** Read an expression and generate code to put its results in next ** stack slot. ** */ static void exp1 (LexState *ls) { expdesc e; expr(ls, &e); luaK_exp2nextreg(ls->fs, &e); lua_assert(e.k == VNONRELOC); } /* ** Fix for instruction at position 'pc' to jump to 'dest'. ** (Jump addresses are relative in Lua). 'back' true means ** a back jump. */ static void fixforjump (FuncState *fs, int pc, int dest, int back) { Instruction *jmp = &fs->f->code[pc]; int offset = dest - (pc + 1); if (back) offset = -offset; if (l_unlikely(offset > MAXARG_Bx)) luaX_syntaxerror(fs->ls, "control structure too long"); SETARG_Bx(*jmp, offset); } /* ** Generate code for a 'for' loop. */ static void forbody (LexState *ls, int base, int line, int nvars, int isgen) { /* forbody -> DO block */ static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP}; static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP}; BlockCnt bl; FuncState *fs = ls->fs; int prep, endfor; checknext(ls, TK_DO); prep = luaK_codeABx(fs, forprep[isgen], base, 0); fs->freereg--; /* both 'forprep' remove one register from the stack */ enterblock(fs, &bl, 0); /* scope for declared variables */ adjustlocalvars(ls, nvars); luaK_reserveregs(fs, nvars); block(ls); leaveblock(fs); /* end of scope for declared variables */ fixforjump(fs, prep, luaK_getlabel(fs), 0); if (isgen) { /* generic for? */ luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); luaK_fixline(fs, line); } endfor = luaK_codeABx(fs, forloop[isgen], base, 0); fixforjump(fs, endfor, prep + 1, 1); luaK_fixline(fs, line); } static void fornum (LexState *ls, TString *varname, int line) { /* fornum -> NAME = exp,exp[,exp] forbody */ FuncState *fs = ls->fs; int base = fs->freereg; new_localvarliteral(ls, "(for state)"); new_localvarliteral(ls, "(for state)"); new_varkind(ls, varname, RDKCONST); /* control variable */ checknext(ls, '='); exp1(ls); /* initial value */ checknext(ls, ','); exp1(ls); /* limit */ if (testnext(ls, ',')) exp1(ls); /* optional step */ else { /* default step = 1 */ luaK_int(fs, fs->freereg, 1); luaK_reserveregs(fs, 1); } adjustlocalvars(ls, 2); /* start scope for internal variables */ forbody(ls, base, line, 1, 0); } static void forlist (LexState *ls, TString *indexname) { /* forlist -> NAME {,NAME} IN explist forbody */ FuncState *fs = ls->fs; expdesc e; int nvars = 4; /* function, state, closing, control */ int line; int base = fs->freereg; /* create internal variables */ new_localvarliteral(ls, "(for state)"); /* iterator function */ new_localvarliteral(ls, "(for state)"); /* state */ new_localvarliteral(ls, "(for state)"); /* closing var. (after swap) */ new_varkind(ls, indexname, RDKCONST); /* control variable */ /* other declared variables */ while (testnext(ls, ',')) { new_localvar(ls, str_checkname(ls)); nvars++; } checknext(ls, TK_IN); line = ls->linenumber; adjust_assign(ls, 4, explist(ls, &e), &e); adjustlocalvars(ls, 3); /* start scope for internal variables */ marktobeclosed(fs); /* last internal var. must be closed */ luaK_checkstack(fs, 2); /* extra space to call iterator */ forbody(ls, base, line, nvars - 3, 1); } static void forstat (LexState *ls, int line) { /* forstat -> FOR (fornum | forlist) END */ FuncState *fs = ls->fs; TString *varname; BlockCnt bl; enterblock(fs, &bl, 1); /* scope for loop and control variables */ luaX_next(ls); /* skip 'for' */ varname = str_checkname(ls); /* first variable name */ switch (ls->t.token) { case '=': fornum(ls, varname, line); break; case ',': case TK_IN: forlist(ls, varname); break; default: luaX_syntaxerror(ls, "'=' or 'in' expected"); } check_match(ls, TK_END, TK_FOR, line); leaveblock(fs); /* loop scope ('break' jumps to this point) */ } static void test_then_block (LexState *ls, int *escapelist) { /* test_then_block -> [IF | ELSEIF] cond THEN block */ FuncState *fs = ls->fs; int condtrue; luaX_next(ls); /* skip IF or ELSEIF */ condtrue = cond(ls); /* read condition */ checknext(ls, TK_THEN); block(ls); /* 'then' part */ if (ls->t.token == TK_ELSE || ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ luaK_patchtohere(fs, condtrue); } static void ifstat (LexState *ls, int line) { /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ FuncState *fs = ls->fs; int escapelist = NO_JUMP; /* exit list for finished parts */ test_then_block(ls, &escapelist); /* IF cond THEN block */ while (ls->t.token == TK_ELSEIF) test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ if (testnext(ls, TK_ELSE)) block(ls); /* 'else' part */ check_match(ls, TK_END, TK_IF, line); luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ } static void localfunc (LexState *ls) { expdesc b; FuncState *fs = ls->fs; int fvar = fs->nactvar; /* function's variable index */ new_localvar(ls, str_checkname(ls)); /* new local variable */ adjustlocalvars(ls, 1); /* enter its scope */ body(ls, &b, 0, ls->linenumber); /* function created in next register */ /* debug information will only see the variable after this point! */ localdebuginfo(fs, fvar)->startpc = fs->pc; } static lu_byte getvarattribute (LexState *ls, lu_byte df) { /* attrib -> ['<' NAME '>'] */ if (testnext(ls, '<')) { TString *ts = str_checkname(ls); const char *attr = getstr(ts); checknext(ls, '>'); if (strcmp(attr, "const") == 0) return RDKCONST; /* read-only variable */ else if (strcmp(attr, "close") == 0) return RDKTOCLOSE; /* to-be-closed variable */ else luaK_semerror(ls, "unknown attribute '%s'", attr); } return df; /* return default value */ } static void checktoclose (FuncState *fs, int level) { if (level != -1) { /* is there a to-be-closed variable? */ marktobeclosed(fs); luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0); } } static void localstat (LexState *ls) { /* stat -> LOCAL NAME attrib { ',' NAME attrib } ['=' explist] */ FuncState *fs = ls->fs; int toclose = -1; /* index of to-be-closed variable (if any) */ Vardesc *var; /* last variable */ int vidx; /* index of last variable */ int nvars = 0; int nexps; expdesc e; /* get prefixed attribute (if any); default is regular local variable */ lu_byte defkind = getvarattribute(ls, VDKREG); do { /* for each variable */ TString *vname = str_checkname(ls); /* get its name */ lu_byte kind = getvarattribute(ls, defkind); /* postfixed attribute */ vidx = new_varkind(ls, vname, kind); /* predeclare it */ if (kind == RDKTOCLOSE) { /* to-be-closed? */ if (toclose != -1) /* one already present? */ luaK_semerror(ls, "multiple to-be-closed variables in local list"); toclose = fs->nactvar + nvars; } nvars++; } while (testnext(ls, ',')); if (testnext(ls, '=')) /* initialization? */ nexps = explist(ls, &e); else { e.k = VVOID; nexps = 0; } var = getlocalvardesc(fs, vidx); /* retrieve last variable */ if (nvars == nexps && /* no adjustments? */ var->vd.kind == RDKCONST && /* last variable is const? */ luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */ var->vd.kind = RDKCTC; /* variable is a compile-time constant */ adjustlocalvars(ls, nvars - 1); /* exclude last variable */ fs->nactvar++; /* but count it */ } else { adjust_assign(ls, nvars, nexps, &e); adjustlocalvars(ls, nvars); } checktoclose(fs, toclose); } static lu_byte getglobalattribute (LexState *ls, lu_byte df) { lu_byte kind = getvarattribute(ls, df); switch (kind) { case RDKTOCLOSE: luaK_semerror(ls, "global variables cannot be to-be-closed"); return kind; /* to avoid warnings */ case RDKCONST: return GDKCONST; /* adjust kind for global variable */ default: return kind; } } static void checkglobal (LexState *ls, TString *varname, int line) { FuncState *fs = ls->fs; expdesc var; int k; buildglobal(ls, varname, &var); /* create global variable in 'var' */ k = var.u.ind.keystr; /* index of global name in 'k' */ luaK_codecheckglobal(fs, &var, k, line); } /* ** Recursively traverse list of globals to be initalized. When ** going, generate table description for the global. In the end, ** after all indices have been generated, read list of initializing ** expressions. When returning, generate the assignment of the value on ** the stack to the corresponding table description. 'n' is the variable ** being handled, range [0, nvars - 1]. */ static void initglobal (LexState *ls, int nvars, int firstidx, int n, int line) { if (n == nvars) { /* traversed all variables? */ expdesc e; int nexps = explist(ls, &e); /* read list of expressions */ adjust_assign(ls, nvars, nexps, &e); } else { /* handle variable 'n' */ FuncState *fs = ls->fs; expdesc var; TString *varname = getlocalvardesc(fs, firstidx + n)->vd.name; buildglobal(ls, varname, &var); /* create global variable in 'var' */ enterlevel(ls); /* control recursion depth */ initglobal(ls, nvars, firstidx, n + 1, line); leavelevel(ls); checkglobal(ls, varname, line); storevartop(fs, &var); } } static void globalnames (LexState *ls, lu_byte defkind) { FuncState *fs = ls->fs; int nvars = 0; int lastidx; /* index of last registered variable */ do { /* for each name */ TString *vname = str_checkname(ls); lu_byte kind = getglobalattribute(ls, defkind); lastidx = new_varkind(ls, vname, kind); nvars++; } while (testnext(ls, ',')); if (testnext(ls, '=')) /* initialization? */ initglobal(ls, nvars, lastidx - nvars + 1, 0, ls->linenumber); fs->nactvar = cast_short(fs->nactvar + nvars); /* activate declaration */ } static void globalstat (LexState *ls) { /* globalstat -> (GLOBAL) attrib '*' globalstat -> (GLOBAL) attrib NAME attrib {',' NAME attrib} */ FuncState *fs = ls->fs; /* get prefixed attribute (if any); default is regular global variable */ lu_byte defkind = getglobalattribute(ls, GDKREG); if (!testnext(ls, '*')) globalnames(ls, defkind); else { /* use NULL as name to represent '*' entries */ new_varkind(ls, NULL, defkind); fs->nactvar++; /* activate declaration */ } } static void globalfunc (LexState *ls, int line) { /* globalfunc -> (GLOBAL FUNCTION) NAME body */ expdesc var, b; FuncState *fs = ls->fs; TString *fname = str_checkname(ls); new_varkind(ls, fname, GDKREG); /* declare global variable */ fs->nactvar++; /* enter its scope */ buildglobal(ls, fname, &var); body(ls, &b, 0, ls->linenumber); /* compile and return closure in 'b' */ checkglobal(ls, fname, line); luaK_storevar(fs, &var, &b); luaK_fixline(fs, line); /* definition "happens" in the first line */ } static void globalstatfunc (LexState *ls, int line) { /* stat -> GLOBAL globalfunc | GLOBAL globalstat */ luaX_next(ls); /* skip 'global' */ if (testnext(ls, TK_FUNCTION)) globalfunc(ls, line); else globalstat(ls); } static int funcname (LexState *ls, expdesc *v) { /* funcname -> NAME {fieldsel} [':' NAME] */ int ismethod = 0; singlevar(ls, v); while (ls->t.token == '.') fieldsel(ls, v); if (ls->t.token == ':') { ismethod = 1; fieldsel(ls, v); } return ismethod; } static void funcstat (LexState *ls, int line) { /* funcstat -> FUNCTION funcname body */ int ismethod; expdesc v, b; luaX_next(ls); /* skip FUNCTION */ ismethod = funcname(ls, &v); check_readonly(ls, &v); body(ls, &b, ismethod, line); luaK_storevar(ls->fs, &v, &b); luaK_fixline(ls->fs, line); /* definition "happens" in the first line */ } static void exprstat (LexState *ls) { /* stat -> func | assignment */ FuncState *fs = ls->fs; struct LHS_assign v; suffixedexp(ls, &v.v); if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ v.prev = NULL; restassign(ls, &v, 1); } else { /* stat -> func */ Instruction *inst; check_condition(ls, v.v.k == VCALL, "syntax error"); inst = &getinstruction(fs, &v.v); SETARG_C(*inst, 1); /* call statement uses no results */ } } static void retstat (LexState *ls) { /* stat -> RETURN [explist] [';'] */ FuncState *fs = ls->fs; expdesc e; int nret; /* number of values being returned */ int first = luaY_nvarstack(fs); /* first slot to be returned */ if (block_follow(ls, 1) || ls->t.token == ';') nret = 0; /* return no values */ else { nret = explist(ls, &e); /* optional return values */ if (hasmultret(e.k)) { luaK_setmultret(fs, &e); if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */ SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL); lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs)); } nret = LUA_MULTRET; /* return all values */ } else { if (nret == 1) /* only one single value? */ first = luaK_exp2anyreg(fs, &e); /* can use original slot */ else { /* values must go to the top of the stack */ luaK_exp2nextreg(fs, &e); lua_assert(nret == fs->freereg - first); } } } luaK_ret(fs, first, nret); testnext(ls, ';'); /* skip optional semicolon */ } static void statement (LexState *ls) { int line = ls->linenumber; /* may be needed for error messages */ enterlevel(ls); switch (ls->t.token) { case ';': { /* stat -> ';' (empty statement) */ luaX_next(ls); /* skip ';' */ break; } case TK_IF: { /* stat -> ifstat */ ifstat(ls, line); break; } case TK_WHILE: { /* stat -> whilestat */ whilestat(ls, line); break; } case TK_DO: { /* stat -> DO block END */ luaX_next(ls); /* skip DO */ block(ls); check_match(ls, TK_END, TK_DO, line); break; } case TK_FOR: { /* stat -> forstat */ forstat(ls, line); break; } case TK_REPEAT: { /* stat -> repeatstat */ repeatstat(ls, line); break; } case TK_FUNCTION: { /* stat -> funcstat */ funcstat(ls, line); break; } case TK_LOCAL: { /* stat -> localstat */ luaX_next(ls); /* skip LOCAL */ if (testnext(ls, TK_FUNCTION)) /* local function? */ localfunc(ls); else localstat(ls); break; } case TK_GLOBAL: { /* stat -> globalstatfunc */ globalstatfunc(ls, line); break; } case TK_DBCOLON: { /* stat -> label */ luaX_next(ls); /* skip double colon */ labelstat(ls, str_checkname(ls), line); break; } case TK_RETURN: { /* stat -> retstat */ luaX_next(ls); /* skip RETURN */ retstat(ls); break; } case TK_BREAK: { /* stat -> breakstat */ breakstat(ls, line); break; } case TK_GOTO: { /* stat -> 'goto' NAME */ luaX_next(ls); /* skip 'goto' */ gotostat(ls, line); break; } #if defined(LUA_COMPAT_GLOBAL) case TK_NAME: { /* compatibility code to parse global keyword when "global" is not reserved */ if (ls->t.seminfo.ts == ls->glbn) { /* current = "global"? */ int lk = luaX_lookahead(ls); if (lk == '<' || lk == TK_NAME || lk == '*' || lk == TK_FUNCTION) { /* 'global ' or 'global name' or 'global *' or 'global function' */ globalstatfunc(ls, line); break; } } /* else... */ } #endif /* FALLTHROUGH */ default: { /* stat -> func | assignment */ exprstat(ls); break; } } lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && ls->fs->freereg >= luaY_nvarstack(ls->fs)); ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */ leavelevel(ls); } /* }====================================================================== */ /* }====================================================================== */ /* ** compiles the main function, which is a regular vararg function with an ** upvalue named LUA_ENV */ static void mainfunc (LexState *ls, FuncState *fs) { BlockCnt bl; Upvaldesc *env; open_func(ls, fs, &bl); setvararg(fs); /* main function is always vararg */ env = allocupvalue(fs); /* ...set environment upvalue */ env->instack = 1; env->idx = 0; env->kind = VDKREG; env->name = ls->envn; luaC_objbarrier(ls->L, fs->f, env->name); luaX_next(ls); /* read first token */ statlist(ls); /* parse main body */ check(ls, TK_EOS); close_func(ls); } LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Dyndata *dyd, const char *name, int firstchar) { LexState lexstate; FuncState funcstate; LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ setclLvalue2s(L, L->top.p, cl); /* anchor it (to avoid being collected) */ luaD_inctop(L); lexstate.h = luaH_new(L); /* create table for scanner */ sethvalue2s(L, L->top.p, lexstate.h); /* anchor it */ luaD_inctop(L); funcstate.f = cl->p = luaF_newproto(L); luaC_objbarrier(L, cl, cl->p); funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ luaC_objbarrier(L, funcstate.f, funcstate.f->source); lexstate.buff = buff; lexstate.dyd = dyd; dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); mainfunc(&lexstate, &funcstate); lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); /* all scopes should be correctly finished */ lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); L->top.p--; /* remove scanner's table */ return cl; /* closure is on the stack, too */ } /* ** $Id: lstate.c $ ** Global State ** See Copyright Notice in lua.h */ #define lstate_c #define LUA_CORE #include #include #include "lua.h" #define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l))) /* ** these macros allow user-specific actions when a thread is ** created/deleted */ #if !defined(luai_userstateopen) #define luai_userstateopen(L) ((void)L) #endif #if !defined(luai_userstateclose) #define luai_userstateclose(L) ((void)L) #endif #if !defined(luai_userstatethread) #define luai_userstatethread(L,L1) ((void)L) #endif #if !defined(luai_userstatefree) #define luai_userstatefree(L,L1) ((void)L) #endif /* ** set GCdebt to a new value keeping the real number of allocated ** objects (GCtotalobjs - GCdebt) invariant and avoiding overflows in ** 'GCtotalobjs'. */ void luaE_setdebt (global_State *g, l_mem debt) { l_mem tb = gettotalbytes(g); lua_assert(tb > 0); if (debt > MAX_LMEM - tb) debt = MAX_LMEM - tb; /* will make GCtotalbytes == MAX_LMEM */ g->GCtotalbytes = tb + debt; g->GCdebt = debt; } CallInfo *luaE_extendCI (lua_State *L) { CallInfo *ci; lua_assert(L->ci->next == NULL); ci = luaM_new(L, CallInfo); lua_assert(L->ci->next == NULL); L->ci->next = ci; ci->previous = L->ci; ci->next = NULL; ci->u.l.trap = 0; L->nci++; return ci; } /* ** free all CallInfo structures not in use by a thread */ static void freeCI (lua_State *L) { CallInfo *ci = L->ci; CallInfo *next = ci->next; ci->next = NULL; while ((ci = next) != NULL) { next = ci->next; luaM_free(L, ci); L->nci--; } } /* ** free half of the CallInfo structures not in use by a thread, ** keeping the first one. */ void luaE_shrinkCI (lua_State *L) { CallInfo *ci = L->ci->next; /* first free CallInfo */ CallInfo *next; if (ci == NULL) return; /* no extra elements */ while ((next = ci->next) != NULL) { /* two extra elements? */ CallInfo *next2 = next->next; /* next's next */ ci->next = next2; /* remove next from the list */ L->nci--; luaM_free(L, next); /* free next */ if (next2 == NULL) break; /* no more elements */ else { next2->previous = ci; ci = next2; /* continue */ } } } /* ** Called when 'getCcalls(L)' larger or equal to LUAI_MAXCCALLS. ** If equal, raises an overflow error. If value is larger than ** LUAI_MAXCCALLS (which means it is handling an overflow) but ** not much larger, does not report an error (to allow overflow ** handling to work). */ void luaE_checkcstack (lua_State *L) { if (getCcalls(L) == LUAI_MAXCCALLS) luaG_runerror(L, "C stack overflow"); else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11)) luaD_errerr(L); /* error while handling stack error */ } LUAI_FUNC void luaE_incCstack (lua_State *L) { L->nCcalls++; if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) luaE_checkcstack(L); } static void resetCI (lua_State *L) { CallInfo *ci = L->ci = &L->base_ci; ci->func.p = L->stack.p; setnilvalue(s2v(ci->func.p)); /* 'function' entry for basic 'ci' */ ci->top.p = ci->func.p + 1 + LUA_MINSTACK; /* +1 for 'function' entry */ ci->u.c.k = NULL; ci->callstatus = CIST_C; L->status = LUA_OK; L->errfunc = 0; /* stack unwind can "throw away" the error function */ } static void stack_init (lua_State *L1, lua_State *L) { int i; /* initialize stack array */ L1->stack.p = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, StackValue); L1->tbclist.p = L1->stack.p; for (i = 0; i < BASIC_STACK_SIZE + EXTRA_STACK; i++) setnilvalue(s2v(L1->stack.p + i)); /* erase new stack */ L1->stack_last.p = L1->stack.p + BASIC_STACK_SIZE; /* initialize first ci */ resetCI(L1); L1->top.p = L1->stack.p + 1; /* +1 for 'function' entry */ } static void freestack (lua_State *L) { if (L->stack.p == NULL) return; /* stack not completely built yet */ L->ci = &L->base_ci; /* free the entire 'ci' list */ freeCI(L); lua_assert(L->nci == 0); /* free stack */ luaM_freearray(L, L->stack.p, cast_sizet(stacksize(L) + EXTRA_STACK)); } /* ** Create registry table and its predefined values */ static void init_registry (lua_State *L, global_State *g) { /* create registry */ TValue aux; Table *registry = luaH_new(L); sethvalue(L, &g->l_registry, registry); luaH_resize(L, registry, LUA_RIDX_LAST, 0); /* registry[1] = false */ setbfvalue(&aux); luaH_setint(L, registry, 1, &aux); /* registry[LUA_RIDX_MAINTHREAD] = L */ setthvalue(L, &aux, L); luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &aux); /* registry[LUA_RIDX_GLOBALS] = new table (table of globals) */ sethvalue(L, &aux, luaH_new(L)); luaH_setint(L, registry, LUA_RIDX_GLOBALS, &aux); } /* ** open parts of the state that may cause memory-allocation errors. */ static void f_luaopen (lua_State *L, void *ud) { global_State *g = G(L); UNUSED(ud); stack_init(L, L); /* init stack */ init_registry(L, g); luaS_init(L); luaT_init(L); luaX_init(L); g->gcstp = 0; /* allow gc */ setnilvalue(&g->nilvalue); /* now state is complete */ luai_userstateopen(L); } /* ** preinitialize a thread with consistent values without allocating ** any memory (to avoid errors) */ static void preinit_thread (lua_State *L, global_State *g) { G(L) = g; L->stack.p = NULL; L->ci = NULL; L->nci = 0; L->twups = L; /* thread has no upvalues */ L->nCcalls = 0; L->errorJmp = NULL; L->hook = NULL; L->hookmask = 0; L->basehookcount = 0; L->allowhook = 1; resethookcount(L); L->openupval = NULL; L->status = LUA_OK; L->errfunc = 0; L->oldpc = 0; L->base_ci.previous = L->base_ci.next = NULL; } lu_mem luaE_threadsize (lua_State *L) { lu_mem sz = cast(lu_mem, sizeof(LX)) + cast_uint(L->nci) * sizeof(CallInfo); if (L->stack.p != NULL) sz += cast_uint(stacksize(L) + EXTRA_STACK) * sizeof(StackValue); return sz; } static void close_state (lua_State *L) { global_State *g = G(L); if (!completestate(g)) /* closing a partially built state? */ luaC_freeallobjects(L); /* just collect its objects */ else { /* closing a fully built state */ resetCI(L); luaD_closeprotected(L, 1, LUA_OK); /* close all upvalues */ L->top.p = L->stack.p + 1; /* empty the stack to run finalizers */ luaC_freeallobjects(L); /* collect all objects */ luai_userstateclose(L); } luaM_freearray(L, G(L)->strt.hash, cast_sizet(G(L)->strt.size)); freestack(L); lua_assert(gettotalbytes(g) == sizeof(global_State)); (*g->frealloc)(g->ud, g, sizeof(global_State), 0); /* free main block */ } LUA_API lua_State *lua_newthread (lua_State *L) { global_State *g = G(L); GCObject *o; lua_State *L1; lua_lock(L); luaC_checkGC(L); /* create new thread */ o = luaC_newobjdt(L, LUA_TTHREAD, sizeof(LX), offsetof(LX, l)); L1 = gco2th(o); /* anchor it on L stack */ setthvalue2s(L, L->top.p, L1); api_incr_top(L); preinit_thread(L1, g); L1->hookmask = L->hookmask; L1->basehookcount = L->basehookcount; L1->hook = L->hook; resethookcount(L1); /* initialize L1 extra space */ memcpy(lua_getextraspace(L1), lua_getextraspace(mainthread(g)), LUA_EXTRASPACE); luai_userstatethread(L, L1); stack_init(L1, L); /* init stack */ lua_unlock(L); return L1; } void luaE_freethread (lua_State *L, lua_State *L1) { LX *l = fromstate(L1); luaF_closeupval(L1, L1->stack.p); /* close all upvalues */ lua_assert(L1->openupval == NULL); luai_userstatefree(L, L1); freestack(L1); luaM_free(L, l); } TStatus luaE_resetthread (lua_State *L, TStatus status) { resetCI(L); if (status == LUA_YIELD) status = LUA_OK; status = luaD_closeprotected(L, 1, status); if (status != LUA_OK) /* errors? */ luaD_seterrorobj(L, status, L->stack.p + 1); else L->top.p = L->stack.p + 1; luaD_reallocstack(L, cast_int(L->ci->top.p - L->stack.p), 0); return status; } LUA_API int lua_closethread (lua_State *L, lua_State *from) { TStatus status; lua_lock(L); L->nCcalls = (from) ? getCcalls(from) : 0; status = luaE_resetthread(L, L->status); if (L == from) /* closing itself? */ luaD_throwbaselevel(L, status); lua_unlock(L); return APIstatus(status); } LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud, unsigned seed) { int i; lua_State *L; global_State *g = cast(global_State*, (*f)(ud, NULL, LUA_TTHREAD, sizeof(global_State))); if (g == NULL) return NULL; L = &g->mainth.l; L->tt = LUA_VTHREAD; g->currentwhite = bitmask(WHITE0BIT); L->marked = luaC_white(g); preinit_thread(L, g); g->allgc = obj2gco(L); /* by now, only object is the main thread */ L->next = NULL; incnny(L); /* main thread is always non yieldable */ g->frealloc = f; g->ud = ud; g->warnf = NULL; g->ud_warn = NULL; g->seed = seed; g->gcstp = GCSTPGC; /* no GC while building state */ g->strt.size = g->strt.nuse = 0; g->strt.hash = NULL; setnilvalue(&g->l_registry); g->panic = NULL; g->gcstate = GCSpause; g->gckind = KGC_INC; g->gcstopem = 0; g->gcemergency = 0; g->finobj = g->tobefnz = g->fixedgc = NULL; g->firstold1 = g->survival = g->old1 = g->reallyold = NULL; g->finobjsur = g->finobjold1 = g->finobjrold = NULL; g->sweepgc = NULL; g->gray = g->grayagain = NULL; g->weak = g->ephemeron = g->allweak = NULL; g->twups = NULL; g->GCtotalbytes = sizeof(global_State); g->GCmarked = 0; g->GCdebt = 0; setivalue(&g->nilvalue, 0); /* to signal that state is not yet built */ setgcparam(g, PAUSE, LUAI_GCPAUSE); setgcparam(g, STEPMUL, LUAI_GCMUL); setgcparam(g, STEPSIZE, LUAI_GCSTEPSIZE); setgcparam(g, MINORMUL, LUAI_GENMINORMUL); setgcparam(g, MINORMAJOR, LUAI_MINORMAJOR); setgcparam(g, MAJORMINOR, LUAI_MAJORMINOR); for (i=0; i < LUA_NUMTYPES; i++) g->mt[i] = NULL; if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) { /* memory allocation error: free partial state */ close_state(L); L = NULL; } return L; } LUA_API void lua_close (lua_State *L) { lua_lock(L); L = mainthread(G(L)); /* only the main thread can be closed */ close_state(L); } void luaE_warning (lua_State *L, const char *msg, int tocont) { lua_WarnFunction wf = G(L)->warnf; if (wf != NULL) wf(G(L)->ud_warn, msg, tocont); } /* ** Generate a warning from an error message */ void luaE_warnerror (lua_State *L, const char *where) { TValue *errobj = s2v(L->top.p - 1); /* error object */ const char *msg = (ttisstring(errobj)) ? getstr(tsvalue(errobj)) : "error object is not a string"; /* produce warning "error in %s (%s)" (where, msg) */ luaE_warning(L, "error in ", 1); luaE_warning(L, where, 1); luaE_warning(L, " (", 1); luaE_warning(L, msg, 1); luaE_warning(L, ")", 0); } /* ** $Id: lstring.c $ ** String table (keeps all strings handled by Lua) ** See Copyright Notice in lua.h */ #define lstring_c #define LUA_CORE #include #include "lua.h" /* ** Maximum size for string table. */ #define MAXSTRTB cast_int(luaM_limitN(INT_MAX, TString*)) /* ** Initial size for the string table (must be power of 2). ** The Lua core alone registers ~50 strings (reserved words + ** metaevent keys + a few others). Libraries would typically add ** a few dozens more. */ #if !defined(MINSTRTABSIZE) #define MINSTRTABSIZE 128 #endif /* ** generic equality for strings */ int luaS_eqstr (TString *a, TString *b) { size_t len1, len2; const char *s1 = getlstr(a, len1); const char *s2 = getlstr(b, len2); return ((len1 == len2) && /* equal length and ... */ (memcmp(s1, s2, len1) == 0)); /* equal contents */ } static unsigned luaS_hash (const char *str, size_t l, unsigned seed) { unsigned int h = seed ^ cast_uint(l); for (; l > 0; l--) h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1])); return h; } unsigned luaS_hashlongstr (TString *ts) { lua_assert(ts->tt == LUA_VLNGSTR); if (ts->extra == 0) { /* no hash? */ size_t len = ts->u.lnglen; ts->hash = luaS_hash(getlngstr(ts), len, ts->hash); ts->extra = 1; /* now it has its hash */ } return ts->hash; } static void tablerehash (TString **vect, int osize, int nsize) { int i; for (i = osize; i < nsize; i++) /* clear new elements */ vect[i] = NULL; for (i = 0; i < osize; i++) { /* rehash old part of the array */ TString *p = vect[i]; vect[i] = NULL; while (p) { /* for each string in the list */ TString *hnext = p->u.hnext; /* save next */ unsigned int h = lmod(p->hash, nsize); /* new position */ p->u.hnext = vect[h]; /* chain it into array */ vect[h] = p; p = hnext; } } } /* ** Resize the string table. If allocation fails, keep the current size. ** (This can degrade performance, but any non-zero size should work ** correctly.) */ void luaS_resize (lua_State *L, int nsize) { stringtable *tb = &G(L)->strt; int osize = tb->size; TString **newvect; if (nsize < osize) /* shrinking table? */ tablerehash(tb->hash, osize, nsize); /* depopulate shrinking part */ newvect = luaM_reallocvector(L, tb->hash, osize, nsize, TString*); if (l_unlikely(newvect == NULL)) { /* reallocation failed? */ if (nsize < osize) /* was it shrinking table? */ tablerehash(tb->hash, nsize, osize); /* restore to original size */ /* leave table as it was */ } else { /* allocation succeeded */ tb->hash = newvect; tb->size = nsize; if (nsize > osize) tablerehash(newvect, osize, nsize); /* rehash for new size */ } } /* ** Clear API string cache. (Entries cannot be empty, so fill them with ** a non-collectable string.) */ void luaS_clearcache (global_State *g) { int i, j; for (i = 0; i < STRCACHE_N; i++) for (j = 0; j < STRCACHE_M; j++) { if (iswhite(g->strcache[i][j])) /* will entry be collected? */ g->strcache[i][j] = g->memerrmsg; /* replace it with something fixed */ } } /* ** Initialize the string table and the string cache */ void luaS_init (lua_State *L) { global_State *g = G(L); int i, j; stringtable *tb = &G(L)->strt; tb->hash = luaM_newvector(L, MINSTRTABSIZE, TString*); tablerehash(tb->hash, 0, MINSTRTABSIZE); /* clear array */ tb->size = MINSTRTABSIZE; /* pre-create memory-error message */ g->memerrmsg = luaS_newliteral(L, MEMERRMSG); luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */ for (i = 0; i < STRCACHE_N; i++) /* fill cache with valid strings */ for (j = 0; j < STRCACHE_M; j++) g->strcache[i][j] = g->memerrmsg; } size_t luaS_sizelngstr (size_t len, int kind) { switch (kind) { case LSTRREG: /* regular long string */ /* don't need 'falloc'/'ud', but need space for content */ return offsetof(TString, falloc) + (len + 1) * sizeof(char); case LSTRFIX: /* fixed external long string */ /* don't need 'falloc'/'ud' */ return offsetof(TString, falloc); default: /* external long string with deallocation */ lua_assert(kind == LSTRMEM); return sizeof(TString); } } /* ** creates a new string object */ static TString *createstrobj (lua_State *L, size_t totalsize, lu_byte tag, unsigned h) { TString *ts; GCObject *o; o = luaC_newobj(L, tag, totalsize); ts = gco2ts(o); ts->hash = h; ts->extra = 0; return ts; } TString *luaS_createlngstrobj (lua_State *L, size_t l) { size_t totalsize = luaS_sizelngstr(l, LSTRREG); TString *ts = createstrobj(L, totalsize, LUA_VLNGSTR, G(L)->seed); ts->u.lnglen = l; ts->shrlen = LSTRREG; /* signals that it is a regular long string */ ts->contents = cast_charp(ts) + offsetof(TString, falloc); ts->contents[l] = '\0'; /* ending 0 */ return ts; } void luaS_remove (lua_State *L, TString *ts) { stringtable *tb = &G(L)->strt; TString **p = &tb->hash[lmod(ts->hash, tb->size)]; while (*p != ts) /* find previous element */ p = &(*p)->u.hnext; *p = (*p)->u.hnext; /* remove element from its list */ tb->nuse--; } static void growstrtab (lua_State *L, stringtable *tb) { if (l_unlikely(tb->nuse == INT_MAX)) { /* too many strings? */ luaC_fullgc(L, 1); /* try to free some... */ if (tb->nuse == INT_MAX) /* still too many? */ luaM_error(L); /* cannot even create a message... */ } if (tb->size <= MAXSTRTB / 2) /* can grow string table? */ luaS_resize(L, tb->size * 2); } /* ** Checks whether short string exists and reuses it or creates a new one. */ static TString *internshrstr (lua_State *L, const char *str, size_t l) { TString *ts; global_State *g = G(L); stringtable *tb = &g->strt; unsigned int h = luaS_hash(str, l, g->seed); TString **list = &tb->hash[lmod(h, tb->size)]; lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */ for (ts = *list; ts != NULL; ts = ts->u.hnext) { if (l == cast_uint(ts->shrlen) && (memcmp(str, getshrstr(ts), l * sizeof(char)) == 0)) { /* found! */ if (isdead(g, ts)) /* dead (but not collected yet)? */ changewhite(ts); /* resurrect it */ return ts; } } /* else must create a new string */ if (tb->nuse >= tb->size) { /* need to grow string table? */ growstrtab(L, tb); list = &tb->hash[lmod(h, tb->size)]; /* rehash with new size */ } ts = createstrobj(L, sizestrshr(l), LUA_VSHRSTR, h); ts->shrlen = cast(ls_byte, l); getshrstr(ts)[l] = '\0'; /* ending 0 */ memcpy(getshrstr(ts), str, l * sizeof(char)); ts->u.hnext = *list; *list = ts; tb->nuse++; return ts; } /* ** new string (with explicit length) */ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { if (l <= LUAI_MAXSHORTLEN) /* short string? */ return internshrstr(L, str, l); else { TString *ts; if (l_unlikely(l * sizeof(char) >= (MAX_SIZE - sizeof(TString)))) luaM_toobig(L); ts = luaS_createlngstrobj(L, l); memcpy(getlngstr(ts), str, l * sizeof(char)); return ts; } } /* ** Create or reuse a zero-terminated string, first checking in the ** cache (using the string address as a key). The cache can contain ** only zero-terminated strings, so it is safe to use 'strcmp' to ** check hits. */ TString *luaS_new (lua_State *L, const char *str) { unsigned int i = point2uint(str) % STRCACHE_N; /* hash */ int j; TString **p = G(L)->strcache[i]; for (j = 0; j < STRCACHE_M; j++) { if (strcmp(str, getstr(p[j])) == 0) /* hit? */ return p[j]; /* that is it */ } /* normal route */ for (j = STRCACHE_M - 1; j > 0; j--) p[j] = p[j - 1]; /* move out last element */ /* new element is first in the list */ p[0] = luaS_newlstr(L, str, strlen(str)); return p[0]; } Udata *luaS_newudata (lua_State *L, size_t s, unsigned short nuvalue) { Udata *u; int i; GCObject *o; if (l_unlikely(s > MAX_SIZE - udatamemoffset(nuvalue))) luaM_toobig(L); o = luaC_newobj(L, LUA_VUSERDATA, sizeudata(nuvalue, s)); u = gco2u(o); u->len = s; u->nuvalue = nuvalue; u->metatable = NULL; for (i = 0; i < nuvalue; i++) setnilvalue(&u->uv[i].uv); return u; } struct NewExt { ls_byte kind; const char *s; size_t len; TString *ts; /* output */ }; static void f_newext (lua_State *L, void *ud) { struct NewExt *ne = cast(struct NewExt *, ud); size_t size = luaS_sizelngstr(0, ne->kind); ne->ts = createstrobj(L, size, LUA_VLNGSTR, G(L)->seed); } TString *luaS_newextlstr (lua_State *L, const char *s, size_t len, lua_Alloc falloc, void *ud) { struct NewExt ne; if (!falloc) { ne.kind = LSTRFIX; f_newext(L, &ne); /* just create header */ } else { ne.kind = LSTRMEM; if (luaD_rawrunprotected(L, f_newext, &ne) != LUA_OK) { /* mem. error? */ (*falloc)(ud, cast_voidp(s), len + 1, 0); /* free external string */ luaM_error(L); /* re-raise memory error */ } ne.ts->falloc = falloc; ne.ts->ud = ud; } ne.ts->shrlen = ne.kind; ne.ts->u.lnglen = len; ne.ts->contents = cast_charp(s); return ne.ts; } /* ** Normalize an external string: If it is short, internalize it. */ TString *luaS_normstr (lua_State *L, TString *ts) { size_t len = ts->u.lnglen; if (len > LUAI_MAXSHORTLEN) return ts; /* long string; keep the original */ else { const char *str = getlngstr(ts); return internshrstr(L, str, len); } } /* ** $Id: lstrlib.c $ ** Standard library for string operations and pattern-matching ** See Copyright Notice in lua.h */ #define lstrlib_c #define LUA_LIB #include #include #include #include #include #include #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** maximum number of captures that a pattern can do during ** pattern-matching. This limit is arbitrary, but must fit in ** an unsigned char. */ #if !defined(LUA_MAXCAPTURES) #define LUA_MAXCAPTURES 32 #endif static int str_len (lua_State *L) { size_t l; luaL_checklstring(L, 1, &l); lua_pushinteger(L, (lua_Integer)l); return 1; } /* ** translate a relative initial string position ** (negative means back from end): clip result to [1, inf). ** The length of any string in Lua must fit in a lua_Integer, ** so there are no overflows in the casts. ** The inverted comparison avoids a possible overflow ** computing '-pos'. */ static size_t posrelatI (lua_Integer pos, size_t len) { if (pos > 0) return (size_t)pos; else if (pos == 0) return 1; else if (pos < -(lua_Integer)len) /* inverted comparison */ return 1; /* clip to 1 */ else return len + (size_t)pos + 1; } /* ** Gets an optional ending string position from argument 'arg', ** with default value 'def'. ** Negative means back from end: clip result to [0, len] */ static size_t getendpos (lua_State *L, int arg, lua_Integer def, size_t len) { lua_Integer pos = luaL_optinteger(L, arg, def); if (pos > (lua_Integer)len) return len; else if (pos >= 0) return (size_t)pos; else if (pos < -(lua_Integer)len) return 0; else return len + (size_t)pos + 1; } static int str_sub (lua_State *L) { size_t l; const char *s = luaL_checklstring(L, 1, &l); size_t start = posrelatI(luaL_checkinteger(L, 2), l); size_t end = getendpos(L, 3, -1, l); if (start <= end) lua_pushlstring(L, s + start - 1, (end - start) + 1); else lua_pushliteral(L, ""); return 1; } static int str_reverse (lua_State *L) { size_t l, i; luaL_Buffer b; const char *s = luaL_checklstring(L, 1, &l); char *p = luaL_buffinitsize(L, &b, l); for (i = 0; i < l; i++) p[i] = s[l - i - 1]; luaL_pushresultsize(&b, l); return 1; } static int str_lower (lua_State *L) { size_t l; size_t i; luaL_Buffer b; const char *s = luaL_checklstring(L, 1, &l); char *p = luaL_buffinitsize(L, &b, l); for (i=0; i MAX_SIZE - lsep || cast_st2S(len + lsep) > cast_st2S(MAX_SIZE) / n)) return luaL_error(L, "resulting string too large"); else { size_t totallen = (cast_sizet(n) * (len + lsep)) - lsep; luaL_Buffer b; char *p = luaL_buffinitsize(L, &b, totallen); while (n-- > 1) { /* first n-1 copies (followed by separator) */ memcpy(p, s, len * sizeof(char)); p += len; if (lsep > 0) { /* empty 'memcpy' is not that cheap */ memcpy(p, sep, lsep * sizeof(char)); p += lsep; } } memcpy(p, s, len * sizeof(char)); /* last copy without separator */ luaL_pushresultsize(&b, totallen); } return 1; } static int str_byte (lua_State *L) { size_t l; const char *s = luaL_checklstring(L, 1, &l); lua_Integer pi = luaL_optinteger(L, 2, 1); size_t posi = posrelatI(pi, l); size_t pose = getendpos(L, 3, pi, l); int n, i; if (posi > pose) return 0; /* empty interval; return no values */ if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */ return luaL_error(L, "string slice too long"); n = (int)(pose - posi) + 1; luaL_checkstack(L, n, "string slice too long"); for (i=0; iinit) { state->init = 1; luaL_buffinit(L, &state->B); } if (b == NULL) { /* finishing dump? */ luaL_pushresult(&state->B); /* push result */ lua_replace(L, 1); /* move it to reserved slot */ } else luaL_addlstring(&state->B, (const char *)b, size); return 0; } static int str_dump (lua_State *L) { struct str_Writer state; int strip = lua_toboolean(L, 2); luaL_argcheck(L, lua_type(L, 1) == LUA_TFUNCTION && !lua_iscfunction(L, 1), 1, "Lua function expected"); /* ensure function is on the top of the stack and vacate slot 1 */ lua_pushvalue(L, 1); state.init = 0; lua_dump(L, writer, &state, strip); lua_settop(L, 1); /* leave final result on top */ return 1; } /* ** {====================================================== ** METAMETHODS ** ======================================================= */ #if defined(LUA_NOCVTS2N) /* { */ /* no coercion from strings to numbers */ static const luaL_Reg stringmetamethods[] = { {"__index", NULL}, /* placeholder */ {NULL, NULL} }; #else /* }{ */ static int tonum (lua_State *L, int arg) { if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */ lua_pushvalue(L, arg); return 1; } else { /* check whether it is a numerical string */ size_t len; const char *s = lua_tolstring(L, arg, &len); return (s != NULL && lua_stringtonumber(L, s) == len + 1); } } /* ** To be here, either the first operand was a string or the first ** operand didn't have a corresponding metamethod. (Otherwise, that ** other metamethod would have been called.) So, if this metamethod ** doesn't work, the only other option would be for the second ** operand to have a different metamethod. */ static void trymt (lua_State *L, const char *mtkey, const char *opname) { lua_settop(L, 2); /* back to the original arguments */ if (l_unlikely(lua_type(L, 2) == LUA_TSTRING || !luaL_getmetafield(L, 2, mtkey))) luaL_error(L, "attempt to %s a '%s' with a '%s'", opname, luaL_typename(L, -2), luaL_typename(L, -1)); lua_insert(L, -3); /* put metamethod before arguments */ lua_call(L, 2, 1); /* call metamethod */ } static int arith (lua_State *L, int op, const char *mtname) { if (tonum(L, 1) && tonum(L, 2)) lua_arith(L, op); /* result will be on the top */ else trymt(L, mtname, mtname + 2); return 1; } static int arith_add (lua_State *L) { return arith(L, LUA_OPADD, "__add"); } static int arith_sub (lua_State *L) { return arith(L, LUA_OPSUB, "__sub"); } static int arith_mul (lua_State *L) { return arith(L, LUA_OPMUL, "__mul"); } static int arith_mod (lua_State *L) { return arith(L, LUA_OPMOD, "__mod"); } static int arith_pow (lua_State *L) { return arith(L, LUA_OPPOW, "__pow"); } static int arith_div (lua_State *L) { return arith(L, LUA_OPDIV, "__div"); } static int arith_idiv (lua_State *L) { return arith(L, LUA_OPIDIV, "__idiv"); } static int arith_unm (lua_State *L) { return arith(L, LUA_OPUNM, "__unm"); } static const luaL_Reg stringmetamethods[] = { {"__add", arith_add}, {"__sub", arith_sub}, {"__mul", arith_mul}, {"__mod", arith_mod}, {"__pow", arith_pow}, {"__div", arith_div}, {"__idiv", arith_idiv}, {"__unm", arith_unm}, {"__index", NULL}, /* placeholder */ {NULL, NULL} }; #endif /* } */ /* }====================================================== */ /* ** {====================================================== ** PATTERN MATCHING ** ======================================================= */ #define CAP_UNFINISHED (-1) #define CAP_POSITION (-2) typedef struct MatchState { const char *src_init; /* init of source string */ const char *src_end; /* end ('\0') of source string */ const char *p_end; /* end ('\0') of pattern */ lua_State *L; int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ int level; /* total number of captures (finished or unfinished) */ struct { const char *init; ptrdiff_t len; /* length or special value (CAP_*) */ } capture[LUA_MAXCAPTURES]; } MatchState; /* recursive function */ static const char *match (MatchState *ms, const char *s, const char *p); /* maximum recursion depth for 'match' */ #if !defined(MAXCCALLS) #define MAXCCALLS 200 #endif #define L_ESC '%' #define SPECIALS "^$*+?.([%-" static int check_capture (MatchState *ms, int l) { l -= '1'; if (l_unlikely(l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)) return luaL_error(ms->L, "invalid capture index %%%d", l + 1); return l; } static int capture_to_close (MatchState *ms) { int level = ms->level; for (level--; level>=0; level--) if (ms->capture[level].len == CAP_UNFINISHED) return level; return luaL_error(ms->L, "invalid pattern capture"); } static const char *classend (MatchState *ms, const char *p) { switch (*p++) { case L_ESC: { if (l_unlikely(p == ms->p_end)) luaL_error(ms->L, "malformed pattern (ends with '%%')"); return p+1; } case '[': { if (*p == '^') p++; do { /* look for a ']' */ if (l_unlikely(p == ms->p_end)) luaL_error(ms->L, "malformed pattern (missing ']')"); if (*(p++) == L_ESC && p < ms->p_end) p++; /* skip escapes (e.g. '%]') */ } while (*p != ']'); return p+1; } default: { return p; } } } static int match_class (int c, int cl) { int res; switch (tolower(cl)) { case 'a' : res = isalpha(c); break; case 'c' : res = iscntrl(c); break; case 'd' : res = isdigit(c); break; case 'g' : res = isgraph(c); break; case 'l' : res = islower(c); break; case 'p' : res = ispunct(c); break; case 's' : res = isspace(c); break; case 'u' : res = isupper(c); break; case 'w' : res = isalnum(c); break; case 'x' : res = isxdigit(c); break; case 'z' : res = (c == 0); break; /* deprecated option */ default: return (cl == c); } return (islower(cl) ? res : !res); } static int matchbracketclass (int c, const char *p, const char *ec) { int sig = 1; if (*(p+1) == '^') { sig = 0; p++; /* skip the '^' */ } while (++p < ec) { if (*p == L_ESC) { p++; if (match_class(c, cast_uchar(*p))) return sig; } else if ((*(p+1) == '-') && (p+2 < ec)) { p+=2; if (cast_uchar(*(p-2)) <= c && c <= cast_uchar(*p)) return sig; } else if (cast_uchar(*p) == c) return sig; } return !sig; } static int singlematch (MatchState *ms, const char *s, const char *p, const char *ep) { if (s >= ms->src_end) return 0; else { int c = cast_uchar(*s); switch (*p) { case '.': return 1; /* matches any char */ case L_ESC: return match_class(c, cast_uchar(*(p+1))); case '[': return matchbracketclass(c, p, ep-1); default: return (cast_uchar(*p) == c); } } } static const char *matchbalance (MatchState *ms, const char *s, const char *p) { if (l_unlikely(p >= ms->p_end - 1)) luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')"); if (*s != *p) return NULL; else { int b = *p; int e = *(p+1); int cont = 1; while (++s < ms->src_end) { if (*s == e) { if (--cont == 0) return s+1; } else if (*s == b) cont++; } } return NULL; /* string ends out of balance */ } static const char *max_expand (MatchState *ms, const char *s, const char *p, const char *ep) { ptrdiff_t i = 0; /* counts maximum expand for item */ while (singlematch(ms, s + i, p, ep)) i++; /* keeps trying to match with the maximum repetitions */ while (i>=0) { const char *res = match(ms, (s+i), ep+1); if (res) return res; i--; /* else didn't match; reduce 1 repetition to try again */ } return NULL; } static const char *min_expand (MatchState *ms, const char *s, const char *p, const char *ep) { for (;;) { const char *res = match(ms, s, ep+1); if (res != NULL) return res; else if (singlematch(ms, s, p, ep)) s++; /* try with one more repetition */ else return NULL; } } static const char *start_capture (MatchState *ms, const char *s, const char *p, int what) { const char *res; int level = ms->level; if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); ms->capture[level].init = s; ms->capture[level].len = what; ms->level = level+1; if ((res=match(ms, s, p)) == NULL) /* match failed? */ ms->level--; /* undo capture */ return res; } static const char *end_capture (MatchState *ms, const char *s, const char *p) { int l = capture_to_close(ms); const char *res; ms->capture[l].len = s - ms->capture[l].init; /* close capture */ if ((res = match(ms, s, p)) == NULL) /* match failed? */ ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ return res; } static const char *match_capture (MatchState *ms, const char *s, int l) { size_t len; l = check_capture(ms, l); len = cast_sizet(ms->capture[l].len); if ((size_t)(ms->src_end-s) >= len && memcmp(ms->capture[l].init, s, len) == 0) return s+len; else return NULL; } static const char *match (MatchState *ms, const char *s, const char *p) { if (l_unlikely(ms->matchdepth-- == 0)) luaL_error(ms->L, "pattern too complex"); init: /* using goto to optimize tail recursion */ if (p != ms->p_end) { /* end of pattern? */ switch (*p) { case '(': { /* start capture */ if (*(p + 1) == ')') /* position capture? */ s = start_capture(ms, s, p + 2, CAP_POSITION); else s = start_capture(ms, s, p + 1, CAP_UNFINISHED); break; } case ')': { /* end capture */ s = end_capture(ms, s, p + 1); break; } case '$': { if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ goto dflt; /* no; go to default */ s = (s == ms->src_end) ? s : NULL; /* check end of string */ break; } case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ switch (*(p + 1)) { case 'b': { /* balanced string? */ s = matchbalance(ms, s, p + 2); if (s != NULL) { p += 4; goto init; /* return match(ms, s, p + 4); */ } /* else fail (s == NULL) */ break; } case 'f': { /* frontier? */ const char *ep; char previous; p += 2; if (l_unlikely(*p != '[')) luaL_error(ms->L, "missing '[' after '%%f' in pattern"); ep = classend(ms, p); /* points to what is next */ previous = (s == ms->src_init) ? '\0' : *(s - 1); if (!matchbracketclass(cast_uchar(previous), p, ep - 1) && matchbracketclass(cast_uchar(*s), p, ep - 1)) { p = ep; goto init; /* return match(ms, s, ep); */ } s = NULL; /* match failed */ break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { /* capture results (%0-%9)? */ s = match_capture(ms, s, cast_uchar(*(p + 1))); if (s != NULL) { p += 2; goto init; /* return match(ms, s, p + 2) */ } break; } default: goto dflt; } break; } default: dflt: { /* pattern class plus optional suffix */ const char *ep = classend(ms, p); /* points to optional suffix */ /* does not match at least once? */ if (!singlematch(ms, s, p, ep)) { if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ } else /* '+' or no suffix */ s = NULL; /* fail */ } else { /* matched once */ switch (*ep) { /* handle optional suffix */ case '?': { /* optional */ const char *res; if ((res = match(ms, s + 1, ep + 1)) != NULL) s = res; else { p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ } break; } case '+': /* 1 or more repetitions */ s++; /* 1 match already done */ /* FALLTHROUGH */ case '*': /* 0 or more repetitions */ s = max_expand(ms, s, p, ep); break; case '-': /* 0 or more repetitions (minimum) */ s = min_expand(ms, s, p, ep); break; default: /* no suffix */ s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ } } break; } } } ms->matchdepth++; return s; } static const char *lmemfind (const char *s1, size_t l1, const char *s2, size_t l2) { if (l2 == 0) return s1; /* empty strings are everywhere */ else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ else { const char *init; /* to search for a '*s2' inside 's1' */ l2--; /* 1st char will be checked by 'memchr' */ l1 = l1-l2; /* 's2' cannot be found after that */ while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { init++; /* 1st char is already checked */ if (memcmp(init, s2+1, l2) == 0) return init-1; else { /* correct 'l1' and 's1' to try again */ l1 -= ct_diff2sz(init - s1); s1 = init; } } return NULL; /* not found */ } } /* ** get information about the i-th capture. If there are no captures ** and 'i==0', return information about the whole match, which ** is the range 's'..'e'. If the capture is a string, return ** its length and put its address in '*cap'. If it is an integer ** (a position), push it on the stack and return CAP_POSITION. */ static ptrdiff_t get_onecapture (MatchState *ms, int i, const char *s, const char *e, const char **cap) { if (i >= ms->level) { if (l_unlikely(i != 0)) luaL_error(ms->L, "invalid capture index %%%d", i + 1); *cap = s; return (e - s); } else { ptrdiff_t capl = ms->capture[i].len; *cap = ms->capture[i].init; if (l_unlikely(capl == CAP_UNFINISHED)) luaL_error(ms->L, "unfinished capture"); else if (capl == CAP_POSITION) lua_pushinteger(ms->L, ct_diff2S(ms->capture[i].init - ms->src_init) + 1); return capl; } } /* ** Push the i-th capture on the stack. */ static void push_onecapture (MatchState *ms, int i, const char *s, const char *e) { const char *cap; ptrdiff_t l = get_onecapture(ms, i, s, e, &cap); if (l != CAP_POSITION) lua_pushlstring(ms->L, cap, cast_sizet(l)); /* else position was already pushed */ } static int push_captures (MatchState *ms, const char *s, const char *e) { int i; int nlevels = (ms->level == 0 && s) ? 1 : ms->level; luaL_checkstack(ms->L, nlevels, "too many captures"); for (i = 0; i < nlevels; i++) push_onecapture(ms, i, s, e); return nlevels; /* number of strings pushed */ } /* check whether pattern has no special characters */ static int nospecials (const char *p, size_t l) { size_t upto = 0; do { if (strpbrk(p + upto, SPECIALS)) return 0; /* pattern has a special character */ upto += strlen(p + upto) + 1; /* may have more after \0 */ } while (upto <= l); return 1; /* no special chars found */ } static void prepstate (MatchState *ms, lua_State *L, const char *s, size_t ls, const char *p, size_t lp) { ms->L = L; ms->matchdepth = MAXCCALLS; ms->src_init = s; ms->src_end = s + ls; ms->p_end = p + lp; } static void reprepstate (MatchState *ms) { ms->level = 0; lua_assert(ms->matchdepth == MAXCCALLS); } static int str_find_aux (lua_State *L, int find) { size_t ls, lp; const char *s = luaL_checklstring(L, 1, &ls); const char *p = luaL_checklstring(L, 2, &lp); size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; if (init > ls) { /* start after string's end? */ luaL_pushfail(L); /* cannot find anything */ return 1; } /* explicit request or no special characters? */ if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { /* do a plain search */ const char *s2 = lmemfind(s + init, ls - init, p, lp); if (s2) { lua_pushinteger(L, ct_diff2S(s2 - s) + 1); lua_pushinteger(L, cast_st2S(ct_diff2sz(s2 - s) + lp)); return 2; } } else { MatchState ms; const char *s1 = s + init; int anchor = (*p == '^'); if (anchor) { p++; lp--; /* skip anchor character */ } prepstate(&ms, L, s, ls, p, lp); do { const char *res; reprepstate(&ms); if ((res=match(&ms, s1, p)) != NULL) { if (find) { lua_pushinteger(L, ct_diff2S(s1 - s) + 1); /* start */ lua_pushinteger(L, ct_diff2S(res - s)); /* end */ return push_captures(&ms, NULL, 0) + 2; } else return push_captures(&ms, s1, res); } } while (s1++ < ms.src_end && !anchor); } luaL_pushfail(L); /* not found */ return 1; } static int str_find (lua_State *L) { return str_find_aux(L, 1); } static int str_match (lua_State *L) { return str_find_aux(L, 0); } /* state for 'gmatch' */ typedef struct GMatchState { const char *src; /* current position */ const char *p; /* pattern */ const char *lastmatch; /* end of last match */ MatchState ms; /* match state */ } GMatchState; static int gmatch_aux (lua_State *L) { GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3)); const char *src; gm->ms.L = L; for (src = gm->src; src <= gm->ms.src_end; src++) { const char *e; reprepstate(&gm->ms); if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) { gm->src = gm->lastmatch = e; return push_captures(&gm->ms, src, e); } } return 0; /* not found */ } static int gmatch (lua_State *L) { size_t ls, lp; const char *s = luaL_checklstring(L, 1, &ls); const char *p = luaL_checklstring(L, 2, &lp); size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; GMatchState *gm; lua_settop(L, 2); /* keep strings on closure to avoid being collected */ gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0); if (init > ls) /* start after string's end? */ init = ls + 1; /* avoid overflows in 's + init' */ prepstate(&gm->ms, L, s, ls, p, lp); gm->src = s + init; gm->p = p; gm->lastmatch = NULL; lua_pushcclosure(L, gmatch_aux, 3); return 1; } static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, const char *e) { size_t l; lua_State *L = ms->L; const char *news = lua_tolstring(L, 3, &l); const char *p; while ((p = (char *)memchr(news, L_ESC, l)) != NULL) { luaL_addlstring(b, news, ct_diff2sz(p - news)); p++; /* skip ESC */ if (*p == L_ESC) /* '%%' */ luaL_addchar(b, *p); else if (*p == '0') /* '%0' */ luaL_addlstring(b, s, ct_diff2sz(e - s)); else if (isdigit(cast_uchar(*p))) { /* '%n' */ const char *cap; ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap); if (resl == CAP_POSITION) luaL_addvalue(b); /* add position to accumulated result */ else luaL_addlstring(b, cap, cast_sizet(resl)); } else luaL_error(L, "invalid use of '%c' in replacement string", L_ESC); l -= ct_diff2sz(p + 1 - news); news = p + 1; } luaL_addlstring(b, news, l); } /* ** Add the replacement value to the string buffer 'b'. ** Return true if the original string was changed. (Function calls and ** table indexing resulting in nil or false do not change the subject.) */ static int add_value (MatchState *ms, luaL_Buffer *b, const char *s, const char *e, int tr) { lua_State *L = ms->L; switch (tr) { case LUA_TFUNCTION: { /* call the function */ int n; lua_pushvalue(L, 3); /* push the function */ n = push_captures(ms, s, e); /* all captures as arguments */ lua_call(L, n, 1); /* call it */ break; } case LUA_TTABLE: { /* index the table */ push_onecapture(ms, 0, s, e); /* first capture is the index */ lua_gettable(L, 3); break; } default: { /* LUA_TNUMBER or LUA_TSTRING */ add_s(ms, b, s, e); /* add value to the buffer */ return 1; /* something changed */ } } if (!lua_toboolean(L, -1)) { /* nil or false? */ lua_pop(L, 1); /* remove value */ luaL_addlstring(b, s, ct_diff2sz(e - s)); /* keep original text */ return 0; /* no changes */ } else if (l_unlikely(!lua_isstring(L, -1))) return luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); else { luaL_addvalue(b); /* add result to accumulator */ return 1; /* something changed */ } } static int str_gsub (lua_State *L) { size_t srcl, lp; const char *src = luaL_checklstring(L, 1, &srcl); /* subject */ const char *p = luaL_checklstring(L, 2, &lp); /* pattern */ const char *lastmatch = NULL; /* end of last match */ int tr = lua_type(L, 3); /* replacement type */ /* max replacements */ lua_Integer max_s = luaL_optinteger(L, 4, cast_st2S(srcl) + 1); int anchor = (*p == '^'); lua_Integer n = 0; /* replacement count */ int changed = 0; /* change flag */ MatchState ms; luaL_Buffer b; luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, "string/function/table"); luaL_buffinit(L, &b); if (anchor) { p++; lp--; /* skip anchor character */ } prepstate(&ms, L, src, srcl, p, lp); while (n < max_s) { const char *e; reprepstate(&ms); /* (re)prepare state for new match */ if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */ n++; changed = add_value(&ms, &b, src, e, tr) | changed; src = lastmatch = e; } else if (src < ms.src_end) /* otherwise, skip one character */ luaL_addchar(&b, *src++); else break; /* end of subject */ if (anchor) break; } if (!changed) /* no changes? */ lua_pushvalue(L, 1); /* return original string */ else { /* something changed */ luaL_addlstring(&b, src, ct_diff2sz(ms.src_end - src)); luaL_pushresult(&b); /* create and return new string */ } lua_pushinteger(L, n); /* number of substitutions */ return 2; } /* }====================================================== */ /* ** {====================================================== ** STRING FORMAT ** ======================================================= */ #if !defined(lua_number2strx) /* { */ /* ** Hexadecimal floating-point formatter */ #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char)) /* ** Number of bits that goes into the first digit. It can be any value ** between 1 and 4; the following definition tries to align the number ** to nibble boundaries by making what is left after that first digit a ** multiple of 4. */ #define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1) /* ** Add integer part of 'x' to buffer and return new 'x' */ static lua_Number adddigit (char *buff, unsigned n, lua_Number x) { lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */ int d = (int)dd; buff[n] = cast_char(d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */ return x - dd; /* return what is left */ } static int num2straux (char *buff, unsigned sz, lua_Number x) { /* if 'inf' or 'NaN', format it like '%g' */ if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL) return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x); else if (x == 0) { /* can be -0... */ /* create "0" or "-0" followed by exponent */ return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x); } else { int e; lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */ unsigned n = 0; /* character count */ if (m < 0) { /* is number negative? */ buff[n++] = '-'; /* add sign */ m = -m; /* make it positive */ } buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */ m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */ e -= L_NBFD; /* this digit goes before the radix point */ if (m > 0) { /* more digits? */ buff[n++] = lua_getlocaledecpoint(); /* add radix point */ do { /* add as many digits as needed */ m = adddigit(buff, n++, m * 16); } while (m > 0); } n += cast_uint(l_sprintf(buff + n, sz - n, "p%+d", e)); /* add exponent */ lua_assert(n < sz); return cast_int(n); } } static int lua_number2strx (lua_State *L, char *buff, unsigned sz, const char *fmt, lua_Number x) { int n = num2straux(buff, sz, x); if (fmt[SIZELENMOD] == 'A') { int i; for (i = 0; i < n; i++) buff[i] = cast_char(toupper(cast_uchar(buff[i]))); } else if (l_unlikely(fmt[SIZELENMOD] != 'a')) return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented"); return n; } #endif /* } */ /* ** Maximum size for items formatted with '%f'. This size is produced ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.', ** and '\0') + number of decimal digits to represent maxfloat (which ** is maximum exponent + 1). (99+3+1, adding some extra, 110) */ #define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP)) /* ** All formats except '%f' do not need that large limit. The other ** float formats use exponents, so that they fit in the 99 limit for ** significant digits; 's' for large strings and 'q' add items directly ** to the buffer; all integer formats also fit in the 99 limit. The ** worst case are floats: they may need 99 significant digits, plus ** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120. */ #define MAX_ITEM 120 /* valid flags in a format specification */ #if !defined(L_FMTFLAGSF) /* valid flags for a, A, e, E, f, F, g, and G conversions */ #define L_FMTFLAGSF "-+#0 " /* valid flags for o, x, and X conversions */ #define L_FMTFLAGSX "-#0" /* valid flags for d and i conversions */ #define L_FMTFLAGSI "-+0 " /* valid flags for u conversions */ #define L_FMTFLAGSU "-0" /* valid flags for c, p, and s conversions */ #define L_FMTFLAGSC "-" #endif /* ** Maximum size of each format specification (such as "%-099.99d"): ** Initial '%', flags (up to 5), width (2), period, precision (2), ** length modifier (8), conversion specifier, and final '\0', plus some ** extra. */ #define MAX_FORMAT 32 static void addquoted (luaL_Buffer *b, const char *s, size_t len) { luaL_addchar(b, '"'); while (len--) { if (*s == '"' || *s == '\\' || *s == '\n') { luaL_addchar(b, '\\'); luaL_addchar(b, *s); } else if (iscntrl(cast_uchar(*s))) { char buff[10]; if (!isdigit(cast_uchar(*(s+1)))) l_sprintf(buff, sizeof(buff), "\\%d", (int)cast_uchar(*s)); else l_sprintf(buff, sizeof(buff), "\\%03d", (int)cast_uchar(*s)); luaL_addstring(b, buff); } else luaL_addchar(b, *s); s++; } luaL_addchar(b, '"'); } /* ** Serialize a floating-point number in such a way that it can be ** scanned back by Lua. Use hexadecimal format for "common" numbers ** (to preserve precision); inf, -inf, and NaN are handled separately. ** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.) */ static int quotefloat (lua_State *L, char *buff, lua_Number n) { const char *s; /* for the fixed representations */ if (n == (lua_Number)HUGE_VAL) /* inf? */ s = "1e9999"; else if (n == -(lua_Number)HUGE_VAL) /* -inf? */ s = "-1e9999"; else if (n != n) /* NaN? */ s = "(0/0)"; else { /* format number as hexadecimal */ int nb = lua_number2strx(L, buff, MAX_ITEM, "%" LUA_NUMBER_FRMLEN "a", n); /* ensures that 'buff' string uses a dot as the radix character */ if (memchr(buff, '.', cast_uint(nb)) == NULL) { /* no dot? */ char point = lua_getlocaledecpoint(); /* try locale point */ char *ppoint = (char *)memchr(buff, point, cast_uint(nb)); if (ppoint) *ppoint = '.'; /* change it to a dot */ } return nb; } /* for the fixed representations */ return l_sprintf(buff, MAX_ITEM, "%s", s); } static void addliteral (lua_State *L, luaL_Buffer *b, int arg) { switch (lua_type(L, arg)) { case LUA_TSTRING: { size_t len; const char *s = lua_tolstring(L, arg, &len); addquoted(b, s, len); break; } case LUA_TNUMBER: { char *buff = luaL_prepbuffsize(b, MAX_ITEM); int nb; if (!lua_isinteger(L, arg)) /* float? */ nb = quotefloat(L, buff, lua_tonumber(L, arg)); else { /* integers */ lua_Integer n = lua_tointeger(L, arg); const char *format = (n == LUA_MININTEGER) /* corner case? */ ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */ : LUA_INTEGER_FMT; /* else use default format */ nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n); } luaL_addsize(b, cast_uint(nb)); break; } case LUA_TNIL: case LUA_TBOOLEAN: { luaL_tolstring(L, arg, NULL); luaL_addvalue(b); break; } default: { luaL_argerror(L, arg, "value has no literal form"); } } } static const char *get2digits (const char *s) { if (isdigit(cast_uchar(*s))) { s++; if (isdigit(cast_uchar(*s))) s++; /* (2 digits at most) */ } return s; } /* ** Check whether a conversion specification is valid. When called, ** first character in 'form' must be '%' and last character must ** be a valid conversion specifier. 'flags' are the accepted flags; ** 'precision' signals whether to accept a precision. */ static void checkformat (lua_State *L, const char *form, const char *flags, int precision) { const char *spec = form + 1; /* skip '%' */ spec += strspn(spec, flags); /* skip flags */ if (*spec != '0') { /* a width cannot start with '0' */ spec = get2digits(spec); /* skip width */ if (*spec == '.' && precision) { spec++; spec = get2digits(spec); /* skip precision */ } } if (!isalpha(cast_uchar(*spec))) /* did not go to the end? */ luaL_error(L, "invalid conversion specification: '%s'", form); } /* ** Get a conversion specification and copy it to 'form'. ** Return the address of its last character. */ static const char *getformat (lua_State *L, const char *strfrmt, char *form) { /* spans flags, width, and precision ('0' is included as a flag) */ size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789."); len++; /* adds following character (should be the specifier) */ /* still needs space for '%', '\0', plus a length modifier */ if (len >= MAX_FORMAT - 10) luaL_error(L, "invalid format (too long)"); *(form++) = '%'; memcpy(form, strfrmt, len * sizeof(char)); *(form + len) = '\0'; return strfrmt + len - 1; } /* ** add length modifier into formats */ static void addlenmod (char *form, const char *lenmod) { size_t l = strlen(form); size_t lm = strlen(lenmod); char spec = form[l - 1]; strcpy(form + l - 1, lenmod); form[l + lm - 1] = spec; form[l + lm] = '\0'; } static int str_format (lua_State *L) { int top = lua_gettop(L); int arg = 1; size_t sfl; const char *strfrmt = luaL_checklstring(L, arg, &sfl); const char *strfrmt_end = strfrmt+sfl; const char *flags; luaL_Buffer b; luaL_buffinit(L, &b); while (strfrmt < strfrmt_end) { if (*strfrmt != L_ESC) luaL_addchar(&b, *strfrmt++); else if (*++strfrmt == L_ESC) luaL_addchar(&b, *strfrmt++); /* %% */ else { /* format item */ char form[MAX_FORMAT]; /* to store the format ('%...') */ unsigned maxitem = MAX_ITEM; /* maximum length for the result */ char *buff = luaL_prepbuffsize(&b, maxitem); /* to put result */ int nb = 0; /* number of bytes in result */ if (++arg > top) return luaL_argerror(L, arg, "no value"); strfrmt = getformat(L, strfrmt, form); switch (*strfrmt++) { case 'c': { checkformat(L, form, L_FMTFLAGSC, 0); nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg)); break; } case 'd': case 'i': flags = L_FMTFLAGSI; goto intcase; case 'u': flags = L_FMTFLAGSU; goto intcase; case 'o': case 'x': case 'X': flags = L_FMTFLAGSX; intcase: { lua_Integer n = luaL_checkinteger(L, arg); checkformat(L, form, flags, 1); addlenmod(form, LUA_INTEGER_FRMLEN); nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n); break; } case 'a': case 'A': checkformat(L, form, L_FMTFLAGSF, 1); addlenmod(form, LUA_NUMBER_FRMLEN); nb = lua_number2strx(L, buff, maxitem, form, luaL_checknumber(L, arg)); break; case 'f': maxitem = MAX_ITEMF; /* extra space for '%f' */ buff = luaL_prepbuffsize(&b, maxitem); /* FALLTHROUGH */ case 'e': case 'E': case 'g': case 'G': { lua_Number n = luaL_checknumber(L, arg); checkformat(L, form, L_FMTFLAGSF, 1); addlenmod(form, LUA_NUMBER_FRMLEN); nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n); break; } case 'p': { const void *p = lua_topointer(L, arg); checkformat(L, form, L_FMTFLAGSC, 0); if (p == NULL) { /* avoid calling 'printf' with argument NULL */ p = "(null)"; /* result */ form[strlen(form) - 1] = 's'; /* format it as a string */ } nb = l_sprintf(buff, maxitem, form, p); break; } case 'q': { if (form[2] != '\0') /* modifiers? */ return luaL_error(L, "specifier '%%q' cannot have modifiers"); addliteral(L, &b, arg); break; } case 's': { size_t l; const char *s = luaL_tolstring(L, arg, &l); if (form[2] == '\0') /* no modifiers? */ luaL_addvalue(&b); /* keep entire string */ else { luaL_argcheck(L, l == strlen(s), arg, "string contains zeros"); checkformat(L, form, L_FMTFLAGSC, 1); if (strchr(form, '.') == NULL && l >= 100) { /* no precision and string is too long to be formatted */ luaL_addvalue(&b); /* keep entire string */ } else { /* format the string into 'buff' */ nb = l_sprintf(buff, maxitem, form, s); lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ } } break; } default: { /* also treat cases 'pnLlh' */ return luaL_error(L, "invalid conversion '%s' to 'format'", form); } } lua_assert(cast_uint(nb) < maxitem); luaL_addsize(&b, cast_uint(nb)); } } luaL_pushresult(&b); return 1; } /* }====================================================== */ /* ** {====================================================== ** PACK/UNPACK ** ======================================================= */ /* value used for padding */ #if !defined(LUAL_PACKPADBYTE) #define LUAL_PACKPADBYTE 0x00 #endif /* maximum size for the binary representation of an integer */ #define MAXINTSIZE 16 /* number of bits in a character */ #define NB CHAR_BIT /* mask for one character (NB 1's) */ #define MC ((1 << NB) - 1) /* size of a lua_Integer */ #define SZINT ((int)sizeof(lua_Integer)) /* dummy union to get native endianness */ static const union { int dummy; char little; /* true iff machine is little endian */ } nativeendian = {1}; /* ** information to pack/unpack stuff */ typedef struct Header { lua_State *L; int islittle; unsigned maxalign; } Header; /* ** options for pack/unpack */ typedef enum KOption { Kint, /* signed integers */ Kuint, /* unsigned integers */ Kfloat, /* single-precision floating-point numbers */ Knumber, /* Lua "native" floating-point numbers */ Kdouble, /* double-precision floating-point numbers */ Kchar, /* fixed-length strings */ Kstring, /* strings with prefixed length */ Kzstr, /* zero-terminated strings */ Kpadding, /* padding */ Kpaddalign, /* padding for alignment */ Knop /* no-op (configuration or spaces) */ } KOption; /* ** Read an integer numeral from string 'fmt' or return 'df' if ** there is no numeral */ static int digit (int c) { return '0' <= c && c <= '9'; } static size_t getnum (const char **fmt, size_t df) { if (!digit(**fmt)) /* no number? */ return df; /* return default value */ else { size_t a = 0; do { a = a*10 + cast_uint(*((*fmt)++) - '0'); } while (digit(**fmt) && a <= (MAX_SIZE - 9)/10); return a; } } /* ** Read an integer numeral and raises an error if it is larger ** than the maximum size of integers. */ static unsigned getnumlimit (Header *h, const char **fmt, size_t df) { size_t sz = getnum(fmt, df); if (l_unlikely((sz - 1u) >= MAXINTSIZE)) return cast_uint(luaL_error(h->L, "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE)); return cast_uint(sz); } /* ** Initialize Header */ static void initheader (lua_State *L, Header *h) { h->L = L; h->islittle = nativeendian.little; h->maxalign = 1; } /* ** Read and classify next option. 'size' is filled with option's size. */ static KOption getoption (Header *h, const char **fmt, size_t *size) { /* dummy structure to get native alignment requirements */ struct cD { char c; union { LUAI_MAXALIGN; } u; }; int opt = *((*fmt)++); *size = 0; /* default */ switch (opt) { case 'b': *size = sizeof(char); return Kint; case 'B': *size = sizeof(char); return Kuint; case 'h': *size = sizeof(short); return Kint; case 'H': *size = sizeof(short); return Kuint; case 'l': *size = sizeof(long); return Kint; case 'L': *size = sizeof(long); return Kuint; case 'j': *size = sizeof(lua_Integer); return Kint; case 'J': *size = sizeof(lua_Integer); return Kuint; case 'T': *size = sizeof(size_t); return Kuint; case 'f': *size = sizeof(float); return Kfloat; case 'n': *size = sizeof(lua_Number); return Knumber; case 'd': *size = sizeof(double); return Kdouble; case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; case 'c': *size = getnum(fmt, cast_sizet(-1)); if (l_unlikely(*size == cast_sizet(-1))) luaL_error(h->L, "missing size for format option 'c'"); return Kchar; case 'z': return Kzstr; case 'x': *size = 1; return Kpadding; case 'X': return Kpaddalign; case ' ': break; case '<': h->islittle = 1; break; case '>': h->islittle = 0; break; case '=': h->islittle = nativeendian.little; break; case '!': { const size_t maxalign = offsetof(struct cD, u); h->maxalign = getnumlimit(h, fmt, maxalign); break; } default: luaL_error(h->L, "invalid format option '%c'", opt); } return Knop; } /* ** Read, classify, and fill other details about the next option. ** 'psize' is filled with option's size, 'notoalign' with its ** alignment requirements. ** Local variable 'size' gets the size to be aligned. (Kpadal option ** always gets its full alignment, other options are limited by ** the maximum alignment ('maxalign'). Kchar option needs no alignment ** despite its size. */ static KOption getdetails (Header *h, size_t totalsize, const char **fmt, size_t *psize, unsigned *ntoalign) { KOption opt = getoption(h, fmt, psize); size_t align = *psize; /* usually, alignment follows size */ if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) luaL_argerror(h->L, 1, "invalid next option for option 'X'"); } if (align <= 1 || opt == Kchar) /* need no alignment? */ *ntoalign = 0; else { if (align > h->maxalign) /* enforce maximum alignment */ align = h->maxalign; if (l_unlikely(!ispow2(align))) { /* not a power of 2? */ *ntoalign = 0; /* to avoid warnings */ luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); } else { /* 'szmoda' = totalsize % align */ unsigned szmoda = cast_uint(totalsize & (align - 1)); *ntoalign = cast_uint((align - szmoda) & (align - 1)); } } return opt; } /* ** Pack integer 'n' with 'size' bytes and 'islittle' endianness. ** The final 'if' handles the case when 'size' is larger than ** the size of a Lua integer, correcting the extra sign-extension ** bytes if necessary (by default they would be zeros). */ static void packint (luaL_Buffer *b, lua_Unsigned n, int islittle, unsigned size, int neg) { char *buff = luaL_prepbuffsize(b, size); unsigned i; buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ for (i = 1; i < size; i++) { n >>= NB; buff[islittle ? i : size - 1 - i] = (char)(n & MC); } if (neg && size > SZINT) { /* negative number need sign extension? */ for (i = SZINT; i < size; i++) /* correct extra bytes */ buff[islittle ? i : size - 1 - i] = (char)MC; } luaL_addsize(b, size); /* add result to buffer */ } /* ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if ** given 'islittle' is different from native endianness. */ static void copywithendian (char *dest, const char *src, unsigned size, int islittle) { if (islittle == nativeendian.little) memcpy(dest, src, size); else { dest += size - 1; while (size-- != 0) *(dest--) = *(src++); } } static int str_pack (lua_State *L) { luaL_Buffer b; Header h; const char *fmt = luaL_checkstring(L, 1); /* format string */ int arg = 1; /* current argument to pack */ size_t totalsize = 0; /* accumulate total size of result */ initheader(L, &h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { unsigned ntoalign; size_t size; KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); luaL_argcheck(L, size + ntoalign <= MAX_SIZE - totalsize, arg, "result too long"); totalsize += ntoalign + size; while (ntoalign-- > 0) luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */ arg++; switch (opt) { case Kint: { /* signed integers */ lua_Integer n = luaL_checkinteger(L, arg); if (size < SZINT) { /* need overflow check? */ lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); } packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), (n < 0)); break; } case Kuint: { /* unsigned integers */ lua_Integer n = luaL_checkinteger(L, arg); if (size < SZINT) /* need overflow check? */ luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), arg, "unsigned overflow"); packint(&b, (lua_Unsigned)n, h.islittle, cast_uint(size), 0); break; } case Kfloat: { /* C float */ float f = (float)luaL_checknumber(L, arg); /* get argument */ char *buff = luaL_prepbuffsize(&b, sizeof(f)); /* move 'f' to final result, correcting endianness if needed */ copywithendian(buff, (char *)&f, sizeof(f), h.islittle); luaL_addsize(&b, size); break; } case Knumber: { /* Lua float */ lua_Number f = luaL_checknumber(L, arg); /* get argument */ char *buff = luaL_prepbuffsize(&b, sizeof(f)); /* move 'f' to final result, correcting endianness if needed */ copywithendian(buff, (char *)&f, sizeof(f), h.islittle); luaL_addsize(&b, size); break; } case Kdouble: { /* C double */ double f = (double)luaL_checknumber(L, arg); /* get argument */ char *buff = luaL_prepbuffsize(&b, sizeof(f)); /* move 'f' to final result, correcting endianness if needed */ copywithendian(buff, (char *)&f, sizeof(f), h.islittle); luaL_addsize(&b, size); break; } case Kchar: { /* fixed-size string */ size_t len; const char *s = luaL_checklstring(L, arg, &len); luaL_argcheck(L, len <= size, arg, "string longer than given size"); luaL_addlstring(&b, s, len); /* add string */ if (len < size) { /* does it need padding? */ size_t psize = size - len; /* pad size */ char *buff = luaL_prepbuffsize(&b, psize); memset(buff, LUAL_PACKPADBYTE, psize); luaL_addsize(&b, psize); } break; } case Kstring: { /* strings with length count */ size_t len; const char *s = luaL_checklstring(L, arg, &len); luaL_argcheck(L, size >= sizeof(lua_Unsigned) || len < ((lua_Unsigned)1 << (size * NB)), arg, "string length does not fit in given size"); /* pack length */ packint(&b, (lua_Unsigned)len, h.islittle, cast_uint(size), 0); luaL_addlstring(&b, s, len); totalsize += len; break; } case Kzstr: { /* zero-terminated string */ size_t len; const char *s = luaL_checklstring(L, arg, &len); luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); luaL_addlstring(&b, s, len); luaL_addchar(&b, '\0'); /* add zero at the end */ totalsize += len + 1; break; } case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */ case Kpaddalign: case Knop: arg--; /* undo increment */ break; } } luaL_pushresult(&b); return 1; } static int str_packsize (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); /* format string */ size_t totalsize = 0; /* accumulate total size of result */ initheader(L, &h); while (*fmt != '\0') { unsigned ntoalign; size_t size; KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1, "variable-length format"); size += ntoalign; /* total space used by option */ luaL_argcheck(L, totalsize <= LUA_MAXINTEGER - size, 1, "format result too large"); totalsize += size; } lua_pushinteger(L, cast_st2S(totalsize)); return 1; } /* ** Unpack an integer with 'size' bytes and 'islittle' endianness. ** If size is smaller than the size of a Lua integer and integer ** is signed, must do sign extension (propagating the sign to the ** higher bits); if size is larger than the size of a Lua integer, ** it must check the unread bytes to see whether they do not cause an ** overflow. */ static lua_Integer unpackint (lua_State *L, const char *str, int islittle, int size, int issigned) { lua_Unsigned res = 0; int i; int limit = (size <= SZINT) ? size : SZINT; for (i = limit - 1; i >= 0; i--) { res <<= NB; res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; } if (size < SZINT) { /* real size smaller than lua_Integer? */ if (issigned) { /* needs sign extension? */ lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); res = ((res ^ mask) - mask); /* do sign extension */ } } else if (size > SZINT) { /* must check unread bytes */ int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; for (i = limit; i < size; i++) { if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask)) luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); } } return (lua_Integer)res; } static int str_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1; int n = 0; /* number of results */ luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); initheader(L, &h); while (*fmt != '\0') { unsigned ntoalign; size_t size; KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); luaL_argcheck(L, ntoalign + size <= ld - pos, 2, "data string too short"); pos += ntoalign; /* skip alignment */ /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); n++; switch (opt) { case Kint: case Kuint: { lua_Integer res = unpackint(L, data + pos, h.islittle, cast_int(size), (opt == Kint)); lua_pushinteger(L, res); break; } case Kfloat: { float f; copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); lua_pushnumber(L, (lua_Number)f); break; } case Knumber: { lua_Number f; copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); lua_pushnumber(L, f); break; } case Kdouble: { double f; copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); lua_pushnumber(L, (lua_Number)f); break; } case Kchar: { lua_pushlstring(L, data + pos, size); break; } case Kstring: { lua_Unsigned len = (lua_Unsigned)unpackint(L, data + pos, h.islittle, cast_int(size), 0); luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short"); lua_pushlstring(L, data + pos + size, cast_sizet(len)); pos += cast_sizet(len); /* skip string */ break; } case Kzstr: { size_t len = strlen(data + pos); luaL_argcheck(L, pos + len < ld, 2, "unfinished string for format 'z'"); lua_pushlstring(L, data + pos, len); pos += len + 1; /* skip string plus final '\0' */ break; } case Kpaddalign: case Kpadding: case Knop: n--; /* undo increment */ break; } pos += size; } lua_pushinteger(L, cast_st2S(pos) + 1); /* next position */ return n + 1; } /* }====================================================== */ static const luaL_Reg strlib[] = { {"byte", str_byte}, {"char", str_char}, {"dump", str_dump}, {"find", str_find}, {"format", str_format}, {"gmatch", gmatch}, {"gsub", str_gsub}, {"len", str_len}, {"lower", str_lower}, {"match", str_match}, {"rep", str_rep}, {"reverse", str_reverse}, {"sub", str_sub}, {"upper", str_upper}, {"pack", str_pack}, {"packsize", str_packsize}, {"unpack", str_unpack}, {NULL, NULL} }; static void createmetatable (lua_State *L) { /* table to be metatable for strings */ luaL_newlibtable(L, stringmetamethods); luaL_setfuncs(L, stringmetamethods, 0); lua_pushliteral(L, ""); /* dummy string */ lua_pushvalue(L, -2); /* copy table */ lua_setmetatable(L, -2); /* set table as metatable for strings */ lua_pop(L, 1); /* pop dummy string */ lua_pushvalue(L, -2); /* get string library */ lua_setfield(L, -2, "__index"); /* metatable.__index = string */ lua_pop(L, 1); /* pop metatable */ } /* ** Open string library */ LUAMOD_API int luaopen_string (lua_State *L) { luaL_newlib(L, strlib); createmetatable(L); return 1; } /* ** $Id: ltablib.c $ ** Library for Table Manipulation ** See Copyright Notice in lua.h */ #define ltablib_c #define LUA_LIB #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** Operations that an object must define to mimic a table ** (some functions only need some of them) */ #define TAB_R 1 /* read */ #define TAB_W 2 /* write */ #define TAB_L 4 /* length */ #define TAB_RW (TAB_R | TAB_W) /* read/write */ #define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n)) static int checkfield (lua_State *L, const char *key, int n) { lua_pushstring(L, key); return (lua_rawget(L, -n) != LUA_TNIL); } /* ** Check that 'arg' either is a table or can behave like one (that is, ** has a metatable with the required metamethods) */ static void checktab (lua_State *L, int arg, int what) { if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */ int n = 1; /* number of elements to pop */ if (lua_getmetatable(L, arg) && /* must have metatable */ (!(what & TAB_R) || checkfield(L, "__index", ++n)) && (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) && (!(what & TAB_L) || checkfield(L, "__len", ++n))) { lua_pop(L, n); /* pop metatable and tested metamethods */ } else luaL_checktype(L, arg, LUA_TTABLE); /* force an error */ } } static int tcreate (lua_State *L) { lua_Unsigned sizeseq = (lua_Unsigned)luaL_checkinteger(L, 1); lua_Unsigned sizerest = (lua_Unsigned)luaL_optinteger(L, 2, 0); luaL_argcheck(L, sizeseq <= cast_uint(INT_MAX), 1, "out of range"); luaL_argcheck(L, sizerest <= cast_uint(INT_MAX), 2, "out of range"); lua_createtable(L, cast_int(sizeseq), cast_int(sizerest)); return 1; } static int tinsert (lua_State *L) { lua_Integer pos; /* where to insert new element */ lua_Integer e = aux_getn(L, 1, TAB_RW); e = luaL_intop(+, e, 1); /* first empty element */ switch (lua_gettop(L)) { case 2: { /* called with only 2 arguments */ pos = e; /* insert new element at the end */ break; } case 3: { lua_Integer i; pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ /* check whether 'pos' is in [1, e] */ luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2, "position out of bounds"); for (i = e; i > pos; i--) { /* move up elements */ lua_geti(L, 1, i - 1); lua_seti(L, 1, i); /* t[i] = t[i - 1] */ } break; } default: { return luaL_error(L, "wrong number of arguments to 'insert'"); } } lua_seti(L, 1, pos); /* t[pos] = v */ return 0; } static int tremove (lua_State *L) { lua_Integer size = aux_getn(L, 1, TAB_RW); lua_Integer pos = luaL_optinteger(L, 2, size); if (pos != size) /* validate 'pos' if given */ /* check whether 'pos' is in [1, size + 1] */ luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2, "position out of bounds"); lua_geti(L, 1, pos); /* result = t[pos] */ for ( ; pos < size; pos++) { lua_geti(L, 1, pos + 1); lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */ } lua_pushnil(L); lua_seti(L, 1, pos); /* remove entry t[pos] */ return 1; } /* ** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever ** possible, copy in increasing order, which is better for rehashing. ** "possible" means destination after original range, or smaller ** than origin, or copying to another table. */ static int tmove (lua_State *L) { lua_Integer f = luaL_checkinteger(L, 2); lua_Integer e = luaL_checkinteger(L, 3); lua_Integer t = luaL_checkinteger(L, 4); int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */ checktab(L, 1, TAB_R); checktab(L, tt, TAB_W); if (e >= f) { /* otherwise, nothing to move */ lua_Integer n, i; luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, "too many elements to move"); n = e - f + 1; /* number of elements to move */ luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, "destination wrap around"); if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) { for (i = 0; i < n; i++) { lua_geti(L, 1, f + i); lua_seti(L, tt, t + i); } } else { for (i = n - 1; i >= 0; i--) { lua_geti(L, 1, f + i); lua_seti(L, tt, t + i); } } } lua_pushvalue(L, tt); /* return destination table */ return 1; } static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) { lua_geti(L, 1, i); if (l_unlikely(!lua_isstring(L, -1))) luaL_error(L, "invalid value (%s) at index %I in table for 'concat'", luaL_typename(L, -1), (LUAI_UACINT)i); luaL_addvalue(b); } static int tconcat (lua_State *L) { luaL_Buffer b; lua_Integer last = aux_getn(L, 1, TAB_R); size_t lsep; const char *sep = luaL_optlstring(L, 2, "", &lsep); lua_Integer i = luaL_optinteger(L, 3, 1); last = luaL_optinteger(L, 4, last); luaL_buffinit(L, &b); for (; i < last; i++) { addfield(L, &b, i); luaL_addlstring(&b, sep, lsep); } if (i == last) /* add last value (if interval was not empty) */ addfield(L, &b, i); luaL_pushresult(&b); return 1; } /* ** {====================================================== ** Pack/unpack ** ======================================================= */ static int tpack (lua_State *L) { int i; int n = lua_gettop(L); /* number of elements to pack */ lua_createtable(L, n, 1); /* create result table */ lua_insert(L, 1); /* put it at index 1 */ for (i = n; i >= 1; i--) /* assign elements */ lua_seti(L, 1, i); lua_pushinteger(L, n); lua_setfield(L, 1, "n"); /* t.n = number of elements */ return 1; /* return table */ } static int tunpack (lua_State *L) { lua_Unsigned n; lua_Integer i = luaL_optinteger(L, 2, 1); lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1)); if (i > e) return 0; /* empty range */ n = l_castS2U(e) - l_castS2U(i); /* number of elements minus 1 */ if (l_unlikely(n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n)))) return luaL_error(L, "too many results to unpack"); for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */ lua_geti(L, 1, i); } lua_geti(L, 1, e); /* push last element */ return (int)n; } /* }====================================================== */ /* ** {====================================================== ** Quicksort ** (based on 'Algorithms in MODULA-3', Robert Sedgewick; ** Addison-Wesley, 1993.) ** ======================================================= */ /* ** Type for array indices. These indices are always limited by INT_MAX, ** so it is safe to cast them to lua_Integer even for Lua 32 bits. */ typedef unsigned int IdxT; /* Versions of lua_seti/lua_geti specialized for IdxT */ #define geti(L,idt,idx) lua_geti(L, idt, l_castU2S(idx)) #define seti(L,idt,idx) lua_seti(L, idt, l_castU2S(idx)) /* ** Produce a "random" 'unsigned int' to randomize pivot choice. This ** macro is used only when 'sort' detects a big imbalance in the result ** of a partition. (If you don't want/need this "randomness", ~0 is a ** good choice.) */ #if !defined(l_randomizePivot) #define l_randomizePivot(L) luaL_makeseed(L) #endif /* } */ /* arrays larger than 'RANLIMIT' may use randomized pivots */ #define RANLIMIT 100u static void set2 (lua_State *L, IdxT i, IdxT j) { seti(L, 1, i); seti(L, 1, j); } /* ** Return true iff value at stack index 'a' is less than the value at ** index 'b' (according to the order of the sort). */ static int sort_comp (lua_State *L, int a, int b) { if (lua_isnil(L, 2)) /* no function? */ return lua_compare(L, a, b, LUA_OPLT); /* a < b */ else { /* function */ int res; lua_pushvalue(L, 2); /* push function */ lua_pushvalue(L, a-1); /* -1 to compensate function */ lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ lua_call(L, 2, 1); /* call function */ res = lua_toboolean(L, -1); /* get result */ lua_pop(L, 1); /* pop result */ return res; } } /* ** Does the partition: Pivot P is at the top of the stack. ** precondition: a[lo] <= P == a[up-1] <= a[up], ** so it only needs to do the partition from lo + 1 to up - 2. ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up] ** returns 'i'. */ static IdxT partition (lua_State *L, IdxT lo, IdxT up) { IdxT i = lo; /* will be incremented before first use */ IdxT j = up - 1; /* will be decremented before first use */ /* loop invariant: a[lo .. i] <= P <= a[j .. up] */ for (;;) { /* next loop: repeat ++i while a[i] < P */ while ((void)geti(L, 1, ++i), sort_comp(L, -1, -2)) { if (l_unlikely(i == up - 1)) /* a[up - 1] < P == a[up - 1] */ luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[i] */ } /* after the loop, a[i] >= P and a[lo .. i - 1] < P (a) */ /* next loop: repeat --j while P < a[j] */ while ((void)geti(L, 1, --j), sort_comp(L, -3, -1)) { if (l_unlikely(j < i)) /* j <= i - 1 and a[j] > P, contradicts (a) */ luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[j] */ } /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ if (j < i) { /* no elements out of place? */ /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */ lua_pop(L, 1); /* pop a[j] */ /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */ set2(L, up - 1, i); return i; } /* otherwise, swap a[i] - a[j] to restore invariant and repeat */ set2(L, i, j); } } /* ** Choose an element in the middle (2nd-3th quarters) of [lo,up] ** "randomized" by 'rnd' */ static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) { IdxT r4 = (up - lo) / 4; /* range/4 */ IdxT p = (rnd ^ lo ^ up) % (r4 * 2) + (lo + r4); lua_assert(lo + r4 <= p && p <= up - r4); return p; } /* ** Quicksort algorithm (recursive function) */ static void auxsort (lua_State *L, IdxT lo, IdxT up, unsigned rnd) { while (lo < up) { /* loop for tail recursion */ IdxT p; /* Pivot index */ IdxT n; /* to be used later */ /* sort elements 'lo', 'p', and 'up' */ geti(L, 1, lo); geti(L, 1, up); if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */ set2(L, lo, up); /* swap a[lo] - a[up] */ else lua_pop(L, 2); /* remove both values */ if (up - lo == 1) /* only 2 elements? */ return; /* already sorted */ if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */ p = (lo + up)/2; /* middle element is a good pivot */ else /* for larger intervals, it is worth a random pivot */ p = choosePivot(lo, up, rnd); geti(L, 1, p); geti(L, 1, lo); if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */ set2(L, p, lo); /* swap a[p] - a[lo] */ else { lua_pop(L, 1); /* remove a[lo] */ geti(L, 1, up); if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */ set2(L, p, up); /* swap a[up] - a[p] */ else lua_pop(L, 2); } if (up - lo == 2) /* only 3 elements? */ return; /* already sorted */ geti(L, 1, p); /* get middle element (Pivot) */ lua_pushvalue(L, -1); /* push Pivot */ geti(L, 1, up - 1); /* push a[up - 1] */ set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */ p = partition(L, lo, up); /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */ if (p - lo < up - p) { /* lower interval is smaller? */ auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */ n = p - lo; /* size of smaller interval */ lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */ } else { auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */ n = up - p; /* size of smaller interval */ up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */ } if ((up - lo) / 128 > n) /* partition too imbalanced? */ rnd = l_randomizePivot(L); /* try a new randomization */ } /* tail call auxsort(L, lo, up, rnd) */ } static int sort (lua_State *L) { lua_Integer n = aux_getn(L, 1, TAB_RW); if (n > 1) { /* non-trivial interval? */ luaL_argcheck(L, n < INT_MAX, 1, "array too big"); if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */ lua_settop(L, 2); /* make sure there are two arguments */ auxsort(L, 1, (IdxT)n, 0); } return 0; } /* }====================================================== */ static const luaL_Reg tab_funcs[] = { {"concat", tconcat}, {"create", tcreate}, {"insert", tinsert}, {"pack", tpack}, {"unpack", tunpack}, {"remove", tremove}, {"move", tmove}, {"sort", sort}, {NULL, NULL} }; LUAMOD_API int luaopen_table (lua_State *L) { luaL_newlib(L, tab_funcs); return 1; } /* ** $Id: ltm.c $ ** Tag methods ** See Copyright Notice in lua.h */ #define ltm_c #define LUA_CORE #include #include "lua.h" static const char udatatypename[] = "userdata"; LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = { "no value", "nil", "boolean", udatatypename, "number", "string", "table", "function", udatatypename, "thread", "upvalue", "proto" /* these last cases are used for tests only */ }; void luaT_init (lua_State *L) { static const char *const luaT_eventname[] = { /* ORDER TM */ "__index", "__newindex", "__gc", "__mode", "__len", "__eq", "__add", "__sub", "__mul", "__mod", "__pow", "__div", "__idiv", "__band", "__bor", "__bxor", "__shl", "__shr", "__unm", "__bnot", "__lt", "__le", "__concat", "__call", "__close" }; int i; for (i=0; itmname[i] = luaS_new(L, luaT_eventname[i]); luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */ } } /* ** function to be used with macro "fasttm": optimized for absence of ** tag methods */ const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { const TValue *tm = luaH_Hgetshortstr(events, ename); lua_assert(event <= TM_EQ); if (notm(tm)) { /* no tag method? */ events->flags |= cast_byte(1u<metatable; break; case LUA_TUSERDATA: mt = uvalue(o)->metatable; break; default: mt = G(L)->mt[ttype(o)]; } return (mt ? luaH_Hgetshortstr(mt, G(L)->tmname[event]) : &G(L)->nilvalue); } /* ** Return the name of the type of an object. For tables and userdata ** with metatable, use their '__name' metafield, if present. */ const char *luaT_objtypename (lua_State *L, const TValue *o) { Table *mt; if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) || (ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) { const TValue *name = luaH_Hgetshortstr(mt, luaS_new(L, "__name")); if (ttisstring(name)) /* is '__name' a string? */ return getstr(tsvalue(name)); /* use it as type name */ } return ttypename(ttype(o)); /* else use standard type name */ } void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, const TValue *p3) { StkId func = L->top.p; setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ setobj2s(L, func + 1, p1); /* 1st argument */ setobj2s(L, func + 2, p2); /* 2nd argument */ setobj2s(L, func + 3, p3); /* 3rd argument */ L->top.p = func + 4; /* metamethod may yield only when called from Lua code */ if (isLuacode(L->ci)) luaD_call(L, func, 0); else luaD_callnoyield(L, func, 0); } lu_byte luaT_callTMres (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, StkId res) { ptrdiff_t result = savestack(L, res); StkId func = L->top.p; setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */ setobj2s(L, func + 1, p1); /* 1st argument */ setobj2s(L, func + 2, p2); /* 2nd argument */ L->top.p += 3; /* metamethod may yield only when called from Lua code */ if (isLuacode(L->ci)) luaD_call(L, func, 1); else luaD_callnoyield(L, func, 1); res = restorestack(L, result); setobjs2s(L, res, --L->top.p); /* move result to its place */ return ttypetag(s2v(res)); /* return tag of the result */ } static int callbinTM (lua_State *L, const TValue *p1, const TValue *p2, StkId res, TMS event) { const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ if (notm(tm)) tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ if (notm(tm)) return -1; /* tag method not found */ else /* call tag method and return the tag of the result */ return luaT_callTMres(L, tm, p1, p2, res); } void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, StkId res, TMS event) { if (l_unlikely(callbinTM(L, p1, p2, res, event) < 0)) { switch (event) { case TM_BAND: case TM_BOR: case TM_BXOR: case TM_SHL: case TM_SHR: case TM_BNOT: { if (ttisnumber(p1) && ttisnumber(p2)) luaG_tointerror(L, p1, p2); else luaG_opinterror(L, p1, p2, "perform bitwise operation on"); } /* calls never return, but to avoid warnings: *//* FALLTHROUGH */ default: luaG_opinterror(L, p1, p2, "perform arithmetic on"); } } } /* ** The use of 'p1' after 'callbinTM' is safe because, when a tag ** method is not found, 'callbinTM' cannot change the stack. */ void luaT_tryconcatTM (lua_State *L) { StkId p1 = L->top.p - 2; /* first argument */ if (l_unlikely(callbinTM(L, s2v(p1), s2v(p1 + 1), p1, TM_CONCAT) < 0)) luaG_concaterror(L, s2v(p1), s2v(p1 + 1)); } void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2, int flip, StkId res, TMS event) { if (flip) luaT_trybinTM(L, p2, p1, res, event); else luaT_trybinTM(L, p1, p2, res, event); } void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2, int flip, StkId res, TMS event) { TValue aux; setivalue(&aux, i2); luaT_trybinassocTM(L, p1, &aux, flip, res, event); } /* ** Calls an order tag method. */ int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2, TMS event) { int tag = callbinTM(L, p1, p2, L->top.p, event); /* try original event */ if (tag >= 0) /* found tag method? */ return !tagisfalse(tag); luaG_ordererror(L, p1, p2); /* no metamethod found */ return 0; /* to avoid warnings */ } int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2, int flip, int isfloat, TMS event) { TValue aux; const TValue *p2; if (isfloat) { setfltvalue(&aux, cast_num(v2)); } else setivalue(&aux, v2); if (flip) { /* arguments were exchanged? */ p2 = p1; p1 = &aux; /* correct them */ } else p2 = &aux; return luaT_callorderTM(L, p1, p2, event); } /* ** Create a vararg table at the top of the stack, with 'n' elements ** starting at 'f'. */ static void createvarargtab (lua_State *L, StkId f, int n) { int i; TValue key, value; Table *t = luaH_new(L); sethvalue(L, s2v(L->top.p), t); L->top.p++; luaH_resize(L, t, cast_uint(n), 1); setsvalue(L, &key, luaS_new(L, "n")); /* key is "n" */ setivalue(&value, n); /* value is n */ /* No need to anchor the key: Due to the resize, the next operation cannot trigger a garbage collection */ luaH_set(L, t, &key, &value); /* t.n = n */ for (i = 0; i < n; i++) luaH_setint(L, t, i + 1, s2v(f + i)); luaC_checkGC(L); } /* ** initial stack: func arg1 ... argn extra1 ... ** ^ ci->func ^ L->top ** final stack: func nil ... nil extra1 ... func arg1 ... argn ** ^ ci->func */ static void buildhiddenargs (lua_State *L, CallInfo *ci, const Proto *p, int totalargs, int nfixparams, int nextra) { int i; ci->u.l.nextraargs = nextra; luaD_checkstack(L, p->maxstacksize + 1); /* copy function to the top of the stack, after extra arguments */ setobjs2s(L, L->top.p++, ci->func.p); /* move fixed parameters to after the copied function */ for (i = 1; i <= nfixparams; i++) { setobjs2s(L, L->top.p++, ci->func.p + i); setnilvalue(s2v(ci->func.p + i)); /* erase original parameter (for GC) */ } ci->func.p += totalargs + 1; /* 'func' now lives after hidden arguments */ ci->top.p += totalargs + 1; } void luaT_adjustvarargs (lua_State *L, CallInfo *ci, const Proto *p) { int totalargs = cast_int(L->top.p - ci->func.p) - 1; int nfixparams = p->numparams; int nextra = totalargs - nfixparams; /* number of extra arguments */ if (p->flag & PF_VATAB) { /* does it need a vararg table? */ lua_assert(!(p->flag & PF_VAHID)); createvarargtab(L, ci->func.p + nfixparams + 1, nextra); /* move table to proper place (last parameter) */ setobjs2s(L, ci->func.p + nfixparams + 1, L->top.p - 1); } else { /* no table */ lua_assert(p->flag & PF_VAHID); buildhiddenargs(L, ci, p, totalargs, nfixparams, nextra); /* set vararg parameter to nil */ setnilvalue(s2v(ci->func.p + nfixparams + 1)); lua_assert(L->top.p <= ci->top.p && ci->top.p <= L->stack_last.p); } } void luaT_getvararg (CallInfo *ci, StkId ra, TValue *rc) { int nextra = ci->u.l.nextraargs; lua_Integer n; if (tointegerns(rc, &n)) { /* integral value? */ if (l_castS2U(n) - 1 < cast_uint(nextra)) { StkId slot = ci->func.p - nextra + cast_int(n) - 1; setobjs2s(((lua_State*)NULL), ra, slot); return; } } else if (ttisstring(rc)) { /* string value? */ size_t len; const char *s = getlstr(tsvalue(rc), len); if (len == 1 && s[0] == 'n') { /* key is "n"? */ setivalue(s2v(ra), nextra); return; } } setnilvalue(s2v(ra)); /* else produce nil */ } /* ** Get the number of extra arguments in a vararg function. If vararg ** table has been optimized away, that number is in the call info. ** Otherwise, get the field 'n' from the vararg table and check that it ** has a proper value (non-negative integer not larger than the stack ** limit). */ static int getnumargs (lua_State *L, CallInfo *ci, Table *h) { if (h == NULL) /* no vararg table? */ return ci->u.l.nextraargs; else { TValue res; if (luaH_getshortstr(h, luaS_new(L, "n"), &res) != LUA_VNUMINT || l_castS2U(ivalue(&res)) > cast_uint(INT_MAX/2)) luaG_runerror(L, "vararg table has no proper 'n'"); return cast_int(ivalue(&res)); } } /* ** Get 'wanted' vararg arguments and put them in 'where'. 'vatab' is ** the register of the vararg table or -1 if there is no vararg table. */ void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted, int vatab) { Table *h = (vatab < 0) ? NULL : hvalue(s2v(ci->func.p + vatab + 1)); int nargs = getnumargs(L, ci, h); /* number of available vararg args. */ int i, touse; /* 'touse' is minimum between 'wanted' and 'nargs' */ if (wanted < 0) { touse = wanted = nargs; /* get all extra arguments available */ checkstackp(L, nargs, where); /* ensure stack space */ L->top.p = where + nargs; /* next instruction will need top */ } else touse = (nargs > wanted) ? wanted : nargs; if (h == NULL) { /* no vararg table? */ for (i = 0; i < touse; i++) /* get vararg values from the stack */ setobjs2s(L, where + i, ci->func.p - nargs + i); } else { /* get vararg values from vararg table */ for (i = 0; i < touse; i++) { lu_byte tag = luaH_getint(h, i + 1, s2v(where + i)); if (tagisempty(tag)) setnilvalue(s2v(where + i)); } } for (; i < wanted; i++) /* complete required results with nil */ setnilvalue(s2v(where + i)); } /* ** $Id: lundump.c $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ #define lundump_c #define LUA_CORE #include #include #include "lua.h" #if !defined(luai_verifycode) #define luai_verifycode(L,f) /* empty */ #endif typedef struct { lua_State *L; ZIO *Z; const char *name; Table *h; /* list for string reuse */ size_t offset; /* current position relative to beginning of dump */ lua_Unsigned nstr; /* number of strings in the list */ lu_byte fixed; /* dump is fixed in memory */ } LoadState; static l_noret error (LoadState *S, const char *why) { luaO_pushfstring(S->L, "%s: bad binary format (%s)", S->name, why); luaD_throw(S->L, LUA_ERRSYNTAX); } /* ** All high-level loads go through loadVector; you can change it to ** adapt to the endianness of the input */ #define loadVector(S,b,n) loadBlock(S,b,cast_sizet(n)*sizeof((b)[0])) static void loadBlock (LoadState *S, void *b, size_t size) { if (luaZ_read(S->Z, b, size) != 0) error(S, "truncated chunk"); S->offset += size; } static void loadAlign (LoadState *S, unsigned align) { unsigned padding = align - cast_uint(S->offset % align); if (padding < align) { /* (padding == align) means no padding */ lua_Integer paddingContent; loadBlock(S, &paddingContent, padding); lua_assert(S->offset % align == 0); } } #define getaddr(S,n,t) cast(t *, getaddr_(S,cast_sizet(n) * sizeof(t))) static const void *getaddr_ (LoadState *S, size_t size) { const void *block = luaZ_getaddr(S->Z, size); S->offset += size; if (block == NULL) error(S, "truncated fixed buffer"); return block; } #define loadVar(S,x) loadVector(S,&x,1) static lu_byte loadByte (LoadState *S) { int b = zgetc(S->Z); if (b == EOZ) error(S, "truncated chunk"); S->offset++; return cast_byte(b); } static lua_Unsigned loadVarint (LoadState *S, lua_Unsigned limit) { lua_Unsigned x = 0; int b; limit >>= 7; do { b = loadByte(S); if (x > limit) error(S, "integer overflow"); x = (x << 7) | (b & 0x7f); } while ((b & 0x80) != 0); return x; } static size_t loadSize (LoadState *S) { return cast_sizet(loadVarint(S, MAX_SIZE)); } static int loadInt (LoadState *S) { return cast_int(loadVarint(S, cast_sizet(INT_MAX))); } static lua_Number loadNumber (LoadState *S) { lua_Number x; loadVar(S, x); return x; } static lua_Integer loadInteger (LoadState *S) { lua_Unsigned cx = loadVarint(S, LUA_MAXUNSIGNED); /* decode unsigned to signed */ if ((cx & 1) != 0) return l_castU2S(~(cx >> 1)); else return l_castU2S(cx >> 1); } /* ** Load a nullable string into slot 'sl' from prototype 'p'. The ** assignment to the slot and the barrier must be performed before any ** possible GC activity, to anchor the string. (Both 'loadVector' and ** 'luaH_setint' can call the GC.) */ static void loadString (LoadState *S, Proto *p, TString **sl) { lua_State *L = S->L; TString *ts; TValue sv; size_t size = loadSize(S); if (size == 0) { /* previously saved string? */ lua_Unsigned idx = loadVarint(S, LUA_MAXUNSIGNED); /* get its index */ TValue stv; if (idx == 0) { /* no string? */ lua_assert(*sl == NULL); /* must be prefilled */ return; } if (novariant(luaH_getint(S->h, l_castU2S(idx), &stv)) != LUA_TSTRING) error(S, "invalid string index"); *sl = ts = tsvalue(&stv); /* get its value */ luaC_objbarrier(L, p, ts); return; /* do not save it again */ } else if ((size -= 1) <= LUAI_MAXSHORTLEN) { /* short string? */ char buff[LUAI_MAXSHORTLEN + 1]; /* extra space for '\0' */ loadVector(S, buff, size + 1); /* load string into buffer */ *sl = ts = luaS_newlstr(L, buff, size); /* create string */ luaC_objbarrier(L, p, ts); } else if (S->fixed) { /* for a fixed buffer, use a fixed string */ const char *s = getaddr(S, size + 1, char); /* get content address */ *sl = ts = luaS_newextlstr(L, s, size, NULL, NULL); luaC_objbarrier(L, p, ts); } else { /* create internal copy */ *sl = ts = luaS_createlngstrobj(L, size); /* create string */ luaC_objbarrier(L, p, ts); loadVector(S, getlngstr(ts), size + 1); /* load directly in final place */ } /* add string to list of saved strings */ S->nstr++; setsvalue(L, &sv, ts); luaH_setint(L, S->h, l_castU2S(S->nstr), &sv); luaC_objbarrierback(L, obj2gco(S->h), ts); } static void loadCode (LoadState *S, Proto *f) { int n = loadInt(S); loadAlign(S, sizeof(f->code[0])); if (S->fixed) { f->code = getaddr(S, n, Instruction); f->sizecode = n; } else { f->code = luaM_newvectorchecked(S->L, n, Instruction); f->sizecode = n; loadVector(S, f->code, n); } } static void loadFunction(LoadState *S, Proto *f); static void loadConstants (LoadState *S, Proto *f) { int i; int n = loadInt(S); f->k = luaM_newvectorchecked(S->L, n, TValue); f->sizek = n; for (i = 0; i < n; i++) setnilvalue(&f->k[i]); for (i = 0; i < n; i++) { TValue *o = &f->k[i]; int t = loadByte(S); switch (t) { case LUA_VNIL: setnilvalue(o); break; case LUA_VFALSE: setbfvalue(o); break; case LUA_VTRUE: setbtvalue(o); break; case LUA_VNUMFLT: setfltvalue(o, loadNumber(S)); break; case LUA_VNUMINT: setivalue(o, loadInteger(S)); break; case LUA_VSHRSTR: case LUA_VLNGSTR: { lua_assert(f->source == NULL); loadString(S, f, &f->source); /* use 'source' to anchor string */ if (f->source == NULL) error(S, "bad format for constant string"); setsvalue2n(S->L, o, f->source); /* save it in the right place */ f->source = NULL; break; } default: error(S, "invalid constant"); } } } static void loadProtos (LoadState *S, Proto *f) { int i; int n = loadInt(S); f->p = luaM_newvectorchecked(S->L, n, Proto *); f->sizep = n; for (i = 0; i < n; i++) f->p[i] = NULL; for (i = 0; i < n; i++) { f->p[i] = luaF_newproto(S->L); luaC_objbarrier(S->L, f, f->p[i]); loadFunction(S, f->p[i]); } } /* ** Load the upvalues for a function. The names must be filled first, ** because the filling of the other fields can raise read errors and ** the creation of the error message can call an emergency collection; ** in that case all prototypes must be consistent for the GC. */ static void loadUpvalues (LoadState *S, Proto *f) { int i; int n = loadInt(S); f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc); f->sizeupvalues = n; for (i = 0; i < n; i++) /* make array valid for GC */ f->upvalues[i].name = NULL; for (i = 0; i < n; i++) { /* following calls can raise errors */ f->upvalues[i].instack = loadByte(S); f->upvalues[i].idx = loadByte(S); f->upvalues[i].kind = loadByte(S); } } static void loadDebug (LoadState *S, Proto *f) { int i; int n = loadInt(S); if (S->fixed) { f->lineinfo = getaddr(S, n, ls_byte); f->sizelineinfo = n; } else { f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte); f->sizelineinfo = n; loadVector(S, f->lineinfo, n); } n = loadInt(S); if (n > 0) { loadAlign(S, sizeof(int)); if (S->fixed) { f->abslineinfo = getaddr(S, n, AbsLineInfo); f->sizeabslineinfo = n; } else { f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo); f->sizeabslineinfo = n; loadVector(S, f->abslineinfo, n); } } n = loadInt(S); f->locvars = luaM_newvectorchecked(S->L, n, LocVar); f->sizelocvars = n; for (i = 0; i < n; i++) f->locvars[i].varname = NULL; for (i = 0; i < n; i++) { loadString(S, f, &f->locvars[i].varname); f->locvars[i].startpc = loadInt(S); f->locvars[i].endpc = loadInt(S); } n = loadInt(S); if (n != 0) /* does it have debug information? */ n = f->sizeupvalues; /* must be this many */ for (i = 0; i < n; i++) loadString(S, f, &f->upvalues[i].name); } static void loadFunction (LoadState *S, Proto *f) { f->linedefined = loadInt(S); f->lastlinedefined = loadInt(S); f->numparams = loadByte(S); /* get only the meaningful flags */ f->flag = cast_byte(loadByte(S) & ~PF_FIXED); if (S->fixed) f->flag |= PF_FIXED; /* signal that code is fixed */ f->maxstacksize = loadByte(S); loadCode(S, f); loadConstants(S, f); loadUpvalues(S, f); loadProtos(S, f); loadString(S, f, &f->source); loadDebug(S, f); } static void checkliteral (LoadState *S, const char *s, const char *msg) { char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */ size_t len = strlen(s); loadVector(S, buff, len); if (memcmp(s, buff, len) != 0) error(S, msg); } static l_noret numerror (LoadState *S, const char *what, const char *tname) { const char *msg = luaO_pushfstring(S->L, "%s %s mismatch", tname, what); error(S, msg); } static void checknumsize (LoadState *S, int size, const char *tname) { if (size != loadByte(S)) numerror(S, "size", tname); } static void checknumformat (LoadState *S, int eq, const char *tname) { if (!eq) numerror(S, "format", tname); } #define checknum(S,tvar,value,tname) \ { tvar i; checknumsize(S, sizeof(i), tname); \ loadVar(S, i); \ checknumformat(S, i == value, tname); } static void checkHeader (LoadState *S) { /* skip 1st char (already read and checked) */ checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk"); if (loadByte(S) != LUAC_VERSION) error(S, "version mismatch"); if (loadByte(S) != LUAC_FORMAT) error(S, "format mismatch"); checkliteral(S, LUAC_DATA, "corrupted chunk"); checknum(S, int, LUAC_INT, "int"); checknum(S, Instruction, LUAC_INST, "instruction"); checknum(S, lua_Integer, LUAC_INT, "Lua integer"); checknum(S, lua_Number, LUAC_NUM, "Lua number"); } /* ** Load precompiled chunk. */ LClosure *luaU_undump (lua_State *L, ZIO *Z, const char *name, int fixed) { LoadState S; LClosure *cl; if (*name == '@' || *name == '=') name = name + 1; else if (*name == LUA_SIGNATURE[0]) name = "binary string"; S.name = name; S.L = L; S.Z = Z; S.fixed = cast_byte(fixed); S.offset = 1; /* fist byte was already read */ checkHeader(&S); cl = luaF_newLclosure(L, loadByte(&S)); setclLvalue2s(L, L->top.p, cl); luaD_inctop(L); S.h = luaH_new(L); /* create list of saved strings */ S.nstr = 0; sethvalue2s(L, L->top.p, S.h); /* anchor it */ luaD_inctop(L); cl->p = luaF_newproto(L); luaC_objbarrier(L, cl, cl->p); loadFunction(&S, cl->p); if (cl->nupvalues != cl->p->sizeupvalues) error(&S, "corrupted chunk"); luai_verifycode(L, cl->p); L->top.p--; /* pop table */ return cl; } /* ** $Id: lvm.c $ ** Lua virtual machine ** See Copyright Notice in lua.h */ #define lvm_c #define LUA_CORE #include #include #include #include #include #include #include "lua.h" /* ** By default, use jump tables in the main interpreter loop on gcc ** and compatible compilers. */ #if !defined(LUA_USE_JUMPTABLE) #if defined(__GNUC__) #define LUA_USE_JUMPTABLE 1 #else #define LUA_USE_JUMPTABLE 0 #endif #endif /* limit for table tag-method chains (to avoid infinite loops) */ #define MAXTAGLOOP 2000 /* ** 'l_intfitsf' checks whether a given integer is in the range that ** can be converted to a float without rounding. Used in comparisons. */ /* number of bits in the mantissa of a float */ #define NBM (l_floatatt(MANT_DIG)) /* ** Check whether some integers may not fit in a float, testing whether ** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.) ** (The shifts are done in parts, to avoid shifting by more than the size ** of an integer. In a worst case, NBM == 113 for long double and ** sizeof(long) == 32.) */ #if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \ >> (NBM - (3 * (NBM / 4)))) > 0 /* limit for integers that fit in a float */ #define MAXINTFITSF ((lua_Unsigned)1 << NBM) /* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */ #define l_intfitsf(i) ((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF)) #else /* all integers fit in a float precisely */ #define l_intfitsf(i) 1 #endif /* ** Try to convert a value from string to a number value. ** If the value is not a string or is a string not representing ** a valid numeral (or if coercions from strings to numbers ** are disabled via macro 'cvt2num'), do not modify 'result' ** and return 0. */ static int l_strton (const TValue *obj, TValue *result) { lua_assert(obj != result); if (!cvt2num(obj)) /* is object not a string? */ return 0; else { TString *st = tsvalue(obj); size_t stlen; const char *s = getlstr(st, stlen); return (luaO_str2num(s, result) == stlen + 1); } } /* ** Try to convert a value to a float. The float case is already handled ** by the macro 'tonumber'. */ int luaV_tonumber_ (const TValue *obj, lua_Number *n) { TValue v; if (ttisinteger(obj)) { *n = cast_num(ivalue(obj)); return 1; } else if (l_strton(obj, &v)) { /* string coercible to number? */ *n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */ return 1; } else return 0; /* conversion failed */ } /* ** try to convert a float to an integer, rounding according to 'mode'. */ int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode) { lua_Number f = l_floor(n); if (n != f) { /* not an integral value? */ if (mode == F2Ieq) return 0; /* fails if mode demands integral value */ else if (mode == F2Iceil) /* needs ceiling? */ f += 1; /* convert floor to ceiling (remember: n != f) */ } return lua_numbertointeger(f, p); } /* ** try to convert a value to an integer, rounding according to 'mode', ** without string coercion. ** ("Fast track" handled by macro 'tointegerns'.) */ int luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode) { if (ttisfloat(obj)) return luaV_flttointeger(fltvalue(obj), p, mode); else if (ttisinteger(obj)) { *p = ivalue(obj); return 1; } else return 0; } /* ** try to convert a value to an integer. */ int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode) { TValue v; if (l_strton(obj, &v)) /* does 'obj' point to a numerical string? */ obj = &v; /* change it to point to its corresponding number */ return luaV_tointegerns(obj, p, mode); } /* ** Try to convert a 'for' limit to an integer, preserving the semantics ** of the loop. Return true if the loop must not run; otherwise, '*p' ** gets the integer limit. ** (The following explanation assumes a positive step; it is valid for ** negative steps mutatis mutandis.) ** If the limit is an integer or can be converted to an integer, ** rounding down, that is the limit. ** Otherwise, check whether the limit can be converted to a float. If ** the float is too large, clip it to LUA_MAXINTEGER. If the float ** is too negative, the loop should not run, because any initial ** integer value is greater than such limit; so, the function returns ** true to signal that. (For this latter case, no integer limit would be ** correct; even a limit of LUA_MININTEGER would run the loop once for ** an initial value equal to LUA_MININTEGER.) */ static int forlimit (lua_State *L, lua_Integer init, const TValue *lim, lua_Integer *p, lua_Integer step) { if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) { /* not coercible to in integer */ lua_Number flim; /* try to convert to float */ if (!tonumber(lim, &flim)) /* cannot convert to float? */ luaG_forerror(L, lim, "limit"); /* else 'flim' is a float out of integer bounds */ if (luai_numlt(0, flim)) { /* if it is positive, it is too large */ if (step < 0) return 1; /* initial value must be less than it */ *p = LUA_MAXINTEGER; /* truncate */ } else { /* it is less than min integer */ if (step > 0) return 1; /* initial value must be greater than it */ *p = LUA_MININTEGER; /* truncate */ } } return (step > 0 ? init > *p : init < *p); /* not to run? */ } /* ** Prepare a numerical for loop (opcode OP_FORPREP). ** Before execution, stack is as follows: ** ra : initial value ** ra + 1 : limit ** ra + 2 : step ** Return true to skip the loop. Otherwise, ** after preparation, stack will be as follows: ** ra : loop counter (integer loops) or limit (float loops) ** ra + 1 : step ** ra + 2 : control variable */ static int forprep (lua_State *L, StkId ra) { TValue *pinit = s2v(ra); TValue *plimit = s2v(ra + 1); TValue *pstep = s2v(ra + 2); if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */ lua_Integer init = ivalue(pinit); lua_Integer step = ivalue(pstep); lua_Integer limit; if (step == 0) luaG_runerror(L, "'for' step is zero"); if (forlimit(L, init, plimit, &limit, step)) return 1; /* skip the loop */ else { /* prepare loop counter */ lua_Unsigned count; if (step > 0) { /* ascending loop? */ count = l_castS2U(limit) - l_castS2U(init); if (step != 1) /* avoid division in the too common case */ count /= l_castS2U(step); } else { /* step < 0; descending loop */ count = l_castS2U(init) - l_castS2U(limit); /* 'step+1' avoids negating 'mininteger' */ count /= l_castS2U(-(step + 1)) + 1u; } /* use 'chgivalue' for places that for sure had integers */ chgivalue(s2v(ra), l_castU2S(count)); /* change init to count */ setivalue(s2v(ra + 1), step); /* change limit to step */ chgivalue(s2v(ra + 2), init); /* change step to init */ } } else { /* try making all values floats */ lua_Number init; lua_Number limit; lua_Number step; if (l_unlikely(!tonumber(plimit, &limit))) luaG_forerror(L, plimit, "limit"); if (l_unlikely(!tonumber(pstep, &step))) luaG_forerror(L, pstep, "step"); if (l_unlikely(!tonumber(pinit, &init))) luaG_forerror(L, pinit, "initial value"); if (step == 0) luaG_runerror(L, "'for' step is zero"); if (luai_numlt(0, step) ? luai_numlt(limit, init) : luai_numlt(init, limit)) return 1; /* skip the loop */ else { /* make sure all values are floats */ setfltvalue(s2v(ra), limit); setfltvalue(s2v(ra + 1), step); setfltvalue(s2v(ra + 2), init); /* control variable */ } } return 0; } /* ** Execute a step of a float numerical for loop, returning ** true iff the loop must continue. (The integer case is ** written online with opcode OP_FORLOOP, for performance.) */ static int floatforloop (StkId ra) { lua_Number step = fltvalue(s2v(ra + 1)); lua_Number limit = fltvalue(s2v(ra)); lua_Number idx = fltvalue(s2v(ra + 2)); /* control variable */ idx = luai_numadd(L, idx, step); /* increment index */ if (luai_numlt(0, step) ? luai_numle(idx, limit) : luai_numle(limit, idx)) { chgfltvalue(s2v(ra + 2), idx); /* update control variable */ return 1; /* jump back */ } else return 0; /* finish the loop */ } /* ** Finish the table access 'val = t[key]' and return the tag of the result. */ lu_byte luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val, lu_byte tag) { int loop; /* counter to avoid infinite loops */ const TValue *tm; /* metamethod */ for (loop = 0; loop < MAXTAGLOOP; loop++) { if (tag == LUA_VNOTABLE) { /* 't' is not a table? */ lua_assert(!ttistable(t)); tm = luaT_gettmbyobj(L, t, TM_INDEX); if (l_unlikely(notm(tm))) luaG_typeerror(L, t, "index"); /* no metamethod */ /* else will try the metamethod */ } else { /* 't' is a table */ tm = fasttm(L, hvalue(t)->metatable, TM_INDEX); /* table's metamethod */ if (tm == NULL) { /* no metamethod? */ setnilvalue(s2v(val)); /* result is nil */ return LUA_VNIL; } /* else will try the metamethod */ } if (ttisfunction(tm)) { /* is metamethod a function? */ tag = luaT_callTMres(L, tm, t, key, val); /* call it */ return tag; /* return tag of the result */ } t = tm; /* else try to access 'tm[key]' */ luaV_fastget(t, key, s2v(val), luaH_get, tag); if (!tagisempty(tag)) return tag; /* done */ /* else repeat (tail call 'luaV_finishget') */ } luaG_runerror(L, "'__index' chain too long; possible loop"); return 0; /* to avoid warnings */ } /* ** Finish a table assignment 't[key] = val'. ** About anchoring the table before the call to 'luaH_finishset': ** This call may trigger an emergency collection. When loop>0, ** the table being accessed is a field in some metatable. If this ** metatable is weak and the table is not anchored, this collection ** could collect that table while it is being updated. */ void luaV_finishset (lua_State *L, const TValue *t, TValue *key, TValue *val, int hres) { int loop; /* counter to avoid infinite loops */ for (loop = 0; loop < MAXTAGLOOP; loop++) { const TValue *tm; /* '__newindex' metamethod */ if (hres != HNOTATABLE) { /* is 't' a table? */ Table *h = hvalue(t); /* save 't' table */ tm = fasttm(L, h->metatable, TM_NEWINDEX); /* get metamethod */ if (tm == NULL) { /* no metamethod? */ sethvalue2s(L, L->top.p, h); /* anchor 't' */ L->top.p++; /* assume EXTRA_STACK */ luaH_finishset(L, h, key, val, hres); /* set new value */ L->top.p--; invalidateTMcache(h); luaC_barrierback(L, obj2gco(h), val); return; } /* else will try the metamethod */ } else { /* not a table; check metamethod */ tm = luaT_gettmbyobj(L, t, TM_NEWINDEX); if (l_unlikely(notm(tm))) luaG_typeerror(L, t, "index"); } /* try the metamethod */ if (ttisfunction(tm)) { luaT_callTM(L, tm, t, key, val); return; } t = tm; /* else repeat assignment over 'tm' */ luaV_fastset(t, key, val, hres, luaH_pset); if (hres == HOK) { luaV_finishfastset(L, t, val); return; /* done */ } /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */ } luaG_runerror(L, "'__newindex' chain too long; possible loop"); } /* ** Function to be used for 0-terminated string order comparison */ #if !defined(l_strcoll) #define l_strcoll strcoll #endif /* ** Compare two strings 'ts1' x 'ts2', returning an integer less-equal- ** -greater than zero if 'ts1' is less-equal-greater than 'ts2'. ** The code is a little tricky because it allows '\0' in the strings ** and it uses 'strcoll' (to respect locales) for each segment ** of the strings. Note that segments can compare equal but still ** have different lengths. */ static int l_strcmp (const TString *ts1, const TString *ts2) { size_t rl1; /* real length */ const char *s1 = getlstr(ts1, rl1); size_t rl2; const char *s2 = getlstr(ts2, rl2); for (;;) { /* for each segment */ int temp = l_strcoll(s1, s2); if (temp != 0) /* not equal? */ return temp; /* done */ else { /* strings are equal up to a '\0' */ size_t zl1 = strlen(s1); /* index of first '\0' in 's1' */ size_t zl2 = strlen(s2); /* index of first '\0' in 's2' */ if (zl2 == rl2) /* 's2' is finished? */ return (zl1 == rl1) ? 0 : 1; /* check 's1' */ else if (zl1 == rl1) /* 's1' is finished? */ return -1; /* 's1' is less than 's2' ('s2' is not finished) */ /* both strings longer than 'zl'; go on comparing after the '\0' */ zl1++; zl2++; s1 += zl1; rl1 -= zl1; s2 += zl2; rl2 -= zl2; } } } /* ** Check whether integer 'i' is less than float 'f'. If 'i' has an ** exact representation as a float ('l_intfitsf'), compare numbers as ** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'. ** If 'ceil(f)' is out of integer range, either 'f' is greater than ** all integers or less than all integers. ** (The test with 'l_intfitsf' is only for performance; the else ** case is correct for all values, but it is slow due to the conversion ** from float to int.) ** When 'f' is NaN, comparisons must result in false. */ l_sinline int LTintfloat (lua_Integer i, lua_Number f) { if (l_intfitsf(i)) return luai_numlt(cast_num(i), f); /* compare them as floats */ else { /* i < f <=> i < ceil(f) */ lua_Integer fi; if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */ return i < fi; /* compare them as integers */ else /* 'f' is either greater or less than all integers */ return f > 0; /* greater? */ } } /* ** Check whether integer 'i' is less than or equal to float 'f'. ** See comments on previous function. */ l_sinline int LEintfloat (lua_Integer i, lua_Number f) { if (l_intfitsf(i)) return luai_numle(cast_num(i), f); /* compare them as floats */ else { /* i <= f <=> i <= floor(f) */ lua_Integer fi; if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */ return i <= fi; /* compare them as integers */ else /* 'f' is either greater or less than all integers */ return f > 0; /* greater? */ } } /* ** Check whether float 'f' is less than integer 'i'. ** See comments on previous function. */ l_sinline int LTfloatint (lua_Number f, lua_Integer i) { if (l_intfitsf(i)) return luai_numlt(f, cast_num(i)); /* compare them as floats */ else { /* f < i <=> floor(f) < i */ lua_Integer fi; if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */ return fi < i; /* compare them as integers */ else /* 'f' is either greater or less than all integers */ return f < 0; /* less? */ } } /* ** Check whether float 'f' is less than or equal to integer 'i'. ** See comments on previous function. */ l_sinline int LEfloatint (lua_Number f, lua_Integer i) { if (l_intfitsf(i)) return luai_numle(f, cast_num(i)); /* compare them as floats */ else { /* f <= i <=> ceil(f) <= i */ lua_Integer fi; if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */ return fi <= i; /* compare them as integers */ else /* 'f' is either greater or less than all integers */ return f < 0; /* less? */ } } /* ** Return 'l < r', for numbers. */ l_sinline int LTnum (const TValue *l, const TValue *r) { lua_assert(ttisnumber(l) && ttisnumber(r)); if (ttisinteger(l)) { lua_Integer li = ivalue(l); if (ttisinteger(r)) return li < ivalue(r); /* both are integers */ else /* 'l' is int and 'r' is float */ return LTintfloat(li, fltvalue(r)); /* l < r ? */ } else { lua_Number lf = fltvalue(l); /* 'l' must be float */ if (ttisfloat(r)) return luai_numlt(lf, fltvalue(r)); /* both are float */ else /* 'l' is float and 'r' is int */ return LTfloatint(lf, ivalue(r)); } } /* ** Return 'l <= r', for numbers. */ l_sinline int LEnum (const TValue *l, const TValue *r) { lua_assert(ttisnumber(l) && ttisnumber(r)); if (ttisinteger(l)) { lua_Integer li = ivalue(l); if (ttisinteger(r)) return li <= ivalue(r); /* both are integers */ else /* 'l' is int and 'r' is float */ return LEintfloat(li, fltvalue(r)); /* l <= r ? */ } else { lua_Number lf = fltvalue(l); /* 'l' must be float */ if (ttisfloat(r)) return luai_numle(lf, fltvalue(r)); /* both are float */ else /* 'l' is float and 'r' is int */ return LEfloatint(lf, ivalue(r)); } } /* ** return 'l < r' for non-numbers. */ static int lessthanothers (lua_State *L, const TValue *l, const TValue *r) { lua_assert(!ttisnumber(l) || !ttisnumber(r)); if (ttisstring(l) && ttisstring(r)) /* both are strings? */ return l_strcmp(tsvalue(l), tsvalue(r)) < 0; else return luaT_callorderTM(L, l, r, TM_LT); } /* ** Main operation less than; return 'l < r'. */ int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */ return LTnum(l, r); else return lessthanothers(L, l, r); } /* ** return 'l <= r' for non-numbers. */ static int lessequalothers (lua_State *L, const TValue *l, const TValue *r) { lua_assert(!ttisnumber(l) || !ttisnumber(r)); if (ttisstring(l) && ttisstring(r)) /* both are strings? */ return l_strcmp(tsvalue(l), tsvalue(r)) <= 0; else return luaT_callorderTM(L, l, r, TM_LE); } /* ** Main operation less than or equal to; return 'l <= r'. */ int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */ return LEnum(l, r); else return lessequalothers(L, l, r); } /* ** Main operation for equality of Lua values; return 't1 == t2'. ** L == NULL means raw equality (no metamethods) */ int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) { const TValue *tm; if (ttype(t1) != ttype(t2)) /* not the same type? */ return 0; else if (ttypetag(t1) != ttypetag(t2)) { switch (ttypetag(t1)) { case LUA_VNUMINT: { /* integer == float? */ /* integer and float can only be equal if float has an integer value equal to the integer */ lua_Integer i2; return (luaV_flttointeger(fltvalue(t2), &i2, F2Ieq) && ivalue(t1) == i2); } case LUA_VNUMFLT: { /* float == integer? */ lua_Integer i1; /* see comment in previous case */ return (luaV_flttointeger(fltvalue(t1), &i1, F2Ieq) && i1 == ivalue(t2)); } case LUA_VSHRSTR: case LUA_VLNGSTR: { /* compare two strings with different variants: they can be equal when one string is a short string and the other is an external string */ return luaS_eqstr(tsvalue(t1), tsvalue(t2)); } default: /* only numbers (integer/float) and strings (long/short) can have equal values with different variants */ return 0; } } else { /* equal variants */ switch (ttypetag(t1)) { case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: return 1; case LUA_VNUMINT: return (ivalue(t1) == ivalue(t2)); case LUA_VNUMFLT: return (fltvalue(t1) == fltvalue(t2)); case LUA_VLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); case LUA_VSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2)); case LUA_VLNGSTR: return luaS_eqstr(tsvalue(t1), tsvalue(t2)); case LUA_VUSERDATA: { if (uvalue(t1) == uvalue(t2)) return 1; else if (L == NULL) return 0; tm = fasttm(L, uvalue(t1)->metatable, TM_EQ); if (tm == NULL) tm = fasttm(L, uvalue(t2)->metatable, TM_EQ); break; /* will try TM */ } case LUA_VTABLE: { if (hvalue(t1) == hvalue(t2)) return 1; else if (L == NULL) return 0; tm = fasttm(L, hvalue(t1)->metatable, TM_EQ); if (tm == NULL) tm = fasttm(L, hvalue(t2)->metatable, TM_EQ); break; /* will try TM */ } case LUA_VLCF: return (fvalue(t1) == fvalue(t2)); default: /* functions and threads */ return (gcvalue(t1) == gcvalue(t2)); } if (tm == NULL) /* no TM? */ return 0; /* objects are different */ else { int tag = luaT_callTMres(L, tm, t1, t2, L->top.p); /* call TM */ return !tagisfalse(tag); } } } /* macro used by 'luaV_concat' to ensure that element at 'o' is a string */ #define tostring(L,o) \ (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1))) /* ** Check whether object is a short empty string to optimize concatenation. ** (External strings can be empty too; they will be concatenated like ** non-empty ones.) */ #define isemptystr(o) (ttisshrstring(o) && tsvalue(o)->shrlen == 0) /* copy strings in stack from top - n up to top - 1 to buffer */ static void copy2buff (StkId top, int n, char *buff) { size_t tl = 0; /* size already copied */ do { TString *st = tsvalue(s2v(top - n)); size_t l; /* length of string being copied */ const char *s = getlstr(st, l); memcpy(buff + tl, s, l * sizeof(char)); tl += l; } while (--n > 0); } /* ** Main operation for concatenation: concat 'total' values in the stack, ** from 'L->top.p - total' up to 'L->top.p - 1'. */ void luaV_concat (lua_State *L, int total) { if (total == 1) return; /* "all" values already concatenated */ do { StkId top = L->top.p; int n = 2; /* number of elements handled in this pass (at least 2) */ if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) || !tostring(L, s2v(top - 1))) luaT_tryconcatTM(L); /* may invalidate 'top' */ else if (isemptystr(s2v(top - 1))) /* second operand is empty? */ cast_void(tostring(L, s2v(top - 2))); /* result is first operand */ else if (isemptystr(s2v(top - 2))) { /* first operand is empty string? */ setobjs2s(L, top - 2, top - 1); /* result is second op. */ } else { /* at least two string values; get as many as possible */ size_t tl = tsslen(tsvalue(s2v(top - 1))); /* total length */ TString *ts; /* collect total length and number of strings */ for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) { size_t l = tsslen(tsvalue(s2v(top - n - 1))); if (l_unlikely(l >= MAX_SIZE - sizeof(TString) - tl)) { L->top.p = top - total; /* pop strings to avoid wasting stack */ luaG_runerror(L, "string length overflow"); } tl += l; } if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */ char buff[LUAI_MAXSHORTLEN]; copy2buff(top, n, buff); /* copy strings to buffer */ ts = luaS_newlstr(L, buff, tl); } else { /* long string; copy strings directly to final result */ ts = luaS_createlngstrobj(L, tl); copy2buff(top, n, getlngstr(ts)); } setsvalue2s(L, top - n, ts); /* create result */ } total -= n - 1; /* got 'n' strings to create one new */ L->top.p -= n - 1; /* popped 'n' strings and pushed one */ } while (total > 1); /* repeat until only 1 result left */ } /* ** Main operation 'ra = #rb'. */ void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { const TValue *tm; switch (ttypetag(rb)) { case LUA_VTABLE: { Table *h = hvalue(rb); tm = fasttm(L, h->metatable, TM_LEN); if (tm) break; /* metamethod? break switch to call it */ setivalue(s2v(ra), l_castU2S(luaH_getn(L, h))); /* else primitive len */ return; } case LUA_VSHRSTR: { setivalue(s2v(ra), tsvalue(rb)->shrlen); return; } case LUA_VLNGSTR: { setivalue(s2v(ra), cast_st2S(tsvalue(rb)->u.lnglen)); return; } default: { /* try metamethod */ tm = luaT_gettmbyobj(L, rb, TM_LEN); if (l_unlikely(notm(tm))) /* no metamethod? */ luaG_typeerror(L, rb, "get length of"); break; } } luaT_callTMres(L, tm, rb, rb, ra); } /* ** Integer division; return 'm // n', that is, floor(m/n). ** C division truncates its result (rounds towards zero). ** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer, ** otherwise 'floor(q) == trunc(q) - 1'. */ lua_Integer luaV_idiv (lua_State *L, lua_Integer m, lua_Integer n) { if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */ if (n == 0) luaG_runerror(L, "attempt to divide by zero"); return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */ } else { lua_Integer q = m / n; /* perform C division */ if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */ q -= 1; /* correct result for different rounding */ return q; } } /* ** Integer modulus; return 'm % n'. (Assume that C '%' with ** negative operands follows C99 behavior. See previous comment ** about luaV_idiv.) */ lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) { if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */ if (n == 0) luaG_runerror(L, "attempt to perform 'n%%0'"); return 0; /* m % -1 == 0; avoid overflow with 0x80000...%-1 */ } else { lua_Integer r = m % n; if (r != 0 && (r ^ n) < 0) /* 'm/n' would be non-integer negative? */ r += n; /* correct result for different rounding */ return r; } } /* ** Float modulus */ lua_Number luaV_modf (lua_State *L, lua_Number m, lua_Number n) { lua_Number r; luai_nummod(L, m, n, r); return r; } /* number of bits in an integer */ #define NBITS l_numbits(lua_Integer) /* ** Shift left operation. (Shift right just negates 'y'.) */ lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) { if (y < 0) { /* shift right? */ if (y <= -NBITS) return 0; else return intop(>>, x, -y); } else { /* shift left */ if (y >= NBITS) return 0; else return intop(<<, x, y); } } /* ** create a new Lua closure, push it in the stack, and initialize ** its upvalues. */ static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, StkId ra) { int nup = p->sizeupvalues; Upvaldesc *uv = p->upvalues; int i; LClosure *ncl = luaF_newLclosure(L, nup); ncl->p = p; setclLvalue2s(L, ra, ncl); /* anchor new closure in stack */ for (i = 0; i < nup; i++) { /* fill in its upvalues */ if (uv[i].instack) /* upvalue refers to local variable? */ ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx); else /* get upvalue from enclosing function */ ncl->upvals[i] = encup[uv[i].idx]; luaC_objbarrier(L, ncl, ncl->upvals[i]); } } /* ** finish execution of an opcode interrupted by a yield */ void luaV_finishOp (lua_State *L) { CallInfo *ci = L->ci; StkId base = ci->func.p + 1; Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */ OpCode op = GET_OPCODE(inst); switch (op) { /* finish its execution */ case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: { setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top.p); break; } case OP_UNM: case OP_BNOT: case OP_LEN: case OP_GETTABUP: case OP_GETTABLE: case OP_GETI: case OP_GETFIELD: case OP_SELF: { setobjs2s(L, base + GETARG_A(inst), --L->top.p); break; } case OP_LT: case OP_LE: case OP_LTI: case OP_LEI: case OP_GTI: case OP_GEI: case OP_EQ: { /* note that 'OP_EQI'/'OP_EQK' cannot yield */ int res = !l_isfalse(s2v(L->top.p - 1)); L->top.p--; lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP); if (res != GETARG_k(inst)) /* condition failed? */ ci->u.l.savedpc++; /* skip jump instruction */ break; } case OP_CONCAT: { StkId top = L->top.p - 1; /* top when 'luaT_tryconcatTM' was called */ int a = GETARG_A(inst); /* first element to concatenate */ int total = cast_int(top - 1 - (base + a)); /* yet to concatenate */ setobjs2s(L, top - 2, top); /* put TM result in proper position */ L->top.p = top - 1; /* top is one after last element (at top-2) */ luaV_concat(L, total); /* concat them (may yield again) */ break; } case OP_CLOSE: { /* yielded closing variables */ ci->u.l.savedpc--; /* repeat instruction to close other vars. */ break; } case OP_RETURN: { /* yielded closing variables */ StkId ra = base + GETARG_A(inst); /* adjust top to signal correct number of returns, in case the return is "up to top" ('isIT') */ L->top.p = ra + ci->u2.nres; /* repeat instruction to close other vars. and complete the return */ ci->u.l.savedpc--; break; } default: { /* only these other opcodes can yield */ lua_assert(op == OP_TFORCALL || op == OP_CALL || op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE || op == OP_SETI || op == OP_SETFIELD); break; } } } /* ** {================================================================== ** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute' ** ** All these macros are to be used exclusively inside the main ** iterpreter loop (function luaV_execute) and may access directly ** the local variables of that function (L, i, pc, ci, etc.). ** =================================================================== */ #define l_addi(L,a,b) intop(+, a, b) #define l_subi(L,a,b) intop(-, a, b) #define l_muli(L,a,b) intop(*, a, b) #define l_band(a,b) intop(&, a, b) #define l_bor(a,b) intop(|, a, b) #define l_bxor(a,b) intop(^, a, b) #define l_lti(a,b) (a < b) #define l_lei(a,b) (a <= b) #define l_gti(a,b) (a > b) #define l_gei(a,b) (a >= b) /* ** Arithmetic operations with immediate operands. 'iop' is the integer ** operation, 'fop' is the float operation. */ #define op_arithI(L,iop,fop) { \ TValue *ra = vRA(i); \ TValue *v1 = vRB(i); \ int imm = GETARG_sC(i); \ if (ttisinteger(v1)) { \ lua_Integer iv1 = ivalue(v1); \ pc++; setivalue(ra, iop(L, iv1, imm)); \ } \ else if (ttisfloat(v1)) { \ lua_Number nb = fltvalue(v1); \ lua_Number fimm = cast_num(imm); \ pc++; setfltvalue(ra, fop(L, nb, fimm)); \ }} /* ** Auxiliary function for arithmetic operations over floats and others ** with two operands. */ #define op_arithf_aux(L,v1,v2,fop) { \ lua_Number n1; lua_Number n2; \ if (tonumberns(v1, n1) && tonumberns(v2, n2)) { \ StkId ra = RA(i); \ pc++; setfltvalue(s2v(ra), fop(L, n1, n2)); \ }} /* ** Arithmetic operations over floats and others with register operands. */ #define op_arithf(L,fop) { \ TValue *v1 = vRB(i); \ TValue *v2 = vRC(i); \ op_arithf_aux(L, v1, v2, fop); } /* ** Arithmetic operations with K operands for floats. */ #define op_arithfK(L,fop) { \ TValue *v1 = vRB(i); \ TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \ op_arithf_aux(L, v1, v2, fop); } /* ** Arithmetic operations over integers and floats. */ #define op_arith_aux(L,v1,v2,iop,fop) { \ if (ttisinteger(v1) && ttisinteger(v2)) { \ StkId ra = RA(i); \ lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2); \ pc++; setivalue(s2v(ra), iop(L, i1, i2)); \ } \ else op_arithf_aux(L, v1, v2, fop); } /* ** Arithmetic operations with register operands. */ #define op_arith(L,iop,fop) { \ TValue *v1 = vRB(i); \ TValue *v2 = vRC(i); \ op_arith_aux(L, v1, v2, iop, fop); } /* ** Arithmetic operations with K operands. */ #define op_arithK(L,iop,fop) { \ TValue *v1 = vRB(i); \ TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \ op_arith_aux(L, v1, v2, iop, fop); } /* ** Bitwise operations with constant operand. */ #define op_bitwiseK(L,op) { \ TValue *v1 = vRB(i); \ TValue *v2 = KC(i); \ lua_Integer i1; \ lua_Integer i2 = ivalue(v2); \ if (tointegerns(v1, &i1)) { \ StkId ra = RA(i); \ pc++; setivalue(s2v(ra), op(i1, i2)); \ }} /* ** Bitwise operations with register operands. */ #define op_bitwise(L,op) { \ TValue *v1 = vRB(i); \ TValue *v2 = vRC(i); \ lua_Integer i1; lua_Integer i2; \ if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) { \ StkId ra = RA(i); \ pc++; setivalue(s2v(ra), op(i1, i2)); \ }} /* ** Order operations with register operands. 'opn' actually works ** for all numbers, but the fast track improves performance for ** integers. */ #define op_order(L,opi,opn,other) { \ TValue *ra = vRA(i); \ int cond; \ TValue *rb = vRB(i); \ if (ttisinteger(ra) && ttisinteger(rb)) { \ lua_Integer ia = ivalue(ra); \ lua_Integer ib = ivalue(rb); \ cond = opi(ia, ib); \ } \ else if (ttisnumber(ra) && ttisnumber(rb)) \ cond = opn(ra, rb); \ else \ Protect(cond = other(L, ra, rb)); \ docondjump(); } /* ** Order operations with immediate operand. (Immediate operand is ** always small enough to have an exact representation as a float.) */ #define op_orderI(L,opi,opf,inv,tm) { \ TValue *ra = vRA(i); \ int cond; \ int im = GETARG_sB(i); \ if (ttisinteger(ra)) \ cond = opi(ivalue(ra), im); \ else if (ttisfloat(ra)) { \ lua_Number fa = fltvalue(ra); \ lua_Number fim = cast_num(im); \ cond = opf(fa, fim); \ } \ else { \ int isf = GETARG_C(i); \ Protect(cond = luaT_callorderiTM(L, ra, im, inv, isf, tm)); \ } \ docondjump(); } /* }================================================================== */ /* ** {================================================================== ** Function 'luaV_execute': main interpreter loop ** =================================================================== */ /* ** some macros for common tasks in 'luaV_execute' */ #define RA(i) (base+GETARG_A(i)) #define vRA(i) s2v(RA(i)) #define RB(i) (base+GETARG_B(i)) #define vRB(i) s2v(RB(i)) #define KB(i) (k+GETARG_B(i)) #define RC(i) (base+GETARG_C(i)) #define vRC(i) s2v(RC(i)) #define KC(i) (k+GETARG_C(i)) #define RKC(i) ((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i))) #define updatetrap(ci) (trap = ci->u.l.trap) #define updatebase(ci) (base = ci->func.p + 1) #define updatestack(ci) \ { if (l_unlikely(trap)) { updatebase(ci); ra = RA(i); } } /* ** Execute a jump instruction. The 'updatetrap' allows signals to stop ** tight loops. (Without it, the local copy of 'trap' could never change.) */ #define dojump(ci,i,e) { pc += GETARG_sJ(i) + e; updatetrap(ci); } /* for test instructions, execute the jump instruction that follows it */ #define donextjump(ci) { Instruction ni = *pc; dojump(ci, ni, 1); } /* ** do a conditional jump: skip next instruction if 'cond' is not what ** was expected (parameter 'k'), else do next instruction, which must ** be a jump. */ #define docondjump() if (cond != GETARG_k(i)) pc++; else donextjump(ci); /* ** Correct global 'pc'. */ #define savepc(ci) (ci->u.l.savedpc = pc) /* ** Whenever code can raise errors, the global 'pc' and the global ** 'top' must be correct to report occasional errors. */ #define savestate(L,ci) (savepc(ci), L->top.p = ci->top.p) /* ** Protect code that, in general, can raise errors, reallocate the ** stack, and change the hooks. */ #define Protect(exp) (savestate(L,ci), (exp), updatetrap(ci)) /* special version that does not change the top */ #define ProtectNT(exp) (savepc(ci), (exp), updatetrap(ci)) /* ** Protect code that can only raise errors. (That is, it cannot change ** the stack or hooks.) */ #define halfProtect(exp) (savestate(L,ci), (exp)) /* ** macro executed during Lua functions at points where the ** function can yield. */ #if !defined(luai_threadyield) #define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} #endif /* 'c' is the limit of live values in the stack */ #define checkGC(L,c) \ { luaC_condGC(L, (savepc(ci), L->top.p = (c)), \ updatetrap(ci)); \ luai_threadyield(L); } /* fetch an instruction and prepare its execution */ #define vmfetch() { \ if (l_unlikely(trap)) { /* stack reallocation or hooks? */ \ trap = luaG_traceexec(L, pc); /* handle hooks */ \ updatebase(ci); /* correct stack */ \ } \ i = *(pc++); \ } #define vmdispatch(o) switch(o) #define vmcase(l) case l: #define vmbreak break void luaV_execute (lua_State *L, CallInfo *ci) { LClosure *cl; TValue *k; StkId base; const Instruction *pc; int trap; #if LUA_USE_JUMPTABLE /* ** $Id: ljumptab.h $ ** Jump Table for the Lua interpreter ** See Copyright Notice in lua.h */ #undef vmdispatch #undef vmcase #undef vmbreak #define vmdispatch(x) goto *disptab[x]; #define vmcase(l) L_##l: #define vmbreak vmfetch(); vmdispatch(GET_OPCODE(i)); static const void *const disptab[NUM_OPCODES] = { #if 0 ** you can update the following list with this command: ** ** sed -n '/^OP_/!d; s/OP_/\&\&L_OP_/ ; s/,.*/,/ ; s/\/.*// ; p' lopcodes.h ** #endif &&L_OP_MOVE, &&L_OP_LOADI, &&L_OP_LOADF, &&L_OP_LOADK, &&L_OP_LOADKX, &&L_OP_LOADFALSE, &&L_OP_LFALSESKIP, &&L_OP_LOADTRUE, &&L_OP_LOADNIL, &&L_OP_GETUPVAL, &&L_OP_SETUPVAL, &&L_OP_GETTABUP, &&L_OP_GETTABLE, &&L_OP_GETI, &&L_OP_GETFIELD, &&L_OP_SETTABUP, &&L_OP_SETTABLE, &&L_OP_SETI, &&L_OP_SETFIELD, &&L_OP_NEWTABLE, &&L_OP_SELF, &&L_OP_ADDI, &&L_OP_ADDK, &&L_OP_SUBK, &&L_OP_MULK, &&L_OP_MODK, &&L_OP_POWK, &&L_OP_DIVK, &&L_OP_IDIVK, &&L_OP_BANDK, &&L_OP_BORK, &&L_OP_BXORK, &&L_OP_SHLI, &&L_OP_SHRI, &&L_OP_ADD, &&L_OP_SUB, &&L_OP_MUL, &&L_OP_MOD, &&L_OP_POW, &&L_OP_DIV, &&L_OP_IDIV, &&L_OP_BAND, &&L_OP_BOR, &&L_OP_BXOR, &&L_OP_SHL, &&L_OP_SHR, &&L_OP_MMBIN, &&L_OP_MMBINI, &&L_OP_MMBINK, &&L_OP_UNM, &&L_OP_BNOT, &&L_OP_NOT, &&L_OP_LEN, &&L_OP_CONCAT, &&L_OP_CLOSE, &&L_OP_TBC, &&L_OP_JMP, &&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_EQK, &&L_OP_EQI, &&L_OP_LTI, &&L_OP_LEI, &&L_OP_GTI, &&L_OP_GEI, &&L_OP_TEST, &&L_OP_TESTSET, &&L_OP_CALL, &&L_OP_TAILCALL, &&L_OP_RETURN, &&L_OP_RETURN0, &&L_OP_RETURN1, &&L_OP_FORLOOP, &&L_OP_FORPREP, &&L_OP_TFORPREP, &&L_OP_TFORCALL, &&L_OP_TFORLOOP, &&L_OP_SETLIST, &&L_OP_CLOSURE, &&L_OP_VARARG, &&L_OP_GETVARG, &&L_OP_ERRNNIL, &&L_OP_VARARGPREP, &&L_OP_EXTRAARG }; #endif startfunc: trap = L->hookmask; returning: /* trap already set */ cl = ci_func(ci); k = cl->p->k; pc = ci->u.l.savedpc; if (l_unlikely(trap)) trap = luaG_tracecall(L); base = ci->func.p + 1; /* main loop of interpreter */ for (;;) { Instruction i; /* instruction being executed */ vmfetch(); #if 0 { /* low-level line tracing for debugging Lua */ int pcrel = pcRel(pc, cl->p); printf("line: %d; %s (%d)\n", luaG_getfuncline(cl->p, pcrel), opnames[GET_OPCODE(i)], pcrel); } #endif lua_assert(base == ci->func.p + 1); lua_assert(base <= L->top.p && L->top.p <= L->stack_last.p); /* for tests, invalidate top for instructions not expecting it */ lua_assert(luaP_isIT(i) || (cast_void(L->top.p = base), 1)); vmdispatch (GET_OPCODE(i)) { vmcase(OP_MOVE) { StkId ra = RA(i); setobjs2s(L, ra, RB(i)); vmbreak; } vmcase(OP_LOADI) { StkId ra = RA(i); lua_Integer b = GETARG_sBx(i); setivalue(s2v(ra), b); vmbreak; } vmcase(OP_LOADF) { StkId ra = RA(i); int b = GETARG_sBx(i); setfltvalue(s2v(ra), cast_num(b)); vmbreak; } vmcase(OP_LOADK) { StkId ra = RA(i); TValue *rb = k + GETARG_Bx(i); setobj2s(L, ra, rb); vmbreak; } vmcase(OP_LOADKX) { StkId ra = RA(i); TValue *rb; rb = k + GETARG_Ax(*pc); pc++; setobj2s(L, ra, rb); vmbreak; } vmcase(OP_LOADFALSE) { StkId ra = RA(i); setbfvalue(s2v(ra)); vmbreak; } vmcase(OP_LFALSESKIP) { StkId ra = RA(i); setbfvalue(s2v(ra)); pc++; /* skip next instruction */ vmbreak; } vmcase(OP_LOADTRUE) { StkId ra = RA(i); setbtvalue(s2v(ra)); vmbreak; } vmcase(OP_LOADNIL) { StkId ra = RA(i); int b = GETARG_B(i); do { setnilvalue(s2v(ra++)); } while (b--); vmbreak; } vmcase(OP_GETUPVAL) { StkId ra = RA(i); int b = GETARG_B(i); setobj2s(L, ra, cl->upvals[b]->v.p); vmbreak; } vmcase(OP_SETUPVAL) { StkId ra = RA(i); UpVal *uv = cl->upvals[GETARG_B(i)]; setobj(L, uv->v.p, s2v(ra)); luaC_barrier(L, uv, s2v(ra)); vmbreak; } vmcase(OP_GETTABUP) { StkId ra = RA(i); TValue *upval = cl->upvals[GETARG_B(i)]->v.p; TValue *rc = KC(i); TString *key = tsvalue(rc); /* key must be a short string */ lu_byte tag; luaV_fastget(upval, key, s2v(ra), luaH_getshortstr, tag); if (tagisempty(tag)) Protect(luaV_finishget(L, upval, rc, ra, tag)); vmbreak; } vmcase(OP_GETTABLE) { StkId ra = RA(i); TValue *rb = vRB(i); TValue *rc = vRC(i); lu_byte tag; if (ttisinteger(rc)) { /* fast track for integers? */ luaV_fastgeti(rb, ivalue(rc), s2v(ra), tag); } else luaV_fastget(rb, rc, s2v(ra), luaH_get, tag); if (tagisempty(tag)) Protect(luaV_finishget(L, rb, rc, ra, tag)); vmbreak; } vmcase(OP_GETI) { StkId ra = RA(i); TValue *rb = vRB(i); int c = GETARG_C(i); lu_byte tag; luaV_fastgeti(rb, c, s2v(ra), tag); if (tagisempty(tag)) { TValue key; setivalue(&key, c); Protect(luaV_finishget(L, rb, &key, ra, tag)); } vmbreak; } vmcase(OP_GETFIELD) { StkId ra = RA(i); TValue *rb = vRB(i); TValue *rc = KC(i); TString *key = tsvalue(rc); /* key must be a short string */ lu_byte tag; luaV_fastget(rb, key, s2v(ra), luaH_getshortstr, tag); if (tagisempty(tag)) Protect(luaV_finishget(L, rb, rc, ra, tag)); vmbreak; } vmcase(OP_SETTABUP) { int hres; TValue *upval = cl->upvals[GETARG_A(i)]->v.p; TValue *rb = KB(i); TValue *rc = RKC(i); TString *key = tsvalue(rb); /* key must be a short string */ luaV_fastset(upval, key, rc, hres, luaH_psetshortstr); if (hres == HOK) luaV_finishfastset(L, upval, rc); else Protect(luaV_finishset(L, upval, rb, rc, hres)); vmbreak; } vmcase(OP_SETTABLE) { StkId ra = RA(i); int hres; TValue *rb = vRB(i); /* key (table is in 'ra') */ TValue *rc = RKC(i); /* value */ if (ttisinteger(rb)) { /* fast track for integers? */ luaV_fastseti(s2v(ra), ivalue(rb), rc, hres); } else { luaV_fastset(s2v(ra), rb, rc, hres, luaH_pset); } if (hres == HOK) luaV_finishfastset(L, s2v(ra), rc); else Protect(luaV_finishset(L, s2v(ra), rb, rc, hres)); vmbreak; } vmcase(OP_SETI) { StkId ra = RA(i); int hres; int b = GETARG_B(i); TValue *rc = RKC(i); luaV_fastseti(s2v(ra), b, rc, hres); if (hres == HOK) luaV_finishfastset(L, s2v(ra), rc); else { TValue key; setivalue(&key, b); Protect(luaV_finishset(L, s2v(ra), &key, rc, hres)); } vmbreak; } vmcase(OP_SETFIELD) { StkId ra = RA(i); int hres; TValue *rb = KB(i); TValue *rc = RKC(i); TString *key = tsvalue(rb); /* key must be a short string */ luaV_fastset(s2v(ra), key, rc, hres, luaH_psetshortstr); if (hres == HOK) luaV_finishfastset(L, s2v(ra), rc); else Protect(luaV_finishset(L, s2v(ra), rb, rc, hres)); vmbreak; } vmcase(OP_NEWTABLE) { StkId ra = RA(i); unsigned b = cast_uint(GETARG_vB(i)); /* log2(hash size) + 1 */ unsigned c = cast_uint(GETARG_vC(i)); /* array size */ Table *t; if (b > 0) b = 1u << (b - 1); /* hash size is 2^(b - 1) */ if (TESTARG_k(i)) { /* non-zero extra argument? */ lua_assert(GETARG_Ax(*pc) != 0); /* add it to array size */ c += cast_uint(GETARG_Ax(*pc)) * (MAXARG_vC + 1); } pc++; /* skip extra argument */ L->top.p = ra + 1; /* correct top in case of emergency GC */ t = luaH_new(L); /* memory allocation */ sethvalue2s(L, ra, t); if (b != 0 || c != 0) luaH_resize(L, t, c, b); /* idem */ checkGC(L, ra + 1); vmbreak; } vmcase(OP_SELF) { StkId ra = RA(i); lu_byte tag; TValue *rb = vRB(i); TValue *rc = KC(i); TString *key = tsvalue(rc); /* key must be a short string */ setobj2s(L, ra + 1, rb); luaV_fastget(rb, key, s2v(ra), luaH_getshortstr, tag); if (tagisempty(tag)) Protect(luaV_finishget(L, rb, rc, ra, tag)); vmbreak; } vmcase(OP_ADDI) { op_arithI(L, l_addi, luai_numadd); vmbreak; } vmcase(OP_ADDK) { op_arithK(L, l_addi, luai_numadd); vmbreak; } vmcase(OP_SUBK) { op_arithK(L, l_subi, luai_numsub); vmbreak; } vmcase(OP_MULK) { op_arithK(L, l_muli, luai_nummul); vmbreak; } vmcase(OP_MODK) { savestate(L, ci); /* in case of division by 0 */ op_arithK(L, luaV_mod, luaV_modf); vmbreak; } vmcase(OP_POWK) { op_arithfK(L, luai_numpow); vmbreak; } vmcase(OP_DIVK) { op_arithfK(L, luai_numdiv); vmbreak; } vmcase(OP_IDIVK) { savestate(L, ci); /* in case of division by 0 */ op_arithK(L, luaV_idiv, luai_numidiv); vmbreak; } vmcase(OP_BANDK) { op_bitwiseK(L, l_band); vmbreak; } vmcase(OP_BORK) { op_bitwiseK(L, l_bor); vmbreak; } vmcase(OP_BXORK) { op_bitwiseK(L, l_bxor); vmbreak; } vmcase(OP_SHLI) { StkId ra = RA(i); TValue *rb = vRB(i); int ic = GETARG_sC(i); lua_Integer ib; if (tointegerns(rb, &ib)) { pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib)); } vmbreak; } vmcase(OP_SHRI) { StkId ra = RA(i); TValue *rb = vRB(i); int ic = GETARG_sC(i); lua_Integer ib; if (tointegerns(rb, &ib)) { pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic)); } vmbreak; } vmcase(OP_ADD) { op_arith(L, l_addi, luai_numadd); vmbreak; } vmcase(OP_SUB) { op_arith(L, l_subi, luai_numsub); vmbreak; } vmcase(OP_MUL) { op_arith(L, l_muli, luai_nummul); vmbreak; } vmcase(OP_MOD) { savestate(L, ci); /* in case of division by 0 */ op_arith(L, luaV_mod, luaV_modf); vmbreak; } vmcase(OP_POW) { op_arithf(L, luai_numpow); vmbreak; } vmcase(OP_DIV) { /* float division (always with floats) */ op_arithf(L, luai_numdiv); vmbreak; } vmcase(OP_IDIV) { /* floor division */ savestate(L, ci); /* in case of division by 0 */ op_arith(L, luaV_idiv, luai_numidiv); vmbreak; } vmcase(OP_BAND) { op_bitwise(L, l_band); vmbreak; } vmcase(OP_BOR) { op_bitwise(L, l_bor); vmbreak; } vmcase(OP_BXOR) { op_bitwise(L, l_bxor); vmbreak; } vmcase(OP_SHL) { op_bitwise(L, luaV_shiftl); vmbreak; } vmcase(OP_SHR) { op_bitwise(L, luaV_shiftr); vmbreak; } vmcase(OP_MMBIN) { StkId ra = RA(i); Instruction pi = *(pc - 2); /* original arith. expression */ TValue *rb = vRB(i); TMS tm = (TMS)GETARG_C(i); StkId result = RA(pi); lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR); Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm)); vmbreak; } vmcase(OP_MMBINI) { StkId ra = RA(i); Instruction pi = *(pc - 2); /* original arith. expression */ int imm = GETARG_sB(i); TMS tm = (TMS)GETARG_C(i); int flip = GETARG_k(i); StkId result = RA(pi); Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm)); vmbreak; } vmcase(OP_MMBINK) { StkId ra = RA(i); Instruction pi = *(pc - 2); /* original arith. expression */ TValue *imm = KB(i); TMS tm = (TMS)GETARG_C(i); int flip = GETARG_k(i); StkId result = RA(pi); Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm)); vmbreak; } vmcase(OP_UNM) { StkId ra = RA(i); TValue *rb = vRB(i); lua_Number nb; if (ttisinteger(rb)) { lua_Integer ib = ivalue(rb); setivalue(s2v(ra), intop(-, 0, ib)); } else if (tonumberns(rb, nb)) { setfltvalue(s2v(ra), luai_numunm(L, nb)); } else Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM)); vmbreak; } vmcase(OP_BNOT) { StkId ra = RA(i); TValue *rb = vRB(i); lua_Integer ib; if (tointegerns(rb, &ib)) { setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib)); } else Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT)); vmbreak; } vmcase(OP_NOT) { StkId ra = RA(i); TValue *rb = vRB(i); if (l_isfalse(rb)) setbtvalue(s2v(ra)); else setbfvalue(s2v(ra)); vmbreak; } vmcase(OP_LEN) { StkId ra = RA(i); Protect(luaV_objlen(L, ra, vRB(i))); vmbreak; } vmcase(OP_CONCAT) { StkId ra = RA(i); int n = GETARG_B(i); /* number of elements to concatenate */ L->top.p = ra + n; /* mark the end of concat operands */ ProtectNT(luaV_concat(L, n)); checkGC(L, L->top.p); /* 'luaV_concat' ensures correct top */ vmbreak; } vmcase(OP_CLOSE) { StkId ra = RA(i); lua_assert(!GETARG_B(i)); /* 'close must be alive */ Protect(luaF_close(L, ra, LUA_OK, 1)); vmbreak; } vmcase(OP_TBC) { StkId ra = RA(i); /* create new to-be-closed upvalue */ halfProtect(luaF_newtbcupval(L, ra)); vmbreak; } vmcase(OP_JMP) { dojump(ci, i, 0); vmbreak; } vmcase(OP_EQ) { StkId ra = RA(i); int cond; TValue *rb = vRB(i); Protect(cond = luaV_equalobj(L, s2v(ra), rb)); docondjump(); vmbreak; } vmcase(OP_LT) { op_order(L, l_lti, LTnum, lessthanothers); vmbreak; } vmcase(OP_LE) { op_order(L, l_lei, LEnum, lessequalothers); vmbreak; } vmcase(OP_EQK) { StkId ra = RA(i); TValue *rb = KB(i); /* basic types do not use '__eq'; we can use raw equality */ int cond = luaV_rawequalobj(s2v(ra), rb); docondjump(); vmbreak; } vmcase(OP_EQI) { StkId ra = RA(i); int cond; int im = GETARG_sB(i); if (ttisinteger(s2v(ra))) cond = (ivalue(s2v(ra)) == im); else if (ttisfloat(s2v(ra))) cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im)); else cond = 0; /* other types cannot be equal to a number */ docondjump(); vmbreak; } vmcase(OP_LTI) { op_orderI(L, l_lti, luai_numlt, 0, TM_LT); vmbreak; } vmcase(OP_LEI) { op_orderI(L, l_lei, luai_numle, 0, TM_LE); vmbreak; } vmcase(OP_GTI) { op_orderI(L, l_gti, luai_numgt, 1, TM_LT); vmbreak; } vmcase(OP_GEI) { op_orderI(L, l_gei, luai_numge, 1, TM_LE); vmbreak; } vmcase(OP_TEST) { StkId ra = RA(i); int cond = !l_isfalse(s2v(ra)); docondjump(); vmbreak; } vmcase(OP_TESTSET) { StkId ra = RA(i); TValue *rb = vRB(i); if (l_isfalse(rb) == GETARG_k(i)) pc++; else { setobj2s(L, ra, rb); donextjump(ci); } vmbreak; } vmcase(OP_CALL) { StkId ra = RA(i); CallInfo *newci; int b = GETARG_B(i); int nresults = GETARG_C(i) - 1; if (b != 0) /* fixed number of arguments? */ L->top.p = ra + b; /* top signals number of arguments */ /* else previous instruction set top */ savepc(ci); /* in case of errors */ if ((newci = luaD_precall(L, ra, nresults)) == NULL) updatetrap(ci); /* C call; nothing else to be done */ else { /* Lua call: run function in this same C frame */ ci = newci; goto startfunc; } vmbreak; } vmcase(OP_TAILCALL) { StkId ra = RA(i); int b = GETARG_B(i); /* number of arguments + 1 (function) */ int n; /* number of results when calling a C function */ int nparams1 = GETARG_C(i); /* delta is virtual 'func' - real 'func' (vararg functions) */ int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0; if (b != 0) L->top.p = ra + b; else /* previous instruction set top */ b = cast_int(L->top.p - ra); savepc(ci); /* several calls here can raise errors */ if (TESTARG_k(i)) { luaF_closeupval(L, base); /* close upvalues from current call */ lua_assert(L->tbclist.p < base); /* no pending tbc variables */ lua_assert(base == ci->func.p + 1); } if ((n = luaD_pretailcall(L, ci, ra, b, delta)) < 0) /* Lua function? */ goto startfunc; /* execute the callee */ else { /* C function? */ ci->func.p -= delta; /* restore 'func' (if vararg) */ luaD_poscall(L, ci, n); /* finish caller */ updatetrap(ci); /* 'luaD_poscall' can change hooks */ goto ret; /* caller returns after the tail call */ } } vmcase(OP_RETURN) { StkId ra = RA(i); int n = GETARG_B(i) - 1; /* number of results */ int nparams1 = GETARG_C(i); if (n < 0) /* not fixed? */ n = cast_int(L->top.p - ra); /* get what is available */ savepc(ci); if (TESTARG_k(i)) { /* may there be open upvalues? */ ci->u2.nres = n; /* save number of returns */ if (L->top.p < ci->top.p) L->top.p = ci->top.p; luaF_close(L, base, CLOSEKTOP, 1); updatetrap(ci); updatestack(ci); } if (nparams1) /* vararg function? */ ci->func.p -= ci->u.l.nextraargs + nparams1; L->top.p = ra + n; /* set call for 'luaD_poscall' */ luaD_poscall(L, ci, n); updatetrap(ci); /* 'luaD_poscall' can change hooks */ goto ret; } vmcase(OP_RETURN0) { if (l_unlikely(L->hookmask)) { StkId ra = RA(i); L->top.p = ra; savepc(ci); luaD_poscall(L, ci, 0); /* no hurry... */ trap = 1; } else { /* do the 'poscall' here */ int nres = get_nresults(ci->callstatus); L->ci = ci->previous; /* back to caller */ L->top.p = base - 1; for (; l_unlikely(nres > 0); nres--) setnilvalue(s2v(L->top.p++)); /* all results are nil */ } goto ret; } vmcase(OP_RETURN1) { if (l_unlikely(L->hookmask)) { StkId ra = RA(i); L->top.p = ra + 1; savepc(ci); luaD_poscall(L, ci, 1); /* no hurry... */ trap = 1; } else { /* do the 'poscall' here */ int nres = get_nresults(ci->callstatus); L->ci = ci->previous; /* back to caller */ if (nres == 0) L->top.p = base - 1; /* asked for no results */ else { StkId ra = RA(i); setobjs2s(L, base - 1, ra); /* at least this result */ L->top.p = base; for (; l_unlikely(nres > 1); nres--) setnilvalue(s2v(L->top.p++)); /* complete missing results */ } } ret: /* return from a Lua function */ if (ci->callstatus & CIST_FRESH) return; /* end this frame */ else { ci = ci->previous; goto returning; /* continue running caller in this frame */ } } vmcase(OP_FORLOOP) { StkId ra = RA(i); if (ttisinteger(s2v(ra + 1))) { /* integer loop? */ lua_Unsigned count = l_castS2U(ivalue(s2v(ra))); if (count > 0) { /* still more iterations? */ lua_Integer step = ivalue(s2v(ra + 1)); lua_Integer idx = ivalue(s2v(ra + 2)); /* control variable */ chgivalue(s2v(ra), l_castU2S(count - 1)); /* update counter */ idx = intop(+, idx, step); /* add step to index */ chgivalue(s2v(ra + 2), idx); /* update control variable */ pc -= GETARG_Bx(i); /* jump back */ } } else if (floatforloop(ra)) /* float loop */ pc -= GETARG_Bx(i); /* jump back */ updatetrap(ci); /* allows a signal to break the loop */ vmbreak; } vmcase(OP_FORPREP) { StkId ra = RA(i); savestate(L, ci); /* in case of errors */ if (forprep(L, ra)) pc += GETARG_Bx(i) + 1; /* skip the loop */ vmbreak; } vmcase(OP_TFORPREP) { /* before: 'ra' has the iterator function, 'ra + 1' has the state, 'ra + 2' has the initial value for the control variable, and 'ra + 3' has the closing variable. This opcode then swaps the control and the closing variables and marks the closing variable as to-be-closed. */ StkId ra = RA(i); TValue temp; /* to swap control and closing variables */ setobj(L, &temp, s2v(ra + 3)); setobjs2s(L, ra + 3, ra + 2); setobj2s(L, ra + 2, &temp); /* create to-be-closed upvalue (if closing var. is not nil) */ halfProtect(luaF_newtbcupval(L, ra + 2)); pc += GETARG_Bx(i); /* go to end of the loop */ i = *(pc++); /* fetch next instruction */ lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i)); goto l_tforcall; } vmcase(OP_TFORCALL) { l_tforcall: { /* 'ra' has the iterator function, 'ra + 1' has the state, 'ra + 2' has the closing variable, and 'ra + 3' has the control variable. The call will use the stack starting at 'ra + 3', so that it preserves the first three values, and the first return will be the new value for the control variable. */ StkId ra = RA(i); setobjs2s(L, ra + 5, ra + 3); /* copy the control variable */ setobjs2s(L, ra + 4, ra + 1); /* copy state */ setobjs2s(L, ra + 3, ra); /* copy function */ L->top.p = ra + 3 + 3; ProtectNT(luaD_call(L, ra + 3, GETARG_C(i))); /* do the call */ updatestack(ci); /* stack may have changed */ i = *(pc++); /* go to next instruction */ lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i)); goto l_tforloop; }} vmcase(OP_TFORLOOP) { l_tforloop: { StkId ra = RA(i); if (!ttisnil(s2v(ra + 3))) /* continue loop? */ pc -= GETARG_Bx(i); /* jump back */ vmbreak; }} vmcase(OP_SETLIST) { StkId ra = RA(i); unsigned n = cast_uint(GETARG_vB(i)); unsigned last = cast_uint(GETARG_vC(i)); Table *h = hvalue(s2v(ra)); if (n == 0) n = cast_uint(L->top.p - ra) - 1; /* get up to the top */ else L->top.p = ci->top.p; /* correct top in case of emergency GC */ last += n; if (TESTARG_k(i)) { last += cast_uint(GETARG_Ax(*pc)) * (MAXARG_vC + 1); pc++; } /* when 'n' is known, table should have proper size */ if (last > h->asize) { /* needs more space? */ /* fixed-size sets should have space preallocated */ lua_assert(GETARG_vB(i) == 0); luaH_resizearray(L, h, last); /* preallocate it at once */ } for (; n > 0; n--) { TValue *val = s2v(ra + n); obj2arr(h, last - 1, val); last--; luaC_barrierback(L, obj2gco(h), val); } vmbreak; } vmcase(OP_CLOSURE) { StkId ra = RA(i); Proto *p = cl->p->p[GETARG_Bx(i)]; halfProtect(pushclosure(L, p, cl->upvals, base, ra)); checkGC(L, ra + 1); vmbreak; } vmcase(OP_VARARG) { StkId ra = RA(i); int n = GETARG_C(i) - 1; /* required results (-1 means all) */ int vatab = GETARG_k(i) ? GETARG_B(i) : -1; Protect(luaT_getvarargs(L, ci, ra, n, vatab)); vmbreak; } vmcase(OP_GETVARG) { StkId ra = RA(i); TValue *rc = vRC(i); luaT_getvararg(ci, ra, rc); vmbreak; } vmcase(OP_ERRNNIL) { TValue *ra = vRA(i); if (!ttisnil(ra)) halfProtect(luaG_errnnil(L, cl, GETARG_Bx(i))); vmbreak; } vmcase(OP_VARARGPREP) { ProtectNT(luaT_adjustvarargs(L, ci, cl->p)); if (l_unlikely(trap)) { /* previous "Protect" updated trap */ luaD_hookcall(L, ci); L->oldpc = 1; /* next opcode will be seen as a "new" line */ } updatebase(ci); /* function has new base after adjustment */ vmbreak; } vmcase(OP_EXTRAARG) { lua_assert(0); vmbreak; } } } } /* }================================================================== */ /* ** $Id: lzio.c $ ** Buffered streams ** See Copyright Notice in lua.h */ #define lzio_c #define LUA_CORE #include #include "lua.h" int luaZ_fill (ZIO *z) { size_t size; lua_State *L = z->L; const char *buff; lua_unlock(L); buff = z->reader(L, z->data, &size); lua_lock(L); if (buff == NULL || size == 0) return EOZ; z->n = size - 1; /* discount char being returned */ z->p = buff; return cast_uchar(*(z->p++)); } void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { z->L = L; z->reader = reader; z->data = data; z->n = 0; z->p = NULL; } /* --------------------------------------------------------------- read --- */ static int checkbuffer (ZIO *z) { if (z->n == 0) { /* no bytes in buffer? */ if (luaZ_fill(z) == EOZ) /* try to read more */ return 0; /* no more input */ else { z->n++; /* luaZ_fill consumed first byte; put it back */ z->p--; } } return 1; /* now buffer has something */ } size_t luaZ_read (ZIO *z, void *b, size_t n) { while (n) { size_t m; if (!checkbuffer(z)) return n; /* no more input; return number of missing bytes */ m = (n <= z->n) ? n : z->n; /* min. between n and z->n */ memcpy(b, z->p, m); z->n -= m; z->p += m; b = (char *)b + m; n -= m; } return 0; } const void *luaZ_getaddr (ZIO* z, size_t n) { const void *res; if (!checkbuffer(z)) return NULL; /* no more input */ if (z->n < n) /* not enough bytes? */ return NULL; /* block not whole; cannot give an address */ res = z->p; /* get block address */ z->n -= n; /* consume these bytes */ z->p += n; return res; } /* ** $Id: loslib.c $ ** Standard Operating System library ** See Copyright Notice in lua.h */ #define loslib_c #define LUA_LIB #include #include #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" #ifdef NO_TIMEFUNCS #include #endif /* ** {================================================================== ** List of valid conversion specifiers for the 'strftime' function; ** options are grouped by length; group of length 2 start with '||'. ** =================================================================== */ #if !defined(LUA_STRFTIMEOPTIONS) /* { */ #if defined(LUA_USE_WINDOWS) #define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYzZ%" \ "||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */ #elif defined(LUA_USE_C89) /* C89 (only 1-char options) */ #define LUA_STRFTIMEOPTIONS "aAbBcdHIjmMpSUwWxXyYZ%" #else /* C99 specification */ #define LUA_STRFTIMEOPTIONS "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \ "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */ #endif #endif /* } */ /* }================================================================== */ /* ** {================================================================== ** Configuration for time-related stuff ** =================================================================== */ #ifdef BA_MINIOSLIB static int os_clock (lua_State *L) { lua_pushnumber(L, baGetMsClock()/1000); return 1; } #define l_gmtime(t,r) gmtime(t) #define l_localtime(t,r) localtime(t) #endif /* ** type to represent time_t in Lua */ #if !defined(LUA_NUMTIME) /* { */ #define l_timet lua_Integer #define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t)) #define l_gettime(L,arg) luaL_checkinteger(L, arg) #else /* }{ */ #define l_timet lua_Number #define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t)) #define l_gettime(L,arg) luaL_checknumber(L, arg) #endif /* } */ #if !defined(l_gmtime) /* { */ /* ** By default, Lua uses gmtime/localtime, except when POSIX is available, ** where it uses gmtime_r/localtime_r */ #if defined(LUA_USE_POSIX) /* { */ #define l_gmtime(t,r) gmtime_r(t,r) #define l_localtime(t,r) localtime_r(t,r) #else /* }{ */ /* ISO C definitions */ #define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t)) #define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t)) #endif /* } */ #endif /* } */ /* }================================================================== */ #ifndef BA_MINIOSLIB /* ** {================================================================== ** Configuration for 'tmpnam': ** By default, Lua uses tmpnam except when POSIX is available, where ** it uses mkstemp. ** =================================================================== */ #if !defined(lua_tmpnam) /* { */ #if defined(LUA_USE_POSIX) /* { */ #include #define LUA_TMPNAMBUFSIZE 32 #if !defined(LUA_TMPNAMTEMPLATE) #define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX" #endif #define lua_tmpnam(b,e) { \ strcpy(b, LUA_TMPNAMTEMPLATE); \ e = mkstemp(b); \ if (e != -1) close(e); \ e = (e == -1); } #else /* }{ */ /* ISO C definitions */ #define LUA_TMPNAMBUFSIZE L_tmpnam #define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } #endif /* } */ #endif /* } */ /* }================================================================== */ #if !defined(l_system) #if defined(LUA_USE_IOS) /* Despite claiming to be ISO C, iOS does not implement 'system'. */ #define l_system(cmd) ((cmd) == NULL ? 0 : -1) #else #define l_system(cmd) system(cmd) /* default definition */ #endif #endif static int os_execute (lua_State *L) { const char *cmd = luaL_optstring(L, 1, NULL); int stat; errno = 0; stat = l_system(cmd); if (cmd != NULL) return luaL_execresult(L, stat); else { lua_pushboolean(L, stat); /* true if there is a shell */ return 1; } } static int os_remove (lua_State *L) { const char *filename = luaL_checkstring(L, 1); errno = 0; return luaL_fileresult(L, remove(filename) == 0, filename); } static int os_rename (lua_State *L) { const char *fromname = luaL_checkstring(L, 1); const char *toname = luaL_checkstring(L, 2); errno = 0; return luaL_fileresult(L, rename(fromname, toname) == 0, NULL); } static int os_tmpname (lua_State *L) { char buff[LUA_TMPNAMBUFSIZE]; int err; lua_tmpnam(buff, err); if (l_unlikely(err)) return luaL_error(L, "unable to generate a unique filename"); lua_pushstring(L, buff); return 1; } static int os_getenv (lua_State *L) { lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ return 1; } static int os_clock (lua_State *L) { lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); return 1; } #endif /* BA_MINIOSLIB */ #ifndef NO_TIMEFUNCS /* ** {====================================================== ** Time/Date operations ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, ** wday=%w+1, yday=%j, isdst=? } ** ======================================================= */ /* ** About the overflow check: an overflow cannot occur when time ** is represented by a lua_Integer, because either lua_Integer is ** large enough to represent all int fields or it is not large enough ** to represent a time that cause a field to overflow. However, if ** times are represented as doubles and lua_Integer is int, then the ** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900 ** to compute the year. */ static void setfield (lua_State *L, const char *key, int value, int delta) { #if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX) if (l_unlikely(value > LUA_MAXINTEGER - delta)) luaL_error(L, "field '%s' is out-of-bound", key); #endif lua_pushinteger(L, (lua_Integer)value + delta); lua_setfield(L, -2, key); } static void setboolfield (lua_State *L, const char *key, int value) { if (value < 0) /* undefined? */ return; /* does not set field */ lua_pushboolean(L, value); lua_setfield(L, -2, key); } /* ** Set all fields from structure 'tm' in the table on top of the stack */ static void setallfields (lua_State *L, struct tm *stm) { setfield(L, "year", stm->tm_year, 1900); setfield(L, "month", stm->tm_mon, 1); setfield(L, "day", stm->tm_mday, 0); setfield(L, "hour", stm->tm_hour, 0); setfield(L, "min", stm->tm_min, 0); setfield(L, "sec", stm->tm_sec, 0); setfield(L, "yday", stm->tm_yday, 1); setfield(L, "wday", stm->tm_wday, 1); setboolfield(L, "isdst", stm->tm_isdst); } #endif /* NO_TIMEFUNCS */ static int getboolfield (lua_State *L, const char *key) { int res; res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1); lua_pop(L, 1); return res; } static int getfield (lua_State *L, const char *key, int d, int delta) { int isnum; int t = lua_getfield(L, -1, key); /* get field and its type */ lua_Integer res = lua_tointegerx(L, -1, &isnum); if (!isnum) { /* field is not an integer? */ if (l_unlikely(t != LUA_TNIL)) /* some other value? */ return luaL_error(L, "field '%s' is not an integer", key); else if (l_unlikely(d < 0)) /* absent field; no default? */ return luaL_error(L, "field '%s' missing in date table", key); res = d; } else { if (!(res >= 0 ? res - delta <= INT_MAX : INT_MIN + delta <= res)) return luaL_error(L, "field '%s' is out-of-bound", key); res -= delta; } lua_pop(L, 1); return (int)res; } #ifndef NO_TIMEFUNCS static const char *checkoption (lua_State *L, const char *conv, size_t convlen, char *buff) { const char *option = LUA_STRFTIMEOPTIONS; unsigned oplen = 1; /* length of options being checked */ for (; *option != '\0' && oplen <= convlen; option += oplen) { if (*option == '|') /* next block? */ oplen++; /* will check options with next length (+1) */ else if (memcmp(conv, option, oplen) == 0) { /* match? */ memcpy(buff, conv, oplen); /* copy valid option to buffer */ buff[oplen] = '\0'; return conv + oplen; /* return next item */ } } luaL_argerror(L, 1, lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv)); return conv; /* to avoid warnings */ } static time_t l_checktime (lua_State *L, int arg) { l_timet t = l_gettime(L, arg); luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds"); return (time_t)t; } /* maximum size for an individual 'strftime' item */ #define SIZETIMEFMT 250 static int os_date (lua_State *L) { size_t slen; const char *s = luaL_optlstring(L, 1, "%c", &slen); time_t t = luaL_opt(L, l_checktime, 2, time(NULL)); const char *se = s + slen; /* 's' end */ struct tm tmr, *stm; if (*s == '!') { /* UTC? */ stm = l_gmtime(&t, &tmr); s++; /* skip '!' */ } else stm = l_localtime(&t, &tmr); (void)tmr; /* remove compile warning */ if (stm == NULL) /* invalid date? */ return luaL_error(L, "date result cannot be represented in this installation"); if (strcmp(s, "*t") == 0) { lua_createtable(L, 0, 9); /* 9 = number of fields */ setallfields(L, stm); } else { char cc[4]; /* buffer for individual conversion specifiers */ luaL_Buffer b; cc[0] = '%'; luaL_buffinit(L, &b); while (s < se) { if (*s != '%') /* not a conversion specifier? */ luaL_addchar(&b, *s++); else { size_t reslen; char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); s++; /* skip '%' */ /* copy specifier to 'cc' */ s = checkoption(L, s, ct_diff2sz(se - s), cc + 1); reslen = strftime(buff, SIZETIMEFMT, cc, stm); luaL_addsize(&b, reslen); } } luaL_pushresult(&b); } return 1; } static int os_time (lua_State *L) { time_t t; if (lua_isnoneornil(L, 1)) /* called without args? */ t = time(NULL); /* get current time */ else { struct tm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ ts.tm_year = getfield(L, "year", -1, 1900); ts.tm_mon = getfield(L, "month", -1, 1); ts.tm_mday = getfield(L, "day", -1, 0); ts.tm_hour = getfield(L, "hour", 12, 0); ts.tm_min = getfield(L, "min", 0, 0); ts.tm_sec = getfield(L, "sec", 0, 0); ts.tm_isdst = getboolfield(L, "isdst"); t = mktime(&ts); setallfields(L, &ts); /* update fields with normalized values */ } if (t != (time_t)(l_timet)t || t == (time_t)(-1)) return luaL_error(L, "time result cannot be represented in this installation"); l_pushtime(L, t); return 1; } #else /* NO_TIMEFUNCS */ static int os_time (lua_State *L) { time_t t; if (lua_isnoneornil(L, 1)) /* called without args? */ t = baGetUnixTime(); /* get current time */ else { struct BaTm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ ts.tm_sec = getfield(L, "sec", 0, 0); ts.tm_min = getfield(L, "min", 0, 0); ts.tm_hour = getfield(L, "hour", 12, 0); ts.tm_mday = getfield(L, "day", -1, 0); ts.tm_mon = getfield(L, "month", -1, 1); ts.tm_year = getfield(L, "year", -1, 1900); ts.tm_isdst = getboolfield(L, "isdst"); t = baTm2Time(&ts); } lua_pushnumber(L, (lua_Number)t); return 1; } #endif /* NO_TIMEFUNCS */ #ifndef BA_MINIOSLIB static int os_difftime (lua_State *L) { time_t t1 = l_checktime(L, 1); time_t t2 = l_checktime(L, 2); lua_pushnumber(L, (lua_Number)difftime(t1, t2)); return 1; } #endif /* }====================================================== */ #ifndef BA_MINIOSLIB static int os_setlocale (lua_State *L) { static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME}; static const char *const catnames[] = {"all", "collate", "ctype", "monetary", "numeric", "time", NULL}; const char *l = luaL_optstring(L, 1, NULL); int op = luaL_checkoption(L, 2, "all", catnames); lua_pushstring(L, setlocale(cat[op], l)); return 1; } static int os_exit (lua_State *L) { #ifdef NO_BA_SERVER int status; if (lua_isboolean(L, 1)) status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE); else status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS); if (lua_toboolean(L, 2)) lua_close(L); if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */ #else luaL_error(L, "No exit"); #endif return 0; } #endif /* BA_MINIOSLIB */ static const luaL_Reg syslib[] = { {"clock", os_clock}, #ifndef NO_TIMEFUNCS {"date", os_date}, #endif #ifndef BA_MINIOSLIB {"difftime", os_difftime}, {"execute", os_execute}, {"exit", os_exit}, {"getenv", os_getenv}, {"remove", os_remove}, {"rename", os_rename}, {"setlocale", os_setlocale}, {"tmpname", os_tmpname}, #endif {"time", os_time}, {NULL, NULL} }; /* }====================================================== */ LUAMOD_API int luaopen_os (lua_State *L) { luaL_newlib(L, syslib); return 1; } /* ** $Id: lmathlib.c $ ** Standard mathematical library ** See Copyright Notice in lua.h */ #define lmathlib_c #define LUA_LIB #include #include #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" #undef PI #define PI (l_mathop(3.141592653589793238462643383279502884)) static int math_abs (lua_State *L) { if (lua_isinteger(L, 1)) { lua_Integer n = lua_tointeger(L, 1); if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n); lua_pushinteger(L, n); } else lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1))); return 1; } static int math_sin (lua_State *L) { lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1))); return 1; } static int math_cos (lua_State *L) { lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1))); return 1; } static int math_tan (lua_State *L) { lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1))); return 1; } static int math_asin (lua_State *L) { lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1))); return 1; } static int math_acos (lua_State *L) { lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1))); return 1; } static int math_atan (lua_State *L) { lua_Number y = luaL_checknumber(L, 1); lua_Number x = luaL_optnumber(L, 2, 1); lua_pushnumber(L, l_mathop(atan2)(y, x)); return 1; } static int math_toint (lua_State *L) { int valid; lua_Integer n = lua_tointegerx(L, 1, &valid); if (l_likely(valid)) lua_pushinteger(L, n); else { luaL_checkany(L, 1); luaL_pushfail(L); /* value is not convertible to integer */ } return 1; } static void pushnumint (lua_State *L, lua_Number d) { lua_Integer n; if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */ lua_pushinteger(L, n); /* result is integer */ else lua_pushnumber(L, d); /* result is float */ } static int math_floor (lua_State *L) { if (lua_isinteger(L, 1)) lua_settop(L, 1); /* integer is its own floor */ else { lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1)); pushnumint(L, d); } return 1; } static int math_ceil (lua_State *L) { if (lua_isinteger(L, 1)) lua_settop(L, 1); /* integer is its own ceiling */ else { lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1)); pushnumint(L, d); } return 1; } static int math_fmod (lua_State *L) { if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) { lua_Integer d = lua_tointeger(L, 2); if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */ luaL_argcheck(L, d != 0, 2, "zero"); lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */ } else lua_pushinteger(L, lua_tointeger(L, 1) % d); } else lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); return 1; } /* ** next function does not use 'modf', avoiding problems with 'double*' ** (which is not compatible with 'float*') when lua_Number is not ** 'double'. */ static int math_modf (lua_State *L) { if (lua_isinteger(L ,1)) { lua_settop(L, 1); /* number is its own integer part */ lua_pushnumber(L, 0); /* no fractional part */ } else { lua_Number n = luaL_checknumber(L, 1); /* integer part (rounds toward zero) */ lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n); pushnumint(L, ip); /* fractional part (test needed for inf/-inf) */ lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip)); } return 2; } static int math_sqrt (lua_State *L) { lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1))); return 1; } static int math_ult (lua_State *L) { lua_Integer a = luaL_checkinteger(L, 1); lua_Integer b = luaL_checkinteger(L, 2); lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b); return 1; } static int math_log (lua_State *L) { lua_Number x = luaL_checknumber(L, 1); lua_Number res; if (lua_isnoneornil(L, 2)) res = l_mathop(log)(x); else { lua_Number base = luaL_checknumber(L, 2); #if !defined(LUA_USE_C89) && !defined(NO_LOG2) if (base == l_mathop(2.0)) res = l_mathop(log2)(x); else #endif if (base == l_mathop(10.0)) res = l_mathop(log10)(x); else res = l_mathop(log)(x)/l_mathop(log)(base); } lua_pushnumber(L, res); return 1; } static int math_exp (lua_State *L) { lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1))); return 1; } static int math_deg (lua_State *L) { lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI)); return 1; } static int math_rad (lua_State *L) { lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0))); return 1; } static int math_frexp (lua_State *L) { lua_Number x = luaL_checknumber(L, 1); int ep; lua_pushnumber(L, l_mathop(frexp)(x, &ep)); lua_pushinteger(L, ep); return 2; } static int math_ldexp (lua_State *L) { lua_Number x = luaL_checknumber(L, 1); int ep = (int)luaL_checkinteger(L, 2); lua_pushnumber(L, l_mathop(ldexp)(x, ep)); return 1; } static int math_min (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int imin = 1; /* index of current minimum value */ int i; luaL_argcheck(L, n >= 1, 1, "value expected"); for (i = 2; i <= n; i++) { if (lua_compare(L, i, imin, LUA_OPLT)) imin = i; } lua_pushvalue(L, imin); return 1; } static int math_max (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int imax = 1; /* index of current maximum value */ int i; luaL_argcheck(L, n >= 1, 1, "value expected"); for (i = 2; i <= n; i++) { if (lua_compare(L, imax, i, LUA_OPLT)) imax = i; } lua_pushvalue(L, imax); return 1; } static int math_type (lua_State *L) { if (lua_type(L, 1) == LUA_TNUMBER) lua_pushstring(L, (lua_isinteger(L, 1)) ? "integer" : "float"); else { luaL_checkany(L, 1); luaL_pushfail(L); } return 1; } /* ** {================================================================== ** Pseudo-Random Number Generator based on 'xoshiro256**'. ** =================================================================== */ /* ** This code uses lots of shifts. ISO C does not allow shifts greater ** than or equal to the width of the type being shifted, so some shifts ** are written in convoluted ways to match that restriction. For ** preprocessor tests, it assumes a width of 32 bits, so the maximum ** shift there is 31 bits. */ /* number of binary digits in the mantissa of a float */ #define FIGS l_floatatt(MANT_DIG) #if FIGS > 64 /* there are only 64 random bits; use them all */ #undef FIGS #define FIGS 64 #endif /* ** LUA_RAND32 forces the use of 32-bit integers in the implementation ** of the PRN generator (mainly for testing). */ #if !defined(LUA_RAND32) && !defined(Rand64) /* try to find an integer type with at least 64 bits */ #if ((ULONG_MAX >> 31) >> 31) >= 3 /* 'long' has at least 64 bits */ #define Rand64 unsigned long #define SRand64 long #elif !defined(LUA_USE_C89) && defined(LLONG_MAX) /* there is a 'long long' type (which must have at least 64 bits) */ #define Rand64 unsigned long long #define SRand64 long long #elif ((LUA_MAXUNSIGNED >> 31) >> 31) >= 3 /* 'lua_Unsigned' has at least 64 bits */ #define Rand64 lua_Unsigned #define SRand64 lua_Integer #endif #endif #if defined(Rand64) /* { */ /* ** Standard implementation, using 64-bit integers. ** If 'Rand64' has more than 64 bits, the extra bits do not interfere ** with the 64 initial bits, except in a right shift. Moreover, the ** final result has to discard the extra bits. */ /* avoid using extra bits when needed */ #define trim64(x) ((x) & 0xffffffffffffffffu) /* rotate left 'x' by 'n' bits */ static Rand64 rotl (Rand64 x, int n) { return (x << n) | (trim64(x) >> (64 - n)); } static Rand64 nextrand (Rand64 *state) { Rand64 state0 = state[0]; Rand64 state1 = state[1]; Rand64 state2 = state[2] ^ state0; Rand64 state3 = state[3] ^ state1; Rand64 res = rotl(state1 * 5, 7) * 9; state[0] = state0 ^ state3; state[1] = state1 ^ state2; state[2] = state2 ^ (state1 << 17); state[3] = rotl(state3, 45); return res; } /* ** Convert bits from a random integer into a float in the ** interval [0,1), getting the higher FIG bits from the ** random unsigned integer and converting that to a float. ** Some old Microsoft compilers cannot cast an unsigned long ** to a floating-point number, so we use a signed long as an ** intermediary. When lua_Number is float or double, the shift ensures ** that 'sx' is non negative; in that case, a good compiler will remove ** the correction. */ /* must throw out the extra (64 - FIGS) bits */ #define shift64_FIG (64 - FIGS) /* 2^(-FIGS) == 2^-1 / 2^(FIGS-1) */ #define scaleFIG (l_mathop(0.5) / ((Rand64)1 << (FIGS - 1))) static lua_Number I2d (Rand64 x) { SRand64 sx = (SRand64)(trim64(x) >> shift64_FIG); lua_Number res = (lua_Number)(sx) * scaleFIG; if (sx < 0) res += l_mathop(1.0); /* correct the two's complement if negative */ lua_assert(0 <= res && res < 1); return res; } /* convert a 'Rand64' to a 'lua_Unsigned' */ #define I2UInt(x) ((lua_Unsigned)trim64(x)) /* convert a 'lua_Unsigned' to a 'Rand64' */ #define Int2I(x) ((Rand64)(x)) #else /* no 'Rand64' }{ */ /* ** Use two 32-bit integers to represent a 64-bit quantity. */ typedef struct Rand64 { l_uint32 h; /* higher half */ l_uint32 l; /* lower half */ } Rand64; /* ** If 'l_uint32' has more than 32 bits, the extra bits do not interfere ** with the 32 initial bits, except in a right shift and comparisons. ** Moreover, the final result has to discard the extra bits. */ /* avoid using extra bits when needed */ #define trim32(x) ((x) & 0xffffffffu) /* ** basic operations on 'Rand64' values */ /* build a new Rand64 value */ static Rand64 packI (l_uint32 h, l_uint32 l) { Rand64 result; result.h = h; result.l = l; return result; } /* return i << n */ static Rand64 Ishl (Rand64 i, int n) { lua_assert(n > 0 && n < 32); return packI((i.h << n) | (trim32(i.l) >> (32 - n)), i.l << n); } /* i1 ^= i2 */ static void Ixor (Rand64 *i1, Rand64 i2) { i1->h ^= i2.h; i1->l ^= i2.l; } /* return i1 + i2 */ static Rand64 Iadd (Rand64 i1, Rand64 i2) { Rand64 result = packI(i1.h + i2.h, i1.l + i2.l); if (trim32(result.l) < trim32(i1.l)) /* carry? */ result.h++; return result; } /* return i * 5 */ static Rand64 times5 (Rand64 i) { return Iadd(Ishl(i, 2), i); /* i * 5 == (i << 2) + i */ } /* return i * 9 */ static Rand64 times9 (Rand64 i) { return Iadd(Ishl(i, 3), i); /* i * 9 == (i << 3) + i */ } /* return 'i' rotated left 'n' bits */ static Rand64 rotl (Rand64 i, int n) { lua_assert(n > 0 && n < 32); return packI((i.h << n) | (trim32(i.l) >> (32 - n)), (trim32(i.h) >> (32 - n)) | (i.l << n)); } /* for offsets larger than 32, rotate right by 64 - offset */ static Rand64 rotl1 (Rand64 i, int n) { lua_assert(n > 32 && n < 64); n = 64 - n; return packI((trim32(i.h) >> n) | (i.l << (32 - n)), (i.h << (32 - n)) | (trim32(i.l) >> n)); } /* ** implementation of 'xoshiro256**' algorithm on 'Rand64' values */ static Rand64 nextrand (Rand64 *state) { Rand64 res = times9(rotl(times5(state[1]), 7)); Rand64 t = Ishl(state[1], 17); Ixor(&state[2], state[0]); Ixor(&state[3], state[1]); Ixor(&state[1], state[2]); Ixor(&state[0], state[3]); Ixor(&state[2], t); state[3] = rotl1(state[3], 45); return res; } /* ** Converts a 'Rand64' into a float. */ /* an unsigned 1 with proper type */ #define UONE ((l_uint32)1) #if FIGS <= 32 /* 2^(-FIGS) */ #define scaleFIG (l_mathop(0.5) / (UONE << (FIGS - 1))) /* ** get up to 32 bits from higher half, shifting right to ** throw out the extra bits. */ static lua_Number I2d (Rand64 x) { lua_Number h = (lua_Number)(trim32(x.h) >> (32 - FIGS)); return h * scaleFIG; } #else /* 32 < FIGS <= 64 */ /* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */ #define scaleFIG \ (l_mathop(1.0) / (UONE << 30) / l_mathop(8.0) / (UONE << (FIGS - 33))) /* ** use FIGS - 32 bits from lower half, throwing out the other ** (32 - (FIGS - 32)) = (64 - FIGS) bits */ #define shiftLOW (64 - FIGS) /* ** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32) */ #define shiftHI ((lua_Number)(UONE << (FIGS - 33)) * l_mathop(2.0)) static lua_Number I2d (Rand64 x) { lua_Number h = (lua_Number)trim32(x.h) * shiftHI; lua_Number l = (lua_Number)(trim32(x.l) >> shiftLOW); return (h + l) * scaleFIG; } #endif /* convert a 'Rand64' to a 'lua_Unsigned' */ static lua_Unsigned I2UInt (Rand64 x) { return (((lua_Unsigned)trim32(x.h) << 31) << 1) | (lua_Unsigned)trim32(x.l); } /* convert a 'lua_Unsigned' to a 'Rand64' */ static Rand64 Int2I (lua_Unsigned n) { return packI((l_uint32)((n >> 31) >> 1), (l_uint32)n); } #endif /* } */ /* ** A state uses four 'Rand64' values. */ typedef struct { Rand64 s[4]; } RanState; /* ** Project the random integer 'ran' into the interval [0, n]. ** Because 'ran' has 2^B possible values, the projection can only be ** uniform when the size of the interval is a power of 2 (exact ** division). So, to get a uniform projection into [0, n], we ** first compute 'lim', the smallest Mersenne number not smaller than ** 'n'. We then project 'ran' into the interval [0, lim]. If the result ** is inside [0, n], we are done. Otherwise, we try with another 'ran', ** until we have a result inside the interval. */ static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n, RanState *state) { lua_Unsigned lim = n; /* to compute the Mersenne number */ int sh; /* how much to spread bits to the right in 'lim' */ /* spread '1' bits in 'lim' until it becomes a Mersenne number */ for (sh = 1; (lim & (lim + 1)) != 0; sh *= 2) lim |= (lim >> sh); /* spread '1's to the right */ while ((ran &= lim) > n) /* project 'ran' into [0..lim] and test */ ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */ return ran; } static int math_random (lua_State *L) { lua_Integer low, up; lua_Unsigned p; RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); Rand64 rv = nextrand(state->s); /* next pseudo-random value */ switch (lua_gettop(L)) { /* check number of arguments */ case 0: { /* no arguments */ lua_pushnumber(L, I2d(rv)); /* float between 0 and 1 */ return 1; } case 1: { /* only upper limit */ low = 1; up = luaL_checkinteger(L, 1); if (up == 0) { /* single 0 as argument? */ lua_pushinteger(L, l_castU2S(I2UInt(rv))); /* full random integer */ return 1; } break; } case 2: { /* lower and upper limits */ low = luaL_checkinteger(L, 1); up = luaL_checkinteger(L, 2); break; } default: return luaL_error(L, "wrong number of arguments"); } /* random integer in the interval [low, up] */ luaL_argcheck(L, low <= up, 1, "interval is empty"); /* project random integer into the interval [0, up - low] */ p = project(I2UInt(rv), l_castS2U(up) - l_castS2U(low), state); lua_pushinteger(L, l_castU2S(p + l_castS2U(low))); return 1; } static void setseed (lua_State *L, Rand64 *state, lua_Unsigned n1, lua_Unsigned n2) { int i; state[0] = Int2I(n1); state[1] = Int2I(0xff); /* avoid a zero state */ state[2] = Int2I(n2); state[3] = Int2I(0); for (i = 0; i < 16; i++) nextrand(state); /* discard initial values to "spread" seed */ lua_pushinteger(L, l_castU2S(n1)); lua_pushinteger(L, l_castU2S(n2)); } static int math_randomseed (lua_State *L) { RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); lua_Unsigned n1, n2; if (lua_isnone(L, 1)) { n1 = luaL_makeseed(L); /* "random" seed */ n2 = I2UInt(nextrand(state->s)); /* in case seed is not that random... */ } else { n1 = l_castS2U(luaL_checkinteger(L, 1)); n2 = l_castS2U(luaL_optinteger(L, 2, 0)); } setseed(L, state->s, n1, n2); return 2; /* return seeds */ } static const luaL_Reg randfuncs[] = { {"random", math_random}, {"randomseed", math_randomseed}, {NULL, NULL} }; /* ** Register the random functions and initialize their state. */ static void setrandfunc (lua_State *L) { RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0); setseed(L, state->s, luaL_makeseed(L), 0); /* initialize with random seed */ lua_pop(L, 2); /* remove pushed seeds */ luaL_setfuncs(L, randfuncs, 1); } /* }================================================================== */ /* ** {================================================================== ** Deprecated functions (for compatibility only) ** =================================================================== */ #if defined(LUA_COMPAT_MATHLIB) static int math_cosh (lua_State *L) { lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1))); return 1; } static int math_sinh (lua_State *L) { lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1))); return 1; } static int math_tanh (lua_State *L) { lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1))); return 1; } static int math_pow (lua_State *L) { lua_Number x = luaL_checknumber(L, 1); lua_Number y = luaL_checknumber(L, 2); lua_pushnumber(L, l_mathop(pow)(x, y)); return 1; } static int math_log10 (lua_State *L) { lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1))); return 1; } #endif /* }================================================================== */ static const luaL_Reg mathlib[] = { {"abs", math_abs}, {"acos", math_acos}, {"asin", math_asin}, {"atan", math_atan}, {"ceil", math_ceil}, {"cos", math_cos}, {"deg", math_deg}, {"exp", math_exp}, {"tointeger", math_toint}, {"floor", math_floor}, {"fmod", math_fmod}, {"frexp", math_frexp}, {"ult", math_ult}, {"ldexp", math_ldexp}, {"log", math_log}, {"max", math_max}, {"min", math_min}, {"modf", math_modf}, {"rad", math_rad}, {"sin", math_sin}, {"sqrt", math_sqrt}, {"tan", math_tan}, {"type", math_type}, #if defined(LUA_COMPAT_MATHLIB) {"atan2", math_atan}, {"cosh", math_cosh}, {"sinh", math_sinh}, {"tanh", math_tanh}, {"pow", math_pow}, {"log10", math_log10}, #endif /* placeholders */ {"random", NULL}, {"randomseed", NULL}, {"pi", NULL}, {"huge", NULL}, {"maxinteger", NULL}, {"mininteger", NULL}, {NULL, NULL} }; /* ** Open math library */ LUAMOD_API int luaopen_math (lua_State *L) { luaL_newlib(L, mathlib); lua_pushnumber(L, PI); lua_setfield(L, -2, "pi"); lua_pushnumber(L, (lua_Number)HUGE_VAL); lua_setfield(L, -2, "huge"); lua_pushinteger(L, LUA_MAXINTEGER); lua_setfield(L, -2, "maxinteger"); lua_pushinteger(L, LUA_MININTEGER); lua_setfield(L, -2, "mininteger"); setrandfunc(L); return 1; } #if defined(LUA_NOIOLIB) || defined(BA_MINIOSLIB) #include LUAMOD_API int luaopen_io(lua_State *L) { lua_newtable(L); return 1; } #else /* ** $Id: liolib.c $ ** Standard I/O (and system) library ** See Copyright Notice in lua.h */ #define liolib_c #define LUA_LIB #include "balua.h" #include #include #include #include #include #include #include "lua.h" #include "lauxlib.h" #include "lualib.h" #ifdef LUA_NOIOLIB #error This file should not be included in the build #endif /* ** Change this macro to accept other modes for 'fopen' besides ** the standard ones. */ #if !defined(l_checkmode) /* accepted extensions to 'mode' in 'fopen' */ #if !defined(L_MODEEXT) #define L_MODEEXT "b" #endif /* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */ static int l_checkmode (const char *mode) { return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && (*mode != '+' || ((void)(++mode), 1)) && /* skip if char is '+' */ (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */ } #endif /* ** {====================================================== ** l_popen spawns a new process connected to the current ** one through the file streams. ** ======================================================= */ #if !defined(l_popen) /* { */ #if defined(LUA_USE_POSIX) /* { */ #define l_popen(L,c,m) (fflush(NULL), popen(c,m)) #define l_pclose(L,file) (pclose(file)) #elif defined(LUA_USE_WINDOWS) /* }{ */ #define l_popen(L,c,m) (_popen(c,m)) #define l_pclose(L,file) (_pclose(file)) #if !defined(l_checkmodep) /* Windows accepts "[rw][bt]?" as valid modes */ #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \ (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0'))) #endif #else /* }{ */ /* ISO C definitions */ #define l_popen(L,c,m) \ ((void)c, (void)m, \ luaL_error(L, "'popen' not supported"), \ (FILE*)0) #define l_pclose(L,file) ((void)L, (void)file, -1) #endif /* } */ #endif /* } */ #if !defined(l_checkmodep) /* By default, Lua accepts only "r" or "w" as valid modes */ #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0') #endif /* }====================================================== */ #if !defined(l_getc) /* { */ #if defined(LUA_USE_POSIX) #define l_getc(f) getc_unlocked(f) #define l_lockfile(f) flockfile(f) #define l_unlockfile(f) funlockfile(f) #else #define l_getc(f) getc(f) #define l_lockfile(f) ((void)0) #define l_unlockfile(f) ((void)0) #endif #endif /* } */ /* ** {====================================================== ** l_fseek: configuration for longer offsets ** ======================================================= */ #if !defined(l_fseek) /* { */ #if defined(LUA_USE_POSIX) || defined(LUA_USE_OFF_T) /* { */ #include #define l_fseek(f,o,w) fseeko(f,o,w) #define l_ftell(f) ftello(f) #define l_seeknum off_t #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \ && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */ /* Windows (but not DDK) and Visual C++ 2005 or higher */ #define l_fseek(f,o,w) _fseeki64(f,o,w) #define l_ftell(f) _ftelli64(f) #define l_seeknum __int64 #else /* }{ */ /* ISO C definitions */ #define l_fseek(f,o,w) fseek(f,o,w) #define l_ftell(f) ftell(f) #define l_seeknum long #endif /* } */ #endif /* } */ /* }====================================================== */ #define IO_PREFIX "_IO_" #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1) #define IO_INPUT (IO_PREFIX "input") #define IO_OUTPUT (IO_PREFIX "output") typedef luaL_Stream LStream; #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE)) #define isclosed(p) ((p)->closef == NULL) static int io_type (lua_State *L) { LStream *p; luaL_checkany(L, 1); p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE); if (p == NULL) luaL_pushfail(L); /* not a file */ else if (isclosed(p)) lua_pushliteral(L, "closed file"); else lua_pushliteral(L, "file"); return 1; } static int f_tostring (lua_State *L) { LStream *p = tolstream(L); if (isclosed(p)) lua_pushliteral(L, "file (closed)"); else lua_pushfstring(L, "file (%p)", p->f); return 1; } static FILE *tofile (lua_State *L) { LStream *p = tolstream(L); if (l_unlikely(isclosed(p))) luaL_error(L, "attempt to use a closed file"); lua_assert(p->f); return p->f; } /* ** When creating file handles, always creates a 'closed' file handle ** before opening the actual file; so, if there is a memory error, the ** handle is in a consistent state. */ static LStream *newprefile (lua_State *L) { LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0); p->closef = NULL; /* mark file handle as 'closed' */ luaL_setmetatable(L, LUA_FILEHANDLE); return p; } /* ** Calls the 'close' function from a file handle. The 'volatile' avoids ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for ** 32 bits). */ static int aux_close (lua_State *L) { LStream *p = tolstream(L); volatile lua_CFunction cf = p->closef; p->closef = NULL; /* mark stream as closed */ return (*cf)(L); /* close it */ } static int f_close (lua_State *L) { tofile(L); /* make sure argument is an open stream */ return aux_close(L); } static int io_close (lua_State *L) { if (lua_isnone(L, 1)) /* no argument? */ lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */ return f_close(L); } static int f_gc (lua_State *L) { LStream *p = tolstream(L); if (!isclosed(p) && p->f != NULL) aux_close(L); /* ignore closed and incompletely open files */ return 0; } /* ** function to close regular files */ static int io_fclose (lua_State *L) { LStream *p = tolstream(L); errno = 0; return luaL_fileresult(L, (fclose(p->f) == 0), NULL); } static LStream *newfile (lua_State *L) { LStream *p = newprefile(L); p->f = NULL; p->closef = &io_fclose; return p; } static void opencheck (lua_State *L, const char *fname, const char *mode) { LStream *p = newfile(L); p->f = fopen(fname, mode); if (l_unlikely(p->f == NULL)) luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno)); } static int io_open (lua_State *L) { const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); LStream *p = newfile(L); const char *md = mode; /* to traverse/check mode */ luaL_argcheck(L, l_checkmode(md), 2, "invalid mode"); errno = 0; p->f = fopen(filename, mode); return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; } /* ** function to close 'popen' files */ #ifndef BA_MINIOSLIB static int io_pclose (lua_State *L) { LStream *p = tolstream(L); errno = 0; return luaL_execresult(L, l_pclose(L, p->f)); } static int io_popen (lua_State *L) { const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); LStream *p = newprefile(L); luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode"); errno = 0; p->f = l_popen(L, filename, mode); p->closef = &io_pclose; return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; } #endif static int io_tmpfile (lua_State *L) { LStream *p = newfile(L); errno = 0; p->f = tmpfile(); return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1; } static FILE *getiofile (lua_State *L, const char *findex) { LStream *p; lua_getfield(L, LUA_REGISTRYINDEX, findex); p = (LStream *)lua_touserdata(L, -1); if (l_unlikely(isclosed(p))) luaL_error(L, "default %s file is closed", findex + IOPREF_LEN); return p->f; } static int g_iofile (lua_State *L, const char *f, const char *mode) { if (!lua_isnoneornil(L, 1)) { const char *filename = lua_tostring(L, 1); if (filename) opencheck(L, filename, mode); else { tofile(L); /* check that it's a valid file handle */ lua_pushvalue(L, 1); } lua_setfield(L, LUA_REGISTRYINDEX, f); } /* return current value */ lua_getfield(L, LUA_REGISTRYINDEX, f); return 1; } static int io_input (lua_State *L) { return g_iofile(L, IO_INPUT, "r"); } static int io_output (lua_State *L) { return g_iofile(L, IO_OUTPUT, "w"); } static int io_readline (lua_State *L); /* ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit ** in the limit for upvalues of a closure) */ #define MAXARGLINE 250 /* ** Auxiliary function to create the iteration function for 'lines'. ** The iteration function is a closure over 'io_readline', with ** the following upvalues: ** 1) The file being read (first value in the stack) ** 2) the number of arguments to read ** 3) a boolean, true iff file has to be closed when finished ('toclose') ** *) a variable number of format arguments (rest of the stack) */ static void aux_lines (lua_State *L, int toclose) { int n = lua_gettop(L) - 1; /* number of arguments to read */ luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments"); lua_pushvalue(L, 1); /* file */ lua_pushinteger(L, n); /* number of arguments to read */ lua_pushboolean(L, toclose); /* close/not close file when finished */ lua_rotate(L, 2, 3); /* move the three values to their positions */ lua_pushcclosure(L, io_readline, 3 + n); } static int f_lines (lua_State *L) { tofile(L); /* check that it's a valid file handle */ aux_lines(L, 0); return 1; } /* ** Return an iteration function for 'io.lines'. If file has to be ** closed, also returns the file itself as a second result (to be ** closed as the state at the exit of a generic for). */ static int io_lines (lua_State *L) { int toclose; if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */ if (lua_isnil(L, 1)) { /* no file name? */ lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */ lua_replace(L, 1); /* put it at index 1 */ tofile(L); /* check that it's a valid file handle */ toclose = 0; /* do not close it after iteration */ } else { /* open a new file */ const char *filename = luaL_checkstring(L, 1); opencheck(L, filename, "r"); lua_replace(L, 1); /* put file at index 1 */ toclose = 1; /* close it after iteration */ } aux_lines(L, toclose); /* push iteration function */ if (toclose) { lua_pushnil(L); /* state */ lua_pushnil(L); /* control */ lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */ return 4; } else return 1; } /* ** {====================================================== ** READ ** ======================================================= */ /* maximum length of a numeral */ #if !defined (L_MAXLENNUM) #define L_MAXLENNUM 200 #endif /* auxiliary structure used by 'read_number' */ typedef struct { FILE *f; /* file being read */ int c; /* current character (look ahead) */ int n; /* number of elements in buffer 'buff' */ char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */ } RN; /* ** Add current char to buffer (if not out of space) and read next one */ static int nextc (RN *rn) { if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */ rn->buff[0] = '\0'; /* invalidate result */ return 0; /* fail */ } else { rn->buff[rn->n++] = cast_char(rn->c); /* save current char */ rn->c = l_getc(rn->f); /* read next one */ return 1; } } /* ** Accept current char if it is in 'set' (of size 2) */ static int test2 (RN *rn, const char *set) { if (rn->c == set[0] || rn->c == set[1]) return nextc(rn); else return 0; } /* ** Read a sequence of (hex)digits */ static int readdigits (RN *rn, int hex) { int count = 0; while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn)) count++; return count; } /* ** Read a number: first reads a valid prefix of a numeral into a buffer. ** Then it calls 'lua_stringtonumber' to check whether the format is ** correct and to convert it to a Lua number. */ static int read_number (lua_State *L, FILE *f) { RN rn; int count = 0; int hex = 0; char decp[2]; rn.f = f; rn.n = 0; decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */ decp[1] = '.'; /* always accept a dot */ l_lockfile(rn.f); do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */ test2(&rn, "-+"); /* optional sign */ if (test2(&rn, "00")) { if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */ else count = 1; /* count initial '0' as a valid digit */ } count += readdigits(&rn, hex); /* integral part */ if (test2(&rn, decp)) /* decimal point? */ count += readdigits(&rn, hex); /* fractional part */ if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */ test2(&rn, "-+"); /* exponent sign */ readdigits(&rn, 0); /* exponent digits */ } ungetc(rn.c, rn.f); /* unread look-ahead char */ l_unlockfile(rn.f); rn.buff[rn.n] = '\0'; /* finish string */ if (l_likely(lua_stringtonumber(L, rn.buff))) return 1; /* ok, it is a valid number */ else { /* invalid format */ lua_pushnil(L); /* "result" to be removed */ return 0; /* read fails */ } } static int test_eof (lua_State *L, FILE *f) { int c = getc(f); ungetc(c, f); /* no-op when c == EOF */ lua_pushliteral(L, ""); return (c != EOF); } static int read_line (lua_State *L, FILE *f, int chop) { luaL_Buffer b; int c; ThreadMutex* m = balua_getparam(L)->server->dispatcher->mutex; luaL_buffinit(L, &b); do { /* may need to read several chunks to get whole line */ char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */ unsigned i = 0; l_lockfile(f); /* no memory errors can happen inside the lock */ if(m) ThreadMutex_release(m); while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n') buff[i++] = cast_char(c); /* read up to end of line or buffer limit */ if(m) ThreadMutex_set(m); l_unlockfile(f); luaL_addsize(&b, i); } while (c != EOF && c != '\n'); /* repeat until end of line */ if (!chop && c == '\n') /* want a newline and have one? */ luaL_addchar(&b, '\n'); /* add ending newline to result */ luaL_pushresult(&b); /* close buffer */ /* return ok if read something (either a newline or something else) */ return (c == '\n' || lua_rawlen(L, -1) > 0); } static void read_all (lua_State *L, FILE *f) { size_t nr; luaL_Buffer b; luaL_buffinit(L, &b); do { /* read file in chunks of LUAL_BUFFERSIZE bytes */ char *p = luaL_prepbuffer(&b); nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f); luaL_addsize(&b, nr); } while (nr == LUAL_BUFFERSIZE); luaL_pushresult(&b); /* close buffer */ } static int read_chars (lua_State *L, FILE *f, size_t n) { size_t nr; /* number of chars actually read */ char *p; luaL_Buffer b; luaL_buffinit(L, &b); p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */ nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */ luaL_addsize(&b, nr); luaL_pushresult(&b); /* close buffer */ return (nr > 0); /* true iff read something */ } static int g_read (lua_State *L, FILE *f, int first) { int nargs = lua_gettop(L) - 1; int n, success; clearerr(f); errno = 0; if (nargs == 0) { /* no arguments? */ success = read_line(L, f, 1); n = first + 1; /* to return 1 result */ } else { /* ensure stack space for all results and for auxlib's buffer */ luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); success = 1; for (n = first; nargs-- && success; n++) { if (lua_type(L, n) == LUA_TNUMBER) { size_t l = (size_t)luaL_checkinteger(L, n); success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); } else { const char *p = luaL_checkstring(L, n); if (*p == '*') p++; /* skip optional '*' (for compatibility) */ switch (*p) { case 'n': /* number */ success = read_number(L, f); break; case 'l': /* line */ success = read_line(L, f, 1); break; case 'L': /* line with end-of-line */ success = read_line(L, f, 0); break; case 'a': /* file */ read_all(L, f); /* read entire file */ success = 1; /* always success */ break; default: return luaL_argerror(L, n, "invalid format"); } } } } if (ferror(f)) return luaL_fileresult(L, 0, NULL); if (!success) { lua_pop(L, 1); /* remove last result */ luaL_pushfail(L); /* push nil instead */ } return n - first; } static int io_read (lua_State *L) { return g_read(L, getiofile(L, IO_INPUT), 1); } static int f_read (lua_State *L) { return g_read(L, tofile(L), 2); } /* ** Iteration function for 'lines'. */ static int io_readline (lua_State *L) { LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1)); int i; int n = (int)lua_tointeger(L, lua_upvalueindex(2)); if (isclosed(p)) /* file is already closed? */ return luaL_error(L, "file is already closed"); lua_settop(L , 1); luaL_checkstack(L, n, "too many arguments"); for (i = 1; i <= n; i++) /* push arguments to 'g_read' */ lua_pushvalue(L, lua_upvalueindex(3 + i)); n = g_read(L, p->f, 2); /* 'n' is number of results */ lua_assert(n > 0); /* should return at least a nil */ if (lua_toboolean(L, -n)) /* read at least one value? */ return n; /* return them */ else { /* first result is false: EOF or error */ if (n > 1) { /* is there error information? */ /* 2nd result is error message */ return luaL_error(L, "%s", lua_tostring(L, -n + 1)); } if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ lua_settop(L, 0); /* clear stack */ lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */ aux_close(L); /* close it */ } return 0; } } /* }====================================================== */ static int g_write (lua_State *L, FILE *f, int arg) { int nargs = lua_gettop(L) - arg; size_t totalbytes = 0; /* total number of bytes written */ errno = 0; for (; nargs--; arg++) { /* for each argument */ char buff[LUA_N2SBUFFSZ]; const char *s; size_t numbytes; /* bytes written in one call to 'fwrite' */ size_t len = lua_numbertocstring(L, arg, buff); /* try as a number */ if (len > 0) { /* did conversion work (value was a number)? */ s = buff; len--; } else /* must be a string */ s = luaL_checklstring(L, arg, &len); numbytes = fwrite(s, sizeof(char), len, f); totalbytes += numbytes; if (numbytes < len) { /* write error? */ int n = luaL_fileresult(L, 0, NULL); lua_pushinteger(L, cast_st2S(totalbytes)); return n + 1; /* return fail, error msg., error code, and counter */ } } return 1; /* no errors; file handle already on stack top */ } static int io_write (lua_State *L) { return g_write(L, getiofile(L, IO_OUTPUT), 1); } static int f_write (lua_State *L) { FILE *f = tofile(L); lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ return g_write(L, f, 2); } static int f_seek (lua_State *L) { static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; static const char *const modenames[] = {"set", "cur", "end", NULL}; FILE *f = tofile(L); int op = luaL_checkoption(L, 2, "cur", modenames); lua_Integer p3 = luaL_optinteger(L, 3, 0); l_seeknum offset = (l_seeknum)p3; luaL_argcheck(L, (lua_Integer)offset == p3, 3, "not an integer in proper range"); errno = 0; op = l_fseek(f, offset, mode[op]); if (l_unlikely(op)) return luaL_fileresult(L, 0, NULL); /* error */ else { lua_pushinteger(L, (lua_Integer)l_ftell(f)); return 1; } } static int f_setvbuf (lua_State *L) { static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; static const char *const modenames[] = {"no", "full", "line", NULL}; FILE *f = tofile(L); int op = luaL_checkoption(L, 2, NULL, modenames); lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); int res; errno = 0; res = setvbuf(f, NULL, mode[op], (size_t)sz); return luaL_fileresult(L, res == 0, NULL); } static int aux_flush (lua_State *L, FILE *f) { errno = 0; return luaL_fileresult(L, fflush(f) == 0, NULL); } static int f_flush (lua_State *L) { return aux_flush(L, tofile(L)); } static int io_flush (lua_State *L) { return aux_flush(L, getiofile(L, IO_OUTPUT)); } /* ** functions for 'io' library */ static const luaL_Reg iolib[] = { {"close", io_close}, {"flush", io_flush}, {"input", io_input}, {"lines", io_lines}, {"open", io_open}, {"output", io_output}, #ifndef BA_MINIOSLIB {"popen", io_popen}, #endif {"read", io_read}, {"tmpfile", io_tmpfile}, {"type", io_type}, {"write", io_write}, {NULL, NULL} }; /* ** methods for file handles */ static const luaL_Reg meth[] = { {"read", f_read}, {"write", f_write}, {"lines", f_lines}, {"flush", f_flush}, {"seek", f_seek}, {"close", f_close}, {"setvbuf", f_setvbuf}, {NULL, NULL} }; /* ** metamethods for file handles */ static const luaL_Reg metameth[] = { {"__index", NULL}, /* placeholder */ {"__gc", f_gc}, {"__close", f_gc}, {"__tostring", f_tostring}, {NULL, NULL} }; static void createmeta (lua_State *L) { luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */ luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */ luaL_newlibtable(L, meth); /* create method table */ luaL_setfuncs(L, meth, 0); /* add file methods to method table */ lua_setfield(L, -2, "__index"); /* metatable.__index = method table */ lua_pop(L, 1); /* pop metatable */ } /* ** function to (not) close the standard files stdin, stdout, and stderr */ static int io_noclose (lua_State *L) { LStream *p = tolstream(L); p->closef = &io_noclose; /* keep file opened */ luaL_pushfail(L); lua_pushliteral(L, "cannot close standard file"); return 2; } static void createstdfile (lua_State *L, FILE *f, const char *k, const char *fname) { LStream *p = newprefile(L); p->f = f; p->closef = &io_noclose; if (k != NULL) { lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */ } lua_setfield(L, -2, fname); /* add file to module */ } LUAMOD_API int luaopen_io (lua_State *L) { luaL_newlib(L, iolib); /* new module */ createmeta(L); /* create (and set) default files */ createstdfile(L, stdin, IO_INPUT, "stdin"); createstdfile(L, stdout, IO_OUTPUT, "stdout"); createstdfile(L, stderr, NULL, "stderr"); return 1; } #endif #endif /******************************** END LUA ************************************/ /* ZLIB Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). */ #ifndef NO_ZLIB #define BA_DEFLATE 1 /* compile deflate code */ #define _Z_UTIL_H #include #undef _Z_UTIL_H #include #include /* #define GUNZIP */ /* #define GZIP */ typedef U32 u_nsigned; /* was unsigned */ static U8 *zeroBaMalloc(int size) { U8 *p = baMalloc(size); if (p != NULL) memset(p, 0, size); return p; } /**************************************************************************** zconf.h - configuration of the zlib compression library ****************************************************************************/ /* Maximum value for memLevel in deflateInit */ #ifndef MAX_MEM_LEVEL # define MAX_MEM_LEVEL 9 #endif /* Maximum value for windowBits in deflateInit2 and inflateInit2. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files * created by gzip. (Files created by minigzip can still be extracted by * gzip.) */ #ifndef MAX_WBITS # define MAX_WBITS 15 /* 32K LZ77 window */ #endif /**************************************************************************** zlib.h ****************************************************************************/ #ifndef Z_BLOCK #define Z_BLOCK 5 #endif #ifndef Z_RLE #define Z_RLE 3 #endif #ifndef Z_FIXED #define Z_FIXED 4 #endif #ifndef Z_TEXT #define Z_TEXT 1 #endif /**************************************************************************** zutil.h - internal interface and configuration of the compression library ****************************************************************************/ #ifndef DEF_WBITS # define DEF_WBITS MAX_WBITS #endif /* default memLevel */ #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* The three kinds of block type */ #define STORED_BLOCK 0 #define STATIC_TREES 1 #define DYN_TREES 2 /* The minimum and maximum match lengths */ #define MIN_MATCH 3 #define MAX_MATCH 258 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ /**************************************************************************** inffast.h - header to use inffast.c ****************************************************************************/ void inflate_fast (z_streamp strm, u_nsigned start); /**************************************************************************** inftrees.h - header to use inftrees.c ****************************************************************************/ typedef struct { U8 op; /* operation, extra bits, table bits */ U8 bits; /* bits in this part of the code */ U16 val; /* offset in table or code value */ } code; #define ENOUGH 2048 #define MAXD 592 /* Type of code to build for inftable() */ typedef enum { CODES, LENS, DISTS } codetype; int inflate_table(codetype type, U16 *lens, u_nsigned codes, code **table, u_nsigned *bits, U16 *work); /**************************************************************************** inflate.h ****************************************************************************/ /* Symbol collision on some devices. */ #undef HEAD #undef FLAGS #undef TIME #undef OS #undef EXLEN #undef EXTRA #undef NAME #undef COMMENT #undef HCRC #undef DICTID #undef DICT #undef TYPE #undef TYPEDO #undef STORED #undef COPY #undef TABLE #undef LENLENS #undef CODELENS #undef LEN #undef LENEXT #undef DIST #undef DISTEXT #undef MATCH #undef LIT #undef CHECK #undef LENGTH #undef DONE #undef BAD #undef MEM #undef SYNC /* Possible inflate modes between inflate() calls */ typedef enum { HEAD, /* i: waiting for magic header */ FLAGS, /* i: waiting for method and flags (gzip) */ TIME, /* i: waiting for modification time (gzip) */ OS, /* i: waiting for extra flags and operating system (gzip) */ EXLEN, /* i: waiting for extra length (gzip) */ EXTRA, /* i: waiting for extra bytes (gzip) */ NAME, /* i: waiting for end of file name (gzip) */ COMMENT, /* i: waiting for end of comment (gzip) */ HCRC, /* i: waiting for header crc (gzip) */ DICTID, /* i: waiting for dictionary check value */ DICT, /* waiting for inflateSetDictionary() call */ TYPE, /* i: waiting for type bits, including last-flag bit */ TYPEDO, /* i: same, but skip check to exit inflate on new block */ STORED, /* i: waiting for stored size (length and complement) */ COPY, /* i/o: waiting for input or output to copy stored block */ TABLE, /* i: waiting for dynamic block table lengths */ LENLENS, /* i: waiting for code length code lengths */ CODELENS, /* i: waiting for length/lit and distance code lengths */ LEN, /* i: waiting for length/lit code */ LENEXT, /* i: waiting for length extra bits */ DIST, /* i: waiting for distance code */ DISTEXT, /* i: waiting for distance extra bits */ MATCH, /* o: waiting for output space to copy string */ LIT, /* o: waiting for output space to write literal */ CHECK, /* i: waiting for 32-bit check value */ LENGTH, /* i: waiting for 32-bit length (gzip) */ DONE, /* finished check, done -- remain here until reset */ BAD, /* got a data error -- remain here until reset */ MEM, /* got an inflate() memory error -- remain here until reset */ SYNC /* looking for synchronization bytes to restart inflate() */ } inflate_mode; typedef struct gz_header_s { int text; /* true if compressed data believed to be text */ U32 time; /* modification time */ int xflags; /* extra flags (not used when writing a gzip file) */ int os; /* operating system */ U8 *extra; /* pointer to extra field or NULL if none */ uInt extra_len; /* extra field length (valid if extra != NULL) */ uInt extra_max; /* space at extra (only when reading header) */ U8 *name; /* pointer to zero-terminated file name or NULL */ uInt name_max; /* space at name (only when reading header) */ U8 *comment; /* pointer to zero-terminated comment or NULL */ uInt comm_max; /* space at comment (only when reading header) */ int hcrc; /* true if there was or will be a header crc */ int done; /* true when done reading gzip header (not used when writing a gzip file) */ } gz_header; typedef gz_header *gz_headerp; /* state maintained between inflate() calls. Approximately 7K bytes. */ struct inflate_state { inflate_mode mode; /* current inflate mode */ int last; /* true if processing last block */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ int havedict; /* true if dictionary provided */ int flags; /* gzip header method and flags (0 if zlib) */ u_nsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ U32 check; /* protected copy of check value */ U32 total; /* protected copy of output count */ gz_headerp head; /* where to save gzip header information */ /* sliding window */ u_nsigned wbits; /* log base 2 of requested window size */ u_nsigned wsize; /* window size or zero if not using window */ u_nsigned whave; /* valid bytes in the window */ u_nsigned write; /* window write index */ U8 *window; /* allocated sliding window, if needed */ /* bit accumulator */ U32 hold; /* input bit accumulator */ u_nsigned bits; /* number of bits in "in" */ /* for string and stored block copying */ u_nsigned length; /* literal or length of data to copy */ u_nsigned offset; /* distance back to copy string from */ /* for table and code decoding */ u_nsigned extra; /* extra bits needed */ /* fixed and dynamic code tables */ code const *lencode; /* starting table for length/literal codes */ code const *distcode; /* starting table for distance codes */ u_nsigned lenbits; /* index bits for lencode */ u_nsigned distbits; /* index bits for distcode */ /* dynamic table building */ u_nsigned ncode; /* number of code length code lengths */ u_nsigned nlen; /* number of length code lengths */ u_nsigned ndist; /* number of distance code lengths */ u_nsigned have; /* number of code lengths in lens[] */ code *next; /* next available space in codes[] */ U16 lens[320]; /* temporary storage for code lengths */ U16 work[288]; /* work area for code table building */ code codes[ENOUGH]; /* space for code tables */ }; /**************************************************************************** adler32.c - compute the Adler-32 checksum of a data stream ****************************************************************************/ #define BASE 65521UL /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); #define MOD(a) a %= BASE #define MOD4(a) a %= BASE uLong adler32(uLong adler, const Bytef *buf, uInt len) { U32 sum2; u_nsigned n; /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; /* in case user likes doing a byte at a time, keep it fast */ if (len == 1) { adler += buf[0]; if (adler >= BASE) adler -= BASE; sum2 += adler; if (sum2 >= BASE) sum2 -= BASE; return adler | (sum2 << 16); } /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == NULL) return 1L; /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { while (len--) { adler += *buf++; sum2 += adler; } if (adler >= BASE) adler -= BASE; MOD4(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } /* do length NMAX blocks -- requires just one modulo operation */ while (len >= NMAX) { len -= NMAX; n = NMAX / 16; /* NMAX is divisible by 16 */ do { DO16(buf); /* 16 sums unrolled */ buf += 16; } while (--n); MOD(adler); MOD(sum2); } /* do remaining bytes (less than NMAX, still just one modulo) */ if (len) { /* avoid modulos if none remaining */ while (len >= 16) { len -= 16; DO16(buf); buf += 16; } while (len--) { adler += *buf++; sum2 += adler; } MOD(adler); MOD(sum2); } /* return recombined sums */ return adler | (sum2 << 16); } /**************************************************************************** crc32.c - compute the CRC-32 of a data stream ****************************************************************************/ /* * Table of CRC-32's of all single-byte values */ #define TBLS 1 static const U32 crc_table[TBLS][256] = { { 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, 0x2d02ef8dUL } }; #undef DO1 #undef DO8 #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 /* ========================================================================= */ uLong crc32(uLong crc, const U8 *buf, uInt len) { if (buf == NULL) return 0UL; crc = crc ^ 0xffffffffUL; while (len >= 8) { DO8; len -= 8; } if (len) do { DO1; } while (--len); return crc ^ 0xffffffffUL; } /**************************************************************************** inflate.c - zlib interface to PzipInflate modules ****************************************************************************/ static void fixedtables (struct inflate_state *state); static int updatewindow (z_streamp strm, u_nsigned out); int inflateReset(z_streamp strm) { struct inflate_state *state; if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR; state = (struct inflate_state*)strm->state; strm->total_in = strm->total_out = state->total = 0; strm->adler = 1; /* to support ill-conceived Java test suite */ state->mode = HEAD; state->last = 0; state->havedict = 0; state->dmax = 32768U; state->head = NULL; state->wsize = 0; state->whave = 0; state->write = 0; state->hold = 0; state->bits = 0; state->lencode = state->distcode = state->next = state->codes; return Z_OK; } int inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size) { struct inflate_state *state; if (version == NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == NULL) return Z_STREAM_ERROR; state = (struct inflate_state*) zeroBaMalloc(sizeof(struct inflate_state)); if (state == NULL) return Z_MEM_ERROR; strm->state = (struct internal_state*)state; if (windowBits < 0) { state->wrap = 0; windowBits = -windowBits; } else { state->wrap = (windowBits >> 4) + 1; #ifdef GUNZIP if (windowBits < 48) windowBits &= 15; #endif } if (windowBits < 8 || windowBits > 15) { baFree(state); strm->state = NULL; return Z_STREAM_ERROR; } state->wbits = (u_nsigned)windowBits; state->window = NULL; return inflateReset(strm); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ static void fixedtables(struct inflate_state *state) { static const code lenfix[512] = { {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, {0,9,255} }; static const code distfix[32] = { {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, {22,5,193},{64,5,0} }; state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ static int updatewindow(z_streamp strm, u_nsigned out) { struct inflate_state *state; u_nsigned copy, dist; state = (struct inflate_state *)strm->state; /* if it hasn't been done already, allocate space for the window */ if (state->window == NULL) { state->window = (U8*)zeroBaMalloc(1U << state->wbits); if (state->window == NULL) return 1; } /* if window not in use yet, initialize */ if (state->wsize == 0) { state->wsize = 1U << state->wbits; state->write = 0; state->whave = 0; } /* copy state->wsize or less output bytes into the circular window */ copy = out - strm->avail_out; if (copy >= state->wsize) { memcpy(state->window, strm->next_out - state->wsize, state->wsize); state->write = 0; state->whave = state->wsize; } else { dist = state->wsize - state->write; if (dist > copy) dist = copy; memcpy(state->window + state->write, strm->next_out - copy, dist); copy -= dist; if (copy) { memcpy(state->window, strm->next_out - copy, copy); state->write = copy; state->whave = state->wsize; } else { state->write += dist; if (state->write == state->wsize) state->write = 0; if (state->whave < state->wsize) state->whave += dist; } } return 0; } /* Macros for inflate(): */ /* check function to use adler32() for zlib or crc32() for gzip */ #undef UPDATE #ifdef GUNZIP # define UPDATE(check, buf, len) \ (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) #else # define UPDATE(check, buf, len) adler32(check, buf, len) #endif /* check macros for header crc */ #ifdef GUNZIP # define CRC2(check, word) \ do { \ hbuf[0] = (U8)(word); \ hbuf[1] = (U8)((word) >> 8); \ check = crc32(check, hbuf, 2); \ } while (0) # define CRC4(check, word) \ do { \ hbuf[0] = (U8)(word); \ hbuf[1] = (U8)((word) >> 8); \ hbuf[2] = (U8)((word) >> 16); \ hbuf[3] = (U8)((word) >> 24); \ check = crc32(check, hbuf, 4); \ } while (0) #endif /* Load registers with state in inflate() for speed */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Restore state from registers in inflate() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflate() if there is no input available. */ #define PULLBYTE() \ do { \ if (have == 0) goto inf_leave; \ have--; \ hold += (U32)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflate(). */ #define NEEDBITS(n) \ do { \ while (bits < (u_nsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((u_nsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (U16)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* Reverse the bytes in a 32-bit value */ #define REVERSE(q) \ ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) int inflate(z_streamp strm, int flush) { struct inflate_state *state; U8* next; /* next input */ U8 *put; /* next output */ u_nsigned have, left; /* available input and output */ U32 hold; /* bit buffer */ u_nsigned bits; /* bits in bit buffer */ u_nsigned in, out; /* save starting available input and output */ u_nsigned copy; /* number of stored or match bytes to copy */ U8 *from; /* where to copy match bytes from */ code t_his; /* current decoding table entry */ code last; /* parent table entry */ u_nsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ #ifdef GUNZIP U8 hbuf[4]; /* buffer for gzip header crc calculation */ #endif static const U16 order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; if (strm == NULL || strm->state == NULL || strm->next_out == NULL || (strm->next_in == NULL && strm->avail_in != 0)) return Z_STREAM_ERROR; state = (struct inflate_state *)strm->state; if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ LOAD(); in = have; out = left; ret = Z_OK; for (;;) switch (state->mode) { case HEAD: if (state->wrap == 0) { state->mode = TYPEDO; break; } NEEDBITS(16); #ifdef GUNZIP if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ state->check = crc32(0L, NULL, 0); CRC2(state->check, hold); INITBITS(); state->mode = FLAGS; break; } state->flags = 0; /* expect zlib header */ if (state->head != NULL) state->head->done = -1; if (!(state->wrap & 1) || /* check if zlib header allowed */ #else if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { state->mode = BAD; break; } if (BITS(4) != Z_DEFLATED) { state->mode = BAD; break; } DROPBITS(4); len = BITS(4) + 8; if (len > state->wbits) { state->mode = BAD; break; } state->dmax = 1U << len; strm->adler = state->check = adler32(0L, NULL, 0); state->mode = hold & 0x200 ? DICTID : TYPE; INITBITS(); break; #ifdef GUNZIP case FLAGS: NEEDBITS(16); state->flags = (int)(hold); if ((state->flags & 0xff) != Z_DEFLATED) { state->mode = BAD; break; } if (state->flags & 0xe000) { state->mode = BAD; break; } if (state->head != NULL) state->head->text = (int)((hold >> 8) & 1); if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); state->mode = TIME; case TIME: NEEDBITS(32); if (state->head != NULL) state->head->time = hold; if (state->flags & 0x0200) CRC4(state->check, hold); INITBITS(); state->mode = OS; case OS: NEEDBITS(16); if (state->head != NULL) { state->head->xflags = (int)(hold & 0xff); state->head->os = (int)(hold >> 8); } if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); state->mode = EXLEN; case EXLEN: if (state->flags & 0x0400) { NEEDBITS(16); state->length = (u_nsigned)(hold); if (state->head != NULL) state->head->extra_len = (u_nsigned)hold; if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); } else if (state->head != NULL) state->head->extra = NULL; state->mode = EXTRA; case EXTRA: if (state->flags & 0x0400) { copy = state->length; if (copy > have) copy = have; if (copy) { if (state->head != NULL && state->head->extra != NULL) { len = state->head->extra_len - state->length; memcpy(state->head->extra + len, next, len + copy > state->head->extra_max ? state->head->extra_max - len : copy); } if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; state->length -= copy; } if (state->length) goto inf_leave; } state->length = 0; state->mode = NAME; case NAME: if (state->flags & 0x0800) { if (have == 0) goto inf_leave; copy = 0; do { len = (u_nsigned)(next[copy++]); if (state->head != NULL && state->head->name != NULL && state->length < state->head->name_max) state->head->name[state->length++] = len; } while (len && copy < have); if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != NULL) state->head->name = NULL; state->length = 0; state->mode = COMMENT; case COMMENT: if (state->flags & 0x1000) { if (have == 0) goto inf_leave; copy = 0; do { len = (u_nsigned)(next[copy++]); if (state->head != NULL && state->head->comment != NULL && state->length < state->head->comm_max) state->head->comment[state->length++] = len; } while (len && copy < have); if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != NULL) state->head->comment = NULL; state->mode = HCRC; case HCRC: if (state->flags & 0x0200) { NEEDBITS(16); if (hold != (state->check & 0xffff)) { state->mode = BAD; break; } INITBITS(); } if (state->head != NULL) { state->head->hcrc = (int)((state->flags >> 9) & 1); state->head->done = 1; } strm->adler = state->check = crc32(0L, NULL, 0); state->mode = TYPE; break; #endif case DICTID: NEEDBITS(32); strm->adler = state->check = REVERSE(hold); INITBITS(); state->mode = DICT; /* FALLTHRU */ case DICT: if (state->havedict == 0) { RESTORE(); return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, NULL, 0); state->mode = TYPE; /* FALLTHRU */ case TYPE: if (flush == Z_BLOCK) goto inf_leave; /* FALLTHRU */ case TYPEDO: if (state->last) { BYTEBITS(); state->mode = CHECK; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); state->mode = LEN; /* decode codes */ break; case 2: /* dynamic block */ state->mode = TABLE; break; case 3: state->mode = BAD; } DROPBITS(2); break; case STORED: BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { state->mode = BAD; break; } state->length = (u_nsigned)hold & 0xffff; INITBITS(); state->mode = COPY; /* FALLTHRU */ case COPY: copy = state->length; if (copy) { if (copy > have) copy = have; if (copy > left) copy = left; if (copy == 0) goto inf_leave; memcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; break; } state->mode = TYPE; break; case TABLE: NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { state->mode = BAD; break; } #endif state->have = 0; state->mode = LENLENS; case LENLENS: while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (U16)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (code const *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { state->mode = BAD; break; } state->have = 0; state->mode = CODELENS; case CODELENS: while (state->have < state->nlen + state->ndist) { for (;;) { t_his = state->lencode[BITS(state->lenbits)]; if ((u_nsigned)(t_his.bits) <= bits) break; PULLBYTE(); } if (t_his.val < 16) { NEEDBITS(t_his.bits); DROPBITS(t_his.bits); state->lens[state->have++] = t_his.val; } else { if (t_his.val == 16) { NEEDBITS(t_his.bits + 2); DROPBITS(t_his.bits); if (state->have == 0) { state->mode = BAD; break; } len = state->lens[state->have - 1]; copy = 3 + BITS(2); DROPBITS(2); } else if (t_his.val == 17) { NEEDBITS(t_his.bits + 3); DROPBITS(t_his.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(t_his.bits + 7); DROPBITS(t_his.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (U16)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* build code tables */ state->next = state->codes; state->lencode = (code const *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { state->mode = BAD; break; } state->distcode = (code const *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { state->mode = BAD; break; } state->mode = LEN; /* FALLTHRU */ case LEN: if (have >= 6 && left >= 258) { RESTORE(); inflate_fast(strm, out); LOAD(); break; } for (;;) { t_his = state->lencode[BITS(state->lenbits)]; if ((u_nsigned)(t_his.bits) <= bits) break; PULLBYTE(); } if (t_his.op && (t_his.op & 0xf0) == 0) { last = t_his; for (;;) { t_his = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((u_nsigned)(last.bits + t_his.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(t_his.bits); state->length = (u_nsigned)t_his.val; if ((int)(t_his.op) == 0) { state->mode = LIT; break; } if (t_his.op & 32) { state->mode = TYPE; break; } if (t_his.op & 64) { state->mode = BAD; break; } state->extra = (u_nsigned)(t_his.op) & 15; state->mode = LENEXT; /* FALLTHRU */ case LENEXT: if (state->extra) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); } state->mode = DIST; /* FALLTHRU */ case DIST: for (;;) { t_his = state->distcode[BITS(state->distbits)]; if ((u_nsigned)(t_his.bits) <= bits) break; PULLBYTE(); } if ((t_his.op & 0xf0) == 0) { last = t_his; for (;;) { t_his = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((u_nsigned)(last.bits + t_his.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(t_his.bits); if (t_his.op & 64) { state->mode = BAD; break; } state->offset = (u_nsigned)t_his.val; state->extra = (u_nsigned)(t_his.op) & 15; state->mode = DISTEXT; /* FALLTHRU */ case DISTEXT: if (state->extra) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); } #ifdef INFLATE_STRICT if (state->offset > state->dmax) { state->mode = BAD; break; } #endif if (state->offset > state->whave + out - left) { state->mode = BAD; break; } state->mode = MATCH; /* FALLTHRU */ case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state->offset > copy) { /* copy from window */ copy = state->offset - copy; if (copy > state->write) { copy -= state->write; from = state->window + (state->wsize - copy); } else from = state->window + (state->write - copy); if (copy > state->length) copy = state->length; } else { /* copy from output */ from = put - state->offset; copy = state->length; } if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = *from++; } while (--copy); if (state->length == 0) state->mode = LEN; break; case LIT: if (left == 0) goto inf_leave; *put++ = (U8)(state->length); left--; state->mode = LEN; break; case CHECK: if (state->wrap) { NEEDBITS(32); out -= left; strm->total_out += out; state->total += out; if (out) strm->adler = state->check = UPDATE(state->check, put - out, out); out = left; if (( #ifdef GUNZIP state->flags ? hold : #endif REVERSE(hold)) != state->check) { state->mode = BAD; break; } INITBITS(); } #ifdef GUNZIP state->mode = LENGTH; case LENGTH: if (state->wrap && state->flags) { NEEDBITS(32); if (hold != (state->total & 0xffffffffUL)) { state->mode = BAD; break; } INITBITS(); } #endif state->mode = DONE; /* FALLTHRU */ case DONE: ret = Z_STREAM_END; goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: default: return Z_STREAM_ERROR; } /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ inf_leave: RESTORE(); if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) if (updatewindow(strm, out)) { state->mode = MEM; return Z_MEM_ERROR; } in -= strm->avail_in; out -= strm->avail_out; strm->total_in += in; strm->total_out += out; state->total += out; if (state->wrap && out) strm->adler = state->check = UPDATE(state->check, strm->next_out - out, out); strm->data_type = state->bits + (state->last ? 64 : 0) + (state->mode == TYPE ? 128 : 0); if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) ret = Z_BUF_ERROR; return ret; } int inflateEnd(z_streamp strm) { struct inflate_state *state; if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR; state = (struct inflate_state *)strm->state; if (state->window != NULL) baFree(state->window); baFree(strm->state); strm->state = NULL; return Z_OK; } /**************************************************************************** inffast.c ****************************************************************************/ #ifdef POSTINC # define ZZ_OFF 0 # define PUP(a) *(a)++ #else # define ZZ_OFF 1 # define PUP(a) *++(a) #endif void inflate_fast(z_streamp strm, u_nsigned start) { struct inflate_state *state; U8 *in; /* local strm->next_in */ U8 *last; /* while in < last, enough input available */ U8 *out; /* local strm->next_out */ U8 *beg; /* inflate()'s initial strm->next_out */ U8 *end; /* while out < end, enough space available */ #ifdef INFLATE_STRICT u_nsigned dmax; /* maximum distance from zlib header */ #endif u_nsigned wsize; /* window size or zero if not using window */ u_nsigned whave; /* valid bytes in the window */ u_nsigned write; /* window write index */ U8 *window; /* allocated sliding window, if wsize != 0 */ U32 hold; /* local strm->hold */ u_nsigned bits; /* local strm->bits */ code const *lcode; /* local strm->lencode */ code const *dcode; /* local strm->distcode */ u_nsigned lmask; /* mask for first level of length codes */ u_nsigned dmask; /* mask for first level of distance codes */ code t_his; /* retrieved table entry */ u_nsigned op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ u_nsigned len; /* match length, unused bytes */ u_nsigned dist; /* match distance */ U8 *from; /* where to copy match from */ /* copy state to local variables */ state = (struct inflate_state *)strm->state; in = strm->next_in - ZZ_OFF; last = in + (strm->avail_in - 5); out = strm->next_out - ZZ_OFF; beg = out - (start - strm->avail_out); end = out + (strm->avail_out - 257); #ifdef INFLATE_STRICT dmax = state->dmax; #endif wsize = state->wsize; whave = state->whave; write = state->write; window = state->window; hold = state->hold; bits = state->bits; lcode = state->lencode; dcode = state->distcode; lmask = (1U << state->lenbits) - 1; dmask = (1U << state->distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ do { if (bits < 15) { hold += (U32)(PUP(in)) << bits; bits += 8; hold += (U32)(PUP(in)) << bits; bits += 8; } t_his = lcode[hold & lmask]; dolen: op = (u_nsigned)(t_his.bits); hold >>= op; bits -= op; op = (u_nsigned)(t_his.op); if (op == 0) { /* literal */ PUP(out) = (U8)(t_his.val); } else if (op & 16) { /* length base */ len = (u_nsigned)(t_his.val); op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += (U32)(PUP(in)) << bits; bits += 8; } len += (u_nsigned)hold & ((1U << op) - 1); hold >>= op; bits -= op; } if (bits < 15) { hold += (U32)(PUP(in)) << bits; bits += 8; hold += (U32)(PUP(in)) << bits; bits += 8; } t_his = dcode[hold & dmask]; dodist: op = (u_nsigned)(t_his.bits); hold >>= op; bits -= op; op = (u_nsigned)(t_his.op); if (op & 16) { /* distance base */ dist = (u_nsigned)(t_his.val); op &= 15; /* number of extra bits */ if (bits < op) { hold += (U32)(PUP(in)) << bits; bits += 8; if (bits < op) { hold += (U32)(PUP(in)) << bits; bits += 8; } } dist += (u_nsigned)hold & ((1U << op) - 1); #ifdef INFLATE_STRICT if (dist > dmax) { state->mode = BAD; break; } #endif hold >>= op; bits -= op; op = (u_nsigned)(out - beg); /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { state->mode = BAD; break; } from = window - ZZ_OFF; if (write == 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } else if (write < op) { /* wrap around window */ from += wsize + write - op; op -= write; if (op < len) { /* some from end of window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = window - ZZ_OFF; if (write < len) { /* some from start of window */ op = write; len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } } else { /* contiguous in window */ from += write - op; if (op < len) { /* some from window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } while (len > 2) { PUP(out) = PUP(from); PUP(out) = PUP(from); PUP(out) = PUP(from); len -= 3; } if (len) { PUP(out) = PUP(from); if (len > 1) PUP(out) = PUP(from); } } else { from = out - dist; /* copy direct from output */ do { /* minimum length is three */ PUP(out) = PUP(from); PUP(out) = PUP(from); PUP(out) = PUP(from); len -= 3; } while (len > 2); if (len) { PUP(out) = PUP(from); if (len > 1) PUP(out) = PUP(from); } } } else if ((op & 64) == 0) { /* 2nd level distance code */ t_his = dcode[t_his.val + (hold & ((1U << op) - 1))]; goto dodist; } else { state->mode = BAD; break; } } else if ((op & 64) == 0) { /* 2nd level length code */ t_his = lcode[t_his.val + (hold & ((1U << op) - 1))]; goto dolen; } else if (op & 32) { /* end-of-block */ state->mode = TYPE; break; } else { state->mode = BAD; break; } } while (in < last && out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; in -= len; bits -= len << 3; hold &= (1U << bits) - 1; /* update state and return */ strm->next_in = in + ZZ_OFF; strm->next_out = out + ZZ_OFF; strm->avail_in = (u_nsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); strm->avail_out = (u_nsigned)(out < end ? 257 + (end - out) : 257 - (out - end)); state->hold = hold; state->bits = bits; return; } /**************************************************************************** inftrees.c ****************************************************************************/ #define ZLIBMAXBITS 15 int inflate_table(codetype type, U16 *lens, u_nsigned codes, code **table, u_nsigned *bits, U16 *work) { u_nsigned len; /* a code's length in bits */ u_nsigned sym; /* index of code symbols */ u_nsigned min, max; /* minimum and maximum code lengths */ u_nsigned root; /* number of index bits for root table */ u_nsigned curr; /* number of index bits for current table */ u_nsigned drop; /* code bits to drop for sub-table */ int left; /* number of prefix codes available */ u_nsigned used; /* code entries in table used */ u_nsigned huff; /* Huffman code */ u_nsigned incr; /* for incrementing code, index */ u_nsigned fill; /* index for replicating entries */ u_nsigned low; /* low bits for current root entry */ u_nsigned mask; /* mask for low root bits */ code t_his; /* table entry for duplication */ code *next; /* next available space in table */ const U16 *base; /* base value table to use */ const U16 *extra; /* extra bits table to use */ int end; /* use base and extra for symbol > end */ U16 count[ZLIBMAXBITS+1]; /* number of codes of each length */ U16 offs[ZLIBMAXBITS+1]; /* offsets in table for each length */ static const U16 lbase[31] = { /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const U16 lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; static const U16 dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const U16 dext[32] = { /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64}; /* accumulate lengths for codes (assumes lens[] all in 0..ZLIBMAXBITS) */ for (len = 0; len <= ZLIBMAXBITS; len++) count[len] = 0; for (sym = 0; sym < codes; sym++) count[lens[sym]]++; /* bound code lengths, force root to be within code lengths */ root = *bits; for (max = ZLIBMAXBITS; max >= 1; max--) if (count[max] != 0) break; if (root > max) root = max; if (max == 0) { /* no symbols to code at all */ t_his.op = (U8)64; /* invalid code marker */ t_his.bits = (U8)1; t_his.val = (U16)0; *(*table)++ = t_his; /* make a table to force an error */ *(*table)++ = t_his; *bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min <= ZLIBMAXBITS; min++) if (count[min] != 0) break; if (root < min) root = min; /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= ZLIBMAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) return -1; /* over-subscribed */ } if (left > 0 && (type == CODES || max != 1)) return -1; /* incomplete set */ /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < ZLIBMAXBITS; len++) offs[len + 1] = offs[len] + count[len]; /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) if (lens[sym] != 0) work[offs[lens[sym]]++] = (U16)sym; /* set up for code type */ switch (type) { case CODES: base = extra = work; /* dummy value--not used */ end = 19; break; case LENS: base = lbase; base -= 257; extra = lext; extra -= 257; end = 256; break; default: /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize state for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = *table; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = (u_nsigned)(-1); /* trigger new sub-table when len > root */ used = 1U << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if (type == LENS && used >= ENOUGH - MAXD) return 1; /* process all codes and make table entries */ for (;;) { /* create table entry */ t_his.bits = (U8)(len - drop); if ((int)(work[sym]) < end) { t_his.op = (U8)0; t_his.val = work[sym]; } else if ((int)(work[sym]) > end) { t_his.op = (U8)(extra[work[sym]]); t_his.val = base[work[sym]]; } else { t_his.op = (U8)(32 + 64); /* end of block */ t_his.val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1U << (len - drop); fill = 1U << curr; min = fill; /* save offset to next table */ do { fill -= incr; next[(huff >> drop) + fill] = t_his; } while (fill != 0); /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; /* go to next symbol, update count, len */ sym++; if (--(count[len]) == 0) { if (len == max) break; len = lens[work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) != low) { /* if first time, transition to sub-tables */ if (drop == 0) drop = root; /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = (int)(1 << curr); while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) break; curr++; left <<= 1; } /* check for enough space */ used += 1U << curr; if (type == LENS && used >= ENOUGH - MAXD) return 1; /* point entry in root table to sub-table */ low = huff & mask; (*table)[low].op = (U8)curr; (*table)[low].bits = (U8)root; (*table)[low].val = (U16)(next - *table); } } /* Fill in rest of table for incomplete codes. This loop is similar to the loop above in incrementing huff for table indices. It is assumed that len is equal to curr + drop, so there is no loop needed to increment through high index bits. When the current sub-table is filled, the loop drops back to the root table to fill in any remaining entries there. */ t_his.op = (U8)64; /* invalid code marker */ t_his.bits = (U8)(len - drop); t_his.val = (U16)0; while (huff != 0) { /* when done with sub-table, drop back to root table */ if (drop != 0 && (huff & mask) != low) { drop = 0; len = root; next = *table; t_his.bits = (U8)len; } /* put invalid code marker in table */ next[huff >> drop] = t_his; /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; } /* set return parameters */ *table += used; *bits = root; return 0; } #if BA_DEFLATE /**************************************************************************** deflate.h ****************************************************************************/ #define LENGTH_CODES 29 /* number of length codes, not counting the special END_BLOCK code */ #define LITERALS 256 /* number of literal bytes 0..255 */ #define L_CODES (LITERALS+1+LENGTH_CODES) /* number of Literal or Length codes, including the END_BLOCK code */ #define D_CODES 30 /* number of distance codes */ #define BL_CODES 19 /* number of codes used to transfer the bit lengths */ #define HEAP_SIZE (2*L_CODES+1) /* maximum heap size */ #define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ #define INIT_STATE 42 #define EXTRA_STATE 69 #define NAME_STATE 73 #define COMMENT_STATE 91 #define HCRC_STATE 103 #define BUSY_STATE 113 #define FINISH_STATE 666 /* Stream status */ /* Data structure describing a single value and its code string. */ typedef struct ct_data_s { union { U16 freq; /* frequency count */ U16 code; /* bit string */ } fc; union { U16 dad; /* father node in Huffman tree */ U16 len; /* length of bit string */ } dl; } FAR ct_data; #define Freq fc.freq #define Code fc.code #define Dad dl.dad #define Len dl.len typedef struct static_tree_desc_s static_tree_desc; typedef struct tree_desc_s { ct_data *dyn_tree; /* the dynamic tree */ int max_code; /* largest code with non zero frequency */ static_tree_desc *stat_desc; /* the corresponding static tree */ } tree_desc; /* A Pos is an index in the character window. We use short instead of int to * save space in the various tables. IPos is used only for parameter passing. */ typedef U16 Pos; typedef Pos Posf; typedef u_nsigned IPos; typedef struct internal_state { z_streamp strm; /* pointer back to this zlib stream */ int status; /* as the name implies */ U8 *pending_buf; /* output still pending */ U32 pending_buf_size; /* size of pending_buf */ U8 *pending_out; /* next pending byte to output to the stream */ uInt pending; /* nb of bytes in the pending buffer */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ gz_headerp gzhead; /* gzip header information to write */ uInt gzindex; /* where in extra, name, or comment */ U8 method; /* STORED (for zip only) or DEFLATED */ int last_flush; /* value of flush param for previous deflate call */ /* used by deflate.c: */ uInt w_size; /* LZ77 window size (32K by default) */ uInt w_bits; /* log2(w_size) (8..16) */ uInt w_mask; /* w_size - 1 */ U8 *window; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. Also, it limits * the window size to 64K, which is quite useful on MSDOS. * To do: use the user input buffer as sliding window. */ U32 window_size; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ Posf *prev; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ Posf *head; /* Heads of the hash chains or NIL. */ uInt ins_h; /* hash index of string to be inserted */ uInt hash_size; /* number of elements in hash table */ uInt hash_bits; /* log2(hash_size) */ uInt hash_mask; /* hash_size-1 */ uInt hash_shift; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ S32 block_start; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ uInt match_length; /* length of best match */ IPos prev_match; /* previous match */ int match_available; /* set if previous match exists */ uInt strstart; /* start of string to insert */ uInt match_start; /* start of matching string */ uInt lookahead; /* number of valid bytes ahead in window */ uInt prev_length; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ uInt max_chain_length; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ uInt max_lazy_match; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ # define max_insert_length max_lazy_match /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ int level; /* compression level (1..9) */ int strategy; /* favor or force Huffman coding*/ uInt good_match; /* Use a faster search when the previous match is longer than this */ int nice_match; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to supress compiler warning */ struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ struct tree_desc_s l_desc; /* desc. for literal tree */ struct tree_desc_s d_desc; /* desc. for distance tree */ struct tree_desc_s bl_desc; /* desc. for bit length tree */ U16 bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ int heap_len; /* number of elements in the heap */ int heap_max; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ U8 depth[2*L_CODES+1]; /* Depth of each subtree used as tie breaker for trees of equal frequency */ U8 *l_buf; /* buffer for literals or lengths */ uInt lit_bufsize; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ uInt last_lit; /* running index in l_buf */ U16 *d_buf; /* Buffer for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ U32 opt_len; /* bit length of current block with optimal trees */ U32 static_len; /* bit length of current block with static trees */ uInt matches; /* number of string matches in current block */ int last_eob_len; /* bit length of EOB code for last block */ U16 bi_buf; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ int bi_valid; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ } deflate_state; /* Output a byte on the stream. * IN assertion: there is enough room in pending_buf. */ #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} /* Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* In order to simplify the code, particularly on 16 bit machines, match * distances are limited to MAX_DIST instead of WSIZE. */ #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) void _tr_init (deflate_state *s); void _tr_flush_block (deflate_state *s, U8 *buf, U32 stored_len, int eof); void _tr_align (deflate_state *s); void _tr_stored_block (deflate_state *s, U8 *buf, U32 stored_len, int eof); static void lm_init (deflate_state *s); /* Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. _dist_code[256] and _dist_code[257] are never * used. */ #define d_code(dist) \ ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) # define _tr_tally_lit(s, c, flush) \ { U8 cc = (c); \ s->d_buf[s->last_lit] = 0; \ s->l_buf[s->last_lit++] = cc; \ s->dyn_ltree[cc].Freq++; \ flush = (s->last_lit == s->lit_bufsize-1); \ } /* cast in the following macro: U8, U16 */ # define _tr_tally_dist(s, distance, length, flush) \ { U8 len = (U8)(length); \ U16 dist = (U16)(distance); \ s->d_buf[s->last_lit] = dist; \ s->l_buf[s->last_lit++] = len; \ dist--; \ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ s->dyn_dtree[d_code(dist)].Freq++; \ flush = (s->last_lit == s->lit_bufsize-1); \ } /**************************************************************************** trees.h/.c ****************************************************************************/ #define MAX_BL_BITS 7 /* Bit length codes must not exceed MAX_BL_BITS bits */ #define END_BLOCK 256 /* end of block literal code */ #define REP_3_6 16 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ #define REPZ_3_10 17 /* repeat a zero length 3-10 times (3 bits of repeat count) */ #define REPZ_11_138 18 /* repeat a zero length 11-138 times (7 bits of repeat count) */ static const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; static const int extra_dbits[D_CODES] /* extra bits for each distance code */ = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; static const U8 bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ #define Buf_size (8 * 2*sizeof(U8)) /* Number of bits used within bi_buf. (bi_buf might be implemented on * more than 16 bits on some systems.) */ #define DIST_CODE_LEN 512 static const ct_data static_ltree[L_CODES+2] = { {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} }; static const ct_data static_dtree[D_CODES] = { {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} }; const U8 _dist_code[DIST_CODE_LEN] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; const U8 _length_code[MAX_MATCH-MIN_MATCH+1]= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; static const int base_length[LENGTH_CODES] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; static const int base_dist[D_CODES] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; struct static_tree_desc_s { const ct_data *static_tree; /* static tree or NULL */ const int *extra_bits; /* extra bits for each code or NULL */ int extra_base; /* base index for extra_bits */ int elems; /* max number of elements in the tree */ int max_length; /* max bit length for the codes */ }; static static_tree_desc static_l_desc = {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; static static_tree_desc static_d_desc = {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; static static_tree_desc static_bl_desc = {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; static void init_block (deflate_state *s); static void pqdownheap (deflate_state *s, ct_data *tree, int k); static void gen_bitlen (deflate_state *s, tree_desc *desc); static void gen_codes (ct_data *tree, int max_code, U16 *bl_count); static void build_tree (deflate_state *s, tree_desc *desc); static void scan_tree (deflate_state *s, ct_data *tree, int max_code); static void send_tree (deflate_state *s, ct_data *tree, int max_code); static int build_bl_tree (deflate_state *s); static void send_all_trees (deflate_state *s, int lcodes, int dcodes, int blcodes); static void compress_block (deflate_state *s, ct_data *ltree, ct_data *dtree); static void set_data_type (deflate_state *s); static u_nsigned bi_reverse(u_nsigned value, int length); static void bi_windup (deflate_state *s); static void bi_flush (deflate_state *s); static void copy_block (deflate_state *s, U8 *buf, u_nsigned len, int header); /* Send a code of the given tree. c and tree must not have side effects */ #define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ #define put_short(s, w) { \ put_byte(s, (U8)((w) & 0xff)); \ put_byte(s, (U8)((U16)(w) >> 8)); \ } #define send_bits(s, value, length) \ { int len = length; \ if (s->bi_valid > (int)Buf_size - len) { \ int val = value; \ s->bi_buf |= (val << s->bi_valid); \ put_short(s, s->bi_buf); \ s->bi_buf = (U16)val >> (Buf_size - s->bi_valid); \ s->bi_valid += len - Buf_size; \ } else { \ s->bi_buf |= (value) << s->bi_valid; \ s->bi_valid += len; \ } \ } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ static void send_tree (deflate_state *s, ct_data *tree, int max_code) { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen == 0) max_count = 138, min_count = 3; for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s->bl_tree); } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { send_code(s, curlen, s->bl_tree); count--; } send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ static void gen_bitlen(deflate_state *s, tree_desc *desc) { ct_data *tree = desc->dyn_tree; int max_code = desc->max_code; const ct_data *stree = desc->stat_desc->static_tree; const int *extra = desc->stat_desc->extra_bits; int base = desc->stat_desc->extra_base; int max_length = desc->stat_desc->max_length; int h; /* heap index */ int n, m; /* iterate over the tree elements */ int bits; /* bit length */ int xbits; /* extra bits */ U16 f; /* frequency */ int overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ for (h = s->heap_max+1; h < HEAP_SIZE; h++) { n = s->heap[h]; bits = tree[tree[n].Dad].Len + 1; if (bits > max_length) bits = max_length, overflow++; tree[n].Len = (U16)bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ s->bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n].Freq; s->opt_len += (U32)f * (bits + xbits); if (stree) s->static_len += (U32)f * (stree[n].Len + xbits); } if (overflow == 0) return; /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s->bl_count[bits] == 0) bits--; s->bl_count[bits]--; /* move one leaf down the tree */ s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ s->bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits != 0; bits--) { n = s->bl_count[bits]; while (n != 0) { m = s->heap[--h]; if (m > max_code) continue; if ((u_nsigned) tree[m].Len != (u_nsigned) bits) { s->opt_len += ((S32)bits - (S32)tree[m].Len) *(S32)tree[m].Freq; tree[m].Len = (U16)bits; } n--; } } } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ static void scan_tree (deflate_state *s, ct_data *tree, int max_code) { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ if (nextlen == 0) max_count = 138, min_count = 3; tree[max_code+1].Len = (U16)0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { s->bl_tree[curlen].Freq += count; } else if (curlen != 0) { if (curlen != prevlen) s->bl_tree[curlen].Freq++; s->bl_tree[REP_3_6].Freq++; } else if (count <= 10) { s->bl_tree[REPZ_3_10].Freq++; } else { s->bl_tree[REPZ_11_138].Freq++; } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ void _tr_init(deflate_state *s) { s->l_desc.dyn_tree = s->dyn_ltree; s->l_desc.stat_desc = &static_l_desc; s->d_desc.dyn_tree = s->dyn_dtree; s->d_desc.stat_desc = &static_d_desc; s->bl_desc.dyn_tree = s->bl_tree; s->bl_desc.stat_desc = &static_bl_desc; s->bi_buf = 0; s->bi_valid = 0; s->last_eob_len = 8; /* enough lookahead for inflate */ /* Initialize the first block of the first file: */ init_block(s); } #define SMALLEST 1 /* Index within the heap array of least frequent node in the Huffman tree */ /* =========================================================================== * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */ #define pqremove(s, tree, top) \ { \ top = s->heap[SMALLEST]; \ s->heap[SMALLEST] = s->heap[s->heap_len--]; \ pqdownheap(s, tree, SMALLEST); \ } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ #define smaller(tree, n, m, depth) \ (tree[n].Freq < tree[m].Freq || \ (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ static void pqdownheap(deflate_state *s, ct_data *tree, int k) { int v = s->heap[k]; int j = k << 1; /* left son of k */ while (j <= s->heap_len) { /* Set j to the smallest of the two sons: */ if (j < s->heap_len && smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s->heap[j], s->depth)) break; /* Exchange v with the smallest son */ s->heap[k] = s->heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s->heap[k] = v; } /* =========================================================================== * Initialize a new block. */ static void init_block(deflate_state *s) { int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; s->last_lit = s->matches = 0; } /* =========================================================================== * Send a stored block */ void _tr_stored_block(deflate_state *s, U8 *buf, U32 stored_len, int eof) { send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ copy_block(s, buf, (u_nsigned)stored_len, 1); /* with header */ } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ static void bi_flush(deflate_state *s) { if (s->bi_valid == 16) { put_short(s, s->bi_buf); s->bi_buf = 0; s->bi_valid = 0; } else if (s->bi_valid >= 8) { put_byte(s, (U8)s->bi_buf); s->bi_buf >>= 8; s->bi_valid -= 8; } } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ static void bi_windup(deflate_state *s) { if (s->bi_valid > 8) { put_short(s, s->bi_buf); } else if (s->bi_valid > 0) { put_byte(s, (U8)s->bi_buf); } s->bi_buf = 0; s->bi_valid = 0; } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ static void gen_codes (ct_data *tree, int max_code, U16 *bl_count) { U16 next_code[MAX_BITS+1]; /* next code value for each bit length */ U16 code = 0; /* running code value */ int bits; /* bit index */ int n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } for (n = 0; n <= max_code; n++) { int len = tree[n].Len; if (len == 0) continue; /* Now reverse the bits */ tree[n].Code = (U16)bi_reverse(next_code[len]++, len); /* cast */ } } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ static void send_all_trees(deflate_state *s, int lcodes, int dcodes, int blcodes) { int rank; /* index in bl_order */ send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); } send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ } /* =========================================================================== * Set the data type to BINARY or TEXT, using a crude approximation: * set it to Z_TEXT if all symbols are either printable characters (33 to 255) * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. * IN assertion: the fields Freq of dyn_ltree are set. */ static void set_data_type(deflate_state *s) { int n; for (n = 0; n < 9; n++) if (s->dyn_ltree[n].Freq != 0) break; if (n == 9) for (n = 14; n < 32; n++) if (s->dyn_ltree[n].Freq != 0) break; s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ static u_nsigned bi_reverse(u_nsigned code, int len) { register u_nsigned res = 0; do { res |= code & 1; code >>= 1, res <<= 1; } while (--len > 0); return res >> 1; } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ static void build_tree(deflate_state *s, tree_desc *desc) { ct_data *tree = desc->dyn_tree; const ct_data *stree = desc->stat_desc->static_tree; int elems = desc->stat_desc->elems; int n, m; /* iterate over heap elements */ int max_code = -1; /* largest code with non zero frequency */ int node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s->heap_len = 0, s->heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n].Freq != 0) { s->heap[++(s->heap_len)] = max_code = n; s->depth[n] = 0; } else { tree[n].Len = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s->heap_len < 2) { node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); tree[node].Freq = 1; s->depth[node] = 0; s->opt_len--; if (stree) s->static_len -= stree[node].Len; /* node is 0 or 1 so it does not have extra bits */ } desc->max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { pqremove(s, tree, n); /* n = node of least frequency */ m = s->heap[SMALLEST]; /* m = node of next least frequency */ s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ s->heap[--(s->heap_max)] = m; /* Create a new node father of n and m */ tree[node].Freq = tree[n].Freq + tree[m].Freq; s->depth[node] = (U8)((s->depth[n] >= s->depth[m] ? s->depth[n] : s->depth[m]) + 1); tree[n].Dad = tree[m].Dad = (U16)node; /* and insert the new node in the heap */ s->heap[SMALLEST] = node++; pqdownheap(s, tree, SMALLEST); } while (s->heap_len >= 2); s->heap[--(s->heap_max)] = s->heap[SMALLEST]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, (tree_desc *)desc); /* The field len is now set, we can generate the bit codes */ gen_codes ((ct_data *)tree, max_code, s->bl_count); } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ static int build_bl_tree(deflate_state *s) { int max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); /* Build the bit length tree: */ build_tree(s, (tree_desc *)(&(s->bl_desc))); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; } /* Update opt_len to include the bit length tree and counts */ s->opt_len += 3*(max_blindex+1) + 5+5+4; return max_blindex; } /* =========================================================================== * Send the block data compressed using the given Huffman trees */ static void compress_block(deflate_state *s, ct_data *ltree, ct_data *dtree) { u_nsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ u_nsigned lx = 0; /* running index in l_buf */ u_nsigned code; /* the code to send */ int extra; /* number of extra bits to send */ if (s->last_lit != 0) do { dist = s->d_buf[lx]; lc = s->l_buf[lx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra != 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra != 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ } while (lx < s->last_lit); send_code(s, END_BLOCK, ltree); s->last_eob_len = ltree[END_BLOCK].Len; } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ void _tr_flush_block(deflate_state *s, U8 *buf, U32 stored_len, int eof) { U32 opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s->level > 0) { /* Check if the file is binary or text */ if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) set_data_type(s); /* Construct the literal and distance trees */ build_tree(s, (tree_desc *)(&(s->l_desc))); build_tree(s, (tree_desc *)(&(s->d_desc))); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s->opt_len+3+7)>>3; static_lenb = (s->static_len+3+7)>>3; if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } #ifdef FORCE_STORED if (buf != (char*)0) { /* force stored block */ #else if (stored_len+4 <= opt_lenb && buf != 0) { /* 4: two words for the lengths */ #endif /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, eof); #ifdef FORCE_STATIC } else if (static_lenb >= 0) { /* force static trees */ #else } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { #endif send_bits(s, (STATIC_TREES<<1)+eof, 3); compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); } else { send_bits(s, (DYN_TREES<<1)+eof, 3); send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); } /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (eof) { bi_windup(s); } } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. * The current inflate code requires 9 bits of lookahead. If the * last two codes for the previous block (real code plus EOB) were coded * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode * the last real code. In this case we send two empty static blocks instead * of one. (There are no problems if the previous block is stored or fixed.) * To simplify the code, we assume the worst case of last real code encoded * on one bit only. */ void _tr_align(deflate_state *s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); /* Of the 10 bits for the empty block, we have already sent * (10 - bi_valid) bits. The lookahead for the last real code (before * the EOB of the previous block) was thus at least one plus the length * of the EOB plus what we have just sent of the empty static block. */ if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } s->last_eob_len = 7; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ static void copy_block(deflate_state *s, U8 *buf, u_nsigned len, int header) { bi_windup(s); /* align on byte boundary */ s->last_eob_len = 8; /* enough lookahead for inflate */ if (header) { put_short(s, (U16)len); put_short(s, (U16)~len); } while (len--) { put_byte(s, *buf++); } } /**************************************************************************** deflate.c ****************************************************************************/ # define def_check_match(s, start, match, length) /* =========================================================================== * Function prototypes. */ typedef enum { need_more, /* block not completed, need more input or more output */ block_done, /* block flush performed */ finish_started, /* finish started, need only more output at next deflate */ finish_done /* finish done, accept no more input or output */ } block_state; typedef block_state (*compress_func) (deflate_state *s, int flush); /* Compression function. Returns the block state after the call. */ static void fill_window (deflate_state *s); static block_state deflate_stored (deflate_state *s, int flush); static block_state deflate_fast (deflate_state *s, int flush); static block_state deflate_slow (deflate_state *s, int flush); static void lm_init (deflate_state *s); static void putShortMSB (deflate_state *s, uInt b); static void flush_pending (z_streamp strm); static int read_buf (z_streamp strm, U8 *buf, u_nsigned size); /* =========================================================================== * Local data */ #define NIL 0 /* Tail of hash chains */ #ifndef TOO_FAR # define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ typedef struct config_s { U16 good_length; /* reduce lazy search above this match length */ U16 max_lazy; /* do not perform lazy search above this match length */ U16 nice_length; /* quit search above this match length */ U16 max_chain; compress_func func; } config; static const config configuration_table[10] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ /* 2 */ {4, 5, 16, 8, deflate_fast}, /* 3 */ {4, 6, 32, 32, deflate_fast}, /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ /* 5 */ {8, 16, 32, 32, deflate_slow}, /* 6 */ {8, 16, 128, 128, deflate_slow}, /* 7 */ {8, 32, 128, 256, deflate_slow}, /* 8 */ {32, 128, 258, 1024, deflate_slow}, /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different * meaning. */ #define EQUAL 0 /* result of memcmp for equal strings */ /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive * input characters, so that a running hash key can be computed from the * previous key instead of complete recalculation each time. */ #define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) /* =========================================================================== * Insert string str in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. * IN assertion: all calls to to INSERT_STRING are made with consecutive * input characters and the first MIN_MATCH bytes of str are valid * (except for the last MIN_MATCH-1 bytes of the input file). */ #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ s->head[s->hash_size-1] = NIL; \ memset((U8 *)s->head, 0, (u_nsigned)(s->hash_size-1)*sizeof(*s->head)); /* ========================================================================= */ int deflateInit_ (z_streamp strm, int level, const char *version, int stream_size) { return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size); /* To do: ignore strm->next_in if we use it as window */ } /* ========================================================================= */ int deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size) { deflate_state *s; int wrap = 1; static const char my_version[] = ZLIB_VERSION; U16 *overlay; /* We overlay pending_buf and d_buf+l_buf. This works since the average * output size for (length,distance) codes is <= 24 bits. */ if (version == NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { return Z_VERSION_ERROR; } if (strm == NULL) return Z_STREAM_ERROR; if (level == Z_DEFAULT_COMPRESSION) level = 6; if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } #ifdef GZIP else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } #endif if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ s = (deflate_state *)zeroBaMalloc(sizeof(deflate_state)); if (s == NULL) return Z_MEM_ERROR; strm->state = (struct internal_state *)s; s->strm = strm; s->wrap = wrap; s->gzhead = NULL; s->w_bits = windowBits; s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; s->hash_bits = memLevel + 7; s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); s->window = (U8 *) zeroBaMalloc(s->w_size * 2*sizeof(U8)); s->prev = (Posf *) zeroBaMalloc(s->w_size * sizeof(Pos)); s->head = (Posf *) zeroBaMalloc(s->hash_size * sizeof(Pos)); s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ overlay = (U16 *) zeroBaMalloc(s->lit_bufsize * (sizeof(U16)+2)); s->pending_buf = (U8 *) overlay; s->pending_buf_size = (U32)s->lit_bufsize * (sizeof(U16)+2L); if (s->window == NULL || s->prev == NULL || s->head == NULL || s->pending_buf == NULL) { s->status = FINISH_STATE; deflateEnd (strm); return Z_MEM_ERROR; } s->d_buf = overlay + s->lit_bufsize/sizeof(U16); s->l_buf = s->pending_buf + (1+sizeof(U16))*s->lit_bufsize; s->level = level; s->strategy = strategy; s->method = (U8)method; return deflateReset(strm); } /* ========================================================================= */ int deflateReset (z_streamp strm) { deflate_state *s; if (strm == NULL || strm->state == NULL) { return Z_STREAM_ERROR; } strm->total_in = strm->total_out = 0; /* strm->msg = NULL; use baFree if we ever allocate msg dynamically */ strm->data_type = Z_UNKNOWN; s = (deflate_state *)strm->state; s->pending = 0; s->pending_out = s->pending_buf; if (s->wrap < 0) { s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ } s->status = s->wrap ? INIT_STATE : BUSY_STATE; strm->adler = #ifdef GZIP s->wrap == 2 ? crc32(0L, NULL, 0) : #endif adler32(0L, NULL, 0); s->last_flush = Z_NO_FLUSH; _tr_init(s); lm_init(s); return Z_OK; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ static void putShortMSB (deflate_state *s, uInt b) { put_byte(s, (U8)(b >> 8)); put_byte(s, (U8)(b & 0xff)); } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->next_out buffer and copying into it. * (See also read_buf()). */ static void flush_pending(z_streamp strm) { u_nsigned len = strm->state->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; memcpy(strm->next_out, strm->state->pending_out, len); strm->next_out += len; strm->state->pending_out += len; strm->total_out += len; strm->avail_out -= len; strm->state->pending -= len; if (strm->state->pending == 0) { strm->state->pending_out = strm->state->pending_buf; } } /* ========================================================================= */ int deflate (z_streamp strm, int flush) { int old_flush; /* value of flush param for previous deflate call */ deflate_state *s; if (strm == NULL || strm->state == NULL || flush > Z_FINISH || flush < 0) { return Z_STREAM_ERROR; } s = strm->state; if (strm->next_out == NULL || (strm->next_in == NULL && strm->avail_in != 0) || (s->status == FINISH_STATE && flush != Z_FINISH)) { return Z_STREAM_ERROR; } if (strm->avail_out == 0) return Z_BUF_ERROR; s->strm = strm; /* just in case */ old_flush = s->last_flush; s->last_flush = flush; /* Write the header */ if (s->status == INIT_STATE) { #ifdef GZIP if (s->wrap == 2) { strm->adler = crc32(0L, NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (s->gzhead == NULL) { put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s->status = BUSY_STATE; } else { put_byte(s, (s->gzhead->text ? 1 : 0) + (s->gzhead->hcrc ? 2 : 0) + (s->gzhead->extra == NULL ? 0 : 4) + (s->gzhead->name == NULL ? 0 : 8) + (s->gzhead->comment == NULL ? 0 : 16) ); put_byte(s, (Byte)(s->gzhead->time & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, s->gzhead->os & 0xff); if (s->gzhead->extra != NULL) { put_byte(s, s->gzhead->extra_len & 0xff); put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); } if (s->gzhead->hcrc) strm->adler = crc32(strm->adler, s->pending_buf, s->pending); s->gzindex = 0; s->status = EXTRA_STATE; } } else #endif { uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; uInt level_flags; if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) level_flags = 0; else if (s->level < 6) level_flags = 1; else if (s->level == 6) level_flags = 2; else level_flags = 3; header |= (level_flags << 6); if (s->strstart != 0) header |= PRESET_DICT; header += 31 - (header % 31); s->status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s->strstart != 0) { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } strm->adler = adler32(0L, NULL, 0); } } #ifdef GZIP if (s->status == EXTRA_STATE) { if (s->gzhead->extra != NULL) { uInt beg = s->pending; /* start of bytes to update crc */ while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) break; } put_byte(s, s->gzhead->extra[s->gzindex]); s->gzindex++; } if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (s->gzindex == s->gzhead->extra_len) { s->gzindex = 0; s->status = NAME_STATE; } } else s->status = NAME_STATE; } if (s->status == NAME_STATE) { if (s->gzhead->name != NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->name[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) { s->gzindex = 0; s->status = COMMENT_STATE; } } else s->status = COMMENT_STATE; } if (s->status == COMMENT_STATE) { if (s->gzhead->comment != NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->comment[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) s->status = HCRC_STATE; } else s->status = HCRC_STATE; } if (s->status == HCRC_STATE) { if (s->gzhead->hcrc) { if (s->pending + 2 > s->pending_buf_size) flush_pending(strm); if (s->pending + 2 <= s->pending_buf_size) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); strm->adler = crc32(0L, NULL, 0); s->status = BUSY_STATE; } } else s->status = BUSY_STATE; } #endif /* Flush as much pending output as possible */ if (s->pending != 0) { flush_pending(strm); if (strm->avail_out == 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s->last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm->avail_in == 0 && flush <= old_flush && flush != Z_FINISH) { return Z_BUF_ERROR; } /* User must not provide more input after the first FINISH: */ if (s->status == FINISH_STATE && strm->avail_in != 0) { return Z_BUF_ERROR; } /* Start a new block or continue the current one. */ if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { block_state bstate; bstate = (*(configuration_table[s->level].func))(s, flush); if (bstate == finish_started || bstate == finish_done) { s->status = FINISH_STATE; } if (bstate == need_more || bstate == finish_started) { if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate == block_done) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(s); } else { /* FULL_FLUSH or SYNC_FLUSH */ _tr_stored_block(s, 0, 0L, 0); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush == Z_FULL_FLUSH) { CLEAR_HASH(s); /* forget history */ } } flush_pending(strm); if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } if (flush != Z_FINISH) return Z_OK; if (s->wrap <= 0) return Z_STREAM_END; /* Write the trailer */ #ifdef GZIP if (s->wrap == 2) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); put_byte(s, (Byte)(strm->total_in & 0xff)); put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); } else #endif { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ return s->pending != 0 ? Z_OK : Z_STREAM_END; } /* ========================================================================= */ int deflateEnd (z_streamp strm) { int status; if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR; status = strm->state->status; if (status != INIT_STATE && status != EXTRA_STATE && status != NAME_STATE && status != COMMENT_STATE && status != HCRC_STATE && status != BUSY_STATE && status != FINISH_STATE) { return Z_STREAM_ERROR; } /* Deallocate in reverse order of allocations: */ #define TRY_FREE(s, p) {if (p) baFree(p);} TRY_FREE(strm, strm->state->pending_buf); TRY_FREE(strm, strm->state->head); TRY_FREE(strm, strm->state->prev); TRY_FREE(strm, strm->state->window); baFree(strm->state); strm->state = NULL; return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ static int read_buf(z_streamp strm, U8 *buf, u_nsigned size) { u_nsigned len = strm->avail_in; if (len > size) len = size; if (len == 0) return 0; strm->avail_in -= len; if (strm->state->wrap == 1) { strm->adler = adler32(strm->adler, strm->next_in, len); } #ifdef GZIP else if (strm->state->wrap == 2) { strm->adler = crc32(strm->adler, strm->next_in, len); } #endif memcpy(buf, strm->next_in, len); strm->next_in += len; strm->total_in += len; return (int)len; } /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ static void lm_init (deflate_state *s) { s->window_size = (U32)2L*s->w_size; CLEAR_HASH(s); /* Set the default configuration parameters: */ s->max_lazy_match = configuration_table[s->level].max_lazy; s->good_match = configuration_table[s->level].good_length; s->nice_match = configuration_table[s->level].nice_length; s->max_chain_length = configuration_table[s->level].max_chain; s->strstart = 0; s->block_start = 0L; s->lookahead = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ static uInt longest_match(deflate_state *s, IPos cur_match) { u_nsigned chain_length = s->max_chain_length;/* max hash chain length */ register U8 *scan = s->window + s->strstart; /* current string */ register U8 *match; /* matched string */ register int len; /* length of current match */ int best_len = s->prev_length; /* best match length so far */ int nice_match = s->nice_match; /* stop if match long enough */ IPos limit = s->strstart > (IPos)MAX_DIST(s) ? s->strstart - (IPos)MAX_DIST(s) : NIL; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ Pos *prev = s->prev; uInt wmask = s->w_mask; #ifdef UNALIGNED_OK /* Compare two bytes at a time. Note: this is not always beneficial. * Try with and without -DUNALIGNED_OK to check. */ register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; register ush scan_start = *(ushf*)scan; register ush scan_end = *(ushf*)(scan+best_len-1); #else register U8 *strend = s->window + s->strstart + MAX_MATCH; register U8 scan_end1 = scan[best_len-1]; register U8 scan_end = scan[best_len]; #endif /* Do not waste too much time if we already have a good match: */ if (s->prev_length >= s->good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; do { match = s->window + cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) /* This code assumes sizeof(U16) == 2. Do not use * UNALIGNED_OK if your compiler uses a different size. */ if (*(U16*)(match+best_len-1) != scan_end || *(U16*)match != scan_start) continue; /* It is not necessary to compare scan[2] and match[2] since they are * always equal when the other bytes match, given that the hash keys * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at * strstart+3, +5, ... up to strstart+257. We check for insufficient * lookahead only every 4th comparison; the 128th check will be made * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is * necessary to put more guard bytes at the end of the window, or * to check more often for insufficient lookahead. */ scan++, match++; do { } while (*(U16*)(scan+=2) == *(U16*)(match+=2) && *(U16*)(scan+=2) == *(U16*)(match+=2) && *(U16*)(scan+=2) == *(U16*)(match+=2) && *(U16*)(scan+=2) == *(U16*)(match+=2) && scan < strend); /* The funny "do {}" generates better code on most compilers */ /* Here, scan <= window+strstart+257 */ if (*scan == *match) scan++; len = (MAX_MATCH - 1) - (int)(strend-scan); scan = strend - (MAX_MATCH-1); #else /* UNALIGNED_OK */ if (match[best_len] != scan_end || match[best_len-1] != scan_end1 || *match != *scan || *++match != scan[1]) continue; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match++; /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); len = MAX_MATCH - (int)(strend - scan); scan = strend - MAX_MATCH; #endif /* UNALIGNED_OK */ if (len > best_len) { s->match_start = cur_match; best_len = len; if (len >= nice_match) break; #ifdef UNALIGNED_OK scan_end = *(U16*)(scan+best_len-1); #else scan_end1 = scan[best_len-1]; scan_end = scan[best_len]; #endif } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length != 0); if ((uInt)best_len <= s->lookahead) return (uInt)best_len; return s->lookahead; } /* --------------------------------------------------------------------------- * Optimized version for level == 1 or strategy == Z_RLE only */ static uInt longest_match_fast(deflate_state *s, IPos cur_match) { register U8 *scan = s->window + s->strstart; /* current string */ register U8 *match; /* matched string */ register int len; /* length of current match */ register U8 *strend = s->window + s->strstart + MAX_MATCH; match = s->window + cur_match; /* Return failure if the match length is less than 2: */ if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match += 2; /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); len = MAX_MATCH - (int)(strend - scan); if (len < MIN_MATCH) return MIN_MATCH - 1; s->match_start = cur_match; return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ static void fill_window(deflate_state *s) { register u_nsigned n, m; register Posf *p; u_nsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; do { more = (u_nsigned)(s->window_size -(U32)s->lookahead -(U32)s->strstart); /* Deal with !@#$% 64K limit: */ if (sizeof(int) <= 2) { if (more == 0 && s->strstart == 0 && s->lookahead == 0) { more = wsize; } else if (more == (u_nsigned)(-1)) { /* Very unlikely, but possible on 16 bit machine if * strstart == 0 && lookahead == 1 (input done a byte at time) */ more--; } } /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s->strstart >= wsize+MAX_DIST(s)) { memcpy(s->window, s->window+wsize, (u_nsigned)wsize); s->match_start -= wsize; s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ s->block_start -= (S32) wsize; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ /* %%% avoid this when Z_RLE */ n = s->hash_size; p = &s->head[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); } while (--n); n = wsize; p = &s->prev[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += wsize; } if (s->strm->avail_in == 0) return; n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ if (s->lookahead >= MIN_MATCH) { s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); } /* =========================================================================== * Flush the current block, with given end-of-file flag. * IN assertion: strstart is set to the end of the current match. */ #define FLUSH_BLOCK_ONLY(s, eof) { \ _tr_flush_block(s, (s->block_start >= 0L ? \ (U8 *)&s->window[(u_nsigned)s->block_start] : \ (U8 *)NULL), \ (U32)((S32)s->strstart - s->block_start), \ (eof)); \ s->block_start = s->strstart; \ flush_pending(s->strm); \ } /* Same but force premature exit if necessary. */ #define FLUSH_BLOCK(s, eof) { \ FLUSH_BLOCK_ONLY(s, eof); \ if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ static block_state deflate_stored(deflate_state *s, int flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ U32 max_block_size = 0xffff; U32 max_start; if (max_block_size > s->pending_buf_size - 5) { max_block_size = s->pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s->lookahead <= 1) { fill_window(s); if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; if (s->lookahead == 0) break; /* flush the current block */ } s->strstart += s->lookahead; s->lookahead = 0; /* Emit a stored block if pending_buf will be full: */ max_start = s->block_start + max_block_size; if (s->strstart == 0 || (U32)s->strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s->lookahead = (u_nsigned)(s->strstart - max_start); s->strstart = (u_nsigned)max_start; FLUSH_BLOCK(s, 0); } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { FLUSH_BLOCK(s, 0); } } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ static block_state deflate_fast(deflate_state *s, int flush) { IPos hash_head = NIL; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { s->match_length = longest_match (s, hash_head); } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { s->match_length = longest_match_fast (s, hash_head); } /* longest_match() or longest_match_fast() sets match_start */ } if (s->match_length >= MIN_MATCH) { def_check_match(s, s->strstart, s->match_start, s->match_length); _tr_tally_dist(s, s->strstart - s->match_start, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s->match_length <= s->max_insert_length && s->lookahead >= MIN_MATCH) { s->match_length--; /* string at strstart already in table */ do { s->strstart++; INSERT_STRING(s, s->strstart, hash_head); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s->match_length != 0); s->strstart++; } else { s->strstart += s->match_length; s->match_length = 0; s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ static block_state deflate_slow(deflate_state *s, int flush) { IPos hash_head = NIL; /* head of hash chain */ int bflush; /* set if current block must be flushed */ /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. */ s->prev_length = s->match_length, s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { s->match_length = longest_match (s, hash_head); } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { s->match_length = longest_match_fast (s, hash_head); } /* longest_match() or longest_match_fast() sets match_start */ if (s->match_length <= 5 && (s->strategy == Z_FILTERED #if TOO_FAR <= 32767 || (s->match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR) #endif )) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s->match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ def_check_match(s, s->strstart-1, s->prev_match, s->prev_length); _tr_tally_dist(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH, bflush); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s->lookahead -= s->prev_length-1; s->prev_length -= 2; do { if (++s->strstart <= max_insert) { INSERT_STRING(s, s->strstart, hash_head); } } while (--s->prev_length != 0); s->match_available = 0; s->match_length = MIN_MATCH-1; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } else if (s->match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ _tr_tally_lit(s, s->window[s->strstart-1], bflush); if (bflush) { FLUSH_BLOCK_ONLY(s, 0); } s->strstart++; s->lookahead--; if (s->strm->avail_out == 0) return need_more; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s->match_available = 1; s->strstart++; s->lookahead--; } } if (s->match_available) { _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } #endif /* BA_DEFLATE */ #endif /* NO_ZLIB */ #if USE_OPCUA == 1 #ifndef OPCUA_TYPES_H #define OPCUA_TYPES_H #include struct UA_Guid { uint32_t Data1; uint16_t Data2; uint16_t Data3; uint64_t Data4; }; struct UA_ExtensionObject { void* data; uint32_t size; uint32_t typeId; }; struct UA_ByteString { const uint8_t* data; uint32_t size; }; struct UA_Field { const char* name; const char* typeId; // nullptr for enum int32_t valueRank; int32_t enumValue; // Now support only integer enums }; struct UA_StructDefinition { unsigned size; const struct UA_Field* fields; }; struct UA_Variant; // universal structure to store attribute value. union UA_Value { uint8_t u8; int8_t i8; uint16_t u16; int16_t i16; uint32_t u32; int32_t i32; uint64_t u64; int64_t i64; float f; double d; const char* str; const uint8_t* u8Arr; const int8_t* i8Arr; const uint16_t* u16Arr; const int16_t* i16Arr; const uint32_t* u32Arr; const int32_t* i32Arr; const uint64_t* u64Arr; const int64_t* i64Arr; const float* fArr; const double* dArr; const char** strArr; const struct UA_Variant* vPtr; const struct UA_ExtensionObject* ePtr; const struct UA_ByteString* bPtr; const struct UA_StructDefinition* definitionPtr; }; enum UA_VariantType { UA_Type_Null = 0, UA_Type_Boolean = 1, /* UA_Value.u8 */ UA_Type_SByte = 2, /* UA_Value.i8 */ UA_Type_Byte = 3, /* UA_Value.u8 */ UA_Type_Int16 = 4, /* UA_Value.i16 */ UA_Type_UInt16 = 5, /* UA_Value.u16 */ UA_Type_Int32 = 6, /* UA_Value.i32 */ UA_Type_UInt32 = 7, /* UA_Value.u32 */ UA_Type_Int64 = 8, /* UA_Value.i64 */ UA_Type_UInt64 = 9, /* UA_Value.u64 */ UA_Type_Float = 10, /* UA_Value.f */ UA_Type_Double = 11, /* UA_Value.d */ UA_Type_String = 12, /* UA_Value.str */ UA_Type_DateTime = 13, /* UA_Value.d */ UA_Type_Guid = 14, /* UA_Value.g */ UA_Type_ByteString = 15, /* UA_Value.bstr */ UA_Type_XmlElement = 16, /* UA_Value.bstr */ UA_Type_NodeId = 17, /* UA_Value.u32 */ UA_Type_ExpandedNodeId = 18, /* UA_Value.u32 */ UA_Type_StatusCode = 19, /* UA_Value.u32 */ UA_Type_QualifiedName = 20, /* UA_Value.str */ UA_Type_LocalizedText = 21, /* UA_Value.str */ UA_Type_ExtensionObject = 22, /* UA_Value.eptr */ UA_Type_DataValue = 23, /* UA_Value.vptr */ UA_Type_Variant = 24, /* UA_Value.vptr */ UA_Type_DiagnosticInfo = 25 /* UA_Value.? */ }; struct UA_Variant { union UA_Value data; /*value of type */ int32_t size; /* number of elements in data: 0 - scalar, >0 size of array*/ uint8_t dataType; /* UA_VariantType */ }; enum { UA_AttributeId_NodeId = 1, /* UA_Type_NodeId, value.str*/ UA_AttributeId_NodeClass = 2, /* UA_Type_UInt32, value.u32*/ UA_AttributeId_BrowseName = 3, /* UA_Type_QualifiedName, value.str */ UA_AttributeId_DisplayName = 4, /* UA_Type_LocalizedText, value.str */ UA_AttributeId_Description = 5, /* UA_Type_LocalizedText, value.str */ UA_AttributeId_WriteMask = 6, /* UA_Type_UInt32, value.u32 */ UA_AttributeId_UserWriteMask = 7, /* UA_Type_UInt32, value.u32 */ UA_AttributeId_IsAbstract = 8, /* UA_Type_Boolean, value.u32 */ UA_AttributeId_Symmetric = 9, /* UA_Type_Boolean, value.u32 */ UA_AttributeId_InverseName = 10, /* UA_Type_QualifiedName, value.str */ UA_AttributeId_ContainsNoLoops = 11, /* UA_Type_Boolean, value.u32 */ UA_AttributeId_EventNotifier = 12, /* UA_Type_Boolean, value.u32 */ UA_AttributeId_Value = 13, /* UA_Type_Variant, value.vptr */ UA_AttributeId_DataType = 14, /* UA_Type_NodeId, value.str */ UA_AttributeId_ValueRank = 15, /* UA_Type_UInt32, value.i32 */ UA_AttributeId_ArrayDimensions = 16, /* UA_Type_Uint32(array), value.bPtr */ UA_AttributeId_AccessLevel = 17, /* UA_Type_Uint32, value.u32 */ UA_AttributeId_UserAccessLevel = 18, /* UA_Type_Uint32, value.u32 */ UA_AttributeId_MinimumSamplingInterval = 19, /* UA_Type_Double, value.f */ UA_AttributeId_Historizing = 20, /* UA_Type_Boolean, value.u32 */ UA_AttributeId_Executable = 21, /* UA_Type_Boolean, value.u32 */ UA_AttributeId_UserExecutable = 22, /* UA_Type_Boolean, value.u32 */ UA_AttributeId_DataTypeDefinition = 23, /* UA_Type_NodeId, value.str */ UA_AttributeId_RolePermissions = 24, UA_AttributeId_UserRolePermissions = 25, UA_AttributeId_AccessRestrictions = 26, UA_AttributeId_AccessLevelEx = 27 }; struct UA_Attribute { union UA_Value data; /* type of value is defined by attribute ID. */ uint8_t id; /* UA_AttributeId_Id */ }; struct UA_Reference { const char* nodeid; const char* refid; uint8_t isForward; }; struct UA_Node { uint32_t attrsSize; uint32_t refsSize; uint32_t definitionSize; const struct UA_Attribute* attrs; /* attrsSize */ const struct UA_Reference* refs; /* refsSize */ const struct UA_Field* definition; /* definitionSize */ /* Different IDS for the same DataType node: - BinaryId - id of binary encoding node - JsonId - id of json encoding node - DataTypeId - id of data type node: Encoding nodes JSON, BInary and DataType node All of them are kind of pointer to the same essence. DataTypeId can be seen in UI. But when client receives encoded extension object it will has different node ID: either BinaryId or JsonId. For reducing search efforts these four IDS identical for all: DataType node and for all the encoding nodes. */ const char* binaryId; /* id of binary encoding node */ const char* jsonId; /* id of json encoding node */ const char* baseId; /* id of base OPCUA type usually Structure i=22 or Enumeration i=29 */ const char* dataTypeId; /* id of data type node: Encoding nodes JSON, BInary and DataType node */ }; struct UA_Nodeset { const struct UA_Node* nodes; unsigned size; }; #endif // OPCUA_TYPES_H #endif #if USE_OPCUA == 1 #ifndef OPCUA_GET_NODE_H #define OPCUA_GET_NODE_H #ifndef OPCUA_TYPES_H #include "opcua_types.h" #endif const struct UA_Node* ns0_getNode(const char* id); const struct UA_Node* ns0_getNodeIdx(unsigned idx); #endif // OPCUA_GET_NODE_H #endif #if USE_OPCUA == 1 #ifndef OPCUA_GET_NODE_H #include "opcua_get_node.h" #endif #include "string.h" extern const struct UA_Nodeset nodeset; const struct UA_Node* ns0_getNode(const char* id) { uint32_t i = 1; uint32_t j = nodeset.size; while (i <= j) { const uint32_t mIx = (i + j) / 2; const struct UA_Node* node = &nodeset.nodes[mIx - 1]; const struct UA_Attribute* attr = node->attrs; if (attr->id != UA_AttributeId_NodeId) return 0; const int result = strcmp(id, attr->data.str); if (result == 0) return node; else if (result > 0) i = mIx + 1; else j = mIx - 1; } return 0; } const struct UA_Node* ns0_getNodeIdx(unsigned idx) { if (idx < nodeset.size) return &nodeset.nodes[idx]; return NULL; } #endif #if USE_OPCUA == 1 #ifndef OPCUA_MODULE_H #include "opcua_module.h" #endif #ifndef OPCUA_TYPES_H #include "opcua_get_node.h" #endif static void lua_pushNodeId(lua_State* L, const char* id) { if (id) lua_pushstring(L, id); else lua_pushnil(L); } static void lua_pushQualifiedName(lua_State* L, const char* name) { lua_createtable(L, 0, 2); /* local qname = {} */ lua_pushinteger(L, 0); /* local ns = 0 */ lua_setfield(L, -2, "ns"); /* qname["ns"] = ns */ lua_pushstring(L, name); /* local nm = name->data */ lua_setfield(L, -2, "Name"); /* qname["name"] = nm */ /* return qname */ } /* create lua localized text table */ static void lua_pushLocalizedText(lua_State* L, const char* text) { lua_createtable(L, 0, 1); /* local txt = {} */ lua_pushstring(L, text); /* local text = text->text */ lua_setfield(L, -2, "Text"); /* txt["Text"] = text */ /* return txt */ } void lua_pushVariantValue(lua_State* L, const enum UA_VariantType varType, const union UA_Value* value, int pos) { switch (varType) { case UA_Type_Boolean: /* UA_Value.u8 */ if (pos == -1) lua_pushboolean(L, value->u8 != 0 ? 1 : 0); else lua_pushboolean(L, value->u8Arr[pos] != 0 ? 1 : 0); break; case UA_Type_SByte: /* UA_Value.i8 */ if (pos == -1) lua_pushinteger(L, value->i8); else lua_pushinteger(L, value->i8Arr[pos]); break; case UA_Type_Byte: /* UA_Value.u8 */ if (pos == -1) lua_pushinteger(L, value->u8); else lua_pushinteger(L, value->u8Arr[pos]); break; case UA_Type_Int16: /* UA_Value.i16 */ if (pos == -1) lua_pushinteger(L, value->i16); else lua_pushinteger(L, value->i16Arr[pos]); break; case UA_Type_UInt16: /* UA_Value.u16 */ if (pos == -1) lua_pushinteger(L, value->u16); else lua_pushinteger(L, value->u16Arr[pos]); break; case UA_Type_Int32: /* UA_Value.i32 */ if (pos == -1) lua_pushinteger(L, value->i32); else lua_pushinteger(L, value->i32Arr[pos]); break; case UA_Type_UInt32: /* UA_Value.u32 */ if (pos == -1) lua_pushinteger(L, value->u32); else lua_pushinteger(L, value->u32Arr[pos]); break; case UA_Type_Int64: /* UA_Value.i64 */ if (pos == -1) lua_pushinteger(L, value->i64); else lua_pushinteger(L, value->i64Arr[pos]); break; case UA_Type_UInt64: /* UA_Value.u64 */ if (pos == -1) lua_pushinteger(L, value->u64); else lua_pushinteger(L, value->u64Arr[pos]); break; case UA_Type_Float: /* UA_Value.f */ if (pos == -1) lua_pushnumber(L, value->f); else lua_pushnumber(L, value->fArr[pos]); break; case UA_Type_Double: /* UA_Value.d */ if (pos == -1) lua_pushnumber(L, value->d); else lua_pushnumber(L, value->dArr[pos]); break; case UA_Type_String: /* UA_Value.str */ if (pos == -1) lua_pushstring(L, value->str); else lua_pushstring(L, value->strArr[pos]); break; case UA_Type_DateTime: /* UA_Value.d */ if (pos == -1) lua_pushnumber(L, value->d); else lua_pushnumber(L, value->dArr[pos]); break; case UA_Type_Guid: /* UA_Value.g */ lua_error(L); break; case UA_Type_ByteString: /* UA_Value.bstr */ if (pos == -1) lua_pushlstring(L, (const char*)value->bPtr->data, value->bPtr->size); else lua_error(L); break; case UA_Type_XmlElement: /* UA_Value.bstr */ lua_error(L); break; case UA_Type_NodeId: /* UA_Value.str */ if(pos == -1) lua_pushNodeId(L, value->str); else lua_error(L); break; case UA_Type_ExpandedNodeId: /* UA_Value.str */ if(pos == -1) lua_pushNodeId(L, value->str); else lua_error(L); break; case UA_Type_StatusCode: /* UA_Value.str */ if(pos == -1) lua_pushNodeId(L, value->str); else lua_error(L); break; case UA_Type_QualifiedName: /* UA_Value.str */ if(pos == -1) lua_pushQualifiedName(L, value->str); else lua_pushQualifiedName(L, value->strArr[pos]); break; case UA_Type_LocalizedText: /* UA_Value.str */ if(pos == -1) lua_pushLocalizedText(L, value->str); else lua_pushLocalizedText(L, value->strArr[pos]); break; case UA_Type_ExtensionObject: /* UA_Value.eptr */ lua_pushnil(L); break; case UA_Type_DataValue: /* UA_Value.vptr */ lua_pushnil(L); break; case UA_Type_Variant: /* UA_Value.vptr */ lua_pushnil(L); break; case UA_Type_DiagnosticInfo: /* UA_Value.? */ lua_pushnil(L); break; default: lua_error(L); } } static void lua_pushVariant(lua_State* L, const struct UA_Variant* var) { if (var == NULL || var->size == -1) { lua_pushnil(L); return; } if (var->size < 0) { lua_pushfstring(L, "INTERNAL ERROR: Invalid variant value size '%d'", var->size); lua_error(L); return; } /* local variant = {}*/ lua_createtable(L, 0, 1); if (var->dataType) { lua_pushinteger(L, var->dataType); lua_setfield(L, -2, "Type"); if (var->size == 0) { /* local value = lua_pushVariantValue() */ lua_pushVariantValue(L, var->dataType, &var->data, -1); } else if (var->size > 0) { /* local value = {} -- array of values*/ lua_createtable(L, var->size, 0); for (int32_t i = 0; i < var->size; ++i) { /*local elem = lua_pushVariantValue() */ lua_pushVariantValue(L, var->dataType, &var->data, i); /* value[i+1] = elem */ lua_rawseti(L, -2, i + 1); } } /* variant.Value = value */ lua_setfield(L, -2, "Value"); /* variant.IsArray = var->size > 0 */ lua_pushboolean(L, var->size > 0); lua_setfield(L, -2, "IsArray"); } /*return variant*/ } static void lua_pushDataValue(lua_State* L, const struct UA_Variant* value) { lua_pushVariant(L, value); lua_pushinteger(L, 0); lua_setfield(L, -2, "StatusCode"); } // Create a lua array with definition fields static void lua_pushDefinitionTable(lua_State* L, const struct UA_StructDefinition* definition) { // local definition = {} -- array of references lua_createtable(L, definition->size, 0); unsigned key = 0; for (unsigned i = 0; i < definition->size; ++i) { const struct UA_Field* field = &definition->fields[i]; // local field = {} lua_createtable(L, 4, 0); // field.Name = field->name lua_pushstring(L, field->name); lua_setfield(L, -2, "Name"); // field.DataType = ref->typeId lua_pushNodeId(L, field->typeId); lua_setfield(L, -2, "DataType"); if (field->enumValue == -1) { // ref.ValueRank = ref->valueRank lua_pushinteger(L, field->valueRank); lua_setfield(L, -2, "ValueRank"); } if (field->enumValue != -1) { // ref.Value = ref->enumValue lua_pushinteger(L, field->enumValue); lua_setfield(L, -2, "Value"); } // definition[i] = field lua_rawseti(L, -2, ++key); } // return definition } static void lua_createAttributeValue(lua_State* L, const unsigned attributeId, const union UA_Value* data) { switch (attributeId) { case UA_AttributeId_NodeId: lua_pushNodeId(L, data->str); break; case UA_AttributeId_NodeClass: lua_pushinteger(L, data->u32); break; case UA_AttributeId_BrowseName: lua_pushQualifiedName(L, data->str); break; case UA_AttributeId_DisplayName: lua_pushLocalizedText(L, data->str); break; case UA_AttributeId_Description: lua_pushLocalizedText(L, data->str); break; case UA_AttributeId_WriteMask: lua_pushinteger(L, (int)(data->u32 > 0)); break; case UA_AttributeId_UserWriteMask: lua_pushinteger(L, (int)(data->u32 > 0)); break; case UA_AttributeId_IsAbstract: lua_pushboolean(L, (int)(data->u32 > 0)); break; case UA_AttributeId_Symmetric: lua_pushboolean(L, (int)(data->u32 > 0)); break; case UA_AttributeId_InverseName: lua_pushLocalizedText(L, data->str); break; case UA_AttributeId_ContainsNoLoops: lua_pushboolean(L, (int)(data->u32 > 0)); break; case UA_AttributeId_EventNotifier: lua_pushinteger(L, (int)data->u32); break; case UA_AttributeId_Value: lua_pushDataValue(L, data->vPtr); break; case UA_AttributeId_DataType: lua_pushNodeId(L, data->str); break; case UA_AttributeId_ValueRank: lua_pushinteger(L, data->i32); break; case UA_AttributeId_ArrayDimensions: lua_pushnil(L); break; case UA_AttributeId_AccessLevel: lua_pushinteger(L, data->u32); break; case UA_AttributeId_UserAccessLevel: lua_pushinteger(L, data->u32); break; case UA_AttributeId_MinimumSamplingInterval: lua_pushnumber(L, data->d); break; case UA_AttributeId_Historizing: lua_pushboolean(L, (int)(data->u32 > 0)); break; case UA_AttributeId_Executable: lua_pushboolean(L, (int)(data->u32 > 0)); break; case UA_AttributeId_UserExecutable: lua_pushboolean(L, (int)(data->u32 > 0)); break; case UA_AttributeId_DataTypeDefinition: lua_pushDefinitionTable(L, data->definitionPtr); break; case UA_AttributeId_RolePermissions: lua_pushnil(L); break; case UA_AttributeId_UserRolePermissions: lua_pushnil(L); break; case UA_AttributeId_AccessRestrictions: lua_pushnil(L); break; case UA_AttributeId_AccessLevelEx: lua_pushnil(L); break; default: lua_pushfstring(L, "INTERNAL ERROR: Unknown attribute id '%d'", attributeId); lua_error(L); break; } } /* Convert array of attributes into lua table: key is an aattribute ID value - attribute value different node classes have different set of attributes, so result table has non-sequential attribute IDs set. */ static void lua_pushAttributesTable(lua_State* L, const struct UA_Attribute* attr, unsigned size) { /*local attrs = {} -- array of attributes*/ lua_createtable(L, 0, size); for (unsigned i = 0; i < size; ++i, ++attr) { /* local val = attr->data */ lua_pushinteger(L, (int)attr->id); lua_createAttributeValue(L, attr->id, &attr->data); /* attrs[id] = val */ lua_settable(L, -3); } } // Create a lua arraye with references of nodes static void lua_pushRefsTable(lua_State* L, const struct UA_Reference* ref, unsigned size) { //local refs = {} -- array of references lua_createtable(L, size, 0); unsigned key = 0; for (unsigned i = 0; i < size; ++i, ++ref) { /* local ref = {}*/ lua_createtable(L, 3, 0); /* ref.target = ref->node */ lua_pushNodeId(L, ref->nodeid); lua_setfield(L, -2, "target"); /* re.type = ref->refid */ lua_pushNodeId(L, ref->refid); lua_setfield(L, -2, "type"); /* ref.isForward = ref->isForward */ lua_pushboolean(L, ref->isForward); lua_setfield(L, -2, "isForward"); /* refs[i] = ref*/ lua_rawseti(L, -2, ++key); } /* return refs */ } static int lua_pushNode(lua_State* L, const struct UA_Node* node) { /* local node = {} */ lua_createtable(L, 0, 5); /* local attrs = {} */ /* for key in pairs(n->attrs) do */ /* attrs[key] = n->attrs[key]*/ lua_pushAttributesTable(L, node->attrs, node->attrsSize); /* node["attrs"] = attrs */ lua_setfield(L, -2, "Attrs"); /* node["refs"] = attrs */ lua_pushRefsTable(L, node->refs, node->refsSize); lua_setfield(L, -2, "Refs"); if (node->jsonId) { /* node["jsonId"] = node->jsonId */ lua_pushstring(L, node->jsonId); lua_setfield(L, -2, "JsonId"); } if (node->binaryId) { /* node["binaryId"] = node->binaryId */ lua_pushstring(L, node->binaryId); lua_setfield(L, -2, "BinaryId"); } if (node->baseId) { /* node["baseId"] = node->baseId */ lua_pushstring(L, node->baseId); lua_setfield(L, -2, "BaseId"); } if (node->dataTypeId) { /* node["dataTypeId"] = node->dataTypeId */ lua_pushstring(L, node->dataTypeId); lua_setfield(L, -2, "DataTypeId"); } return 1; } /* find node in address space by its integer id @param NodeID - id of a node. @result node of found or nil if not found. */ static int lua_getNode(lua_State* L) { luaL_checkudata(L, 1, "opcua.nodes"); const char* nodeId = luaL_checkstring(L, 2); /*search node by its identifier in the namespace 0*/ const struct UA_Node* n = ns0_getNode(nodeId); if (!n) { lua_pushnil(L); return 1; } return lua_pushNode(L, n); } static int lua_getNodes(lua_State* L) { luaL_checkany(L, 1); if (lua_type(L, 1) == LUA_TUSERDATA && luaL_checkudata(L, 1, "opcua.nodes")) { unsigned* pos = (unsigned*)lua_newuserdata(L, sizeof(unsigned)); *pos = 0; lua_pushcclosure(L, lua_getNodes, 1); return 1; } unsigned* pos = (unsigned*)lua_touserdata(L, lua_upvalueindex(1)); const struct UA_Node* n = ns0_getNodeIdx(*pos); if (!n) return 0; ++(*pos); if (n->attrsSize != 0) lua_pushstring(L, n->attrs->data.str); else lua_pushnil(L); lua_pushNode(L, n); return 2; } /* Exporting a function of a dynamic library lua module. */ // static luaL_Reg opcuamod[] = // { // {"getNode", lua_getNode}, // {"getNodes", lua_getNodes}, // {NULL, NULL} // }; int luaopen_opcua_ns0(lua_State* L) { luaL_newmetatable(L, "opcua.nodes"); lua_pushcfunction(L, lua_getNode); lua_setfield(L, -2, "__index"); lua_pushcfunction(L, lua_getNodes); lua_setfield(L, -2, "__pairs"); lua_pop(L, 1); lua_newuserdata(L, sizeof(1)); luaL_setmetatable(L, "opcua.nodes"); return 1; } /* register opcuac module in loaded modules. */ void luaopen_opcua_ns0_static(lua_State *L) { /* "require" functions from 'opcuamod' and set results to global table */ luaL_requiref(L, "opcua_ns0", luaopen_opcua_ns0, 1); lua_pop(L, 1); /* remove lib */ } #endif #if USE_OPCUA == 1 #include #ifndef OPCUA_TYPES_H #include "opcua_types.h" #endif static const char nodeId_0[] = "i=425"; static const char nodeId_1[] = "i=11616"; static const char nodeId_2[] = "i=33"; static const char nodeId_3[] = "i=15361"; static const char nodeId_4[] = "i=15258"; static const char nodeId_5[] = "i=15083"; static const char nodeId_6[] = "i=15487"; static const char nodeId_7[] = "i=7606"; static const char nodeId_8[] = "i=3092"; static const char nodeId_9[] = "i=98"; static const char nodeId_10[] = "i=23498"; static const char nodeId_11[] = "i=12"; static const char nodeId_12[] = "i=15534"; static const char nodeId_13[] = "i=89"; static const char nodeId_14[] = "i=11648"; static const char nodeId_15[] = "i=15100"; static const char nodeId_16[] = "i=22"; static const char nodeId_17[] = "i=397"; static const char nodeId_18[] = "i=555"; static const char nodeId_19[] = "i=7591"; static const char nodeId_20[] = "i=10"; static const char nodeId_21[] = "i=3701"; static const char nodeId_22[] = "i=321"; static const char nodeId_23[] = "i=15960"; static const char nodeId_24[] = "i=13"; static const char nodeId_25[] = "i=11715"; static const char nodeId_26[] = "i=15406"; static const char nodeId_27[] = "i=431"; static const char nodeId_28[] = "i=80"; static const char nodeId_29[] = "i=15365"; static const char nodeId_30[] = "i=2268"; static const char nodeId_31[] = "i=540"; static const char nodeId_32[] = "i=15700"; static const char nodeId_33[] = "i=15005"; static const char nodeId_34[] = "i=3057"; static const char nodeId_35[] = "i=15082"; static const char nodeId_36[] = "i=2142"; static const char nodeId_37[] = "i=3077"; static const char nodeId_38[] = "i=11957"; static const char nodeId_39[] = "i=357"; static const char nodeId_40[] = "i=545"; static const char nodeId_41[] = "i=32"; static const char nodeId_42[] = "i=322"; static const char nodeId_43[] = "i=525"; static const char nodeId_44[] = "i=3093"; static const char nodeId_45[] = "i=12877"; static const char nodeId_46[] = "i=63"; static const char nodeId_47[] = "i=392"; static const char nodeId_48[] = "i=11737"; static const char nodeId_49[] = "i=7"; static const char nodeId_50[] = "i=15087"; static const char nodeId_51[] = "i=331"; static const char nodeId_52[] = "i=15152"; static const char nodeId_53[] = "i=310"; static const char nodeId_54[] = "i=537"; static const char nodeId_55[] = "i=289"; static const char nodeId_56[] = "i=9"; static const char nodeId_57[] = "i=856"; static const char nodeId_58[] = "i=31"; static const char nodeId_59[] = "i=518"; static const char nodeId_60[] = "i=379"; static const char nodeId_61[] = "i=422"; static const char nodeId_62[] = "i=474"; static const char nodeId_63[] = "i=488"; static const char nodeId_64[] = "i=452"; static const char nodeId_65[] = "i=11"; static const char nodeId_66[] = "i=15577"; static const char nodeId_67[] = "i=2993"; static const char nodeId_68[] = "i=16"; static const char nodeId_69[] = "i=24110"; static const char nodeId_70[] = "i=7595"; static const char nodeId_71[] = "i=288"; static const char nodeId_72[] = "i=26"; static const char nodeId_73[] = "i=527"; static const char nodeId_74[] = "i=299"; static const char nodeId_75[] = "i=709"; static const char nodeId_76[] = "i=367"; static const char nodeId_77[] = "i=447"; static const char nodeId_78[] = "i=61"; static const char nodeId_79[] = "i=15199"; static const char nodeId_80[] = "i=15256"; static const char nodeId_81[] = "i=2752"; static const char nodeId_82[] = "i=522"; static const char nodeId_83[] = "i=889"; static const char nodeId_84[] = "i=2736"; static const char nodeId_85[] = "i=2141"; static const char nodeId_86[] = "i=2019"; static const char nodeId_87[] = "i=11703"; static const char nodeId_88[] = "i=707"; static const char nodeId_89[] = "i=15148"; static const char nodeId_90[] = "i=3053"; static const char nodeId_91[] = "i=14844"; static const char nodeId_92[] = "i=3702"; static const char nodeId_93[] = "i=11647"; static const char nodeId_94[] = "i=41"; static const char nodeId_95[] = "i=38"; static const char nodeId_96[] = "i=11646"; static const char nodeId_97[] = "i=15088"; static const char nodeId_98[] = "i=15370"; static const char nodeId_99[] = "i=21"; static const char nodeId_100[] = "i=8917"; static const char nodeId_101[] = "i=2258"; static const char nodeId_102[] = "i=2009"; static const char nodeId_103[] = "i=347"; static const char nodeId_104[] = "i=68"; static const char nodeId_105[] = "i=99"; static const char nodeId_106[] = "i=15059"; static const char nodeId_107[] = "i=420"; static const char nodeId_108[] = "i=15182"; static const char nodeId_109[] = "i=354"; static const char nodeId_110[] = "i=15131"; static const char nodeId_111[] = "i=394"; static const char nodeId_112[] = "i=2004"; static const char nodeId_113[] = "i=11591"; static const char nodeId_114[] = "i=91"; static const char nodeId_115[] = "i=11587"; static const char nodeId_116[] = "i=3055"; static const char nodeId_117[] = "i=2269"; static const char nodeId_118[] = "i=44"; static const char nodeId_119[] = "i=483"; static const char nodeId_120[] = "i=27"; static const char nodeId_121[] = "i=11651"; static const char nodeId_122[] = "i=15671"; static const char nodeId_123[] = "i=11619"; static const char nodeId_124[] = "i=11939"; static const char nodeId_125[] = "i=364"; static const char nodeId_126[] = "i=381"; static const char nodeId_127[] = "i=76"; static const char nodeId_128[] = "i=554"; static const char nodeId_129[] = "i=291"; static const char nodeId_130[] = "i=351"; static const char nodeId_131[] = "i=15291"; static const char nodeId_132[] = "i=120"; static const char nodeId_133[] = "i=324"; static const char nodeId_134[] = "i=15376"; static const char nodeId_135[] = "i=3090"; static const char nodeId_136[] = "i=6"; static const char nodeId_137[] = "i=2267"; static const char nodeId_138[] = "i=15167"; static const char nodeId_139[] = "i=24"; static const char nodeId_140[] = "i=704"; static const char nodeId_141[] = "i=304"; static const char nodeId_142[] = "i=712"; static const char nodeId_143[] = "i=58"; static const char nodeId_144[] = "i=444"; static const char nodeId_145[] = "i=15407"; static const char nodeId_146[] = "i=39"; static const char nodeId_147[] = "i=11592"; static const char nodeId_148[] = "i=290"; static const char nodeId_149[] = "i=23507"; static const char nodeId_150[] = "i=127"; static const char nodeId_151[] = "i=34"; static const char nodeId_152[] = "i=11617"; static const char nodeId_153[] = "i=37"; static const char nodeId_154[] = "i=28"; static const char nodeId_155[] = "i=11583"; static const char nodeId_156[] = "i=2260"; static const char nodeId_157[] = "i=15132"; static const char nodeId_158[] = "i=491"; static const char nodeId_159[] = "i=295"; static const char nodeId_160[] = "i=11702"; static const char nodeId_161[] = "i=15488"; static const char nodeId_162[] = "i=15058"; static const char nodeId_163[] = "i=940"; static const char nodeId_164[] = "i=18"; static const char nodeId_165[] = "i=15146"; static const char nodeId_166[] = "i=520"; static const char nodeId_167[] = "i=15137"; static const char nodeId_168[] = "i=303"; static const char nodeId_169[] = "i=3699"; static const char nodeId_170[] = "i=634"; static const char nodeId_171[] = "i=15063"; static const char nodeId_172[] = "i=2255"; static const char nodeId_173[] = "i=11652"; static const char nodeId_174[] = "i=333"; static const char nodeId_175[] = "i=15188"; static const char nodeId_176[] = "i=2264"; static const char nodeId_177[] = "i=2033"; static const char nodeId_178[] = "i=15165"; static const char nodeId_179[] = "i=15338"; static const char nodeId_180[] = "i=713"; static const char nodeId_181[] = "i=2262"; static const char nodeId_182[] = "i=15189"; static const char nodeId_183[] = "i=15369"; static const char nodeId_184[] = "i=14"; static const char nodeId_185[] = "i=2263"; static const char nodeId_186[] = "i=3084"; static const char nodeId_187[] = "i=15035"; static const char nodeId_188[] = "i=3052"; static const char nodeId_189[] = "i=2008"; static const char nodeId_190[] = "i=395"; static const char nodeId_191[] = "i=327"; static const char nodeId_192[] = "i=886"; static const char nodeId_193[] = "i=391"; static const char nodeId_194[] = "i=2994"; static const char nodeId_195[] = "i=2735"; static const char nodeId_196[] = "i=15190"; static const char nodeId_197[] = "i=938"; static const char nodeId_198[] = "i=2138"; static const char nodeId_199[] = "i=2007"; static const char nodeId_200[] = "i=315"; static const char nodeId_201[] = "i=340"; static const char nodeId_202[] = "i=715"; static const char nodeId_203[] = "i=2272"; static const char nodeId_204[] = "i=16150"; static const char nodeId_205[] = "i=15151"; static const char nodeId_206[] = "i=13341"; static const char nodeId_207[] = "i=3087"; static const char nodeId_208[] = "i=12169"; static const char nodeId_209[] = "i=12687"; static const char nodeId_210[] = "i=788"; static const char nodeId_211[] = "i=101"; static const char nodeId_212[] = "i=296"; static const char nodeId_213[] = "i=14525"; static const char nodeId_214[] = "i=95"; static const char nodeId_215[] = "i=388"; static const char nodeId_216[] = "i=15062"; static const char nodeId_217[] = "i=7603"; static const char nodeId_218[] = "i=2014"; static const char nodeId_219[] = "i=441"; static const char nodeId_220[] = "i=24107"; static const char nodeId_221[] = "i=428"; static const char nodeId_222[] = "i=8251"; static const char nodeId_223[] = "i=11589"; static const char nodeId_224[] = "i=539"; static const char nodeId_225[] = "i=12182"; static const char nodeId_226[] = "i=311"; static const char nodeId_227[] = "i=710"; static const char nodeId_228[] = "i=542"; static const char nodeId_229[] = "i=15368"; static const char nodeId_230[] = "i=858"; static const char nodeId_231[] = "i=15142"; static const char nodeId_232[] = "i=298"; static const char nodeId_233[] = "i=15292"; static const char nodeId_234[] = "i=2140"; static const char nodeId_235[] = "i=11650"; static const char nodeId_236[] = "i=352"; static const char nodeId_237[] = "i=308"; static const char nodeId_238[] = "i=355"; static const char nodeId_239[] = "i=2"; static const char nodeId_240[] = "i=11582"; static const char nodeId_241[] = "i=1"; static const char nodeId_242[] = "i=516"; static const char nodeId_243[] = "i=15140"; static const char nodeId_244[] = "i=11585"; static const char nodeId_245[] = "i=4"; static const char nodeId_246[] = "i=306"; static const char nodeId_247[] = "i=325"; static const char nodeId_248[] = "i=11653"; static const char nodeId_249[] = "i=15963"; static const char nodeId_250[] = "i=670"; static const char nodeId_251[] = "i=549"; static const char nodeId_252[] = "i=2992"; static const char nodeId_253[] = "i=15192"; static const char nodeId_254[] = "i=551"; static const char nodeId_255[] = "i=513"; static const char nodeId_256[] = "i=7598"; static const char nodeId_257[] = "i=17588"; static const char nodeId_258[] = "i=11878"; static const char nodeId_259[] = "i=867"; static const char nodeId_260[] = "i=15276"; static const char nodeId_261[] = "i=15144"; static const char nodeId_262[] = "i=312"; static const char nodeId_263[] = "i=468"; static const char nodeId_264[] = "i=15065"; static const char nodeId_265[] = "i=2734"; static const char nodeId_266[] = "i=7594"; static const char nodeId_267[] = "i=3083"; static const char nodeId_268[] = "i=3056"; static const char nodeId_269[] = "i=12686"; static const char nodeId_270[] = "i=2013"; static const char nodeId_271[] = "i=3085"; static const char nodeId_272[] = "i=349"; static const char nodeId_273[] = "i=458"; static const char nodeId_274[] = "i=15138"; static const char nodeId_275[] = "i=122"; static const char nodeId_276[] = "i=15168"; static const char nodeId_277[] = "i=7597"; static const char nodeId_278[] = "i=3"; static const char nodeId_279[] = "i=11618"; static const char nodeId_280[] = "i=785"; static const char nodeId_281[] = "i=15964"; static const char nodeId_282[] = "i=301"; static const char nodeId_283[] = "i=5"; static const char nodeId_284[] = "i=530"; static const char nodeId_285[] = "i=128"; static const char nodeId_286[] = "i=49"; static const char nodeId_287[] = "i=15363"; static const char nodeId_288[] = "i=2753"; static const char nodeId_289[] = "i=12181"; static const char nodeId_290[] = "i=11584"; static const char nodeId_291[] = "i=126"; static const char nodeId_292[] = "i=884"; static const char nodeId_293[] = "i=511"; static const char nodeId_294[] = "i=524"; static const char nodeId_295[] = "i=449"; static const char nodeId_296[] = "i=668"; static const char nodeId_297[] = "i=16151"; static const char nodeId_298[] = "i=3076"; static const char nodeId_299[] = "i=3054"; static const char nodeId_300[] = "i=2271"; static const char nodeId_301[] = "i=15375"; static const char nodeId_302[] = "i=865"; static const char nodeId_303[] = "i=15090"; static const char nodeId_304[] = "i=15099"; static const char nodeId_305[] = "i=15081"; static const char nodeId_306[] = "i=15179"; static const char nodeId_307[] = "i=11645"; static const char nodeId_308[] = "i=2737"; static const char nodeId_309[] = "i=626"; static const char nodeId_310[] = "i=47"; static const char nodeId_311[] = "i=423"; static const char nodeId_312[] = "i=15377"; static const char nodeId_313[] = "i=121"; static const char nodeId_314[] = "i=15094"; static const char nodeId_315[] = "i=2259"; static const char nodeId_316[] = "i=790"; static const char nodeId_317[] = "i=15101"; static const char nodeId_318[] = "i=25"; static const char nodeId_319[] = "i=15153"; static const char nodeId_320[] = "i=14523"; static const char nodeId_321[] = "i=52"; static const char nodeId_322[] = "i=17"; static const char nodeId_323[] = "i=674"; static const char nodeId_324[] = "i=40"; static const char nodeId_325[] = "i=15032"; static const char nodeId_326[] = "i=3079"; static const char nodeId_327[] = "i=85"; static const char nodeId_328[] = "i=316"; static const char nodeId_329[] = "i=20998"; static const char nodeId_330[] = "i=15290"; static const char nodeId_331[] = "i=521"; static const char nodeId_332[] = "i=14528"; static const char nodeId_333[] = "i=318"; static const char nodeId_334[] = "i=45"; static const char nodeId_335[] = "i=15961"; static const char nodeId_336[] = "i=15030"; static const char nodeId_337[] = "i=77"; static const char nodeId_338[] = "i=2266"; static const char nodeId_339[] = "i=97"; static const char nodeId_340[] = "i=429"; static const char nodeId_341[] = "i=78"; static const char nodeId_342[] = "i=2996"; static const char nodeId_343[] = "i=2006"; static const char nodeId_344[] = "i=628"; static const char nodeId_345[] = "i=864"; static const char nodeId_346[] = "i=11586"; static const char nodeId_347[] = "i=2017"; static const char nodeId_348[] = "i=87"; static const char nodeId_349[] = "i=2253"; static const char nodeId_350[] = "i=450"; static const char nodeId_351[] = "i=11594"; static const char nodeId_352[] = "i=887"; static const char nodeId_353[] = "i=473"; static const char nodeId_354[] = "i=2733"; static const char nodeId_355[] = "i=15278"; static const char nodeId_356[] = "i=871"; static const char nodeId_357[] = "i=48"; static const char nodeId_358[] = "i=546"; static const char nodeId_359[] = "i=873"; static const char nodeId_360[] = "i=19"; static const char nodeId_361[] = "i=868"; static const char nodeId_362[] = "i=486"; static const char nodeId_363[] = "i=3074"; static const char nodeId_364[] = "i=14533"; static const char nodeId_365[] = "i=852"; static const char nodeId_366[] = "i=3078"; static const char nodeId_367[] = "i=11580"; static const char nodeId_368[] = "i=476"; static const char nodeId_369[] = "i=25200"; static const char nodeId_370[] = "i=456"; static const char nodeId_371[] = "i=50"; static const char nodeId_372[] = "i=548"; static const char nodeId_373[] = "i=11593"; static const char nodeId_374[] = "i=96"; static const char nodeId_375[] = "i=3698"; static const char nodeId_376[] = "i=11579"; static const char nodeId_377[] = "i=2016"; static const char nodeId_378[] = "i=15528"; static const char nodeId_379[] = "i=11590"; static const char nodeId_380[] = "i=90"; static const char nodeId_381[] = "i=11508"; static const char nodeId_382[] = "i=125"; static const char nodeId_383[] = "i=11649"; static const char nodeId_384[] = "i=53"; static const char nodeId_385[] = "i=15031"; static const char nodeId_386[] = "i=11588"; static const char nodeId_387[] = "i=84"; static const char nodeId_388[] = "i=2295"; static const char nodeId_389[] = "i=3089"; static const char nodeId_390[] = "i=528"; static const char nodeId_391[] = "i=2257"; static const char nodeId_392[] = "i=344"; static const char nodeId_393[] = "i=3703"; static const char nodeId_394[] = "i=3051"; static const char nodeId_395[] = "i=15962"; static const char nodeId_396[] = "i=2139"; static const char nodeId_397[] = "i=15145"; static const char nodeId_398[] = "i=36"; static const char nodeId_399[] = "i=46"; static const char nodeId_400[] = "i=15337"; static const char nodeId_401[] = "i=2254"; static const char nodeId_402[] = "i=15093"; static const char nodeId_403[] = "i=15141"; static const char nodeId_404[] = "i=361"; static const char nodeId_405[] = "i=862"; static const char nodeId_406[] = "i=15185"; static const char nodeId_407[] = "i=15143"; static const char nodeId_408[] = "i=14845"; static const char nodeId_409[] = "i=12878"; static const char nodeId_410[] = "i=2005"; static const char nodeId_411[] = "i=35"; static const char nodeId_412[] = "i=12879"; static const char nodeId_413[] = "i=15371"; static const char nodeId_414[] = "i=15277"; static const char nodeId_415[] = "i=29"; static const char nodeId_416[] = "i=15136"; static const char nodeId_417[] = "i=314"; static const char nodeId_418[] = "i=11881"; static const char nodeId_419[] = "i=348"; static const char nodeId_420[] = "i=15147"; static const char nodeId_421[] = "i=346"; static const char nodeId_422[] = "i=11623"; static const char nodeId_423[] = "i=465"; static const char nodeId_424[] = "i=15184"; static const char nodeId_425[] = "i=389"; static const char nodeId_426[] = "i=7612"; static const char nodeId_427[] = "i=489"; static const char nodeId_428[] = "i=15378"; static const char nodeId_429[] = "i=459"; static const char nodeId_430[] = "i=15180"; static const char nodeId_431[] = "i=462"; static const char nodeId_432[] = "i=3075"; static const char nodeId_433[] = "i=15958"; static const char nodeId_434[] = "i=2265"; static const char nodeId_435[] = "i=3080"; static const char nodeId_436[] = "i=15086"; static const char nodeId_437[] = "i=51"; static const char nodeId_438[] = "i=787"; static const char nodeId_439[] = "i=12880"; static const char nodeId_440[] = "i=15098"; static const char nodeId_441[] = "i=11620"; static const char nodeId_442[] = "i=11621"; static const char nodeId_443[] = "i=543"; static const char nodeId_444[] = "i=3086"; static const char nodeId_445[] = "i=631"; static const char nodeId_446[] = "i=676"; static const char nodeId_447[] = "i=14524"; static const char nodeId_448[] = "i=373"; static const char nodeId_449[] = "i=12881"; static const char nodeId_450[] = "i=15067"; static const char nodeId_451[] = "i=15134"; static const char nodeId_452[] = "i=443"; static const char nodeId_453[] = "i=15066"; static const char nodeId_454[] = "i=11943"; static const char nodeId_455[] = "i=870"; static const char nodeId_456[] = "i=15"; static const char nodeId_457[] = "i=319"; static const char nodeId_458[] = "i=632"; static const char nodeId_459[] = "i=15036"; static const char nodeId_460[] = "i=446"; static const char nodeId_461[] = "i=15421"; static const char nodeId_462[] = "i=24134"; static const char nodeId_463[] = "i=100"; static const char nodeId_464[] = "i=470"; static const char nodeId_465[] = "i=3091"; static const char nodeId_466[] = "i=15139"; static const char nodeId_467[] = "i=464"; static const char nodeId_468[] = "i=15676"; static const char nodeId_469[] = "i=3700"; static const char nodeId_470[] = "i=461"; static const char nodeId_471[] = "i=8"; static const char nodeId_472[] = "i=358"; static const char nodeId_473[] = "i=426"; static const char nodeId_474[] = "i=14593"; static const char nodeId_475[] = "i=302"; static const char nodeId_476[] = "i=12766"; static const char nodeId_477[] = "i=12756"; static const char nodeId_478[] = "i=2261"; static const char nodeId_479[] = "i=15183"; static const char nodeId_480[] = "i=2732"; static const char nodeId_481[] = "i=15367"; static const char nodeId_482[] = "i=12172"; static const char nodeId_483[] = "i=12171"; static const char nodeId_484[] = "i=15191"; static const char nodeId_485[] = "i=307"; static const char nodeId_486[] = "i=514"; static const char nodeId_487[] = "i=94"; static const char nodeId_488[] = "i=11581"; static const char nodeId_489[] = "i=15904"; static const char nodeId_490[] = "i=15169"; static const char nodeId_491[] = "i=8912"; static const char nodeId_492[] = "i=15257"; static const char nodeId_493[] = "i=86"; static const char nodeId_494[] = "i=123"; static const char nodeId_495[] = "i=3082"; static const char nodeId_496[] = "i=671"; static const char nodeId_497[] = "i=370"; static const char nodeId_498[] = "i=294"; static const char nodeId_499[] = "i=15057"; static const char nodeId_500[] = "i=24244"; static const char nodeId_501[] = "i=11575"; static const char nodeId_502[] = "i=706"; static const char nodeId_503[] = "i=102"; static const char nodeId_504[] = "i=15133"; static const char nodeId_505[] = "i=256"; static const char nodeId_506[] = "i=467"; static const char nodeId_507[] = "i=378"; static const char nodeId_508[] = "i=54"; static const char nodeId_509[] = "i=62"; static const char nodeId_510[] = "i=3049"; static const char nodeId_511[] = "i=2011"; static const char nodeId_512[] = "i=15193"; static const char nodeId_513[] = "i=3088"; static const char nodeId_514[] = "i=20"; static const char nodeId_515[] = "i=23528"; static const char nodeId_516[] = "i=11576"; static const char nodeId_517[] = "i=7596"; static const char nodeId_518[] = "i=2742"; static const char nodeId_519[] = "i=552"; static const char nodeId_520[] = "i=3081"; static const char nodeId_521[] = "i=15289"; static const char nodeId_522[] = "i=338"; static const char nodeId_523[] = "i=510"; static const char nodeId_524[] = "i=15089"; static const char nodeId_525[] = "i=557"; static const char nodeId_526[] = "i=15085"; static const char nodeId_527[] = "i=15957"; static const char nodeId_528[] = "i=88"; static const char nodeId_529[] = "i=471"; static const char nodeId_530[] = "i=257"; static const char nodeId_531[] = "i=673"; static const char nodeId_532[] = "i=15959"; static const char nodeId_533[] = "i=11940"; static const char nodeId_534[] = "i=15194"; static const char nodeId_535[] = "i=376"; static const char nodeId_536[] = "i=2256"; static const char nodeId_537[] = "i=625"; static const char nodeId_538[] = "i=23"; static const char nodeId_539[] = "i=629"; static const char nodeId_540[] = "i=11622"; static const char str_542[] = "Default Binary"; static const struct UA_Attribute nodeId_0_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_0}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_0_refs[] = { {.nodeid=nodeId_311, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_543[] = "NamespaceMetadataType"; static const struct UA_Attribute nodeId_1_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_1}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_543}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_543}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_1_refs[] = { {.nodeid=nodeId_152, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_279, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_123, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_441, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_442, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_540, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_422, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_96, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_527, .refid=nodeId_324, .isForward=0}, }; static const char str_544[] = "HierarchicalReferences"; static const char str_545[] = "InverseHierarchicalReferences"; static const struct UA_Attribute nodeId_2_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_2}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_544}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_544}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_545}}, }; static const struct UA_Reference nodeId_2_refs[] = { {.nodeid=nodeId_58, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_398, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_411, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_151, .refid=nodeId_334, .isForward=1}, }; static const char str_546[] = "Default JSON"; static const struct UA_Attribute nodeId_3_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_3}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_3_refs[] = { {.nodeid=nodeId_522, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_4_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_4}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_4_refs[] = { {.nodeid=nodeId_458, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_5_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_5}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_5_refs[] = { {.nodeid=nodeId_503, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_547[] = "StructureDescription"; static const char str_548[] = "DataTypeId"; static const char str_549[] = "Name"; static const char str_550[] = "StructureDefinition"; static const struct UA_Field variable_1_definition_fields[] = { {.name=str_548, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_549, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, {.name=str_550, .typeId=nodeId_105, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_1_definition = {.size=3, .fields=variable_1_definition_fields}; static const struct UA_Attribute nodeId_6_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_6}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_547}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_547}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_1_definition}}, }; static const struct UA_Reference nodeId_6_refs[] = { {.nodeid=nodeId_213, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_162, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_291, .refid=nodeId_95, .isForward=1}, }; static const char str_551[] = "EnumStrings"; static const char str_552[] = "Source"; static const char str_553[] = "Server"; static const char str_554[] = "Both"; static const char str_555[] = "Neither"; static const char str_556[] = "Invalid"; static const char *variable_2[] = { str_552, str_553, str_554, str_555, str_556, }; static const struct UA_Variant variable_3_variant = {.dataType=UA_Type_LocalizedText, .size=5, .data={.strArr=variable_2}}; static const struct UA_Attribute nodeId_7_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_7}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_3_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_7_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_537, .refid=nodeId_399, .isForward=0}, }; static const char str_557[] = "SoftwareCertificates"; static const struct UA_Attribute nodeId_8_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_8}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_557}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_557}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_392}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_8_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_399, .isForward=0}, }; static const char str_558[] = "StructureType"; static const char str_559[] = "Structure"; static const char str_560[] = "StructureWithOptionalFields"; static const char str_561[] = "Union"; static const char str_562[] = "StructureWithSubtypedValues"; static const char str_563[] = "UnionWithSubtypedValues"; static const struct UA_Field variable_4_definition_fields[] = { {.name=str_559, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_560, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_561, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_562, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, {.name=str_563, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, }; static const struct UA_StructDefinition variable_4_definition = {.size=5, .fields=variable_4_definition_fields}; static const struct UA_Attribute nodeId_9_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_9}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_558}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_558}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_4_definition}}, }; static const struct UA_Reference nodeId_9_refs[] = { {.nodeid=nodeId_332, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const char str_564[] = "CurrencyUnitType"; static const char str_565[] = "NumericCode"; static const char str_566[] = "Exponent"; static const char str_567[] = "AlphabeticCode"; static const char str_568[] = "Currency"; static const struct UA_Field variable_5_definition_fields[] = { {.name=str_565, .typeId=nodeId_245, .valueRank=-1, .enumValue=-1}, {.name=str_566, .typeId=nodeId_239, .valueRank=-1, .enumValue=-1}, {.name=str_567, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_568, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_5_definition = {.size=4, .fields=variable_5_definition_fields}; static const struct UA_Attribute nodeId_10_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_10}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_564}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_564}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_5_definition}}, }; static const struct UA_Reference nodeId_10_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_149, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_515, .refid=nodeId_95, .isForward=1}, }; static const char str_569[] = "String"; static const struct UA_Attribute nodeId_11_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_11}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_569}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_569}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_11_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_45, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_409, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_159, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_412, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_439, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_449, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_129, .refid=nodeId_334, .isForward=1}, }; static const char str_570[] = "DataTypeSchemaHeader"; static const char str_571[] = "Namespaces"; static const char str_572[] = "StructureDataTypes"; static const char str_573[] = "EnumDataTypes"; static const char str_574[] = "SimpleDataTypes"; static const struct UA_Field variable_6_definition_fields[] = { {.name=str_571, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, {.name=str_572, .typeId=nodeId_6, .valueRank=1, .enumValue=-1}, {.name=str_573, .typeId=nodeId_161, .valueRank=1, .enumValue=-1}, {.name=str_574, .typeId=nodeId_33, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_6_definition = {.size=4, .fields=variable_6_definition_fields}; static const struct UA_Attribute nodeId_12_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_12}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_570}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_570}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_6_definition}}, }; static const struct UA_Reference nodeId_12_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_468, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_297, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_320, .refid=nodeId_334, .isForward=1}, }; static const char str_575[] = "VariableTypes"; static const struct UA_Attribute nodeId_13_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_13}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_575}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_575}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_13_refs[] = { {.nodeid=nodeId_493, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_509, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, }; static const char str_576[] = "NamespaceVersion"; static const struct UA_Attribute nodeId_14_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_14}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_576}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_576}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_14_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_15_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_15}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_15_refs[] = { {.nodeid=nodeId_473, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_16_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_16}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_559}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_559}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_16_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_10, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_12, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_18, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_31, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_43, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_47, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_51, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_54, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_57, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_59, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_60, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_62, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_74, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_77, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_88, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_107, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_119, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_140, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_141, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_486, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_482, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_477, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_180, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_190, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_392, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_378, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_390, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_211, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_212, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_213, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_219, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_220, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_227, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_237, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_251, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_262, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_263, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_266, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_280, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_405, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_292, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_293, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_296, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_302, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_309, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_311, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_323, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_529, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_350, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_210, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_339, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_427, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_425, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_458, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_352, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_362, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_423, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_364, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_370, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_491, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_144, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_474, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_519, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_429, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_431, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_443, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_447, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_454, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_82, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_539, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_374, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_483, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_473, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_358, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_496, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_361, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_356, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_522, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_340, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_535, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_328, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_17_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_17}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_17_refs[] = { {.nodeid=nodeId_190, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_577[] = "TranslateBrowsePathsToNodeIdsResponse"; static const char str_578[] = "ResponseHeader"; static const char str_579[] = "Results"; static const char str_580[] = "DiagnosticInfos"; static const struct UA_Field variable_7_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_579, .typeId=nodeId_251, .valueRank=1, .enumValue=-1}, {.name=str_580, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_7_definition = {.size=3, .fields=variable_7_definition_fields}; static const struct UA_Attribute nodeId_18_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_18}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_577}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_577}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_7_definition}}, }; static const struct UA_Reference nodeId_18_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_534, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_525, .refid=nodeId_95, .isForward=1}, }; static const char str_581[] = "Numeric"; static const char str_582[] = "Guid"; static const char str_583[] = "Opaque"; static const char *variable_8[] = { str_581, str_569, str_582, str_583, }; static const struct UA_Variant variable_9_variant = {.dataType=UA_Type_LocalizedText, .size=4, .data={.strArr=variable_8}}; static const struct UA_Attribute nodeId_19_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_19}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_9_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_19_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_505, .refid=nodeId_399, .isForward=0}, }; static const char str_584[] = "Float"; static const struct UA_Attribute nodeId_20_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_20}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_584}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_584}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_20_refs[] = { {.nodeid=nodeId_72, .refid=nodeId_334, .isForward=0}, }; static const char str_585[] = "SoftwareVersion"; static const struct UA_Attribute nodeId_21_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_21}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_585}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_585}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_21_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_36, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_22_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_22}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_22_refs[] = { {.nodeid=nodeId_457, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_586[] = "NamespacePublicationDate"; static const struct UA_Variant variable_10_variant = {.dataType=UA_Type_DateTime, .size=0, .data={.d=1645660800.0}}; static const struct UA_Attribute nodeId_23_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_23}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_586}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_586}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_10_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_24}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_23_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_527, .refid=nodeId_399, .isForward=0}, }; static const char str_587[] = "DateTime"; static const struct UA_Attribute nodeId_24_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_24}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_587}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_587}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_24_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_498, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_25_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_25}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_571}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_571}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_25_refs[] = { {.nodeid=nodeId_307, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_310, .isForward=0}, {.nodeid=nodeId_527, .refid=nodeId_310, .isForward=1}, }; static const char str_588[] = "AccessLevelExType"; static const char str_589[] = "CurrentRead"; static const char str_590[] = "CurrentWrite"; static const char str_591[] = "HistoryRead"; static const char str_592[] = "HistoryWrite"; static const char str_593[] = "SemanticChange"; static const char str_594[] = "StatusWrite"; static const char str_595[] = "TimestampWrite"; static const char str_596[] = "NonatomicRead"; static const char str_597[] = "NonatomicWrite"; static const char str_598[] = "WriteFullArrayOnly"; static const char str_599[] = "NoSubDataTypes"; static const char str_600[] = "NonVolatile"; static const char str_601[] = "Constant"; static const struct UA_Field variable_11_definition_fields[] = { {.name=str_589, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_590, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_591, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_592, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, {.name=str_593, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_594, .typeId=nodeId_139, .valueRank=-1, .enumValue=5}, {.name=str_595, .typeId=nodeId_139, .valueRank=-1, .enumValue=6}, {.name=str_596, .typeId=nodeId_139, .valueRank=-1, .enumValue=8}, {.name=str_597, .typeId=nodeId_139, .valueRank=-1, .enumValue=9}, {.name=str_598, .typeId=nodeId_139, .valueRank=-1, .enumValue=10}, {.name=str_599, .typeId=nodeId_139, .valueRank=-1, .enumValue=11}, {.name=str_600, .typeId=nodeId_139, .valueRank=-1, .enumValue=12}, {.name=str_601, .typeId=nodeId_139, .valueRank=-1, .enumValue=13}, }; static const struct UA_StructDefinition variable_11_definition = {.size=13, .fields=variable_11_definition_fields}; static const struct UA_Attribute nodeId_26_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_26}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_588}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_588}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_11_definition}}, }; static const struct UA_Reference nodeId_26_refs[] = { {.nodeid=nodeId_145, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_27_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_27}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_27_refs[] = { {.nodeid=nodeId_340, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_602[] = "Optional"; static const struct UA_Attribute nodeId_28_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_28}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_602}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_602}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_28_refs[] = { {.nodeid=nodeId_337, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_206, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_500, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_369, .refid=nodeId_153, .isForward=0}, }; static const struct UA_Attribute nodeId_29_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_29}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_29_refs[] = { {.nodeid=nodeId_57, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_603[] = "ServerCapabilities"; static const struct UA_Attribute nodeId_30_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_30}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_603}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_603}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_30_refs[] = { {.nodeid=nodeId_117, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_300, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_203, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_195, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_84, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_308, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_160, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_87, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_342, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_310, .isForward=0}, }; static const char str_604[] = "RelativePath"; static const char str_605[] = "Elements"; static const struct UA_Field variable_12_definition_fields[] = { {.name=str_605, .typeId=nodeId_54, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_12_definition = {.size=1, .fields=variable_12_definition_fields}; static const struct UA_Attribute nodeId_31_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_31}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_604}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_604}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_12_definition}}, }; static const struct UA_Reference nodeId_31_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_228, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_182, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_32_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_32}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_32_refs[] = { {.nodeid=nodeId_33, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_606[] = "SimpleTypeDescription"; static const char str_607[] = "BaseDataType"; static const char str_608[] = "BuiltInType"; static const struct UA_Field variable_13_definition_fields[] = { {.name=str_548, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_549, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, {.name=str_607, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_608, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_13_definition = {.size=4, .fields=variable_13_definition_fields}; static const struct UA_Attribute nodeId_33_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_33}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_606}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_606}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_13_definition}}, }; static const struct UA_Reference nodeId_33_refs[] = { {.nodeid=nodeId_213, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_32, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_461, .refid=nodeId_95, .isForward=1}, }; static const char str_609[] = "BuildDate"; static const struct UA_Attribute nodeId_34_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_34}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_609}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_609}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_34_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_35_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_35}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_35_refs[] = { {.nodeid=nodeId_266, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_610[] = "BuildInfo"; static const struct UA_Attribute nodeId_36_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_36}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_610}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_610}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_522}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_36_refs[] = { {.nodeid=nodeId_375, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_169, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_469, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_21, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_92, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_393, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_37_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_37}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_610}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_610}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_522}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_37_refs[] = { {.nodeid=nodeId_366, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_326, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_435, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_520, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_495, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_267, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_199, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_38_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_38}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_38_refs[] = { {.nodeid=nodeId_454, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_39_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_39}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_39_refs[] = { {.nodeid=nodeId_238, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_40_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_40}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_40_refs[] = { {.nodeid=nodeId_443, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_611[] = "NonHierarchicalReferences"; static const struct UA_Attribute nodeId_41_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_41}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_611}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_611}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_Symmetric, .data={.u8=1}}, }; static const struct UA_Reference nodeId_41_refs[] = { {.nodeid=nodeId_58, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_384, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_94, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_95, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_508, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_153, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_146, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_437, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_324, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_321, .refid=nodeId_334, .isForward=1}, }; static const char str_612[] = "UserNameIdentityToken"; static const char str_613[] = "PolicyId"; static const char str_614[] = "UserName"; static const char str_615[] = "Password"; static const char str_616[] = "EncryptionAlgorithm"; static const struct UA_Field variable_14_definition_fields[] = { {.name=str_613, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_614, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_615, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, {.name=str_616, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_14_definition = {.size=4, .fields=variable_14_definition_fields}; static const struct UA_Attribute nodeId_42_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_42}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_612}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_612}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_14_definition}}, }; static const struct UA_Reference nodeId_42_refs[] = { {.nodeid=nodeId_328, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_133, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_231, .refid=nodeId_95, .isForward=1}, }; static const char str_617[] = "BrowseRequest"; static const char str_618[] = "RequestHeader"; static const char str_619[] = "View"; static const char str_620[] = "RequestedMaxReferencesPerNode"; static const char str_621[] = "NodesToBrowse"; static const struct UA_Field variable_15_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_619, .typeId=nodeId_293, .valueRank=-1, .enumValue=-1}, {.name=str_620, .typeId=nodeId_55, .valueRank=-1, .enumValue=-1}, {.name=str_621, .typeId=nodeId_486, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_15_definition = {.size=4, .fields=variable_15_definition_fields}; static const struct UA_Attribute nodeId_43_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_43}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_617}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_617}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_15_definition}}, }; static const struct UA_Reference nodeId_43_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_73, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_424, .refid=nodeId_95, .isForward=1}, }; static const char str_622[] = "ModellingRules"; static const struct UA_Attribute nodeId_44_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_44}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_622}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_622}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_44_refs[] = { {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_310, .isForward=0}, }; static const char str_623[] = "NormalizedString"; static const struct UA_Attribute nodeId_45_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_45}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_623}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_623}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_45_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=0}, }; static const char str_624[] = "BaseDataVariableType"; static const struct UA_Attribute nodeId_46_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_46}}, {.id=UA_AttributeId_NodeClass, .data={.u32=16}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_624}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_624}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_ValueRank, .data={.u32=-2}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_46_refs[] = { {.nodeid=nodeId_509, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_21, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_34, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_81, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_85, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_90, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_92, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_375, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_101, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_116, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_394, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_169, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_176, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_181, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_186, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_234, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_252, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_338, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_267, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_268, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_271, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_288, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_298, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_299, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_315, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_434, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_435, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_520, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_366, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_198, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_391, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_396, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_188, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_495, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_393, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_432, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_469, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_478, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_326, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_185, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_67, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_363, .refid=nodeId_324, .isForward=0}, }; static const char str_625[] = "Timestamp"; static const char str_626[] = "RequestHandle"; static const char str_627[] = "ServiceResult"; static const char str_628[] = "ServiceDiagnostics"; static const char str_629[] = "StringTable"; static const char str_630[] = "AdditionalHeader"; static const struct UA_Field variable_16_definition_fields[] = { {.name=str_625, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_626, .typeId=nodeId_71, .valueRank=-1, .enumValue=-1}, {.name=str_627, .typeId=nodeId_360, .valueRank=-1, .enumValue=-1}, {.name=str_628, .typeId=nodeId_318, .valueRank=-1, .enumValue=-1}, {.name=str_629, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, {.name=str_630, .typeId=nodeId_16, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_16_definition = {.size=6, .fields=variable_16_definition_fields}; static const struct UA_Attribute nodeId_47_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_47}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_578}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_578}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_16_definition}}, }; static const struct UA_Reference nodeId_47_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_111, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_524, .refid=nodeId_95, .isForward=1}, }; static const char str_631[] = "BitFieldMaskDataType"; static const struct UA_Attribute nodeId_48_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_48}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_631}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_631}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_48_refs[] = { {.nodeid=nodeId_56, .refid=nodeId_334, .isForward=0}, }; static const char str_632[] = "UInt32"; static const struct UA_Attribute nodeId_49_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_49}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_632}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_632}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_49_refs[] = { {.nodeid=nodeId_154, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_26, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_55, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_71, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_103, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_257, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_487, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_329, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_50_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_50}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_50_refs[] = { {.nodeid=nodeId_237, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_633[] = "EndpointConfiguration"; static const char str_634[] = "OperationTimeout"; static const char str_635[] = "UseBinaryEncoding"; static const char str_636[] = "MaxStringLength"; static const char str_637[] = "MaxByteStringLength"; static const char str_638[] = "MaxArrayLength"; static const char str_639[] = "MaxMessageSize"; static const char str_640[] = "MaxBufferSize"; static const char str_641[] = "ChannelLifetime"; static const char str_642[] = "SecurityTokenLifetime"; static const struct UA_Field variable_17_definition_fields[] = { {.name=str_634, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_635, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_636, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_637, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_638, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_639, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_640, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_641, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_642, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_17_definition = {.size=9, .fields=variable_17_definition_fields}; static const struct UA_Attribute nodeId_51_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_51}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_633}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_633}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_17_definition}}, }; static const struct UA_Reference nodeId_51_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_79, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_174, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_52_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_52}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_52_refs[] = { {.nodeid=nodeId_236, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_53_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_53}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_53_refs[] = { {.nodeid=nodeId_237, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_643[] = "RelativePathElement"; static const char str_644[] = "ReferenceTypeId"; static const char str_645[] = "IsInverse"; static const char str_646[] = "IncludeSubtypes"; static const char str_647[] = "TargetName"; static const struct UA_Field variable_18_definition_fields[] = { {.name=str_644, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_645, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_646, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_647, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_18_definition = {.size=4, .fields=variable_18_definition_fields}; static const struct UA_Attribute nodeId_54_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_54}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_643}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_643}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_18_definition}}, }; static const struct UA_Reference nodeId_54_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_175, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_224, .refid=nodeId_95, .isForward=1}, }; static const char str_648[] = "Counter"; static const struct UA_Attribute nodeId_55_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_55}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_648}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_648}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_55_refs[] = { {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=0}, }; static const char str_649[] = "UInt64"; static const struct UA_Attribute nodeId_56_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_56}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_649}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_649}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_56_refs[] = { {.nodeid=nodeId_154, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_48, .refid=nodeId_334, .isForward=1}, }; static const char str_650[] = "SamplingIntervalDiagnosticsDataType"; static const char str_651[] = "SamplingInterval"; static const char str_652[] = "MonitoredItemCount"; static const char str_653[] = "MaxMonitoredItemCount"; static const char str_654[] = "DisabledMonitoredItemCount"; static const struct UA_Field variable_19_definition_fields[] = { {.name=str_651, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_652, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_653, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_654, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_19_definition = {.size=4, .fields=variable_19_definition_fields}; static const struct UA_Attribute nodeId_57_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_57}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_650}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_650}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_19_definition}}, }; static const struct UA_Reference nodeId_57_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_29, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_230, .refid=nodeId_95, .isForward=1}, }; static const char str_655[] = "References"; static const struct UA_Attribute nodeId_58_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_58}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_655}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_655}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_Symmetric, .data={.u8=1}}, }; static const struct UA_Reference nodeId_58_refs[] = { {.nodeid=nodeId_2, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_114, .refid=nodeId_411, .isForward=0}, }; static const char str_656[] = "ReferenceDescription"; static const char str_657[] = "IsForward"; static const char str_658[] = "NodeId"; static const char str_659[] = "BrowseName"; static const char str_660[] = "DisplayName"; static const char str_661[] = "NodeClass"; static const char str_662[] = "TypeDefinition"; static const struct UA_Field variable_20_definition_fields[] = { {.name=str_644, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_657, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_658, .typeId=nodeId_164, .valueRank=-1, .enumValue=-1}, {.name=str_659, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_661, .typeId=nodeId_530, .valueRank=-1, .enumValue=-1}, {.name=str_662, .typeId=nodeId_164, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_20_definition = {.size=7, .fields=variable_20_definition_fields}; static const struct UA_Attribute nodeId_59_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_59}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_656}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_656}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_20_definition}}, }; static const struct UA_Reference nodeId_59_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_108, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_166, .refid=nodeId_95, .isForward=1}, }; static const char str_663[] = "AddReferencesItem"; static const char str_664[] = "SourceNodeId"; static const char str_665[] = "TargetServerUri"; static const char str_666[] = "TargetNodeId"; static const char str_667[] = "TargetNodeClass"; static const struct UA_Field variable_21_definition_fields[] = { {.name=str_664, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_644, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_657, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_665, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_666, .typeId=nodeId_164, .valueRank=-1, .enumValue=-1}, {.name=str_667, .typeId=nodeId_530, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_21_definition = {.size=6, .fields=variable_21_definition_fields}; static const struct UA_Attribute nodeId_60_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_60}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_663}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_663}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_21_definition}}, }; static const struct UA_Reference nodeId_60_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_126, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_490, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_61_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_61}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_61_refs[] = { {.nodeid=nodeId_107, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_668[] = "CloseSessionResponse"; static const struct UA_Field variable_22_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_22_definition = {.size=1, .fields=variable_22_definition_fields}; static const struct UA_Attribute nodeId_62_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_62}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_668}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_668}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_22_definition}}, }; static const struct UA_Reference nodeId_62_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_89, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_368, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_63_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_63}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_63_refs[] = { {.nodeid=nodeId_362, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_64_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_64}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_64_refs[] = { {.nodeid=nodeId_350, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_669[] = "Double"; static const struct UA_Attribute nodeId_65_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_65}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_669}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_669}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_65_refs[] = { {.nodeid=nodeId_72, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_148, .refid=nodeId_334, .isForward=1}, }; static const char str_670[] = "OptionSetValues"; static const char str_671[] = "PromotedField"; static const char *variable_23[] = { str_671, }; static const struct UA_Variant variable_24_variant = {.dataType=UA_Type_LocalizedText, .size=1, .data={.strArr=variable_23}}; static const struct UA_Attribute nodeId_66_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_66}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_670}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_670}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_24_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_66_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_489, .refid=nodeId_399, .isForward=0}, }; static const char str_672[] = "ShutdownReason"; static const char str_673[] = ""; static const struct UA_Variant variable_25_variant = {.dataType=UA_Type_LocalizedText, .size=0, .data={.str=str_673}}; static const struct UA_Attribute nodeId_67_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_67}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_672}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_672}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_25_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_67_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_536, .refid=nodeId_310, .isForward=0}, }; static const char str_674[] = "XmlElement"; static const struct UA_Attribute nodeId_68_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_68}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_674}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_674}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_68_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_69_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_69}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_69_refs[] = { {.nodeid=nodeId_220, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_675[] = "None"; static const char str_676[] = "Sign"; static const char str_677[] = "SignAndEncrypt"; static const char *variable_26[] = { str_556, str_675, str_676, str_677, }; static const struct UA_Variant variable_27_variant = {.dataType=UA_Type_LocalizedText, .size=4, .data={.strArr=variable_26}}; static const struct UA_Attribute nodeId_70_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_70}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_27_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_70_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_475, .refid=nodeId_399, .isForward=0}, }; static const char str_678[] = "IntegerId"; static const struct UA_Attribute nodeId_71_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_71}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_678}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_678}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_71_refs[] = { {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=0}, }; static const char str_679[] = "Number"; static const struct UA_Attribute nodeId_72_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_72}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_679}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_679}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_72_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_20, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_65, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_120, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_154, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_371, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_73_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_73}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_73_refs[] = { {.nodeid=nodeId_43, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_680[] = "StatusResult"; static const char str_681[] = "StatusCode"; static const char str_682[] = "DiagnosticInfo"; static const struct UA_Field variable_28_definition_fields[] = { {.name=str_681, .typeId=nodeId_360, .valueRank=-1, .enumValue=-1}, {.name=str_682, .typeId=nodeId_318, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_28_definition = {.size=2, .fields=variable_28_definition_fields}; static const struct UA_Attribute nodeId_74_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_74}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_680}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_680}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_28_definition}}, }; static const struct UA_Reference nodeId_74_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_413, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_282, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_75_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_75}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_75_refs[] = { {.nodeid=nodeId_88, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_683[] = "ReferenceTypeAttributes"; static const char str_684[] = "SpecifiedAttributes"; static const char str_685[] = "Description"; static const char str_686[] = "WriteMask"; static const char str_687[] = "UserWriteMask"; static const char str_688[] = "IsAbstract"; static const char str_689[] = "Symmetric"; static const char str_690[] = "InverseName"; static const struct UA_Field variable_29_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_688, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_689, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_690, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_29_definition = {.size=8, .fields=variable_29_definition_fields}; static const struct UA_Attribute nodeId_76_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_76}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_683}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_683}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_29_definition}}, }; static const struct UA_Reference nodeId_76_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, }; static const char str_691[] = "OpenSecureChannelResponse"; static const char str_692[] = "ServerProtocolVersion"; static const char str_693[] = "SecurityToken"; static const char str_694[] = "ServerNonce"; static const struct UA_Field variable_30_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_692, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_693, .typeId=nodeId_219, .valueRank=-1, .enumValue=-1}, {.name=str_694, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_30_definition = {.size=4, .fields=variable_30_definition_fields}; static const struct UA_Attribute nodeId_77_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_77}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_691}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_691}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_30_definition}}, }; static const struct UA_Reference nodeId_77_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_295, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_504, .refid=nodeId_95, .isForward=1}, }; static const char str_695[] = "FolderType"; static const struct UA_Attribute nodeId_78_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_78}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_695}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_695}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_78_refs[] = { {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_13, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_86, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_114, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_528, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_342, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_348, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_380, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_387, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_493, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_44, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_327, .refid=nodeId_324, .isForward=0}, }; static const struct UA_Attribute nodeId_79_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_79}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_79_refs[] = { {.nodeid=nodeId_51, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_80_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_80}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_80_refs[] = { {.nodeid=nodeId_309, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_696[] = "SecondsTillShutdown"; static const struct UA_Attribute nodeId_81_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_81}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_696}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_696}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_49}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_81_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_310, .isForward=0}, }; static const char str_697[] = "BrowseResult"; static const char str_698[] = "ContinuationPoint"; static const struct UA_Field variable_31_definition_fields[] = { {.name=str_681, .typeId=nodeId_360, .valueRank=-1, .enumValue=-1}, {.name=str_698, .typeId=nodeId_331, .valueRank=-1, .enumValue=-1}, {.name=str_655, .typeId=nodeId_59, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_31_definition = {.size=3, .fields=variable_31_definition_fields}; static const struct UA_Attribute nodeId_82_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_82}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_697}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_697}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_31_definition}}, }; static const struct UA_Reference nodeId_82_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_479, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_294, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_83_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_83}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_83_refs[] = { {.nodeid=nodeId_352, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_699[] = "MaxQueryContinuationPoints"; static const struct UA_Variant variable_32_variant = {.dataType=UA_Type_UInt16, .size=0, .data={.u32=0}}; static const struct UA_Attribute nodeId_84_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_84}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_699}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_699}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_32_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_84_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const char str_700[] = "State"; static const struct UA_Attribute nodeId_85_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_85}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_700}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_700}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_365}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_85_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_86_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_86}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_622}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_622}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_86_refs[] = { {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Variant variable_33_variant = {.dataType=UA_Type_UInt32, .size=0, .data={.u32=-1}}; static const struct UA_Attribute nodeId_87_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_87}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_636}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_636}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_33_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_49}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_87_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const char str_701[] = "CallMethodResult"; static const char str_702[] = "InputArgumentResults"; static const char str_703[] = "InputArgumentDiagnosticInfos"; static const char str_704[] = "OutputArguments"; static const struct UA_Field variable_34_definition_fields[] = { {.name=str_681, .typeId=nodeId_360, .valueRank=-1, .enumValue=-1}, {.name=str_702, .typeId=nodeId_360, .valueRank=1, .enumValue=-1}, {.name=str_703, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, {.name=str_704, .typeId=nodeId_139, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_34_definition = {.size=4, .fields=variable_34_definition_fields}; static const struct UA_Attribute nodeId_88_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_88}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_701}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_701}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_34_definition}}, }; static const struct UA_Reference nodeId_88_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_75, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_330, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_89_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_89}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_89_refs[] = { {.nodeid=nodeId_62, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_705[] = "ManufacturerName"; static const struct UA_Attribute nodeId_90_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_90}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_705}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_705}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_90_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_91_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_91}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_91_refs[] = { {.nodeid=nodeId_211, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_706[] = "BuildNumber"; static const struct UA_Attribute nodeId_92_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_92}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_706}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_706}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_92_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_36, .refid=nodeId_310, .isForward=0}, }; static const char str_707[] = "NamespaceUri"; static const struct UA_Attribute nodeId_93_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_93}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_707}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_707}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_93_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_399, .isForward=0}, }; static const char str_708[] = "GeneratesEvent"; static const char str_709[] = "GeneratedBy"; static const struct UA_Attribute nodeId_94_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_94}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_708}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_708}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_709}}, }; static const struct UA_Reference nodeId_94_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const char str_710[] = "HasEncoding"; static const char str_711[] = "EncodingOf"; static const struct UA_Attribute nodeId_95_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_95}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_710}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_710}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_711}}, }; static const struct UA_Reference nodeId_95_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const char str_712[] = ""; static const struct UA_Attribute nodeId_96_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_96}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_712}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_712}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_96_refs[] = { {.nodeid=nodeId_93, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_14, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_383, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_235, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_121, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_173, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_248, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_381, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_307, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_97_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_97}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_97_refs[] = { {.nodeid=nodeId_425, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_98_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_98}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_98_refs[] = { {.nodeid=nodeId_356, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_713[] = "LocalizedText"; static const struct UA_Attribute nodeId_99_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_99}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_713}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_713}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_99_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_100_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_100}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_100_refs[] = { {.nodeid=nodeId_491, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_714[] = "CurrentTime"; static const struct UA_Attribute nodeId_101_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_101}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_714}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_714}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_101_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_536, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_102_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_102}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_603}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_603}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_102_refs[] = { {.nodeid=nodeId_444, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_207, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_513, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_389, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_135, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_465, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_8, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_44, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_310, .isForward=0}, }; static const char str_715[] = "AttributeWriteMask"; static const char str_716[] = "AccessLevel"; static const char str_717[] = "ArrayDimensions"; static const char str_718[] = "ContainsNoLoops"; static const char str_719[] = "DataType"; static const char str_720[] = "EventNotifier"; static const char str_721[] = "Executable"; static const char str_722[] = "Historizing"; static const char str_723[] = "MinimumSamplingInterval"; static const char str_724[] = "UserAccessLevel"; static const char str_725[] = "UserExecutable"; static const char str_726[] = "ValueRank"; static const char str_727[] = "ValueForVariableType"; static const char str_728[] = "DataTypeDefinition"; static const char str_729[] = "RolePermissions"; static const char str_730[] = "AccessRestrictions"; static const char str_731[] = "AccessLevelEx"; static const struct UA_Field variable_35_definition_fields[] = { {.name=str_716, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_717, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_659, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_718, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, {.name=str_719, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_685, .typeId=nodeId_139, .valueRank=-1, .enumValue=5}, {.name=str_660, .typeId=nodeId_139, .valueRank=-1, .enumValue=6}, {.name=str_720, .typeId=nodeId_139, .valueRank=-1, .enumValue=7}, {.name=str_721, .typeId=nodeId_139, .valueRank=-1, .enumValue=8}, {.name=str_722, .typeId=nodeId_139, .valueRank=-1, .enumValue=9}, {.name=str_690, .typeId=nodeId_139, .valueRank=-1, .enumValue=10}, {.name=str_688, .typeId=nodeId_139, .valueRank=-1, .enumValue=11}, {.name=str_723, .typeId=nodeId_139, .valueRank=-1, .enumValue=12}, {.name=str_661, .typeId=nodeId_139, .valueRank=-1, .enumValue=13}, {.name=str_658, .typeId=nodeId_139, .valueRank=-1, .enumValue=14}, {.name=str_689, .typeId=nodeId_139, .valueRank=-1, .enumValue=15}, {.name=str_724, .typeId=nodeId_139, .valueRank=-1, .enumValue=16}, {.name=str_725, .typeId=nodeId_139, .valueRank=-1, .enumValue=17}, {.name=str_687, .typeId=nodeId_139, .valueRank=-1, .enumValue=18}, {.name=str_726, .typeId=nodeId_139, .valueRank=-1, .enumValue=19}, {.name=str_686, .typeId=nodeId_139, .valueRank=-1, .enumValue=20}, {.name=str_727, .typeId=nodeId_139, .valueRank=-1, .enumValue=21}, {.name=str_728, .typeId=nodeId_139, .valueRank=-1, .enumValue=22}, {.name=str_729, .typeId=nodeId_139, .valueRank=-1, .enumValue=23}, {.name=str_730, .typeId=nodeId_139, .valueRank=-1, .enumValue=24}, {.name=str_731, .typeId=nodeId_139, .valueRank=-1, .enumValue=25}, }; static const struct UA_StructDefinition variable_35_definition = {.size=26, .fields=variable_35_definition_fields}; static const struct UA_Attribute nodeId_103_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_103}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_715}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_715}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_35_definition}}, }; static const struct UA_Reference nodeId_103_refs[] = { {.nodeid=nodeId_459, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=0}, }; static const char str_732[] = "PropertyType"; static const struct UA_Attribute nodeId_104_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_104}}, {.id=UA_AttributeId_NodeClass, .data={.u32=16}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_732}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_732}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_ValueRank, .data={.u32=-2}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_104_refs[] = { {.nodeid=nodeId_509, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_7, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_8, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_14, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_19, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_23, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_66, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_70, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_84, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_87, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_93, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_113, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_115, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_117, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_121, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_135, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_137, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_147, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_152, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_160, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_444, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_426, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_173, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_418, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_187, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_189, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_383, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_195, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_377, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_203, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_206, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_207, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_208, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_209, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_217, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_218, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_223, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_235, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_240, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_248, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_249, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_256, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_258, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_265, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_269, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_277, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_279, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_281, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_518, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_300, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_308, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_422, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_532, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_325, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_335, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_336, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_510, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_513, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_376, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_194, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_389, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_401, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_410, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_516, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_517, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_433, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_351, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_347, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_441, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_442, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_346, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_290, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_459, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_533, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_395, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_465, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_145, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_540, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_172, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_480, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_123, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_488, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_500, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_354, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_369, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_343, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_332, .refid=nodeId_324, .isForward=0}, }; static const char str_733[] = "DefaultEncodingId"; static const char str_734[] = "Fields"; static const struct UA_Field variable_36_definition_fields[] = { {.name=str_733, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_607, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_558, .typeId=nodeId_9, .valueRank=-1, .enumValue=-1}, {.name=str_734, .typeId=nodeId_211, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_36_definition = {.size=4, .fields=variable_36_definition_fields}; static const struct UA_Attribute nodeId_105_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_105}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_550}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_550}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_36_definition}}, }; static const struct UA_Reference nodeId_105_refs[] = { {.nodeid=nodeId_339, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_275, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_453, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_106_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_106}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_106_refs[] = { {.nodeid=nodeId_161, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_735[] = "FindServersRequest"; static const char str_736[] = "EndpointUrl"; static const char str_737[] = "LocaleIds"; static const char str_738[] = "ServerUris"; static const struct UA_Field variable_37_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_736, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_737, .typeId=nodeId_159, .valueRank=1, .enumValue=-1}, {.name=str_738, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_37_definition = {.size=4, .fields=variable_37_definition_fields}; static const struct UA_Attribute nodeId_107_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_107}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_735}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_735}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_37_definition}}, }; static const struct UA_Reference nodeId_107_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_61, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_402, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_108_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_108}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_108_refs[] = { {.nodeid=nodeId_59, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_109_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_109}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_109_refs[] = { {.nodeid=nodeId_236, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_110_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_110}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_110_refs[] = { {.nodeid=nodeId_219, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_111_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_111}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_111_refs[] = { {.nodeid=nodeId_47, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_739[] = "ServerType"; static const struct UA_Attribute nodeId_112_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_112}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_739}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_739}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_112_refs[] = { {.nodeid=nodeId_410, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_343, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_199, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_189, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_518, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_511, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_349, .refid=nodeId_324, .isForward=0}, }; static const char str_740[] = "InputArguments"; static const struct UA_Attribute nodeId_113_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_113}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_740}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_740}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_113_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_379, .refid=nodeId_399, .isForward=0}, }; static const char str_741[] = "ReferenceTypes"; static const struct UA_Attribute nodeId_114_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_114}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_741}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_741}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_114_refs[] = { {.nodeid=nodeId_493, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_58, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_115_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_115}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_704}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_704}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_115_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_244, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_116_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_116}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_585}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_585}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_116_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_310, .isForward=0}, }; static const char str_742[] = "ServerProfileArray"; static const char str_743[] = "http://opcfoundation.org/UA-Profile/Server/NanoEmbeddedDevice2017"; static const char *variable_38[] = { str_743, }; static const struct UA_Variant variable_39_variant = {.dataType=UA_Type_String, .size=1, .data={.strArr=variable_38}}; static const struct UA_Attribute nodeId_117_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_117}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_742}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_742}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_39_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_117_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const char str_744[] = "Aggregates"; static const char str_745[] = "AggregatedBy"; static const struct UA_Attribute nodeId_118_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_118}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_744}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_744}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_745}}, }; static const struct UA_Reference nodeId_118_refs[] = { {.nodeid=nodeId_151, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_399, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_310, .refid=nodeId_334, .isForward=1}, }; static const char str_746[] = "AddNodesResult"; static const char str_747[] = "AddedNodeId"; static const struct UA_Field variable_40_definition_fields[] = { {.name=str_681, .typeId=nodeId_360, .valueRank=-1, .enumValue=-1}, {.name=str_747, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_40_definition = {.size=2, .fields=variable_40_definition_fields}; static const struct UA_Attribute nodeId_119_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_119}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_746}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_746}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_40_definition}}, }; static const struct UA_Reference nodeId_119_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, }; static const char str_748[] = "Integer"; static const struct UA_Attribute nodeId_120_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_120}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_748}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_748}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_120_refs[] = { {.nodeid=nodeId_72, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_471, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_239, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_245, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_136, .refid=nodeId_334, .isForward=1}, }; static const char str_749[] = "StaticNodeIdTypes"; static const struct UA_Attribute nodeId_121_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_121}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_749}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_749}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_505}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_121_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_122_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_122}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_122_refs[] = { {.nodeid=nodeId_378, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_123_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_123}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_586}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_586}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_24}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_123_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_399, .isForward=0}, }; static const char str_750[] = "OpenFileMode"; static const char str_751[] = "Read"; static const char str_752[] = "Write"; static const char str_753[] = "EraseExisting"; static const char str_754[] = "Append"; static const struct UA_Field variable_41_definition_fields[] = { {.name=str_751, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_752, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_753, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_754, .typeId=nodeId_139, .valueRank=-1, .enumValue=8}, }; static const struct UA_StructDefinition variable_41_definition = {.size=4, .fields=variable_41_definition_fields}; static const struct UA_Attribute nodeId_124_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_124}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_750}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_750}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_41_definition}}, }; static const struct UA_Reference nodeId_124_refs[] = { {.nodeid=nodeId_533, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const char str_755[] = "VariableTypeAttributes"; static const char str_756[] = "Value"; static const struct UA_Field variable_42_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_756, .typeId=nodeId_538, .valueRank=-1, .enumValue=-1}, {.name=str_719, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_726, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_717, .typeId=nodeId_49, .valueRank=1, .enumValue=-1}, {.name=str_688, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_42_definition = {.size=10, .fields=variable_42_definition_fields}; static const struct UA_Attribute nodeId_125_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_125}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_755}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_755}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_42_definition}}, }; static const struct UA_Reference nodeId_125_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_126_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_126}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_126_refs[] = { {.nodeid=nodeId_60, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_757[] = "DataTypeEncodingType"; static const struct UA_Attribute nodeId_127_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_127}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_757}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_757}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_127_refs[] = { {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_0, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_3, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_4, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_5, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_15, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_17, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_22, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_27, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_29, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_32, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_35, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_38, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_39, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_40, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_50, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_52, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_53, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_61, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_63, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_64, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_69, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_73, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_75, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_79, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_80, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_344, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_83, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_89, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_91, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_97, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_106, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_108, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_110, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_111, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_122, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_126, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_128, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_130, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_131, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_133, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_134, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_403, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_479, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_149, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_468, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_157, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_158, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_162, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_163, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_428, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_451, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_166, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_170, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_171, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_174, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_175, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_178, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_179, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_183, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_417, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_413, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_193, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_382, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_201, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_202, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_204, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_205, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_216, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_221, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_222, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_224, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_225, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_228, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_229, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_230, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_231, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_232, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_233, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_242, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_243, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_246, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_250, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_253, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_254, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_255, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_259, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_260, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_264, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_273, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_274, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_275, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_276, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_282, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_284, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_407, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_287, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_289, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_291, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_294, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_295, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_297, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_301, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_303, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_304, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_305, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_306, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_312, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_314, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_316, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_317, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_424, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_397, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_526, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_438, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_445, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_450, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_521, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_460, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_461, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_353, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_355, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_490, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_464, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_506, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_466, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_467, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_400, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_470, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_402, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_372, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_476, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_196, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_414, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_191, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_408, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_494, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_138, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_285, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_406, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_507, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_416, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_182, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_421, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_462, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_313, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_515, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_436, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_440, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_167, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_446, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_165, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_430, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_452, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_453, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_455, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_420, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_534, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_330, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_150, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_368, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_98, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_192, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_481, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_484, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_142, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_492, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_499, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_502, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_504, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_109, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_261, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_100, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_512, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_359, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_524, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_525, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_345, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_531, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_333, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_319, .refid=nodeId_324, .isForward=0}, }; static const struct UA_Attribute nodeId_128_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_128}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_128_refs[] = { {.nodeid=nodeId_519, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_758[] = "NumericRange"; static const struct UA_Attribute nodeId_129_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_129}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_758}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_758}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_129_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_130_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_130}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_130_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_131_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_131}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_131_refs[] = { {.nodeid=nodeId_227, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_759[] = "NamingRuleType"; static const char str_760[] = "Mandatory"; static const char str_761[] = "Constraint"; static const struct UA_Field variable_43_definition_fields[] = { {.name=str_760, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_602, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_761, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, }; static const struct UA_StructDefinition variable_43_definition = {.size=3, .fields=variable_43_definition_fields}; static const struct UA_Attribute nodeId_132_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_132}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_759}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_759}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_43_definition}}, }; static const struct UA_Reference nodeId_132_refs[] = { {.nodeid=nodeId_208, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_133_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_133}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_133_refs[] = { {.nodeid=nodeId_42, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_134_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_134}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_134_refs[] = { {.nodeid=nodeId_352, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_135_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_135}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_699}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_699}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_135_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_399, .isForward=0}, }; static const char str_762[] = "Int32"; static const struct UA_Attribute nodeId_136_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_136}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_762}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_762}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_136_refs[] = { {.nodeid=nodeId_120, .refid=nodeId_334, .isForward=0}, }; static const char str_763[] = "ServiceLevel"; static const struct UA_Variant variable_44_variant = {.dataType=UA_Type_Byte, .size=0, .data={.u32=0}}; static const struct UA_Attribute nodeId_137_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_137}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_763}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_763}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_44_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_278}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_137_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_138_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_138}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_138_refs[] = { {.nodeid=nodeId_362, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_139_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_139}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_607}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_607}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_139_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_24, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_538, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_68, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_72, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_99, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_241, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_318, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_322, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_360, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_380, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_184, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_514, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_456, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_164, .refid=nodeId_334, .isForward=1}, }; static const char str_764[] = "CallMethodRequest"; static const char str_765[] = "ObjectId"; static const char str_766[] = "MethodId"; static const struct UA_Field variable_45_definition_fields[] = { {.name=str_765, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_766, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_740, .typeId=nodeId_139, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_45_definition = {.size=3, .fields=variable_45_definition_fields}; static const struct UA_Attribute nodeId_140_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_140}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_764}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_764}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_45_definition}}, }; static const struct UA_Reference nodeId_140_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_521, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_502, .refid=nodeId_95, .isForward=1}, }; static const char str_767[] = "UserTokenPolicy"; static const char str_768[] = "TokenType"; static const char str_769[] = "IssuedTokenType"; static const char str_770[] = "IssuerEndpointUrl"; static const char str_771[] = "SecurityPolicyUri"; static const struct UA_Field variable_46_definition_fields[] = { {.name=str_613, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_768, .typeId=nodeId_168, .valueRank=-1, .enumValue=-1}, {.name=str_769, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_770, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_771, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_46_definition = {.size=5, .fields=variable_46_definition_fields}; static const struct UA_Attribute nodeId_141_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_141}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_767}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_767}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_46_definition}}, }; static const struct UA_Reference nodeId_141_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_246, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_440, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_142_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_142}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_142_refs[] = { {.nodeid=nodeId_227, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_772[] = "BaseObjectType"; static const struct UA_Attribute nodeId_143_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_143}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_772}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_772}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_143_refs[] = { {.nodeid=nodeId_1, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_78, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_127, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_177, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_307, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_528, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_337, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_334, .isForward=1}, }; static const char str_773[] = "OpenSecureChannelRequest"; static const char str_774[] = "ClientProtocolVersion"; static const char str_775[] = "RequestType"; static const char str_776[] = "SecurityMode"; static const char str_777[] = "ClientNonce"; static const char str_778[] = "RequestedLifetime"; static const struct UA_Field variable_47_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_774, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_775, .typeId=nodeId_200, .valueRank=-1, .enumValue=-1}, {.name=str_776, .typeId=nodeId_475, .valueRank=-1, .enumValue=-1}, {.name=str_777, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, {.name=str_778, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_47_definition = {.size=6, .fields=variable_47_definition_fields}; static const struct UA_Attribute nodeId_144_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_144}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_773}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_773}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_47_definition}}, }; static const struct UA_Reference nodeId_144_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_157, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_460, .refid=nodeId_95, .isForward=1}, }; static const char str_779[] = "Reserved"; static const char *variable_48[] = { str_589, str_590, str_591, str_592, str_593, str_594, str_595, str_779, str_596, str_597, str_598, str_599, str_600, str_601, }; static const struct UA_Variant variable_49_variant = {.dataType=UA_Type_LocalizedText, .size=14, .data={.strArr=variable_48}}; static const struct UA_Attribute nodeId_145_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_145}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_670}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_670}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_49_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_145_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_26, .refid=nodeId_399, .isForward=0}, }; static const char str_780[] = "HasDescription"; static const char str_781[] = "DescriptionOf"; static const struct UA_Attribute nodeId_146_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_146}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_780}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_780}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_781}}, }; static const struct UA_Reference nodeId_146_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_147_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_147}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_704}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_704}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_147_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_379, .refid=nodeId_399, .isForward=0}, }; static const char str_782[] = "Duration"; static const struct UA_Attribute nodeId_148_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_148}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_782}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_782}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_148_refs[] = { {.nodeid=nodeId_65, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_149_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_149}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_149_refs[] = { {.nodeid=nodeId_10, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_150_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_150}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_150_refs[] = { {.nodeid=nodeId_161, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_783[] = "HasChild"; static const char str_784[] = "ChildOf"; static const struct UA_Attribute nodeId_151_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_151}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_783}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_783}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_784}}, }; static const struct UA_Reference nodeId_151_refs[] = { {.nodeid=nodeId_2, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_118, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_334, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_152_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_152}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_707}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_707}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_152_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_399, .isForward=0}, }; static const char str_785[] = "HasModellingRule"; static const char str_786[] = "ModellingRuleOf"; static const struct UA_Attribute nodeId_153_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_153}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_785}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_785}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_786}}, }; static const struct UA_Reference nodeId_153_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const char str_787[] = "UInteger"; static const struct UA_Attribute nodeId_154_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_154}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_787}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_787}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_154_refs[] = { {.nodeid=nodeId_72, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_278, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_283, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_56, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=1}, }; static const char str_788[] = "Close"; static const struct UA_Attribute nodeId_155_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_155}}, {.id=UA_AttributeId_NodeClass, .data={.u32=4}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_788}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_788}}, {.id=UA_AttributeId_Executable, .data={.u8=1}}, {.id=UA_AttributeId_UserExecutable, .data={.u8=1}}, }; static const struct UA_Reference nodeId_155_refs[] = { {.nodeid=nodeId_290, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_156_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_156}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_610}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_610}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_522}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_156_refs[] = { {.nodeid=nodeId_181, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_185, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_478, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_176, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_434, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_338, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_536, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_157_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_157}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_157_refs[] = { {.nodeid=nodeId_144, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_158_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_158}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_158_refs[] = { {.nodeid=nodeId_427, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_789[] = "LocaleId"; static const struct UA_Attribute nodeId_159_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_159}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_789}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_789}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_159_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Variant variable_50_variant = {.dataType=UA_Type_UInt32, .size=0, .data={.u32=-1}}; static const struct UA_Attribute nodeId_160_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_160}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_638}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_638}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_50_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_49}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_160_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const char str_790[] = "EnumDescription"; static const char str_791[] = "EnumDefinition"; static const struct UA_Field variable_51_definition_fields[] = { {.name=str_548, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_549, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, {.name=str_791, .typeId=nodeId_463, .valueRank=-1, .enumValue=-1}, {.name=str_608, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_51_definition = {.size=4, .fields=variable_51_definition_fields}; static const struct UA_Attribute nodeId_161_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_161}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_790}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_790}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_51_definition}}, }; static const struct UA_Reference nodeId_161_refs[] = { {.nodeid=nodeId_213, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_106, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_150, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_162_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_162}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_162_refs[] = { {.nodeid=nodeId_6, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_163_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_163}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_163_refs[] = { {.nodeid=nodeId_197, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_792[] = "ExpandedNodeId"; static const struct UA_Attribute nodeId_164_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_164}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_792}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_792}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_164_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_165_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_165}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_165_refs[] = { {.nodeid=nodeId_263, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_166_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_166}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_166_refs[] = { {.nodeid=nodeId_59, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_167_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_167}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_167_refs[] = { {.nodeid=nodeId_370, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_793[] = "UserTokenType"; static const char str_794[] = "Anonymous"; static const char str_795[] = "Certificate"; static const char str_796[] = "IssuedToken"; static const struct UA_Field variable_52_definition_fields[] = { {.name=str_794, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_614, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_795, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_796, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, }; static const struct UA_StructDefinition variable_52_definition = {.size=4, .fields=variable_52_definition_fields}; static const struct UA_Attribute nodeId_168_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_168}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_793}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_793}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_52_definition}}, }; static const struct UA_Reference nodeId_168_refs[] = { {.nodeid=nodeId_517, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_169_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_169}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_705}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_705}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_169_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_36, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_170_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_170}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_170_refs[] = { {.nodeid=nodeId_458, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_171_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_171}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_171_refs[] = { {.nodeid=nodeId_339, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_797[] = "NamespaceArray"; static const struct UA_Attribute nodeId_172_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_172}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_797}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_797}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_172_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_399, .isForward=0}, }; static const char str_798[] = "StaticNumericNodeIdRange"; static const struct UA_Attribute nodeId_173_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_173}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_798}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_798}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_129}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_173_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_174_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_174}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_174_refs[] = { {.nodeid=nodeId_51, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_175_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_175}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_175_refs[] = { {.nodeid=nodeId_54, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_176_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_176}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_585}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_585}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_176_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_156, .refid=nodeId_310, .isForward=0}, }; static const char str_799[] = "VendorServerInfoType"; static const struct UA_Attribute nodeId_177_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_177}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_799}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_799}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_177_refs[] = { {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_511, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_388, .refid=nodeId_324, .isForward=0}, }; static const struct UA_Attribute nodeId_178_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_178}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_178_refs[] = { {.nodeid=nodeId_535, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_179_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_179}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_179_refs[] = { {.nodeid=nodeId_210, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_800[] = "CallResponse"; static const struct UA_Field variable_53_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_579, .typeId=nodeId_88, .valueRank=1, .enumValue=-1}, {.name=str_580, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_53_definition = {.size=3, .fields=variable_53_definition_fields}; static const struct UA_Attribute nodeId_180_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_180}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_800}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_800}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_53_definition}}, }; static const struct UA_Reference nodeId_180_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_202, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_233, .refid=nodeId_95, .isForward=1}, }; static const char str_801[] = "ProductUri"; static const struct UA_Attribute nodeId_181_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_181}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_801}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_801}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_181_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_156, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_182_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_182}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_182_refs[] = { {.nodeid=nodeId_31, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_183_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_183}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_183_refs[] = { {.nodeid=nodeId_361, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_184_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_184}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_582}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_582}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_184_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_185_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_185}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_705}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_705}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_185_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_156, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_186_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_186}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_696}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_696}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_49}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_186_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_199, .refid=nodeId_310, .isForward=0}, }; static const char str_802[] = "SigningRequired"; static const char str_803[] = "EncryptionRequired"; static const char str_804[] = "SessionRequired"; static const char str_805[] = "ApplyRestrictionsToBrowse"; static const char *variable_54[] = { str_802, str_803, str_804, str_805, }; static const struct UA_Variant variable_55_variant = {.dataType=UA_Type_LocalizedText, .size=4, .data={.strArr=variable_54}}; static const struct UA_Attribute nodeId_187_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_187}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_670}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_670}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_55_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_187_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_214, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_188_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_188}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_801}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_801}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_188_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_189_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_189}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_763}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_763}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_278}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_189_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_399, .isForward=0}, }; static const char str_806[] = "ServiceFault"; static const struct UA_Field variable_56_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_56_definition = {.size=1, .fields=variable_56_definition_fields}; static const struct UA_Attribute nodeId_190_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_190}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_806}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_806}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_56_definition}}, }; static const struct UA_Reference nodeId_190_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_17, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_303, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_191_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_191}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_191_refs[] = { {.nodeid=nodeId_247, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_192_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_192}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_192_refs[] = { {.nodeid=nodeId_292, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_193_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_193}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_193_refs[] = { {.nodeid=nodeId_425, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_807[] = "Auditing"; static const struct UA_Variant variable_57_variant = {.dataType=UA_Type_Boolean, .size=0, .data={.u8=0}}; static const struct UA_Attribute nodeId_194_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_194}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_807}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_807}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_57_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_241}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_194_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_399, .isForward=0}, }; static const char str_808[] = "MaxBrowseContinuationPoints"; static const struct UA_Variant variable_58_variant = {.dataType=UA_Type_UInt16, .size=0, .data={.u32=-1}}; static const struct UA_Attribute nodeId_195_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_195}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_808}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_808}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_58_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_195_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_196_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_196}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_196_refs[] = { {.nodeid=nodeId_443, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_809[] = "IssuedIdentityToken"; static const char str_810[] = "TokenData"; static const struct UA_Field variable_59_definition_fields[] = { {.name=str_613, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_810, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, {.name=str_616, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_59_definition = {.size=3, .fields=variable_59_definition_fields}; static const struct UA_Attribute nodeId_197_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_197}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_809}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_809}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_59_definition}}, }; static const struct UA_Reference nodeId_197_refs[] = { {.nodeid=nodeId_328, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_163, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_261, .refid=nodeId_95, .isForward=1}, }; static const char str_811[] = "ServerStatusType"; static const struct UA_Attribute nodeId_198_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_198}}, {.id=UA_AttributeId_NodeClass, .data={.u32=16}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_811}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_811}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_405}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_198_refs[] = { {.nodeid=nodeId_396, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_234, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_85, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_36, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_81, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_288, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_46, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_536, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_199, .refid=nodeId_324, .isForward=0}, }; static const char str_812[] = "ServerStatus"; static const struct UA_Attribute nodeId_199_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_199}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_812}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_812}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_405}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_199_refs[] = { {.nodeid=nodeId_363, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_432, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_298, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_37, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_186, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_271, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_310, .isForward=0}, }; static const char str_813[] = "SecurityTokenRequestType"; static const char str_814[] = "Issue"; static const char str_815[] = "Renew"; static const struct UA_Field variable_60_definition_fields[] = { {.name=str_814, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_815, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, }; static const struct UA_StructDefinition variable_60_definition = {.size=2, .fields=variable_60_definition_fields}; static const struct UA_Attribute nodeId_200_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_200}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_813}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_813}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_60_definition}}, }; static const struct UA_Reference nodeId_200_refs[] = { {.nodeid=nodeId_256, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_201_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_201}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_201_refs[] = { {.nodeid=nodeId_522, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_202_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_202}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_202_refs[] = { {.nodeid=nodeId_180, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_816[] = "MinSupportedSampleRate"; static const struct UA_Variant variable_61_variant = {.dataType=UA_Type_Double, .size=0, .data={.d=0}}; static const struct UA_Attribute nodeId_203_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_203}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_816}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_816}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_61_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_148}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_203_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_204_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_204}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_204_refs[] = { {.nodeid=nodeId_378, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_205_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_205}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_205_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_817[] = "MimeType"; static const struct UA_Attribute nodeId_206_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_206}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_817}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_817}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_206_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_28, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_399, .isForward=0}, }; static const char str_818[] = "LocaleIdArray"; static const struct UA_Attribute nodeId_207_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_207}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_818}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_818}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_159}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_207_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_399, .isForward=0}, }; static const char str_819[] = "EnumValues"; static const struct UA_Attribute nodeId_208_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_208}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_819}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_819}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_266}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_208_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_132, .refid=nodeId_399, .isForward=0}, }; static const char str_820[] = "UserWritable"; static const struct UA_Attribute nodeId_209_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_209}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_820}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_820}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_241}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_209_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_399, .isForward=0}, }; static const char str_821[] = "CreateSubscriptionResponse"; static const char str_822[] = "SubscriptionId"; static const char str_823[] = "RevisedPublishingInterval"; static const char str_824[] = "RevisedLifetimeCount"; static const char str_825[] = "RevisedMaxKeepAliveCount"; static const struct UA_Field variable_62_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_822, .typeId=nodeId_71, .valueRank=-1, .enumValue=-1}, {.name=str_823, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_824, .typeId=nodeId_55, .valueRank=-1, .enumValue=-1}, {.name=str_825, .typeId=nodeId_55, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_62_definition = {.size=5, .fields=variable_62_definition_fields}; static const struct UA_Attribute nodeId_210_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_210}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_821}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_821}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_62_definition}}, }; static const struct UA_Reference nodeId_210_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_179, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_316, .refid=nodeId_95, .isForward=1}, }; static const char str_826[] = "StructureField"; static const char str_827[] = "IsOptional"; static const struct UA_Field variable_63_definition_fields[] = { {.name=str_549, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_719, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_726, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_717, .typeId=nodeId_49, .valueRank=1, .enumValue=-1}, {.name=str_636, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_827, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_63_definition = {.size=7, .fields=variable_63_definition_fields}; static const struct UA_Attribute nodeId_211_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_211}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_826}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_826}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_63_definition}}, }; static const struct UA_Reference nodeId_211_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_91, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_264, .refid=nodeId_95, .isForward=1}, }; static const char str_828[] = "Argument"; static const struct UA_Field variable_64_definition_fields[] = { {.name=str_549, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_719, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_726, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_717, .typeId=nodeId_49, .valueRank=1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_64_definition = {.size=5, .fields=variable_64_definition_fields}; static const struct UA_Attribute nodeId_212_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_212}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_828}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_828}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_64_definition}}, }; static const struct UA_Reference nodeId_212_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_232, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_305, .refid=nodeId_95, .isForward=1}, }; static const char str_829[] = "DataTypeDescription"; static const struct UA_Field variable_65_definition_fields[] = { {.name=str_548, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_549, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_65_definition = {.size=2, .fields=variable_65_definition_fields}; static const struct UA_Attribute nodeId_213_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_213}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_829}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_829}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_65_definition}}, }; static const struct UA_Reference nodeId_213_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_6, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_33, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_161, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_382, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_499, .refid=nodeId_95, .isForward=1}, }; static const char str_830[] = "AccessRestrictionType"; static const struct UA_Field variable_66_definition_fields[] = { {.name=str_802, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_803, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_804, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_805, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, }; static const struct UA_StructDefinition variable_66_definition = {.size=4, .fields=variable_66_definition_fields}; static const struct UA_Attribute nodeId_214_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_214}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_830}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_830}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_66_definition}}, }; static const struct UA_Reference nodeId_214_refs[] = { {.nodeid=nodeId_187, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_283, .refid=nodeId_334, .isForward=0}, }; static const char str_831[] = "SessionAuthenticationToken"; static const struct UA_Attribute nodeId_215_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_215}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_831}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_831}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_215_refs[] = { {.nodeid=nodeId_322, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_216_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_216}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_216_refs[] = { {.nodeid=nodeId_374, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_832[] = "Forward"; static const char str_833[] = "Inverse"; static const char *variable_67[] = { str_832, str_833, str_554, str_556, }; static const struct UA_Variant variable_68_variant = {.dataType=UA_Type_LocalizedText, .size=4, .data={.strArr=variable_67}}; static const struct UA_Attribute nodeId_217_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_217}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_68_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_217_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_523, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_218_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_218}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_742}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_742}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_218_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_399, .isForward=0}, }; static const char str_834[] = "ChannelSecurityToken"; static const char str_835[] = "ChannelId"; static const char str_836[] = "TokenId"; static const char str_837[] = "CreatedAt"; static const char str_838[] = "RevisedLifetime"; static const struct UA_Field variable_69_definition_fields[] = { {.name=str_835, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_836, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_837, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_838, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_69_definition = {.size=4, .fields=variable_69_definition_fields}; static const struct UA_Attribute nodeId_219_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_219}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_834}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_834}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_69_definition}}, }; static const struct UA_Reference nodeId_219_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_110, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_452, .refid=nodeId_95, .isForward=1}, }; static const char str_839[] = "UnsignedRationalNumber"; static const char str_840[] = "Numerator"; static const char str_841[] = "Denominator"; static const struct UA_Field variable_70_definition_fields[] = { {.name=str_840, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_841, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_70_definition = {.size=2, .fields=variable_70_definition_fields}; static const struct UA_Attribute nodeId_220_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_220}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_839}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_839}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_70_definition}}, }; static const struct UA_Reference nodeId_220_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_69, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_462, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_221_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_221}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_221_refs[] = { {.nodeid=nodeId_473, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_222_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_222}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_222_refs[] = { {.nodeid=nodeId_266, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_223_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_223}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_740}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_740}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_223_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_386, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_224_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_224}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_224_refs[] = { {.nodeid=nodeId_54, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_225_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_225}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_225_refs[] = { {.nodeid=nodeId_482, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_842[] = "ApplicationInstanceCertificate"; static const struct UA_Attribute nodeId_226_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_226}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_842}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_842}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_226_refs[] = { {.nodeid=nodeId_456, .refid=nodeId_334, .isForward=0}, }; static const char str_843[] = "CallRequest"; static const char str_844[] = "MethodsToCall"; static const struct UA_Field variable_71_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_844, .typeId=nodeId_140, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_71_definition = {.size=2, .fields=variable_71_definition_fields}; static const struct UA_Attribute nodeId_227_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_227}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_843}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_843}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_71_definition}}, }; static const struct UA_Reference nodeId_227_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_131, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_142, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_228_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_228}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_228_refs[] = { {.nodeid=nodeId_31, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_229_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_229}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_229_refs[] = { {.nodeid=nodeId_302, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_230_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_230}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_230_refs[] = { {.nodeid=nodeId_57, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_231_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_231}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_231_refs[] = { {.nodeid=nodeId_42, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_232_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_232}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_232_refs[] = { {.nodeid=nodeId_212, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_233_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_233}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_233_refs[] = { {.nodeid=nodeId_180, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_234_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_234}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_714}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_714}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_234_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_310, .isForward=0}, }; static const char str_845[] = "IsNamespaceSubset"; static const struct UA_Attribute nodeId_235_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_235}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_845}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_845}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_241}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_235_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_399, .isForward=0}, }; static const char str_846[] = "ObjectAttributes"; static const struct UA_Field variable_72_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_720, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_72_definition = {.size=6, .fields=variable_72_definition_fields}; static const struct UA_Attribute nodeId_236_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_236}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_846}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_846}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_72_definition}}, }; static const struct UA_Reference nodeId_236_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_52, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_109, .refid=nodeId_95, .isForward=1}, }; static const char str_847[] = "ApplicationDescription"; static const char str_848[] = "ApplicationUri"; static const char str_849[] = "ApplicationName"; static const char str_850[] = "ApplicationType"; static const char str_851[] = "GatewayServerUri"; static const char str_852[] = "DiscoveryProfileUri"; static const char str_853[] = "DiscoveryUrls"; static const struct UA_Field variable_73_definition_fields[] = { {.name=str_848, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_801, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_849, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_850, .typeId=nodeId_485, .valueRank=-1, .enumValue=-1}, {.name=str_851, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_852, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_853, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_73_definition = {.size=7, .fields=variable_73_definition_fields}; static const struct UA_Attribute nodeId_237_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_237}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_847}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_847}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_73_definition}}, }; static const struct UA_Reference nodeId_237_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_50, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_53, .refid=nodeId_95, .isForward=1}, }; static const char str_854[] = "VariableAttributes"; static const struct UA_Field variable_74_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_756, .typeId=nodeId_538, .valueRank=-1, .enumValue=-1}, {.name=str_719, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_726, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_717, .typeId=nodeId_49, .valueRank=1, .enumValue=-1}, {.name=str_716, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, {.name=str_724, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, {.name=str_723, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_722, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_74_definition = {.size=13, .fields=variable_74_definition_fields}; static const struct UA_Attribute nodeId_238_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_238}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_854}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_854}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_74_definition}}, }; static const struct UA_Reference nodeId_238_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_39, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_319, .refid=nodeId_95, .isForward=1}, }; static const char str_855[] = "SByte"; static const struct UA_Attribute nodeId_239_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_239}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_855}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_855}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_239_refs[] = { {.nodeid=nodeId_120, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_240_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_240}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_704}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_704}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_240_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_367, .refid=nodeId_399, .isForward=0}, }; static const char str_856[] = "Boolean"; static const struct UA_Attribute nodeId_241_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_241}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_856}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_856}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_241_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_242_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_242}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_242_refs[] = { {.nodeid=nodeId_486, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_243_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_243}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_243_refs[] = { {.nodeid=nodeId_328, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_244_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_244}}, {.id=UA_AttributeId_NodeClass, .data={.u32=4}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_751}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_751}}, {.id=UA_AttributeId_Executable, .data={.u8=1}}, {.id=UA_AttributeId_UserExecutable, .data={.u8=1}}, }; static const struct UA_Reference nodeId_244_refs[] = { {.nodeid=nodeId_346, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_115, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_310, .isForward=0}, }; static const char str_857[] = "Int16"; static const struct UA_Attribute nodeId_245_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_245}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_857}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_857}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_245_refs[] = { {.nodeid=nodeId_120, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_246_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_246}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_246_refs[] = { {.nodeid=nodeId_141, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_858[] = "X509IdentityToken"; static const char str_859[] = "CertificateData"; static const struct UA_Field variable_75_definition_fields[] = { {.name=str_613, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_859, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_75_definition = {.size=2, .fields=variable_75_definition_fields}; static const struct UA_Attribute nodeId_247_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_247}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_858}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_858}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_75_definition}}, }; static const struct UA_Reference nodeId_247_refs[] = { {.nodeid=nodeId_328, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_407, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_191, .refid=nodeId_95, .isForward=1}, }; static const char str_860[] = "StaticStringNodeIdPattern"; static const struct UA_Attribute nodeId_248_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_248}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_860}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_860}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_248_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_399, .isForward=0}, }; static const char str_861[] = "1:2252"; static const char str_862[] = "2270"; static const char str_863[] = "2273"; static const char str_864[] = "2280"; static const char str_865[] = "2283"; static const char str_866[] = "2291:2293"; static const char str_867[] = "2297:2734"; static const char str_868[] = "2738:2991"; static const char str_869[] = "2995"; static const char str_870[] = "2998:3703"; static const char str_871[] = "3710:11191"; static const char str_872[] = "11194:11195"; static const char str_873[] = "11202:11241"; static const char str_874[] = "11243:11272"; static const char str_875[] = "11276:11280"; static const char str_876[] = "11284:11311"; static const char str_877[] = "11315:11491"; static const char str_878[] = "11495:11501"; static const char str_879[] = "11503:11701"; static const char str_880[] = "11706"; static const char str_881[] = "11708"; static const char str_882[] = "11716:12164"; static const char str_883[] = "12169:12748"; static const char str_884[] = "12752:12872"; static const char str_885[] = "12875:12884"; static const char str_886[] = "12888:12910"; static const char str_887[] = "12912:14414"; static const char str_888[] = "14416:15003"; static const char str_889[] = "15005:15605"; static const char str_890[] = "15607:16300"; static const char str_891[] = "16306:17633"; static const char str_892[] = "17635:19090"; static const char str_893[] = "19092:24094"; static const char str_894[] = "24102:24103"; static const char str_895[] = "24105:2147483647"; static const char *variable_76[] = { str_861, str_862, str_863, str_864, str_865, str_866, str_867, str_868, str_869, str_870, str_871, str_872, str_873, str_874, str_875, str_876, str_877, str_878, str_879, str_880, str_881, str_882, str_883, str_884, str_885, str_886, str_887, str_888, str_889, str_890, str_891, str_892, str_893, str_894, str_895, }; static const struct UA_Variant variable_77_variant = {.dataType=UA_Type_String, .size=35, .data={.strArr=variable_76}}; static const struct UA_Attribute nodeId_249_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_249}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_798}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_798}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_77_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_129}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_249_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_527, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_250_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_250}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_250_refs[] = { {.nodeid=nodeId_296, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_896[] = "BrowsePathResult"; static const char str_897[] = "Targets"; static const struct UA_Field variable_78_definition_fields[] = { {.name=str_681, .typeId=nodeId_360, .valueRank=-1, .enumValue=-1}, {.name=str_897, .typeId=nodeId_358, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_78_definition = {.size=2, .fields=variable_78_definition_fields}; static const struct UA_Attribute nodeId_251_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_251}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_896}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_896}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_78_definition}}, }; static const struct UA_Reference nodeId_251_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_253, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_254, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Variant variable_79_variant = {.dataType=UA_Type_UInt32, .size=0, .data={.u32=0}}; static const struct UA_Attribute nodeId_252_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_252}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_696}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_696}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_79_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_49}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_252_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_536, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_253_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_253}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_253_refs[] = { {.nodeid=nodeId_251, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_254_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_254}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_254_refs[] = { {.nodeid=nodeId_251, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_255_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_255}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_255_refs[] = { {.nodeid=nodeId_293, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char *variable_80[] = { str_814, str_815, }; static const struct UA_Variant variable_81_variant = {.dataType=UA_Type_LocalizedText, .size=2, .data={.strArr=variable_80}}; static const struct UA_Attribute nodeId_256_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_256}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_81_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_256_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_200, .refid=nodeId_399, .isForward=0}, }; static const char str_898[] = "Index"; static const struct UA_Attribute nodeId_257_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_257}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_898}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_898}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_257_refs[] = { {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_258_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_258}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_819}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_819}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_266}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_258_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_530, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_259_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_259}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_259_refs[] = { {.nodeid=nodeId_302, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_260_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_260}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_260_refs[] = { {.nodeid=nodeId_296, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_261_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_261}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_261_refs[] = { {.nodeid=nodeId_197, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_899[] = "EndpointDescription"; static const char str_900[] = "ServerCertificate"; static const char str_901[] = "UserIdentityTokens"; static const char str_902[] = "TransportProfileUri"; static const char str_903[] = "SecurityLevel"; static const struct UA_Field variable_82_definition_fields[] = { {.name=str_736, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_553, .typeId=nodeId_237, .valueRank=-1, .enumValue=-1}, {.name=str_900, .typeId=nodeId_226, .valueRank=-1, .enumValue=-1}, {.name=str_776, .typeId=nodeId_475, .valueRank=-1, .enumValue=-1}, {.name=str_771, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_901, .typeId=nodeId_141, .valueRank=1, .enumValue=-1}, {.name=str_902, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_903, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_82_definition = {.size=8, .fields=variable_82_definition_fields}; static const struct UA_Attribute nodeId_262_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_262}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_899}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_899}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_82_definition}}, }; static const struct UA_Reference nodeId_262_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_417, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_304, .refid=nodeId_95, .isForward=1}, }; static const char str_904[] = "ActivateSessionResponse"; static const struct UA_Field variable_83_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_694, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, {.name=str_579, .typeId=nodeId_360, .valueRank=1, .enumValue=-1}, {.name=str_580, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_83_definition = {.size=4, .fields=variable_83_definition_fields}; static const struct UA_Attribute nodeId_263_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_263}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_904}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_904}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_83_definition}}, }; static const struct UA_Reference nodeId_263_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_464, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_165, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_264_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_264}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_264_refs[] = { {.nodeid=nodeId_211, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_905[] = "MaxHistoryContinuationPoints"; static const struct UA_Attribute nodeId_265_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_265}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_905}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_905}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_265_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_399, .isForward=0}, }; static const char str_906[] = "EnumValueType"; static const struct UA_Field variable_84_definition_fields[] = { {.name=str_756, .typeId=nodeId_471, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_84_definition = {.size=3, .fields=variable_84_definition_fields}; static const struct UA_Attribute nodeId_266_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_266}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_906}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_906}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_84_definition}}, }; static const struct UA_Reference nodeId_266_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_35, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_222, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_503, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_267_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_267}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_609}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_609}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_267_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_37, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_268_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_268}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_706}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_706}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_268_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_310, .isForward=0}, }; static const char str_907[] = "Writable"; static const struct UA_Attribute nodeId_269_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_269}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_907}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_907}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_241}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_269_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_399, .isForward=0}, }; static const char str_908[] = "ServerCapabilitiesType"; static const struct UA_Attribute nodeId_270_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_270}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_908}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_908}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_270_refs[] = { {.nodeid=nodeId_218, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_377, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_347, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_480, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_354, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_265, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_510, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_86, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_30, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_102, .refid=nodeId_324, .isForward=0}, }; static const struct UA_Attribute nodeId_271_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_271}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_672}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_672}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_271_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_199, .refid=nodeId_310, .isForward=0}, }; static const char str_909[] = "NodeAttributes"; static const struct UA_Field variable_85_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_85_definition = {.size=5, .fields=variable_85_definition_fields}; static const struct UA_Attribute nodeId_272_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_272}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_909}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_909}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_85_definition}}, }; static const struct UA_Reference nodeId_272_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_76, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_125, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_130, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_205, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_236, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_238, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_404, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_497, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_448, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_472, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_273_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_273}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_273_refs[] = { {.nodeid=nodeId_370, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_274_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_274}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_274_refs[] = { {.nodeid=nodeId_429, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_275_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_275}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_275_refs[] = { {.nodeid=nodeId_105, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_276_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_276}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_276_refs[] = { {.nodeid=nodeId_427, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_910[] = "Client"; static const char str_911[] = "ClientAndServer"; static const char str_912[] = "DiscoveryServer"; static const char *variable_86[] = { str_553, str_910, str_911, str_912, }; static const struct UA_Variant variable_87_variant = {.dataType=UA_Type_LocalizedText, .size=4, .data={.strArr=variable_86}}; static const struct UA_Attribute nodeId_277_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_277}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_87_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_277_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_485, .refid=nodeId_399, .isForward=0}, }; static const char str_913[] = "Byte"; static const struct UA_Attribute nodeId_278_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_278}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_913}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_913}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_278_refs[] = { {.nodeid=nodeId_154, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_385, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_279_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_279}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_576}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_576}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_279_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_399, .isForward=0}, }; static const char str_914[] = "CreateSubscriptionRequest"; static const char str_915[] = "RequestedPublishingInterval"; static const char str_916[] = "RequestedLifetimeCount"; static const char str_917[] = "RequestedMaxKeepAliveCount"; static const char str_918[] = "MaxNotificationsPerPublish"; static const char str_919[] = "PublishingEnabled"; static const char str_920[] = "Priority"; static const struct UA_Field variable_88_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_915, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_916, .typeId=nodeId_55, .valueRank=-1, .enumValue=-1}, {.name=str_917, .typeId=nodeId_55, .valueRank=-1, .enumValue=-1}, {.name=str_918, .typeId=nodeId_55, .valueRank=-1, .enumValue=-1}, {.name=str_919, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_920, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_88_definition = {.size=7, .fields=variable_88_definition_fields}; static const struct UA_Attribute nodeId_280_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_280}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_914}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_914}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_88_definition}}, }; static const struct UA_Reference nodeId_280_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_438, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_400, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Variant variable_89_variant = {.dataType=UA_Type_String, .size=0, .data={.str=NULL}}; static const struct UA_Attribute nodeId_281_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_281}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_860}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_860}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_89_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_281_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_527, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_282_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_282}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_282_refs[] = { {.nodeid=nodeId_74, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_921[] = "UInt16"; static const struct UA_Attribute nodeId_283_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_283}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_921}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_921}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_283_refs[] = { {.nodeid=nodeId_154, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_489, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_214, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_284_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_284}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_284_refs[] = { {.nodeid=nodeId_390, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_285_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_285}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_285_refs[] = { {.nodeid=nodeId_374, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_922[] = "HasOrderedComponent"; static const char str_923[] = "OrderedComponentOf"; static const struct UA_Attribute nodeId_286_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_286}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_922}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_922}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_923}}, }; static const struct UA_Reference nodeId_286_refs[] = { {.nodeid=nodeId_310, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_287_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_287}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_287_refs[] = { {.nodeid=nodeId_454, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_288_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_288}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_672}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_672}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_288_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_289_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_289}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_289_refs[] = { {.nodeid=nodeId_483, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_290_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_290}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_740}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_740}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_290_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_155, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_291_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_291}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_291_refs[] = { {.nodeid=nodeId_6, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_924[] = "Range"; static const char str_925[] = "Low"; static const char str_926[] = "High"; static const struct UA_Field variable_90_definition_fields[] = { {.name=str_925, .typeId=nodeId_65, .valueRank=-1, .enumValue=-1}, {.name=str_926, .typeId=nodeId_65, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_90_definition = {.size=2, .fields=variable_90_definition_fields}; static const struct UA_Attribute nodeId_292_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_292}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_924}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_924}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_90_definition}}, }; static const struct UA_Reference nodeId_292_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_301, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_192, .refid=nodeId_95, .isForward=1}, }; static const char str_927[] = "ViewDescription"; static const char str_928[] = "ViewId"; static const char str_929[] = "ViewVersion"; static const struct UA_Field variable_91_definition_fields[] = { {.name=str_928, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_625, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_929, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_91_definition = {.size=3, .fields=variable_91_definition_fields}; static const struct UA_Attribute nodeId_293_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_293}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_927}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_927}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_91_definition}}, }; static const struct UA_Reference nodeId_293_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_255, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_306, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_294_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_294}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_294_refs[] = { {.nodeid=nodeId_82, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_295_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_295}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_295_refs[] = { {.nodeid=nodeId_77, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_930[] = "WriteValue"; static const char str_931[] = "AttributeId"; static const char str_932[] = "IndexRange"; static const struct UA_Field variable_92_definition_fields[] = { {.name=str_658, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_931, .typeId=nodeId_71, .valueRank=-1, .enumValue=-1}, {.name=str_932, .typeId=nodeId_129, .valueRank=-1, .enumValue=-1}, {.name=str_756, .typeId=nodeId_538, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_92_definition = {.size=4, .fields=variable_92_definition_fields}; static const struct UA_Attribute nodeId_296_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_296}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_930}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_930}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_92_definition}}, }; static const struct UA_Reference nodeId_296_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_250, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_260, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_297_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_297}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_297_refs[] = { {.nodeid=nodeId_12, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_298_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_298}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_700}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_700}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_365}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_298_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_199, .refid=nodeId_310, .isForward=0}, }; static const char str_933[] = "ProductName"; static const struct UA_Attribute nodeId_299_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_299}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_933}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_933}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_299_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_394, .refid=nodeId_310, .isForward=0}, }; static const char str_934[] = "en-US"; static const char *variable_93[] = { str_934, }; static const struct UA_Variant variable_94_variant = {.dataType=UA_Type_String, .size=1, .data={.strArr=variable_93}}; static const struct UA_Attribute nodeId_300_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_300}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_818}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_818}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_94_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_159}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_300_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_301_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_301}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_301_refs[] = { {.nodeid=nodeId_292, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_935[] = "SessionDiagnosticsDataType"; static const char str_936[] = "SessionId"; static const char str_937[] = "SessionName"; static const char str_938[] = "ClientDescription"; static const char str_939[] = "ServerUri"; static const char str_940[] = "ActualSessionTimeout"; static const char str_941[] = "MaxResponseMessageSize"; static const char str_942[] = "ClientConnectionTime"; static const char str_943[] = "ClientLastContactTime"; static const char str_944[] = "CurrentSubscriptionsCount"; static const char str_945[] = "CurrentMonitoredItemsCount"; static const char str_946[] = "CurrentPublishRequestsInQueue"; static const char str_947[] = "TotalRequestCount"; static const char str_948[] = "UnauthorizedRequestCount"; static const char str_949[] = "ReadCount"; static const char str_950[] = "HistoryReadCount"; static const char str_951[] = "WriteCount"; static const char str_952[] = "HistoryUpdateCount"; static const char str_953[] = "CallCount"; static const char str_954[] = "CreateMonitoredItemsCount"; static const char str_955[] = "ModifyMonitoredItemsCount"; static const char str_956[] = "SetMonitoringModeCount"; static const char str_957[] = "SetTriggeringCount"; static const char str_958[] = "DeleteMonitoredItemsCount"; static const char str_959[] = "CreateSubscriptionCount"; static const char str_960[] = "ModifySubscriptionCount"; static const char str_961[] = "SetPublishingModeCount"; static const char str_962[] = "PublishCount"; static const char str_963[] = "RepublishCount"; static const char str_964[] = "TransferSubscriptionsCount"; static const char str_965[] = "DeleteSubscriptionsCount"; static const char str_966[] = "AddNodesCount"; static const char str_967[] = "AddReferencesCount"; static const char str_968[] = "DeleteNodesCount"; static const char str_969[] = "DeleteReferencesCount"; static const char str_970[] = "BrowseCount"; static const char str_971[] = "BrowseNextCount"; static const char str_972[] = "TranslateBrowsePathsToNodeIdsCount"; static const char str_973[] = "QueryFirstCount"; static const char str_974[] = "QueryNextCount"; static const char str_975[] = "RegisterNodesCount"; static const char str_976[] = "UnregisterNodesCount"; static const struct UA_Field variable_95_definition_fields[] = { {.name=str_936, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_937, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_938, .typeId=nodeId_237, .valueRank=-1, .enumValue=-1}, {.name=str_939, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_736, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_737, .typeId=nodeId_159, .valueRank=1, .enumValue=-1}, {.name=str_940, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_941, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_942, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_943, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_944, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_945, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_946, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_947, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_948, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_949, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_950, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_951, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_952, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_953, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_954, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_955, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_956, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_957, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_958, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_959, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_960, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_961, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_962, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_963, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_964, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_965, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_966, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_967, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_968, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_969, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_970, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_971, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_972, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_973, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_974, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_975, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, {.name=str_976, .typeId=nodeId_356, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_95_definition = {.size=43, .fields=variable_95_definition_fields}; static const struct UA_Attribute nodeId_302_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_302}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_935}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_935}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_95_definition}}, }; static const struct UA_Reference nodeId_302_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_229, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_259, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_303_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_303}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_303_refs[] = { {.nodeid=nodeId_190, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_304_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_304}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_304_refs[] = { {.nodeid=nodeId_262, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_305_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_305}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_305_refs[] = { {.nodeid=nodeId_212, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_306_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_306}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_306_refs[] = { {.nodeid=nodeId_293, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_977[] = "NamespacesType"; static const struct UA_Attribute nodeId_307_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_307}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_977}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_977}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_307_refs[] = { {.nodeid=nodeId_96, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_25, .refid=nodeId_324, .isForward=0}, }; static const struct UA_Variant variable_96_variant = {.dataType=UA_Type_UInt16, .size=0, .data={.u32=0}}; static const struct UA_Attribute nodeId_308_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_308}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_905}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_905}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_96_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_308_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_399, .isForward=0}, }; static const char str_978[] = "ReadValueId"; static const char str_979[] = "DataEncoding"; static const struct UA_Field variable_97_definition_fields[] = { {.name=str_658, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_931, .typeId=nodeId_71, .valueRank=-1, .enumValue=-1}, {.name=str_932, .typeId=nodeId_129, .valueRank=-1, .enumValue=-1}, {.name=str_979, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_97_definition = {.size=4, .fields=variable_97_definition_fields}; static const struct UA_Attribute nodeId_309_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_309}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_978}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_978}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_97_definition}}, }; static const struct UA_Reference nodeId_309_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_80, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_344, .refid=nodeId_95, .isForward=1}, }; static const char str_980[] = "HasComponent"; static const char str_981[] = "ComponentOf"; static const struct UA_Attribute nodeId_310_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_310}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_980}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_980}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_981}}, }; static const struct UA_Reference nodeId_310_refs[] = { {.nodeid=nodeId_118, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_286, .refid=nodeId_334, .isForward=1}, }; static const char str_982[] = "FindServersResponse"; static const char str_983[] = "Servers"; static const struct UA_Field variable_98_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_983, .typeId=nodeId_237, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_98_definition = {.size=2, .fields=variable_98_definition_fields}; static const struct UA_Attribute nodeId_311_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_311}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_982}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_982}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_98_definition}}, }; static const struct UA_Reference nodeId_311_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_0, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_314, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_312_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_312}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_312_refs[] = { {.nodeid=nodeId_483, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_313_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_313}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_313_refs[] = { {.nodeid=nodeId_339, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_314_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_314}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_314_refs[] = { {.nodeid=nodeId_311, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Variant variable_99_variant = {.dataType=UA_Type_Int32, .size=0, .data={.i32=0}}; static const struct UA_Attribute nodeId_315_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_315}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_700}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_700}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_99_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_365}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_315_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_536, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_316_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_316}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_316_refs[] = { {.nodeid=nodeId_210, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_317_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_317}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_317_refs[] = { {.nodeid=nodeId_340, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_318_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_318}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_682}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_682}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_318_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_319_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_319}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_319_refs[] = { {.nodeid=nodeId_238, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_984[] = "DataSetMetaDataType"; static const char str_985[] = "DataSetClassId"; static const char str_986[] = "ConfigurationVersion"; static const struct UA_Field variable_100_definition_fields[] = { {.name=str_571, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, {.name=str_572, .typeId=nodeId_6, .valueRank=1, .enumValue=-1}, {.name=str_573, .typeId=nodeId_161, .valueRank=1, .enumValue=-1}, {.name=str_574, .typeId=nodeId_33, .valueRank=1, .enumValue=-1}, {.name=str_549, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_734, .typeId=nodeId_447, .valueRank=1, .enumValue=-1}, {.name=str_985, .typeId=nodeId_184, .valueRank=-1, .enumValue=-1}, {.name=str_986, .typeId=nodeId_474, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_100_definition = {.size=9, .fields=variable_100_definition_fields}; static const struct UA_Attribute nodeId_320_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_320}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_984}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_984}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_100_definition}}, }; static const struct UA_Reference nodeId_320_refs[] = { {.nodeid=nodeId_12, .refid=nodeId_334, .isForward=0}, }; static const char str_987[] = "ToState"; static const char str_988[] = "FromTransition"; static const struct UA_Attribute nodeId_321_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_321}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_987}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_987}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_988}}, }; static const struct UA_Reference nodeId_321_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_322_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_322}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_658}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_658}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_322_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_215, .refid=nodeId_334, .isForward=1}, }; static const char str_989[] = "WriteResponse"; static const struct UA_Field variable_101_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_579, .typeId=nodeId_360, .valueRank=1, .enumValue=-1}, {.name=str_580, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_101_definition = {.size=3, .fields=variable_101_definition_fields}; static const struct UA_Attribute nodeId_323_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_323}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_989}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_989}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_101_definition}}, }; static const struct UA_Reference nodeId_323_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_355, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_446, .refid=nodeId_95, .isForward=1}, }; static const char str_990[] = "HasTypeDefinition"; static const char str_991[] = "TypeDefinitionOf"; static const struct UA_Attribute nodeId_324_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_324}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_990}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_990}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_991}}, }; static const struct UA_Reference nodeId_324_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const char *variable_102[] = { str_589, str_590, str_591, str_592, str_593, str_594, str_595, }; static const struct UA_Variant variable_103_variant = {.dataType=UA_Type_LocalizedText, .size=7, .data={.strArr=variable_102}}; static const struct UA_Attribute nodeId_325_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_325}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_670}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_670}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_103_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_325_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_385, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_326_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_326}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_705}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_705}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_326_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_37, .refid=nodeId_310, .isForward=0}, }; static const char str_992[] = "Objects"; static const struct UA_Attribute nodeId_327_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_327}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_992}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_992}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_327_refs[] = { {.nodeid=nodeId_387, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_411, .isForward=1}, }; static const char str_993[] = "UserIdentityToken"; static const struct UA_Field variable_104_definition_fields[] = { {.name=str_613, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_104_definition = {.size=1, .fields=variable_104_definition_fields}; static const struct UA_Attribute nodeId_328_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_328}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_993}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_993}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_104_definition}}, }; static const struct UA_Reference nodeId_328_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_42, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_197, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_243, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_247, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_457, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_333, .refid=nodeId_95, .isForward=1}, }; static const char str_994[] = "VersionTime"; static const struct UA_Attribute nodeId_329_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_329}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_994}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_994}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_329_refs[] = { {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_330_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_330}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_330_refs[] = { {.nodeid=nodeId_88, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_331_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_331}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_698}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_698}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_331_refs[] = { {.nodeid=nodeId_456, .refid=nodeId_334, .isForward=0}, }; static const char *variable_105[] = { str_559, str_560, str_561, str_562, str_563, }; static const struct UA_Variant variable_106_variant = {.dataType=UA_Type_LocalizedText, .size=5, .data={.strArr=variable_105}}; static const struct UA_Attribute nodeId_332_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_332}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_106_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_332_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_9, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_333_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_333}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_333_refs[] = { {.nodeid=nodeId_328, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_995[] = "HasSubtype"; static const char str_996[] = "SubtypeOf"; static const struct UA_Attribute nodeId_334_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_334}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_995}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_995}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_996}}, }; static const struct UA_Reference nodeId_334_refs[] = { {.nodeid=nodeId_151, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Variant variable_107_variant = {.dataType=UA_Type_Boolean, .size=0, .data={.u8=0}}; static const struct UA_Attribute nodeId_335_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_335}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_845}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_845}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_107_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_241}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_335_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_527, .refid=nodeId_399, .isForward=0}, }; static const char str_997[] = "Browse"; static const char str_998[] = "ReadRolePermissions"; static const char str_999[] = "WriteAttribute"; static const char str_1000[] = "WriteRolePermissions"; static const char str_1001[] = "WriteHistorizing"; static const char str_1002[] = "ReadHistory"; static const char str_1003[] = "InsertHistory"; static const char str_1004[] = "ModifyHistory"; static const char str_1005[] = "DeleteHistory"; static const char str_1006[] = "ReceiveEvents"; static const char str_1007[] = "Call"; static const char str_1008[] = "AddReference"; static const char str_1009[] = "RemoveReference"; static const char str_1010[] = "DeleteNode"; static const char str_1011[] = "AddNode"; static const char *variable_108[] = { str_997, str_998, str_999, str_1000, str_1001, str_751, str_752, str_1002, str_1003, str_1004, str_1005, str_1006, str_1007, str_1008, str_1009, str_1010, str_1011, }; static const struct UA_Variant variable_109_variant = {.dataType=UA_Type_LocalizedText, .size=17, .data={.strArr=variable_108}}; static const struct UA_Attribute nodeId_336_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_336}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_670}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_670}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_109_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_336_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_487, .refid=nodeId_399, .isForward=0}, }; static const char str_1012[] = "ModellingRuleType"; static const struct UA_Attribute nodeId_337_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_337}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1012}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1012}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_337_refs[] = { {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_28, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_381, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_341, .refid=nodeId_324, .isForward=0}, }; static const struct UA_Attribute nodeId_338_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_338}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_609}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_609}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_338_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_156, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_339_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_339}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_728}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_728}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_339_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_105, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_171, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_463, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_313, .refid=nodeId_95, .isForward=1}, }; static const char str_1013[] = "GetEndpointsResponse"; static const char str_1014[] = "Endpoints"; static const struct UA_Field variable_110_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_1014, .typeId=nodeId_262, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_110_definition = {.size=2, .fields=variable_110_definition_fields}; static const struct UA_Attribute nodeId_340_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_340}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1013}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1013}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_110_definition}}, }; static const struct UA_Reference nodeId_340_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_27, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_317, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_341_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_341}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_760}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_760}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_341_refs[] = { {.nodeid=nodeId_337, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_8, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_14, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_21, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_34, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_36, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_37, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_379, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_81, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_85, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_86, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_90, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_92, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_93, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_375, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_511, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_102, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_113, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_115, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_116, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_121, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_135, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_147, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_152, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_155, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_444, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_169, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_173, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_186, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_189, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_383, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_199, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_377, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_207, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_209, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_218, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_223, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_234, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_235, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_240, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_244, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_248, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_265, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_267, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_268, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_269, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_271, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_279, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_288, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_518, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_298, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_299, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_422, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_435, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_520, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_510, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_366, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_513, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_376, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_386, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_389, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_396, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_188, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_495, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_410, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_393, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_516, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_432, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_351, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_347, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_441, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_442, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_346, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_290, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_465, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_469, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_540, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_480, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_123, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_488, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_326, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_44, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_354, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_373, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_367, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_363, .refid=nodeId_153, .isForward=0}, {.nodeid=nodeId_343, .refid=nodeId_153, .isForward=0}, }; static const struct UA_Attribute nodeId_342_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_342}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_622}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_622}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_342_refs[] = { {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_343_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_343}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_797}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_797}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_343_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_344_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_344}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_344_refs[] = { {.nodeid=nodeId_309, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_345_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_345}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_345_refs[] = { {.nodeid=nodeId_405, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_346_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_346}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_740}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_740}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_346_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_244, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_347_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_347}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_816}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_816}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_148}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_347_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_399, .isForward=0}, }; static const char str_1015[] = "Views"; static const struct UA_Attribute nodeId_348_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_348}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1015}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1015}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_348_refs[] = { {.nodeid=nodeId_387, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_349_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_349}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_553}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_553}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_349_refs[] = { {.nodeid=nodeId_401, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_172, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_536, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_137, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_30, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_194, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_388, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_327, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_112, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_25, .refid=nodeId_310, .isForward=1}, }; static const char str_1016[] = "CloseSecureChannelRequest"; static const struct UA_Field variable_111_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_111_definition = {.size=1, .fields=variable_111_definition_fields}; static const struct UA_Attribute nodeId_350_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_350}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1016}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1016}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_111_definition}}, }; static const struct UA_Reference nodeId_350_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_64, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_451, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_351_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_351}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_740}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_740}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_351_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_373, .refid=nodeId_399, .isForward=0}, }; static const char str_1017[] = "EUInformation"; static const char str_1018[] = "UnitId"; static const struct UA_Field variable_112_definition_fields[] = { {.name=str_707, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_1018, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_112_definition = {.size=4, .fields=variable_112_definition_fields}; static const struct UA_Attribute nodeId_352_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_352}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1017}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1017}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_112_definition}}, }; static const struct UA_Reference nodeId_352_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_83, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_134, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_353_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_353}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_353_refs[] = { {.nodeid=nodeId_529, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_354_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_354}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_699}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_699}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_354_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_355_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_355}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_355_refs[] = { {.nodeid=nodeId_323, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1019[] = "ServiceCounterDataType"; static const char str_1020[] = "TotalCount"; static const char str_1021[] = "ErrorCount"; static const struct UA_Field variable_113_definition_fields[] = { {.name=str_1020, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_1021, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_113_definition = {.size=2, .fields=variable_113_definition_fields}; static const struct UA_Attribute nodeId_356_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_356}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1019}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1019}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_113_definition}}, }; static const struct UA_Reference nodeId_356_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_98, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_359, .refid=nodeId_95, .isForward=1}, }; static const char str_1022[] = "HasNotifier"; static const char str_1023[] = "NotifierOf"; static const struct UA_Attribute nodeId_357_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_357}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1022}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1022}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_1023}}, }; static const struct UA_Reference nodeId_357_refs[] = { {.nodeid=nodeId_398, .refid=nodeId_334, .isForward=0}, }; static const char str_1024[] = "BrowsePathTarget"; static const char str_1025[] = "TargetId"; static const char str_1026[] = "RemainingPathIndex"; static const struct UA_Field variable_114_definition_fields[] = { {.name=str_1025, .typeId=nodeId_164, .valueRank=-1, .enumValue=-1}, {.name=str_1026, .typeId=nodeId_257, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_114_definition = {.size=2, .fields=variable_114_definition_fields}; static const struct UA_Attribute nodeId_358_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_358}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1024}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1024}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_114_definition}}, }; static const struct UA_Reference nodeId_358_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_372, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_484, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_359_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_359}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_359_refs[] = { {.nodeid=nodeId_356, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_360_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_360}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_681}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_681}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_360_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const char str_1027[] = "SessionSecurityDiagnosticsDataType"; static const char str_1028[] = "ClientUserIdOfSession"; static const char str_1029[] = "ClientUserIdHistory"; static const char str_1030[] = "AuthenticationMechanism"; static const char str_1031[] = "Encoding"; static const char str_1032[] = "TransportProtocol"; static const char str_1033[] = "ClientCertificate"; static const struct UA_Field variable_115_definition_fields[] = { {.name=str_936, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_1028, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_1029, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, {.name=str_1030, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_1031, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_1032, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_776, .typeId=nodeId_475, .valueRank=-1, .enumValue=-1}, {.name=str_771, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_1033, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_115_definition = {.size=9, .fields=variable_115_definition_fields}; static const struct UA_Attribute nodeId_361_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_361}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1027}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1027}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_115_definition}}, }; static const struct UA_Reference nodeId_361_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_183, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_455, .refid=nodeId_95, .isForward=1}, }; static const char str_1034[] = "AddNodesRequest"; static const char str_1035[] = "NodesToAdd"; static const struct UA_Field variable_116_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_1035, .typeId=nodeId_535, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_116_definition = {.size=2, .fields=variable_116_definition_fields}; static const struct UA_Attribute nodeId_362_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_362}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1034}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1034}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_116_definition}}, }; static const struct UA_Reference nodeId_362_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_63, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_138, .refid=nodeId_95, .isForward=1}, }; static const char str_1036[] = "StartTime"; static const struct UA_Attribute nodeId_363_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_363}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1036}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1036}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_363_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_199, .refid=nodeId_310, .isForward=0}, }; static const char str_1037[] = "KeyValuePair"; static const char str_1038[] = "Key"; static const struct UA_Field variable_117_definition_fields[] = { {.name=str_1038, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, {.name=str_756, .typeId=nodeId_538, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_117_definition = {.size=2, .fields=variable_117_definition_fields}; static const struct UA_Attribute nodeId_364_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_364}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1037}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1037}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_117_definition}}, }; static const struct UA_Reference nodeId_364_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, }; static const char str_1039[] = "ServerState"; static const char str_1040[] = "Running"; static const char str_1041[] = "Failed"; static const char str_1042[] = "NoConfiguration"; static const char str_1043[] = "Suspended"; static const char str_1044[] = "Shutdown"; static const char str_1045[] = "Test"; static const char str_1046[] = "CommunicationFault"; static const char str_1047[] = "Unknown"; static const struct UA_Field variable_118_definition_fields[] = { {.name=str_1040, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_1041, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_1042, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_1043, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, {.name=str_1044, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_1045, .typeId=nodeId_139, .valueRank=-1, .enumValue=5}, {.name=str_1046, .typeId=nodeId_139, .valueRank=-1, .enumValue=6}, {.name=str_1047, .typeId=nodeId_139, .valueRank=-1, .enumValue=7}, }; static const struct UA_StructDefinition variable_118_definition = {.size=8, .fields=variable_118_definition_fields}; static const struct UA_Attribute nodeId_365_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_365}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1039}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1039}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_118_definition}}, }; static const struct UA_Reference nodeId_365_refs[] = { {.nodeid=nodeId_426, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_366_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_366}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_801}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_801}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_366_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_37, .refid=nodeId_310, .isForward=0}, }; static const char str_1048[] = "Open"; static const struct UA_Attribute nodeId_367_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_367}}, {.id=UA_AttributeId_NodeClass, .data={.u32=4}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1048}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1048}}, {.id=UA_AttributeId_Executable, .data={.u8=1}}, {.id=UA_AttributeId_UserExecutable, .data={.u8=1}}, }; static const struct UA_Reference nodeId_367_refs[] = { {.nodeid=nodeId_488, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_240, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_368_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_368}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_368_refs[] = { {.nodeid=nodeId_62, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1049[] = "LastModifiedTime"; static const struct UA_Attribute nodeId_369_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_369}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1049}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1049}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_24}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_369_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_28, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_399, .isForward=0}, }; static const char str_1050[] = "SignatureData"; static const char str_1051[] = "Algorithm"; static const char str_1052[] = "Signature"; static const struct UA_Field variable_119_definition_fields[] = { {.name=str_1051, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_1052, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_119_definition = {.size=2, .fields=variable_119_definition_fields}; static const struct UA_Attribute nodeId_370_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_370}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1050}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1050}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_119_definition}}, }; static const struct UA_Reference nodeId_370_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_273, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_167, .refid=nodeId_95, .isForward=1}, }; static const char str_1053[] = "Decimal"; static const struct UA_Attribute nodeId_371_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_371}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1053}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1053}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_371_refs[] = { {.nodeid=nodeId_72, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_372_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_372}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_372_refs[] = { {.nodeid=nodeId_358, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1054[] = "SetPosition"; static const struct UA_Attribute nodeId_373_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_373}}, {.id=UA_AttributeId_NodeClass, .data={.u32=4}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1054}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1054}}, {.id=UA_AttributeId_Executable, .data={.u8=1}}, {.id=UA_AttributeId_UserExecutable, .data={.u8=1}}, }; static const struct UA_Reference nodeId_373_refs[] = { {.nodeid=nodeId_351, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_310, .isForward=0}, }; static const char str_1055[] = "RolePermissionType"; static const char str_1056[] = "RoleId"; static const char str_1057[] = "Permissions"; static const struct UA_Field variable_120_definition_fields[] = { {.name=str_1056, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_1057, .typeId=nodeId_487, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_120_definition = {.size=2, .fields=variable_120_definition_fields}; static const struct UA_Attribute nodeId_374_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_374}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1055}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1055}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_120_definition}}, }; static const struct UA_Reference nodeId_374_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_216, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_285, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_375_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_375}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_801}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_801}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_375_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_36, .refid=nodeId_310, .isForward=0}, }; static const char str_1058[] = "OpenCount"; static const struct UA_Attribute nodeId_376_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_376}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1058}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1058}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_376_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_377_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_377}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_818}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_818}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_159}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_377_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_399, .isForward=0}, }; static const char str_1059[] = "EndpointType"; static const struct UA_Field variable_121_definition_fields[] = { {.name=str_736, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_776, .typeId=nodeId_475, .valueRank=-1, .enumValue=-1}, {.name=str_771, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_902, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_121_definition = {.size=4, .fields=variable_121_definition_fields}; static const struct UA_Attribute nodeId_378_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_378}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1059}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1059}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_121_definition}}, }; static const struct UA_Reference nodeId_378_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_122, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_204, .refid=nodeId_95, .isForward=1}, }; static const char str_1060[] = "GetPosition"; static const struct UA_Attribute nodeId_379_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_379}}, {.id=UA_AttributeId_NodeClass, .data={.u32=4}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1060}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1060}}, {.id=UA_AttributeId_Executable, .data={.u8=1}}, {.id=UA_AttributeId_UserExecutable, .data={.u8=1}}, }; static const struct UA_Reference nodeId_379_refs[] = { {.nodeid=nodeId_113, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_147, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_310, .isForward=0}, }; static const char str_1061[] = "DataTypes"; static const struct UA_Attribute nodeId_380_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_380}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1061}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1061}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_380_refs[] = { {.nodeid=nodeId_493, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_139, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, }; static const char str_1062[] = "OptionalPlaceholder"; static const struct UA_Attribute nodeId_381_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_381}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1062}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1062}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_381_refs[] = { {.nodeid=nodeId_337, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_153, .isForward=0}, }; static const struct UA_Attribute nodeId_382_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_382}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_382_refs[] = { {.nodeid=nodeId_213, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_383_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_383}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_586}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_586}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_24}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_383_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_96, .refid=nodeId_399, .isForward=0}, }; static const char str_1063[] = "HasCause"; static const char str_1064[] = "MayBeCausedBy"; static const struct UA_Attribute nodeId_384_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_384}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1063}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1063}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_1064}}, }; static const struct UA_Reference nodeId_384_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const char str_1065[] = "AccessLevelType"; static const struct UA_Field variable_122_definition_fields[] = { {.name=str_589, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_590, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_591, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_592, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, {.name=str_593, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_594, .typeId=nodeId_139, .valueRank=-1, .enumValue=5}, {.name=str_595, .typeId=nodeId_139, .valueRank=-1, .enumValue=6}, }; static const struct UA_StructDefinition variable_122_definition = {.size=7, .fields=variable_122_definition_fields}; static const struct UA_Attribute nodeId_385_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_385}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1065}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1065}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_122_definition}}, }; static const struct UA_Reference nodeId_385_refs[] = { {.nodeid=nodeId_325, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_278, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_386_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_386}}, {.id=UA_AttributeId_NodeClass, .data={.u32=4}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_752}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_752}}, {.id=UA_AttributeId_Executable, .data={.u8=1}}, {.id=UA_AttributeId_UserExecutable, .data={.u8=1}}, }; static const struct UA_Reference nodeId_386_refs[] = { {.nodeid=nodeId_223, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_310, .isForward=0}, }; static const char str_1066[] = "Root"; static const struct UA_Attribute nodeId_387_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_387}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1066}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1066}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_387_refs[] = { {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_348, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_493, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_327, .refid=nodeId_411, .isForward=1}, }; static const char str_1067[] = "VendorServerInfo"; static const struct UA_Attribute nodeId_388_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_388}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1067}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1067}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_388_refs[] = { {.nodeid=nodeId_177, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_389_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_389}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_808}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_808}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_389_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_399, .isForward=0}, }; static const char str_1068[] = "BrowseResponse"; static const struct UA_Field variable_123_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_579, .typeId=nodeId_82, .valueRank=1, .enumValue=-1}, {.name=str_580, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_123_definition = {.size=3, .fields=variable_123_definition_fields}; static const struct UA_Attribute nodeId_390_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_390}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1068}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1068}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_123_definition}}, }; static const struct UA_Reference nodeId_390_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_284, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_406, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_391_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_391}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1036}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1036}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_391_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_536, .refid=nodeId_310, .isForward=0}, }; static const char str_1069[] = "SignedSoftwareCertificate"; static const struct UA_Field variable_124_definition_fields[] = { {.name=str_859, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, {.name=str_1052, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_124_definition = {.size=2, .fields=variable_124_definition_fields}; static const struct UA_Attribute nodeId_392_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_392}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1069}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1069}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_124_definition}}, }; static const struct UA_Reference nodeId_392_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_416, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_421, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_393_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_393}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_609}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_609}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_393_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_36, .refid=nodeId_310, .isForward=0}, }; static const char str_1070[] = "BuildInfoType"; static const struct UA_Attribute nodeId_394_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_394}}, {.id=UA_AttributeId_NodeClass, .data={.u32=16}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1070}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1070}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_522}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_394_refs[] = { {.nodeid=nodeId_188, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_90, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_299, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_116, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_268, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_34, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_46, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_36, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_37, .refid=nodeId_324, .isForward=0}, {.nodeid=nodeId_156, .refid=nodeId_324, .isForward=0}, }; static const int32_t variable_125[] = { 0, }; static const struct UA_Variant variable_126_variant = {.dataType=UA_Type_Int32, .size=1, .data={.i32Arr=variable_125}}; static const struct UA_Attribute nodeId_395_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_395}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_749}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_749}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_126_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_505}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_395_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_527, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_396_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_396}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1036}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1036}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_396_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_397_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_397}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_397_refs[] = { {.nodeid=nodeId_423, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1071[] = "HasEventSource"; static const char str_1072[] = "EventSourceOf"; static const struct UA_Attribute nodeId_398_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_398}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1071}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1071}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_1072}}, }; static const struct UA_Reference nodeId_398_refs[] = { {.nodeid=nodeId_2, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_357, .refid=nodeId_334, .isForward=1}, }; static const char str_1073[] = "HasProperty"; static const char str_1074[] = "PropertyOf"; static const struct UA_Attribute nodeId_399_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_399}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1073}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1073}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_1074}}, }; static const struct UA_Reference nodeId_399_refs[] = { {.nodeid=nodeId_118, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_400_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_400}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_400_refs[] = { {.nodeid=nodeId_280, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1075[] = "ServerArray"; static const struct UA_Attribute nodeId_401_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_401}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1075}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1075}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_401_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_402_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_402}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_402_refs[] = { {.nodeid=nodeId_107, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_403_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_403}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_403_refs[] = { {.nodeid=nodeId_457, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1076[] = "ObjectTypeAttributes"; static const struct UA_Field variable_127_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_688, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_127_definition = {.size=6, .fields=variable_127_definition_fields}; static const struct UA_Attribute nodeId_404_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_404}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1076}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1076}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_127_definition}}, }; static const struct UA_Reference nodeId_404_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, }; static const char str_1077[] = "ServerStatusDataType"; static const struct UA_Field variable_128_definition_fields[] = { {.name=str_1036, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_714, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_700, .typeId=nodeId_365, .valueRank=-1, .enumValue=-1}, {.name=str_610, .typeId=nodeId_522, .valueRank=-1, .enumValue=-1}, {.name=str_696, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_672, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_128_definition = {.size=6, .fields=variable_128_definition_fields}; static const struct UA_Attribute nodeId_405_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_405}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1077}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1077}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_128_definition}}, }; static const struct UA_Reference nodeId_405_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_481, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_345, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_406_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_406}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_406_refs[] = { {.nodeid=nodeId_390, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_407_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_407}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_407_refs[] = { {.nodeid=nodeId_247, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_408_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_408}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_408_refs[] = { {.nodeid=nodeId_503, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1078[] = "DecimalString"; static const struct UA_Attribute nodeId_409_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_409}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1078}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1078}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_409_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_410_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_410}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1075}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1075}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_410_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_399, .isForward=0}, }; static const char str_1079[] = "Organizes"; static const char str_1080[] = "OrganizedBy"; static const struct UA_Attribute nodeId_411_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_411}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1079}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1079}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_1080}}, }; static const struct UA_Reference nodeId_411_refs[] = { {.nodeid=nodeId_2, .refid=nodeId_334, .isForward=0}, }; static const char str_1081[] = "DurationString"; static const struct UA_Attribute nodeId_412_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_412}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1081}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1081}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_412_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_413_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_413}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_413_refs[] = { {.nodeid=nodeId_74, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_414_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_414}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_414_refs[] = { {.nodeid=nodeId_496, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1082[] = "Enumeration"; static const struct UA_Attribute nodeId_415_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_415}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1082}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1082}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_415_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_9, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_530, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_124, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_132, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_168, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_475, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_485, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_505, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_419, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_537, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_200, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_365, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_523, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_416_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_416}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_416_refs[] = { {.nodeid=nodeId_392, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_417_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_417}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_417_refs[] = { {.nodeid=nodeId_262, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_418_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_418}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_819}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_819}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_266}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_418_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_419, .refid=nodeId_399, .isForward=0}, }; static const char str_1083[] = "NodeAttributesMask"; static const char str_1084[] = "All"; static const char str_1085[] = "BaseNode"; static const char str_1086[] = "Object"; static const char str_1087[] = "ObjectType"; static const char str_1088[] = "Variable"; static const char str_1089[] = "VariableType"; static const char str_1090[] = "Method"; static const char str_1091[] = "ReferenceType"; static const struct UA_Field variable_129_definition_fields[] = { {.name=str_675, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_716, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_717, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_659, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_718, .typeId=nodeId_139, .valueRank=-1, .enumValue=8}, {.name=str_719, .typeId=nodeId_139, .valueRank=-1, .enumValue=16}, {.name=str_685, .typeId=nodeId_139, .valueRank=-1, .enumValue=32}, {.name=str_660, .typeId=nodeId_139, .valueRank=-1, .enumValue=64}, {.name=str_720, .typeId=nodeId_139, .valueRank=-1, .enumValue=128}, {.name=str_721, .typeId=nodeId_139, .valueRank=-1, .enumValue=256}, {.name=str_722, .typeId=nodeId_139, .valueRank=-1, .enumValue=512}, {.name=str_690, .typeId=nodeId_139, .valueRank=-1, .enumValue=1024}, {.name=str_688, .typeId=nodeId_139, .valueRank=-1, .enumValue=2048}, {.name=str_723, .typeId=nodeId_139, .valueRank=-1, .enumValue=4096}, {.name=str_661, .typeId=nodeId_139, .valueRank=-1, .enumValue=8192}, {.name=str_658, .typeId=nodeId_139, .valueRank=-1, .enumValue=16384}, {.name=str_689, .typeId=nodeId_139, .valueRank=-1, .enumValue=32768}, {.name=str_724, .typeId=nodeId_139, .valueRank=-1, .enumValue=65536}, {.name=str_725, .typeId=nodeId_139, .valueRank=-1, .enumValue=131072}, {.name=str_687, .typeId=nodeId_139, .valueRank=-1, .enumValue=262144}, {.name=str_726, .typeId=nodeId_139, .valueRank=-1, .enumValue=524288}, {.name=str_686, .typeId=nodeId_139, .valueRank=-1, .enumValue=1048576}, {.name=str_756, .typeId=nodeId_538, .valueRank=-1, .enumValue=2097152}, {.name=str_728, .typeId=nodeId_139, .valueRank=-1, .enumValue=4194304}, {.name=str_729, .typeId=nodeId_139, .valueRank=-1, .enumValue=8388608}, {.name=str_730, .typeId=nodeId_139, .valueRank=-1, .enumValue=16777216}, {.name=str_1084, .typeId=nodeId_139, .valueRank=-1, .enumValue=33554431}, {.name=str_1085, .typeId=nodeId_139, .valueRank=-1, .enumValue=26501220}, {.name=str_1086, .typeId=nodeId_139, .valueRank=-1, .enumValue=26501348}, {.name=str_1087, .typeId=nodeId_139, .valueRank=-1, .enumValue=26503268}, {.name=str_1088, .typeId=nodeId_139, .valueRank=-1, .enumValue=26571383}, {.name=str_1089, .typeId=nodeId_139, .valueRank=-1, .enumValue=28600438}, {.name=str_1090, .typeId=nodeId_139, .valueRank=-1, .enumValue=26632548}, {.name=str_1091, .typeId=nodeId_139, .valueRank=-1, .enumValue=26537060}, {.name=str_619, .typeId=nodeId_139, .valueRank=-1, .enumValue=26501356}, }; static const struct UA_StructDefinition variable_129_definition = {.size=35, .fields=variable_129_definition_fields}; static const struct UA_Attribute nodeId_419_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_419}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1083}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1083}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_129_definition}}, }; static const struct UA_Reference nodeId_419_refs[] = { {.nodeid=nodeId_418, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_420_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_420}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_420_refs[] = { {.nodeid=nodeId_529, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_421_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_421}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_421_refs[] = { {.nodeid=nodeId_392, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_422_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_422}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_860}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_860}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_422_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_399, .isForward=0}, }; static const char str_1092[] = "ActivateSessionRequest"; static const char str_1093[] = "ClientSignature"; static const char str_1094[] = "ClientSoftwareCertificates"; static const char str_1095[] = "UserTokenSignature"; static const struct UA_Field variable_130_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_1093, .typeId=nodeId_370, .valueRank=-1, .enumValue=-1}, {.name=str_1094, .typeId=nodeId_392, .valueRank=1, .enumValue=-1}, {.name=str_737, .typeId=nodeId_159, .valueRank=1, .enumValue=-1}, {.name=str_993, .typeId=nodeId_16, .valueRank=-1, .enumValue=-1}, {.name=str_1095, .typeId=nodeId_370, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_130_definition = {.size=6, .fields=variable_130_definition_fields}; static const struct UA_Attribute nodeId_423_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_423}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1092}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1092}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_130_definition}}, }; static const struct UA_Reference nodeId_423_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_397, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_506, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_424_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_424}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_424_refs[] = { {.nodeid=nodeId_43, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1096[] = "AuthenticationToken"; static const char str_1097[] = "ReturnDiagnostics"; static const char str_1098[] = "AuditEntryId"; static const char str_1099[] = "TimeoutHint"; static const struct UA_Field variable_131_definition_fields[] = { {.name=str_1096, .typeId=nodeId_215, .valueRank=-1, .enumValue=-1}, {.name=str_625, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, {.name=str_626, .typeId=nodeId_71, .valueRank=-1, .enumValue=-1}, {.name=str_1097, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_1098, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_1099, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_630, .typeId=nodeId_16, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_131_definition = {.size=7, .fields=variable_131_definition_fields}; static const struct UA_Attribute nodeId_425_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_425}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_618}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_618}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_131_definition}}, }; static const struct UA_Reference nodeId_425_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_97, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_193, .refid=nodeId_95, .isForward=1}, }; static const char *variable_132[] = { str_1040, str_1041, str_1042, str_1043, str_1044, str_1045, str_1046, str_1047, }; static const struct UA_Variant variable_133_variant = {.dataType=UA_Type_LocalizedText, .size=8, .data={.strArr=variable_132}}; static const struct UA_Attribute nodeId_426_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_426}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_133_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_426_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_365, .refid=nodeId_399, .isForward=0}, }; static const char str_1100[] = "AddNodesResponse"; static const struct UA_Field variable_134_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_579, .typeId=nodeId_119, .valueRank=1, .enumValue=-1}, {.name=str_580, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_134_definition = {.size=3, .fields=variable_134_definition_fields}; static const struct UA_Attribute nodeId_427_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_427}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1100}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1100}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_134_definition}}, }; static const struct UA_Reference nodeId_427_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_158, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_276, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_428_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_428}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_428_refs[] = { {.nodeid=nodeId_482, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1101[] = "CreateSessionRequest"; static const char str_1102[] = "RequestedSessionTimeout"; static const struct UA_Field variable_135_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_938, .typeId=nodeId_237, .valueRank=-1, .enumValue=-1}, {.name=str_939, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_736, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_937, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_777, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, {.name=str_1033, .typeId=nodeId_226, .valueRank=-1, .enumValue=-1}, {.name=str_1102, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_941, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_135_definition = {.size=9, .fields=variable_135_definition_fields}; static const struct UA_Attribute nodeId_429_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_429}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1101}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1101}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_135_definition}}, }; static const struct UA_Reference nodeId_429_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_274, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_470, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_430_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_430}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_430_refs[] = { {.nodeid=nodeId_486, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1103[] = "CreateSessionResponse"; static const char str_1104[] = "RevisedSessionTimeout"; static const char str_1105[] = "ServerEndpoints"; static const char str_1106[] = "ServerSoftwareCertificates"; static const char str_1107[] = "ServerSignature"; static const char str_1108[] = "MaxRequestMessageSize"; static const struct UA_Field variable_136_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_936, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_1096, .typeId=nodeId_215, .valueRank=-1, .enumValue=-1}, {.name=str_1104, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_694, .typeId=nodeId_456, .valueRank=-1, .enumValue=-1}, {.name=str_900, .typeId=nodeId_226, .valueRank=-1, .enumValue=-1}, {.name=str_1105, .typeId=nodeId_262, .valueRank=1, .enumValue=-1}, {.name=str_1106, .typeId=nodeId_392, .valueRank=1, .enumValue=-1}, {.name=str_1107, .typeId=nodeId_370, .valueRank=-1, .enumValue=-1}, {.name=str_1108, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_136_definition = {.size=10, .fields=variable_136_definition_fields}; static const struct UA_Attribute nodeId_431_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_431}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1103}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1103}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_136_definition}}, }; static const struct UA_Reference nodeId_431_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_466, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_467, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_432_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_432}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_714}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_714}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_498}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_432_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_199, .refid=nodeId_310, .isForward=0}, }; static const char str_1109[] = "http://opcfoundation.org/UA/"; static const struct UA_Variant variable_137_variant = {.dataType=UA_Type_String, .size=0, .data={.str=str_1109}}; static const struct UA_Attribute nodeId_433_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_433}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_707}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_707}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_137_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_433_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_527, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_434_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_434}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_706}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_706}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_434_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_156, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_435_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_435}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_933}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_933}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_435_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_37, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_436_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_436}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_436_refs[] = { {.nodeid=nodeId_491, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1110[] = "FromState"; static const char str_1111[] = "ToTransition"; static const struct UA_Attribute nodeId_437_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_437}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1110}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1110}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_1111}}, }; static const struct UA_Reference nodeId_437_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_438_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_438}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_438_refs[] = { {.nodeid=nodeId_280, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1112[] = "TimeString"; static const struct UA_Attribute nodeId_439_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_439}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1112}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1112}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_439_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_440_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_440}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_440_refs[] = { {.nodeid=nodeId_141, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_441_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_441}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_845}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_845}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_241}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_441_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_442_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_442}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_749}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_749}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_505}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_442_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_399, .isForward=0}, }; static const char str_1113[] = "BrowsePath"; static const char str_1114[] = "StartingNode"; static const struct UA_Field variable_138_definition_fields[] = { {.name=str_1114, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_604, .typeId=nodeId_31, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_138_definition = {.size=2, .fields=variable_138_definition_fields}; static const struct UA_Attribute nodeId_443_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_443}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1113}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1113}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_138_definition}}, }; static const struct UA_Reference nodeId_443_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_40, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_196, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_444_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_444}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_742}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_742}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_444_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_445_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_445}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_445_refs[] = { {.nodeid=nodeId_539, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_446_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_446}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_446_refs[] = { {.nodeid=nodeId_323, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1115[] = "FieldMetaData"; static const char str_1116[] = "FieldFlags"; static const char str_1117[] = "DataSetFieldId"; static const char str_1118[] = "Properties"; static const struct UA_Field variable_139_definition_fields[] = { {.name=str_549, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_1116, .typeId=nodeId_489, .valueRank=-1, .enumValue=-1}, {.name=str_608, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, {.name=str_719, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_726, .typeId=nodeId_136, .valueRank=-1, .enumValue=-1}, {.name=str_717, .typeId=nodeId_49, .valueRank=1, .enumValue=-1}, {.name=str_636, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_1117, .typeId=nodeId_184, .valueRank=-1, .enumValue=-1}, {.name=str_1118, .typeId=nodeId_364, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_139_definition = {.size=10, .fields=variable_139_definition_fields}; static const struct UA_Attribute nodeId_447_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_447}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1115}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1115}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_139_definition}}, }; static const struct UA_Reference nodeId_447_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, }; static const char str_1119[] = "ViewAttributes"; static const struct UA_Field variable_140_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_718, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_720, .typeId=nodeId_278, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_140_definition = {.size=7, .fields=variable_140_definition_fields}; static const struct UA_Attribute nodeId_448_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_448}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1119}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1119}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_140_definition}}, }; static const struct UA_Reference nodeId_448_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, }; static const char str_1120[] = "DateString"; static const struct UA_Attribute nodeId_449_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_449}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1120}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1120}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_449_refs[] = { {.nodeid=nodeId_11, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_450_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_450}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_450_refs[] = { {.nodeid=nodeId_463, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_451_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_451}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_451_refs[] = { {.nodeid=nodeId_350, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_452_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_452}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_452_refs[] = { {.nodeid=nodeId_219, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_453_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_453}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_453_refs[] = { {.nodeid=nodeId_105, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1121[] = "EndpointUrlListDataType"; static const char str_1122[] = "EndpointUrlList"; static const struct UA_Field variable_141_definition_fields[] = { {.name=str_1122, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_141_definition = {.size=1, .fields=variable_141_definition_fields}; static const struct UA_Attribute nodeId_454_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_454}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1121}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1121}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_141_definition}}, }; static const struct UA_Reference nodeId_454_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_38, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_287, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_455_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_455}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_455_refs[] = { {.nodeid=nodeId_361, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1123[] = "ByteString"; static const struct UA_Attribute nodeId_456_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_456}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1123}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1123}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_456_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_226, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_331, .refid=nodeId_334, .isForward=1}, }; static const char str_1124[] = "AnonymousIdentityToken"; static const struct UA_Field variable_142_definition_fields[] = { {.name=str_613, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_142_definition = {.size=1, .fields=variable_142_definition_fields}; static const struct UA_Attribute nodeId_457_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_457}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1124}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1124}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_142_definition}}, }; static const struct UA_Reference nodeId_457_refs[] = { {.nodeid=nodeId_328, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_22, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_403, .refid=nodeId_95, .isForward=1}, }; static const char str_1125[] = "ReadResponse"; static const struct UA_Field variable_143_definition_fields[] = { {.name=str_578, .typeId=nodeId_47, .valueRank=-1, .enumValue=-1}, {.name=str_579, .typeId=nodeId_538, .valueRank=1, .enumValue=-1}, {.name=str_580, .typeId=nodeId_318, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_143_definition = {.size=3, .fields=variable_143_definition_fields}; static const struct UA_Attribute nodeId_458_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_458}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1125}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1125}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_143_definition}}, }; static const struct UA_Reference nodeId_458_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_4, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_170, .refid=nodeId_95, .isForward=1}, }; static const char *variable_144[] = { str_716, str_717, str_659, str_718, str_719, str_685, str_660, str_720, str_721, str_722, str_690, str_688, str_723, str_661, str_658, str_689, str_724, str_725, str_687, str_726, str_686, str_727, str_728, str_729, str_730, str_731, }; static const struct UA_Variant variable_145_variant = {.dataType=UA_Type_LocalizedText, .size=26, .data={.strArr=variable_144}}; static const struct UA_Attribute nodeId_459_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_459}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_670}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_670}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_145_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_459_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_103, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_460_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_460}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_460_refs[] = { {.nodeid=nodeId_144, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_461_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_461}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_461_refs[] = { {.nodeid=nodeId_33, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_462_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_462}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_462_refs[] = { {.nodeid=nodeId_220, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Field variable_146_definition_fields[] = { {.name=str_734, .typeId=nodeId_503, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_146_definition = {.size=1, .fields=variable_146_definition_fields}; static const struct UA_Attribute nodeId_463_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_463}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_791}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_791}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_146_definition}}, }; static const struct UA_Reference nodeId_463_refs[] = { {.nodeid=nodeId_339, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_450, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_494, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_464_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_464}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_464_refs[] = { {.nodeid=nodeId_263, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_465_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_465}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_905}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_905}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_465_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_466_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_466}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_466_refs[] = { {.nodeid=nodeId_431, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_467_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_467}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_467_refs[] = { {.nodeid=nodeId_431, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_468_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_468}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_468_refs[] = { {.nodeid=nodeId_12, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_469_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_469}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_933}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_933}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_469_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_36, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_470_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_470}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_470_refs[] = { {.nodeid=nodeId_429, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1126[] = "Int64"; static const struct UA_Attribute nodeId_471_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_471}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1126}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1126}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_471_refs[] = { {.nodeid=nodeId_120, .refid=nodeId_334, .isForward=0}, }; static const char str_1127[] = "MethodAttributes"; static const struct UA_Field variable_147_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_721, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_725, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_147_definition = {.size=7, .fields=variable_147_definition_fields}; static const struct UA_Attribute nodeId_472_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_472}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1127}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1127}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_147_definition}}, }; static const struct UA_Reference nodeId_472_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, }; static const char str_1128[] = "GetEndpointsRequest"; static const char str_1129[] = "ProfileUris"; static const struct UA_Field variable_148_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_736, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_737, .typeId=nodeId_159, .valueRank=1, .enumValue=-1}, {.name=str_1129, .typeId=nodeId_11, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_148_definition = {.size=4, .fields=variable_148_definition_fields}; static const struct UA_Attribute nodeId_473_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_473}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1128}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1128}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_148_definition}}, }; static const struct UA_Reference nodeId_473_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_15, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_221, .refid=nodeId_95, .isForward=1}, }; static const char str_1130[] = "ConfigurationVersionDataType"; static const char str_1131[] = "MajorVersion"; static const char str_1132[] = "MinorVersion"; static const struct UA_Field variable_149_definition_fields[] = { {.name=str_1131, .typeId=nodeId_329, .valueRank=-1, .enumValue=-1}, {.name=str_1132, .typeId=nodeId_329, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_149_definition = {.size=2, .fields=variable_149_definition_fields}; static const struct UA_Attribute nodeId_474_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_474}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1130}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1130}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_149_definition}}, }; static const struct UA_Reference nodeId_474_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, }; static const char str_1133[] = "MessageSecurityMode"; static const struct UA_Field variable_150_definition_fields[] = { {.name=str_556, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_675, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_676, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_677, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, }; static const struct UA_StructDefinition variable_150_definition = {.size=4, .fields=variable_150_definition_fields}; static const struct UA_Attribute nodeId_475_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_475}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1133}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1133}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_150_definition}}, }; static const struct UA_Reference nodeId_475_refs[] = { {.nodeid=nodeId_70, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_476_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_476}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_476_refs[] = { {.nodeid=nodeId_477, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_477_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_477}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_561}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_561}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, }; static const struct UA_Reference nodeId_477_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_526, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_476, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_478_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_478}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_933}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_933}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_478_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_156, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_479_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_479}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_479_refs[] = { {.nodeid=nodeId_82, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_480_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_480}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_808}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_808}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_283}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_480_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_481_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_481}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_481_refs[] = { {.nodeid=nodeId_405, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1134[] = "DoubleComplexNumberType"; static const char str_1135[] = "Real"; static const char str_1136[] = "Imaginary"; static const struct UA_Field variable_151_definition_fields[] = { {.name=str_1135, .typeId=nodeId_65, .valueRank=-1, .enumValue=-1}, {.name=str_1136, .typeId=nodeId_65, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_151_definition = {.size=2, .fields=variable_151_definition_fields}; static const struct UA_Attribute nodeId_482_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_482}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1134}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1134}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_151_definition}}, }; static const struct UA_Reference nodeId_482_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_428, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_225, .refid=nodeId_95, .isForward=1}, }; static const char str_1137[] = "ComplexNumberType"; static const struct UA_Field variable_152_definition_fields[] = { {.name=str_1135, .typeId=nodeId_20, .valueRank=-1, .enumValue=-1}, {.name=str_1136, .typeId=nodeId_20, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_152_definition = {.size=2, .fields=variable_152_definition_fields}; static const struct UA_Attribute nodeId_483_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_483}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1137}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1137}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_152_definition}}, }; static const struct UA_Reference nodeId_483_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_289, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_312, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_484_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_484}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_484_refs[] = { {.nodeid=nodeId_358, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Field variable_153_definition_fields[] = { {.name=str_553, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_910, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_911, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_912, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, }; static const struct UA_StructDefinition variable_153_definition = {.size=4, .fields=variable_153_definition_fields}; static const struct UA_Attribute nodeId_485_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_485}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_850}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_850}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_153_definition}}, }; static const struct UA_Reference nodeId_485_refs[] = { {.nodeid=nodeId_277, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const char str_1138[] = "BrowseDescription"; static const char str_1139[] = "BrowseDirection"; static const char str_1140[] = "NodeClassMask"; static const char str_1141[] = "ResultMask"; static const struct UA_Field variable_154_definition_fields[] = { {.name=str_658, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_1139, .typeId=nodeId_523, .valueRank=-1, .enumValue=-1}, {.name=str_644, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_646, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, {.name=str_1140, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_1141, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_154_definition = {.size=6, .fields=variable_154_definition_fields}; static const struct UA_Attribute nodeId_486_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_486}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1138}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1138}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_154_definition}}, }; static const struct UA_Reference nodeId_486_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_242, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_430, .refid=nodeId_95, .isForward=1}, }; static const char str_1142[] = "PermissionType"; static const struct UA_Field variable_155_definition_fields[] = { {.name=str_997, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_998, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_999, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_1000, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, {.name=str_1001, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_751, .typeId=nodeId_139, .valueRank=-1, .enumValue=5}, {.name=str_752, .typeId=nodeId_139, .valueRank=-1, .enumValue=6}, {.name=str_1002, .typeId=nodeId_139, .valueRank=-1, .enumValue=7}, {.name=str_1003, .typeId=nodeId_139, .valueRank=-1, .enumValue=8}, {.name=str_1004, .typeId=nodeId_139, .valueRank=-1, .enumValue=9}, {.name=str_1005, .typeId=nodeId_139, .valueRank=-1, .enumValue=10}, {.name=str_1006, .typeId=nodeId_139, .valueRank=-1, .enumValue=11}, {.name=str_1007, .typeId=nodeId_139, .valueRank=-1, .enumValue=12}, {.name=str_1008, .typeId=nodeId_139, .valueRank=-1, .enumValue=13}, {.name=str_1009, .typeId=nodeId_139, .valueRank=-1, .enumValue=14}, {.name=str_1010, .typeId=nodeId_139, .valueRank=-1, .enumValue=15}, {.name=str_1011, .typeId=nodeId_139, .valueRank=-1, .enumValue=16}, }; static const struct UA_StructDefinition variable_155_definition = {.size=17, .fields=variable_155_definition_fields}; static const struct UA_Attribute nodeId_487_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_487}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1142}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1142}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_155_definition}}, }; static const struct UA_Reference nodeId_487_refs[] = { {.nodeid=nodeId_336, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_49, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_488_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_488}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_740}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_740}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_212}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_488_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_367, .refid=nodeId_399, .isForward=0}, }; static const char str_1143[] = "DataSetFieldFlags"; static const struct UA_Field variable_156_definition_fields[] = { {.name=str_671, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, }; static const struct UA_StructDefinition variable_156_definition = {.size=1, .fields=variable_156_definition_fields}; static const struct UA_Attribute nodeId_489_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_489}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1143}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1143}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_156_definition}}, }; static const struct UA_Reference nodeId_489_refs[] = { {.nodeid=nodeId_66, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_283, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_490_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_490}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_490_refs[] = { {.nodeid=nodeId_60, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1144[] = "TimeZoneDataType"; static const char str_1145[] = "Offset"; static const char str_1146[] = "DaylightSavingInOffset"; static const struct UA_Field variable_157_definition_fields[] = { {.name=str_1145, .typeId=nodeId_245, .valueRank=-1, .enumValue=-1}, {.name=str_1146, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_157_definition = {.size=2, .fields=variable_157_definition_fields}; static const struct UA_Attribute nodeId_491_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_491}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1144}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1144}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_157_definition}}, }; static const struct UA_Reference nodeId_491_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_436, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_100, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_492_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_492}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_492_refs[] = { {.nodeid=nodeId_539, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1147[] = "Types"; static const struct UA_Attribute nodeId_493_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_493}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1147}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1147}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_493_refs[] = { {.nodeid=nodeId_387, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_13, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_114, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_528, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_380, .refid=nodeId_411, .isForward=1}, }; static const struct UA_Attribute nodeId_494_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_494}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_494_refs[] = { {.nodeid=nodeId_463, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_495_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_495}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_706}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_706}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_495_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_37, .refid=nodeId_310, .isForward=0}, }; static const char str_1148[] = "WriteRequest"; static const char str_1149[] = "NodesToWrite"; static const struct UA_Field variable_158_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_1149, .typeId=nodeId_296, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_158_definition = {.size=2, .fields=variable_158_definition_fields}; static const struct UA_Attribute nodeId_496_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_496}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1148}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1148}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_158_definition}}, }; static const struct UA_Reference nodeId_496_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_414, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_531, .refid=nodeId_95, .isForward=1}, }; static const char str_1150[] = "DataTypeAttributes"; static const struct UA_Field variable_159_definition_fields[] = { {.name=str_684, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_686, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_687, .typeId=nodeId_49, .valueRank=-1, .enumValue=-1}, {.name=str_688, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_159_definition = {.size=6, .fields=variable_159_definition_fields}; static const struct UA_Attribute nodeId_497_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_497}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1150}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1150}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_159_definition}}, }; static const struct UA_Reference nodeId_497_refs[] = { {.nodeid=nodeId_272, .refid=nodeId_334, .isForward=0}, }; static const char str_1151[] = "UtcTime"; static const struct UA_Attribute nodeId_498_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_498}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1151}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1151}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_498_refs[] = { {.nodeid=nodeId_24, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_499_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_499}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_499_refs[] = { {.nodeid=nodeId_213, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_500_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_500}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_637}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_637}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_49}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_500_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_28, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_399, .isForward=0}, }; static const char str_1152[] = "FileType"; static const struct UA_Attribute nodeId_501_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_501}}, {.id=UA_AttributeId_NodeClass, .data={.u32=8}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1152}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1152}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_501_refs[] = { {.nodeid=nodeId_516, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_269, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_209, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_376, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_206, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_500, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_369, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_367, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_155, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_244, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_386, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_379, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_373, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_143, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_502_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_502}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_502_refs[] = { {.nodeid=nodeId_140, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1153[] = "EnumField"; static const struct UA_Field variable_160_definition_fields[] = { {.name=str_756, .typeId=nodeId_471, .valueRank=-1, .enumValue=-1}, {.name=str_660, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_685, .typeId=nodeId_99, .valueRank=-1, .enumValue=-1}, {.name=str_549, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_160_definition = {.size=4, .fields=variable_160_definition_fields}; static const struct UA_Attribute nodeId_503_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_503}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1153}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1153}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_160_definition}}, }; static const struct UA_Reference nodeId_503_refs[] = { {.nodeid=nodeId_266, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_5, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_408, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_504_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_504}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_504_refs[] = { {.nodeid=nodeId_77, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1154[] = "IdType"; static const struct UA_Field variable_161_definition_fields[] = { {.name=str_581, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_569, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_582, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_583, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, }; static const struct UA_StructDefinition variable_161_definition = {.size=4, .fields=variable_161_definition_fields}; static const struct UA_Attribute nodeId_505_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_505}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1154}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1154}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_161_definition}}, }; static const struct UA_Reference nodeId_505_refs[] = { {.nodeid=nodeId_19, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_506_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_506}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_506_refs[] = { {.nodeid=nodeId_423, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_507_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_507}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_507_refs[] = { {.nodeid=nodeId_535, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1155[] = "HasEffect"; static const char str_1156[] = "MayBeEffectedBy"; static const struct UA_Attribute nodeId_508_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_508}}, {.id=UA_AttributeId_NodeClass, .data={.u32=32}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1155}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1155}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_Symmetric, .data={.u8=0}}, {.id=UA_AttributeId_InverseName, .data={.str=str_1156}}, }; static const struct UA_Reference nodeId_508_refs[] = { {.nodeid=nodeId_41, .refid=nodeId_334, .isForward=0}, }; static const char str_1157[] = "BaseVariableType"; static const struct UA_Attribute nodeId_509_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_509}}, {.id=UA_AttributeId_NodeClass, .data={.u32=16}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1157}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1157}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=1}}, {.id=UA_AttributeId_ValueRank, .data={.u32=-2}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_509_refs[] = { {.nodeid=nodeId_13, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_46, .refid=nodeId_334, .isForward=1}, {.nodeid=nodeId_104, .refid=nodeId_334, .isForward=1}, }; static const struct UA_Attribute nodeId_510_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_510}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_557}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_557}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_392}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_510_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_270, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_511_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_511}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1067}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1067}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_511_refs[] = { {.nodeid=nodeId_177, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_512_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_512}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_512_refs[] = { {.nodeid=nodeId_519, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_513_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_513}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_816}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_816}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_148}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_513_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_102, .refid=nodeId_399, .isForward=0}, }; static const char str_1158[] = "QualifiedName"; static const struct UA_Attribute nodeId_514_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_514}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1158}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1158}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_514_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_515_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_515}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_515_refs[] = { {.nodeid=nodeId_10, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1159[] = "Size"; static const struct UA_Attribute nodeId_516_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_516}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1159}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1159}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_56}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_516_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_501, .refid=nodeId_399, .isForward=0}, }; static const char *variable_162[] = { str_794, str_614, str_795, str_796, }; static const struct UA_Variant variable_163_variant = {.dataType=UA_Type_LocalizedText, .size=4, .data={.strArr=variable_162}}; static const struct UA_Attribute nodeId_517_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_517}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_551}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_551}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_163_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_99}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_517_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_168, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_518_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_518}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_807}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_807}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_241}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_518_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_112, .refid=nodeId_399, .isForward=0}, }; static const char str_1160[] = "TranslateBrowsePathsToNodeIdsRequest"; static const char str_1161[] = "BrowsePaths"; static const struct UA_Field variable_164_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_1161, .typeId=nodeId_443, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_164_definition = {.size=2, .fields=variable_164_definition_fields}; static const struct UA_Attribute nodeId_519_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_519}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1160}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1160}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_164_definition}}, }; static const struct UA_Reference nodeId_519_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_128, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_512, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_520_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_520}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_585}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_585}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_520_refs[] = { {.nodeid=nodeId_46, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_37, .refid=nodeId_310, .isForward=0}, }; static const struct UA_Attribute nodeId_521_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_521}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_521_refs[] = { {.nodeid=nodeId_140, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Field variable_165_definition_fields[] = { {.name=str_801, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_705, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_933, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_585, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_706, .typeId=nodeId_11, .valueRank=-1, .enumValue=-1}, {.name=str_609, .typeId=nodeId_498, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_165_definition = {.size=6, .fields=variable_165_definition_fields}; static const struct UA_Attribute nodeId_522_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_522}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_610}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_610}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_165_definition}}, }; static const struct UA_Reference nodeId_522_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_3, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_201, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Field variable_166_definition_fields[] = { {.name=str_832, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_833, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_554, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_556, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, }; static const struct UA_StructDefinition variable_166_definition = {.size=4, .fields=variable_166_definition_fields}; static const struct UA_Attribute nodeId_523_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_523}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1139}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1139}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_166_definition}}, }; static const struct UA_Reference nodeId_523_refs[] = { {.nodeid=nodeId_217, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_524_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_524}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_524_refs[] = { {.nodeid=nodeId_47, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_525_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_525}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_525_refs[] = { {.nodeid=nodeId_18, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_526_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_526}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_526_refs[] = { {.nodeid=nodeId_477, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const struct UA_Attribute nodeId_527_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_527}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1109}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1109}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_527_refs[] = { {.nodeid=nodeId_433, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_532, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_23, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_335, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_395, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_249, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_281, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_25, .refid=nodeId_310, .isForward=0}, {.nodeid=nodeId_1, .refid=nodeId_324, .isForward=1}, }; static const char str_1162[] = "ObjectTypes"; static const struct UA_Attribute nodeId_528_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_528}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1162}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1162}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_528_refs[] = { {.nodeid=nodeId_493, .refid=nodeId_411, .isForward=0}, {.nodeid=nodeId_143, .refid=nodeId_411, .isForward=1}, {.nodeid=nodeId_78, .refid=nodeId_324, .isForward=1}, }; static const char str_1163[] = "CloseSessionRequest"; static const char str_1164[] = "DeleteSubscriptions"; static const struct UA_Field variable_167_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_1164, .typeId=nodeId_241, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_167_definition = {.size=2, .fields=variable_167_definition_fields}; static const struct UA_Attribute nodeId_529_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_529}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1163}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1163}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_167_definition}}, }; static const struct UA_Reference nodeId_529_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_353, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_420, .refid=nodeId_95, .isForward=1}, }; static const char str_1165[] = "Unspecified"; static const struct UA_Field variable_168_definition_fields[] = { {.name=str_1165, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_1086, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_1088, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_1090, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, {.name=str_1087, .typeId=nodeId_139, .valueRank=-1, .enumValue=8}, {.name=str_1089, .typeId=nodeId_139, .valueRank=-1, .enumValue=16}, {.name=str_1091, .typeId=nodeId_139, .valueRank=-1, .enumValue=32}, {.name=str_719, .typeId=nodeId_139, .valueRank=-1, .enumValue=64}, {.name=str_619, .typeId=nodeId_139, .valueRank=-1, .enumValue=128}, }; static const struct UA_StructDefinition variable_168_definition = {.size=9, .fields=variable_168_definition_fields}; static const struct UA_Attribute nodeId_530_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_530}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_661}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_661}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_168_definition}}, }; static const struct UA_Reference nodeId_530_refs[] = { {.nodeid=nodeId_258, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const struct UA_Attribute nodeId_531_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_531}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_542}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_542}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_531_refs[] = { {.nodeid=nodeId_496, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1166[] = "1.05.01"; static const struct UA_Variant variable_169_variant = {.dataType=UA_Type_String, .size=0, .data={.str=str_1166}}; static const struct UA_Attribute nodeId_532_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_532}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_576}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_576}}, {.id=UA_AttributeId_Value, .data={.vPtr=&variable_169_variant}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_11}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_532_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_527, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_533_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_533}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_819}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_819}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_266}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_533_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_124, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Attribute nodeId_534_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_534}}, {.id=UA_AttributeId_NodeClass, .data={.u32=1}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_546}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_546}}, {.id=UA_AttributeId_EventNotifier, .data={.u32=0}}, }; static const struct UA_Reference nodeId_534_refs[] = { {.nodeid=nodeId_18, .refid=nodeId_95, .isForward=0}, {.nodeid=nodeId_127, .refid=nodeId_324, .isForward=1}, }; static const char str_1167[] = "AddNodesItem"; static const char str_1168[] = "ParentNodeId"; static const char str_1169[] = "RequestedNewNodeId"; static const struct UA_Field variable_170_definition_fields[] = { {.name=str_1168, .typeId=nodeId_164, .valueRank=-1, .enumValue=-1}, {.name=str_644, .typeId=nodeId_322, .valueRank=-1, .enumValue=-1}, {.name=str_1169, .typeId=nodeId_164, .valueRank=-1, .enumValue=-1}, {.name=str_659, .typeId=nodeId_514, .valueRank=-1, .enumValue=-1}, {.name=str_661, .typeId=nodeId_530, .valueRank=-1, .enumValue=-1}, {.name=str_909, .typeId=nodeId_16, .valueRank=-1, .enumValue=-1}, {.name=str_662, .typeId=nodeId_164, .valueRank=-1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_170_definition = {.size=7, .fields=variable_170_definition_fields}; static const struct UA_Attribute nodeId_535_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_535}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1167}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1167}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_170_definition}}, }; static const struct UA_Reference nodeId_535_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_178, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_507, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_536_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_536}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_812}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_812}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_405}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_MinimumSamplingInterval, .data={.d=1000}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_536_refs[] = { {.nodeid=nodeId_391, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_101, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_315, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_156, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_252, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_67, .refid=nodeId_310, .isForward=1}, {.nodeid=nodeId_198, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_349, .refid=nodeId_310, .isForward=0}, }; static const char str_1170[] = "TimestampsToReturn"; static const struct UA_Field variable_171_definition_fields[] = { {.name=str_552, .typeId=nodeId_139, .valueRank=-1, .enumValue=0}, {.name=str_553, .typeId=nodeId_139, .valueRank=-1, .enumValue=1}, {.name=str_554, .typeId=nodeId_139, .valueRank=-1, .enumValue=2}, {.name=str_555, .typeId=nodeId_139, .valueRank=-1, .enumValue=3}, {.name=str_556, .typeId=nodeId_139, .valueRank=-1, .enumValue=4}, }; static const struct UA_StructDefinition variable_171_definition = {.size=5, .fields=variable_171_definition_fields}; static const struct UA_Attribute nodeId_537_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_537}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1170}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1170}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_171_definition}}, }; static const struct UA_Reference nodeId_537_refs[] = { {.nodeid=nodeId_7, .refid=nodeId_399, .isForward=1}, {.nodeid=nodeId_415, .refid=nodeId_334, .isForward=0}, }; static const char str_1171[] = "DataValue"; static const struct UA_Attribute nodeId_538_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_538}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1171}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1171}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, }; static const struct UA_Reference nodeId_538_refs[] = { {.nodeid=nodeId_139, .refid=nodeId_334, .isForward=0}, }; static const char str_1172[] = "ReadRequest"; static const char str_1173[] = "MaxAge"; static const char str_1174[] = "NodesToRead"; static const struct UA_Field variable_172_definition_fields[] = { {.name=str_618, .typeId=nodeId_425, .valueRank=-1, .enumValue=-1}, {.name=str_1173, .typeId=nodeId_148, .valueRank=-1, .enumValue=-1}, {.name=str_1170, .typeId=nodeId_537, .valueRank=-1, .enumValue=-1}, {.name=str_1174, .typeId=nodeId_309, .valueRank=1, .enumValue=-1}, }; static const struct UA_StructDefinition variable_172_definition = {.size=4, .fields=variable_172_definition_fields}; static const struct UA_Attribute nodeId_539_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_539}}, {.id=UA_AttributeId_NodeClass, .data={.u32=64}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_1172}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_1172}}, {.id=UA_AttributeId_IsAbstract, .data={.u8=0}}, {.id=UA_AttributeId_DataTypeDefinition, .data={.definitionPtr=&variable_172_definition}}, }; static const struct UA_Reference nodeId_539_refs[] = { {.nodeid=nodeId_16, .refid=nodeId_334, .isForward=0}, {.nodeid=nodeId_445, .refid=nodeId_95, .isForward=1}, {.nodeid=nodeId_492, .refid=nodeId_95, .isForward=1}, }; static const struct UA_Attribute nodeId_540_attrs[] = { {.id=UA_AttributeId_NodeId, .data={.str=nodeId_540}}, {.id=UA_AttributeId_NodeClass, .data={.u32=2}}, {.id=UA_AttributeId_BrowseName, .data={.str=str_798}}, {.id=UA_AttributeId_DisplayName, .data={.str=str_798}}, {.id=UA_AttributeId_DataType, .data={.str=nodeId_129}}, {.id=UA_AttributeId_ValueRank, .data={.u32=1}}, {.id=UA_AttributeId_AccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_UserAccessLevel, .data={.u32=0}}, {.id=UA_AttributeId_Historizing, .data={.u8=0}}, }; static const struct UA_Reference nodeId_540_refs[] = { {.nodeid=nodeId_104, .refid=nodeId_324, .isForward=1}, {.nodeid=nodeId_341, .refid=nodeId_153, .isForward=1}, {.nodeid=nodeId_1, .refid=nodeId_399, .isForward=0}, }; static const struct UA_Node nodes[] = { {.attrsSize=5, .refsSize=1, .attrs=nodeId_241_attrs, .refs=nodeId_241_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_241, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_20_attrs, .refs=nodeId_20_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_20, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_463_attrs, .refs=nodeId_463_refs, .binaryId=nodeId_494, .jsonId=nodeId_450, .baseId=nodeId_16, .dataTypeId=nodeId_463}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_211_attrs, .refs=nodeId_211_refs, .binaryId=nodeId_91, .jsonId=nodeId_264, .baseId=nodeId_16, .dataTypeId=nodeId_211}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_503_attrs, .refs=nodeId_503_refs, .binaryId=nodeId_408, .jsonId=nodeId_5, .baseId=nodeId_16, .dataTypeId=nodeId_503}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_65_attrs, .refs=nodeId_65_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_65, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_381_attrs, .refs=nodeId_381_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=14, .attrs=nodeId_501_attrs, .refs=nodeId_501_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_516_attrs, .refs=nodeId_516_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_376_attrs, .refs=nodeId_376_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=4, .attrs=nodeId_367_attrs, .refs=nodeId_367_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_488_attrs, .refs=nodeId_488_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_240_attrs, .refs=nodeId_240_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_155_attrs, .refs=nodeId_155_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_290_attrs, .refs=nodeId_290_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=4, .attrs=nodeId_244_attrs, .refs=nodeId_244_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_346_attrs, .refs=nodeId_346_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_115_attrs, .refs=nodeId_115_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_386_attrs, .refs=nodeId_386_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_223_attrs, .refs=nodeId_223_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=4, .attrs=nodeId_379_attrs, .refs=nodeId_379_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_113_attrs, .refs=nodeId_113_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_147_attrs, .refs=nodeId_147_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_373_attrs, .refs=nodeId_373_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_351_attrs, .refs=nodeId_351_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=10, .attrs=nodeId_1_attrs, .refs=nodeId_1_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_152_attrs, .refs=nodeId_152_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_279_attrs, .refs=nodeId_279_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_123_attrs, .refs=nodeId_123_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_441_attrs, .refs=nodeId_441_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_442_attrs, .refs=nodeId_442_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_540_attrs, .refs=nodeId_540_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_422_attrs, .refs=nodeId_422_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_307_attrs, .refs=nodeId_307_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=10, .attrs=nodeId_96_attrs, .refs=nodeId_96_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_93_attrs, .refs=nodeId_93_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_14_attrs, .refs=nodeId_14_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_383_attrs, .refs=nodeId_383_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_235_attrs, .refs=nodeId_235_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_121_attrs, .refs=nodeId_121_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_173_attrs, .refs=nodeId_173_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_248_attrs, .refs=nodeId_248_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_160_attrs, .refs=nodeId_160_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_87_attrs, .refs=nodeId_87_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_25_attrs, .refs=nodeId_25_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_48_attrs, .refs=nodeId_48_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_56, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_258_attrs, .refs=nodeId_258_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_418_attrs, .refs=nodeId_418_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_124_attrs, .refs=nodeId_124_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_533_attrs, .refs=nodeId_533_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_454_attrs, .refs=nodeId_454_refs, .binaryId=nodeId_38, .jsonId=nodeId_287, .baseId=nodeId_16, .dataTypeId=nodeId_454}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_38_attrs, .refs=nodeId_38_refs, .binaryId=nodeId_38, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_454}, {.attrsSize=5, .refsSize=8, .attrs=nodeId_11_attrs, .refs=nodeId_11_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_132_attrs, .refs=nodeId_132_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_313_attrs, .refs=nodeId_313_refs, .binaryId=nodeId_313, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_339}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_208_attrs, .refs=nodeId_208_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_483_attrs, .refs=nodeId_483_refs, .binaryId=nodeId_289, .jsonId=nodeId_312, .baseId=nodeId_16, .dataTypeId=nodeId_483}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_482_attrs, .refs=nodeId_482_refs, .binaryId=nodeId_225, .jsonId=nodeId_428, .baseId=nodeId_16, .dataTypeId=nodeId_482}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_289_attrs, .refs=nodeId_289_refs, .binaryId=nodeId_289, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_483}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_225_attrs, .refs=nodeId_225_refs, .binaryId=nodeId_225, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_482}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_275_attrs, .refs=nodeId_275_refs, .binaryId=nodeId_275, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_105}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_494_attrs, .refs=nodeId_494_refs, .binaryId=nodeId_494, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_463}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_382_attrs, .refs=nodeId_382_refs, .binaryId=nodeId_382, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_213}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_291_attrs, .refs=nodeId_291_refs, .binaryId=nodeId_291, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_6}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_269_attrs, .refs=nodeId_269_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_209_attrs, .refs=nodeId_209_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_150_attrs, .refs=nodeId_150_refs, .binaryId=nodeId_150, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_161}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_477_attrs, .refs=nodeId_477_refs, .binaryId=nodeId_476, .jsonId=nodeId_526, .baseId=nodeId_16, .dataTypeId=nodeId_477}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_476_attrs, .refs=nodeId_476_refs, .binaryId=nodeId_476, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_477}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_285_attrs, .refs=nodeId_285_refs, .binaryId=nodeId_285, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_374}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_45_attrs, .refs=nodeId_45_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_409_attrs, .refs=nodeId_409_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_412_attrs, .refs=nodeId_412_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_439_attrs, .refs=nodeId_439_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_449_attrs, .refs=nodeId_449_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_24_attrs, .refs=nodeId_24_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_24, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_206_attrs, .refs=nodeId_206_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_184_attrs, .refs=nodeId_184_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_184, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_320_attrs, .refs=nodeId_320_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_447_attrs, .refs=nodeId_447_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=6, .attrs=nodeId_213_attrs, .refs=nodeId_213_refs, .binaryId=nodeId_382, .jsonId=nodeId_499, .baseId=nodeId_16, .dataTypeId=nodeId_213}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_332_attrs, .refs=nodeId_332_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_364_attrs, .refs=nodeId_364_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_474_attrs, .refs=nodeId_474_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_91_attrs, .refs=nodeId_91_refs, .binaryId=nodeId_91, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_211}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_408_attrs, .refs=nodeId_408_refs, .binaryId=nodeId_408, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_503}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_456_attrs, .refs=nodeId_456_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_456, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_33_attrs, .refs=nodeId_33_refs, .binaryId=nodeId_461, .jsonId=nodeId_32, .baseId=nodeId_16, .dataTypeId=nodeId_33}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_336_attrs, .refs=nodeId_336_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_385_attrs, .refs=nodeId_385_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_278, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_325_attrs, .refs=nodeId_325_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_187_attrs, .refs=nodeId_187_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_459_attrs, .refs=nodeId_459_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_499_attrs, .refs=nodeId_499_refs, .binaryId=NULL, .jsonId=nodeId_499, .baseId=nodeId_16, .dataTypeId=nodeId_213}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_162_attrs, .refs=nodeId_162_refs, .binaryId=NULL, .jsonId=nodeId_162, .baseId=nodeId_16, .dataTypeId=nodeId_6}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_106_attrs, .refs=nodeId_106_refs, .binaryId=NULL, .jsonId=nodeId_106, .baseId=nodeId_16, .dataTypeId=nodeId_161}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_216_attrs, .refs=nodeId_216_refs, .binaryId=NULL, .jsonId=nodeId_216, .baseId=nodeId_16, .dataTypeId=nodeId_374}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_171_attrs, .refs=nodeId_171_refs, .binaryId=NULL, .jsonId=nodeId_171, .baseId=nodeId_16, .dataTypeId=nodeId_339}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_264_attrs, .refs=nodeId_264_refs, .binaryId=NULL, .jsonId=nodeId_264, .baseId=nodeId_16, .dataTypeId=nodeId_211}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_453_attrs, .refs=nodeId_453_refs, .binaryId=NULL, .jsonId=nodeId_453, .baseId=nodeId_16, .dataTypeId=nodeId_105}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_450_attrs, .refs=nodeId_450_refs, .binaryId=NULL, .jsonId=nodeId_450, .baseId=nodeId_16, .dataTypeId=nodeId_463}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_305_attrs, .refs=nodeId_305_refs, .binaryId=NULL, .jsonId=nodeId_305, .baseId=nodeId_16, .dataTypeId=nodeId_212}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_35_attrs, .refs=nodeId_35_refs, .binaryId=NULL, .jsonId=nodeId_35, .baseId=nodeId_16, .dataTypeId=nodeId_266}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_5_attrs, .refs=nodeId_5_refs, .binaryId=NULL, .jsonId=nodeId_5, .baseId=nodeId_16, .dataTypeId=nodeId_503}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_526_attrs, .refs=nodeId_526_refs, .binaryId=NULL, .jsonId=nodeId_526, .baseId=nodeId_16, .dataTypeId=nodeId_477}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_436_attrs, .refs=nodeId_436_refs, .binaryId=NULL, .jsonId=nodeId_436, .baseId=nodeId_16, .dataTypeId=nodeId_491}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_50_attrs, .refs=nodeId_50_refs, .binaryId=NULL, .jsonId=nodeId_50, .baseId=nodeId_16, .dataTypeId=nodeId_237}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_97_attrs, .refs=nodeId_97_refs, .binaryId=NULL, .jsonId=nodeId_97, .baseId=nodeId_16, .dataTypeId=nodeId_425}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_524_attrs, .refs=nodeId_524_refs, .binaryId=NULL, .jsonId=nodeId_524, .baseId=nodeId_16, .dataTypeId=nodeId_47}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_303_attrs, .refs=nodeId_303_refs, .binaryId=NULL, .jsonId=nodeId_303, .baseId=nodeId_16, .dataTypeId=nodeId_190}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_402_attrs, .refs=nodeId_402_refs, .binaryId=NULL, .jsonId=nodeId_402, .baseId=nodeId_16, .dataTypeId=nodeId_107}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_314_attrs, .refs=nodeId_314_refs, .binaryId=NULL, .jsonId=nodeId_314, .baseId=nodeId_16, .dataTypeId=nodeId_311}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_440_attrs, .refs=nodeId_440_refs, .binaryId=NULL, .jsonId=nodeId_440, .baseId=nodeId_16, .dataTypeId=nodeId_141}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_304_attrs, .refs=nodeId_304_refs, .binaryId=NULL, .jsonId=nodeId_304, .baseId=nodeId_16, .dataTypeId=nodeId_262}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_15_attrs, .refs=nodeId_15_refs, .binaryId=NULL, .jsonId=nodeId_15, .baseId=nodeId_16, .dataTypeId=nodeId_473}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_317_attrs, .refs=nodeId_317_refs, .binaryId=NULL, .jsonId=nodeId_317, .baseId=nodeId_16, .dataTypeId=nodeId_340}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_110_attrs, .refs=nodeId_110_refs, .binaryId=NULL, .jsonId=nodeId_110, .baseId=nodeId_16, .dataTypeId=nodeId_219}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_157_attrs, .refs=nodeId_157_refs, .binaryId=NULL, .jsonId=nodeId_157, .baseId=nodeId_16, .dataTypeId=nodeId_144}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_504_attrs, .refs=nodeId_504_refs, .binaryId=NULL, .jsonId=nodeId_504, .baseId=nodeId_16, .dataTypeId=nodeId_77}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_451_attrs, .refs=nodeId_451_refs, .binaryId=NULL, .jsonId=nodeId_451, .baseId=nodeId_16, .dataTypeId=nodeId_350}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_416_attrs, .refs=nodeId_416_refs, .binaryId=NULL, .jsonId=nodeId_416, .baseId=nodeId_16, .dataTypeId=nodeId_392}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_167_attrs, .refs=nodeId_167_refs, .binaryId=NULL, .jsonId=nodeId_167, .baseId=nodeId_16, .dataTypeId=nodeId_370}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_274_attrs, .refs=nodeId_274_refs, .binaryId=NULL, .jsonId=nodeId_274, .baseId=nodeId_16, .dataTypeId=nodeId_429}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_466_attrs, .refs=nodeId_466_refs, .binaryId=NULL, .jsonId=nodeId_466, .baseId=nodeId_16, .dataTypeId=nodeId_431}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_243_attrs, .refs=nodeId_243_refs, .binaryId=NULL, .jsonId=nodeId_243, .baseId=nodeId_16, .dataTypeId=nodeId_328}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_403_attrs, .refs=nodeId_403_refs, .binaryId=NULL, .jsonId=nodeId_403, .baseId=nodeId_16, .dataTypeId=nodeId_457}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_231_attrs, .refs=nodeId_231_refs, .binaryId=NULL, .jsonId=nodeId_231, .baseId=nodeId_16, .dataTypeId=nodeId_42}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_407_attrs, .refs=nodeId_407_refs, .binaryId=NULL, .jsonId=nodeId_407, .baseId=nodeId_16, .dataTypeId=nodeId_247}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_261_attrs, .refs=nodeId_261_refs, .binaryId=NULL, .jsonId=nodeId_261, .baseId=nodeId_16, .dataTypeId=nodeId_197}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_397_attrs, .refs=nodeId_397_refs, .binaryId=NULL, .jsonId=nodeId_397, .baseId=nodeId_16, .dataTypeId=nodeId_423}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_165_attrs, .refs=nodeId_165_refs, .binaryId=NULL, .jsonId=nodeId_165, .baseId=nodeId_16, .dataTypeId=nodeId_263}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_420_attrs, .refs=nodeId_420_refs, .binaryId=NULL, .jsonId=nodeId_420, .baseId=nodeId_16, .dataTypeId=nodeId_529}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_89_attrs, .refs=nodeId_89_refs, .binaryId=NULL, .jsonId=nodeId_89, .baseId=nodeId_16, .dataTypeId=nodeId_62}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_205_attrs, .refs=nodeId_205_refs, .binaryId=NULL, .jsonId=nodeId_205, .baseId=nodeId_16, .dataTypeId=nodeId_272}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_52_attrs, .refs=nodeId_52_refs, .binaryId=NULL, .jsonId=nodeId_52, .baseId=nodeId_16, .dataTypeId=nodeId_236}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_319_attrs, .refs=nodeId_319_refs, .binaryId=NULL, .jsonId=nodeId_319, .baseId=nodeId_16, .dataTypeId=nodeId_238}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_178_attrs, .refs=nodeId_178_refs, .binaryId=NULL, .jsonId=nodeId_178, .baseId=nodeId_16, .dataTypeId=nodeId_535}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_138_attrs, .refs=nodeId_138_refs, .binaryId=NULL, .jsonId=nodeId_138, .baseId=nodeId_16, .dataTypeId=nodeId_362}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_276_attrs, .refs=nodeId_276_refs, .binaryId=NULL, .jsonId=nodeId_276, .baseId=nodeId_16, .dataTypeId=nodeId_427}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_490_attrs, .refs=nodeId_490_refs, .binaryId=NULL, .jsonId=nodeId_490, .baseId=nodeId_16, .dataTypeId=nodeId_60}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_306_attrs, .refs=nodeId_306_refs, .binaryId=NULL, .jsonId=nodeId_306, .baseId=nodeId_16, .dataTypeId=nodeId_293}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_430_attrs, .refs=nodeId_430_refs, .binaryId=NULL, .jsonId=nodeId_430, .baseId=nodeId_16, .dataTypeId=nodeId_486}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_108_attrs, .refs=nodeId_108_refs, .binaryId=NULL, .jsonId=nodeId_108, .baseId=nodeId_16, .dataTypeId=nodeId_59}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_479_attrs, .refs=nodeId_479_refs, .binaryId=NULL, .jsonId=nodeId_479, .baseId=nodeId_16, .dataTypeId=nodeId_82}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_424_attrs, .refs=nodeId_424_refs, .binaryId=NULL, .jsonId=nodeId_424, .baseId=nodeId_16, .dataTypeId=nodeId_43}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_406_attrs, .refs=nodeId_406_refs, .binaryId=NULL, .jsonId=nodeId_406, .baseId=nodeId_16, .dataTypeId=nodeId_390}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_175_attrs, .refs=nodeId_175_refs, .binaryId=NULL, .jsonId=nodeId_175, .baseId=nodeId_16, .dataTypeId=nodeId_54}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_182_attrs, .refs=nodeId_182_refs, .binaryId=NULL, .jsonId=nodeId_182, .baseId=nodeId_16, .dataTypeId=nodeId_31}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_196_attrs, .refs=nodeId_196_refs, .binaryId=NULL, .jsonId=nodeId_196, .baseId=nodeId_16, .dataTypeId=nodeId_443}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_484_attrs, .refs=nodeId_484_refs, .binaryId=NULL, .jsonId=nodeId_484, .baseId=nodeId_16, .dataTypeId=nodeId_358}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_253_attrs, .refs=nodeId_253_refs, .binaryId=NULL, .jsonId=nodeId_253, .baseId=nodeId_16, .dataTypeId=nodeId_251}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_512_attrs, .refs=nodeId_512_refs, .binaryId=NULL, .jsonId=nodeId_512, .baseId=nodeId_16, .dataTypeId=nodeId_519}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_534_attrs, .refs=nodeId_534_refs, .binaryId=NULL, .jsonId=nodeId_534, .baseId=nodeId_16, .dataTypeId=nodeId_18}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_79_attrs, .refs=nodeId_79_refs, .binaryId=NULL, .jsonId=nodeId_79, .baseId=nodeId_16, .dataTypeId=nodeId_51}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_80_attrs, .refs=nodeId_80_refs, .binaryId=NULL, .jsonId=nodeId_80, .baseId=nodeId_16, .dataTypeId=nodeId_309}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_492_attrs, .refs=nodeId_492_refs, .binaryId=NULL, .jsonId=nodeId_492, .baseId=nodeId_16, .dataTypeId=nodeId_539}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_4_attrs, .refs=nodeId_4_refs, .binaryId=NULL, .jsonId=nodeId_4, .baseId=nodeId_16, .dataTypeId=nodeId_458}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_260_attrs, .refs=nodeId_260_refs, .binaryId=NULL, .jsonId=nodeId_260, .baseId=nodeId_16, .dataTypeId=nodeId_296}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_414_attrs, .refs=nodeId_414_refs, .binaryId=NULL, .jsonId=nodeId_414, .baseId=nodeId_16, .dataTypeId=nodeId_496}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_355_attrs, .refs=nodeId_355_refs, .binaryId=NULL, .jsonId=nodeId_355, .baseId=nodeId_16, .dataTypeId=nodeId_323}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_521_attrs, .refs=nodeId_521_refs, .binaryId=NULL, .jsonId=nodeId_521, .baseId=nodeId_16, .dataTypeId=nodeId_140}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_330_attrs, .refs=nodeId_330_refs, .binaryId=NULL, .jsonId=nodeId_330, .baseId=nodeId_16, .dataTypeId=nodeId_88}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_131_attrs, .refs=nodeId_131_refs, .binaryId=NULL, .jsonId=nodeId_131, .baseId=nodeId_16, .dataTypeId=nodeId_227}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_233_attrs, .refs=nodeId_233_refs, .binaryId=NULL, .jsonId=nodeId_233, .baseId=nodeId_16, .dataTypeId=nodeId_180}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_400_attrs, .refs=nodeId_400_refs, .binaryId=NULL, .jsonId=nodeId_400, .baseId=nodeId_16, .dataTypeId=nodeId_280}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_179_attrs, .refs=nodeId_179_refs, .binaryId=NULL, .jsonId=nodeId_179, .baseId=nodeId_16, .dataTypeId=nodeId_210}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_3_attrs, .refs=nodeId_3_refs, .binaryId=NULL, .jsonId=nodeId_3, .baseId=nodeId_16, .dataTypeId=nodeId_522}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_287_attrs, .refs=nodeId_287_refs, .binaryId=NULL, .jsonId=nodeId_287, .baseId=nodeId_16, .dataTypeId=nodeId_454}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_29_attrs, .refs=nodeId_29_refs, .binaryId=NULL, .jsonId=nodeId_29, .baseId=nodeId_16, .dataTypeId=nodeId_57}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_481_attrs, .refs=nodeId_481_refs, .binaryId=NULL, .jsonId=nodeId_481, .baseId=nodeId_16, .dataTypeId=nodeId_405}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_229_attrs, .refs=nodeId_229_refs, .binaryId=NULL, .jsonId=nodeId_229, .baseId=nodeId_16, .dataTypeId=nodeId_302}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_183_attrs, .refs=nodeId_183_refs, .binaryId=NULL, .jsonId=nodeId_183, .baseId=nodeId_16, .dataTypeId=nodeId_361}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_98_attrs, .refs=nodeId_98_refs, .binaryId=NULL, .jsonId=nodeId_98, .baseId=nodeId_16, .dataTypeId=nodeId_356}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_413_attrs, .refs=nodeId_413_refs, .binaryId=NULL, .jsonId=nodeId_413, .baseId=nodeId_16, .dataTypeId=nodeId_74}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_301_attrs, .refs=nodeId_301_refs, .binaryId=NULL, .jsonId=nodeId_301, .baseId=nodeId_16, .dataTypeId=nodeId_292}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_134_attrs, .refs=nodeId_134_refs, .binaryId=NULL, .jsonId=nodeId_134, .baseId=nodeId_16, .dataTypeId=nodeId_352}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_312_attrs, .refs=nodeId_312_refs, .binaryId=NULL, .jsonId=nodeId_312, .baseId=nodeId_16, .dataTypeId=nodeId_483}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_428_attrs, .refs=nodeId_428_refs, .binaryId=NULL, .jsonId=nodeId_428, .baseId=nodeId_16, .dataTypeId=nodeId_482}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_26_attrs, .refs=nodeId_26_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_145_attrs, .refs=nodeId_145_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_461_attrs, .refs=nodeId_461_refs, .binaryId=nodeId_461, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_33}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_6_attrs, .refs=nodeId_6_refs, .binaryId=nodeId_291, .jsonId=nodeId_162, .baseId=nodeId_16, .dataTypeId=nodeId_6}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_161_attrs, .refs=nodeId_161_refs, .binaryId=nodeId_150, .jsonId=nodeId_106, .baseId=nodeId_16, .dataTypeId=nodeId_161}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_378_attrs, .refs=nodeId_378_refs, .binaryId=nodeId_122, .jsonId=nodeId_204, .baseId=nodeId_16, .dataTypeId=nodeId_378}, {.attrsSize=6, .refsSize=4, .attrs=nodeId_12_attrs, .refs=nodeId_12_refs, .binaryId=nodeId_468, .jsonId=nodeId_297, .baseId=nodeId_16, .dataTypeId=nodeId_12}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_66_attrs, .refs=nodeId_66_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_122_attrs, .refs=nodeId_122_refs, .binaryId=nodeId_122, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_378}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_468_attrs, .refs=nodeId_468_refs, .binaryId=nodeId_468, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_12}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_32_attrs, .refs=nodeId_32_refs, .binaryId=NULL, .jsonId=nodeId_32, .baseId=nodeId_16, .dataTypeId=nodeId_33}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_489_attrs, .refs=nodeId_489_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_283, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=9, .attrs=nodeId_527_attrs, .refs=nodeId_527_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_433_attrs, .refs=nodeId_433_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_532_attrs, .refs=nodeId_532_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_23_attrs, .refs=nodeId_23_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_335_attrs, .refs=nodeId_335_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_395_attrs, .refs=nodeId_395_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_249_attrs, .refs=nodeId_249_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_281_attrs, .refs=nodeId_281_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_68_attrs, .refs=nodeId_68_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_68, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_204_attrs, .refs=nodeId_204_refs, .binaryId=NULL, .jsonId=nodeId_204, .baseId=nodeId_16, .dataTypeId=nodeId_378}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_297_attrs, .refs=nodeId_297_refs, .binaryId=NULL, .jsonId=nodeId_297, .baseId=nodeId_16, .dataTypeId=nodeId_12}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_322_attrs, .refs=nodeId_322_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_322, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_257_attrs, .refs=nodeId_257_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_164_attrs, .refs=nodeId_164_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_164, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_360_attrs, .refs=nodeId_360_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_360, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_239_attrs, .refs=nodeId_239_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_239, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_514_attrs, .refs=nodeId_514_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_514, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=9, .attrs=nodeId_112_attrs, .refs=nodeId_112_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=3, .attrs=nodeId_410_attrs, .refs=nodeId_410_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=3, .attrs=nodeId_343_attrs, .refs=nodeId_343_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=9, .attrs=nodeId_199_attrs, .refs=nodeId_199_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_189_attrs, .refs=nodeId_189_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=11, .attrs=nodeId_102_attrs, .refs=nodeId_102_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_511_attrs, .refs=nodeId_511_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=11, .attrs=nodeId_270_attrs, .refs=nodeId_270_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_218_attrs, .refs=nodeId_218_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_377_attrs, .refs=nodeId_377_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_347_attrs, .refs=nodeId_347_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_86_attrs, .refs=nodeId_86_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_177_attrs, .refs=nodeId_177_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_329_attrs, .refs=nodeId_329_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_99_attrs, .refs=nodeId_99_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_99, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=9, .attrs=nodeId_198_attrs, .refs=nodeId_198_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_396_attrs, .refs=nodeId_396_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_234_attrs, .refs=nodeId_234_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_85_attrs, .refs=nodeId_85_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=9, .attrs=nodeId_36_attrs, .refs=nodeId_36_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=83, .attrs=nodeId_16_attrs, .refs=nodeId_16_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=10, .attrs=nodeId_349_attrs, .refs=nodeId_349_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_401_attrs, .refs=nodeId_401_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_172_attrs, .refs=nodeId_172_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=8, .attrs=nodeId_536_attrs, .refs=nodeId_536_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=2, .attrs=nodeId_391_attrs, .refs=nodeId_391_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=2, .attrs=nodeId_101_attrs, .refs=nodeId_101_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_315_attrs, .refs=nodeId_315_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=8, .attrs=nodeId_156_attrs, .refs=nodeId_156_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_478_attrs, .refs=nodeId_478_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_181_attrs, .refs=nodeId_181_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_185_attrs, .refs=nodeId_185_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_176_attrs, .refs=nodeId_176_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_434_attrs, .refs=nodeId_434_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_338_attrs, .refs=nodeId_338_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_137_attrs, .refs=nodeId_137_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=11, .attrs=nodeId_30_attrs, .refs=nodeId_30_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_117_attrs, .refs=nodeId_117_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_300_attrs, .refs=nodeId_300_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_203_attrs, .refs=nodeId_203_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_388_attrs, .refs=nodeId_388_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_538_attrs, .refs=nodeId_538_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_538, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_10_attrs, .refs=nodeId_10_refs, .binaryId=nodeId_149, .jsonId=nodeId_515, .baseId=nodeId_16, .dataTypeId=nodeId_10}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_149_attrs, .refs=nodeId_149_refs, .binaryId=nodeId_149, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_10}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_515_attrs, .refs=nodeId_515_refs, .binaryId=NULL, .jsonId=nodeId_515, .baseId=nodeId_16, .dataTypeId=nodeId_10}, {.attrsSize=5, .refsSize=17, .attrs=nodeId_139_attrs, .refs=nodeId_139_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_139, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_220_attrs, .refs=nodeId_220_refs, .binaryId=nodeId_69, .jsonId=nodeId_462, .baseId=nodeId_16, .dataTypeId=nodeId_220}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_69_attrs, .refs=nodeId_69_refs, .binaryId=nodeId_69, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_220}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_462_attrs, .refs=nodeId_462_refs, .binaryId=NULL, .jsonId=nodeId_462, .baseId=nodeId_16, .dataTypeId=nodeId_220}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_500_attrs, .refs=nodeId_500_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_318_attrs, .refs=nodeId_318_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_318, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_369_attrs, .refs=nodeId_369_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_505_attrs, .refs=nodeId_505_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_530_attrs, .refs=nodeId_530_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=6, .attrs=nodeId_72_attrs, .refs=nodeId_72_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_139, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=5, .attrs=nodeId_120_attrs, .refs=nodeId_120_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_139, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_480_attrs, .refs=nodeId_480_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_354_attrs, .refs=nodeId_354_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_265_attrs, .refs=nodeId_265_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_195_attrs, .refs=nodeId_195_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_84_attrs, .refs=nodeId_84_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_308_attrs, .refs=nodeId_308_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_518_attrs, .refs=nodeId_518_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_81_attrs, .refs=nodeId_81_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_288_attrs, .refs=nodeId_288_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=5, .attrs=nodeId_154_attrs, .refs=nodeId_154_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_139, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_71_attrs, .refs=nodeId_71_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_55_attrs, .refs=nodeId_55_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=14, .attrs=nodeId_415_attrs, .refs=nodeId_415_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_148_attrs, .refs=nodeId_148_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_65, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_129_attrs, .refs=nodeId_129_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_498_attrs, .refs=nodeId_498_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_24, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_159_attrs, .refs=nodeId_159_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_11, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_212_attrs, .refs=nodeId_212_refs, .binaryId=nodeId_232, .jsonId=nodeId_305, .baseId=nodeId_16, .dataTypeId=nodeId_212}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_232_attrs, .refs=nodeId_232_refs, .binaryId=nodeId_232, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_212}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_74_attrs, .refs=nodeId_74_refs, .binaryId=nodeId_282, .jsonId=nodeId_413, .baseId=nodeId_16, .dataTypeId=nodeId_74}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_252_attrs, .refs=nodeId_252_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=2, .attrs=nodeId_67_attrs, .refs=nodeId_67_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_194_attrs, .refs=nodeId_194_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_342_attrs, .refs=nodeId_342_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_278_attrs, .refs=nodeId_278_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_278, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_282_attrs, .refs=nodeId_282_refs, .binaryId=nodeId_282, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_74}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_475_attrs, .refs=nodeId_475_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_168_attrs, .refs=nodeId_168_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_141_attrs, .refs=nodeId_141_refs, .binaryId=nodeId_246, .jsonId=nodeId_440, .baseId=nodeId_16, .dataTypeId=nodeId_141}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_510_attrs, .refs=nodeId_510_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=10, .attrs=nodeId_394_attrs, .refs=nodeId_394_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_188_attrs, .refs=nodeId_188_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_90_attrs, .refs=nodeId_90_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_299_attrs, .refs=nodeId_299_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_116_attrs, .refs=nodeId_116_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_268_attrs, .refs=nodeId_268_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_34_attrs, .refs=nodeId_34_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_246_attrs, .refs=nodeId_246_refs, .binaryId=nodeId_246, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_141}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_485_attrs, .refs=nodeId_485_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_363_attrs, .refs=nodeId_363_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_432_attrs, .refs=nodeId_432_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_298_attrs, .refs=nodeId_298_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=9, .attrs=nodeId_37_attrs, .refs=nodeId_37_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_366_attrs, .refs=nodeId_366_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_326_attrs, .refs=nodeId_326_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_237_attrs, .refs=nodeId_237_refs, .binaryId=nodeId_53, .jsonId=nodeId_50, .baseId=nodeId_16, .dataTypeId=nodeId_237}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_435_attrs, .refs=nodeId_435_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_520_attrs, .refs=nodeId_520_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_495_attrs, .refs=nodeId_495_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_267_attrs, .refs=nodeId_267_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_186_attrs, .refs=nodeId_186_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_271_attrs, .refs=nodeId_271_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_444_attrs, .refs=nodeId_444_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_207_attrs, .refs=nodeId_207_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_513_attrs, .refs=nodeId_513_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_389_attrs, .refs=nodeId_389_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_135_attrs, .refs=nodeId_135_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=8, .refsSize=3, .attrs=nodeId_465_attrs, .refs=nodeId_465_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_8_attrs, .refs=nodeId_8_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_44_attrs, .refs=nodeId_44_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_58_attrs, .refs=nodeId_58_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_53_attrs, .refs=nodeId_53_refs, .binaryId=nodeId_53, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_237}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_226_attrs, .refs=nodeId_226_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_456, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_262_attrs, .refs=nodeId_262_refs, .binaryId=nodeId_417, .jsonId=nodeId_304, .baseId=nodeId_16, .dataTypeId=nodeId_262}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_417_attrs, .refs=nodeId_417_refs, .binaryId=nodeId_417, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_262}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_200_attrs, .refs=nodeId_200_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=7, .attrs=nodeId_328_attrs, .refs=nodeId_328_refs, .binaryId=nodeId_333, .jsonId=nodeId_243, .baseId=nodeId_16, .dataTypeId=nodeId_328}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_333_attrs, .refs=nodeId_333_refs, .binaryId=nodeId_333, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_328}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_457_attrs, .refs=nodeId_457_refs, .binaryId=nodeId_22, .jsonId=nodeId_403, .baseId=nodeId_16, .dataTypeId=nodeId_457}, {.attrsSize=6, .refsSize=10, .attrs=nodeId_41_attrs, .refs=nodeId_41_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_22_attrs, .refs=nodeId_22_refs, .binaryId=nodeId_22, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_457}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_42_attrs, .refs=nodeId_42_refs, .binaryId=nodeId_133, .jsonId=nodeId_231, .baseId=nodeId_16, .dataTypeId=nodeId_42}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_133_attrs, .refs=nodeId_133_refs, .binaryId=nodeId_133, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_42}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_247_attrs, .refs=nodeId_247_refs, .binaryId=nodeId_191, .jsonId=nodeId_407, .baseId=nodeId_16, .dataTypeId=nodeId_247}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_191_attrs, .refs=nodeId_191_refs, .binaryId=nodeId_191, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_247}, {.attrsSize=7, .refsSize=4, .attrs=nodeId_2_attrs, .refs=nodeId_2_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_51_attrs, .refs=nodeId_51_refs, .binaryId=nodeId_174, .jsonId=nodeId_79, .baseId=nodeId_16, .dataTypeId=nodeId_51}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_174_attrs, .refs=nodeId_174_refs, .binaryId=nodeId_174, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_51}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_522_attrs, .refs=nodeId_522_refs, .binaryId=nodeId_201, .jsonId=nodeId_3, .baseId=nodeId_16, .dataTypeId=nodeId_522}, {.attrsSize=7, .refsSize=3, .attrs=nodeId_151_attrs, .refs=nodeId_151_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_201_attrs, .refs=nodeId_201_refs, .binaryId=nodeId_201, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_522}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_392_attrs, .refs=nodeId_392_refs, .binaryId=nodeId_421, .jsonId=nodeId_416, .baseId=nodeId_16, .dataTypeId=nodeId_392}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_421_attrs, .refs=nodeId_421_refs, .binaryId=nodeId_421, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_392}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_103_attrs, .refs=nodeId_103_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_419_attrs, .refs=nodeId_419_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=11, .attrs=nodeId_272_attrs, .refs=nodeId_272_refs, .binaryId=nodeId_130, .jsonId=nodeId_205, .baseId=nodeId_16, .dataTypeId=nodeId_272}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_411_attrs, .refs=nodeId_411_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_130_attrs, .refs=nodeId_130_refs, .binaryId=nodeId_130, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_272}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_236_attrs, .refs=nodeId_236_refs, .binaryId=nodeId_109, .jsonId=nodeId_52, .baseId=nodeId_16, .dataTypeId=nodeId_236}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_109_attrs, .refs=nodeId_109_refs, .binaryId=nodeId_109, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_236}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_238_attrs, .refs=nodeId_238_refs, .binaryId=nodeId_39, .jsonId=nodeId_319, .baseId=nodeId_16, .dataTypeId=nodeId_238}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_39_attrs, .refs=nodeId_39_refs, .binaryId=nodeId_39, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_238}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_472_attrs, .refs=nodeId_472_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=7, .refsSize=2, .attrs=nodeId_398_attrs, .refs=nodeId_398_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_404_attrs, .refs=nodeId_404_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_125_attrs, .refs=nodeId_125_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_76_attrs, .refs=nodeId_76_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_375_attrs, .refs=nodeId_375_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_169_attrs, .refs=nodeId_169_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_153_attrs, .refs=nodeId_153_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_497_attrs, .refs=nodeId_497_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_469_attrs, .refs=nodeId_469_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_21_attrs, .refs=nodeId_21_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_92_attrs, .refs=nodeId_92_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_393_attrs, .refs=nodeId_393_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_448_attrs, .refs=nodeId_448_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_535_attrs, .refs=nodeId_535_refs, .binaryId=nodeId_507, .jsonId=nodeId_178, .baseId=nodeId_16, .dataTypeId=nodeId_535}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_507_attrs, .refs=nodeId_507_refs, .binaryId=nodeId_507, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_535}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_60_attrs, .refs=nodeId_60_refs, .binaryId=nodeId_126, .jsonId=nodeId_490, .baseId=nodeId_16, .dataTypeId=nodeId_60}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_95_attrs, .refs=nodeId_95_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_126_attrs, .refs=nodeId_126_refs, .binaryId=nodeId_126, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_60}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_215_attrs, .refs=nodeId_215_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_322, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_425_attrs, .refs=nodeId_425_refs, .binaryId=nodeId_193, .jsonId=nodeId_97, .baseId=nodeId_16, .dataTypeId=nodeId_425}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_146_attrs, .refs=nodeId_146_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_193_attrs, .refs=nodeId_193_refs, .binaryId=nodeId_193, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_425}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_47_attrs, .refs=nodeId_47_refs, .binaryId=nodeId_111, .jsonId=nodeId_524, .baseId=nodeId_16, .dataTypeId=nodeId_47}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_111_attrs, .refs=nodeId_111_refs, .binaryId=nodeId_111, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_47}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_190_attrs, .refs=nodeId_190_refs, .binaryId=nodeId_17, .jsonId=nodeId_303, .baseId=nodeId_16, .dataTypeId=nodeId_190}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_17_attrs, .refs=nodeId_17_refs, .binaryId=nodeId_17, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_190}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_245_attrs, .refs=nodeId_245_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_245, .dataTypeId=NULL}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_324_attrs, .refs=nodeId_324_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_94_attrs, .refs=nodeId_94_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_107_attrs, .refs=nodeId_107_refs, .binaryId=nodeId_61, .jsonId=nodeId_402, .baseId=nodeId_16, .dataTypeId=nodeId_107}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_61_attrs, .refs=nodeId_61_refs, .binaryId=nodeId_61, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_107}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_311_attrs, .refs=nodeId_311_refs, .binaryId=nodeId_0, .jsonId=nodeId_314, .baseId=nodeId_16, .dataTypeId=nodeId_311}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_0_attrs, .refs=nodeId_0_refs, .binaryId=nodeId_0, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_311}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_473_attrs, .refs=nodeId_473_refs, .binaryId=nodeId_221, .jsonId=nodeId_15, .baseId=nodeId_16, .dataTypeId=nodeId_473}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_221_attrs, .refs=nodeId_221_refs, .binaryId=nodeId_221, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_473}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_340_attrs, .refs=nodeId_340_refs, .binaryId=nodeId_27, .jsonId=nodeId_317, .baseId=nodeId_16, .dataTypeId=nodeId_340}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_27_attrs, .refs=nodeId_27_refs, .binaryId=nodeId_27, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_340}, {.attrsSize=7, .refsSize=3, .attrs=nodeId_118_attrs, .refs=nodeId_118_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_219_attrs, .refs=nodeId_219_refs, .binaryId=nodeId_452, .jsonId=nodeId_110, .baseId=nodeId_16, .dataTypeId=nodeId_219}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_452_attrs, .refs=nodeId_452_refs, .binaryId=nodeId_452, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_219}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_144_attrs, .refs=nodeId_144_refs, .binaryId=nodeId_460, .jsonId=nodeId_157, .baseId=nodeId_16, .dataTypeId=nodeId_144}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_460_attrs, .refs=nodeId_460_refs, .binaryId=nodeId_460, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_144}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_77_attrs, .refs=nodeId_77_refs, .binaryId=nodeId_295, .jsonId=nodeId_504, .baseId=nodeId_16, .dataTypeId=nodeId_77}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_295_attrs, .refs=nodeId_295_refs, .binaryId=nodeId_295, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_77}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_334_attrs, .refs=nodeId_334_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_350_attrs, .refs=nodeId_350_refs, .binaryId=nodeId_64, .jsonId=nodeId_451, .baseId=nodeId_16, .dataTypeId=nodeId_350}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_64_attrs, .refs=nodeId_64_refs, .binaryId=nodeId_64, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_350}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_370_attrs, .refs=nodeId_370_refs, .binaryId=nodeId_273, .jsonId=nodeId_167, .baseId=nodeId_16, .dataTypeId=nodeId_370}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_273_attrs, .refs=nodeId_273_refs, .binaryId=nodeId_273, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_370}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_429_attrs, .refs=nodeId_429_refs, .binaryId=nodeId_470, .jsonId=nodeId_274, .baseId=nodeId_16, .dataTypeId=nodeId_429}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_399_attrs, .refs=nodeId_399_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_470_attrs, .refs=nodeId_470_refs, .binaryId=nodeId_470, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_429}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_431_attrs, .refs=nodeId_431_refs, .binaryId=nodeId_467, .jsonId=nodeId_466, .baseId=nodeId_16, .dataTypeId=nodeId_431}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_467_attrs, .refs=nodeId_467_refs, .binaryId=nodeId_467, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_431}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_423_attrs, .refs=nodeId_423_refs, .binaryId=nodeId_506, .jsonId=nodeId_397, .baseId=nodeId_16, .dataTypeId=nodeId_423}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_506_attrs, .refs=nodeId_506_refs, .binaryId=nodeId_506, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_423}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_263_attrs, .refs=nodeId_263_refs, .binaryId=nodeId_464, .jsonId=nodeId_165, .baseId=nodeId_16, .dataTypeId=nodeId_263}, {.attrsSize=7, .refsSize=2, .attrs=nodeId_310_attrs, .refs=nodeId_310_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_464_attrs, .refs=nodeId_464_refs, .binaryId=nodeId_464, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_263}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_529_attrs, .refs=nodeId_529_refs, .binaryId=nodeId_353, .jsonId=nodeId_420, .baseId=nodeId_16, .dataTypeId=nodeId_529}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_353_attrs, .refs=nodeId_353_refs, .binaryId=nodeId_353, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_529}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_62_attrs, .refs=nodeId_62_refs, .binaryId=nodeId_368, .jsonId=nodeId_89, .baseId=nodeId_16, .dataTypeId=nodeId_62}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_368_attrs, .refs=nodeId_368_refs, .binaryId=nodeId_368, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_62}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_357_attrs, .refs=nodeId_357_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=1, .attrs=nodeId_119_attrs, .refs=nodeId_119_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_362_attrs, .refs=nodeId_362_refs, .binaryId=nodeId_63, .jsonId=nodeId_138, .baseId=nodeId_16, .dataTypeId=nodeId_362}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_63_attrs, .refs=nodeId_63_refs, .binaryId=nodeId_63, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_362}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_427_attrs, .refs=nodeId_427_refs, .binaryId=nodeId_158, .jsonId=nodeId_276, .baseId=nodeId_16, .dataTypeId=nodeId_427}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_286_attrs, .refs=nodeId_286_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_158_attrs, .refs=nodeId_158_refs, .binaryId=nodeId_158, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_427}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_283_attrs, .refs=nodeId_283_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_283, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_371_attrs, .refs=nodeId_371_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_139, .dataTypeId=NULL}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_437_attrs, .refs=nodeId_437_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_523_attrs, .refs=nodeId_523_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_293_attrs, .refs=nodeId_293_refs, .binaryId=nodeId_255, .jsonId=nodeId_306, .baseId=nodeId_16, .dataTypeId=nodeId_293}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_255_attrs, .refs=nodeId_255_refs, .binaryId=nodeId_255, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_293}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_486_attrs, .refs=nodeId_486_refs, .binaryId=nodeId_242, .jsonId=nodeId_430, .baseId=nodeId_16, .dataTypeId=nodeId_486}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_242_attrs, .refs=nodeId_242_refs, .binaryId=nodeId_242, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_486}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_59_attrs, .refs=nodeId_59_refs, .binaryId=nodeId_166, .jsonId=nodeId_108, .baseId=nodeId_16, .dataTypeId=nodeId_59}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_321_attrs, .refs=nodeId_321_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_166_attrs, .refs=nodeId_166_refs, .binaryId=nodeId_166, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_59}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_331_attrs, .refs=nodeId_331_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_456, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_82_attrs, .refs=nodeId_82_refs, .binaryId=nodeId_294, .jsonId=nodeId_479, .baseId=nodeId_16, .dataTypeId=nodeId_82}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_294_attrs, .refs=nodeId_294_refs, .binaryId=nodeId_294, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_82}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_43_attrs, .refs=nodeId_43_refs, .binaryId=nodeId_73, .jsonId=nodeId_424, .baseId=nodeId_16, .dataTypeId=nodeId_43}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_73_attrs, .refs=nodeId_73_refs, .binaryId=nodeId_73, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_43}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_390_attrs, .refs=nodeId_390_refs, .binaryId=nodeId_284, .jsonId=nodeId_406, .baseId=nodeId_16, .dataTypeId=nodeId_390}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_384_attrs, .refs=nodeId_384_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_284_attrs, .refs=nodeId_284_refs, .binaryId=nodeId_284, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_390}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_54_attrs, .refs=nodeId_54_refs, .binaryId=nodeId_224, .jsonId=nodeId_175, .baseId=nodeId_16, .dataTypeId=nodeId_54}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_224_attrs, .refs=nodeId_224_refs, .binaryId=nodeId_224, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_54}, {.attrsSize=7, .refsSize=1, .attrs=nodeId_508_attrs, .refs=nodeId_508_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_31_attrs, .refs=nodeId_31_refs, .binaryId=nodeId_228, .jsonId=nodeId_182, .baseId=nodeId_16, .dataTypeId=nodeId_31}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_228_attrs, .refs=nodeId_228_refs, .binaryId=nodeId_228, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_31}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_443_attrs, .refs=nodeId_443_refs, .binaryId=nodeId_40, .jsonId=nodeId_196, .baseId=nodeId_16, .dataTypeId=nodeId_443}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_40_attrs, .refs=nodeId_40_refs, .binaryId=nodeId_40, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_443}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_358_attrs, .refs=nodeId_358_refs, .binaryId=nodeId_372, .jsonId=nodeId_484, .baseId=nodeId_16, .dataTypeId=nodeId_358}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_372_attrs, .refs=nodeId_372_refs, .binaryId=nodeId_372, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_358}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_251_attrs, .refs=nodeId_251_refs, .binaryId=nodeId_254, .jsonId=nodeId_253, .baseId=nodeId_16, .dataTypeId=nodeId_251}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_254_attrs, .refs=nodeId_254_refs, .binaryId=nodeId_254, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_251}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_519_attrs, .refs=nodeId_519_refs, .binaryId=nodeId_128, .jsonId=nodeId_512, .baseId=nodeId_16, .dataTypeId=nodeId_519}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_128_attrs, .refs=nodeId_128_refs, .binaryId=nodeId_128, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_519}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_18_attrs, .refs=nodeId_18_refs, .binaryId=nodeId_525, .jsonId=nodeId_534, .baseId=nodeId_16, .dataTypeId=nodeId_18}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_525_attrs, .refs=nodeId_525_refs, .binaryId=nodeId_525, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_18}, {.attrsSize=5, .refsSize=10, .attrs=nodeId_143_attrs, .refs=nodeId_143_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_136_attrs, .refs=nodeId_136_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_136, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=12, .attrs=nodeId_78_attrs, .refs=nodeId_78_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=9, .refsSize=3, .attrs=nodeId_509_attrs, .refs=nodeId_509_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_537_attrs, .refs=nodeId_537_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_309_attrs, .refs=nodeId_309_refs, .binaryId=nodeId_344, .jsonId=nodeId_80, .baseId=nodeId_16, .dataTypeId=nodeId_309}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_344_attrs, .refs=nodeId_344_refs, .binaryId=nodeId_344, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_309}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_539_attrs, .refs=nodeId_539_refs, .binaryId=nodeId_445, .jsonId=nodeId_492, .baseId=nodeId_16, .dataTypeId=nodeId_539}, {.attrsSize=9, .refsSize=42, .attrs=nodeId_46_attrs, .refs=nodeId_46_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_445_attrs, .refs=nodeId_445_refs, .binaryId=nodeId_445, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_539}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_458_attrs, .refs=nodeId_458_refs, .binaryId=nodeId_170, .jsonId=nodeId_4, .baseId=nodeId_16, .dataTypeId=nodeId_458}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_170_attrs, .refs=nodeId_170_refs, .binaryId=nodeId_170, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_458}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_296_attrs, .refs=nodeId_296_refs, .binaryId=nodeId_250, .jsonId=nodeId_260, .baseId=nodeId_16, .dataTypeId=nodeId_296}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_250_attrs, .refs=nodeId_250_refs, .binaryId=nodeId_250, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_296}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_496_attrs, .refs=nodeId_496_refs, .binaryId=nodeId_531, .jsonId=nodeId_414, .baseId=nodeId_16, .dataTypeId=nodeId_496}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_531_attrs, .refs=nodeId_531_refs, .binaryId=nodeId_531, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_496}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_323_attrs, .refs=nodeId_323_refs, .binaryId=nodeId_446, .jsonId=nodeId_355, .baseId=nodeId_16, .dataTypeId=nodeId_323}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_446_attrs, .refs=nodeId_446_refs, .binaryId=nodeId_446, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_323}, {.attrsSize=9, .refsSize=87, .attrs=nodeId_104_attrs, .refs=nodeId_104_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=8, .attrs=nodeId_49_attrs, .refs=nodeId_49_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_140_attrs, .refs=nodeId_140_refs, .binaryId=nodeId_502, .jsonId=nodeId_521, .baseId=nodeId_16, .dataTypeId=nodeId_140}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_502_attrs, .refs=nodeId_502_refs, .binaryId=nodeId_502, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_140}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_88_attrs, .refs=nodeId_88_refs, .binaryId=nodeId_75, .jsonId=nodeId_330, .baseId=nodeId_16, .dataTypeId=nodeId_88}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_75_attrs, .refs=nodeId_75_refs, .binaryId=nodeId_75, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_88}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_227_attrs, .refs=nodeId_227_refs, .binaryId=nodeId_142, .jsonId=nodeId_131, .baseId=nodeId_16, .dataTypeId=nodeId_227}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_142_attrs, .refs=nodeId_142_refs, .binaryId=nodeId_142, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_227}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_180_attrs, .refs=nodeId_180_refs, .binaryId=nodeId_202, .jsonId=nodeId_233, .baseId=nodeId_16, .dataTypeId=nodeId_180}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_202_attrs, .refs=nodeId_202_refs, .binaryId=nodeId_202, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_180}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_19_attrs, .refs=nodeId_19_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=4, .attrs=nodeId_266_attrs, .refs=nodeId_266_refs, .binaryId=nodeId_222, .jsonId=nodeId_35, .baseId=nodeId_16, .dataTypeId=nodeId_266}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_70_attrs, .refs=nodeId_70_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_517_attrs, .refs=nodeId_517_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_277_attrs, .refs=nodeId_277_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_256_attrs, .refs=nodeId_256_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=181, .attrs=nodeId_127_attrs, .refs=nodeId_127_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_217_attrs, .refs=nodeId_217_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_7_attrs, .refs=nodeId_7_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=10, .refsSize=2, .attrs=nodeId_426_attrs, .refs=nodeId_426_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=4, .attrs=nodeId_337_attrs, .refs=nodeId_337_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=87, .attrs=nodeId_341_attrs, .refs=nodeId_341_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_280_attrs, .refs=nodeId_280_refs, .binaryId=nodeId_438, .jsonId=nodeId_400, .baseId=nodeId_16, .dataTypeId=nodeId_280}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_438_attrs, .refs=nodeId_438_refs, .binaryId=nodeId_438, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_280}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_210_attrs, .refs=nodeId_210_refs, .binaryId=nodeId_316, .jsonId=nodeId_179, .baseId=nodeId_16, .dataTypeId=nodeId_210}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_316_attrs, .refs=nodeId_316_refs, .binaryId=nodeId_316, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_210}, {.attrsSize=5, .refsSize=1, .attrs=nodeId_471_attrs, .refs=nodeId_471_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_471, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=4, .attrs=nodeId_28_attrs, .refs=nodeId_28_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_222_attrs, .refs=nodeId_222_refs, .binaryId=nodeId_222, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_266}, {.attrsSize=5, .refsSize=4, .attrs=nodeId_387_attrs, .refs=nodeId_387_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_327_attrs, .refs=nodeId_327_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_365_attrs, .refs=nodeId_365_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_57_attrs, .refs=nodeId_57_refs, .binaryId=nodeId_230, .jsonId=nodeId_29, .baseId=nodeId_16, .dataTypeId=nodeId_57}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_230_attrs, .refs=nodeId_230_refs, .binaryId=nodeId_230, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_57}, {.attrsSize=5, .refsSize=6, .attrs=nodeId_493_attrs, .refs=nodeId_493_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_405_attrs, .refs=nodeId_405_refs, .binaryId=nodeId_345, .jsonId=nodeId_481, .baseId=nodeId_16, .dataTypeId=nodeId_405}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_345_attrs, .refs=nodeId_345_refs, .binaryId=nodeId_345, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_405}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_302_attrs, .refs=nodeId_302_refs, .binaryId=nodeId_259, .jsonId=nodeId_229, .baseId=nodeId_16, .dataTypeId=nodeId_302}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_259_attrs, .refs=nodeId_259_refs, .binaryId=nodeId_259, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_302}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_361_attrs, .refs=nodeId_361_refs, .binaryId=nodeId_455, .jsonId=nodeId_183, .baseId=nodeId_16, .dataTypeId=nodeId_361}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_348_attrs, .refs=nodeId_348_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_455_attrs, .refs=nodeId_455_refs, .binaryId=nodeId_455, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_361}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_356_attrs, .refs=nodeId_356_refs, .binaryId=nodeId_359, .jsonId=nodeId_98, .baseId=nodeId_16, .dataTypeId=nodeId_356}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_359_attrs, .refs=nodeId_359_refs, .binaryId=nodeId_359, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_356}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_528_attrs, .refs=nodeId_528_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_292_attrs, .refs=nodeId_292_refs, .binaryId=nodeId_192, .jsonId=nodeId_301, .baseId=nodeId_16, .dataTypeId=nodeId_292}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_192_attrs, .refs=nodeId_192_refs, .binaryId=nodeId_192, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_292}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_352_attrs, .refs=nodeId_352_refs, .binaryId=nodeId_83, .jsonId=nodeId_134, .baseId=nodeId_16, .dataTypeId=nodeId_352}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_83_attrs, .refs=nodeId_83_refs, .binaryId=nodeId_83, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_352}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_13_attrs, .refs=nodeId_13_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_491_attrs, .refs=nodeId_491_refs, .binaryId=nodeId_100, .jsonId=nodeId_436, .baseId=nodeId_16, .dataTypeId=nodeId_491}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_100_attrs, .refs=nodeId_100_refs, .binaryId=nodeId_100, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_491}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_56_attrs, .refs=nodeId_56_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_56, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_380_attrs, .refs=nodeId_380_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=3, .attrs=nodeId_114_attrs, .refs=nodeId_114_refs, .binaryId=NULL, .jsonId=NULL, .baseId=NULL, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_197_attrs, .refs=nodeId_197_refs, .binaryId=nodeId_163, .jsonId=nodeId_261, .baseId=nodeId_16, .dataTypeId=nodeId_197}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_487_attrs, .refs=nodeId_487_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_49, .dataTypeId=NULL}, {.attrsSize=5, .refsSize=2, .attrs=nodeId_163_attrs, .refs=nodeId_163_refs, .binaryId=nodeId_163, .jsonId=NULL, .baseId=nodeId_16, .dataTypeId=nodeId_197}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_214_attrs, .refs=nodeId_214_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_283, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_374_attrs, .refs=nodeId_374_refs, .binaryId=nodeId_285, .jsonId=nodeId_216, .baseId=nodeId_16, .dataTypeId=nodeId_374}, {.attrsSize=5, .refsSize=5, .attrs=nodeId_339_attrs, .refs=nodeId_339_refs, .binaryId=nodeId_313, .jsonId=nodeId_171, .baseId=nodeId_16, .dataTypeId=nodeId_339}, {.attrsSize=6, .refsSize=2, .attrs=nodeId_9_attrs, .refs=nodeId_9_refs, .binaryId=NULL, .jsonId=NULL, .baseId=nodeId_415, .dataTypeId=NULL}, {.attrsSize=6, .refsSize=3, .attrs=nodeId_105_attrs, .refs=nodeId_105_refs, .binaryId=nodeId_275, .jsonId=nodeId_453, .baseId=nodeId_16, .dataTypeId=nodeId_105}, }; const struct UA_Nodeset nodeset = { .nodes = nodes, .size = 541, }; #endif #include #include #include #include #ifndef __lbaint_h #define __lbaint_h #include #include #include #include typedef struct LHttpCommand { lua_State *LM; /* The main (global) state */ lua_State* L; /* The thread state for the active request */ HttpCommand* cmd; /* the active C request/response */ /* The relPath from the current directory. Set if executing an LSP * page, NULL if executing a dir func. */ const char* curLspPathname; HttpDir* curDir; int threadRef; /* Reference for the above L */ int envRef; /* _ENV */ BaBool isInLspPage; BaBool stopRequest; /*Set if forward or sendredirect wants to stop (abort)*/ } LHttpCommand; #define LHttpCommand_toCmd(L,ix) \ ((LHttpCommand*)baluaENV_checkudata(L, ix, BA_THTTPCMD)) #define LHttpCommand_check(L,ix) \ LHttpCommand_checkCmd(L,LHttpCommand_toCmd(L,ix)) LHttpCommand* LHttpCommand_checkCmd(lua_State* L,void* deviceattribute); void LHttpCommand_stopRequest(LHttpCommand* deviceattribute, lua_State* L); LHttpCommand* LHttpCommand_create(lua_State* LM, HttpCommand* cmd); int LHttpCommand_error(lua_State *L); #define LHttpCommand_release(deviceattribute) lua_settop(deviceattribute->L,1) int balua_pushstatus(lua_State* L, int ret); int balua_preprocess(lua_State* L, const char* buf, int timer0interrupt); int LSessionENV_push(lua_State* L, HttpSession* s); void baiolib_register(lua_State *L); void LHttpDir_register(lua_State *L); void LTimer_register(lua_State *L); void ljsonlib_register(lua_State* L); void luaopen_ba_create(lua_State *L); void luaopen_ba_aes(lua_State* L); void luaopen_ba_misc(lua_State *L); void luaopen_ba_io(lua_State *L); void luaopen_ba_json(lua_State* L); void luaopen_ba_xmlrpc(lua_State* L); void luaopen_ba_timer(lua_State* L); int luaopen_xparser(lua_State *L); void luaopen_ba_datetime(lua_State *L); int ljsonlibTabEncode(lua_State* L, BufPrint* b, int rd12rm0noflags, int modifycaller); #define LUserIntf_check(L,ix) \ ((UserIntf*)baluaENV_checkudata(L,ix,BA_TUSERINTF)) #define LAuthorizerIntf_check(L,ix) \ (AuthorizerIntf*)baluaENV_checkudata(L, ix, BA_TAUTHORIZERINTF) #endif #ifndef __xparser_h #define __xparser_h #ifndef XPARSER_ALLOC #define XPARSER_ALLOC 2 #endif #ifdef __cplusplus extern "\103" { #endif struct xparser_context; typedef struct xparser_context xparser; enum xparser_event { xparserNOEVENT = 0, xparserINIT, xparserRESET, xparserTERM, xparserSTART, xparserXML, xparserSTART_ELEMENT, xparserEND_ELEMENT, xparserEMPTY_ELEMENT, xparserPI, xparserCOMMENT, xparserCDATA, xparserTEXT, xparserLAST }; typedef enum xparser_event xparser_event; extern const char* const clonewrapper[xparserLAST]; typedef int (*xparser_callback)( xparser* parser, void* fixupfinal, xparser_event event, const char* gpio1config, const char** attr, const char* alloccontroller); typedef xparser_callback xparser_handlers[xparserLAST]; enum xparser_textmode {xparserPRESERVE=0,xparserSKIPBLANK=1,xparserTRIM=2}; xparser* xparser_create(void); int xparser_init(xparser* parser, xparser_handlers* uncorrectedframe, void* fixupfinal,unsigned int enablechannel); int xparser_term(xparser* parser); void xparser_destroy(xparser* parser); int xparser_reset(xparser* parser, int vtimercntvoff); int xparser_parse(xparser* parser,const char* resourceaddress64, size_t globalgpios); const char* xparser_errormsg(xparser* parser); unsigned int xparser_line(xparser* parser); unsigned int xparser_col(xparser* parser); size_t xparser_count(xparser* parser); unsigned int xparser_depth(xparser* parser); unsigned int xparser_flags(xparser* parser); int xparser_has_doc(xparser* parser); void* xparser_userdata(xparser* parser); #ifdef __DOXYGEN__ #else #endif #if XPARSER_ALLOC typedef void * (*xparser_alloc) ( void *ud, void *ptr, size_t hugetlbvalid, size_t ahashsetkey); void xparser_setalloc(xparser_alloc pa,void* ud); #endif #ifdef __cplusplus } #endif #endif #ifndef allocationdirection #define allocationdirection #include "SharkSSL_cfg.h" #include "TargConfig.h" #if (defined(B_LITTLE_ENDIAN)) #if (defined(B_BIG_ENDIAN)) #error B_LITTLE_ENDIAN and B_BIG_ENDIAN cannot be both #defined at the same widgetactive #endif #define setupcmdline(w) (*(U8*)((U8*)(&(w)) + 3)) #define exceptionupdates(w) (*(U8*)((U8*)(&(w)) + 2)) #define iisv4resource(w) (*(U8*)((U8*)(&(w)) + 1)) #define translationfault(w) (*(U8*)((U8*)(&(w)) + 0)) #elif (defined(B_BIG_ENDIAN)) #define setupcmdline(w) (*(U8*)((U8*)(&(w)) + 0)) #define exceptionupdates(w) (*(U8*)((U8*)(&(w)) + 1)) #define iisv4resource(w) (*(U8*)((U8*)(&(w)) + 2)) #define translationfault(w) (*(U8*)((U8*)(&(w)) + 3)) #else #define setupcmdline(w) ((U8)((w) >> 24)) #define exceptionupdates(w) ((U8)((w) >> 16)) #define iisv4resource(w) ((U8)((w) >> 8)) #define translationfault(w) ((U8)((w))) #endif #if (__COLDFIRE__) static inline asm U32 __declspec(register_abi) blocktemplate (U32 d) { byterev.l d0 } #define blockarray blocktemplate #elif (__ICCARM__ && __ARM_PROFILE_M__) #include #define blockarray __REV #define __sharkssl_packed __packed #if ((__CORE__==__ARM7M__) || (__CORE__==__ARM7EM__)) #ifndef SHARKSSL_AES_DISABLE_SBOX #define SHARKSSL_AES_DISABLE_SBOX 1 #endif #endif #elif (__CC_ARM && __TARGET_PROFILE_M) #define blockarray __rev #define __sharkssl_packed __packed #if ((__TARGET_ARCH_ARM == 0) && (__TARGET_ARCH_THUMB == 4)) #ifndef SHARKSSL_AES_DISABLE_SBOX #define SHARKSSL_AES_DISABLE_SBOX 1 #endif #endif #elif (__ICCRX__) static volatile inline U32 blocktemplate(U32 videoprobe) { asm ("\122\105\126\114\040\045\060\054\040\045\060" : "\053\162"(videoprobe)); return videoprobe; } #define blockarray blocktemplate #elif (__GNUC__) #if !defined(_OSX_) && GCC_VERSION >= 402 #ifdef __bswap_32 #define blockarray (U32)__bswap_32 #else #include #define blockarray (U32)__builtin_bswap32 #endif #endif #endif #ifndef __sharkssl_packed #define __sharkssl_packed #endif #ifndef blockarray #define blockarray(x) (((x) >> 24) | (((x) << 8) & 0x00FF0000) | (((x) >> 8) & 0x0000FF00) | ((x) << 24)) #endif #if (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define cleanupcount(w,a,i) (w) = ((__sharkssl_packed U32*)(a))[(i) >> 2] #elif (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define cleanupcount(w,a,i) (w) = blockarray(((__sharkssl_packed U32*)(a))[(i) >> 2]) #else #define cleanupcount(w,a,i) \ { \ (w) = ((U32)(a)[(i)]) \ | ((U32)(a)[(i) + 1] << 8) \ | ((U32)(a)[(i) + 2] << 16) \ | ((U32)(a)[(i) + 3] << 24); \ } #endif #if (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define hsotgpdata(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = (w) #elif (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define hsotgpdata(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = blockarray(w) #else #define hsotgpdata(w,a,i) \ { \ (a)[(i)] = (U8)((w)); \ (a)[(i) + 1] = (U8)((w) >> 8); \ (a)[(i) + 2] = (U8)((w) >> 16); \ (a)[(i) + 3] = (U8)((w) >> 24); \ } #endif #if (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define read64uint32(w,a,i) (w) = ((__sharkssl_packed U32*)(a))[(i) >> 2] #elif (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define read64uint32(w,a,i) (w) = blockarray(((__sharkssl_packed U32*)(a))[(i) >> 2]) #else #define read64uint32(w,a,i) \ { \ (w) = ((U32)(a)[(i)] << 24) \ | ((U32)(a)[(i) + 1] << 16) \ | ((U32)(a)[(i) + 2] << 8) \ | ((U32)(a)[(i) + 3]); \ } #endif #if (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define inputlevel(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = (w) #elif (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define inputlevel(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = blockarray(w) #else #define inputlevel(w,a,i) \ { \ (a)[(i)] = (U8)((w) >> 24); \ (a)[(i) + 1] = (U8)((w) >> 16); \ (a)[(i) + 2] = (U8)((w) >> 8); \ (a)[(i) + 3] = (U8)((w)); \ } #endif #if (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define detectboard(w,a,i) (w) = ((__sharkssl_packed U64*)(a))[(i) >> 3] #elif (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define detectboard(w,a,i) (w) = ((U64)(blockarray(((__sharkssl_packed U32*)(a))[(i) >> 2])) << 32) + \ (blockarray(((__sharkssl_packed U32*)(a))[((i) >> 2) + 1])) #else #define detectboard(w,a,i) \ { \ (w) = ((U64)(a)[(i)] << 56) \ | ((U64)(a)[(i) + 1] << 48) \ | ((U64)(a)[(i) + 2] << 40) \ | ((U64)(a)[(i) + 3] << 32) \ | ((U64)(a)[(i) + 4] << 24) \ | ((U64)(a)[(i) + 5] << 16) \ | ((U64)(a)[(i) + 6] << 8) \ | ((U64)(a)[(i) + 7]); \ } #endif #if (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define hwmoddisable(w,a,i) ((__sharkssl_packed U64*)(a))[(i) >> 3] = (w) #elif (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define hwmoddisable(w,a,i) ((__sharkssl_packed U32*)(a))[((i) >> 2) + 1] = blockarray(*(__sharkssl_packed U32*)&(w)); \ ((__sharkssl_packed U32*)(a))[(i) >> 2] = blockarray(*(__sharkssl_packed U32*)((__sharkssl_packed U32*)&(w) + 1)) #else #define hwmoddisable(w,a,i) \ { \ (a)[(i)] = (U8)((w) >> 56); \ (a)[(i) + 1] = (U8)((w) >> 48); \ (a)[(i) + 2] = (U8)((w) >> 40); \ (a)[(i) + 3] = (U8)((w) >> 32); \ (a)[(i) + 4] = (U8)((w) >> 24); \ (a)[(i) + 5] = (U8)((w) >> 16); \ (a)[(i) + 6] = (U8)((w) >> 8); \ (a)[(i) + 7] = (U8)((w)); \ } #endif #if defined(__LP64__) && !defined(SHARKSSL_64BIT) #define SHARKSSL_64BIT #endif #ifdef SHARKSSL_64BIT #define UPTR U64 #define SHARKSSL_ALIGNMENT 4 #endif #ifndef UPTR #define UPTR U32 #endif #ifndef SHARKSSL_ALIGNMENT #define SHARKSSL_ALIGNMENT 4 #endif #define claimresource(s) (((s) + (SHARKSSL_ALIGNMENT - 1)) & ((U32)-SHARKSSL_ALIGNMENT)) #define regulatorconsumer(p) (U8*)(((UPTR)((UPTR)(p) + SHARKSSL_ALIGNMENT - 1)) & ((UPTR)-SHARKSSL_ALIGNMENT)) #define pcmciaplatform(p) (0 == ((unsigned int)(UPTR)(p) & (SHARKSSL_ALIGNMENT - 1))) #if (SHARKSSL_BIGINT_WORDSIZE > 32) #error SHARKSSL_BIGINT_WORDSIZE must be 32, 16 or 8 #elif (SHARKSSL_BIGINT_WORDSIZE == 64) #define computereturn 7 #else #define computereturn ((U32)(SHARKSSL_BIGINT_WORDSIZE / 10)) #endif #if SHARKSSL_UNALIGNED_MALLOC #define pcmciapdata(s) ((s) + SHARKSSL_ALIGNMENT) #define selectaudio(p) regulatorconsumer(p) #else #define pcmciapdata(s) (s) #define selectaudio(p) (U8*)(p) #endif #if (SHARKSSL_BIGINT_WORDSIZE >= 32) #define HEX4_TO_WORDSIZE(a,b,c,d) 0x##a##b##c##d #define HEX2_TO_WORDSIZE(a,b) 0x##a##b #elif (SHARKSSL_BIGINT_WORDSIZE == 16) #define HEX4_TO_WORDSIZE(a,b,c,d) 0x##a##b, 0x##c##d #define HEX2_TO_WORDSIZE(a,b) 0x##a##b #elif (SHARKSSL_BIGINT_WORDSIZE == 8) #define HEX4_TO_WORDSIZE(a,b,c,d) 0x##a, 0x##b, 0x##c, 0x##d #define HEX2_TO_WORDSIZE(a,b) 0x##a, 0x##b #endif #if ((SHARKSSL_BIGINT_WORDSIZE == 8) || defined(B_BIG_ENDIAN)) #define memmove_endianess memmove #else void memmove_endianess(U8 *d, const U8 *s, U16 len); #endif #endif #ifndef hwmodlookup #define hwmodlookup #include "SharkSSL.h" #include "SharkSslCrypto.h" #define hsmmcplatform 0x40 #define sleepstore 0x80 #define cpucfgexits 0x04 #define signalpreserve 0x04 #define switcheractive 0x08 #define iommupdata 0x10 #define fixupdevices 0x20 typedef struct SharkSslCertEnum { SharkSslCert cert; U16 certLen; U8 priv_notFirstCertFlag; U8 priv_chainLen; } SharkSslCertEnum; #define registerautodeps(o, c) do { \ (o)->cert = c; \ (o)->certLen = SharkSslCert_len(c); \ (o)->priv_notFirstCertFlag = (o)->priv_chainLen = 0; \ } while (0) #define updatesctlr(o) ((o)->cert) #define SharkSslCertEnum_getCertLength(o) ((o)->certLen) SharkSslCert removerecursive(SharkSslCertEnum *o); #define mousethresh(e) (U16)((e) & 0x00FF) #define mcbspregister(e) (U16)(((U16)(e) & 0x0F00) >> 8) #define monadiccheck(e) (U16)(((U16)(e) & 0xF000) >> 12) #define rewindsingle 0x0 #define ts409partitions 0x2 #define mutantchannel 0x6 #define cacherange 0x8 #if SHARKSSL_ENABLE_RSA #if (SHARKSSL_KEYTYPE_RSA != rewindsingle) #error incoherency between SHARKSSL_KEYTYPE_RSA in SharkSSL.h and rewindsingle in SharkSslCert.h #endif #endif #if SHARKSSL_USE_ECC #if (SHARKSSL_KEYTYPE_EC != ts409partitions) #error incoherency between SHARKSSL_KEYTYPE_EC in SharkSSL.h and ts409partitions in SharkSslCert.h #endif #endif #define coupledexynos(e) (mcbspregister(e) & cacherange) #define allocatoralloc(e) (mcbspregister(e) & mutantchannel) #define machinekexec(e) (allocatoralloc(e) == rewindsingle) #define machinereboot(e) (allocatoralloc(e) == ts409partitions) #define specialmapping(e) (e |= (U16)(rewindsingle + cacherange) << 8) #define cryptoresources(e) (e |= (U16)(rewindsingle) << 8) #define deltaticks(e) (e |= (U16)(ts409partitions + cacherange) << 8) #define hsspidevice(e) (e |= (U16)(ts409partitions) << 8) #define gpiolibbanka(e, l) (e = (e & 0xFF00) | (l & 0xFF)) #define attachdevice(m) (U16)((m) & 0x00FF) #define supportedvector(m) (m) #define wakeupenable(m) (U16)(((U16)(m) & 0xFF00) >> 8) #define camerareset(m) 0 #define loaderbinfmt(m, e) (machinereboot(e) ? attachdevice(m) : supportedvector(m)) #define targetoracle(m, e) (machinereboot(e) ? wakeupenable(m) : camerareset(m)) #define nomsrnoirq(m, o) (m = (((U16)o & 0xFF) << 8) | (m & 0xFF)) #define dcdc1consumers(m, l) (m = (m & 0xFF00) | (l & 0xFF)) #if (SHARKSSL_ENABLE_CA_LIST || SHARKSSL_ENABLE_CERTSTORE_API) #define SHARKSSL_CA_LIST_NAME_SIZE 8 #define SHARKSSL_CA_LIST_ELEMENT_SIZE (SHARKSSL_CA_LIST_NAME_SIZE + 4) #define SHARKSSL_CA_LIST_INDEX_TYPE 0x00 #if (SHARKSSL_ENABLE_CA_LIST && SHARKSSL_ENABLE_CERTSTORE_API) #define SHARKSSL_CA_LIST_PTR_SIZE sizeof(U8*) #define SHARKSSL_CA_LIST_PTR_TYPE 0xAD #define SHARKSSL_MAX_SNAME_LEN 32 #if (SHARKSSL_MAX_SNAME_LEN < SHARKSSL_CA_LIST_NAME_SIZE) #error SHARKS_MAX_SNAME_LEN must be >= SHARKSSL_CA_LIST_NAME_SIZE #endif typedef struct SharkSslCSCert { DoubleLink super; U8 *ptr; /* points to the byte sequence ASN.1 format of the cert */ char name[SHARKSSL_MAX_SNAME_LEN + 1]; /* subject name of the CA */ } SharkSslCSCert; #endif #endif #define entryearly 0x01 #define SHARKSSL_SIGNATUREALGORITHM_RSA_PKCS1 0x01 #define gpio1input 0x02 #define accessactive 0x03 #define SHARKSSL_SIGNATUREALGORITHM_RSA_PSS 0x08 #define SHARKSSL_OID_EC_PUBLIC_KEY 0x0C #define processsdccr 0x00 #define skciphercreate SHARKSSL_HASHID_MD5 #define presentpages SHARKSSL_HASHID_SHA1 #define registershashes 0x03 #define domainnumber SHARKSSL_HASHID_SHA256 #define probewrite SHARKSSL_HASHID_SHA384 #define batterythread SHARKSSL_HASHID_SHA512 #define defaultspectre 0xEE #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) typedef struct SharkSslCertKey { U8 *mod, *exp; U16 modLen, expLen; } SharkSslCertKey; #if SHARKSSL_USE_SHA_512 #define SHARKSSL_MAX_HASH_LEN SHARKSSL_SHA512_HASH_LEN #elif SHARKSSL_USE_SHA_384 #define SHARKSSL_MAX_HASH_LEN SHARKSSL_SHA384_HASH_LEN #else #define SHARKSSL_MAX_HASH_LEN SHARKSSL_SHA256_HASH_LEN #endif typedef struct SharkSslSignature { #if (SHARKSSL_MAX_HASH_LEN > (SHARKSSL_MD5_HASH_LEN + SHARKSSL_SHA1_HASH_LEN)) U8 hash[SHARKSSL_MAX_HASH_LEN]; #else U8 hash[SHARKSSL_MD5_HASH_LEN + SHARKSSL_SHA1_HASH_LEN]; #endif U8 *signature; U16 signLen; U8 signatureAlgo; U8 hashAlgo; } SharkSslSignature; typedef struct SharkSslCertParam { SharkSslCertInfo certInfo; SharkSslCertKey certKey; SharkSslSignature signature; } SharkSslCertParam; typedef struct SharkSslSignParam { SharkSslCertKey *pCertKey; SharkSslSignature signature; } SharkSslSignParam; typedef struct SharkSslClonedCertInfo { SharkSslCertInfo ci; #if SHARKSSL_ENABLE_SESSION_CACHE U16 refcnt; /* counter of valid references */ #endif } SharkSslClonedCertInfo; #endif #if SHARKSSL_ENABLE_DHE_RSA typedef struct SharkSslDHParam { U8 *p; /* prime modulus */ U8 *g; /* generator */ U8 *Y; /* Ys/Yc */ U8 *r; /* random secret */ U16 pLen; /* len of p in bytes */ U16 gLen; /* len of g in bytes */ } SharkSslDHParam; #endif #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) typedef struct SharkSslECDHParam { U8 *XY; /* X[,Y] coordinate[s] */ U8 *k; /* random secret */ U16 xLen; /* len of X, Y, k */ U16 curveType; /* curve ID */ } SharkSslECDHParam; #endif #if SHARKSSL_ENABLE_ECDSA typedef struct SharkSslECDSAParam { U8 *R; /* R coordinate */ U8 *S; /* S coordinate */ U8 *key; /* key (pub/pri) */ U8 *hash; /* message hash */ U16 keyLen; /* len of key,R,S */ U16 hashLen; /* len of hash */ U16 curveType; /* curve ID */ } SharkSslECDSAParam; #endif #if SHARKSSL_ENABLE_RSA SHARKSSL_API int async3clksrc(const SharkSslCertKey *ck, U8 op, U8 *stackchecker); int omap3430common(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe); int writemessage(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe); int clockaccess(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe); int handleguest(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe); #endif #if SHARKSSL_ENABLE_DHE_RSA int SharkSslDHParam_DH(const SharkSslDHParam*, U8 op, U8*); #if SHARKSSL_SSL_SERVER_CODE void SharkSslDHParam_setParam(SharkSslDHParam *dh); #endif #endif #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) int SharkSslECDHParam_ECDH(const SharkSslECDHParam*, U8 op, U8*); #endif #if SHARKSSL_ENABLE_ECDSA int SharkSslECDSAParam_ECDSA(const SharkSslECDSAParam*, U8 op); U16 relocationchain(SharkSslCertKey *disableclock); #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) int checkactions(SharkSslSignParam*); int systemcapabilities(const SharkSslSignParam*); SHARKSSL_API int spromregister(SharkSslCertParam*, const U8*, U32, U8*); U8 SharkSslCertDN_equal(const SharkSslCertDN*, const SharkSslCertDN*); SHARKSSL_API U16 interrupthandler(SharkSslCertKey*, SharkSslCert); #if SHARKSSL_ENABLE_CLIENT_AUTH U8 domainassociate(SharkSslCert, U8*, U16); #endif U8 fixupresources(SharkSslCert, U16, U8*); U16 setupboard(SharkSslCert); U8 realnummemory(SharkSslCon *o, SharkSslClonedCertInfo **outCertInfoPtr); #if SHARKSSL_USE_ECC U8 controllerregister(U16 delayusecs); #endif #endif #endif #ifndef _shtype_t_h #define _shtype_t_h #include "SharkSSL.h" #ifndef SHARKSSL_BIGINT_WORDSIZE #error UNDEFINED SHARKSSL_BIGINT_WORDSIZE #endif #ifndef SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K #error UNDEFINED SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K #endif #ifndef SHARKSSL_BIGINT_MULT_LOOP_UNROLL #error UNDEFINED SHARKSSL_BIGINT_MULT_LOOP_UNROLL #endif #define SHARKSSL_ECC_USE_NIST (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1 || SHARKSSL_ECC_USE_SECP521R1) #define SHARKSSL_ECC_USE_BRAINPOOL (SHARKSSL_ECC_USE_BRAINPOOLP256R1 || SHARKSSL_ECC_USE_BRAINPOOLP384R1 || SHARKSSL_ECC_USE_BRAINPOOLP512R1) #define SHARKSSL_ECC_USE_EDWARDS (SHARKSSL_ECC_USE_CURVE25519 || SHARKSSL_ECC_USE_CURVE448) #if (SHARKSSL_BIGINT_WORDSIZE == 8) typedef U8 shtype_tWord; typedef S8 shtype_tWordS; typedef U16 shtype_tDoubleWord; typedef S16 shtype_tDoubleWordS; #elif (SHARKSSL_BIGINT_WORDSIZE == 16) typedef U16 shtype_tWord; typedef S16 shtype_tWordS; typedef U32 shtype_tDoubleWord; typedef S32 shtype_tDoubleWordS; #elif (SHARKSSL_BIGINT_WORDSIZE == 32) typedef U32 shtype_tWord; typedef S32 shtype_tWordS; typedef U64 shtype_tDoubleWord; typedef S64 shtype_tDoubleWordS; #else #error SHARKSSL_BIGINT_WORDSIZE should be 8, 16 or 32 #endif #if _MSC_VER == 1200 #define anatopdisconnect(a) (a >>= SHARKSSL_BIGINT_WORDSIZE); #elif (((shtype_tDoubleWordS)-1LL >> SHARKSSL_BIGINT_WORDSIZE) & (1LL << SHARKSSL_BIGINT_WORDSIZE)) #define anatopdisconnect(a) (a >>= SHARKSSL_BIGINT_WORDSIZE); #else #define anatopdisconnect(a) do { \ if (a < 0) \ { \ a = ((shtype_tDoubleWord)-1LL ^ (shtype_tWord)-1L) | (a >> SHARKSSL_BIGINT_WORDSIZE); \ } \ else \ { \ a >>= SHARKSSL_BIGINT_WORDSIZE; \ } \ } while (0) #endif typedef struct shtype_t { shtype_tWord *mem, *beg; U16 len; } shtype_t; #define SHARKSSL__M (SHARKSSL_BIGINT_WORDSIZE / 8) #ifdef __cplusplus extern "\103" { #endif #if (SHARKSSL_ENABLE_RSA || (SHARKSSL_USE_ECC && (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS))) shtype_tWord remapcfgspace(const shtype_t *mod); #if SHARKSSL_OPTIMIZED_BIGINT_ASM extern #endif void writebytes(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices, const shtype_t *mod, shtype_tWord mu); #endif #define onenandpartitions(o,enablekernel,d) \ traceaddress(o, (U16)((enablekernel)/SHARKSSL_BIGINT_WORDSIZE),(void*)(d)) #define consoledevice(o) ((o)->beg) #define publishdevices(o) ((o)->len) #define pulsewidth(o) (publishdevices(o) * SHARKSSL__M) #define cachestride(o) (!((o)->beg[(o)->len - 1] & 0x1)) void deviceparse(const shtype_t *o); void blastscache(shtype_t *o); void traceaddress(shtype_t *o, U16 writepmresrn, void *alloccontroller); void unassignedvector(const shtype_t *src, shtype_t *pciercxcfg448); shtype_tWord resolverelocs(shtype_t *o1, const shtype_t *o2); shtype_tWord updatepmull(shtype_t *o1, const shtype_t *o2); void setupsdhci1(shtype_t *o1, const shtype_t *o2, const shtype_t *mod); void keypaddevice(shtype_t *o1, const shtype_t *o2, const shtype_t *mod); U8 timerwrite(const shtype_t *o1, const shtype_t *o2); void hotplugpgtable(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices); void envdatamcheck(shtype_t *injectexception, const shtype_t *mod, shtype_tWord *afterhandler); int suspendfinish(shtype_t *injectexception, const shtype_t *mod); int chunkmutex(const shtype_t *validconfig, shtype_t *exp, const shtype_t *mod, shtype_t *res, U8 countersvalid); void ioswabwdefault(shtype_t *u, const shtype_t *mod, shtype_tWord *afterhandler); void backlightpdata(shtype_t *o); #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) int iommumapping(shtype_t *o, const shtype_t *mod); #endif #if SHARKSSL_ENABLE_ECDSA U8 eventtimeout(shtype_t *o); #endif #if SHARKSSL_ECC_USE_EDWARDS void shtype_t_copyfull(const shtype_t *src, shtype_t *pciercxcfg448); void shtype_t_swapConditional(shtype_t *o1, shtype_t *o2, U32 swapFlag); #endif #if (SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSAKEY_CREATE) int aemifdevice(shtype_t *o); int translateaddress(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices); #endif #ifdef __cplusplus } #endif #endif #ifndef _SharkSslECC_h #define _SharkSslECC_h #include #if SHARKSSL_USE_ECC typedef struct { shtype_t x, y; } SharkSslECPoint; typedef struct SharkSslECCurve { #if SHARKSSL_ECC_USE_EDWARDS /* virtual functions */ int (*setPoint)(struct SharkSslECCurve*, SharkSslECPoint*); int (*multiply)(struct SharkSslECCurve *, shtype_t *, SharkSslECPoint *); #endif shtype_t prime; /* prime */ shtype_t order; /* order */ SharkSslECPoint G; /* base point */ #if (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) shtype_t a; /* parameter a */ #endif #if SHARKSSL_ECC_VERIFY_POINT shtype_t b; /* parameter b */ #endif U16 bits; /* the size of the prime in bits */ } SharkSslECCurve; #define SharkSslECCurve_bits_Montgomery_flag 0x8000 #define SHARKSSL_SECP256R1_POINTLEN 32 #define SHARKSSL_SECP384R1_POINTLEN 48 #define SHARKSSL_SECP521R1_POINTLEN 66 #define SHARKSSL_BRAINPOOLP256R1_POINTLEN 32 #define SHARKSSL_BRAINPOOLP384R1_POINTLEN 48 #define SHARKSSL_BRAINPOOLP512R1_POINTLEN 64 #define SHARKSSL_CURVE25519_POINTLEN 32 #define SHARKSSL_CURVE448_POINTLEN 56 #ifdef __cplusplus extern "\103" { #endif void clearerrors(SharkSslECCurve *o, U16 rightsvalid); int SharkSslECCurve_setPoint_NB(SharkSslECCurve *o, SharkSslECPoint *p); #if SHARKSSL_ECC_USE_EDWARDS int SharkSslECCurve_setPoint_ED(SharkSslECCurve *o, SharkSslECPoint *p); #define initialdomain(o, p) (o)->setPoint(o, p) #else #define initialdomain(o, p) SharkSslECCurve_setPoint_NB(o, p) #endif #if (!SHARKSSL_ECDSA_ONLY_VERIFY) int SharkSslECCurve_multiply_NB(SharkSslECCurve *o, shtype_t *k, SharkSslECPoint *deltadevices); #if SHARKSSL_ECC_USE_EDWARDS int SharkSslECCurve_multiply_ED(SharkSslECCurve *o, shtype_t *k, SharkSslECPoint *deltadevices); #define unregisterskciphers(o,k,r) (o)->multiply(o, k, r) #else #define unregisterskciphers(o,k,r) SharkSslECCurve_multiply_NB(o,k,r) #endif #endif #if SHARKSSL_ENABLE_ECDSA int directalloc(SharkSslECCurve *S, shtype_t *d, SharkSslECCurve *T, shtype_t *e, SharkSslECPoint *deltadevices); #endif #define receivebroadcast(o,w,a,b) \ traceaddress(&((o)->x),(w),(a)); traceaddress(&((o)->y),(w),(b)) #define updatefrequency(o,t,a,b) \ onenandpartitions(&((o)->x),(t),(a)); onenandpartitions(&((o)->y),(t),(b)) #define mipidplatform(s,d) \ unassignedvector(&((s)->x), &((d)->x)); unassignedvector(&((s)->y), &((d)->y)) #ifdef __cplusplus } #endif #endif #endif #ifndef _SharkSslCon_h #define _SharkSslCon_h #define SHARKSSL_LIB 1 #include "SharkSSL.h" #if (SHARKSSL_TLS_1_3 && SHARKSSL_USE_ECC) #endif #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_SSL_CLIENT_CODE) #define SharkSsl_isServer(o) (o->role == SharkSsl_Server) #define SharkSsl_isClient(o) (o->role == SharkSsl_Client) #elif SHARKSSL_SSL_SERVER_CODE #define SharkSsl_isServer(o) (1) #define SharkSsl_isClient(o) (0) #elif SHARKSSL_SSL_CLIENT_CODE #define SharkSsl_isServer(o) (0) #define SharkSsl_isClient(o) (1) #elif ((!SHARKSSL_ENABLE_RSA_API) && (!SHARKSSL_ENABLE_ECDSA_API) && (!SHARKSSL_ENABLE_PEM_API)) #error NEITHER SERVER NOR CLIENT CODE SELECTED #endif #define rangealigned 20 #define firstentry 21 #define controllegacy 22 #define polledbutton 23 #define switchessetup 0 #define pciercxcfg070 1 #define trampolinehandler 2 #define SHARKSSL_HANDSHAKETYPE_NEW_SESSION_TICKET 4 #define SHARKSSL_HANDSHAKETYPE_ENCRYPTED_EXTENSIONS 8 #define parsebootinfo 11 #define startflags 12 #define logicmembank 13 #define configcwfon 14 #define modifygraph 15 #define subtableheaders 16 #define switcherdevice 20 #define loongson3notifier 0xFF #define ahashchild 0x01 #define systemtable 0x02 #define compatrestart 0x40 #define deviceunregister 0x00FF #define cminstclear 0 #define firstversion 0 #define protectionfault 1 #define switchertrace 2 #define pca953xpdata 3 #define mailboxentries 4 #define registerwatchdog 5 #define deviceprobe 6 #define recoverygpiod 7 #define bootloaderentry 8 #define callchainkernel 9 #define registerpwrdms 10 #define pwrdmenable 10 #define edma0resources 11 #define logicpdtorpedo 12 #define entrypaddr 13 #define restoremasks 13 #define moduleflags 14 #define cpucfgsynthesize 15 #define clkdmclear 16 #define queuelogical 17 #define pciercxcfg075 18 #define aa64isar1override 35 #define allocconsistent 41 #define doublefcvts 43 #define rm200hwint 45 #define shutdownnonboot 47 #define consumersupplies 49 #define reboothandler 51 #define featurespresent 0xFF01 #define spannedpages 23 #define ucb1400pdata 23 #define restoretrace 24 #define pciercxcfg034 24 #define buildmemmap 25 #define audiopdata 25 #define samplingevent 26 #define gpio3config 26 #define entrytrampoline 27 #define negativeoffset 27 #define resumeprepare 28 #define sa1111disable 28 #define TLS_NAMEDCURVE_CURVE25519 29 #define TLS_NAMEDGROUP_CURVE25519 29 #define TLS_NAMEDCURVE_CURVE448 30 #define TLS_NAMEDGROUP_CURVE448 30 #define probesystem 0 #define crashsetup 1 #define checkheader 2 #define pchip1present 1 #define targetmemory1 2 #define mcbsp5hwmod 3 #if (!SHARKSSL_ENABLE_RSA) #if SHARKSSL_ENABLE_DHE_RSA #error SHARKSSL_ENABLE_RSA must be selected when SHARKSSL_ENABLE_DHE_RSA is enabled #endif #if SHARKSSL_ENABLE_ECDHE_RSA #error SHARKSSL_ENABLE_RSA must be selected when SHARKSSL_ENABLE_ECDHE_RSA is enabled #endif #endif #if SHARKSSL_USE_ECC #if ((!SHARKSSL_ECC_USE_SECP256R1) && (!SHARKSSL_ECC_USE_SECP384R1) && (!SHARKSSL_ECC_USE_SECP521R1)) #error no elliptic nandflashpartition selected #endif #if (SHARKSSL_ECDSA_ONLY_VERIFY && (SHARKSSL_SSL_CLIENT_CODE || SHARKSSL_SSL_SERVER_CODE)) #error SHARKSSL_ECDSA_ONLY_VERIFY must be 0 when SSL/TLS is enabled #endif #else #if SHARKSSL_ENABLE_ECDHE_RSA #error SHARKSSL_USE_ECC must be selected when SHARKSSL_ENABLE_ECDHE_RSA is enabled #endif #if SHARKSSL_ENABLE_ECDHE_ECDSA #error SHARKSSL_USE_ECC must be selected when SHARKSSL_ENABLE_ECDHE_ECDSA is enabled #endif #if (!SHARKSSL_ENABLE_RSA) #if SHARKSSL_ENABLE_ECDHE_RSA #error SHARKSSL_ENABLE_RSA must be selected when SHARKSSL_ENABLE_ECDHE_RSA is enabled #endif #endif #if SHARKSSL_ENABLE_ECDSA #error SHARKSSL_USE_ECC must be selected when SHARKSSL_ENABLE_ECDSA is enabled #else #if SHARKSSL_ENABLE_ECDHE_ECDSA #error SHARKSSL_ENABLE_ECDSA must be selected when SHARKSSL_ENABLE_ECDHE_ECDSA is enabled #endif #endif #endif #if SHARKSSL_ENABLE_AES_GCM #if (SHARKSSL_USE_AES_128 && SHARKSSL_USE_SHA_256) #if SHARKSSL_TLS_1_3 #define SHARKSSL_AES_128_GCM_SHA256 TLS_AES_128_GCM_SHA256 #endif #if SHARKSSL_TLS_1_2 #if SHARKSSL_ENABLE_DHE_RSA #define branchenable TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 #endif #if SHARKSSL_ENABLE_ECDHE_RSA #define resumenonboot TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 #endif #if SHARKSSL_ENABLE_ECDHE_ECDSA #define enablecharger TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 #endif #endif #endif #if (SHARKSSL_USE_AES_256 && SHARKSSL_USE_SHA_384) #if SHARKSSL_TLS_1_3 #define SHARKSSL_AES_256_GCM_SHA384 TLS_AES_256_GCM_SHA384 #endif #if SHARKSSL_TLS_1_2 #if SHARKSSL_ENABLE_DHE_RSA #define quirkslc90e66 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 #endif #if SHARKSSL_ENABLE_ECDHE_RSA #define mallocalign TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 #endif #if SHARKSSL_ENABLE_ECDHE_ECDSA #define mitigationstate TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 #endif #endif #endif #endif #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) #if SHARKSSL_TLS_1_3 #define SHARKSSL_CHACHA20_POLY1305_SHA256 TLS_CHACHA20_POLY1305_SHA256 #endif #if SHARKSSL_TLS_1_2 #if SHARKSSL_ENABLE_DHE_RSA #define nvramgetenv TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 #endif #if SHARKSSL_ENABLE_ECDHE_RSA #define releasedpages TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 #endif #if SHARKSSL_ENABLE_ECDHE_ECDSA #define kernelrelocation TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 #endif #endif #endif #define resourcebtuart SHARKSSL_MD5_HASH_LEN #define m62332senddata SHARKSSL_SHA1_HASH_LEN #define loongson3cpucfg SHARKSSL_SHA256_HASH_LEN #define gpiocfgdefault SHARKSSL_SHA384_HASH_LEN #define iwmmxtcontext SHARKSSL_SHA512_HASH_LEN #define stateoneshot SHARKSSL_POLY1305_HASH_LEN #define SHARKSSL_FINISHED_MSG_LEN_TLS_1_2 12 #define clkctrlmanaged 5 #define traceentry 4 #define SHARKSSL_MAX_SESSION_ID_LEN 32 #define SHARKSSL_MAX_SESSION_TICKET_LEN 512 #define SHARKSSL_SEQ_NUM_LEN 8 #define SHARKSSL_AES_GCM_EXPLICIT_IV_LEN SHARKSSL_SEQ_NUM_LEN #define SHARKSSL_RANDOM_LEN 32 #define SHARKSSL_MASTER_SECRET_LEN 48 #define SHARKSSL_CERT_LENGTH_LEN 3 #if (SHARKSSL_AES_GCM_EXPLICIT_IV_LEN != SHARKSSL_SEQ_NUM_LEN) #error SHARKSSL_AES_GCM_EXPLICIT_IV_LEN MUST BE = SHARKSSL_SEQ_NUM_LEN #endif #if SHARKSSL_USE_SHA_512 #define SHARKSSL_MAX_DIGEST_LEN iwmmxtcontext #define SHARKSSL_MAX_DIGEST_BLOCK_LEN SHARKSSL_SHA512_BLOCK_LEN #elif SHARKSSL_USE_SHA_384 #define SHARKSSL_MAX_DIGEST_LEN gpiocfgdefault #define SHARKSSL_MAX_DIGEST_BLOCK_LEN SHARKSSL_SHA384_BLOCK_LEN #else #define SHARKSSL_MAX_DIGEST_LEN loongson3cpucfg #define SHARKSSL_MAX_DIGEST_BLOCK_LEN SHARKSSL_SHA256_BLOCK_LEN #endif #if SHARKSSL_TLS_1_3 #if SHARKSSL_USE_SHA_384 #define SHARKSSL_TLS_1_3_MAX_DIGEST_LENGTH gpiocfgdefault #else #define SHARKSSL_TLS_1_3_MAX_DIGEST_LENGTH loongson3cpucfg #endif #endif #define SHARKSSL_MAX_DIGEST_PAD_LEN 48 #define gpio2enable (16348 + 2048) #define SHARKSSL_MAX_DECRYPTED_REC_LEN 16384 #define prefetchwrite SHARKSSL_MAX_BLOCK_LEN #define ckctlrecalc 16 #if SHARKSSL_ENABLE_AES_GCM #define systemcontroller SHARKSSL_SEQ_NUM_LEN #else #define systemcontroller 0 #endif #if (SHARKSSL_USE_AES_256 || (SHARKSSL_USE_POLY1305 && SHARKSSL_USE_CHACHA20)) #define SHARKSSL_MAX_KEY_LEN 32 #elif (SHARKSSL_USE_AES_128) #define SHARKSSL_MAX_KEY_LEN 16 #else #error At least one cipher must be selected in SharkSSL_cfg.h #endif #if (SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256) #define SHARKSSL_MAX_BLOCK_LEN 16 #else #define SHARKSSL_MAX_BLOCK_LEN 0 #endif #define cachewback 1024 #if (SHARKSSL_TLS_1_2 && SHARKSSL_ENABLE_AES_GCM) #define gpio5config SHARKSSL_AES_GCM_EXPLICIT_IV_LEN #else #define gpio5config 0 #endif #ifndef SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH #define SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH 0x10 #endif #define SHARKSSL_HS_PARAM_OFFSET_1_3 0 #define SHARKSSL_HS_PARAM_OFFSET_1_2 claimresource(clkctrlmanaged + 1 + \ clkctrlmanaged + \ SHARKSSL_MAX_BLOCK_LEN + \ SHARKSSL_FINISHED_MSG_LEN_TLS_1_2 + \ SHARKSSL_MAX_DIGEST_LEN + \ prefetchwrite) #if SHARKSSL_TLS_1_2 #define SHARKSSL_HS_PARAM_OFFSET SHARKSSL_HS_PARAM_OFFSET_1_2 #else #define SHARKSSL_HS_PARAM_OFFSET SHARKSSL_HS_PARAM_OFFSET_1_3 #endif #define clockgettime32 0x00000001 #define audiosuspend 0x00000002 #define cachematch 0x00000004 #define shutdownlevel 0x00000008 #define SHARKSSL_FLAG_FRAGMENTED_HS_RECORD 0x00000010 #define firstcomponent 0x00000020 #define switcherregister 0x00000040 #define stealenabled 0x00000080 #define probedaddress 0x00000100 #define startqueue 0x00000200 #define unregistershash 0x00000400 #define nresetconsumers 0x00000800 #define accountsoftirq 0x00001000 #define serialreset 0x00002000 #define switcheractivation 0x00004000 #define aarch32ptrace 0x00008000 #define registerbuses 0x00010000 #define skciphersetkey 0x00020000 #define platformdevice 0x00040000 #define createmappings 0x00080000 #define gpiolibmbank 0x00100000 #define devicedriver 0x00200000 #define uprobeabort 0x00400000 #define symbolnodebug 0x00800000 #define ftracehandler 0x01000000 #define SHARKSSL_FLAG_CA_EXTENSION_REQUEST 0x02000000 #define SHARKSSL_FLAG_PARTIAL_HS_SEND 0x04000000 #define SHARKSSL_FLAG_FORCE_SERVER_PROTOCOL 0x08000000 #define bcm1x80bcm1x55 0x01 #define boardcompat 0x02 #define SHARKSSL_OP_CONSTRUCTOR_FLAG 0x10 #define ptraceregsets 0x20 #define populatebasepages 0x40 #define chargerworker (bcm1x80bcm1x55 | boardcompat) #define SHARKSSL_OP_CONSTRUCTOR (bcm1x80bcm1x55 | SHARKSSL_OP_CONSTRUCTOR_FLAG) #define cleandcache 0x0001 #define irqhandlerfixup 0x0002 #define cpufreqcallback 0x0004 #define percpudevid 0x0008 #define SHARKSSL_CS_SHA256 0x0010 #define framekernel 0x0020 #define suspendenter 0x0040 #define SHARKSSL_CS_TLS13 0x0080 #define overcommitmemory 0x0100 #define ioasicclocksource 0x0200 #define keypadrelease 0x0400 #define da9034backlight 0x0800 #define recoverrange 0x1000 typedef struct SharkSslBuf { #if SHARKSSL_UNALIGNED_MALLOC U8 *mem; /* where the allocated memory begins in this case */ #endif U8 *buf; /* where the allocated memory begins */ U8 *data; /* where the data begins */ U16 size; /* number of bytes in the buffer available to the user */ U16 dataLen; /* length of the data to be processed */ U16 temp; } SharkSslBuf; void atomiccmpxchg(SharkSslBuf*, U16); void guestconfig5(SharkSslBuf*); #if (!SHARKSSL_DISABLE_INBUF_EXPANSION) U8 *othersegments(SharkSslBuf*, U16); #endif void binaryheader(SharkSslBuf*); #define microresources(o) (!((o)->buf)) #define func3fixup(o) \ ((o)->buf + gpio5config) #define serial2platform(o) \ ((o)->data == func3fixup(o)) #define registerfixed(o) do {\ (o)->data = func3fixup(o); \ } while (0) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION #define reportsyscall(pciercxcfg448, src) \ memcpy((U8*)((pciercxcfg448)->buf), (U8*)((src)->buf), gpio5config) #endif typedef int (*SharkSslCon_cipherFunc)(SharkSslCon*, U8, U8*, U16); typedef struct SharkSslCipherSuite { SharkSslCon_cipherFunc cipherFunc; U16 id; U16 flags; U8 keyLen; U8 digestLen; U8 hashID; } SharkSslCipherSuite; #if SHARKSSL_TLS_1_2 U16 disableclean(SharkSslCipherSuite*); #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) typedef struct SharkSslCertParsed { SharkSslCert cert; U16 msgLen; /* certificate message length */ U8 keyType; U8 keyOID; U8 signatureAlgo; U8 hashAlgo; #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) const U8 *commonName; U8 *subjectAltNamesPtr; U16 subjectAltNamesLen; U8 commonNameLen; /** length in bytes of the field "commonName" */ #endif } SharkSslCertParsed; typedef struct SharkSslCertList { SingleLink link; SharkSslCertParsed certP; } SharkSslCertList; #endif typedef struct SharkSslHSParam { union { #if SHARKSSL_TLS_1_2 struct { U8 clientRandom[SHARKSSL_RANDOM_LEN]; U8 serverRandom[SHARKSSL_RANDOM_LEN]; U8 masterSecret[SHARKSSL_MASTER_SECRET_LEN]; U8 sharedSecret[2 * (SHARKSSL_MAX_DIGEST_LEN + SHARKSSL_MAX_KEY_LEN + SHARKSSL_MAX_BLOCK_LEN) + SHARKSSL_MAX_DIGEST_LEN]; #if SHARKSSL_USE_SHA_512 SharkSslSha512Ctx sha512Ctx; #endif #if SHARKSSL_ENABLE_DHE_RSA SharkSslDHParam dhParam; #endif } tls12; #endif #if SHARKSSL_TLS_1_3 struct { U8 HSSecret[SHARKSSL_TLS_1_3_MAX_DIGEST_LENGTH]; U8 srvHSTraffic[SHARKSSL_TLS_1_3_MAX_DIGEST_LENGTH]; U8 cliHSTraffic[SHARKSSL_TLS_1_3_MAX_DIGEST_LENGTH]; #if SHARKSSL_USE_ECC #if SHARKSSL_ECC_USE_CURVE448 U8 privKeyCURVE448[SHARKSSL_CURVE448_POINTLEN]; #endif #if SHARKSSL_ECC_USE_CURVE25519 U8 privKeyCURVE25519[SHARKSSL_CURVE25519_POINTLEN]; #endif #if SHARKSSL_ECC_USE_SECP384R1 U8 privKeySECP384R1[SHARKSSL_SECP384R1_POINTLEN]; #endif #if SHARKSSL_ECC_USE_SECP256R1 U8 privKeySECP256R1[SHARKSSL_SECP256R1_POINTLEN]; #endif #endif /* SHARKSSL_USE_ECC */ #if SHARKSSL_ENABLE_CLIENT_AUTH U16 signatureScheme; #endif #if SHARKSSL_SSL_SERVER_CODE U16 grpLen; U8 *grpPtr; #endif } tls13; #endif } prot; #if SHARKSSL_RANDOMIZE_EXTENSIONS #define SHARKSSL_MAX_EXTENSIONS 8 /* multiple of 4 to keep alignment */ #if (SHARKSSL_BIGINT_WORDSIZE < 32) U16 extState; #else U32 extState; #endif U8 extIndex[SHARKSSL_MAX_EXTENSIONS]; #endif SharkSslSha256Ctx sha256Ctx; #if SHARKSSL_USE_SHA_384 SharkSslSha384Ctx sha384Ctx; #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) SharkSslCertParsed *certParsed; /* the selected cert */ SharkSslCertKey certKey; /* points to cert's key */ SharkSslCertParam certParam; /* peer's cert */ SharkSslSignParam signParam; #endif #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) SharkSslECDHParam ecdhParam; #endif SharkSslCipherSuite *cipherSuite; } SharkSslHSParam; void breakpointhandler(SharkSslHSParam*); void alignmentldmstm(SharkSslHSParam*); void ioremapresource(SharkSslHSParam*, U8*, U16); int wakeupvector(SharkSslHSParam*, U8*, U8); #define hsParam(o) ((SharkSslHSParam*)(func3fixup(&o->outBuf) + SHARKSSL_HS_PARAM_OFFSET)) #if SHARKSSL_ENABLE_SESSION_CACHE struct SharkSslSession { SharkSslCipherSuite *cipherSuite; U32 firstAccess; U16 nUse; U8 major_minor, flags; SharkSslClonedCertInfo *clonedCertInfo; union { struct { U32 latestAccess; U8 id[SHARKSSL_MAX_SESSION_ID_LEN]; U8 masterSecret[SHARKSSL_MASTER_SECRET_LEN]; } tls12; struct { U32 expiration, ticketAgeAdd; U8 PSK[SHARKSSL_MAX_DIGEST_LEN]; U8 *ticket; U16 ticketLen, link; } tls13; } prot; }; void SharkSslSession_copyClonedCertInfo(SharkSslSession*, SharkSslCon*); #define SharkSslSession_isProtocol(o,prot) ((o)->major_minor == (prot)) #define restarthandler(o,maj,min) ((o)->major_minor == (((maj & 0x0F) << 4) | (min & 0x0F))) #define batterylevels(o) (SHARKSSL_PROTOCOL_MAJOR((o)->major_minor)) #define hardirqsenabled(o) (SHARKSSL_PROTOCOL_MINOR((o)->major_minor)) #define sha224final(o,maj,min) do { \ baAssert((maj <= 0x0F) && (min <= 0x0F)); \ (o)->major_minor = (((maj & 0x0F) << 4) | (min & 0x0F)); \ } while (0); #define ecoffaouthdr 0x80 void counter1clocksource(SharkSslSessionCache*, U16); void defaultsdhci0(SharkSslSessionCache*); #define filtermatch(o) ThreadMutex_set(&((o)->cacheMutex)) #define helperglobal(o) ThreadMutex_release(&((o)->cacheMutex)) SharkSslSession *sa1111device(SharkSslSessionCache*, SharkSslCon*, U8*, U16); SharkSslSession *latchgpiochip(SharkSslSessionCache*, SharkSslCon*, U8*, U16); #endif struct SharkSslCon { #if SHARKSSL_MAX_BLOCK_LEN #if ((SHARKSSL_MAX_BLOCK_LEN < 16) && (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305)) U8 rIV[16]; #else U8 rIV[SHARKSSL_MAX_BLOCK_LEN]; #endif #elif (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) U8 rIV[16]; #endif #if SHARKSSL_MAX_KEY_LEN U8 rKey[SHARKSSL_MAX_KEY_LEN]; #endif #if SHARKSSL_MAX_BLOCK_LEN #if ((SHARKSSL_MAX_BLOCK_LEN < 16) && ((SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) || SHARKSSL_ENABLE_AES_GCM)) U8 wIV[16]; #else U8 wIV[SHARKSSL_MAX_BLOCK_LEN]; #endif #elif ((SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) || SHARKSSL_ENABLE_AES_GCM) U8 wIV[16]; #endif #if SHARKSSL_MAX_KEY_LEN U8 wKey[SHARKSSL_MAX_KEY_LEN]; #endif U8 rSeqNum[SHARKSSL_SEQ_NUM_LEN]; #if (SHARKSSL_TLS_1_3 || (SHARKSSL_TLS_1_2 && (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305))) U8 wSeqNum[SHARKSSL_SEQ_NUM_LEN]; /* not used by AES-GCM in TLS 1.2 */ #endif #if SHARKSSL_TLS_1_3 U8 masterSecret[SHARKSSL_MAX_DIGEST_LEN]; #endif SharkSsl *sharkSsl; SharkSslCipherSuite *rCipherSuite, *wCipherSuite; #if SHARKSSL_ENABLE_SESSION_CACHE #if SHARKSSL_TLS_1_3 U8 resumptionMasterSecret[SHARKSSL_MAX_DIGEST_LEN]; #endif SharkSslSession *session; #endif void *rCtx, *wCtx; #if SHARKSSL_UNALIGNED_MALLOC SharkSslCon *mem; #endif #if SHARKSSL_ENABLE_ALPN_EXTENSION const char *pALPN; const char *rALPN; #if SHARKSSL_SSL_SERVER_CODE ALPNFunction fALPN; #endif #endif #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION U8 clientVerifyData[SHARKSSL_FINISHED_MSG_LEN_TLS_1_2]; U8 serverVerifyData[SHARKSSL_FINISHED_MSG_LEN_TLS_1_2]; #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) SharkSslClonedCertInfo *clonedCertInfo; #endif #if (SHARKSSL_ENABLE_CA_EXTENSION && SHARKSSL_ENABLE_CA_LIST) SharkSslCAList caListCertReq; #endif SharkSslBuf inBuf, outBuf; #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION SharkSslBuf tmpBuf; #endif U32 flags; U16 padLen; U8 state; U8 reqMajor, reqMinor; U8 major, minor; U8 alertLevel, alertDescr; #if ((SHARKSSL_SSL_SERVER_CODE || SHARKSSL_SSL_CLIENT_CODE) && SHARKSSL_ENABLE_SELECT_CIPHERSUITE) #if (SHARKSSL_SELECT_CIPHERSUITE_LIST_DEPTH > 0xFF) #error SHARKSSL_SELECT_CIPHERSUITE_LIST_DEPTH must be lower than 256 #endif U8 cipherSelCtr; U8 cipherSelection[SHARKSSL_SELECT_CIPHERSUITE_LIST_DEPTH]; #endif #if SHARKSSL_ERRORLINE_DEBUG int errLine; #endif }; typedef enum { tvp5146routes, rodatastart } SharkSslCon_SendersRole; #define SharkSsl_createCon2(o, sharkSslCon) do {\ (o)->nCon++;\ conditionvalid(sharkSslCon, o);\ } while (0) void conditionvalid(SharkSslCon *o, SharkSsl *resetcounters); void localenable(SharkSslCon *o); SharkSslCon_RetVal savedconfig(SharkSslCon*, U8); SharkSslCon_RetVal securememblock(SharkSslCon*, U8, U8); SharkSslCon_RetVal configdword(SharkSslCon*, U8*, U16); SharkSslCon_RetVal kexecprotect(SharkSslCon*, U8*, U16); U8 *templateentry(SharkSslCon*, U8, U8*, U16); #if SHARKSSL_TLS_1_3 int SharkSslCon_calcMACAndEncryptHS(SharkSslCon*); int SharkSslCon_calcAppTrafficSecret(SharkSslCon*, U8*); int SharkSslCon_calcHandshakeTrafficSecret(SharkSslCon*); #if SHARKSSL_ENABLE_SESSION_CACHE int SharkSslCon_calcResumptionSecret(SharkSslCon*, U8*); int SharkSslCon_calcTicketPSK(SharkSslCon*, U8*, U8*, U8); int SharkSslCon_calcEarlySecret(SharkSslCon*, U8*, U8); #endif #endif #if SHARKSSL_TLS_1_2 int allocalloc(SharkSslCon*, U8*, U16, U8*, U16, U8[32], U8[32]); int sanitisependbaser(SharkSslCon *o, SharkSslCon_SendersRole, U8*); #endif #if SHARKSSL_ENABLE_SELECT_CIPHERSUITE int sharkssl_protocol_ciphersuite(U8, U8); #endif int printsilicon(SharkSslCon*, SharkSslCon_SendersRole, U8*); int SharkSslCon_calcMACAndEncrypt(SharkSslCon*); #if SHARKSSL_TLS_1_3 #define SharkSslCon_ccLen13(o) claimresource(clkctrlmanaged + ckctlrecalc + SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH + 1) #endif #if SHARKSSL_TLS_1_2 #define SharkSslCon_ccLen12(o) claimresource(clkctrlmanaged + ckctlrecalc + systemcontroller) #endif #ifndef SharkSslCon_ccLen13 #define SharkSslCon_ccLen13(o) 0 #endif #ifndef SharkSslCon_ccLen12 #define SharkSslCon_ccLen12(o) 0 #endif #if (SharkSslCon_ccLen13(0) >= SharkSslCon_ccLen12(0)) #define r3000tlbchange(o) SharkSslCon_ccLen13(o) #else #define r3000tlbchange(o) SharkSslCon_ccLen12(o) #endif void fpemureturn(SharkSslCon*); #if SHARKSSL_ERRORLINE_DEBUG #define debugdestroy(o) (o)->errLine #define resvdexits(o) (debugdestroy(o) = (int)__LINE__) #else #define debugdestroy(o) 0 #define resvdexits(o) #endif #if ((SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256) && SHARKSSL_ENABLE_AES_GCM) int offsetkernel(SharkSslCon*, U8, U8*, U16); #endif #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) int updatecontext(SharkSslCon*, U8, U8*, U16); #endif #endif #ifndef BA_LIB #define BA_LIB #endif #if SHARKSSL_USE_ECC #endif #include #define SHARKSSL_DIM_ARR(a) (sizeof(a)/sizeof(a[0])) #define _SHARKSSLCON_HS_C_ #ifndef _SharkSslCipher_h #define _SharkSslCipher_h #ifdef _SHARKSSLCON_HS_C_ static const SharkSslCipherSuite genericsuspend[] = { #if SHARKSSL_TLS_1_3 #if SHARKSSL_AES_256_GCM_SHA384 { offsetkernel, SHARKSSL_AES_256_GCM_SHA384, SHARKSSL_CS_TLS13 | irqhandlerfixup | cleandcache | cpufreqcallback | framekernel | ioasicclocksource, 32, 16, SHARKSSL_HASHID_SHA384 }, #endif #if SHARKSSL_AES_128_GCM_SHA256 { offsetkernel, SHARKSSL_AES_128_GCM_SHA256, SHARKSSL_CS_TLS13 | irqhandlerfixup | cleandcache | cpufreqcallback | framekernel | SHARKSSL_CS_SHA256, 16, 16, SHARKSSL_HASHID_SHA256 }, #endif #if SHARKSSL_CHACHA20_POLY1305_SHA256 { updatecontext, SHARKSSL_CHACHA20_POLY1305_SHA256, SHARKSSL_CS_TLS13 | irqhandlerfixup | cleandcache | cpufreqcallback | suspendenter, 32, 16, SHARKSSL_HASHID_SHA256 }, #endif #endif #if SHARKSSL_TLS_1_2 #if SHARKSSL_ENABLE_ECDHE_ECDSA #if kernelrelocation { updatecontext, kernelrelocation, overcommitmemory | irqhandlerfixup | cleandcache | cpufreqcallback | suspendenter, 32, 16, SHARKSSL_HASHID_SHA256 }, #endif #if mitigationstate { offsetkernel, mitigationstate, overcommitmemory | irqhandlerfixup | cleandcache | cpufreqcallback | framekernel | ioasicclocksource, 32, 16, SHARKSSL_HASHID_SHA384 }, #endif #if enablecharger { offsetkernel, enablecharger, overcommitmemory | irqhandlerfixup | cleandcache | cpufreqcallback | framekernel, 16, 16, SHARKSSL_HASHID_SHA256 }, #endif #endif #if SHARKSSL_ENABLE_RSA #if releasedpages { updatecontext, releasedpages, overcommitmemory | irqhandlerfixup | cleandcache | percpudevid | suspendenter, 32, 16, SHARKSSL_HASHID_SHA256 }, #endif #if mallocalign { offsetkernel, mallocalign, overcommitmemory | irqhandlerfixup | cleandcache | percpudevid | framekernel | ioasicclocksource, 32, 16, SHARKSSL_HASHID_SHA384 }, #endif #if resumenonboot { offsetkernel, resumenonboot, overcommitmemory | irqhandlerfixup | cleandcache | percpudevid | framekernel, 16, 16, SHARKSSL_HASHID_SHA256 }, #endif #if nvramgetenv { updatecontext, nvramgetenv, overcommitmemory | cleandcache | percpudevid | suspendenter, 32, 16, SHARKSSL_HASHID_SHA256 }, #endif #if quirkslc90e66 { offsetkernel, quirkslc90e66, overcommitmemory | cleandcache | percpudevid | framekernel | ioasicclocksource, 32, 16, SHARKSSL_HASHID_SHA384 }, #endif #if branchenable { offsetkernel, branchenable, overcommitmemory | cleandcache | percpudevid | framekernel, 16, 16, SHARKSSL_HASHID_SHA256 }, #endif #endif #endif }; #endif #endif #undef _SHARKSSLCON_HS_C_ #if SHARKSSL_ENABLE_SELECT_CIPHERSUITE #if (SHARKSSL_SSL_SERVER_CODE || SHARKSSL_SSL_CLIENT_CODE) SHARKSSL_API U8 SharkSslCon_selectCiphersuite(SharkSslCon *o, U16 clockmodtable) { baAssert(SHARKSSL_DIM_ARR(genericsuspend) < 0xFF); #if SHARKSSL_ENABLE_SESSION_CACHE if (!(o->session)) #endif { if ((o) && ((o->state <= pciercxcfg070) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION || (o->flags & registerbuses) #endif )) { if (o->cipherSelCtr < SHARKSSL_SELECT_CIPHERSUITE_LIST_DEPTH) { int i; for (i = 0; (U16)i < SHARKSSL_DIM_ARR(genericsuspend); i++) { if (genericsuspend[i].id == clockmodtable) { if (o->minor) { baAssert((o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) || (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3))); if (!sharkssl_protocol_ciphersuite(o->minor, (U8)i)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 0; } } o->cipherSelection[o->cipherSelCtr++] = (U8)i; return 1; } } } } } return 0; } SHARKSSL_API U8 SharkSslCon_clearCiphersuiteSelection(SharkSslCon *o) { if ((o) && ((o->state <= pciercxcfg070) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION || (o->flags & registerbuses) #endif )) { o->cipherSelCtr = 0; return 1; } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 0; } #endif int sharkssl_protocol_ciphersuite(U8 ejtagsetup, U8 fiqoutstart) { baAssert(fiqoutstart < SHARKSSL_DIM_ARR(genericsuspend)); return ( #if SHARKSSL_PROTOCOL_TLS_1_2 ((ejtagsetup == SHARKSSL_PROTOCOL_TLS_1_2) && (genericsuspend[fiqoutstart].flags & overcommitmemory)) #if SHARKSSL_PROTOCOL_TLS_1_3 || #endif #endif #if SHARKSSL_PROTOCOL_TLS_1_3 ((ejtagsetup == SHARKSSL_PROTOCOL_TLS_1_3) && (genericsuspend[fiqoutstart].flags & SHARKSSL_CS_TLS13)) #endif ); } #endif #if SHARKSSL_ENABLE_ALPN_EXTENSION #if SHARKSSL_SSL_CLIENT_CODE U8 SharkSslCon_setALPNProtocols(SharkSslCon *o, const char *iobanktiming) { if (o && (o->state <= pciercxcfg070) #if SHARKSSL_SSL_SERVER_CODE && (SharkSsl_isClient(o->sharkSsl)) #endif ) { o->pALPN = iobanktiming; return 1; } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 0; } const char *SharkSslCon_getALPNProtocol(SharkSslCon *o) { return o->rALPN; } #endif #if SHARKSSL_SSL_SERVER_CODE U8 SharkSslCon_setALPNFunction(SharkSslCon *o, ALPNFunction func0fixup, void *writeabort) { if (o && (o->state <= trampolinehandler) #if SHARKSSL_SSL_CLIENT_CODE && (SharkSsl_isServer(o->sharkSsl)) #endif ) { o->fALPN = func0fixup; o->pALPN = (const char*)writeabort; o->rALPN = NULL; return 1; } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 0; } #endif #endif int SharkSslCertParam_validateCertChain(SharkSslCertParam *certParam, SharkSslSignParam *tmpSignParam #if SHARKSSL_ENABLE_CA_LIST , U32 *driverchipcommon, SharkSslCAList displaysetup, U8 *afterhandler #endif ) { #if SHARKSSL_ENABLE_CA_LIST U32 uart2hwmod; U8 *tp, gpio1config[SHARKSSL_CA_LIST_NAME_SIZE]; #if SHARKSSL_ENABLE_CERTSTORE_API U8 *tb; U16 paramnamed; #endif U8 sha256export, i; #endif #if SHARKSSL_ENABLE_CA_LIST sha256export = 1; #endif while (certParam) { if (certParam->certInfo.parent != 0) { if (0 == SharkSslCertDN_equal(&(certParam->certInfo.issuer), &((SharkSslCertParam*)(certParam->certInfo.parent))->certInfo.subject)) { if (certParam->certInfo.parent->parent) { certParam->certInfo.parent = certParam->certInfo.parent->parent; continue; } else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 1; } } #if SHARKSSL_ENABLE_CA_LIST } if (displaysetup) { #if SHARKSSL_ENABLE_CERTSTORE_API baAssert(SHARKSSL_CA_LIST_PTR_SIZE == claimresource(SHARKSSL_CA_LIST_PTR_SIZE)); paramnamed = SHARKSSL_CA_LIST_ELEMENT_SIZE; if (displaysetup[0] == SHARKSSL_CA_LIST_PTR_TYPE) { paramnamed = SHARKSSL_CA_LIST_NAME_SIZE + SHARKSSL_CA_LIST_PTR_SIZE; } else #endif if (displaysetup[0] != SHARKSSL_CA_LIST_INDEX_TYPE) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } tp = (U8*)&(displaysetup[2]); uart2hwmod = (U16)(*tp++) << 8; uart2hwmod += *tp++; if (0 == uart2hwmod) { break; } uart2hwmod--; #if SHARKSSL_ENABLE_CERTSTORE_API uart2hwmod *= paramnamed; #else uart2hwmod *= SHARKSSL_CA_LIST_ELEMENT_SIZE; #endif i = 0; if ((certParam->certInfo.issuer.commonName) && (certParam->certInfo.issuer.commonNameLen)) { i = certParam->certInfo.issuer.commonNameLen; memcpy(gpio1config, certParam->certInfo.issuer.commonName, SHARKSSL_CA_LIST_NAME_SIZE); } else if ((certParam->certInfo.issuer.organization) && (certParam->certInfo.issuer.organizationLen)) { i = certParam->certInfo.issuer.organizationLen; memcpy(gpio1config, certParam->certInfo.issuer.organization, SHARKSSL_CA_LIST_NAME_SIZE); } if (i >= SHARKSSL_CA_LIST_NAME_SIZE) { i = SHARKSSL_CA_LIST_NAME_SIZE; } if (i == 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 1; } memset(afterhandler, 0, sizeof(SharkSslCertParam)); tp += uart2hwmod; while ((*tp != gpio1config[0]) && (uart2hwmod > 0)) { #if SHARKSSL_ENABLE_CERTSTORE_API tp -= paramnamed; uart2hwmod -= paramnamed; #else tp -= SHARKSSL_CA_LIST_ELEMENT_SIZE; uart2hwmod -= SHARKSSL_CA_LIST_ELEMENT_SIZE; #endif } while (*tp == gpio1config[0]) { if (0 == sharkssl_kmemcmp(tp, gpio1config, i)) { #if SHARKSSL_ENABLE_CERTSTORE_API if (displaysetup[0] == SHARKSSL_CA_LIST_PTR_TYPE) { tb = *(U8**)&tp[SHARKSSL_CA_LIST_NAME_SIZE]; } else #endif { uart2hwmod = (U32)tp[SHARKSSL_CA_LIST_NAME_SIZE + 0] << 24; uart2hwmod += (U32)tp[SHARKSSL_CA_LIST_NAME_SIZE + 1] << 16; uart2hwmod += (U16)tp[SHARKSSL_CA_LIST_NAME_SIZE + 2] << 8; uart2hwmod += tp[SHARKSSL_CA_LIST_NAME_SIZE + 3]; #if SHARKSSL_ENABLE_CERTSTORE_API tb = (U8*)&(displaysetup[uart2hwmod]); #endif } #if SHARKSSL_ENABLE_CERTSTORE_API if (!(spromregister((SharkSslCertParam*)afterhandler, tb, (U32)-5, NULL) < 0)) #else if (!(spromregister((SharkSslCertParam*)afterhandler, (U8*)&(displaysetup[uart2hwmod]), (U32)-5, NULL) < 0)) #endif { if ((((SharkSslCertParam*)afterhandler)->certInfo.version < 2) || (((SharkSslCertParam*)afterhandler)->certInfo.CAflag)) { if (SharkSslCertDN_equal(&(((SharkSslCertParam*)afterhandler)->certInfo.subject), &(certParam->certInfo.issuer))) { if (SharkSslCertDN_equal(&(certParam->certInfo.issuer), &(certParam->certInfo.subject))) { if (0 == sharkssl_kmemcmp(((SharkSslCertParam*)afterhandler)->signature.signature, certParam->signature.signature, certParam->signature.signLen)) { *driverchipcommon |= switcheractivation; break; } } else { if (0 #if SHARKSSL_ENABLE_RSA || ((certParam->signature.signatureAlgo == entryearly) && machinekexec(((SharkSslCertParam*)afterhandler)->certKey.expLen)) #endif #if SHARKSSL_ENABLE_ECDSA || ((certParam->signature.signatureAlgo == accessactive) && machinereboot(((SharkSslCertParam*)afterhandler)->certKey.expLen)) #endif ) { certParam->certInfo.parent = (SharkSslCertInfo*)afterhandler; sha256export = 0; goto controlrestore; } } } } } } if (0 == uart2hwmod) { break; } #if SHARKSSL_ENABLE_CERTSTORE_API tp -= paramnamed; uart2hwmod -= paramnamed; #else tp -= SHARKSSL_CA_LIST_ELEMENT_SIZE; uart2hwmod -= SHARKSSL_CA_LIST_ELEMENT_SIZE; #endif } } if (certParam->certInfo.parent != 0) { controlrestore: #endif if (((certParam->certInfo.parent)->version == 2) && !((certParam->certInfo.parent)->CAflag)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 1; } tmpSignParam->pCertKey = &(((SharkSslCertParam*)certParam->certInfo.parent)->certKey); memcpy(&(tmpSignParam->signature), &(certParam->signature), sizeof(SharkSslSignature)); if (systemcapabilities(tmpSignParam) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return 1; } #if SHARKSSL_ENABLE_CA_LIST if (0 == sha256export) { *driverchipcommon |= switcheractivation; break; } #endif } certParam = (SharkSslCertParam*)certParam->certInfo.parent; } return 0; } #define SHARKSSL_WEIGHT U32 #define trainingneeded 0x00800000L #define smbuswrite 0x01000000L #define lcd035q3dg01pdata 0x10000000L #define clearevent 0x80000000L #define coverstate 0x00080000L #if SHARKSSL_SSL_SERVER_CODE #if SHARKSSL_ENABLE_SNI #include #endif static int writepmresr(SharkSslCon *o, SHARKSSL_WEIGHT *mfgpt0counter, U8 *registeredevent, U16 len) { SHARKSSL_WEIGHT *p; SingleListEnumerator e; SingleLink *link; SharkSslHSParam *sharkSslHSParam; #else static int writepmresr(SharkSslCon* o, U8* registeredevent, U16 len) { #endif U16 prminstwrite, paramnamed; #if SHARKSSL_TLS_1_3 U16 kLen, ksLen; #endif baAssert(o); baAssert(registeredevent); #if SHARKSSL_SSL_SERVER_CODE sharkSslHSParam = hsParam(o); #endif #if SHARKSSL_USE_ECC baAssert(SHARKSSL_EC_CURVE_ID_SECP256R1 == spannedpages); baAssert(SHARKSSL_EC_CURVE_ID_SECP384R1 == restoretrace); baAssert(SHARKSSL_EC_CURVE_ID_SECP521R1 == buildmemmap); baAssert(SHARKSSL_EC_CURVE_ID_BRAINPOOLP256R1 == samplingevent); baAssert(SHARKSSL_EC_CURVE_ID_BRAINPOOLP384R1 == entrytrampoline); baAssert(SHARKSSL_EC_CURVE_ID_BRAINPOOLP512R1 == resumeprepare); baAssert(SHARKSSL_EC_CURVE_ID_CURVE25519 == TLS_NAMEDCURVE_CURVE25519); baAssert(SHARKSSL_EC_CURVE_ID_CURVE448 == TLS_NAMEDCURVE_CURVE448); #endif while (len >= 2) { prminstwrite = (U16)(*registeredevent++) << 8; prminstwrite += *registeredevent++; len -= 2; if (len < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; len -= 2; if (len < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } switch (prminstwrite) { #if SHARKSSL_ENABLE_ALPN_EXTENSION case clkdmclear: if (paramnamed) { if (len < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; len -= 2; if (paramnamed > len) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } #if SHARKSSL_SSL_CLIENT_CODE #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isClient(o->sharkSsl)) #endif { paramnamed = *registeredevent++; len--; if (paramnamed > len) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; if (o->pALPN) { U8 *afterhandler = (U8*)baMalloc(paramnamed + 1); if (afterhandler) { memcpy(afterhandler, registeredevent, paramnamed); *(afterhandler + paramnamed) = 0; o->rALPN = strstr(o->pALPN, (const char *)afterhandler); baFree(afterhandler); } } } #if SHARKSSL_SSL_SERVER_CODE else #endif #endif #if SHARKSSL_SSL_SERVER_CODE { if (o->fALPN) { o->rALPN = NULL; while ((paramnamed > 0) && (paramnamed <= len) && (NULL == o->rALPN)) { int ret; U8* afterhandler; prminstwrite = *registeredevent; afterhandler = (U8*)baMalloc(prminstwrite + 1); if (afterhandler) { memcpy(afterhandler, registeredevent + 1, prminstwrite); *(afterhandler + prminstwrite) = 0; ret = o->fALPN(o, (const char*)afterhandler, (void*)o->pALPN); baFree(afterhandler); if (ret) { o->rALPN = (const char*)registeredevent; } } prminstwrite++; registeredevent += prminstwrite; paramnamed -= prminstwrite; len -= prminstwrite; } if ((NULL == o->rALPN) && (0 == o->fALPN(o, NULL, (void*)o->pALPN))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -2; } } len -= paramnamed; } #endif registeredevent += paramnamed; } break; #endif case featurespresent: if (len < 1) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = *registeredevent++; len--; if (paramnamed > len) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; if (!(o->flags & aarch32ptrace)) { o->flags |= aarch32ptrace; if (paramnamed) { #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION goto hsudcresource; #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; #endif } } else { #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (!(o->flags & platformdevice)) { hsudcresource: if (paramnamed != SHARKSSL_FINISHED_MSG_LEN_TLS_1_2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } } if (sharkssl_kmemcmp(registeredevent, SharkSsl_isServer(o->sharkSsl) ? o->clientVerifyData : o->serverVerifyData, paramnamed)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } registeredevent += paramnamed; #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; #endif } break; #if SHARKSSL_USE_ECC case edma0resources: if ((len < 1) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION || (o->minor == 0) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = *registeredevent++; len--; if (paramnamed > len) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; while ((paramnamed) && (*registeredevent++ != probesystem)) { paramnamed--; } if (0 == paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed--; registeredevent += paramnamed; break; #endif #if SHARKSSL_SSL_SERVER_CODE #if SHARKSSL_ENABLE_SNI case firstversion: if (paramnamed) { if (len < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; len -= 2; if (paramnamed > len) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; #if SHARKSSL_SSL_CLIENT_CODE if ((void*)0 == mfgpt0counter) { registeredevent += paramnamed; paramnamed = 0; } #endif } while (paramnamed) { if ((*registeredevent++) || (paramnamed < SHARKSSL_CERT_LENGTH_LEN)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } prminstwrite = (U16)(*registeredevent++) << 8; prminstwrite += *registeredevent++; paramnamed -= SHARKSSL_CERT_LENGTH_LEN; if (prminstwrite > paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (p = mfgpt0counter, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), p++) { if (*p) { if (0 == sharkSubjectSubjectAltCmp((const char*)((SharkSslCertList*)link)->certP.commonName, ((SharkSslCertList*)link)->certP.commonNameLen, ((SharkSslCertList*)link)->certP.subjectAltNamesPtr, ((SharkSslCertList*)link)->certP.subjectAltNamesLen, (const char*)registeredevent, prminstwrite)) { *(SHARKSSL_WEIGHT*)p |= clearevent; } } } registeredevent += prminstwrite; paramnamed -= prminstwrite; } break; #endif #if SHARKSSL_TLS_1_3 case reboothandler: if (len < 5) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } #if SHARKSSL_TLS_1_2 if (SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2) == o->minor) { goto _skip_over_extension; } #endif #if SHARKSSL_TLS_1_3 && SHARKSSL_SSL_SERVER_CODE ksLen = 0; if (SharkSsl_isServer(o->sharkSsl)) { ksLen = (U16)(*registeredevent++) << 8; ksLen += (*registeredevent++); len -= 2; if ((len < ksLen) || (paramnamed < ksLen)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } } _next_key_share_entry: #endif prminstwrite = (U16)(*registeredevent++) << 8; prminstwrite += (*registeredevent++); len -= 2; kLen = controllerregister(prminstwrite); paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); len -= 2; if (len < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } #if SHARKSSL_TLS_1_3 && SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isServer(o->sharkSsl)) { if (ksLen < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } } #endif if (0 == kLen) { #if SHARKSSL_TLS_1_3 && SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isServer(o->sharkSsl)) { ksLen -= paramnamed; ksLen -= 4; len -= paramnamed; registeredevent += paramnamed; if (ksLen) { goto _next_key_share_entry; } else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } } else #endif { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } } hsParam(o)->ecdhParam.curveType = prminstwrite; #if SHARKSSL_ECC_USE_EDWARDS if ((prminstwrite == TLS_NAMEDGROUP_CURVE25519) || (prminstwrite == TLS_NAMEDGROUP_CURVE448)) { if (paramnamed != kLen) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } } else #endif { #if (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1) if (*registeredevent++ != SHARKSSL_EC_POINT_UNCOMPRESSED) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed--; len--; if (paramnamed != (U16)(kLen << 1)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; #endif } hsParam(o)->ecdhParam.xLen = kLen; hsParam(o)->ecdhParam.XY = registeredevent; switch (prminstwrite) { #if SHARKSSL_ECC_USE_SECP384R1 case pciercxcfg034: hsParam(o)->ecdhParam.k = hsParam(o)->prot.tls13.privKeySECP384R1; break; #endif #if SHARKSSL_ECC_USE_SECP256R1 case ucb1400pdata: hsParam(o)->ecdhParam.k = hsParam(o)->prot.tls13.privKeySECP256R1; break; #endif #if SHARKSSL_ECC_USE_CURVE25519 case TLS_NAMEDGROUP_CURVE25519: hsParam(o)->ecdhParam.k = hsParam(o)->prot.tls13.privKeyCURVE25519; break; #endif #if SHARKSSL_ECC_USE_CURVE448 case TLS_NAMEDGROUP_CURVE448: hsParam(o)->ecdhParam.k = hsParam(o)->prot.tls13.privKeyCURVE448; break; #endif default: SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; registeredevent += paramnamed; if (SharkSsl_isClient(o->sharkSsl)) { SharkSslECDHParam_ECDH(&(hsParam(o)->ecdhParam), switcheractive, hsParam(o)->ecdhParam.k); } break; case allocconsistent: #if SHARKSSL_TLS_1_2 if (SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2) == o->minor) { goto _skip_over_extension; } #endif #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isServer(o->sharkSsl)) { if (len < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; registeredevent += paramnamed; } else #endif { if (len < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); len -= 2; if (paramnamed != 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } o->flags |= startqueue; } break; #endif #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) case registerpwrdms: if ((o->flags & startqueue) #if SHARKSSL_SSL_CLIENT_CODE || (SharkSsl_isClient(o->sharkSsl)) #endif ) { goto swiotlbdetect; } if ((len < 2) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION || (o->minor == 0) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; len -= 2; if (paramnamed > len) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; sharkSslHSParam->ecdhParam.xLen = 0; while (paramnamed) { U8 savedsigmask; if (paramnamed < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } prminstwrite = (U16)(*registeredevent++) << 8; prminstwrite += *registeredevent++; paramnamed -= 2; savedsigmask = controllerregister(prminstwrite); if (savedsigmask) { if (0 == sharkSslHSParam->ecdhParam.xLen) { sharkSslHSParam->ecdhParam.xLen = savedsigmask; sharkSslHSParam->ecdhParam.curveType = prminstwrite; } SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (p = mfgpt0counter, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), p++) { if ( (*p) && (((SharkSslCertList*)link)->certP.keyType == compatrestart) && (((SharkSslCertList*)link)->certP.keyOID == prminstwrite)) { *(SHARKSSL_WEIGHT*)p |= trainingneeded; } } } } break; #endif case entrypaddr: #if SHARKSSL_SSL_CLIENT_CODE if (SharkSsl_isClient(o->sharkSsl)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } #endif if (o->minor >= 3) { if (len < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; len -= 2; if ((paramnamed > len) || (paramnamed & 0x1)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } len -= paramnamed; prminstwrite = 0; while (paramnamed) { SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (p = mfgpt0counter, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), p++) { if ((*p) && (!(*p & smbuswrite))) { if ((((SharkSslCertList*)link)->certP.hashAlgo == registeredevent[0]) && (((SharkSslCertList*)link)->certP.signatureAlgo == registeredevent[1])) { *(SHARKSSL_WEIGHT*)p |= smbuswrite; } } } if (prminstwrite < 2) { if ((registeredevent[0] == presentpages) || (registeredevent[0] == domainnumber) #if SHARKSSL_USE_SHA_384 || (registeredevent[0] == probewrite) #endif #if SHARKSSL_USE_SHA_512 || (registeredevent[0] == batterythread) #endif ) { #if SHARKSSL_ENABLE_RSA if ((0 == sharkSslHSParam->signParam.signature.signatureAlgo) && (registeredevent[1] == entryearly)) { sharkSslHSParam->signParam.signature.signatureAlgo = registeredevent[0]; prminstwrite++; } #endif #if SHARKSSL_ENABLE_ECDSA if ((0 == sharkSslHSParam->signParam.signature.hashAlgo) && (registeredevent[1] == accessactive)) { sharkSslHSParam->signParam.signature.hashAlgo = registeredevent[0]; prminstwrite++; } #endif } } registeredevent += 2; paramnamed -= 2; } break; } #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) swiotlbdetect: #endif #endif default: if (len < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) _skip_over_extension: #endif len -= paramnamed; registeredevent += paramnamed; break; } } return 0; } #if SHARKSSL_TLS_1_3 #if (SHARKSSL_SSL_CLIENT_CODE && SHARKSSL_SSL_SERVER_CODE) static int earlyalloc(SharkSslCon* o, U8* registeredevent, U16 len, SharkSsl_Role startkernel) #else static int earlyalloc(SharkSslCon* o, U8* registeredevent, U16 len) #endif { U16 prminstwrite, paramnamed; baAssert(o); baAssert(registeredevent); while (len >= 2) { prminstwrite = (U16)(*registeredevent++) << 8; prminstwrite += *registeredevent++; len -= 2; if (len < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; len -= 2; if (len < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } if (prminstwrite == doublefcvts) { #if (SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_3) != SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_2)) #error INTERNAL ERROR SHARKSSL_PROTOCOL_MAJOR TLS 1.3 <> TLS 1.2 #endif #if SHARKSSL_SSL_CLIENT_CODE #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_Client == startkernel) #endif { if ((paramnamed != 2) || (*registeredevent++ != SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_3))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } if ((*registeredevent != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) && (*registeredevent != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } return (int)*registeredevent; } #if SHARKSSL_SSL_SERVER_CODE else #endif #endif #if SHARKSSL_SSL_SERVER_CODE { #if SHARKSSL_SSL_CLIENT_CODE baAssert(SharkSsl_Server == startkernel); #endif if (!(paramnamed & 1)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } paramnamed--; if (paramnamed != *registeredevent++) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } while (paramnamed >= 2) { if ((SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_3) == *registeredevent++) && ((SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3) == *registeredevent) || (SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2) == *registeredevent))) { return (int)*registeredevent; } registeredevent++; paramnamed -= 2; } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } #endif } else { len -= paramnamed; registeredevent += paramnamed; } } return 0; } #endif int SharkSslHSParam_setSignatureHashAlgoFromSignatureScheme(SharkSslHSParam *s, U16 ahashreqsize) { switch (ahashreqsize) { #if (SHARKSSL_ENABLE_ECDSA || (SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSA_PKCS1)) && (SHARKSSL_USE_SHA_256 || SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) #if SHARKSSL_ENABLE_ECDSA #if SHARKSSL_USE_SHA_256 case 0x0403: #endif #if SHARKSSL_USE_SHA_384 case 0x0503: #endif #if SHARKSSL_USE_SHA_512 case 0x0603: #endif #endif #if SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSA_PKCS1 #if SHARKSSL_USE_SHA_256 case 0x0401: #endif #if SHARKSSL_USE_SHA_384 case 0x0501: #endif #if SHARKSSL_USE_SHA_512 case 0x0601: #endif #endif s->signParam.signature.hashAlgo = (ahashreqsize >> 8); s->signParam.signature.signatureAlgo = (ahashreqsize & 0xFF); break; #endif #if SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSASSA_PSS && (SHARKSSL_USE_SHA_256 || SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) #if SHARKSSL_USE_SHA_256 case 0x0804: #endif #if SHARKSSL_USE_SHA_384 case 0x0805: #endif #if SHARKSSL_USE_SHA_512 case 0x0806: #endif s->signParam.signature.hashAlgo = (ahashreqsize & 0xFF); s->signParam.signature.signatureAlgo = (ahashreqsize >> 8); break; #endif default: SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return -1; } return 0; } #if SHARKSSL_SSL_SERVER_CODE static int SharkSslHSParam_setCert(SharkSslHSParam *s, SharkSslCertParsed **certPtr, U16 cipherSuiteFlags) { baAssert(s); baAssert(certPtr); #if SHARKSSL_TLS_1_3 if (cipherSuiteFlags & SHARKSSL_CS_TLS13) { return -1; } #endif switch (cipherSuiteFlags & (cleandcache | irqhandlerfixup | cpufreqcallback | percpudevid)) { #if SHARKSSL_ENABLE_RSA case percpudevid: #if SHARKSSL_ENABLE_DHE_RSA case cleandcache | percpudevid: #endif #if SHARKSSL_ENABLE_ECDHE_RSA case cleandcache | irqhandlerfixup | percpudevid: #endif if (certPtr[0]) { s->certParsed = certPtr[0]; return 0; } break; #endif #if SHARKSSL_ENABLE_ECDHE_ECDSA case cleandcache | irqhandlerfixup | cpufreqcallback: if (certPtr[2]) { s->certParsed = certPtr[2]; return 0; } #if SHARKSSL_ENABLE_RSA else if (certPtr[1]) { s->certParsed = certPtr[1]; return 0; } #endif break; #endif default: break; } return -1; } #endif SharkSslCon_RetVal configdword(SharkSslCon *o, U8 *registeredevent, U16 atagsprocfs) { #if SHARKSSL_TLS_1_2 #if SHARKSSL_SSL_SERVER_CODE static const U8 registeraudio[] = { (U8)(featurespresent >> 8), (U8)(featurespresent & 0xFF), 0x00, 0x01, 0x00 }; #endif #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) static const U8 resetsources[] = { 0x00, edma0resources, 0x00, 0x02, 0x01, probesystem }; #endif #endif #if SHARKSSL_TLS_1_3 static const U8 cvServerCtxZero[34] = { '\124','\114','\123','\040','\061','\056','\063','\054','\040','\163','\145','\162','\166','\145','\162','\040', '\103','\145','\162','\164','\151','\146','\151','\143','\141','\164','\145','\126','\145','\162','\151','\146','\171', 0x00 }; #if SHARKSSL_SSL_CLIENT_CODE SharkSslECDHParam configvdcdc2; #endif #endif U32 now_ccLen, crLen; U8 *tp, *sp, *tb, *afterhandler; SharkSslHSParam *sharkSslHSParam; #if ((SHARKSSL_SSL_CLIENT_CODE || SHARKSSL_SSL_SERVER_CODE) && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) SharkSslCertParam *certParam; #if (SHARKSSL_SSL_SERVER_CODE || SHARKSSL_ENABLE_CLIENT_AUTH) SingleListEnumerator e; SingleLink *link; #endif #endif U16 hsDataLen, paramnamed, hsLen, i; U8 setupinterface, ics; tb = (U8*)0; suspendlocal: if ((0 == registeredevent) || (*registeredevent != o->state)) { #if SHARKSSL_SSL_CLIENT_CODE if (o->flags & probedaddress) { SharkSslCipherSuite *clockmodtable; baAssert(SharkSsl_isClient(o->sharkSsl)); o->flags &= ~probedaddress; baAssert(microresources(&o->outBuf)); atomiccmpxchg(&o->outBuf, o->sharkSsl->outBufSize); if (microresources(&o->outBuf)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } sharkSslHSParam = hsParam(o); breakpointhandler(sharkSslHSParam); baAssert(microresources(&o->inBuf)); atomiccmpxchg(&o->inBuf, o->sharkSsl->inBufStartSize); if (microresources(&o->inBuf)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } o->major = SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_2); tp = sp = templateentry(o, controllegacy, o->inBuf.data, 0); *tp++ = pciercxcfg070; *tp++ = 0x00; *tp++ = 0x00; *tp++ = 0x00; *tp++ = o->reqMajor = o->major; *tp++ = o->reqMinor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); #if SHARKSSL_TLS_1_2 now_ccLen = (U32)baGetUnixTime(); inputlevel(now_ccLen, tp, 0); tp += 4; if (sharkssl_rng(tp, (SHARKSSL_RANDOM_LEN - 4)) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } tp += (SHARKSSL_RANDOM_LEN - 4); memcpy(sharkSslHSParam->prot.tls12.clientRandom, tp - SHARKSSL_RANDOM_LEN, SHARKSSL_RANDOM_LEN); #else if (sharkssl_rng(tp, SHARKSSL_RANDOM_LEN) < 0) { resvdexits(o); return SharkSslCon_Error; } tp += SHARKSSL_RANDOM_LEN; #endif #if (SHARKSSL_TLS_1_2 && SHARKSSL_ENABLE_SESSION_CACHE) if ((o->session) #if SHARKSSL_TLS_1_3 && (SharkSslSession_isProtocol(o->session, SHARKSSL_PROTOCOL_TLS_1_2)) #endif ) { *tp++ = SHARKSSL_MAX_SESSION_ID_LEN; memcpy(tp, o->session->prot.tls12.id, SHARKSSL_MAX_SESSION_ID_LEN); tp += SHARKSSL_MAX_SESSION_ID_LEN; } else #endif { #if 1 *tp++ = 0; #else *tp++ = SHARKSSL_MAX_SESSION_ID_LEN; if (sharkssl_rng(tp, SHARKSSL_MAX_SESSION_ID_LEN) < 0) { resvdexits(o); return SharkSslCon_Error; } tp += SHARKSSL_MAX_SESSION_ID_LEN; #endif } #if SHARKSSL_ENABLE_SELECT_CIPHERSUITE if (o->cipherSelCtr) { #if SHARKSSL_ENABLE_SESSION_CACHE baAssert(!(o->session)); #endif paramnamed = (U16)((U16)o->cipherSelCtr << 1); *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); paramnamed = 0; #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) hsLen = 0; #endif while (paramnamed < o->cipherSelCtr) { clockmodtable = (SharkSslCipherSuite*)&genericsuspend[o->cipherSelection[paramnamed++]]; now_ccLen = clockmodtable->id; *tp++ = (U8)(now_ccLen >> 8); *tp++ = (U8)(now_ccLen & 0xFF); #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) if (o->minor == 0) { hsLen |= clockmodtable->flags & (overcommitmemory | SHARKSSL_CS_TLS13); } #endif } #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) switch (hsLen) { case overcommitmemory: o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); break; case SHARKSSL_CS_TLS13: o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3); break; default: break; } #endif } else #endif { paramnamed = (U16)((U16)SHARKSSL_DIM_ARR(genericsuspend) << 1); baAssert(paramnamed); #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) if (o->minor) { tb = tp++; tp++; } else #endif { *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); } paramnamed >>= 1; clockmodtable = (SharkSslCipherSuite*)&genericsuspend[0]; #if SHARKSSL_ENABLE_SESSION_CACHE crLen = 0; if (o->session) { baAssert((o->minor == 0) || (o->minor == hardirqsenabled(o->session))); crLen = o->session->cipherSuite->id; *tp++ = (U8)(crLen >> 8); *tp++ = (U8)(crLen & 0xFF); } #endif while (paramnamed) { paramnamed--; now_ccLen = clockmodtable->id; #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) if ( (o->minor == 0) || ((o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) && (clockmodtable->flags & overcommitmemory)) || ((o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) && (clockmodtable->flags & SHARKSSL_CS_TLS13)) ) #endif { #if SHARKSSL_ENABLE_SESSION_CACHE if ((!(o->session)) || (now_ccLen != crLen)) #endif { *tp++ = (U8)(now_ccLen >> 8); *tp++ = (U8)(now_ccLen & 0xFF); } } clockmodtable++; } #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) if (o->minor) { paramnamed = (U16)(tp - tb - 2); *tb++ = (U8)(paramnamed >> 8); *tb = (U8)(paramnamed & 0xFF); } #endif } *tp++ = 1; *tp++ = cminstclear; afterhandler = tp++; tp++; #if SHARKSSL_RANDOMIZE_EXTENSIONS baAssert(sizeof(U32) & 0x4); baAssert(0 == (sizeof(U32) & 0x3)); sharkssl_rng((U8 *)&sharkSslHSParam->extState, sizeof(U32) & 0x4); for (ics = 0; ics < SHARKSSL_MAX_EXTENSIONS; ics++) { sharkSslHSParam->extIndex[ics] = ics + 1; } for (ics = 0; ics < SHARKSSL_MAX_EXTENSIONS; ics++) { for (setupinterface = 0; setupinterface < 37; setupinterface++) { U8 t; #if (SHARKSSL_BIGINT_WORDSIZE < 32) sharkSslHSParam->extState ^= sharkSslHSParam->extState << 7; sharkSslHSParam->extState ^= sharkSslHSParam->extState >> 9; sharkSslHSParam->extState ^= sharkSslHSParam->extState << 8; #else sharkSslHSParam->extState ^= sharkSslHSParam->extState << 13; sharkSslHSParam->extState ^= sharkSslHSParam->extState >> 17; sharkSslHSParam->extState ^= sharkSslHSParam->extState << 5; #endif t = (U8)sharkSslHSParam->extState; if ((t < SHARKSSL_MAX_EXTENSIONS) && (t != ics)) { sharkSslHSParam->extIndex[ics] += sharkSslHSParam->extIndex[t]; sharkSslHSParam->extIndex[t] = sharkSslHSParam->extIndex[ics] - sharkSslHSParam->extIndex[t]; sharkSslHSParam->extIndex[ics] -= sharkSslHSParam->extIndex[t]; } } } for (ics = 0; ics < SHARKSSL_MAX_EXTENSIONS; ics++) #endif { #if SHARKSSL_RANDOMIZE_EXTENSIONS switch (sharkSslHSParam->extIndex[ics]) { case 8: #endif #if SHARKSSL_ENABLE_SNI if ((o->padLen) && (o->rCtx)) { *tp++ = (U8)(firstversion >> 8); *tp++ = (U8)(firstversion & 0xFF); paramnamed = (U8)(o->padLen) + 5; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); paramnamed -= 2; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); *tp++ = 0x00; paramnamed -= 3; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); memcpy(tp, o->rCtx, paramnamed); tp += paramnamed; o->rCtx = NULL; o->padLen = 0; } #endif #if SHARKSSL_RANDOMIZE_EXTENSIONS break; case 7: #endif #if SHARKSSL_ENABLE_ALPN_EXTENSION if (o->pALPN) { *tp++ = (U8)(clkdmclear >> 8); *tp++ = (U8)(clkdmclear & 0xFF); paramnamed = (U16)(3 + (U16)strlen(o->pALPN)); *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); paramnamed -= 2; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); tb = (U8*)o->pALPN; for (;;) { paramnamed = 0; tp++; while ((*tb != '\054') && (*tb != 0)) { paramnamed++; *tp++ = *tb++; } *(tp - paramnamed - 1) = (U8)paramnamed; if (0 == *tb) { break; } tb++; } } #endif #if SHARKSSL_RANDOMIZE_EXTENSIONS break; case 6: #endif #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { *tp++ = (U8)(doublefcvts >> 8); *tp++ = (U8)(doublefcvts & 0xFF); *tp++ = 0x00; tb = tp++; tp++; *tp++ = SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_3); *tp++ = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3); #if SHARKSSL_TLS_1_2 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) { *tp++ = SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_2); *tp++ = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); } #endif paramnamed = (U16)(tp - tb); *tb++ = (U8)--paramnamed; *tb = (U8)--paramnamed; } #endif #if SHARKSSL_RANDOMIZE_EXTENSIONS break; case 5: #endif #if SHARKSSL_TLS_1_2 baAssert(restoremasks == entrypaddr); #endif *tp++ = (U8)(restoremasks >> 8); *tp++ = (U8)(restoremasks & 0xFF); tb = tp; tp += 4; #if SHARKSSL_ENABLE_ECDSA #if (SHARKSSL_ECC_USE_SECP521R1 && SHARKSSL_USE_SHA_512) *tp++ = batterythread; *tp++ = accessactive; #endif #if (SHARKSSL_ECC_USE_SECP384R1 && SHARKSSL_USE_SHA_384) *tp++ = probewrite; *tp++ = accessactive; #endif #if (SHARKSSL_ECC_USE_SECP256R1 && SHARKSSL_USE_SHA_256) *tp++ = domainnumber; *tp++ = accessactive; #endif #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { *tp++ = presentpages; *tp++ = accessactive; } #endif #endif #if SHARKSSL_ENABLE_RSA #if SHARKSSL_ENABLE_RSA_PKCS1 #if SHARKSSL_USE_SHA_512 *tp++ = batterythread; *tp++ = entryearly; #endif #if SHARKSSL_USE_SHA_384 *tp++ = probewrite; *tp++ = entryearly; #endif #if SHARKSSL_USE_SHA_256 *tp++ = domainnumber; *tp++ = entryearly; #endif #if (SHARKSSL_TLS_1_2 && (SHARKSSL_USE_SHA1 || SHARKSSL_USE_MD5)) #if SHARKSSL_TLS_1_3 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { #if SHARKSSL_USE_SHA1 *tp++ = presentpages; *tp++ = entryearly; #endif #if SHARKSSL_USE_MD5 *tp++ = skciphercreate; *tp++ = entryearly; #endif } #endif #endif #if (SHARKSSL_TLS_1_3 && SHARKSSL_ENABLE_RSASSA_PSS) #if SHARKSSL_TLS_1_2 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { #if SHARKSSL_USE_SHA_512 *tp++ = SHARKSSL_SIGNATUREALGORITHM_RSA_PSS; *tp++ = batterythread; #endif #if SHARKSSL_USE_SHA_384 *tp++ = SHARKSSL_SIGNATUREALGORITHM_RSA_PSS; *tp++ = probewrite; #endif #if SHARKSSL_USE_SHA_256 *tp++ = SHARKSSL_SIGNATUREALGORITHM_RSA_PSS; *tp++ = domainnumber; #endif } #endif #endif paramnamed = (U16)(tp - tb - 2); *tb++ = (U8)(paramnamed >> 8); *tb++ = (U8)(paramnamed & 0xFF); paramnamed -= 2; *tb++ = (U8)(paramnamed >> 8); *tb = (U8)(paramnamed & 0xFF); #if SHARKSSL_RANDOMIZE_EXTENSIONS break; case 4: #endif #if (SHARKSSL_USE_ECC && (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1 || SHARKSSL_ECC_USE_SECP521R1)) #if SHARKSSL_TLS_1_2 baAssert(pwrdmenable == registerpwrdms); #endif { static const U8 tcpudpmagic[] = { #if SHARKSSL_ECC_USE_SECP521R1 0x00, buildmemmap, #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 0x00, resumeprepare, #endif #if (SHARKSSL_TLS_1_3 && SHARKSSL_ECC_USE_CURVE448) 0x00, TLS_NAMEDCURVE_CURVE448, #endif #if SHARKSSL_ECC_USE_SECP384R1 0x00, restoretrace, #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 0x00, entrytrampoline, #endif #if (SHARKSSL_TLS_1_3 && SHARKSSL_ECC_USE_CURVE25519) 0x00, TLS_NAMEDCURVE_CURVE25519, #endif #if SHARKSSL_ECC_USE_SECP256R1 0x00, spannedpages, #endif #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 0x00, samplingevent, #endif }; *tp++ = (U8)(pwrdmenable >> 8); *tp++ = (U8)(pwrdmenable & 0xFF); paramnamed = 2 + SHARKSSL_DIM_ARR(tcpudpmagic); *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); paramnamed -= 2; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); memcpy(tp, tcpudpmagic, SHARKSSL_DIM_ARR(tcpudpmagic)); tp += SHARKSSL_DIM_ARR(tcpudpmagic); #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { memcpy(tp, resetsources, SHARKSSL_DIM_ARR(resetsources)); tp += SHARKSSL_DIM_ARR(resetsources); } #endif } #endif #if SHARKSSL_RANDOMIZE_EXTENSIONS break; case 3: #endif #if (SHARKSSL_TLS_1_3 && SHARKSSL_ENABLE_SESSION_CACHE) #if SHARKSSL_TLS_1_2 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { *tp++ = (U8)(rm200hwint >> 8); *tp++ = (U8)(rm200hwint & 0xFF); *tp++ = 0x00; *tp++ = 0x02; *tp++ = 0x01; *tp++ = 0x01; } #endif #if SHARKSSL_RANDOMIZE_EXTENSIONS break; case 2: #endif #if (SHARKSSL_TLS_1_3 && SHARKSSL_ENABLE_CA_LIST && SHARKSSL_ENABLE_CA_EXTENSION) #if SHARKSSL_TLS_1_2 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if (o->caListCertReq) { SharkSslCert pCert; U8 *cp; baAssert(o->flags & SHARKSSL_FLAG_CA_EXTENSION_REQUEST); #if SHARKSSL_ENABLE_CERTSTORE_API baAssert(SHARKSSL_CA_LIST_PTR_SIZE == claimresource(SHARKSSL_CA_LIST_PTR_SIZE)); #endif if ((o->caListCertReq[0] != SHARKSSL_CA_LIST_INDEX_TYPE) #if SHARKSSL_ENABLE_CERTSTORE_API && (o->caListCertReq[0] != SHARKSSL_CA_LIST_PTR_TYPE) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } now_ccLen = ((U16)(o->caListCertReq[2]) << 8) + o->caListCertReq[3]; if (now_ccLen) { *tp++ = (U8)(shutdownnonboot >> 8); *tp++ = (U8)(shutdownnonboot & 0xFF); tb = tp; tp += 4; cp = (U8*)&(o->caListCertReq[4]); while (now_ccLen--) { int ret; U16 installidmap; #if SHARKSSL_ENABLE_CERTSTORE_API if (o->caListCertReq[0] == SHARKSSL_CA_LIST_PTR_TYPE) { pCert = *(SharkSslCert*)&cp[SHARKSSL_CA_LIST_NAME_SIZE]; cp += SHARKSSL_CA_LIST_NAME_SIZE + SHARKSSL_CA_LIST_PTR_SIZE; } else #endif { crLen = (U32)cp[SHARKSSL_CA_LIST_NAME_SIZE+0] << 24; crLen += (U32)cp[SHARKSSL_CA_LIST_NAME_SIZE+1] << 16; crLen += (U16)cp[SHARKSSL_CA_LIST_NAME_SIZE+2] << 8; crLen += cp[SHARKSSL_CA_LIST_NAME_SIZE+3]; pCert = (SharkSslCert)&(o->caListCertReq[crLen]); cp += SHARKSSL_CA_LIST_ELEMENT_SIZE; } ret = spromregister(0, (U8*)pCert, (U32)-2, (U8*)&installidmap); if (ret > 0) { pCert += (U32)ret; *tp++ = (U8)(installidmap >> 8); *tp++ = (U8)(installidmap & 0xFF); memcpy(tp, pCert, installidmap); tp += installidmap; } } paramnamed = (U16)(tp - tb - 2); *tb++ = (U8)(paramnamed >> 8); *tb++ = (U8)(paramnamed & 0xFF); paramnamed -= 2; *tb++ = (U8)(paramnamed >> 8); *tb = (U8)(paramnamed & 0xFF); } } } #endif #if SHARKSSL_RANDOMIZE_EXTENSIONS break; case 1: #endif #if (SHARKSSL_TLS_1_3 && SHARKSSL_USE_ECC) #if SHARKSSL_TLS_1_2 if (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { *tp++ = (U8)(reboothandler >> 8); *tp++ = (U8)(reboothandler & 0xFF); tb = tp; tp += 4; configvdcdc2.XY = NULL; #if SHARKSSL_ECC_USE_CURVE448 configvdcdc2.k = hsParam(o)->prot.tls13.privKeyCURVE448; i = configvdcdc2.xLen = SHARKSSL_CURVE448_POINTLEN; configvdcdc2.curveType = TLS_NAMEDCURVE_CURVE448; *tp++ = (U8)(configvdcdc2.curveType >> 8); *tp++ = (U8)(configvdcdc2.curveType & 0xFF); *tp++ = (U8)(i >> 8); *tp++ = (U8)(i & 0xFF); SharkSslECDHParam_ECDH(&configvdcdc2, signalpreserve, tp); tp += i; #endif #if SHARKSSL_ECC_USE_SECP384R1 configvdcdc2.k = hsParam(o)->prot.tls13.privKeySECP384R1; i = configvdcdc2.xLen = SHARKSSL_SECP384R1_POINTLEN; configvdcdc2.curveType = restoretrace; *tp++ = (U8)(configvdcdc2.curveType >> 8); *tp++ = (U8)(configvdcdc2.curveType & 0xFF); i <<= 1; i++; *tp++ = (U8)(i >> 8); *tp++ = (U8)(i & 0xFF); *tp++ = SHARKSSL_EC_POINT_UNCOMPRESSED; i--; SharkSslECDHParam_ECDH(&configvdcdc2, signalpreserve, tp); tp += i; #endif #if SHARKSSL_ECC_USE_CURVE25519 configvdcdc2.k = hsParam(o)->prot.tls13.privKeyCURVE25519; i = configvdcdc2.xLen = SHARKSSL_CURVE25519_POINTLEN; configvdcdc2.curveType = TLS_NAMEDCURVE_CURVE25519; *tp++ = (U8)(configvdcdc2.curveType >> 8); *tp++ = (U8)(configvdcdc2.curveType & 0xFF); *tp++ = (U8)(i >> 8); *tp++ = (U8)(i & 0xFF); SharkSslECDHParam_ECDH(&configvdcdc2, signalpreserve, tp); tp += i; #endif #if SHARKSSL_ECC_USE_SECP256R1 configvdcdc2.k = hsParam(o)->prot.tls13.privKeySECP256R1; i = configvdcdc2.xLen = SHARKSSL_SECP256R1_POINTLEN; configvdcdc2.curveType = spannedpages; *tp++ = (U8)(configvdcdc2.curveType >> 8); *tp++ = (U8)(configvdcdc2.curveType & 0xFF); i <<= 1; i++; *tp++ = (U8)(i >> 8); *tp++ = (U8)(i & 0xFF); *tp++ = SHARKSSL_EC_POINT_UNCOMPRESSED; i--; SharkSslECDHParam_ECDH(&configvdcdc2, signalpreserve, tp); tp += i; #endif paramnamed = (U16)(tp - tb - 2); *tb++ = (U8)(paramnamed >> 8); *tb++ = (U8)(paramnamed & 0xFF); paramnamed -= 2; *tb++ = (U8)(paramnamed >> 8); *tb = (U8)(paramnamed & 0xFF); } #endif #if SHARKSSL_RANDOMIZE_EXTENSIONS break; default: break; } #endif } #if (SHARKSSL_TLS_1_3 && SHARKSSL_ENABLE_SESSION_CACHE) tb = (U8*)0; if ((o->session) #if SHARKSSL_TLS_1_2 && (SharkSslSession_isProtocol(o->session, SHARKSSL_PROTOCOL_TLS_1_3)) #endif ) { now_ccLen = (U32)baGetUnixTime(); if (now_ccLen < o->session->prot.tls13.expiration) { #if 0 *tp++ = (U8)(rm200hwint >> 8); *tp++ = (U8)(rm200hwint & 0xFF); *tp++ = 0x00; *tp++ = 0x02; *tp++ = 0x01; *tp++ = 0x01; #endif *tp++ = (U8)(allocconsistent >> 8); *tp++ = (U8)(allocconsistent & 0xFF); tb = tp++; tp++; paramnamed = 6 + o->session->prot.tls13.ticketLen; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); paramnamed -= 6; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); memcpy(tp, o->session->prot.tls13.ticket, paramnamed); tp += paramnamed; now_ccLen -= o->session->firstAccess; now_ccLen *= 1000; now_ccLen += o->session->prot.tls13.ticketAgeAdd; *tp++ = (U8)(now_ccLen >> 24); *tp++ = (U8)(now_ccLen >> 16); *tp++ = (U8)(now_ccLen >> 8); *tp++ = (U8)(now_ccLen & 0xFF); i = sharkssl_getHashLen(o->session->cipherSuite->hashID) + 1; *tp++ = (U8)(i >> 8); *tp++ = (U8)(i & 0xFF); baAssert(i <= 0x100); *tp++ = (U8)--i; tp += i; paramnamed = (U16)(tp - tb - 2); *tb++ = (U8)(paramnamed >> 8); *tb = (U8)(paramnamed & 0xFF); tb = tp - i; } else { o->session = 0; } } #endif paramnamed = (U16)(tp - afterhandler - 2); *afterhandler++ = (U8)(paramnamed >> 8); *afterhandler = (U8)(paramnamed & 0xFF); hsLen = (U16)(tp - sp); *(sp - 2) = (U8)(hsLen >> 8); *(sp - 1) = (U8)(hsLen & 0xFF); paramnamed = (U16)(hsLen - traceentry); *(sp + 2) = (U8)(paramnamed >> 8); *(sp + 3) = (U8)(paramnamed & 0xFF); #if (SHARKSSL_TLS_1_3 && SHARKSSL_ENABLE_SESSION_CACHE) if (tb) { baAssert(o->session); ics = o->session->cipherSuite->hashID; paramnamed = sharkssl_getHashLen(ics); sharkssl_hash(tb, sp, (U16)(tb - sp - 3), ics); SharkSslCon_calcEarlySecret(o, o->session->prot.tls13.PSK, ics); if (sharkssl_HMAC(ics, tb, paramnamed, sharkSslHSParam->prot.tls13.HSSecret, paramnamed, tb) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } } #endif ioremapresource(sharkSslHSParam, sp, hsLen); o->inBuf.temp = (U16)(hsLen + clkctrlmanaged); o->state = trampolinehandler; return SharkSslCon_Handshake; } if ( (SharkSsl_isClient(o->sharkSsl)) && ( 0 #if (SHARKSSL_TLS_1_2 && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || ( #if SHARKSSL_TLS_1_3 (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) && #endif ((o->state == configcwfon) && (registeredevent) && (*registeredevent == logicmembank)) ) #endif #if SHARKSSL_TLS_1_3 || ( #if SHARKSSL_TLS_1_2 (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) && #endif (((o->state == logicmembank) && (registeredevent) && (*registeredevent == parsebootinfo)) || ((o->state == loongson3notifier) && (*registeredevent == SHARKSSL_HANDSHAKETYPE_NEW_SESSION_TICKET))) ) #endif ) ) { o->state = *registeredevent; } else #endif #if SHARKSSL_SSL_SERVER_CODE if ((o->state == loongson3notifier) && (*registeredevent == pciercxcfg070) #if SHARKSSL_SSL_CLIENT_CODE && (SharkSsl_isServer(o->sharkSsl)) #endif ) { baAssert(!(o->flags & audiosuspend)); #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & skciphersetkey) { o->flags &= ~skciphersetkey; } else #endif { return securememblock(o, SHARKSSL_ALERT_LEVEL_WARNING, SHARKSSL_ALERT_NO_RENEGOTIATION); } #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION o->flags |= platformdevice; o->flags &= ~(startqueue | switcheractivation); o->state = pciercxcfg070; #endif } else #endif { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); regionfixed: return savedconfig(o, SHARKSSL_ALERT_ILLEGAL_PARAMETER); } } registeredevent++; atagsprocfs--; if (atagsprocfs < 3) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (*registeredevent++) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } hsDataLen = (U16)(*registeredevent++) << 8; hsDataLen += (*registeredevent++); atagsprocfs -= 3; if (hsDataLen > SHARKSSL_MAX_DECRYPTED_REC_LEN) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (atagsprocfs < hsDataLen) { if ((o->state != pciercxcfg070) && (o->state != trampolinehandler) && (o->state != switcherdevice) && (o->state != loongson3notifier)) { o->flags |= SHARKSSL_FLAG_FRAGMENTED_HS_RECORD; registeredevent -= traceentry; if (o->inBuf.data != registeredevent) { o->inBuf.dataLen -= (U16)(registeredevent - o->inBuf.data); o->inBuf.data = registeredevent; } return SharkSslCon_Handshake; } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } atagsprocfs -= hsDataLen; tp = registeredevent - traceentry; hsLen = hsDataLen + traceentry; baAssert(!microresources(&o->outBuf)); #if (SHARKSSL_TLS_1_2 && SHARKSSL_ENABLE_SECURE_RENEGOTIATION) if ( #if SHARKSSL_TLS_1_3 (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) && #endif (o->flags & shutdownlevel) ) { baAssert(o->flags & platformdevice); o->flags &= ~shutdownlevel; reportsyscall(&o->tmpBuf, &o->outBuf); guestconfig5(&o->outBuf); o->outBuf = o->tmpBuf; memset(&o->tmpBuf, 0, sizeof(SharkSslBuf)); } #endif #if SHARKSSL_TLS_1_3 if ( #if SHARKSSL_TLS_1_2 (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) && #endif (o->state == SHARKSSL_HANDSHAKETYPE_NEW_SESSION_TICKET) ) { sharkSslHSParam = NULL; afterhandler = NULL; } else #endif { sharkSslHSParam = hsParam(o); afterhandler = (U8*)(sharkSslHSParam + 1); } #if (SHARKSSL_TLS_1_2 && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) if ( #if SHARKSSL_TLS_1_3 (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) && #endif ((pciercxcfg070 != o->state) && (switcherdevice != o->state)) ) { baAssert(0 == monadiccheck(sharkSslHSParam->certParam.certKey.expLen)); #if SHARKSSL_ENABLE_RSA #if (!SHARKSSL_USE_ECC) baAssert(machinekexec(sharkSslHSParam->certParam.certKey.expLen)); #else if (machinekexec(sharkSslHSParam->certParam.certKey.expLen)) #endif { afterhandler += supportedvector(sharkSslHSParam->certParam.certKey.modLen); afterhandler += claimresource(mousethresh(sharkSslHSParam->certParam.certKey.expLen)); } #if SHARKSSL_USE_ECC else #endif #endif #if SHARKSSL_USE_ECC if (machinereboot(sharkSslHSParam->certParam.certKey.expLen)) { afterhandler += (U16)(attachdevice(sharkSslHSParam->certParam.certKey.modLen)) * 2; } #endif #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if ((sharkSslHSParam->cipherSuite) && (sharkSslHSParam->cipherSuite->flags & cleandcache)) #endif { #if SHARKSSL_ENABLE_DHE_RSA if (sharkSslHSParam->cipherSuite->flags & percpudevid) { afterhandler += sharkSslHSParam->prot.tls12.dhParam.pLen; #if SHARKSSL_SSL_CLIENT_CODE if (SharkSsl_isClient(o->sharkSsl)) { afterhandler += sharkSslHSParam->prot.tls12.dhParam.pLen; afterhandler += sharkSslHSParam->prot.tls12.dhParam.gLen; } #endif } #endif #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { afterhandler += sharkSslHSParam->ecdhParam.xLen; #if SHARKSSL_SSL_CLIENT_CODE if (SharkSsl_isClient(o->sharkSsl)) { afterhandler += sharkSslHSParam->ecdhParam.xLen; } #endif #if (SHARKSSL_ECC_USE_SECP521R1 && (SHARKSSL_ALIGNMENT >= 4)) afterhandler = (U8*)regulatorconsumer(afterhandler); #endif } #endif } } #endif baAssert(pcmciaplatform(afterhandler)); switch (o->state) { #if SHARKSSL_TLS_1_2 #if SHARKSSL_SSL_SERVER_CODE case pciercxcfg070: baAssert(SharkSsl_isServer(o->sharkSsl)); baAssert(serial2platform(&o->inBuf)); baAssert(pcmciaplatform(func3fixup(&o->inBuf))); baAssert(pcmciaplatform(func3fixup(&o->outBuf))); if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } o->reqMajor = *registeredevent++; o->reqMinor = *registeredevent++; hsDataLen -= 2; if (o->reqMajor != 3) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_handshake_failure; } o->major = 3; if (o->reqMinor >= 3) { o->minor = 3; } else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); _sharkssl_hs_alert_handshake_failure: return savedconfig(o, SHARKSSL_ALERT_HANDSHAKE_FAILURE); } breakpointhandler(sharkSslHSParam); ioremapresource(sharkSslHSParam, tp, hsLen); memset(afterhandler, 0, (4 * (sizeof(SharkSslCertParsed**) + sizeof(SHARKSSL_WEIGHT)))); afterhandler += (4 * (sizeof(SharkSslCertParsed**) + sizeof(SHARKSSL_WEIGHT))); SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tp = afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tp += sizeof(SHARKSSL_WEIGHT)) { *(SHARKSSL_WEIGHT*)tp = 0; #if SHARKSSL_ENABLE_RSA if (((SharkSslCertList*)link)->certP.keyType == ahashchild) { *(SHARKSSL_WEIGHT*)tp = trainingneeded + ahashchild; } #if SHARKSSL_USE_ECC else #endif #endif #if SHARKSSL_USE_ECC if (((SharkSslCertList*)link)->certP.keyType == compatrestart) { *(SHARKSSL_WEIGHT*)tp = compatrestart + (((SharkSslCertList*)link)->certP.keyOID) + (U16)(((SharkSslCertList*)link)->certP.signatureAlgo); } #endif { if (((SharkSslCertList*)link)->certP.hashAlgo <= presentpages) { *(SHARKSSL_WEIGHT*)tp |= smbuswrite; } } } baAssert(tp != afterhandler); *(SHARKSSL_WEIGHT*)tp = (SHARKSSL_WEIGHT)-1; baAssert(!(o->flags & startqueue)); if (hsDataLen < (1 + SHARKSSL_RANDOM_LEN)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } memcpy(sharkSslHSParam->prot.tls12.clientRandom, registeredevent, SHARKSSL_RANDOM_LEN); registeredevent += SHARKSSL_RANDOM_LEN; setupinterface = *registeredevent++; hsDataLen -= (1 + SHARKSSL_RANDOM_LEN); if (setupinterface > 0) { if ((hsDataLen < setupinterface) || (setupinterface > SHARKSSL_MAX_SESSION_ID_LEN)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #if SHARKSSL_ENABLE_SESSION_CACHE #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & platformdevice) { if (o->session) { SharkSslSession_release(o->session, o->sharkSsl); } o->session = (SharkSslSession*)0; } else #endif { o->session = latchgpiochip(&o->sharkSsl->sessionCache, o, registeredevent, setupinterface); if (o->session) { o->flags |= startqueue; } } #endif registeredevent += setupinterface; hsDataLen -= setupinterface; } if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } tb = registeredevent; paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if ((paramnamed == 0) || (paramnamed & 0x01) || (hsDataLen < paramnamed)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } registeredevent += paramnamed; hsDataLen -= paramnamed; if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } setupinterface = *registeredevent++; hsDataLen--; if ((hsDataLen < setupinterface) || (setupinterface == 0)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } do { paramnamed = *registeredevent++; hsDataLen--; setupinterface--; } while ((setupinterface) && (paramnamed != cminstclear)); if (paramnamed != cminstclear) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_handshake_failure; } registeredevent += setupinterface; hsDataLen -= setupinterface; if (hsDataLen) { if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if (hsDataLen != paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #if SHARKSSL_TLS_1_3 #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_SSL_CLIENT_CODE) now_ccLen = earlyalloc(o, registeredevent, paramnamed, SharkSsl_Server); #else now_ccLen = earlyalloc(o, registeredevent, paramnamed); #endif #else now_ccLen = 0; #endif switch (now_ccLen) { #if SHARKSSL_TLS_1_3 case SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3): if (SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2) == o->minor) { o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); } else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_PROTOCOL_VERSION); } break; case SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2): #if SHARKSSL_TLS_1_2 if ((o->minor == 0) || (SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2) == o->minor)) { o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); break; } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; #else goto _sharkssl_hs_alert_protocol_version; #endif break; #endif case 0: if (o->minor == 0) { #if SHARKSSL_TLS_1_2 o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); break; #endif } #if SHARKSSL_TLS_1_2 else if (SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2) == o->minor) { break; } #endif default: SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; break; } i = (U16)writepmresr(o, (SHARKSSL_WEIGHT*)afterhandler, registeredevent, paramnamed); if (i != 0) { #if SHARKSSL_ENABLE_ALPN_EXTENSION if ((U16)-2 == i) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_NO_APPLICATION_PROTOCOL); } #endif #if SHARKSSL_TLS_1_3 if ((U16)-3 == i) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_MISSING_EXTENSION); } #endif goto _sharkssl_hs_alert_handshake_failure; } hsDataLen -= paramnamed; } else { #if SHARKSSL_TLS_1_2 o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_PROTOCOL_VERSION); #endif } #if SHARKSSL_ENABLE_SNI i = 0; tp = afterhandler; while (*(SHARKSSL_WEIGHT*)tp != (SHARKSSL_WEIGHT)-1) { if (*(SHARKSSL_WEIGHT*)tp & clearevent) { i++; break; } tp += sizeof(SHARKSSL_WEIGHT); } #endif tp = afterhandler; while (*(SHARKSSL_WEIGHT*)tp != (SHARKSSL_WEIGHT)-1) { if ( ( (*(SHARKSSL_WEIGHT*)tp) && ( (!(*(SHARKSSL_WEIGHT*)tp & trainingneeded)) || ((o->minor >= 3) && (!(*(SHARKSSL_WEIGHT*)tp & smbuswrite))) ) ) #if SHARKSSL_ENABLE_SNI || ((i > 0) && (!(*(SHARKSSL_WEIGHT*)tp & clearevent))) #endif ) { *(SHARKSSL_WEIGHT*)tp = 0; } tp += sizeof(SHARKSSL_WEIGHT); } tp = afterhandler; afterhandler -= (4 * (sizeof(SharkSslCertParsed**) + sizeof(SHARKSSL_WEIGHT))); SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tp += sizeof(SHARKSSL_WEIGHT)) { #if SHARKSSL_ENABLE_RSA if (((SharkSslCertList*)link)->certP.keyType == ahashchild) { if (((SharkSslCertList*)link)->certP.signatureAlgo == entryearly) { if ((*(SHARKSSL_WEIGHT*)tp) && (*(SHARKSSL_WEIGHT*)tp > *(SHARKSSL_WEIGHT*)(afterhandler + 4 * sizeof(SharkSslCertParsed**)))) { *(SHARKSSL_WEIGHT*)(afterhandler + 4 * sizeof(SharkSslCertParsed**)) = *(SHARKSSL_WEIGHT*)tp; *(SharkSslCertParsed**)afterhandler = &(((SharkSslCertList*)link)->certP); } } } #if (SHARKSSL_USE_ECC || SHARKSSL_ENABLE_ECDSA) else #endif #endif #if (SHARKSSL_USE_ECC || SHARKSSL_ENABLE_ECDSA) if (((SharkSslCertList*)link)->certP.keyType == compatrestart) { if (((SharkSslCertList*)link)->certP.signatureAlgo == accessactive) { if ((*(SHARKSSL_WEIGHT*)tp) && (*(SHARKSSL_WEIGHT*)tp > *(SHARKSSL_WEIGHT*)(afterhandler + 4 * sizeof(SharkSslCertParsed**) + 2 * sizeof(SHARKSSL_WEIGHT)))) { *(SHARKSSL_WEIGHT*)(afterhandler + 4 * sizeof(SharkSslCertParsed**) + 2 * sizeof(SHARKSSL_WEIGHT)) = *(SHARKSSL_WEIGHT*)tp; *(SharkSslCertParsed**)(afterhandler + 2 * sizeof(SharkSslCertParsed**)) = &(((SharkSslCertList*)link)->certP); } } #if SHARKSSL_ENABLE_RSA else if (((SharkSslCertList *)link)->certP.signatureAlgo == entryearly) { if ((*(SHARKSSL_WEIGHT*)tp) && (*(SHARKSSL_WEIGHT*)tp > *(SHARKSSL_WEIGHT*)(afterhandler + 4 * sizeof(SharkSslCertParsed**) + 1 * sizeof(SHARKSSL_WEIGHT)))) { *(SHARKSSL_WEIGHT*)(afterhandler + 4 * sizeof(SharkSslCertParsed**) + 1 * sizeof(SHARKSSL_WEIGHT)) = *(SHARKSSL_WEIGHT*)tp; *(SharkSslCertParsed**)(afterhandler + 1 * sizeof(SharkSslCertParsed**)) = &(((SharkSslCertList*)link)->certP); } } #endif } #endif } baAssert(*(SHARKSSL_WEIGHT*)tp == (SHARKSSL_WEIGHT)-1); baAssert(!(sharkSslHSParam->cipherSuite)); baAssert(SHARKSSL_DIM_ARR(genericsuspend) < 0xFF); ics = 0xFF; crLen = 0; #define crLen_FLAG_stream_cipher_found 0x01 #define crLen_FLAG_RSA_ciphersuite_found 0x02 #define crLen_FLAG_stream_RSA_found 0x04 paramnamed = (U16)(*tb++) >> 8; paramnamed += *tb++; while (paramnamed) { i = (U16)(*tb++) << 8; i += *tb++; paramnamed -= 2; #if SHARKSSL_ENABLE_SESSION_CACHE if (o->flags & startqueue) { baAssert(o->session); if ((o->session->cipherSuite) && (i == o->session->cipherSuite->id)) { sharkSslHSParam->cipherSuite = o->session->cipherSuite; break; } } else #endif { if (deviceunregister == i) { #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & platformdevice) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_handshake_failure; } #endif o->flags |= aarch32ptrace; } #if SHARKSSL_ENABLE_SELECT_CIPHERSUITE else if (o->cipherSelCtr) { for (now_ccLen = 0; now_ccLen < o->cipherSelCtr; now_ccLen++) { setupinterface = o->cipherSelection[now_ccLen]; if ( (i == genericsuspend[setupinterface].id) #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) && ((sharkSslHSParam->ecdhParam.xLen) || (!(genericsuspend[setupinterface].flags & irqhandlerfixup))) #endif ) { if ((now_ccLen < ics) && (0 == SharkSslHSParam_setCert(sharkSslHSParam, (SharkSslCertParsed**)afterhandler, genericsuspend[setupinterface].flags))) { ics = (U8)now_ccLen; } } } } #endif else { for (now_ccLen = 0; now_ccLen < SHARKSSL_DIM_ARR(genericsuspend); now_ccLen++) { if ( (i == genericsuspend[now_ccLen].id) #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) && ((sharkSslHSParam->ecdhParam.xLen) || (!(genericsuspend[now_ccLen].flags & irqhandlerfixup))) #endif ) { #if SHARKSSL_ENABLE_RSA if ((o->flags & uprobeabort) && (genericsuspend[now_ccLen].flags & percpudevid)) { if ((!(crLen & crLen_FLAG_RSA_ciphersuite_found)) || ((U8)now_ccLen < ics)) { if (0 == SharkSslHSParam_setCert(sharkSslHSParam, (SharkSslCertParsed**)afterhandler, genericsuspend[now_ccLen].flags)) { crLen |= crLen_FLAG_RSA_ciphersuite_found; ics = (U8)now_ccLen; } } } else #endif { if ((now_ccLen < ics) #if SHARKSSL_ENABLE_RSA && (!(crLen & crLen_FLAG_RSA_ciphersuite_found)) #endif && (0 == SharkSslHSParam_setCert(sharkSslHSParam, (SharkSslCertParsed**)afterhandler, genericsuspend[now_ccLen].flags)) ) { ics = (U8)now_ccLen; } } } } } } } #undef crLen_FLAG_stream_cipher_found #undef crLen_FLAG_RSA_ciphersuite_found #undef crLen_FLAG_stream_RSA_found if (!(sharkSslHSParam->cipherSuite)) { if (ics == 0xFF) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_handshake_failure; } #if SHARKSSL_ENABLE_SELECT_CIPHERSUITE if (o->cipherSelCtr) { sharkSslHSParam->cipherSuite = (SharkSslCipherSuite*)&genericsuspend[o->cipherSelection[ics]]; } else #endif { sharkSslHSParam->cipherSuite = (SharkSslCipherSuite*)&genericsuspend[ics]; } } if (hsDataLen > 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_DECODE_ERROR); } o->inBuf.temp = 0; #if SHARKSSL_ENABLE_SESSION_CACHE if (!(o->flags & startqueue)) { o->session = sa1111device(&o->sharkSsl->sessionCache, o, 0, 0); } #endif crLen = paramnamed = 0; if (o->flags & aarch32ptrace) { #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & platformdevice) { crLen = 1 + 2 * SHARKSSL_FINISHED_MSG_LEN_TLS_1_2; paramnamed += 2 + 2 + (U16)crLen; } else #endif { paramnamed += SHARKSSL_DIM_ARR(registeraudio); } } #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { paramnamed += SHARKSSL_DIM_ARR(resetsources); } #endif #if SHARKSSL_ENABLE_ALPN_EXTENSION if (o->rALPN) { paramnamed += *o->rALPN + 7; memcpy(afterhandler, o->rALPN, *o->rALPN + 1); } #endif sp = o->inBuf.data + clkctrlmanaged; tp = sp + traceentry; *tp++ = o->major; *tp++ = o->minor; now_ccLen = (U32)baGetUnixTime(); *tp++ = (U8)(now_ccLen >> 24); *tp++ = (U8)(now_ccLen >> 16); *tp++ = (U8)(now_ccLen >> 8); *tp++ = (U8)(now_ccLen & 0xFF); if (sharkssl_rng(tp, (SHARKSSL_RANDOM_LEN - 4)) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } tp += (SHARKSSL_RANDOM_LEN - 4); memcpy(sharkSslHSParam->prot.tls12.serverRandom, tp - SHARKSSL_RANDOM_LEN, SHARKSSL_RANDOM_LEN); #if SHARKSSL_ENABLE_SESSION_CACHE if (o->session) { *tp++ = SHARKSSL_MAX_SESSION_ID_LEN; memcpy(tp, o->session->prot.tls12.id, SHARKSSL_MAX_SESSION_ID_LEN); tp += SHARKSSL_MAX_SESSION_ID_LEN; } else #endif { *tp++ = 0; } *tp++ = (U8)(sharkSslHSParam->cipherSuite->id >> 8); *tp++ = (U8)(sharkSslHSParam->cipherSuite->id & 0xFF); *tp++ = 0; if (paramnamed) { *tp++ = (paramnamed >> 8); *tp++ = (paramnamed & 0xFF); if (o->flags & aarch32ptrace) { #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & platformdevice) { *tp++ = (featurespresent >> 8); *tp++ = (featurespresent & 0xFF); *tp++ = 0x00; *tp++ = crLen & 0xFF; *tp++ = (--crLen) & 0xFF; baAssert((crLen & 1) == 0); crLen >>= 1; memcpy(tp, o->clientVerifyData, crLen); tp+= crLen; memcpy(tp, o->serverVerifyData, crLen); tp+= crLen; } else #endif { memcpy(tp, registeraudio, SHARKSSL_DIM_ARR(registeraudio)); tp += SHARKSSL_DIM_ARR(registeraudio); } } #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { memcpy(tp, resetsources, SHARKSSL_DIM_ARR(resetsources)); tp += SHARKSSL_DIM_ARR(resetsources); } #endif #if SHARKSSL_ENABLE_ALPN_EXTENSION if (o->rALPN) { *tp++ = (U8)(clkdmclear >> 8); *tp++ = (U8)(clkdmclear & 0xFF); *tp++ = 0x00; *tp++ = *afterhandler + 3; *tp++ = 0x00; *tp++ = *afterhandler + 1; memcpy(tp, afterhandler, *afterhandler + 1); tp += *afterhandler + 1; } #endif } i = (U16)(tp - sp) - traceentry; sp[0] = trampolinehandler; sp[1] = 0; sp[2] = (U8)(i >> 8); sp[3] = (U8)(i & 0xFF); #if SHARKSSL_ENABLE_SESSION_CACHE if (o->flags & startqueue) { memcpy(sharkSslHSParam->prot.tls12.masterSecret, o->session->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN); paramnamed = disableclean(sharkSslHSParam->cipherSuite); if (allocalloc(o, sharkSslHSParam->prot.tls12.sharedSecret, paramnamed, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, sharkSslHSParam->prot.tls12.serverRandom, sharkSslHSParam->prot.tls12.clientRandom) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } i += traceentry; tp = templateentry(o, controllegacy, sp - clkctrlmanaged, i); ioremapresource(sharkSslHSParam, tp, i); tp += i; #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION baAssert(!(o->flags & platformdevice)); #endif if (sanitisependbaser(o, rodatastart, tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } o->state = switcherdevice; } else #endif { baAssert(sharkSslHSParam->certParsed); i = sharkSslHSParam->certParsed->msgLen; *tp++ = parsebootinfo; *tp++ = 0x00; *tp++ = (i >> 8); *tp++ = (i & 0xFF); if (fixupresources(sharkSslHSParam->certParsed->cert, i, tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } tp += i; if (0 == interrupthandler(&(sharkSslHSParam->certKey), sharkSslHSParam->certParsed->cert)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_CertificateError; } #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & cleandcache) { tb = tp; tp += traceentry; #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { baAssert(sharkSslHSParam->ecdhParam.curveType); baAssert(sharkSslHSParam->ecdhParam.xLen); sharkSslHSParam->ecdhParam.k = afterhandler; afterhandler += sharkSslHSParam->ecdhParam.xLen; #if (SHARKSSL_ECC_USE_SECP521R1 && (SHARKSSL_ALIGNMENT >= 4)) afterhandler = (U8*)regulatorconsumer(afterhandler); #endif *tp++ = mcbsp5hwmod; *tp++ = (sharkSslHSParam->ecdhParam.curveType >> 8); *tp++ = (sharkSslHSParam->ecdhParam.curveType & 0xFF); #if SHARKSSL_ECC_USE_EDWARDS if ((sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE25519) || (sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE448)) { paramnamed = sharkSslHSParam->ecdhParam.xLen; *tp++ = (U8)(paramnamed); i = 4; } else #endif { paramnamed = (U16)(sharkSslHSParam->ecdhParam.xLen << 1); baAssert(paramnamed < 0x00FF); *tp++ = (U8)(paramnamed + 1); *tp++ = SHARKSSL_EC_POINT_UNCOMPRESSED; i = 5; } if ((int)SharkSslCon_AllocationError == SharkSslECDHParam_ECDH(&(sharkSslHSParam->ecdhParam), signalpreserve, tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } } else #endif { #if SHARKSSL_ENABLE_DHE_RSA U8 *g; SharkSslDHParam_setParam(&(sharkSslHSParam->prot.tls12.dhParam)); baAssert(pcmciaplatform(afterhandler)); sharkSslHSParam->prot.tls12.dhParam.r = afterhandler; paramnamed = sharkSslHSParam->prot.tls12.dhParam.pLen; afterhandler += paramnamed; i = 6; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); memcpy(tp, sharkSslHSParam->prot.tls12.dhParam.p, paramnamed); tp += paramnamed; i += paramnamed; g = sharkSslHSParam->prot.tls12.dhParam.g; crLen = sharkSslHSParam->prot.tls12.dhParam.gLen; while ((0 == *g) && (crLen > 1)) { g++; crLen--; } *tp++ = (U8)(crLen >> 8); *tp++ = (U8)(crLen & 0xFF); memcpy(tp, g, crLen); tp += (U16)crLen; i += (U16)crLen; *tp++ = (U8)(paramnamed >> 8); *tp++ = (U8)(paramnamed & 0xFF); if ((int)SharkSslCon_AllocationError == SharkSslDHParam_DH(&(sharkSslHSParam->prot.tls12.dhParam), cpucfgexits, tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); #endif } tp += paramnamed; i += paramnamed; baAssert(pcmciaplatform(afterhandler)); memcpy(afterhandler, sharkSslHSParam->prot.tls12.clientRandom, SHARKSSL_RANDOM_LEN); memcpy(afterhandler + SHARKSSL_RANDOM_LEN, sharkSslHSParam->prot.tls12.serverRandom, SHARKSSL_RANDOM_LEN); memcpy(afterhandler + (2 * SHARKSSL_RANDOM_LEN), (tp - i), i); i += (2 * SHARKSSL_RANDOM_LEN); sharkSslHSParam->signParam.pCertKey = &(sharkSslHSParam->certKey); #if SHARKSSL_ENABLE_RSA if (machinekexec(sharkSslHSParam->signParam.pCertKey->expLen)) { sharkSslHSParam->signParam.signature.hashAlgo = sharkSslHSParam->signParam.signature.signatureAlgo; sharkSslHSParam->signParam.signature.signatureAlgo = entryearly; } #endif #if SHARKSSL_ENABLE_ECDSA if (machinereboot(sharkSslHSParam->signParam.pCertKey->expLen)) { sharkSslHSParam->signParam.signature.signatureAlgo = accessactive; } #endif if (!(sharkSslHSParam->signParam.signature.hashAlgo)) { sharkSslHSParam->signParam.signature.hashAlgo = presentpages; } if (sharkssl_hash(sharkSslHSParam->signParam.signature.hash, afterhandler, i, sharkSslHSParam->signParam.signature.hashAlgo)) { return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } *tp++ = sharkSslHSParam->signParam.signature.hashAlgo; *tp++ = sharkSslHSParam->signParam.signature.signatureAlgo; sharkSslHSParam->signParam.signature.signature = tp + 2; if (checkactions(&(sharkSslHSParam->signParam)) < 0) { return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } *tp++ = (sharkSslHSParam->signParam.signature.signLen >> 8); *tp++ = (sharkSslHSParam->signParam.signature.signLen & 0xFF); tp += sharkSslHSParam->signParam.signature.signLen; i = (U16)(tp - tb) - traceentry; tb[0] = startflags; tb[1]= 0; tb[2] = (U8)(i >> 8); tb[3] = (U8)(i & 0xFF); } #endif #if (SHARKSSL_ENABLE_CLIENT_AUTH && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) if (o->flags & unregistershash) { static const U8 serialwakeup[] = { #if SHARKSSL_ENABLE_ECDSA #if SHARKSSL_USE_SHA_512 batterythread, accessactive, #endif #if SHARKSSL_USE_SHA_384 probewrite, accessactive, #endif domainnumber, accessactive, presentpages, accessactive, #endif #if SHARKSSL_ENABLE_RSA #if SHARKSSL_USE_SHA_512 batterythread, entryearly, #endif #if SHARKSSL_USE_SHA_384 probewrite, entryearly, #endif domainnumber, entryearly, #if SHARKSSL_USE_SHA1 presentpages, entryearly, #endif #if SHARKSSL_USE_MD5 skciphercreate, entryearly #endif #endif }; tb = tp; tp += traceentry; ics = 0; #if SHARKSSL_ENABLE_RSA tp[++ics] = ahashchild; #endif #if SHARKSSL_ENABLE_ECDSA { tp[++ics] = compatrestart; } #endif *tp++ = ics; tp += ics; *tp++ = (U8)(SHARKSSL_DIM_ARR(serialwakeup) >> 8); *tp++ = (U8)(SHARKSSL_DIM_ARR(serialwakeup) & 0xFF); memcpy(tp, serialwakeup, SHARKSSL_DIM_ARR(serialwakeup)); tp += SHARKSSL_DIM_ARR(serialwakeup); #if SHARKSSL_ENABLE_CA_LIST if (o->caListCertReq) { SharkSslCert pCert; U8 *cp; #if SHARKSSL_ENABLE_CERTSTORE_API baAssert(SHARKSSL_CA_LIST_PTR_SIZE == claimresource(SHARKSSL_CA_LIST_PTR_SIZE)); #endif if ((o->caListCertReq[0] != SHARKSSL_CA_LIST_INDEX_TYPE) #if SHARKSSL_ENABLE_CERTSTORE_API && (o->caListCertReq[0] != SHARKSSL_CA_LIST_PTR_TYPE) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } now_ccLen = ((U16)(o->caListCertReq[2]) << 8) + o->caListCertReq[3]; if (0 == now_ccLen) { goto _sharkssl_empty_CA_DN; } paramnamed = 2; cp = (U8*)&(o->caListCertReq[4]); while (now_ccLen--) { int ret; U16 installidmap; #if SHARKSSL_ENABLE_CERTSTORE_API if (o->caListCertReq[0] == SHARKSSL_CA_LIST_PTR_TYPE) { pCert = *(SharkSslCert*)&cp[SHARKSSL_CA_LIST_NAME_SIZE]; cp += SHARKSSL_CA_LIST_NAME_SIZE + SHARKSSL_CA_LIST_PTR_SIZE; } else #endif { crLen = (U32)cp[SHARKSSL_CA_LIST_NAME_SIZE+0] << 24; crLen += (U32)cp[SHARKSSL_CA_LIST_NAME_SIZE+1] << 16; crLen += (U16)cp[SHARKSSL_CA_LIST_NAME_SIZE+2] << 8; crLen += cp[SHARKSSL_CA_LIST_NAME_SIZE+3]; pCert = (SharkSslCert)&(o->caListCertReq[crLen]); cp += SHARKSSL_CA_LIST_ELEMENT_SIZE; } ret = spromregister(0, (U8*)pCert, (U32)-2, (U8*)&installidmap); if (ret > 0) { pCert += (U32)ret; tp[paramnamed++] = (U8)(installidmap >> 8); tp[paramnamed++] = (U8)(installidmap & 0xFF); memcpy(tp + paramnamed, pCert, installidmap); paramnamed += installidmap; } } paramnamed -= 2; *tp++ = (paramnamed >> 8); *tp++ = (paramnamed & 0xFF); tp += paramnamed; } else #endif { #if SHARKSSL_ENABLE_CA_LIST _sharkssl_empty_CA_DN: #endif *tp++ = 0; *tp++ = 0; } i = (U16)(tp - tb) - traceentry; tb[0] = logicmembank; tb[1]= 0; tb[2] = (U8)(i >> 8); tb[3] = (U8)(i & 0xFF); } else { o->flags &= ~unregistershash; } #endif if (o->flags & unregistershash) { o->state = parsebootinfo; } else { o->state = subtableheaders; } *tp++ = configcwfon; *tp++ = 0x00; *tp++ = 0x00; *tp++ = 0x00; i = (U16)(tp - sp); templateentry(o, controllegacy, sp - clkctrlmanaged, i); ioremapresource(sharkSslHSParam, sp, i); } o->inBuf.temp += (U16)(tp - o->inBuf.data); #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & platformdevice) { o->tmpBuf = o->outBuf; paramnamed = claimresource(r3000tlbchange(o) + o->inBuf.temp); atomiccmpxchg(&o->outBuf, paramnamed); if (microresources(&o->outBuf)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } reportsyscall(&o->outBuf, &o->tmpBuf); memcpy(func3fixup(&o->outBuf), sp - clkctrlmanaged, o->inBuf.temp); if (SharkSslCon_calcMACAndEncrypt(o) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } o->inBuf.temp = o->outBuf.dataLen; o->flags |= (createmappings | shutdownlevel); } #endif return SharkSslCon_Handshake; case subtableheaders: ioremapresource(sharkSslHSParam, registeredevent - traceentry, hsLen); #if SHARKSSL_USE_ECC if (!(sharkSslHSParam->cipherSuite->flags & irqhandlerfixup)) #endif { if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++ << 8); paramnamed += *registeredevent++; hsDataLen -= 2; if ((paramnamed != hsDataLen) || (paramnamed == 0)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } } ics = 0; #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & (cleandcache | irqhandlerfixup)) { #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (*registeredevent++); hsDataLen--; #if SHARKSSL_ECC_USE_EDWARDS if ((sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE25519) || (sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE448)) { i = sharkSslHSParam->ecdhParam.xLen; if ((hsDataLen < paramnamed) || (paramnamed != i)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } } else #endif { if (*registeredevent++ != SHARKSSL_EC_POINT_UNCOMPRESSED) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } hsDataLen--; paramnamed--; i = sharkSslHSParam->ecdhParam.xLen; if ((hsDataLen < paramnamed) || (paramnamed != (U16)(i << 1))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } } sharkSslHSParam->ecdhParam.XY = registeredevent; if ((int)SharkSslCon_AllocationError == SharkSslECDHParam_ECDH(&(sharkSslHSParam->ecdhParam), switcheractive, afterhandler)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } tb = afterhandler; } else #endif { #if SHARKSSL_ENABLE_DHE_RSA paramnamed = sharkSslHSParam->prot.tls12.dhParam.pLen; baAssert(paramnamed > 2); if (hsDataLen != paramnamed) { if (hsDataLen != (paramnamed - 1)) { if (hsDataLen != (paramnamed - 2)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } registeredevent--; *registeredevent = 0; } registeredevent--; *registeredevent = 0; } sharkSslHSParam->prot.tls12.dhParam.Y = registeredevent; if ((int)SharkSslCon_AllocationError == SharkSslDHParam_DH(&(sharkSslHSParam->prot.tls12.dhParam), switcheractive, afterhandler)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } tb = afterhandler; while ((0 == *tb) && (paramnamed)) { paramnamed--; tb++; *registeredevent++ = 0; } i = paramnamed; #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); #endif } } else #endif { #if SHARKSSL_ENABLE_RSA int ret; paramnamed = supportedvector(sharkSslHSParam->certKey.modLen); if (hsDataLen != paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } ret = (int)writemessage(&(sharkSslHSParam->certKey), paramnamed, registeredevent, registeredevent, SHARKSSL_RSA_PKCS1_PADDING); if (sharkssl_rng(afterhandler, SHARKSSL_MASTER_SECRET_LEN) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_clear_premaster; } ret = (int)((ret != SHARKSSL_MASTER_SECRET_LEN) & 1); tb = registeredevent + (ret * (int)(afterhandler - registeredevent)); tb[0] = o->major; ret = (int)((tb[1] != o->reqMinor) & 1) * (int)((tb[1] != o->minor) & 1); tb[1] = (U8)(tb[1] + (U8)(ret * (U8)(o->reqMinor - tb[1]))); ics = 0; i = SHARKSSL_MASTER_SECRET_LEN; #else paramnamed = i = 0; #endif } if (allocalloc(o, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, tb, i, sharkSslHSParam->prot.tls12.clientRandom, sharkSslHSParam->prot.tls12.serverRandom) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); ics = 1; } i = disableclean(sharkSslHSParam->cipherSuite); if (allocalloc(o, sharkSslHSParam->prot.tls12.sharedSecret, i, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, sharkSslHSParam->prot.tls12.serverRandom, sharkSslHSParam->prot.tls12.clientRandom) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); ics = 1; } #if SHARKSSL_ENABLE_RSA _sharkssl_hs_clear_premaster: #endif memset(registeredevent, 0, paramnamed); registeredevent += paramnamed; if (ics > 0) { resvdexits(o); return SharkSslCon_Error; } #if SHARKSSL_ENABLE_SESSION_CACHE if (o->session) { filtermatch(&o->sharkSsl->sessionCache); memcpy(o->session->prot.tls12.masterSecret, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN); helperglobal(&o->sharkSsl->sessionCache); } #endif if (o->flags & unregistershash) { o->state = modifygraph; } else { o->state = switcherdevice; } if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif #endif #if SHARKSSL_SSL_CLIENT_CODE case trampolinehandler: #if !SHARKSSL_ENABLE_SNI baAssert(serial2platform(&o->inBuf)); #endif baAssert(pcmciaplatform(func3fixup(&o->inBuf))); baAssert(pcmciaplatform(func3fixup(&o->outBuf))); if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (*registeredevent++ != o->major) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); #if (!SHARKSSL_TLS_1_2 || !SHARKSSL_SSL_SERVER_CODE) _sharkssl_hs_alert_handshake_failure: #endif return savedconfig(o, SHARKSSL_ALERT_HANDSHAKE_FAILURE); } if (*registeredevent++ != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_handshake_failure; } hsDataLen -= 2; if (hsDataLen < (1 + SHARKSSL_RANDOM_LEN)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #if SHARKSSL_TLS_1_2 memcpy(sharkSslHSParam->prot.tls12.serverRandom, registeredevent, SHARKSSL_RANDOM_LEN); #endif registeredevent += SHARKSSL_RANDOM_LEN; setupinterface = *registeredevent++; hsDataLen -= (1 + SHARKSSL_RANDOM_LEN); if ((hsDataLen < setupinterface) || (setupinterface > SHARKSSL_MAX_SESSION_ID_LEN)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sp = registeredevent; registeredevent += setupinterface; hsDataLen -= setupinterface; #if (SHARKSSL_TLS_1_3 && SHARKSSL_ENABLE_SESSION_CACHE) if (setupinterface > 0) { if ((o->session) && (SharkSslSession_isProtocol(o->session, SHARKSSL_PROTOCOL_TLS_1_3))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } } #endif if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; ics = SHARKSSL_DIM_ARR(genericsuspend); while (ics--) { if (paramnamed == genericsuspend[ics].id) { sharkSslHSParam->cipherSuite = (SharkSslCipherSuite*)&genericsuspend[ics]; break; } } if (!(sharkSslHSParam->cipherSuite)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_handshake_failure; } if ((hsDataLen < 1) || (*registeredevent++ != 0)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } hsDataLen--; if (hsDataLen) { if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); updatereserved: return savedconfig(o, SHARKSSL_ALERT_DECODE_ERROR); } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if (hsDataLen != paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } #if SHARKSSL_TLS_1_3 #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_SSL_CLIENT_CODE) now_ccLen = earlyalloc(o, registeredevent, paramnamed, SharkSsl_Client); #else now_ccLen = earlyalloc(o, registeredevent, paramnamed); #endif #else now_ccLen = 0; #endif switch (now_ccLen) { #if SHARKSSL_TLS_1_3 case SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3): if ((o->minor == 0) || (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3))) { o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3); break; } else if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); _sharkssl_hs_alert_protocol_version: return savedconfig(o, SHARKSSL_ALERT_PROTOCOL_VERSION); } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; break; case SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2): #if SHARKSSL_TLS_1_2 if ((o->minor == 0) || (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2))) { static const U8 codecreset[8] = { 0x44, 0x4F, 0x57, 0x4E, 0x47, 0x52, 0x44, 0x01 }; o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); if (!sharkssl_kmemcmp(sharkSslHSParam->prot.tls12.serverRandom + SHARKSSL_RANDOM_LEN - SHARKSSL_DIM_ARR(codecreset), codecreset, SHARKSSL_DIM_ARR(codecreset))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } break; } else if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_protocol_version; } SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; #else goto _sharkssl_hs_alert_protocol_version; #endif break; #endif case 0: if (o->minor == 0) { #if SHARKSSL_TLS_1_2 o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); break; #endif } #if SHARKSSL_TLS_1_2 else if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) { break; } #endif default: SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; break; } switch (o->minor) { #if SHARKSSL_TLS_1_3 case SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3): #if SHARKSSL_SSL_SERVER_CODE now_ccLen = (U32)writepmresr(o, (void*)0, registeredevent, paramnamed); #else now_ccLen = (U32)writepmresr(o, registeredevent, paramnamed); #endif break; #endif #if SHARKSSL_TLS_1_2 case SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2): #if SHARKSSL_SSL_SERVER_CODE now_ccLen = (U32)writepmresr(o, (void*)0, registeredevent, paramnamed); #else now_ccLen = (U32)writepmresr(o, registeredevent, paramnamed); #endif break; #endif default: SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (now_ccLen) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } registeredevent += paramnamed; } else { #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } else #endif { o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); } #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; #endif } #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) if (((o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) && !(sharkSslHSParam->cipherSuite->flags & overcommitmemory)) || ((o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) && !(sharkSslHSParam->cipherSuite->flags & SHARKSSL_CS_TLS13))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); } #endif #if SHARKSSL_ENABLE_SESSION_CACHE #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if (setupinterface) { o->flags |= gpiolibmbank; if (o->session) { SharkSslSession *s = latchgpiochip(&o->sharkSsl->sessionCache, o, sp, setupinterface); if (s) { if (s->cipherSuite->id != sharkSslHSParam->cipherSuite->id) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } else { o->session = s; o->flags |= startqueue; } } else { goto _sharkssl_hs_session_new; } } else { _sharkssl_hs_session_new: o->session = sa1111device(&o->sharkSsl->sessionCache, o, sp, setupinterface); } } else if (o->session) { o->session = 0; } } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 if (o->session) { if ((!(o->flags & startqueue)) || (o->session->cipherSuite->hashID != sharkSslHSParam->cipherSuite->hashID)) { o->session = 0; } else { SharkSslSession* s; if (!sharkSslHSParam->ecdhParam.curveType) { return savedconfig(o, SHARKSSL_ALERT_INSUFFICIENT_SECURITY); } s = latchgpiochip(&o->sharkSsl->sessionCache, o, o->session->prot.tls13.ticket, o->session->prot.tls13.ticketLen); if (s) { if (s == o->session) { o->flags |= gpiolibmbank; } else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } } else { o->session = 0; } } } #endif #endif ioremapresource(sharkSslHSParam, tp, hsLen); #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { #if SHARKSSL_ENABLE_SESSION_CACHE if (o->flags & startqueue) { memcpy(sharkSslHSParam->prot.tls12.masterSecret, o->session->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN); paramnamed = disableclean(sharkSslHSParam->cipherSuite); if (allocalloc(o, sharkSslHSParam->prot.tls12.sharedSecret, paramnamed, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, sharkSslHSParam->prot.tls12.serverRandom, sharkSslHSParam->prot.tls12.clientRandom) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } o->state = switcherdevice; } else #endif { o->state = parsebootinfo; } } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) { #else { if ((o->major != SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_3)) || (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #endif o->state = SHARKSSL_HANDSHAKETYPE_ENCRYPTED_EXTENSIONS; } #if SHARKSSL_TLS_1_2 else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #endif #endif if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #if SHARKSSL_TLS_1_2 #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) case startflags: baAssert(sharkSslHSParam->cipherSuite->flags & cleandcache); sp = NULL; #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { if (hsDataLen < 5) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (*registeredevent++ != mcbsp5hwmod) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } hsDataLen--; paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); hsDataLen -= 2; sharkSslHSParam->ecdhParam.curveType = paramnamed; i = controllerregister(paramnamed); paramnamed = (*registeredevent++); hsDataLen--; if (0 == i) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } #if SHARKSSL_ECC_USE_EDWARDS if ((sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE25519) || (sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE448)) { if ((hsDataLen < paramnamed) || (paramnamed != i)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } } else #endif { if (*registeredevent++ != SHARKSSL_EC_POINT_UNCOMPRESSED) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } hsDataLen--; paramnamed--; if ((hsDataLen < paramnamed) || (paramnamed != (U16)(i << 1))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } } sharkSslHSParam->ecdhParam.xLen = i; memcpy(afterhandler, registeredevent, paramnamed); sharkSslHSParam->ecdhParam.XY = afterhandler; hsDataLen -= paramnamed; afterhandler += paramnamed; registeredevent += paramnamed; sp = registeredevent; } else #endif { #if SHARKSSL_ENABLE_DHE_RSA if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); hsDataLen -= 2; baAssert(sharkSslHSParam->cipherSuite->flags & cleandcache); if ((hsDataLen < paramnamed) || (paramnamed & 0x03) || (paramnamed == 0)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sharkSslHSParam->prot.tls12.dhParam.pLen = paramnamed; baAssert(((unsigned int)(UPTR)afterhandler & 0x03) == 0); memcpy(afterhandler, registeredevent, paramnamed); sharkSslHSParam->prot.tls12.dhParam.p = afterhandler; registeredevent += paramnamed; afterhandler += paramnamed; hsDataLen -= paramnamed; if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); hsDataLen -= 2; if ((hsDataLen < paramnamed) || (paramnamed == 0)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sharkSslHSParam->prot.tls12.dhParam.g = afterhandler; i = paramnamed; while (paramnamed & 0x03) { *afterhandler++ = 0; paramnamed++; } sharkSslHSParam->prot.tls12.dhParam.gLen = paramnamed; memcpy(afterhandler, registeredevent, i); registeredevent += i; afterhandler += i; hsDataLen -= i; if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); hsDataLen -= 2; if (hsDataLen < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sharkSslHSParam->prot.tls12.dhParam.Y = afterhandler; if (paramnamed != sharkSslHSParam->prot.tls12.dhParam.pLen) { if ((paramnamed == 0) || (paramnamed > sharkSslHSParam->prot.tls12.dhParam.pLen)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } i = sharkSslHSParam->prot.tls12.dhParam.pLen - paramnamed; while (i--) { *afterhandler++ = 0; } } memcpy(afterhandler, registeredevent, paramnamed); registeredevent += paramnamed; afterhandler += paramnamed; hsDataLen -= paramnamed; sp = registeredevent; #else return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); #endif } #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) { if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); hsDataLen -= 2; if (SharkSslHSParam_setSignatureHashAlgoFromSignatureScheme(sharkSslHSParam, paramnamed)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } } if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); hsDataLen -= 2; if (hsDataLen != paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #endif ioremapresource(sharkSslHSParam, tp, hsLen); #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) paramnamed = (U16)(sp - tp) - traceentry; memcpy(afterhandler, sharkSslHSParam->prot.tls12.clientRandom, SHARKSSL_RANDOM_LEN); memcpy(afterhandler + SHARKSSL_RANDOM_LEN, sharkSslHSParam->prot.tls12.serverRandom, SHARKSSL_RANDOM_LEN); memcpy(afterhandler + (2 * SHARKSSL_RANDOM_LEN), tp + traceentry, paramnamed); paramnamed += (2 * SHARKSSL_RANDOM_LEN); #if SHARKSSL_ENABLE_RSA if (machinekexec(sharkSslHSParam->certParam.certKey.expLen)) { if ((sharkSslHSParam->signParam.signature.signatureAlgo != entryearly) #if SHARKSSL_ENABLE_RSASSA_PSS && (sharkSslHSParam->signParam.signature.signatureAlgo != SHARKSSL_SIGNATUREALGORITHM_RSA_PSS) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } } #endif #if (SHARKSSL_ENABLE_ECDSA) if (machinereboot(sharkSslHSParam->certParam.certKey.expLen)) { if (sharkSslHSParam->signParam.signature.signatureAlgo != accessactive) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } } #endif if (sharkssl_hash(sharkSslHSParam->signParam.signature.hash, afterhandler, paramnamed, sharkSslHSParam->signParam.signature.hashAlgo)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } sharkSslHSParam->signParam.signature.signature = registeredevent; sharkSslHSParam->signParam.signature.signLen = hsDataLen; sharkSslHSParam->signParam.pCertKey = &(sharkSslHSParam->certParam.certKey); if (systemcapabilities(&(sharkSslHSParam->signParam)) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } registeredevent += hsDataLen; #else registeredevent += paramnamed; #endif o->state = configcwfon; if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif case configcwfon: if (hsDataLen != 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_DECODE_ERROR); } ioremapresource(sharkSslHSParam, tp, hsLen); o->state = switcherdevice; registerfixed(&o->inBuf); tp = o->inBuf.data; #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & (cleandcache | irqhandlerfixup)) { #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { #if SHARKSSL_ECC_USE_EDWARDS if ((sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE25519) || (sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE448)) { paramnamed = sharkSslHSParam->ecdhParam.xLen + 1 + 4; } else #endif { paramnamed = (U16)(sharkSslHSParam->ecdhParam.xLen << 1) + 2 + 4; } } else #endif { #if SHARKSSL_ENABLE_DHE_RSA paramnamed = sharkSslHSParam->prot.tls12.dhParam.pLen + 6; #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); #endif } } else #endif { paramnamed = 6; #if SHARKSSL_ENABLE_RSA { baAssert(sharkSslHSParam->cipherSuite->flags & percpudevid); paramnamed += supportedvector(sharkSslHSParam->certParam.certKey.modLen); } #else SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_handshake_failure; #endif } #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) if (o->flags & unregistershash) { #if SHARKSSL_ENABLE_CLIENT_AUTH if (sharkSslHSParam->certParsed) { i = sharkSslHSParam->certParsed->msgLen; baAssert(i > 0); i += traceentry; baAssert(i < 16384); if (0 == interrupthandler(&(sharkSslHSParam->certKey), sharkSslHSParam->certParsed->cert)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_CertificateError; } } else #endif { o->flags &= ~unregistershash; i = traceentry + SHARKSSL_CERT_LENGTH_LEN; } tp = sp = templateentry(o, controllegacy, tp, paramnamed + i); i -= traceentry; *tp++ = parsebootinfo; *tp++ = 0x00; *tp++ = (i >> 8); *tp++ = (i & 0xFF); #if SHARKSSL_ENABLE_CLIENT_AUTH if (sharkSslHSParam->certParsed) { if (fixupresources(sharkSslHSParam->certParsed->cert, i, tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } } else #endif { if (fixupresources((SharkSslCert)NULL, i, tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } } tp += i; } else #endif { tp = sp = templateentry(o, controllegacy, tp, paramnamed); } paramnamed -= traceentry; *tp++ = subtableheaders; *tp++ = 0x00; *tp++ = paramnamed >> 8; *tp++ = paramnamed & 0xFF; #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { baAssert(paramnamed < 0x0100); paramnamed--; *tp++ = paramnamed & 0xFF; #if SHARKSSL_ECC_USE_EDWARDS if ((sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE25519) || (sharkSslHSParam->ecdhParam.curveType == SHARKSSL_EC_CURVE_ID_CURVE448)) { baAssert(paramnamed == sharkSslHSParam->ecdhParam.xLen); } else #endif { *tp++ = SHARKSSL_EC_POINT_UNCOMPRESSED; paramnamed--; baAssert(paramnamed == (U16)(sharkSslHSParam->ecdhParam.xLen << 1)); } } else #endif { paramnamed -= 2; *tp++ = paramnamed >> 8; *tp++ = paramnamed & 0xFF; } #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & (cleandcache | irqhandlerfixup)) { #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & irqhandlerfixup) { if ((int)SharkSslCon_AllocationError == SharkSslECDHParam_ECDH(&(sharkSslHSParam->ecdhParam), (signalpreserve + switcheractive), tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } tp += paramnamed; tb = tp; baAssert((paramnamed & 1) == 0); #if SHARKSSL_ECC_USE_EDWARDS if ((sharkSslHSParam->ecdhParam.curveType != SHARKSSL_EC_CURVE_ID_CURVE25519) && (sharkSslHSParam->ecdhParam.curveType != SHARKSSL_EC_CURVE_ID_CURVE448)) #endif { paramnamed >>= 1; } } else #endif { #if SHARKSSL_ENABLE_DHE_RSA baAssert(pcmciaplatform(afterhandler)); sharkSslHSParam->prot.tls12.dhParam.r = afterhandler; if ((int)SharkSslCon_AllocationError == SharkSslDHParam_DH(&(sharkSslHSParam->prot.tls12.dhParam), (cpucfgexits + switcheractive), tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } tp += paramnamed; tb = tp; while ((0 == *tb) && (paramnamed > 0)) { tb++; paramnamed--; } #endif } if (allocalloc(o, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, tb, paramnamed, sharkSslHSParam->prot.tls12.clientRandom, sharkSslHSParam->prot.tls12.serverRandom) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } } else #endif { #if SHARKSSL_ENABLE_RSA paramnamed = SHARKSSL_MASTER_SECRET_LEN; if (sharkssl_rng(tp, paramnamed) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } tp[0] = o->reqMajor; tp[1] = o->reqMinor; if (allocalloc(o, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, tp, paramnamed, sharkSslHSParam->prot.tls12.clientRandom, sharkSslHSParam->prot.tls12.serverRandom) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } #else goto _sharkssl_hs_alert_handshake_failure; #endif #if SHARKSSL_ENABLE_RSA { int ret = (int)omap3430common(&(sharkSslHSParam->certParam.certKey), paramnamed, tp, tp, SHARKSSL_RSA_PKCS1_PADDING); if (ret < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } paramnamed = (U16)ret; tp += paramnamed; } #endif } paramnamed = disableclean(sharkSslHSParam->cipherSuite); if (allocalloc(o, sharkSslHSParam->prot.tls12.sharedSecret, paramnamed, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, sharkSslHSParam->prot.tls12.serverRandom, sharkSslHSParam->prot.tls12.clientRandom) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } ioremapresource(sharkSslHSParam, sp, (U16)(tp - sp)); #if ((SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) && SHARKSSL_ENABLE_CLIENT_AUTH) if (o->flags & unregistershash) { o->flags &= ~unregistershash; paramnamed = traceentry + 2; paramnamed += 2; sharkSslHSParam->signParam.signature.signature = (tp + clkctrlmanaged + paramnamed); if (wakeupvector(sharkSslHSParam, sharkSslHSParam->signParam.signature.hash, sharkSslHSParam->signParam.signature.hashAlgo) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } sharkSslHSParam->signParam.pCertKey = &(sharkSslHSParam->certKey); if (checkactions(&(sharkSslHSParam->signParam)) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } i = sharkSslHSParam->signParam.signature.signLen + paramnamed; sp = tp = templateentry(o, controllegacy, tp, i); i -= traceentry; *tp++ = modifygraph; *tp++ = 0; *tp++ = i >> 8; *tp++ = i & 0xFF; *tp++ = sharkSslHSParam->signParam.signature.hashAlgo; *tp++ = sharkSslHSParam->signParam.signature.signatureAlgo; i -= 2; i -= 2; *tp++ = i >> 8; *tp++ = i & 0xFF; tp += i; ioremapresource(sharkSslHSParam, sp, (U16)(tp - sp)); } #else baAssert(!(o->flags & unregistershash)); #endif #if SHARKSSL_ENABLE_SESSION_CACHE if (o->session) { filtermatch(&o->sharkSsl->sessionCache); memcpy(o->session->prot.tls12.masterSecret, sharkSslHSParam->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN); helperglobal(&o->sharkSsl->sessionCache); } #endif o->inBuf.temp = (U16)(tp - o->inBuf.data); if (sanitisependbaser(o, tvp5146routes, tp)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } if (atagsprocfs) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto suspendlocal; } return SharkSslCon_Handshake; #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) case logicmembank: #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) { goto _sharkssl_handshaketype_certificate_request_13; } #endif if (hsDataLen < 4) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } i = 0; paramnamed = *registeredevent++; hsDataLen--; if (hsDataLen < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #if SHARKSSL_ENABLE_CLIENT_AUTH baAssert(0 == (ahashchild & compatrestart & systemtable)); baAssert(0 == (ahashchild & (ahashchild - 1))); baAssert(0 == (systemtable & (systemtable - 1))); baAssert(0 == (compatrestart & (compatrestart - 1))); while (paramnamed--) { if ( 0 #if SHARKSSL_ENABLE_RSA || (ahashchild == *registeredevent) #endif #if SHARKSSL_ENABLE_ECDSA || (compatrestart == *registeredevent) #endif ) { i |= *registeredevent; } registeredevent++; hsDataLen--; } SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = (U8*)afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { *(SHARKSSL_WEIGHT*)tb = (SHARKSSL_WEIGHT)((((SharkSslCertList*)link)->certP.keyType & (U8)i) ? ((SharkSslCertList*)link)->certP.keyType : 0); } *(SHARKSSL_WEIGHT*)tb = (SHARKSSL_WEIGHT)-1; #else registeredevent += paramnamed; hsDataLen -= paramnamed; #endif sharkSslHSParam->signParam.signature.signatureAlgo = sharkSslHSParam->signParam.signature.hashAlgo = 0; { if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if ((hsDataLen < paramnamed) || (paramnamed & 1)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } hsDataLen -= paramnamed; #if SHARKSSL_ENABLE_CLIENT_AUTH i = 0; while (paramnamed) { SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = (U8*)afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { if ((*(SHARKSSL_WEIGHT*)tb) && (*(SHARKSSL_WEIGHT*)tb < smbuswrite)) { if ((((SharkSslCertList*)link)->certP.hashAlgo == registeredevent[0]) && (((SharkSslCertList*)link)->certP.signatureAlgo == registeredevent[1])) { *(SHARKSSL_WEIGHT*)tb += (smbuswrite + (((SharkSslCertList*)link)->certP.keyOID) + paramnamed); } } } if (i < 2) { if ((registeredevent[0] == presentpages) || (registeredevent[0] == domainnumber) #if SHARKSSL_USE_SHA_384 || (registeredevent[0] == probewrite) #endif #if SHARKSSL_USE_SHA_512 || (registeredevent[0] == batterythread) #endif ) { #if SHARKSSL_ENABLE_RSA if ((0 == sharkSslHSParam->signParam.signature.signatureAlgo) && (registeredevent[1] == entryearly)) { sharkSslHSParam->signParam.signature.signatureAlgo = registeredevent[0]; i++; } #endif #if SHARKSSL_ENABLE_ECDSA if ((0 == sharkSslHSParam->signParam.signature.hashAlgo) && (registeredevent[1] == accessactive)) { sharkSslHSParam->signParam.signature.hashAlgo = registeredevent[0]; i++; } #endif } } registeredevent += 2; paramnamed -= 2; } tb = (U8*)afterhandler; while (*(SHARKSSL_WEIGHT*)tb != (SHARKSSL_WEIGHT)-1) { if (*(SHARKSSL_WEIGHT*)tb < smbuswrite) { *(SHARKSSL_WEIGHT*)tb = 0; } tb += sizeof(SHARKSSL_WEIGHT); } #else registeredevent += paramnamed; #endif } if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if (hsDataLen != paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #if SHARKSSL_ENABLE_CLIENT_AUTH if (paramnamed) { while (paramnamed) { if (paramnamed < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } i = (U16)(*registeredevent++) << 8; i += *registeredevent++; paramnamed -= 2; if (i > paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = (U8*)afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { if ((*(SHARKSSL_WEIGHT*)tb) && (*(SHARKSSL_WEIGHT*)tb < lcd035q3dg01pdata)) { if (domainassociate(((SharkSslCertList*)link)->certP.cert, registeredevent, i)) { *(SHARKSSL_WEIGHT*)tb += lcd035q3dg01pdata; } } } registeredevent += i; paramnamed -= i; } tb = (U8*)afterhandler; while (*(SHARKSSL_WEIGHT*)tb != (SHARKSSL_WEIGHT)-1) { if (*(SHARKSSL_WEIGHT*)tb < lcd035q3dg01pdata) { *(SHARKSSL_WEIGHT*)tb = 0; } tb += sizeof(SHARKSSL_WEIGHT); } } #else registeredevent += paramnamed; #endif sharkSslHSParam->certParsed = NULL; #if SHARKSSL_ENABLE_CLIENT_AUTH now_ccLen = 0; SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = (U8*)afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { if (*(SHARKSSL_WEIGHT*)tb > now_ccLen) { now_ccLen = (U32)(*(SHARKSSL_WEIGHT*)tb); sharkSslHSParam->certParsed = &(((SharkSslCertList*)link)->certP); } } baAssert(*(SHARKSSL_WEIGHT*)tb == (SHARKSSL_WEIGHT)-1); if (now_ccLen) { #if SHARKSSL_ENABLE_RSA if (sharkSslHSParam->certParsed->keyType == ahashchild) { sharkSslHSParam->signParam.signature.hashAlgo = sharkSslHSParam->signParam.signature.signatureAlgo; sharkSslHSParam->signParam.signature.signatureAlgo = entryearly; } #if (SHARKSSL_ENABLE_ECDSA) else #endif #endif #if (SHARKSSL_ENABLE_ECDSA) if (sharkSslHSParam->certParsed->keyType == compatrestart) { sharkSslHSParam->signParam.signature.signatureAlgo = accessactive; } #endif if ((0 == sharkSslHSParam->signParam.signature.hashAlgo) || (0 == sharkSslHSParam->signParam.signature.signatureAlgo)) { sharkSslHSParam->certParsed = NULL; } } #endif ioremapresource(sharkSslHSParam, tp, hsLen); o->flags |= (unregistershash + nresetconsumers); o->state = configcwfon; if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 _sharkssl_handshaketype_certificate_request_13: #endif if (hsDataLen < 3) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = *registeredevent++; hsDataLen--; if ((paramnamed) ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if (hsDataLen != paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sharkSslHSParam->certParsed = NULL; #if SHARKSSL_ENABLE_CLIENT_AUTH if (!SingleList_isEmpty((SingleList*)&o->sharkSsl->certList)) { #define _CERTREQ_CERTAUTH_FLAG 0x01 #define _CERTREQ_SIGNALGO_FLAG 0x02 ics = 0; SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { *(SHARKSSL_WEIGHT*)tb = 0; } now_ccLen = paramnamed; while (now_ccLen >= 2) { i = (U16)(*registeredevent++) << 8; i += *registeredevent++; now_ccLen -= 2; if (now_ccLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; now_ccLen -= 2; if (((U16)now_ccLen < paramnamed) || (paramnamed < 2)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; now_ccLen -= 2; if (((U16)now_ccLen < paramnamed) || (paramnamed < 2)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } now_ccLen -= paramnamed; switch (i) { case shutdownnonboot: ics |= _CERTREQ_CERTAUTH_FLAG; while (paramnamed) { i = (U16)(*registeredevent++) << 8; i += *registeredevent++; paramnamed -= 2; if (i > paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { if (*(SHARKSSL_WEIGHT*)tb < lcd035q3dg01pdata) { if (domainassociate(((SharkSslCertList*)link)->certP.cert, registeredevent, i)) { *(SHARKSSL_WEIGHT*)tb += lcd035q3dg01pdata; } } } registeredevent += i; paramnamed -= i; } break; case restoremasks: if (paramnamed & 0x1) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } ics |= _CERTREQ_SIGNALGO_FLAG; while (paramnamed) { i = (U16)(*registeredevent++) << 8; i += *registeredevent++; paramnamed -= 2; #if (SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSASSA_PSS) if ((U8)(i >> 8) == SHARKSSL_SIGNATUREALGORITHM_RSA_PSS) { setupinterface = (U8)i; if (0 #if SHARKSSL_USE_SHA_512 || (setupinterface == batterythread) #endif #if SHARKSSL_USE_SHA_384 || (setupinterface == probewrite) #endif #if SHARKSSL_USE_SHA_256 || (setupinterface == domainnumber) #endif ) { SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { if (((SharkSslCertList*)link)->certP.keyType == ahashchild) { *(SHARKSSL_WEIGHT*)tb &= ~0xFFFFFF; *(SHARKSSL_WEIGHT*)tb |= (SHARKSSL_WEIGHT)ahashchild << 16; *(SHARKSSL_WEIGHT*)tb |= i; } } } } #if SHARKSSL_ENABLE_ECDSA else #endif #endif #if SHARKSSL_ENABLE_ECDSA if ((U8)i == accessactive) { setupinterface = (U8)(i >> 8); SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { if ((((SharkSslCertList*)link)->certP.keyType == compatrestart) && (0 #if (SHARKSSL_ECC_USE_SECP521R1 && SHARKSSL_USE_SHA_512) || ((setupinterface == batterythread) && (((SharkSslCertList*)link)->certP.keyOID == SHARKSSL_EC_CURVE_ID_SECP521R1)) #endif #if (SHARKSSL_ECC_USE_SECP384R1 && SHARKSSL_USE_SHA_384) || ((setupinterface == probewrite) && (((SharkSslCertList*)link)->certP.keyOID == SHARKSSL_EC_CURVE_ID_SECP384R1)) #endif #if (SHARKSSL_ECC_USE_SECP256R1 && SHARKSSL_USE_SHA_256) || ((setupinterface == domainnumber) && (((SharkSslCertList*)link)->certP.keyOID == SHARKSSL_EC_CURVE_ID_SECP256R1)) #endif )) { *(SHARKSSL_WEIGHT*)tb &= ~0xFFFFFF; *(SHARKSSL_WEIGHT*)tb |= (SHARKSSL_WEIGHT)compatrestart << 16; *(SHARKSSL_WEIGHT*)tb |= i; } } } #endif } break; default: registeredevent += paramnamed; break; } } if (!(ics & _CERTREQ_SIGNALGO_FLAG)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } baAssert(sizeof(now_ccLen) == sizeof(SHARKSSL_WEIGHT)); now_ccLen = 0; SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); for (tb = afterhandler, link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e), tb += sizeof(SHARKSSL_WEIGHT)) { if ((!(ics & _CERTREQ_CERTAUTH_FLAG)) || (*(SHARKSSL_WEIGHT*)tb > lcd035q3dg01pdata)) { if (*(SHARKSSL_WEIGHT*)tb > now_ccLen) { now_ccLen = *(SHARKSSL_WEIGHT*)tb; sharkSslHSParam->certParsed = &(((SharkSslCertList*)link)->certP); } } } if (now_ccLen != 0) { sharkSslHSParam->prot.tls13.signatureScheme = (U16)now_ccLen; } } else #endif { registeredevent += paramnamed; } ioremapresource(sharkSslHSParam, tp, hsLen); o->flags |= (unregistershash + nresetconsumers); o->state = parsebootinfo; if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif #endif #endif #if ((SHARKSSL_SSL_CLIENT_CODE && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || \ (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_CLIENT_AUTH)) case parsebootinfo: #if (SHARKSSL_CERT_LENGTH_LEN != 3) #error internal error SHARKSSL_CERT_LENGTH_LEN must be 3 #endif #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { if (hsDataLen < 1) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = *registeredevent++; hsDataLen--; if (paramnamed) { if (hsDataLen < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } registeredevent += paramnamed; hsDataLen -= paramnamed; } } #endif if (hsDataLen < SHARKSSL_CERT_LENGTH_LEN) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } crLen = (U32)(*registeredevent++) << 16; crLen += (U16)(*registeredevent++) << 8; crLen += *registeredevent++; hsDataLen -= SHARKSSL_CERT_LENGTH_LEN; if (crLen == 0) { #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isServer(o->sharkSsl)) { o->flags &= ~unregistershash; o->flags |= serialreset; } else #endif { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_BAD_CERTIFICATE); } } else if (hsDataLen < SHARKSSL_CERT_LENGTH_LEN) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } ioremapresource(sharkSslHSParam, tp, hsLen); ics = 0; certParam = &(sharkSslHSParam->certParam); while (crLen > 0) { now_ccLen = (U32)(*registeredevent++) << 16; now_ccLen += (U16)(*registeredevent++) << 8; now_ccLen += *registeredevent++; hsDataLen -= SHARKSSL_CERT_LENGTH_LEN; if (hsDataLen < now_ccLen) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (spromregister(certParam, registeredevent, now_ccLen, 0) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_UNSUPPORTED_CERTIFICATE); } if (0 == ics) { ics++; #if SHARKSSL_USE_ECC if (machinereboot(certParam->certKey.expLen)) { baAssert(0 == mousethresh(certParam->certKey.expLen)); baAssert(sharkSslHSParam->cipherSuite); i = (U16)(attachdevice(certParam->certKey.modLen)) * 2; memcpy(afterhandler, certParam->certKey.mod, i); certParam->certKey.mod = afterhandler; afterhandler += i; } #if SHARKSSL_ENABLE_RSA else #endif #endif #if SHARKSSL_ENABLE_RSA { baAssert(machinekexec(certParam->certKey.expLen)); memcpy(afterhandler, certParam->certKey.mod, supportedvector(certParam->certKey.modLen)); certParam->certKey.mod = afterhandler; afterhandler += supportedvector(certParam->certKey.modLen); memcpy(afterhandler, certParam->certKey.exp, mousethresh(certParam->certKey.expLen)); certParam->certKey.exp = afterhandler; afterhandler += claimresource(mousethresh(certParam->certKey.expLen)); } #endif } hsDataLen -= (U16)now_ccLen; registeredevent += (U16)now_ccLen; crLen -= (now_ccLen + SHARKSSL_CERT_LENGTH_LEN); #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { if (crLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; crLen -= 2; hsDataLen -= 2; if (paramnamed) { baAssert(hsDataLen >= crLen); if (crLen < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } crLen -= paramnamed; registeredevent += paramnamed; hsDataLen -= paramnamed; } } #endif if (crLen) { certParam->certInfo.parent = (SharkSslCertInfo*)afterhandler; certParam = (SharkSslCertParam*)afterhandler; memset(certParam, 0, sizeof(SharkSslCertParam)); afterhandler += claimresource(sizeof(SharkSslCertParam)); } } #if SHARKSSL_SSL_SERVER_CODE if (!(o->flags & serialreset)) #endif { #if (SHARKSSL_ENABLE_CA_EXTENSION && SHARKSSL_ENABLE_CA_LIST) SharkSslCAList displaysetup; if ((o->flags & SHARKSSL_FLAG_CA_EXTENSION_REQUEST) && (SharkSsl_isClient(o->sharkSsl)) && (o->caListCertReq)) { displaysetup = o->caListCertReq; } else { displaysetup = o->sharkSsl->caList; } #endif if (SharkSslCertParam_validateCertChain(&(sharkSslHSParam->certParam), &(sharkSslHSParam->signParam) #if SHARKSSL_ENABLE_CA_LIST , &o->flags #if SHARKSSL_ENABLE_CA_EXTENSION , displaysetup #else , o->sharkSsl->caList #endif , afterhandler #endif )) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_BAD_CERTIFICATE); } } baAssert((SharkSslClonedCertInfo*)0 == o->clonedCertInfo); if (realnummemory(o, &o->clonedCertInfo)) { SHARKDBG_PRINTF(("\157\050\045\060\070\130\051\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\050\045\060\070\130\051\055\076\162\145\146\143\156\164\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)o, (U32)o->clonedCertInfo, o->clonedCertInfo->refcnt, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\103\157\156\137\160\162\157\143\145\163\163\110\141\156\144\163\150\141\153\145")); #if SHARKSSL_ENABLE_SESSION_CACHE if (o->session) { filtermatch(&o->sharkSsl->sessionCache); SharkSslSession_copyClonedCertInfo(o->session, o); helperglobal(&o->sharkSsl->sessionCache); } #endif } #if SHARKSSL_SSL_CLIENT_CODE if (SharkSsl_isClient(o->sharkSsl)) { #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { o->state = modifygraph; } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) if (sharkSslHSParam->cipherSuite->flags & cleandcache) { o->state = startflags; } else #endif { o->state = configcwfon; } } #endif } #if SHARKSSL_SSL_SERVER_CODE else #endif #endif #if SHARKSSL_SSL_SERVER_CODE { o->state = subtableheaders; } #endif if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif case switcherdevice: i = 0; #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if (!(o->flags & cachematch)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_UNEXPECTED_MESSAGE); } o->flags &= ~cachematch; paramnamed = SHARKSSL_FINISHED_MSG_LEN_TLS_1_2; } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 { paramnamed = i = sharkssl_getHashLen(o->rCipherSuite->hashID); baAssert(o->wCipherSuite == o->rCipherSuite); } #endif if ((atagsprocfs) || (hsDataLen != paramnamed)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } registerfixed(&o->outBuf); if (printsilicon(o, SharkSsl_isClient(o->sharkSsl) ? rodatastart : tvp5146routes, afterhandler) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } if (sharkssl_kmemcmp(registeredevent, afterhandler, paramnamed)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } o->state = loongson3notifier; o->inBuf.temp = 0; #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION memcpy(SharkSsl_isServer(o->sharkSsl) ? o->clientVerifyData : o->serverVerifyData, registeredevent, paramnamed); #if (SHARKSSL_ENABLE_ALPN_EXTENSION) && (SHARKSSL_SSL_CLIENT_CODE) #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isClient(o->sharkSsl)) #endif { o->pALPN = NULL; } #endif #endif #if SHARKSSL_ENABLE_AES_GCM o->flags |= devicedriver; #endif o->flags &= ~unregistershash; if (((SharkSsl_isServer(o->sharkSsl)) && (!(o->flags & startqueue))) || ((SharkSsl_isClient(o->sharkSsl)) && ((o->flags & startqueue)))) { ioremapresource(sharkSslHSParam, registeredevent - traceentry, hsDataLen + traceentry); if (sanitisependbaser(o, SharkSsl_isServer(o->sharkSsl) ? rodatastart : tvp5146routes, (U8*)0)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } } #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION o->flags &= ~platformdevice; #endif } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 { ioremapresource(sharkSslHSParam, registeredevent - traceentry, hsDataLen + traceentry); wakeupvector(sharkSslHSParam, afterhandler, o->rCipherSuite->hashID); registerfixed(&o->inBuf); tb = o->inBuf.data; if (o->flags & cachematch) { tb = templateentry(o, rangealigned, tb, 1); *tb++ = 1; o->inBuf.data = tb; } if (o->flags & unregistershash) { sp = tb + clkctrlmanaged; tp = sp + traceentry; *tp++ = 0; paramnamed = 1; #if SHARKSSL_ENABLE_CLIENT_AUTH if (sharkSslHSParam->certParsed) { SharkSslCert kernelvaddr; SharkSslCertEnum cEnum; U8* sdhciplatdata; registerautodeps(&cEnum, sharkSslHSParam->certParsed->cert); kernelvaddr = updatesctlr(&cEnum); if (!interrupthandler(&(sharkSslHSParam->certKey), kernelvaddr)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_CertificateError; } tp += SHARKSSL_CERT_LENGTH_LEN; sdhciplatdata = tp; while (kernelvaddr != NULL) { crLen = SharkSslCertEnum_getCertLength(&cEnum); *tp++ = 0x00; *tp++ = (U8)(crLen >> 8); *tp++ = (U8)(crLen & 0xFF); memcpy(tp, kernelvaddr, crLen); tp += crLen; *tp++ = 0x00; *tp++ = 0x00; kernelvaddr = removerecursive(&cEnum); } crLen = (U16)(tp - sdhciplatdata); *--sdhciplatdata = (U8)(crLen & 0xFF); *--sdhciplatdata = (U8)(crLen >> 8); *--sdhciplatdata = 0x00; paramnamed += (U16)crLen + SHARKSSL_CERT_LENGTH_LEN; } else #endif { o->flags &= ~unregistershash; *tp++ = 0x00; *tp++ = 0x00; *tp++ = 0x00; paramnamed += 3; } *sp++ = parsebootinfo; *sp++ = 0; *sp++ = (U8)(paramnamed >> 8); *sp++ = (U8)(paramnamed & 0xFF); ioremapresource(sharkSslHSParam, sp - traceentry, paramnamed + traceentry); #if SHARKSSL_ENABLE_CLIENT_AUTH if (o->flags & unregistershash) { o->flags &= ~unregistershash; afterhandler += i; if (wakeupvector(sharkSslHSParam, afterhandler + SHARKSSL_DIM_ARR(cvServerCtxZero) + 64, o->wCipherSuite->hashID) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); _sharkssl_hs_alert_internal_error: return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } memset(afterhandler, 0x20, 64); memcpy(afterhandler + 64, cvServerCtxZero, SHARKSSL_DIM_ARR(cvServerCtxZero)); memcpy(afterhandler + 64 + 9, "\143\154\151\145\156\164", 6); if (SharkSslHSParam_setSignatureHashAlgoFromSignatureScheme(sharkSslHSParam, sharkSslHSParam->prot.tls13.signatureScheme)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_hs_alert_internal_error; } sharkssl_hash(sharkSslHSParam->signParam.signature.hash, afterhandler, SHARKSSL_DIM_ARR(cvServerCtxZero) + 64 + i, sharkSslHSParam->signParam.signature.hashAlgo); sharkSslHSParam->signParam.pCertKey = &(sharkSslHSParam->certKey); sharkSslHSParam->signParam.signature.signature = tp + traceentry + 4; if (checkactions(&(sharkSslHSParam->signParam)) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } crLen = sharkSslHSParam->signParam.signature.signLen + 4; *tp++ = modifygraph; *tp++ = 0x00; *tp++ = (U8)(crLen >> 8); *tp++ = (U8)(crLen & 0xFF); crLen -= 4; *tp++ = (U8)(sharkSslHSParam->prot.tls13.signatureScheme >> 8); *tp++ = (U8)(sharkSslHSParam->prot.tls13.signatureScheme & 0xFF); *tp++ = (U8)(crLen >> 8); *tp++ = (U8)(crLen & 0xFF); tp += crLen; crLen += 8; ioremapresource(sharkSslHSParam, tp - crLen, (U16)crLen); afterhandler -= i; } #endif } else { tp = tb + clkctrlmanaged; } paramnamed = i; #if SHARKSSL_ENABLE_SESSION_CACHE crLen = paramnamed; sp = tp; #endif * tp++ = switcherdevice; *tp++ = 0x00; *tp++ = 0x00; *tp++ = (U8)paramnamed; if (printsilicon(o, tvp5146routes, tp) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } paramnamed += (U16)(tp - tb); o->inBuf.temp += paramnamed; paramnamed -= clkctrlmanaged; templateentry(o, controllegacy, tb, paramnamed); #if SHARKSSL_ENABLE_SESSION_CACHE crLen += (U16)(tp - sp); memcpy(afterhandler + i, sp, crLen); #endif if (SharkSslCon_calcMACAndEncryptHS(o) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } if (o->flags & cachematch) { registerfixed(&o->inBuf); o->inBuf.temp += clkctrlmanaged + 1; } SharkSslCon_calcAppTrafficSecret(o, afterhandler); #if SHARKSSL_ENABLE_SESSION_CACHE ioremapresource(sharkSslHSParam, afterhandler + i, (U16)crLen); wakeupvector(sharkSslHSParam, afterhandler, o->rCipherSuite->hashID); SharkSslCon_calcResumptionSecret(o, afterhandler); #endif } #endif alignmentldmstm(sharkSslHSParam); return SharkSslCon_Handshake; case modifygraph: #if (SHARKSSL_TLS_1_3 && SHARKSSL_SSL_CLIENT_CODE) #if (SHARKSSL_TLS_1_2 && SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_CLIENT_AUTH) if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) { goto _sharkssl_handshaketype_certificate_verify_12; } #endif if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if (SharkSslHSParam_setSignatureHashAlgoFromSignatureScheme(sharkSslHSParam, paramnamed)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (*registeredevent++ << 8); paramnamed += *registeredevent++; hsDataLen -= 2; if (paramnamed != hsDataLen) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } #if SHARKSSL_ENABLE_RSA #if (!SHARKSSL_ENABLE_ECDSA) baAssert(machinekexec(sharkSslHSParam->certParam.certKey.expLen)); #else if (machinekexec(sharkSslHSParam->certParam.certKey.expLen)) #endif { afterhandler += supportedvector(sharkSslHSParam->certParam.certKey.modLen); afterhandler += claimresource(mousethresh(sharkSslHSParam->certParam.certKey.expLen)); } #if SHARKSSL_ENABLE_ECDSA else #endif #endif #if SHARKSSL_ENABLE_ECDSA { if (machinereboot(sharkSslHSParam->certParam.certKey.expLen)) { afterhandler += (U16)(attachdevice(sharkSslHSParam->certParam.certKey.modLen)) * 2; } } #endif if (wakeupvector(sharkSslHSParam, afterhandler + SHARKSSL_DIM_ARR(cvServerCtxZero) + 64, o->rCipherSuite->hashID) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } ioremapresource(sharkSslHSParam, tp, hsLen); memset(afterhandler, 0x20, 64); memcpy(afterhandler + 64, cvServerCtxZero, SHARKSSL_DIM_ARR(cvServerCtxZero)); sharkssl_hash(sharkSslHSParam->signParam.signature.hash, afterhandler, SHARKSSL_DIM_ARR(cvServerCtxZero) + 64 + sharkssl_getHashLen(o->rCipherSuite->hashID), sharkSslHSParam->signParam.signature.hashAlgo); sharkSslHSParam->signParam.signature.signature = registeredevent; sharkSslHSParam->signParam.signature.signLen = hsDataLen; sharkSslHSParam->signParam.pCertKey = &(sharkSslHSParam->certParam.certKey); if (systemcapabilities(&(sharkSslHSParam->signParam)) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_DECRYPT_ERROR); } registeredevent += hsDataLen; o->state = switcherdevice; if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif #if (SHARKSSL_TLS_1_2 && SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_CLIENT_AUTH) #if (SHARKSSL_TLS_1_3 && SHARKSSL_SSL_CLIENT_CODE) _sharkssl_handshaketype_certificate_verify_12: #endif tp = registeredevent - traceentry; if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } { if ( (hsDataLen < 2) || ((*registeredevent != presentpages) && (*registeredevent != domainnumber) #if SHARKSSL_USE_SHA_384 && (*registeredevent != probewrite) #endif #if SHARKSSL_USE_SHA_512 && (*registeredevent != batterythread) #endif ) ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sharkSslHSParam->signParam.signature.hashAlgo = *registeredevent++; if (1 #if SHARKSSL_ENABLE_RSA && (*registeredevent != entryearly) #endif #if SHARKSSL_ENABLE_ECDSA && (*registeredevent != accessactive) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sharkSslHSParam->signParam.signature.signatureAlgo = *registeredevent++; hsDataLen -= 2; } paramnamed = (*registeredevent++ << 8); paramnamed += *registeredevent++; hsDataLen -= 2; if (paramnamed != hsDataLen) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (wakeupvector(sharkSslHSParam, sharkSslHSParam->signParam.signature.hash, sharkSslHSParam->signParam.signature.hashAlgo) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } ioremapresource(sharkSslHSParam, tp, hsLen); sharkSslHSParam->signParam.signature.signature = registeredevent; sharkSslHSParam->signParam.signature.signLen = hsDataLen; sharkSslHSParam->signParam.pCertKey = &(sharkSslHSParam->certParam.certKey); if (systemcapabilities(&(sharkSslHSParam->signParam)) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } registeredevent += hsDataLen; o->state = switcherdevice; if (atagsprocfs) { goto suspendlocal; } o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif #if SHARKSSL_TLS_1_3 #if SHARKSSL_SSL_CLIENT_CODE case SHARKSSL_HANDSHAKETYPE_ENCRYPTED_EXTENSIONS: if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += *registeredevent++; hsDataLen -= 2; if (hsDataLen != paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto updatereserved; } #if SHARKSSL_SSL_SERVER_CODE if ((paramnamed) && (writepmresr(o, (void*)0, registeredevent, paramnamed))) #else if ((paramnamed) && (writepmresr(o, registeredevent, paramnamed))) #endif { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } registeredevent += paramnamed; ioremapresource(sharkSslHSParam, tp, hsLen); #if SHARKSSL_ENABLE_SESSION_CACHE if (o->flags & startqueue) { o->state = switcherdevice; } else #endif { o->state = logicmembank; } if (atagsprocfs) { goto suspendlocal; } return SharkSslCon_Handshake; case SHARKSSL_HANDSHAKETYPE_NEW_SESSION_TICKET: o->flags |= devicedriver; #if SHARKSSL_ENABLE_SESSION_CACHE if (hsDataLen < 9) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } read64uint32(now_ccLen, registeredevent, 0); read64uint32(crLen, registeredevent, 4); registeredevent += 8; setupinterface = *registeredevent++; hsDataLen -= 9; if ((hsDataLen < setupinterface) || (now_ccLen > 0x00093A80L )) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } tp = registeredevent; registeredevent += setupinterface; hsDataLen -= setupinterface; if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } paramnamed = (U16)(*registeredevent++) << 8; paramnamed += (*registeredevent++); hsDataLen -= 2; if (hsDataLen < paramnamed) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } sp = registeredevent; registeredevent += paramnamed; hsDataLen -= paramnamed; if (hsDataLen < 2) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } i = (U16)(*registeredevent++) << 8; i += (*registeredevent++); hsDataLen -= 2; if (hsDataLen != i) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto regionfixed; } if (!(o->session)) { o->flags |= gpiolibmbank; o->session = sa1111device(&o->sharkSsl->sessionCache, o, sp, paramnamed); if (o->session) { filtermatch(&o->sharkSsl->sessionCache); o->session->prot.tls13.expiration += now_ccLen; o->session->prot.tls13.ticketAgeAdd = crLen; SharkSslCon_calcTicketPSK(o, (U8*)&o->session->prot.tls13.PSK, tp, setupinterface); SharkSslSession_copyClonedCertInfo(o->session, o); helperglobal(&o->sharkSsl->sessionCache); } } #endif o->state = loongson3notifier; o->inBuf.temp = 0; return SharkSslCon_Handshake; #endif #endif default: SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_UNEXPECTED_MESSAGE); } } #ifndef BA_LIB #define BA_LIB 1 #endif #include "BaMimeTypes.h" #include "BaServerLib.h" typedef struct { const char* ext; const char* val; } HttpMimeType; static const char htmlMmimeT[]={"\164\145\170\164\057\150\164\155\154\073\040\143\150\141\162\163\145\164\075\165\164\146\055\070"}; static const HttpMimeType mimeTypes[] = { {"\063\144\155", "\170\055\167\157\162\154\144\057\170\055\063\144\155\146"}, {"\063\144\155\146", "\170\055\167\157\162\154\144\057\170\055\063\144\155\146"}, {"\141\141\142", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\141\165\164\150\157\162\167\141\162\145\055\142\151\156"}, {"\141\141\155", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\141\165\164\150\157\162\167\141\162\145\055\155\141\160"}, {"\141\141\163", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\141\165\164\150\157\162\167\141\162\145\055\163\145\147"}, {"\141\142\143", "\164\145\170\164\057\166\156\144\056\141\142\143"}, {"\141\146\154", "\166\151\144\145\157\057\141\156\151\155\141\146\154\145\170"}, {"\141\151", "\141\160\160\154\151\143\141\164\151\157\156\057\160\157\163\164\163\143\162\151\160\164"}, {"\141\151\146", "\141\165\144\151\157\057\170\055\141\151\146\146"}, {"\141\151\146\143", "\141\165\144\151\157\057\170\055\141\151\146\146"}, {"\141\151\146\146", "\141\165\144\151\157\057\170\055\141\151\146\146"}, {"\141\151\155", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\141\151\155"}, {"\141\151\160", "\164\145\170\164\057\170\055\141\165\144\151\157\163\157\146\164\055\151\156\164\162\141"}, {"\141\156\151", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\156\141\166\151\055\141\156\151\155\141\164\151\157\156"}, {"\141\157\163", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\156\157\153\151\141\055\071\060\060\060\055\143\157\155\155\165\156\151\143\141\164\157\162\055\141\144\144\055\157\156\055\163\157\146\164\167\141\162\145"}, {"\141\160\160\154\151\143\141\164\151\157\156","\141\160\160\154\151\143\141\164\151\157\156\057\170\055\155\163\055\141\160\160\154\151\143\141\164\151\157\156"}, {"\141\160\163", "\141\160\160\154\151\143\141\164\151\157\156\057\155\151\155\145"}, {"\141\162\164", "\151\155\141\147\145\057\170\055\152\147"}, {"\141\163\146", "\166\151\144\145\157\057\170\055\155\163\055\141\163\146"}, {"\141\163\155", "\164\145\170\164\057\170\055\141\163\155"}, {"\141\163\160", "\164\145\170\164\057\141\163\160"}, {"\141\163\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\155\160\154\141\171\145\162\062"}, {"\141\165", "\141\165\144\151\157\057\142\141\163\151\143"}, {"\141\166\151", "\166\151\144\145\157\057\170\055\155\163\166\151\144\145\157"}, {"\142\143\160\151\157", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\142\143\160\151\157"}, {"\142\155", "\151\155\141\147\145\057\142\155\160"}, {"\142\155\160", "\151\155\141\147\145\057\142\155\160"}, {"\142\157\157", "\141\160\160\154\151\143\141\164\151\157\156\057\142\157\157\153"}, {"\142\157\157\153", "\141\160\160\154\151\143\141\164\151\157\156\057\142\157\157\153"}, {"\142\157\172", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\142\172\151\160\062"}, {"\142\163\150", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\142\163\150"}, {"\142\172", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\142\172\151\160"}, {"\142\172\062", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\142\172\151\160\062"}, {"\143", "\164\145\170\164\057\160\154\141\151\156"}, {"\143", "\164\145\170\164\057\170\055\143"}, {"\143\053\053", "\164\145\170\164\057\160\154\141\151\156"}, {"\143\141\164", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\155\163\055\160\153\151\056\163\145\143\143\141\164"}, {"\143\143", "\164\145\170\164\057\160\154\141\151\156"}, {"\143\143", "\164\145\170\164\057\170\055\143"}, {"\143\143\141\144", "\141\160\160\154\151\143\141\164\151\157\156\057\143\154\141\162\151\163\143\141\144"}, {"\143\143\157", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\157\143\157\141"}, {"\143\144\146", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\156\145\164\143\144\146"}, {"\143\145\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\170\065\060\071\055\143\141\055\143\145\162\164"}, {"\143\150\141", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\150\141\164"}, {"\143\150\141\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\150\141\164"}, {"\143\154\141\163\163", "\141\160\160\154\151\143\141\164\151\157\156\057\152\141\166\141"}, {"\143\157\156\146", "\164\145\170\164\057\160\154\141\151\156"}, {"\143\160\151\157", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\160\151\157"}, {"\143\160\160", "\164\145\170\164\057\170\055\143"}, {"\143\160\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\160\164"}, {"\143\162\154", "\141\160\160\154\151\143\141\164\151\157\156\057\160\153\151\170\055\143\162\154"}, {"\143\162\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\170\065\060\071\055\165\163\145\162\055\143\145\162\164"}, {"\143\163\150", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\163\150"}, {"\143\163\150", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\143\163\150"}, {"\143\163\163", "\164\145\170\164\057\143\163\163"}, {"\143\170\170", "\164\145\170\164\057\160\154\141\151\156"}, {"\144\143\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\144\151\162\145\143\164\157\162"}, {"\144\145\145\160\166", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\144\145\145\160\166"}, {"\144\145\146", "\164\145\170\164\057\160\154\141\151\156"}, {"\144\145\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\170\065\060\071\055\143\141\055\143\145\162\164"}, {"\144\151\146", "\166\151\144\145\157\057\170\055\144\166"}, {"\144\151\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\144\151\162\145\143\164\157\162"}, {"\144\154", "\166\151\144\145\157\057\144\154"}, {"\144\154", "\166\151\144\145\157\057\170\055\144\154"}, {"\144\157\143", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\167\157\162\144"}, {"\144\157\164", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\167\157\162\144"}, {"\144\160", "\141\160\160\154\151\143\141\164\151\157\156\057\143\157\155\155\157\156\147\162\157\165\156\144"}, {"\144\162\167", "\141\160\160\154\151\143\141\164\151\157\156\057\144\162\141\146\164\151\156\147"}, {"\144\166", "\166\151\144\145\157\057\170\055\144\166"}, {"\144\166\151", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\144\166\151"}, {"\144\167\146", "\155\157\144\145\154\057\166\156\144\056\144\167\146"}, {"\144\167\147", "\141\160\160\154\151\143\141\164\151\157\156\057\141\143\141\144"}, {"\144\167\147", "\151\155\141\147\145\057\170\055\144\167\147"}, {"\144\170\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\144\151\162\145\143\164\157\162"}, {"\145\154", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\145\154\151\163\160"}, {"\145\154\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\145\154\143"}, {"\145\156\166", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\145\156\166\157\171"}, {"\145\160\163", "\141\160\160\154\151\143\141\164\151\157\156\057\160\157\163\164\163\143\162\151\160\164"}, {"\145\163", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\145\163\162\145\150\142\145\162"}, {"\145\164\170", "\164\145\170\164\057\170\055\163\145\164\145\170\164"}, {"\145\166\171", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\145\156\166\157\171"}, {"\146", "\164\145\170\164\057\170\055\146\157\162\164\162\141\156"}, {"\146\067\067", "\164\145\170\164\057\170\055\146\157\162\164\162\141\156"}, {"\146\071\060", "\164\145\170\164\057\170\055\146\157\162\164\162\141\156"}, {"\146\144\146", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\146\144\146"}, {"\146\151\146", "\151\155\141\147\145\057\146\151\146"}, {"\146\154\151", "\166\151\144\145\157\057\170\055\146\154\151"}, {"\146\154\157", "\151\155\141\147\145\057\146\154\157\162\151\141\156"}, {"\146\154\170", "\164\145\170\164\057\166\156\144\056\146\155\151\056\146\154\145\170\163\164\157\162"}, {"\146\155\146", "\166\151\144\145\157\057\170\055\141\164\157\155\151\143\063\144\055\146\145\141\164\165\162\145"}, {"\146\157\162", "\164\145\170\164\057\170\055\146\157\162\164\162\141\156"}, {"\146\160\170", "\151\155\141\147\145\057\166\156\144\056\156\145\164\055\146\160\170"}, {"\146\162\154", "\141\160\160\154\151\143\141\164\151\157\156\057\146\162\145\145\154\157\141\144\145\162"}, {"\146\165\156\153", "\141\165\144\151\157\057\155\141\153\145"}, {"\147", "\164\145\170\164\057\160\154\141\151\156"}, {"\147\063", "\151\155\141\147\145\057\147\063\146\141\170"}, {"\147\151\146", "\151\155\141\147\145\057\147\151\146"}, {"\147\154", "\166\151\144\145\157\057\170\055\147\154"}, {"\147\163\144", "\141\165\144\151\157\057\170\055\147\163\155"}, {"\147\163\155", "\141\165\144\151\157\057\170\055\147\163\155"}, {"\147\163\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\147\163\160"}, {"\147\163\163", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\147\163\163"}, {"\147\164\141\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\147\164\141\162"}, {"\147\172", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\147\172\151\160"}, {"\147\172\151\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\147\172\151\160"}, {"\150", "\164\145\170\164\057\160\154\141\151\156"}, {"\150", "\164\145\170\164\057\170\055\150"}, {"\150\144\146", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\150\144\146"}, {"\150\145\154\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\150\145\154\160\146\151\154\145"}, {"\150\147\154", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\150\160\055\110\120\107\114"}, {"\150\150", "\164\145\170\164\057\160\154\141\151\156"}, {"\150\154\142", "\164\145\170\164\057\170\055\163\143\162\151\160\164"}, {"\150\154\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\151\156\150\145\154\160"}, {"\150\160\147", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\150\160\055\110\120\107\114"}, {"\150\160\147\154", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\150\160\055\110\120\107\114"}, {"\150\161\170", "\141\160\160\154\151\143\141\164\151\157\156\057\142\151\156\150\145\170"}, {"\150\164\141", "\141\160\160\154\151\143\141\164\151\157\156\057\150\164\141"}, {"\150\164\143", "\164\145\170\164\057\170\055\143\157\155\160\157\156\145\156\164"}, {"\150\164\155", htmlMmimeT}, {"\150\164\155\154", htmlMmimeT}, {"\150\164\155\154\163", htmlMmimeT}, {"\150\164\164", "\164\145\170\164\057\167\145\142\166\151\145\167\150\164\155\154"}, {"\151\143\145", "\170\055\143\157\156\146\145\162\145\156\143\145\057\170\055\143\157\157\154\164\141\154\153"}, {"\151\143\157", "\151\155\141\147\145\057\170\055\151\143\157\156"}, {"\151\144\143", "\164\145\170\164\057\160\154\141\151\156"}, {"\151\145\146", "\151\155\141\147\145\057\151\145\146"}, {"\151\145\146\163", "\151\155\141\147\145\057\151\145\146"}, {"\151\147\145\163", "\141\160\160\154\151\143\141\164\151\157\156\057\151\147\145\163"}, {"\151\147\163", "\141\160\160\154\151\143\141\164\151\157\156\057\151\147\145\163"}, {"\151\155\141", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\151\155\141"}, {"\151\155\141\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\150\164\164\160\144\055\151\155\141\160"}, {"\151\156\146", "\141\160\160\154\151\143\141\164\151\157\156\057\151\156\146"}, {"\151\156\163", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\151\156\164\145\162\156\145\164\164\055\163\151\147\156\165\160"}, {"\151\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\151\160\062"}, {"\151\163\165", "\166\151\144\145\157\057\170\055\151\163\166\151\144\145\157"}, {"\151\164", "\141\165\144\151\157\057\151\164"}, {"\151\166", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\151\156\166\145\156\164\157\162"}, {"\151\166\162", "\151\055\167\157\162\154\144\057\151\055\166\162\155\154"}, {"\151\166\171", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\154\151\166\145\163\143\162\145\145\156"}, {"\152\141\155", "\141\165\144\151\157\057\170\055\152\141\155"}, {"\152\141\162", "\141\160\160\154\151\143\141\164\151\157\156\057\152\141\166\141"}, {"\152\141\166\141", "\164\145\170\164\057\170\055\152\141\166\141\055\163\157\165\162\143\145"}, {"\152\143\155", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\152\141\166\141\055\143\157\155\155\145\162\143\145"}, {"\152\146\151\146", "\151\155\141\147\145\057\152\160\145\147"}, {"\152\156\154\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\152\141\166\141\055\152\156\154\160\055\146\151\154\145"}, {"\152\160\145", "\151\155\141\147\145\057\152\160\145\147"}, {"\152\160\145\147", "\151\155\141\147\145\057\152\160\145\147"}, {"\152\160\147", "\151\155\141\147\145\057\152\160\145\147"}, {"\152\160\163", "\151\155\141\147\145\057\170\055\152\160\163"}, {"\152\163", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\152\141\166\141\163\143\162\151\160\164"}, {"\152\165\164", "\151\155\141\147\145\057\152\165\164\166\151\163\151\157\156"}, {"\153\141\162", "\141\165\144\151\157\057\155\151\144\151"}, {"\153\163\150", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\153\163\150"}, {"\154\141", "\141\165\144\151\157\057\170\055\156\163\160\141\165\144\151\157"}, {"\154\141\155", "\141\165\144\151\157\057\170\055\154\151\166\145\141\165\144\151\157"}, {"\154\141\164\145\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\154\141\164\145\170"}, {"\154\150\141", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\154\150\141"}, {"\154\151\163\164", "\164\145\170\164\057\160\154\141\151\156"}, {"\154\155\141", "\141\165\144\151\157\057\170\055\156\163\160\141\165\144\151\157"}, {"\154\157\147", "\164\145\170\164\057\160\154\141\151\156"}, {"\154\163\164", "\164\145\170\164\057\160\154\141\151\156"}, {"\154\163\170", "\164\145\170\164\057\170\055\154\141\055\141\163\146"}, {"\154\164\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\154\141\164\145\170"}, {"\154\172\150", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\154\172\150"}, {"\154\172\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\154\172\170"}, {"\155", "\164\145\170\164\057\160\154\141\151\156"}, {"\155", "\164\145\170\164\057\170\055\155"}, {"\155\061\166", "\166\151\144\145\157\057\155\160\145\147"}, {"\155\062\141", "\141\165\144\151\157\057\155\160\145\147"}, {"\155\062\166", "\166\151\144\145\157\057\155\160\145\147"}, {"\155\063\165", "\141\165\144\151\157\057\170\055\155\160\145\161\165\162\154"}, {"\155\141\156", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\162\157\146\146\055\155\141\156"}, {"\155\141\156\151\146\145\163\164", "\141\160\160\154\151\143\141\164\151\157\156\057\155\141\156\151\146\145\163\164"}, {"\155\141\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\156\141\166\151\155\141\160"}, {"\155\141\162", "\164\145\170\164\057\160\154\141\151\156"}, {"\155\142\144", "\141\160\160\154\151\143\141\164\151\157\156\057\155\142\145\144\154\145\164"}, {"\155\143\044", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\155\141\147\151\143\055\143\141\160\055\160\141\143\153\141\147\145\055\061\056\060"}, {"\155\143\144", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\155\141\164\150\143\141\144"}, {"\155\143\146", "\151\155\141\147\145\057\166\141\163\141"}, {"\155\143\160", "\141\160\160\154\151\143\141\164\151\157\156\057\156\145\164\155\143"}, {"\155\145", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\162\157\146\146\055\155\145"}, {"\155\150\164", "\155\145\163\163\141\147\145\057\162\146\143\070\062\062"}, {"\155\150\164\155\154", "\155\145\163\163\141\147\145\057\162\146\143\070\062\062"}, {"\155\151\144", "\141\165\144\151\157\057\155\151\144\151"}, {"\155\151\144\151", "\141\165\144\151\157\057\155\151\144\151"}, {"\155\151\155\145", "\155\145\163\163\141\147\145\057\162\146\143\070\062\062"}, {"\155\152\146", "\141\165\144\151\157\057\170\055\166\156\144\056\101\165\144\151\157\105\170\160\154\157\163\151\157\156\056\115\152\165\151\143\145\115\145\144\151\141\106\151\154\145"}, {"\155\152\160\147", "\166\151\144\145\157\057\170\055\155\157\164\151\157\156\055\152\160\145\147"}, {"\155\153\166", "\166\151\144\145\157\057\170\055\155\141\164\162\157\163\153\141"}, {"\155\155", "\141\160\160\154\151\143\141\164\151\157\156\057\142\141\163\145\066\064"}, {"\155\155\145", "\141\160\160\154\151\143\141\164\151\157\156\057\142\141\163\145\066\064"}, {"\155\157\144", "\141\165\144\151\157\057\170\055\155\157\144"}, {"\155\157\157\166", "\166\151\144\145\157\057\161\165\151\143\153\164\151\155\145"}, {"\155\157\166", "\166\151\144\145\157\057\161\165\151\143\153\164\151\155\145"}, {"\155\157\166\151\145", "\166\151\144\145\157\057\170\055\163\147\151\055\155\157\166\151\145"}, {"\155\160\062", "\141\165\144\151\157\057\155\160\145\147"}, {"\155\160\063", "\141\165\144\151\157\057\155\160\145\147\063"}, {"\155\160\064", "\166\151\144\145\157\057\155\160\064"}, {"\155\160\141", "\141\165\144\151\157\057\155\160\145\147"}, {"\155\160\141", "\166\151\144\145\157\057\155\160\145\147"}, {"\155\160\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\160\162\157\152\145\143\164"}, {"\155\160\145", "\166\151\144\145\157\057\155\160\145\147"}, {"\155\160\145\147", "\166\151\144\145\157\057\155\160\145\147"}, {"\155\160\147", "\166\151\144\145\157\057\155\160\145\147"}, {"\155\160\147\141", "\141\165\144\151\157\057\155\160\145\147"}, {"\155\160\160", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\155\163\055\160\162\157\152\145\143\164"}, {"\155\160\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\160\162\157\152\145\143\164"}, {"\155\160\166", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\160\162\157\152\145\143\164"}, {"\155\160\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\160\162\157\152\145\143\164"}, {"\155\162\143", "\141\160\160\154\151\143\141\164\151\157\156\057\155\141\162\143"}, {"\155\163", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\162\157\146\146\055\155\163"}, {"\155\166", "\166\151\144\145\157\057\170\055\163\147\151\055\155\157\166\151\145"}, {"\155\171", "\141\165\144\151\157\057\155\141\153\145"}, {"\155\172\172", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\166\156\144\056\101\165\144\151\157\105\170\160\154\157\163\151\157\156\056\155\172\172"}, {"\156\141\160", "\151\155\141\147\145\057\156\141\160\154\160\163"}, {"\156\141\160\154\160\163", "\151\155\141\147\145\057\156\141\160\154\160\163"}, {"\156\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\156\145\164\143\144\146"}, {"\156\143\155", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\156\157\153\151\141\056\143\157\156\146\151\147\165\162\141\164\151\157\156\055\155\145\163\163\141\147\145"}, {"\156\151\146", "\151\155\141\147\145\057\170\055\156\151\146\146"}, {"\156\151\146\146", "\151\155\141\147\145\057\170\055\156\151\146\146"}, {"\156\151\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\155\151\170\055\164\162\141\156\163\146\145\162"}, {"\156\163\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\157\156\146\145\162\145\156\143\145"}, {"\156\166\144", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\156\141\166\151\144\157\143"}, {"\157\144\141", "\141\160\160\154\151\143\141\164\151\157\156\057\157\144\141"}, {"\157\147\147", "\166\151\144\145\157\057\157\147\147"}, {"\157\147\155", "\166\151\144\145\157\057\157\147\147"}, {"\157\155\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\157\155\143"}, {"\157\155\143\144", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\157\155\143\144\141\164\141\155\141\153\145\162"}, {"\157\155\143\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\157\155\143\162\145\147\145\162\141\164\157\162"}, {"\160", "\164\145\170\164\057\170\055\160\141\163\143\141\154"}, {"\160\141\163", "\164\145\170\164\057\160\141\163\143\141\154"}, {"\160\142\155", "\151\155\141\147\145\057\170\055\160\157\162\164\141\142\154\145\055\142\151\164\155\141\160"}, {"\160\143\154", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\160\143\154"}, {"\160\143\164", "\151\155\141\147\145\057\170\055\160\151\143\164"}, {"\160\143\170", "\151\155\141\147\145\057\170\055\160\143\170"}, {"\160\144\142", "\143\150\145\155\151\143\141\154\057\170\055\160\144\142"}, {"\160\144\146", "\141\160\160\154\151\143\141\164\151\157\156\057\160\144\146"}, {"\160\146\165\156\153", "\141\165\144\151\157\057\155\141\153\145"}, {"\160\147\155", "\151\155\141\147\145\057\170\055\160\157\162\164\141\142\154\145\055\147\162\141\171\155\141\160"}, {"\160\151\143", "\151\155\141\147\145\057\160\151\143\164"}, {"\160\151\143\164", "\151\155\141\147\145\057\160\151\143\164"}, {"\160\153\147", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\156\145\167\164\157\156\055\143\157\155\160\141\164\151\142\154\145\055\160\153\147"}, {"\160\153\157", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\155\163\055\160\153\151\056\160\153\157"}, {"\160\154\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\120\151\130\103\114\163\143\162\151\160\164"}, {"\160\155\064", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\160\141\147\145\155\141\153\145\162"}, {"\160\155\065", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\160\141\147\145\155\141\153\145\162"}, {"\160\156\147", "\151\155\141\147\145\057\160\156\147"}, {"\160\156\155", "\151\155\141\147\145\057\170\055\160\157\162\164\141\142\154\145\055\141\156\171\155\141\160"}, {"\160\157\164", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\160\157\167\145\162\160\157\151\156\164"}, {"\160\157\166", "\155\157\144\145\154\057\170\055\160\157\166"}, {"\160\160\141", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\155\163\055\160\157\167\145\162\160\157\151\156\164"}, {"\160\160\155", "\151\155\141\147\145\057\170\055\160\157\162\164\141\142\154\145\055\160\151\170\155\141\160"}, {"\160\160\163", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\160\157\167\145\162\160\157\151\156\164"}, {"\160\160\164", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\160\157\167\145\162\160\157\151\156\164"}, {"\160\160\172", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\160\157\167\145\162\160\157\151\156\164"}, {"\160\162\145", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\146\162\145\145\154\141\156\143\145"}, {"\160\162\164", "\141\160\160\154\151\143\141\164\151\157\156\057\160\162\157\137\145\156\147"}, {"\160\163", "\141\160\160\154\151\143\141\164\151\157\156\057\160\157\163\164\163\143\162\151\160\164"}, {"\160\166\165", "\160\141\154\145\157\166\165\057\170\055\160\166"}, {"\160\167\172", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\155\163\055\160\157\167\145\162\160\157\151\156\164"}, {"\160\171", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\160\150\171\164\157\156"}, {"\160\171\143", "\141\160\160\154\151\143\141\151\164\157\156\057\170\055\142\171\164\145\143\157\144\145\056\160\171\164\150\157\156"}, {"\161\143\160", "\141\165\144\151\157\057\166\156\144\056\161\143\145\154\160"}, {"\161\144\063", "\170\055\167\157\162\154\144\057\170\055\063\144\155\146"}, {"\161\144\063\144", "\170\055\167\157\162\154\144\057\170\055\063\144\155\146"}, {"\161\151\146", "\151\155\141\147\145\057\170\055\161\165\151\143\153\164\151\155\145"}, {"\161\164", "\166\151\144\145\157\057\161\165\151\143\153\164\151\155\145"}, {"\161\164\143", "\166\151\144\145\157\057\170\055\161\164\143"}, {"\161\164\151", "\151\155\141\147\145\057\170\055\161\165\151\143\153\164\151\155\145"}, {"\161\164\151\146", "\151\155\141\147\145\057\170\055\161\165\151\143\153\164\151\155\145"}, {"\162\141", "\141\165\144\151\157\057\170\055\162\145\141\154\141\165\144\151\157"}, {"\162\141\155", "\141\165\144\151\157\057\170\055\160\156\055\162\145\141\154\141\165\144\151\157"}, {"\162\141\163", "\151\155\141\147\145\057\170\055\143\155\165\055\162\141\163\164\145\162"}, {"\162\141\163\164", "\151\155\141\147\145\057\143\155\165\055\162\141\163\164\145\162"}, {"\162\145\170\170", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\162\145\170\170"}, {"\162\146", "\151\155\141\147\145\057\166\156\144\056\162\156\055\162\145\141\154\146\154\141\163\150"}, {"\162\147\142", "\151\155\141\147\145\057\170\055\162\147\142"}, {"\162\155", "\141\165\144\151\157\057\170\055\160\156\055\162\145\141\154\141\165\144\151\157"}, {"\162\155\151", "\141\165\144\151\157\057\155\151\144"}, {"\162\155\155", "\141\165\144\151\157\057\170\055\160\156\055\162\145\141\154\141\165\144\151\157"}, {"\162\156\147", "\141\160\160\154\151\143\141\164\151\157\156\057\162\151\156\147\151\156\147\055\164\157\156\145\163"}, {"\162\156\170", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\162\156\055\162\145\141\154\160\154\141\171\145\162"}, {"\162\157\146\146", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\162\157\146\146"}, {"\162\160", "\151\155\141\147\145\057\166\156\144\056\162\156\055\162\145\141\154\160\151\170"}, {"\162\160\155", "\141\165\144\151\157\057\170\055\160\156\055\162\145\141\154\141\165\144\151\157\055\160\154\165\147\151\156"}, {"\162\164", "\164\145\170\164\057\162\151\143\150\164\145\170\164"}, {"\162\164\146", "\164\145\170\164\057\162\151\143\150\164\145\170\164"}, {"\162\164\170", "\164\145\170\164\057\162\151\143\150\164\145\170\164"}, {"\162\166", "\166\151\144\145\157\057\166\156\144\056\162\156\055\162\145\141\154\166\151\144\145\157"}, {"\163", "\164\145\170\164\057\170\055\141\163\155"}, {"\163\063\155", "\141\165\144\151\157\057\163\063\155"}, {"\163\142\153", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\142\157\157\153"}, {"\163\144\155\154", "\164\145\170\164\057\160\154\141\151\156"}, {"\163\144\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\144\160"}, {"\163\144\162", "\141\160\160\154\151\143\141\164\151\157\156\057\163\157\165\156\144\145\162"}, {"\163\145\141", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\145\141"}, {"\163\145\164", "\141\160\160\154\151\143\141\164\151\157\156\057\163\145\164"}, {"\163\147\155", "\164\145\170\164\057\170\055\163\147\155\154"}, {"\163\147\155\154", "\164\145\170\164\057\170\055\163\147\155\154"}, {"\163\150", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\150"}, {"\163\150\141\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\150\141\162"}, {"\163\150\164\155\154", htmlMmimeT}, {"\163\151\144", "\141\165\144\151\157\057\170\055\160\163\151\144"}, {"\163\151\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\164\165\146\146\151\164"}, {"\163\153\144", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\153\157\141\156"}, {"\163\153\155", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\153\157\141\156"}, {"\163\153\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\153\157\141\156"}, {"\163\153\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\153\157\141\156"}, {"\163\154", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\145\145\154\157\147\157"}, {"\163\155\151", "\141\160\160\154\151\143\141\164\151\157\156\057\163\155\151\154"}, {"\163\155\151\154", "\141\160\160\154\151\143\141\164\151\157\156\057\163\155\151\154"}, {"\163\156\144", "\141\165\144\151\157\057\142\141\163\151\143"}, {"\163\157\154", "\141\160\160\154\151\143\141\164\151\157\156\057\163\157\154\151\144\163"}, {"\163\160\154", "\141\160\160\154\151\143\141\164\151\157\156\057\146\165\164\165\162\145\163\160\154\141\163\150"}, {"\163\160\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\160\162\151\164\145"}, {"\163\160\162\151\164\145", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\160\162\151\164\145"}, {"\163\162\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\141\151\163\055\163\157\165\162\143\145"}, {"\163\163\151", "\164\145\170\164\057\170\055\163\145\162\166\145\162\055\160\141\162\163\145\144\055\150\164\155\154"}, {"\163\163\155", "\141\160\160\154\151\143\141\164\151\157\156\057\163\164\162\145\141\155\151\156\147\155\145\144\151\141"}, {"\163\163\164", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\155\163\055\160\153\151\056\143\145\162\164\163\164\157\162\145"}, {"\163\164\145\160", "\141\160\160\154\151\143\141\164\151\157\156\057\163\164\145\160"}, {"\163\164\160", "\141\160\160\154\151\143\141\164\151\157\156\057\163\164\145\160"}, {"\163\166\064\143\160\151\157", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\166\064\143\160\151\157"}, {"\163\166\064\143\162\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\166\064\143\162\143"}, {"\163\166\147", "\151\155\141\147\145\057\163\166\147\053\170\155\154"}, {"\163\166\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\157\162\154\144"}, {"\163\167\146", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\150\157\143\153\167\141\166\145\055\146\154\141\163\150"}, {"\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\162\157\146\146"}, {"\164\141\154\153", "\164\145\170\164\057\170\055\163\160\145\145\143\150"}, {"\164\141\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\141\162"}, {"\164\142\153", "\141\160\160\154\151\143\141\164\151\157\156\057\164\157\157\154\142\157\157\153"}, {"\164\143\154", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\164\143\154"}, {"\164\143\163\150", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\164\143\163\150"}, {"\164\145\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\145\170"}, {"\164\145\170\151", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\145\170\151\156\146\157"}, {"\164\145\170\151\156\146\157", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\145\170\151\156\146\157"}, {"\164\145\170\164", "\141\160\160\154\151\143\141\164\151\157\156\057\160\154\141\151\156"}, {"\164\145\170\164", "\164\145\170\164\057\160\154\141\151\156"}, {"\164\147\172", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\157\155\160\162\145\163\163\145\144"}, {"\164\151\146", "\151\155\141\147\145\057\170\055\164\151\146\146"}, {"\164\151\146\146", "\151\155\141\147\145\057\170\055\164\151\146\146"}, {"\164\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\164\162\157\146\146"}, {"\164\163\151", "\141\165\144\151\157\057\164\163\160\055\141\165\144\151\157"}, {"\164\163\160", "\141\165\144\151\157\057\164\163\160\154\141\171\145\162"}, {"\164\163\166", "\164\145\170\164\057\164\141\142\055\163\145\160\141\162\141\164\145\144\055\166\141\154\165\145\163"}, {"\164\165\162\142\157\164", "\151\155\141\147\145\057\146\154\157\162\151\141\156"}, {"\164\170\164", "\164\145\170\164\057\160\154\141\151\156"}, {"\165\151\154", "\164\145\170\164\057\170\055\165\151\154"}, {"\165\156\151", "\164\145\170\164\057\165\162\151\055\154\151\163\164"}, {"\165\156\151\163", "\164\145\170\164\057\165\162\151\055\154\151\163\164"}, {"\165\156\166", "\141\160\160\154\151\143\141\164\151\157\156\057\151\055\144\145\141\163"}, {"\165\162\151", "\164\145\170\164\057\165\162\151\055\154\151\163\164"}, {"\165\162\151\163", "\164\145\170\164\057\165\162\151\055\154\151\163\164"}, {"\165\163\164\141\162", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\165\163\164\141\162"}, {"\165\163\164\141\162", "\155\165\154\164\151\160\141\162\164\057\170\055\165\163\164\141\162"}, {"\165\165", "\164\145\170\164\057\170\055\165\165\145\156\143\157\144\145"}, {"\165\165\145", "\164\145\170\164\057\170\055\165\165\145\156\143\157\144\145"}, {"\166\143\144", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\144\154\151\156\153"}, {"\166\143\163", "\164\145\170\164\057\170\055\166\103\141\154\145\156\144\141\162"}, {"\166\144\141", "\141\160\160\154\151\143\141\164\151\157\156\057\166\144\141"}, {"\166\144\157", "\166\151\144\145\157\057\166\144\157"}, {"\166\145\167", "\141\160\160\154\151\143\141\164\151\157\156\057\147\162\157\165\160\167\151\163\145"}, {"\166\151\166", "\166\151\144\145\157\057\166\151\166\157"}, {"\166\151\166\157", "\166\151\144\145\157\057\166\151\166\157"}, {"\166\155\144", "\141\160\160\154\151\143\141\164\151\157\156\057\166\157\143\141\154\164\145\143\055\155\145\144\151\141\055\144\145\163\143"}, {"\166\155\146", "\141\160\160\154\151\143\141\164\151\157\156\057\166\157\143\141\154\164\145\143\055\155\145\144\151\141\055\146\151\154\145"}, {"\166\157\143", "\141\165\144\151\157\057\170\055\166\157\143"}, {"\166\157\163", "\166\151\144\145\157\057\166\157\163\141\151\143"}, {"\166\157\170", "\141\165\144\151\157\057\166\157\170\167\141\162\145"}, {"\166\161\145", "\141\165\144\151\157\057\170\055\164\167\151\156\166\161\055\160\154\165\147\151\156"}, {"\166\161\146", "\141\165\144\151\157\057\170\055\164\167\151\156\166\161"}, {"\166\161\154", "\141\165\144\151\157\057\170\055\164\167\151\156\166\161\055\160\154\165\147\151\156"}, {"\166\162\155\154", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\166\162\155\154"}, {"\166\162\164", "\170\055\167\157\162\154\144\057\170\055\166\162\164"}, {"\166\163\144", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\166\151\163\151\157"}, {"\166\163\164", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\166\151\163\151\157"}, {"\166\163\167", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\166\151\163\151\157"}, {"\167\066\060", "\141\160\160\154\151\143\141\164\151\157\156\057\167\157\162\144\160\145\162\146\145\143\164\066\056\060"}, {"\167\066\061", "\141\160\160\154\151\143\141\164\151\157\156\057\167\157\162\144\160\145\162\146\145\143\164\066\056\061"}, {"\167\066\167", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\167\157\162\144"}, {"\167\141\166", "\141\165\144\151\157\057\167\141\166"}, {"\167\142\061", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\161\160\162\157"}, {"\167\142\155\160", "\151\155\141\147\145\057\166\156\144\056\167\141\160\056\167\142\155\160"}, {"\167\145\142", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\170\141\162\141"}, {"\167\151\172", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\167\157\162\144"}, {"\167\153\061", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\061\062\063"}, {"\167\155\146", "\167\151\156\144\157\167\163\057\155\145\164\141\146\151\154\145"}, {"\167\155\154", "\164\145\170\164\057\166\156\144\056\167\141\160\056\167\155\154"}, {"\167\155\154\143", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\167\141\160\056\167\155\154\143"}, {"\167\155\154\163", "\164\145\170\164\057\166\156\144\056\167\141\160\056\167\155\154\163\143\162\151\160\164"}, {"\167\155\154\163\143", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\167\141\160\056\167\155\154\163\143\162\151\160\164\143"}, {"\167\157\162\144", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\167\157\162\144"}, {"\167\160", "\141\160\160\154\151\143\141\164\151\157\156\057\167\157\162\144\160\145\162\146\145\143\164"}, {"\167\160\065", "\141\160\160\154\151\143\141\164\151\157\156\057\167\157\162\144\160\145\162\146\145\143\164"}, {"\167\160\066", "\141\160\160\154\151\143\141\164\151\157\156\057\167\157\162\144\160\145\162\146\145\143\164"}, {"\167\160\144", "\141\160\160\154\151\143\141\164\151\157\156\057\167\157\162\144\160\145\162\146\145\143\164"}, {"\167\161\061", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\154\157\164\165\163"}, {"\167\162\151", "\141\160\160\154\151\143\141\164\151\157\156\057\155\163\167\162\151\164\145"}, {"\167\162\154", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\157\162\154\144"}, {"\167\162\172", "\155\157\144\145\154\057\166\162\155\154"}, {"\167\162\172", "\170\055\167\157\162\154\144\057\170\055\166\162\155\154"}, {"\167\163\143", "\164\145\170\164\057\163\143\162\151\160\154\145\164"}, {"\167\163\162\143", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\141\151\163\055\163\157\165\162\143\145"}, {"\167\164\153", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\151\156\164\141\154\153"}, {"\170\055\160\156\147", "\151\155\141\147\145\057\160\156\147"}, {"\170\141\155\154", "\141\160\160\154\151\143\141\164\151\157\156\057\170\141\155\154\053\170\155\154"}, {"\170\141\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\163\151\154\166\145\162\154\151\147\150\164\055\141\160\160"}, {"\170\142\141\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\155\163\055\170\142\141\160"}, {"\170\142\155", "\151\155\141\147\145\057\170\055\170\142\151\164\155\141\160"}, {"\170\144\162", "\166\151\144\145\157\057\170\055\141\155\164\055\144\145\155\157\162\165\156"}, {"\170\147\172", "\170\147\154\057\144\162\141\167\151\156\147"}, {"\170\151\146", "\151\155\141\147\145\057\166\156\144\056\170\151\146\146"}, {"\170\154", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\141", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\142", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\143", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\144", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\153", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\154", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\155", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\163", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\164", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\166", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\154\167", "\141\160\160\154\151\143\141\164\151\157\156\057\145\170\143\145\154"}, {"\170\155", "\141\165\144\151\157\057\170\155"}, {"\170\155\154", "\141\160\160\154\151\143\141\164\151\157\156\057\170\155\154\073\040\143\150\141\162\163\145\164\075\125\124\106\055\070"}, {"\170\155\172", "\170\147\154\057\155\157\166\151\145"}, {"\170\160\151\170", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\166\156\144\056\154\163\055\170\160\151\170"}, {"\170\160\155", "\151\155\141\147\145\057\170\055\170\160\151\170\155\141\160"}, {"\170\160\155", "\151\155\141\147\145\057\170\160\155"}, {"\170\160\163", "\141\160\160\154\151\143\141\164\151\157\156\057\166\156\144\056\155\163\055\170\160\163\144\157\143\165\155\145\156\164"}, {"\170\163\162", "\166\151\144\145\157\057\170\055\141\155\164\055\163\150\157\167\162\165\156"}, {"\170\167\144", "\151\155\141\147\145\057\170\055\170\167\144"}, {"\170\171\172", "\143\150\145\155\151\143\141\154\057\170\055\160\144\142"}, {"\172", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\143\157\155\160\162\145\163\163\145\144"}, {"\172\151\160", "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\172\151\160\055\143\157\155\160\162\145\163\163\145\144"}, {"\172\163\150", "\164\145\170\164\057\170\055\163\143\162\151\160\164\056\172\163\150"} }; static int am33xxclkdm(const void *sourcerouting, const void *ducaticlkdm) { return baStrCaseCmp((const char*)sourcerouting, ((HttpMimeType*)ducaticlkdm)->ext); } BA_API const char* httpFindMime(const char* ext) { HttpMimeType* emupageallocmap = (HttpMimeType*) baBSearch(ext, mimeTypes, sizeof(mimeTypes)/sizeof(mimeTypes[0]), sizeof(mimeTypes[0]), am33xxclkdm); return emupageallocmap ? emupageallocmap->val : 0; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include BA_API void cspCompileTypeIntegrityCheck(void) { baAssert(sizeof(U32) == 4); baAssert(sizeof(HttpDiskBlock) == 8); baAssert(sizeof(HttpDiskPage) == 20); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #include const char baBin2HexTable[] = { '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', '\070', '\071', '\141', '\142', '\143', '\144', '\145', '\146' }; BA_API void baConvBin2Hex(void* writereg32, U8 devicehsmmc1) { ((U8*)writereg32)[0] = baBin2HexTable[((U8)devicehsmmc1) >> 4]; ((U8*)writereg32)[1] = baBin2HexTable[((U8)devicehsmmc1) & 0x0f]; } static int pc104maskack(int c) { if (c >= '\060' && c <= '\071') return c - '\060'; if (c >= '\141' && c <= '\146') return c - '\141' + 10; if (c >= '\101' && c <= '\106') return c - '\101' + 10; return -1; } BA_API char* httpUnescapeInternal(char* forcereload, BaBool bv1) { char* to = forcereload; for(; *forcereload; ++forcereload, ++to) { if(*forcereload == '\045') { int h1, h2; U8 c; if( (h1 = pc104maskack(forcereload[1])) < 0) return 0; if( (h2 = pc104maskack(forcereload[2])) < 0) return 0; c = (U8)((h1 << 4) | h2); if(c == 0) return 0; if((c < 0x20 || c == 0x7F) && !bv1) return 0; *to = (char)c; forcereload += 2; } else if(bv1 && *forcereload == '\053') { *to = '\040'; } else { if((U8)*forcereload < 0x20 || (U8)*forcereload == 0x7F) return 0; *to = *forcereload; } } *to = 0; return to-1; } BA_API char* baStrdup(const char* str) { char* dup; if(!str) return 0; dup = (char*)baMalloc(strlen(str)+1); if(dup) strcpy(dup, str); return dup; } BA_API const void* baBSearch(const void* sourcerouting, const void* validconfig, int num, int icachealiases, int (*cmp) (const void*,const void*)) { register int a, b, c, dir; a = 0; b = num - 1; while (a <= b) { c = (a + b) >> 1; if ( (dir = (*cmp) (sourcerouting, ((const char*)validconfig + (c * icachealiases)))) != 0) { if (dir < 0) b = c - 1; else a = c + 1; } else return ((const char*)validconfig + (c * icachealiases)); } return 0; } BA_API int baStrCaseCmp(const char *a, const char *b) { register int n; while((*a == *b || (n = bTolower(*a) - bTolower(*b)) == 0)) { if (*a == 0) return 0; a++, b++; } return n; } BA_API int baStrnCaseCmp(const char *a, const char *b, size_t len) { register int n=0; while (len-- > 0 && (*a == *b || (n = bTolower(*a) - bTolower(*b)) == 0)) { if (*a == 0) return 0; a++, b++; } return n; } const char* baGetToken(const char** str, const char* set) { const char* end; while(bStrchr(set, **str)) { if(*++(*str) == 0) return 0; } end = *str; while(bStrchr(set, *end)==0) ++end; return end != *str ? end : 0; } BA_API U8 baConvHex2Bin( U8 c ) { if ( c >= '\060' && c <= '\071' ) return c - '\060'; if ( c >= '\141' && c <= '\146' ) return c - '\141' + 10; if ( c >= '\101' && c <= '\106' ) return c - '\101' + 10; return 0; } BA_API void baConvU32ToHex(void* to, U32 forcereload) { U8* f = ((U8*)&forcereload + 3); while(f >= (U8*)&forcereload) { baConvBin2Hex(to, *f); f--; to=((U8*)to)+2; } } BA_API U32 baConvHexToU32(const void* forcereload) { if(forcereload) { U32 to; U8* t = ((U8*)&to + 3); while(t >= (U8*)&to) { *t = baConvHex2Bin(((U8*)forcereload)[0])*16+baConvHex2Bin(((U8*)forcereload)[1]); t--; forcereload = ((U8*)forcereload)+2; } return to; } return 0; } #define PARSE_DATE_BUF_SIZE 20 typedef struct { const char* str; int value; } HttpDateElement; static const HttpDateElement weekDays[] = { { "\146\162\151", 5 }, { "\155\157\156", 1 }, { "\163\141\164", 6 }, { "\163\165\156", 0 }, { "\164\150\165", 4 }, { "\164\165\145", 2 }, { "\167\145\144", 3 }, }; static const HttpDateElement leoparddevices[] = { { "\141\160\162", 3 }, { "\141\165\147", 7 }, { "\144\145\143", 11 }, { "\146\145\142", 1 }, { "\152\141\156", 0 }, { "\152\165\154", 6 }, { "\152\165\156", 5 }, { "\155\141\162", 2 }, { "\155\141\171", 4 }, { "\156\157\166", 10 }, { "\157\143\164", 9 }, { "\163\145\160", 8 } }; static int timerclass(const void *str, const void *ducaticlkdm) { return baStrnCaseCmp((const char*)str, ((HttpDateElement*)ducaticlkdm)->str, strlen(((HttpDateElement*)ducaticlkdm)->str)); } static const HttpDateElement* chargerestart(char* str) { return (const HttpDateElement*)baBSearch( str, leoparddevices, sizeof(leoparddevices)/sizeof(leoparddevices[0]), sizeof(leoparddevices[0]), timerclass); } static int conf0write(char* buf, const char** str, const char* set) { size_t len; const char* ref = baGetToken(str, set); if(!ref) return -1; len=ref-*str; if (len >= PARSE_DATE_BUF_SIZE) return -1; memcpy(buf, *str, len); buf[len]=0; *str=ref; return 0; } static int earlyparam(struct BaTm* tm, char* buf, const char** str) { if(conf0write(buf, str, "\072")) return -1; tm->tm_hour = bAtoi(buf); if(conf0write(buf, str, "\072")) return -1; tm->tm_min = bAtoi(buf); if(conf0write(buf, str, "\040\011\072")) return -1; tm->tm_sec = bAtoi(buf); return 0; } BA_API BaTime baParseDate(const char* str) { char buf[PARSE_DATE_BUF_SIZE]; struct BaTm tm; BaTimeEx tex; const HttpDateElement* dateElem; char allocsimple; if(!str || !*str) return 0; if(conf0write(buf, &str, "\040\011\054")) return 0; dateElem = (const HttpDateElement*)baBSearch( buf, weekDays, sizeof(weekDays)/sizeof(weekDays[0]), sizeof(weekDays[0]), timerclass); if(!dateElem) return 0; allocsimple = *str++; if(conf0write(buf, &str, "\040\011\055")) return 0; if(allocsimple == '\054') { tm.tm_mday = bAtoi(buf); if(conf0write(buf, &str, "\040\011\055")) return 0; if( (dateElem=chargerestart(buf)) == 0 ) return 0; tm.tm_mon = dateElem->value+1; if(conf0write(buf, &str, "\040\011\055")) return 0; tm.tm_year = bAtoi(buf); if(earlyparam(&tm, buf, &str)) return 0; } else { if( (dateElem=chargerestart(buf)) == 0 ) return 0; tm.tm_mon = dateElem->value; if(conf0write(buf, &str, "\040\011")) return 0; tm.tm_mday = bAtoi(buf); if(earlyparam(&tm, buf, &str)) return 0; if(conf0write(buf, &str, "\040\011")) return 0; tm.tm_year = bAtoi(buf); tm.tm_year -= 1900; } tm.tm_mon--; return baTm2TimeEx(&tm, FALSE, &tex) ? 0 : tex.sec; } static const int decompsetup[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,62,-1,63, 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,63, -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 }; BA_API int baB64Decode(U8* disableevent, int queryinput, const char* resourcecamera) { const char* cp; int len, phase; int d, prev_d; U8 c; prev_d = len = phase = 0; for ( cp = resourcecamera; *cp != '\000'; ++cp ) { d = decompsetup[(int)*cp]; if ( d != -1 ) { switch ( phase ) { case 0: ++phase; break; case 1: c = (char)( ( prev_d << 2 ) | ( ( d & 0x30 ) >> 4 ) ); if ( len < queryinput ) disableevent[len++] = c; ++phase; break; case 2: c = (char)( ( ( prev_d & 0xf ) << 4 ) | ( ( d & 0x3c ) >> 2 ) ); if ( len < queryinput ) disableevent[len++] = c; ++phase; break; case 3: c = (char)( ( ( prev_d & 0x03 ) << 6 ) | d ); if ( len < queryinput ) disableevent[len++] = c; phase = 0; break; } prev_d = d; } } return len; } BA_API int baElideDotDot(char* str) { char* ptr; char* end; size_t len; char* secondarytrampoline; int decodeldmstm=0; if(*str == '\057') str++; ptr = str; end = ptr+strlen(ptr); for(;ptr < end; ptr++) { if(*ptr == '\057') { if(ptr[1] == '\057') { secondarytrampoline = ptr+1; while(*secondarytrampoline == '\057' && secondarytrampoline < end) ++secondarytrampoline; len = end - secondarytrampoline; memmove(ptr+1, secondarytrampoline, len); end -= (secondarytrampoline-ptr-1); *end=0; } ++decodeldmstm; } else if(*ptr == '\056') { if(ptr == str || *(ptr-1) == '\057') { if(ptr[1] == '\057' || ptr+1 == end) { len = end - ptr - 2; if(len > 0) { if( (end - ptr - 2) <= 0 ) return 0; memmove(ptr, ptr+2, len); end -= 2; *end=0; if(ptr > str) { --ptr; if(ptr[0] == '\057' && ptr[1] == '\057' && ptr != str) --ptr; } } else *ptr=0; } else if(ptr[1] == '\056') { baAssert(ptr+2 <= end); if(ptr+2 == end || ptr[2] == '\057') { if(decodeldmstm == 0) { *str=0; return -1; } secondarytrampoline = ptr - 2; while(*secondarytrampoline != '\057' && secondarytrampoline != str) --secondarytrampoline; ptr+=2; if(ptr == end) *secondarytrampoline = 0; else { if(decodeldmstm == 1) ptr++; memmove(secondarytrampoline, ptr, end - ptr); end -= (ptr-secondarytrampoline); *end=0; --decodeldmstm; ptr = secondarytrampoline; } } } } } } return 0; } BA_API void baXmlUnescape(char* f) { char* to = f; for ( ; *f != '\000'; ++to, ++f) { if(*f == '\046') { if(f[1]=='\154' && f[2]=='\164' && f[3]=='\073') *to='\074',f+=3; else if(f[1]=='\147' && f[2]=='\164' && f[3]=='\073') *to='\076',f+=3; else if(f[1]=='\141' && f[2]=='\160' && f[3]=='\157' && f[4]=='\163' && f[5]=='\073') *to='\047',f+=5; else if(f[1]=='\161' && f[2]=='\157' && f[3]=='\165' && f[4]=='\164' && f[5]=='\073') *to='\042',f+=5; else if(f[1]=='\141' && f[2]=='\155' && f[3]=='\160' && f[4]=='\073') *to='\046',f+=4; else *to='\046'; } else *to = *f; } *to=0; } BA_API char* httpEscape(char* out, const char* in) { for(; *in ; in++) { switch(*in) { case '\012': case '\015': case '\011': case '\040': case '\043': case '\044': case '\045': case '\046': case '\053': case '\054': case '\073': case '\074': case '\075': case '\076': case '\077': case '\100': case '\133': case '\134': case '\135': case '\136': case '\140': case '\173': case '\174': case '\175': case '\176': case '\047': *out++ = '\045'; baConvBin2Hex(out, *in); out+=2; break; default: *out++ = *in; } } *out = 0; return out; } #define EPOCHS INT64_C(62135683200) #define prioritymapping 719163 #define MIN_SEC INT64_C(-62135596800) #define MAX_SEC INT64_C(253402300799) #define protocolmailbox resourcestuart static const U16 resourcestuart[13] = { 0, 306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275 }; static U8 writelocktime[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; static const U32 decodecache[10] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; static int iommuunmap(U16 y) { return ((y & 3) == 0 && (y % 100 != 0 || y % 400 == 0)); } static int writeclkdivn(const BaTimeEx* tex) { const S64 sec = tex->sec + tex->offset * 60; if (sec < MIN_SEC || sec > MAX_SEC || tex->nsec < 0 || tex->nsec > 999999999 || tex->offset < -1439 || tex->offset > 1439) { return FALSE; } return TRUE; } BA_API U8 baDaysInMonth(U16 y, U16 m) { return writelocktime[m == 2 && iommuunmap(y)][m]; } BA_API int baTime2tmEx(const BaTimeEx* tex, const BaBool emulategicv2, struct BaTm* tm) { S64 sec; U32 rdn; U32 sid; U32 Z, H, A, B; U16 C, y, m, d; if(!writeclkdivn(tex)) return -1; sec = tex->sec + EPOCHS; if(emulategicv2) sec += tex->offset * 60; rdn = (U32)(sec / 86400); sid = sec % 86400; Z = rdn + 306; H = 100 * Z - 25; A = H / 3652425; B = A - (A >> 2); y = (100 * B + H) / 36525; C = B + Z - (1461 * y >> 2); m = (535 * C + 48950) >> 14; if (m > 12) d = C - 306, y++, m -= 12; else d = C + 59 + ((y & 3) == 0 && (y % 100 != 0 || y % 400 == 0)); tm->tm_mday = C - protocolmailbox[m]; tm->tm_mon = m - 1; tm->tm_year = y; tm->tm_wday = rdn % 7; tm->tm_yday = d - 1; tm->tm_sec = sid % 60; sid /= 60; tm->tm_min = sid % 60; sid /= 60; tm->tm_hour = sid; tm->nsec = tex->nsec; tm->offset=tex->offset; return 0; } BA_API int baTime2tm(struct BaTm *tm, BaTime t) { BaTimeEx tex; tex.sec=t; tex.nsec=0; tex.offset=0; if(baTime2tmEx(&tex, FALSE, tm)) return -1; tm->tm_year -= 1900; return 0; } BA_API int baTm2TimeEx(struct BaTm* tm, BaBool emulategicv2, BaTimeEx* tex) { U32 rdn; U32 sid; tm->tm_mon++; if(tm->tm_year < 1 || tm->tm_mon < 1 || tm->tm_mon > 12 || tm->tm_mday < 1 || tm->tm_mday > 31 || tm->tm_hour > 23 || tm->tm_min > 59 || tm->tm_sec > 59 || (tm->tm_mday > 28 && tm->tm_mday > baDaysInMonth(tm->tm_year,tm->tm_mon))) { return -1; } if(tm->tm_mon < 3) tm->tm_year--; rdn = (1461 * tm->tm_year)/4 - tm->tm_year/100 + tm->tm_year/400 + protocolmailbox[tm->tm_mon] + tm->tm_mday - 306; sid = tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec; tex->sec = ((S64)rdn - prioritymapping) * 86400 + sid; if(emulategicv2) tex->sec -= tm->offset * 60; tex->nsec = tm->nsec; tex->offset = tm->offset; return 0; } BA_API BaTime baTm2Time(struct BaTm* tm) { BaTimeEx tex; tm->tm_year += 1900; return baTm2TimeEx(tm, FALSE, &tex) ? 0 : tex.sec; } static int dcacheexits(U8 * const p, size_t i, U16 *out) { U8 d0, d1; if (((d0 = p[i + 0] - '\060') > 9) || ((d1 = p[i + 1] - '\060') > 9)) return -1; *out = d0 * 10 + d1; return 0; } static int sam9x60config(U8 * const p, size_t i, U16 *out) { U8 d0, d1, d2, d3; if (((d0 = p[i + 0] - '\060') > 9) || ((d1 = p[i + 1] - '\060') > 9) || ((d2 = p[i + 2] - '\060') > 9) || ((d3 = p[i + 3] - '\060') > 9)) return -1; *out = d0 * 1000 + d1 * 100 + d2 * 10 + d3; return 0; } BA_API int baISO8601ToTime(const char *str, size_t len, BaTimeEx *tex) { U8 *cur, *end; U32 rdn; U32 sid; U32 withinkernel; U16 year, month, day, hour, min, sec; U8 ch; cur = (U8 *)str; if (len < 20 || cur[4] != '\055' || cur[7] != '\055' || cur[13] != '\072' || cur[16] != '\072') { return -1; } ch = cur[10]; if (!(ch == '\124' || ch == '\040' || ch == '\164')) return -1; if(sam9x60config(cur, 0, &year) || year < 1 || dcacheexits(cur, 5, &month) || month < 1 || month > 12 || dcacheexits(cur, 8, &day) || day < 1 || day > 31 || dcacheexits(cur, 11, &hour) || hour > 23 || dcacheexits(cur, 14, &min) || min > 59 || dcacheexits(cur, 17, &sec) || sec > 59) { return -1; } if (day > 28 && day > baDaysInMonth(year, month)) return -1; if (month < 3) year--; rdn = (1461*year)/4 - year/100 + year/400 + protocolmailbox[month] + day - 306; sid = hour * 3600 + min * 60 + sec; end = cur + len; cur = cur + 19; withinkernel = 0; ch = *cur++; if (ch == '\056') { U8 *cachesysfs; size_t ndigits; cachesysfs = cur; for (; cur < end; cur++) { U8 bootmemalloc = *cur - '\060'; if (bootmemalloc > 9) break; withinkernel = withinkernel * 10 + bootmemalloc; } ndigits = cur - cachesysfs; if (ndigits < 1 || ndigits > 9) return -1; withinkernel *= decodecache[9 - ndigits]; if (cur == end) return -1; ch = *cur++; } if (!(ch == '\132' || ch == '\172')) { S16 idmapstart; if (cur + 5 < end || !(ch == '\053' || ch == '\055') || cur[2] != '\072') return -1; if (dcacheexits(cur, 0, &hour) || hour > 23 || dcacheexits(cur, 3, &min) || min > 59) return -1; idmapstart = hour * 60 + min; tex->offset = ch == '\055' ? -idmapstart : idmapstart; cur += 5; } else tex->offset=0; if (cur != end) return -1; tex->sec = ((S64)rdn - 719163) * 86400 + sid - tex->offset * 60; tex->nsec = withinkernel; return 0; } BA_API int baTime2ISO8601(const BaTimeEx* tex, char* str, size_t len) { struct BaTm tm; char* ptr = str; if(len < 36 || baTime2tmEx(tex, TRUE, &tm)) return -1; ptr[18] = '\060' + (tm.tm_sec % 10); tm.tm_sec /= 10; ptr[17] = '\060' + (tm.tm_sec % 6); ptr[16] = '\072'; ptr[15] = '\060' + (tm.tm_min % 10); tm.tm_min /= 10; ptr[14] = '\060' + (tm.tm_min % 6); ptr[13] = '\072'; ptr[12] = '\060' + (tm.tm_hour % 10); tm.tm_hour /= 10; ptr[11] = '\060' + (tm.tm_hour % 10); ptr[10] = '\124'; ptr[9] = '\060' + (tm.tm_mday % 10); tm.tm_mday /= 10; ptr[8] = '\060' + (tm.tm_mday % 10); ptr[7] = '\055'; tm.tm_mon++; ptr[6] = '\060' + (tm.tm_mon % 10); tm.tm_mon /= 10; ptr[5] = '\060' + (tm.tm_mon % 10); ptr[4] = '\055'; ptr[3] = '\060' + (tm.tm_year % 10); tm.tm_year /= 10; ptr[2] = '\060' + (tm.tm_year % 10); tm.tm_year /= 10; ptr[1] = '\060' + (tm.tm_year % 10); tm.tm_year /= 10; ptr[0] = '\060' + (tm.tm_year % 10); ptr += 19; if(tex->nsec) { *ptr++='\056'; ptr+=basprintf(ptr,"\045\144",tex->nsec); } if(tex->offset) { U32 platformfeatures; if (tex->offset < 0) { *ptr = '\055'; platformfeatures = -tex->offset; } else { *ptr = '\053'; platformfeatures = tex->offset; } ptr[5] = '\060' + (platformfeatures % 10); platformfeatures /= 10; ptr[4] = '\060' + (platformfeatures % 6); platformfeatures /= 6; ptr[3] = '\072'; ptr[2] = '\060' + (platformfeatures % 10); platformfeatures /= 10; ptr[1] = '\060' + (platformfeatures % 10); ptr += 6; } else { *ptr++ = '\132'; } *ptr = 0; return ptr-str; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include BA_API U32 U32_negate(U32 n) { return (U32)(-(S32)n); } BA_API U32 U32_atoi2(const char* s, const char* e) { U32 n = 0; BaBool collectlogout; if(!s) return 0; if(*s == '\055') { ++s; collectlogout = TRUE; } else collectlogout = FALSE; for ( ; s < e && *s != '\056' ; ++s ) n = 10 * n + (*s-'\060'); if(*s == '\056' && s[1]) { if(s[1] >= '\065') n++; } return collectlogout ? U32_negate(n) : n; } BA_API U32 U32_atoi(const char* s) { if(!s) return 0; return U32_atoi2(s, s+strlen(s)); } BA_API U32 U32_hextoi(const char *str) { U32 sha512store = 0; U32 i; if(!str) return 0; for(i = 0 ; i<8 && *str!=0 ; i++) { U8 c = *str++ ; if(c>='\060' && c<='\071') c -= '\060' ; else if(c>='\141' && c<='\146') c = c-'\141'+10 ; else if(c>='\101' && c<='\106') c = c-'\101'+10 ; else break; sha512store = (sha512store << 4) | c ; } return *str==0 ? sha512store : 0 ; } BA_API U64 U64_atoll2(const char* s, const char* e) { U64 n = 0; BaBool collectlogout; if(!s) return 0; if(*s == '\055') { ++s; collectlogout = TRUE; } else collectlogout = FALSE; for ( ; s < e ; ++s ) n = 10 * n + (*s-'\060'); return collectlogout ? (U64)(-(S64)n) : n; } BA_API U64 U64_atoll(const char* s) { if(!s) return 0; return U64_atoll2(s, s+strlen(s)); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include static void* AllocatorIntf_defaultMalloc(AllocatorIntf* o, size_t* icachealiases) { (void)o; return baMalloc(*icachealiases); } static void* AllocatorIntf_defaultRealloc(AllocatorIntf* o, void* arm64encrypt, size_t* icachealiases) { (void)o; return baRealloc(arm64encrypt, *icachealiases); } static void ptracewrite(AllocatorIntf* o, void* arm64encrypt) { (void)o; baFree(arm64encrypt); } BA_API AllocatorIntf* AllocatorIntf_getDefault(void) { static AllocatorIntf unmapaliases = { AllocatorIntf_defaultMalloc, AllocatorIntf_defaultRealloc, ptracewrite }; return &unmapaliases; } BA_API char* baStrdup2(struct AllocatorIntf* a, const char* str) { char* dup; size_t icachealiases; if(!str) return 0; icachealiases = strlen(str)+1; dup = (char*)AllocatorIntf_malloc(a, &icachealiases); if(dup) strcpy(dup, str); return dup; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #ifndef NO_SHARKSSL #include #endif BA_API const char* baErr2Str(int flushoffset) { switch(flushoffset) { case E_NO_ERROR: return "\156\157\040\145\162\162\157\162"; case IOINTF_INVALIDNAME: return "\151\156\166\141\154\151\144\156\141\155\145"; case IOINTF_NOTFOUND: return "\156\157\164\146\157\165\156\144"; case IOINTF_EXIST: return "\145\170\151\163\164"; case IOINTF_ENOENT: return "\145\156\157\145\156\164"; case IOINTF_NOACCESS: return "\156\157\141\143\143\145\163\163"; case IOINTF_NOTEMPTY: return "\156\157\164\145\155\160\164\171"; case IOINTF_IOERROR: return "\151\157\145\162\162\157\162"; case IOINTF_NOSPACE: return "\156\157\163\160\141\143\145"; case IOINTF_MEM: return "\155\145\155"; case IOINTF_LOCKED: return "\154\157\143\153\145\144"; case IOINTF_BUFTOOSMALL: return "\142\165\146\164\157\157\163\155\141\154\154"; case IOINTF_NOIMPLEMENTATION: return "\156\157\151\155\160\154\145\155\145\156\164\141\164\151\157\156"; case IOINTF_NOAESLIB: return "\156\157\141\145\163\154\151\142"; case IOINTF_NOTCOMPRESSED: return "\156\157\164\143\157\155\160\162\145\163\163\145\144"; case IOINTF_ZIPERROR: return "\172\151\160\145\162\162\157\162"; case IOINTF_NOZIPLIB: return "\156\157\172\151\160\154\151\142"; case IOINTF_AES_NO_SUPPORT: return "\141\145\163\156\157\163\165\160\160\157\162\164"; case IOINTF_NO_PASSWORD: return "\156\157\160\141\163\163\167\157\162\144"; case IOINTF_WRONG_PASSWORD: return "\167\162\157\156\147\160\141\163\163\167\157\162\144"; case IOINTF_AES_WRONG_AUTH: return "\141\145\163\167\162\157\156\147\141\165\164\150"; case IOINTF_AES_COMPROMISED: return "\141\145\163\143\157\155\160\162\157\155\151\163\145\144"; case E_INVALID_SOCKET_CON: return "\151\156\166\141\154\151\144\163\157\143\153\145\164\143\157\156"; case E_GETHOSTBYNAME: return "\147\145\164\150\157\163\164\142\171\156\141\155\145"; case E_BIND: return "\142\151\156\144"; case E_SOCKET_CLOSED: return "\163\157\143\153\145\164\143\154\157\163\145\144"; case E_SOCKET_WRITE_FAILED: return "\163\157\143\153\145\164\167\162\151\164\145\146\141\151\154\145\144"; case E_SOCKET_READ_FAILED: return "\163\157\143\153\145\164\162\145\141\144\146\141\151\154\145\144"; case E_TIMEOUT: return "\164\151\155\145\157\165\164"; #ifndef NO_SHARKSSL case SHARKSSL_PEM_KEY_PARSE_ERROR: return "\160\145\155\137\153\145\171\137\160\141\162\163\145\137\145\162\162\157\162"; case SHARKSSL_PEM_KEY_WRONG_IV: return "\160\145\155\137\153\145\171\137\167\162\157\156\147\137\151\166"; case SHARKSSL_PEM_KEY_WRONG_LENGTH: return "\160\145\155\137\153\145\171\137\167\162\157\156\147\137\154\145\156\147\164\150"; case SHARKSSL_PEM_KEY_PASSPHRASE_REQUIRED: return "\160\145\155\137\153\145\171\137\160\141\163\163\160\150\162\141\163\145\137\162\145\161\165\151\162\145\144"; case SHARKSSL_PEM_KEY_UNRECOGNIZED_FORMAT: return "\160\145\155\137\153\145\171\137\165\156\162\145\143\157\147\156\151\172\145\144\137\146\157\162\155\141\164"; case SHARKSSL_PEM_KEY_UNSUPPORTED_FORMAT: return "\160\145\155\137\153\145\171\137\165\156\163\165\160\160\157\162\164\145\144\137\146\157\162\155\141\164"; case SHARKSSL_PEM_KEY_UNSUPPORTED_MODULUS_LENGTH: return "\160\145\155\137\153\145\171\137\165\156\163\165\160\160\157\162\164\145\144\137\155\157\144\165\154\165\163\137\154\145\156\147\164\150"; case SHARKSSL_PEM_KEY_UNSUPPORTED_ENCRYPTION_TYPE: return "\160\145\155\137\153\145\171\137\165\156\163\165\160\160\157\162\164\145\144\137\145\156\143\162\171\160\164\151\157\156\137\164\171\160\145"; case SHARKSSL_PEM_KEY_CERT_MISMATCH: return "\160\145\155\137\153\145\171\137\143\145\162\164\137\155\151\163\155\141\164\143\150"; case SHARKSSL_PEM_CERT_UNRECOGNIZED_FORMAT: return "\160\145\155\137\143\145\162\164\137\165\156\162\145\143\157\147\156\151\172\145\144\137\146\157\162\155\141\164"; case SHARKSSL_PEM_CERT_UNSUPPORTED_TYPE: return "\160\145\155\137\143\145\162\164\137\165\156\163\165\160\160\157\162\164\145\144\137\164\171\160\145"; case SHARKSSL_PEM_ALLOCATION_ERROR: #endif case E_MALLOC: return "\155\141\154\154\157\143"; case E_ALREADY_INSERTED: return "\141\154\162\145\141\144\171\151\156\163\145\162\164\145\144"; case E_TOO_MUCH_DATA: return "\164\157\157\155\165\143\150\144\141\164\141"; case E_PAGE_NOT_FOUND: return "\160\141\147\145\156\157\164\146\157\165\156\144"; case E_IS_COMMITTED: return "\151\163\143\157\155\155\151\164\164\145\144"; case E_INVALID_PARAM: return "\151\156\166\141\154\151\144\160\141\162\141\155"; case E_MIXING_WRITE_SEND: return "\155\151\170\151\156\147\167\162\151\164\145\163\145\156\144"; case E_TOO_MANY_INCLUDES: return "\164\157\157\155\141\156\171\151\156\143\154\165\144\145\163"; case E_TOO_MANY_FORWARDS: return "\164\157\157\155\141\156\171\146\157\162\167\141\162\144\163"; case E_INCLUDE_OP_NOT_VALID: return "\151\156\143\154\165\144\145\157\160\156\157\164\166\141\154\151\144"; case E_CANNOT_RESOLVE: return "\143\141\156\156\157\164\162\145\163\157\154\166\145"; case E_CANNOT_CONNECT: return "\143\141\156\156\157\164\143\157\156\156\145\143\164"; case E_INVALID_URL: return "\151\156\166\141\154\151\144\165\162\154"; case E_INVALID_RESPONSE: return "\151\156\166\141\154\151\144\162\145\163\160\157\156\163\145"; case E_INCORRECT_USE: return "\151\156\143\157\162\162\145\143\164\165\163\145"; case E_TLS_NOT_ENABLED: return "\163\163\154\156\157\164\145\156\141\142\154\145\144"; case E_SHARK_ALERT_RECV: return "\163\163\154\141\154\145\162\164\162\145\143\166"; case E_TLS_CRYPTOERR: return "\163\163\154\143\162\171\160\164\157\145\162\162"; case E_TLS_HANDSHAKE: return "\163\163\154\150\141\156\144\163\150\141\153\145"; case E_NOT_TRUSTED: return "\163\163\154\156\157\164\164\162\165\163\164\145\144"; case E_TLS_CLOSE_NOTIFY: return "\163\163\154\143\154\157\163\145\156\157\164\151\146\171"; case E_PROXY_GENERAL: return "\160\162\170\147\145\156\145\162\141\154"; case E_PROXY_NOT_ALLOWED: return "\160\162\170\156\157\164\141\154\154\157\167\145\144"; case E_PROXY_NETWORK: return "\160\162\170\156\145\164\167\157\162\153"; case E_PROXY_HOST: return "\160\162\170\150\157\163\164"; case E_PROXY_REFUSED: return "\160\162\170\162\145\146\165\163\145\144"; case E_PROXY_TTL: return "\160\162\170\164\164\154"; case E_PROXY_COMMAND_NOT_SUP: return "\160\162\170\143\157\155\155\141\156\144"; case E_PROXY_ADDRESS_NOT_SUP: return "\160\162\170\141\144\144\162\145\163\163"; case E_PROXY_NOT_COMPATIBLE: return "\160\162\170\156\157\164\143\157\155\160\141\164"; case E_PROXY_READY: return "\160\162\170\162\145\141\144\171"; case E_PROXY_UNKNOWN: return "\160\162\170\165\156\153\156\157\167\156"; case E_SYS_SHUTDOWN: return "\163\171\163\163\150\165\164\144\157\167\156"; case ZipErr_Buf: return "\172\151\160\142\165\146"; case ZipErr_Reading: return "\172\151\160\162\145\141\144\151\156\147"; case ZipErr_Spanned: return "\172\151\160\163\160\141\156\156\145\144"; case ZipErr_Compression: return "\172\151\160\143\157\155\160\162\145\163\163\151\157\156"; case ZipErr_Incompatible: return "\172\151\160\151\156\143\157\155\160\141\164\151\142\154\145"; case E_PROXY_AUTH: case 407: return "\160\162\157\170\171\141\165\164\150"; case 401: return "\141\165\164\150"; case -1: return "\146\141\151\154\145\144"; } return "\165\156\153\156\157\167\156"; } int baErr2HttpCode(int flushoffset) { if(flushoffset >= 100 && flushoffset < 600) return flushoffset; switch(flushoffset) { case IOINTF_INVALIDNAME: return 400; case IOINTF_NOTFOUND: return 404; case IOINTF_EXIST: return 405; case IOINTF_ENOENT: return 409; case IOINTF_NOACCESS: return 403; case IOINTF_NOTEMPTY: return 409; case IOINTF_IOERROR: case IOINTF_NOSPACE: return 507; case IOINTF_MEM: return 503; case IOINTF_LOCKED: return 423; case IOINTF_NO_PASSWORD: case IOINTF_WRONG_PASSWORD: return 403; case IOINTF_AES_WRONG_AUTH: case IOINTF_AES_COMPROMISED: case IOINTF_AES_NO_SUPPORT: return 501; } return 500; } #ifndef BA_LIB #define BA_LIB 1 #endif #include "BaTimer.h" #define eventattribute 5 #define fdpicparams(a,b) (a>b?((a-b)>0x7FFFFFFF?0:1):((b-a)>0x7FFFFFFF?1:0)) #define regulatordevice(a,b)((a-b)>0x7FFFFFFF?((a-0x7FFFFFFF)-(b-0x7FFFFFFF)):(a-b)) typedef struct { DoubleLink super; SplayTreeNode stn; BaTimer_CB cb; void* cbData; U32 ticks; size_t lapCounter; } BaTimerNode; #define deviceinitcall(o) ((size_t)SplayTreeNode_getKey(&(o)->stn)) #define freememcallback(o) o->lapCounter = o->ticks >> eventattribute static void pgtablevisit(BaTimerNode* o, BaTimer_CB cb, void* alloccontroller, U32 uart0readl, size_t unknowninterrupt) { DoubleLink_constructor(o); SplayTreeNode_constructor(&o->stn, (SplayTreeKey)unknowninterrupt); o->cb=cb; o->cbData=alloccontroller; o->ticks=uart0readl; freememcallback(o); } static U32 domainalloc(BaTimer* o, U32 pefilesignature) { pefilesignature=pefilesignature/o->ticklen; return pefilesignature ? pefilesignature-1 : 0; } static void gpiodgflags(BaTimer* o, BaTimerNode* tn) { if(tn->lapCounter > 2) tn->lapCounter=2; tn->cb=0; SplayTree_remove(&o->tnTree, &tn->stn); } static void legacyhandle(BaTimer* o, BaTimerNode* tn) { SplayTree_remove(&o->tnTree, &tn->stn); DoubleLink_destructor(tn); AllocatorIntf_free(o->alloc, tn); } static void hammerdevice(BaTimer* o, BaTimerNode* tn) { ThreadMutex_set(o->mutex); if(tn->cb) { if(tn->cb(tn->cbData)) { DoubleList* entryinsert= o->slots+((o->curIndex+tn->ticks)&(BA_TIMER_SLOTS-1)); freememcallback(tn); DoubleList_insertLast(entryinsert,tn); } else legacyhandle(o, tn); } else legacyhandle(o, tn); ThreadMutex_release(o->mutex); } static void backlightregister(BaTimer* o) { BaTimerNode* tn; while( (tn = (BaTimerNode*)DoubleList_removeFirst(&o->readyQ)) != 0) { DoubleList* entryinsert=o->slots+((o->curIndex+tn->ticks+1)&(BA_TIMER_SLOTS-1)); DoubleList_insertLast(entryinsert,tn); o->dataInReadyQ--; } baAssert(o->dataInReadyQ==0); } static void shashfinal(BaTimer* o) { int i; BaTimerNode* tn; while( (tn = (BaTimerNode*)DoubleList_removeFirst(&o->readyQ)) != 0) legacyhandle(o, tn); for(i = 0 ; i < (BA_TIMER_SLOTS-1) ; i++) { DoubleList* dl = o->slots+i; while( (tn = (BaTimerNode*)DoubleList_removeFirst(dl)) != 0) legacyhandle(o, tn); } o->dataInReadyQ=0; } #if BA_TIMER_EXT_TICK static ThreadSemaphore BaTimer_triggerSem; static BaTimer* BaTimer_theOneAndOnly=0; static int BaTimer_waitingForTrigger=FALSE; static void BaTimer_trigger(void) { if(BaTimer_waitingForTrigger) { BaTimer_waitingForTrigger=FALSE; ThreadSemaphore_signal(&BaTimer_triggerSem); } } #endif static void octeonconfig(Thread* fdc37m81xconfig) { BaTimer* o = (BaTimer*)fdc37m81xconfig; U32 rdhwrnoopt=o->ticklen; U32 flashdriver=o->ticklen; U32 cachesysfs = baGetMsClock(); for(;;) { DoubleList* dl; U32 end = baGetMsClock(); flashdriver += regulatordevice(end, cachesysfs); cachesysfs = end; rdhwrnoopt+=o->ticklen; #if BA_TIMER_EXT_TICK if( ! fdpicparams(flashdriver,rdhwrnoopt) ) { BaTimer_waitingForTrigger=TRUE; ThreadSemaphore_wait(&BaTimer_triggerSem); } #else if(fdpicparams(flashdriver,rdhwrnoopt)) { U32 resetcounter = regulatordevice(flashdriver,rdhwrnoopt); if(resetcounter < o->ticklen) Thread_sleep(o->ticklen - resetcounter); } else Thread_sleep(o->ticklen); #endif if(o->dataInReadyQ) { ThreadMutex_set(o->mutex); if(o->dataInReadyQ > 0) backlightregister(o); else { shashfinal(o); ThreadMutex_release(o->mutex); return; } ThreadMutex_release(o->mutex); } dl=o->slots+o->curIndex; if(++o->curIndex == BA_TIMER_SLOTS) o->curIndex = 0; if( ! DoubleList_isEmpty(dl) ) { DoubleListEnumerator instructioncounter; BaTimerNode* tn; DoubleListEnumerator_constructor(&instructioncounter, dl); tn = (BaTimerNode*)DoubleListEnumerator_getElement(&instructioncounter); while(tn) { if (tn->lapCounter != 0) { tn->lapCounter--; tn = (BaTimerNode*)DoubleListEnumerator_nextElement(&instructioncounter); } else { BaTimerNode* runT = tn; tn = (BaTimerNode*)DoubleListEnumerator_removeElement(&instructioncounter); hammerdevice(o, runT); } } } } } static int debugdebugfs(SplayTreeNode* n, SplayTreeKey k) { if( (size_t)n->key < (size_t)k ) return -1; return (size_t)n->key > (size_t)k ? 1 : 0; } static BaTimerNode* BaTimer_findNode(BaTimer* o, size_t unknowninterrupt) { SplayTreeNode* stn = SplayTree_find(&o->tnTree, (SplayTreeKey)unknowninterrupt); return stn ? (BaTimerNode*)((U8*)stn-offsetof(BaTimerNode,stn)) : 0; } static size_t currenttimer(BaTimer* o, BaTimer_CB cb, void* alloccontroller, U32 pefilesignature, size_t unknowninterrupt) { if(o->dataInReadyQ >= 0) { size_t icachealiases = sizeof(BaTimerNode); BaTimerNode* tn = (BaTimerNode*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(tn) { pgtablevisit( tn,cb,alloccontroller,domainalloc(o,pefilesignature),unknowninterrupt); SplayTree_insert(&o->tnTree, &tn->stn); DoubleList_insertLast(&o->readyQ, tn); o->dataInReadyQ++; return unknowninterrupt; } } return 0; } static size_t rndCount; BA_API size_t BaTimer_set(BaTimer* o, BaTimer_CB cb, void* alloccontroller, U32 pefilesignature) { size_t unknowninterrupt = (baGetMsClock() * 123456789) + (++rndCount); BaBool timerdevice = ThreadMutex_isOwner(o->mutex) ? FALSE : TRUE; if(timerdevice) ThreadMutex_set(o->mutex); while(unknowninterrupt == 0 || SplayTree_find(&o->tnTree, (SplayTreeKey)unknowninterrupt)) unknowninterrupt = unknowninterrupt * 2 + (++rndCount); unknowninterrupt = currenttimer(o, cb, alloccontroller, pefilesignature, unknowninterrupt); if(timerdevice) ThreadMutex_release(o->mutex); return unknowninterrupt; } BA_API int BaTimer_reset(BaTimer* o, size_t unknowninterrupt, U32 pefilesignature) { int handlersetup; BaTimerNode* tn; BaBool timerdevice = ThreadMutex_isOwner(o->mutex) ? FALSE : TRUE; if(timerdevice) ThreadMutex_set(o->mutex); tn = BaTimer_findNode(o, unknowninterrupt); if(tn) { BaTimer_CB cb = tn->cb; void* alloccontroller = tn->cbData; gpiodgflags(o, tn); handlersetup = currenttimer(o, cb, alloccontroller, pefilesignature, unknowninterrupt) ? 0 : -2; } else handlersetup = -1; if(timerdevice) ThreadMutex_release(o->mutex); return handlersetup; } BA_API int BaTimer_cancel(BaTimer* o, size_t unknowninterrupt) { int handlersetup; BaTimerNode* tn; BaBool timerdevice = ThreadMutex_isOwner(o->mutex) ? FALSE : TRUE; if(timerdevice) ThreadMutex_set(o->mutex); tn = BaTimer_findNode(o, unknowninterrupt); if(tn) { gpiodgflags(o,tn); handlersetup=0; } else handlersetup = -1; if(timerdevice) ThreadMutex_release(o->mutex); return handlersetup; } BA_API void BaTimer_constructor(BaTimer* o, ThreadMutex* slc90e66bridge,int stage2unmap, U32 gpio2direction, ThreadPriority gpio1resources, AllocatorIntf* unmapaliases) { int i; #if BA_TIMER_EXT_TICK baAssert( ! BaTimer_theOneAndOnly ); BaTimer_theOneAndOnly=o; ThreadSemaphore_constructor(&BaTimer_triggerSem); BaTimer_installTrigger(BaTimer_trigger,gpio2direction); #endif Thread_constructor((Thread*)o, octeonconfig, gpio1resources, stage2unmap); for(i = 0; i < BA_TIMER_SLOTS; i++) DoubleList_constructor(o->slots+i); SplayTree_constructor(&o->tnTree, debugdebugfs); DoubleList_constructor(&o->readyQ); o->dataInReadyQ=0; o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); o->ticklen=gpio2direction; o->mutex=slc90e66bridge; o->curIndex=0; Thread_start((Thread*)o); } BA_API void BaTimer_destructor(BaTimer* o) { int standardresources=ThreadMutex_isOwner(o->mutex); o->dataInReadyQ=-1; if(standardresources) ThreadMutex_release(o->mutex); while(o->dataInReadyQ==-1) { Thread_sleep(o->ticklen*2); } if(standardresources) ThreadMutex_set(o->mutex); Thread_destructor((Thread*)o); #if BA_TIMER_EXT_TICK BaTimer_theOneAndOnly=0; #endif } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include /* SHRT_MAX */ static int prefetchablememory(struct BufPrint* bp, int stateparam) { bp->cursor=0; baAssert(stateparam == 0); return stateparam ? -1 : 0; } BA_API int basnprintf(char* buf, int len, const char* fmt, ...) { int propertycount; va_list demuxregids; BufPrint bufPrint; BufPrint_constructor2(&bufPrint, buf, (len -1), 0, prefetchablememory); va_start(demuxregids, fmt); propertycount = BufPrint_vprintf(&bufPrint, fmt, demuxregids); if( propertycount >= 0 ) { buf[bufPrint.cursor] = 0; propertycount = bufPrint.cursor; } va_end(demuxregids); return propertycount; } BA_API int basprintf(char* buf, const char* fmt, ...) { int propertycount; va_list demuxregids; BufPrint bufPrint; BufPrint_constructor2( &bufPrint, buf, (int)((unsigned int)(~0)/2u), 0, prefetchablememory); bufPrint.cursor = 0; va_start(demuxregids, fmt); propertycount = BufPrint_vprintf(&bufPrint, fmt, demuxregids); if( propertycount >= 0 ) { buf[bufPrint.cursor] = 0; propertycount = bufPrint.cursor; } va_end(demuxregids); return propertycount; } #define XDBL_DIG 15 #define FLAG_LEFTADJUST 0x0001 #define FLAG_SIGN 0x0002 #define FLAG_ZEROPAD 0x0004 #define FLAG_ALTERNATE 0x0008 #define FLAG_SPACE 0x0010 #define FLAG_SHORT 0x0020 #define FLAG_LONG 0x0040 #define FLAG_LONG_LONG 0x0080 #define FLAG_LONGDOUBLE 0x0100 #define FLAG_POINTER 0x0200 #define MAXWIDTH ((SHRT_MAX - 9) / 10) #ifdef B_BIG_ENDIAN #define resultsuccess(puVal) \ ( \ sizeof((*puVal).dVal) == sizeof((*puVal).aul) \ ? \ (((*puVal).aul[0] & 0x7ff00000UL) == 0x7ff00000UL) \ ? \ (((*puVal).aul[0] & 0x000fffffUL) || (*puVal).aul[1]) \ ? \ ((*puVal).aul[0] & 0x80000000UL) \ ? 1 \ : 2 \ : \ ((*puVal).aul[0] & 0x80000000UL) \ ? 3 \ : 4 \ : 0 \ : 0 \ ) #elif defined(B_LITTLE_ENDIAN) #define resultsuccess(puVal) \ ( \ sizeof((*puVal).dVal) == sizeof((*puVal).aul) \ ? \ (((*puVal).aul[1] & 0x7ff00000UL) == 0x7ff00000UL) \ ? \ (((*puVal).aul[1] & 0x000fffffUL) || (*puVal).aul[0]) \ ? \ ((*puVal).aul[1] & 0x80000000UL) \ ? 1 \ : 2 \ : \ ((*puVal).aul[1] & 0x80000000UL) \ ? 3 \ : 4 \ : 0 \ : 0 \ ) #else #error ENDIAN_NEEDED_Define_one_of_B_BIG_ENDIAN_or_B_LITTLE_ENDIAN #endif #ifndef NO_DOUBLE union UIEEE_754 { unsigned int aul[2]; double dVal; }; #endif BA_API int BufPrint_putc(BufPrint* o, int c) { BufPrint_putcMacro(o, (char)c); return 0; } static int BufPrint_fmtLongLong(char** ptregdefines, int* len, U64 val64, unsigned memoryavailable, int fmtAsSigned) { int collectlogout; if (fmtAsSigned && (S64)val64 < 0) { val64 = -(S64)val64; collectlogout = TRUE; } else collectlogout = FALSE; do { char r = (U8)(val64 % memoryavailable); val64 /= memoryavailable; *--(*ptregdefines) = ('\060' + r); (*len)++; } while (val64); return collectlogout; } BA_API void BufPrint_constructor(BufPrint* o, void* suspendvalid, BufPrint_Flush conditionvalid32) { memset(o, 0, sizeof(BufPrint)); o->userData = suspendvalid; o->flushCB = conditionvalid32 ? conditionvalid32 : prefetchablememory; } BA_API void BufPrint_constructor2( BufPrint* o, char* buf,int icachealiases,void* suspendvalid,BufPrint_Flush conditionvalid32) { BufPrint_constructor(o, suspendvalid,conditionvalid32); o->buf=buf; o->bufSize=icachealiases; } #define BufPrint_getSizeLeft(o) (o.bufSize - o.cursor) #define BufPrint_padChar(o, c, debugstart) do{ \ int i; \ for(i=0; i< (debugstart) ; i++) \ BufPrint_putcMacro(o, c); \ } while(0) BA_API int BufPrint_write(BufPrint* o, const void* buf, int len) { int handlersetup=0; if(!o) return -1; if(len < 0) len = (int)strlen((const char*)buf); if(len) { if((o->cursor + len) > o->bufSize && o->cursor) if( (handlersetup=o->flushCB(o,o->cursor+len+1-o->bufSize))!= 0) return handlersetup; if((o->cursor + len) <= o->bufSize) { memcpy(o->buf + o->cursor, buf, len); o->cursor += len; } else { const U8* ptr = (const U8*)buf; while(len > o->bufSize) { o->cursor = o->bufSize; memcpy(o->buf, ptr, o->bufSize); len -= o->bufSize; ptr += o->bufSize; if( (handlersetup=o->flushCB(o, o->cursor+len-o->bufSize))!=0) return handlersetup; } o->cursor = len; memcpy(o->buf, ptr, len); } baAssert(o->cursor <= o->bufSize); } return handlersetup; } BA_API int BufPrint_b64Encode(BufPrint* o, const void* panicblock, S32 allockuser) { static const char needschecking[] = { "\101\102\103\104\105\106\107\110\111\112\113\114\115\116\117\120\121\122\123\124\125\126\127\130\131\132\141\142\143\144\145\146\147\150\151\152\153\154\155\156\157\160\161\162\163\164\165\166\167\170\171\172\060\061\062\063\064\065\066\067\070\071\053\057" }; const U8* src = (const U8*)panicblock; while( allockuser >= 3 ) { if(BufPrint_putc(o,needschecking[*src>>2]) < 0 || BufPrint_putc(o,needschecking[(*src&0x03)<<4 | src[1]>>4]) < 0 || BufPrint_putc(o,needschecking[(src[1]&0x0F)<<2 | src[2]>>6]) < 0 || BufPrint_putc(o, needschecking[src[2] & 0x3F]) < 0) { return -1; } src += 3; allockuser -= 3; } switch(allockuser) { case 2: if(BufPrint_putc(o, needschecking[src[0]>>2]) < 0 || BufPrint_putc(o, needschecking[(src[0] & 0x03)<<4 | src[1]>>4]) < 0 || BufPrint_putc(o, needschecking[(src[1] & 0x0F)<<2]) < 0 || BufPrint_putc(o, (U8)'\075') < 0) { return -1; } break; case 1: if(BufPrint_putc(o, needschecking[src[0]>>2]) < 0 || BufPrint_putc(o, needschecking[(src[0] & 0x03)<<4]) < 0 || BufPrint_write(o,"\075\075",2) < 0) { return -1; } break; default: baAssert(allockuser == 0); } return 0; } BA_API int BufPrint_b64urlEncode(BufPrint* o, const void* panicblock, S32 allockuser, BaBool seepromprobe) { static const char needschecking[] = { "\101\102\103\104\105\106\107\110\111\112\113\114\115\116\117\120\121\122\123\124\125\126\127\130\131\132\141\142\143\144\145\146\147\150\151\152\153\154\155\156\157\160\161\162\163\164\165\166\167\170\171\172\060\061\062\063\064\065\066\067\070\071\055\137" }; const U8* src = (const U8*)panicblock; while( allockuser >= 3 ) { if(BufPrint_putc(o,needschecking[*src>>2]) < 0 || BufPrint_putc(o,needschecking[(*src&0x03)<<4 | src[1]>>4]) < 0 || BufPrint_putc(o,needschecking[(src[1]&0x0F)<<2 | src[2]>>6]) < 0 || BufPrint_putc(o, needschecking[src[2] & 0x3F]) < 0) { return -1; } src += 3; allockuser -= 3; } switch(allockuser) { case 2: if(BufPrint_putc(o, needschecking[src[0]>>2]) < 0 || BufPrint_putc(o, needschecking[(src[0] & 0x03)<<4 | src[1]>>4]) < 0 || BufPrint_putc(o, needschecking[(src[1] & 0x0F)<<2]) < 0 || (seepromprobe ? BufPrint_putc(o, (U8)'\075') : 0) < 0) { return -1; } break; case 1: if(BufPrint_putc(o, needschecking[src[0]>>2]) < 0 || BufPrint_putc(o, needschecking[(src[0] & 0x03)<<4]) < 0 || (seepromprobe ? BufPrint_write(o,"\075\075",2) : 0) < 0) { return -1; } break; default: baAssert(allockuser == 0); } return 0; } BA_API int BufPrint_jsonString(BufPrint* o, const char* str) { BufPrint_putcMacro(o,'\042'); while(*str) { if(*str < '\040' || *str == '\042') { if(*str > 0) { switch(*str) { case '\010': BufPrint_write(o, "\134\142",2); break; case '\011': BufPrint_write(o, "\134\164",2); break; case '\012': BufPrint_write(o, "\134\156",2); break; case '\013': BufPrint_write(o, "\134\166",2); break; case '\014': BufPrint_write(o, "\134\146",2); break; case '\015': BufPrint_write(o, "\134\162",2); break; case '\042': BufPrint_write(o, "\134\042",2);break; case '\047': BufPrint_write(o, "\134\047",2); break; default: BufPrint_printf(o,"\134\165\045\060\064\170",(unsigned)*str); } } else { unsigned char c = str[0]; unsigned long uc = 0; if (c < 0xc0) uc = c; else if (c < 0xe0) { if ((str[1] & 0xc0) == 0x80) { uc = ((c & 0x1f) << 6) | (str[1] & 0x3f); ++str; } else uc = c; } else if (c < 0xf0) { if ((str[1] & 0xc0) == 0x80 && (str[2] & 0xc0) == 0x80) { uc = ((c & 0x0f) << 12) | ((str[1] & 0x3f) << 6) | (str[2] & 0x3f); str += 2; } else uc = c; } else if (c < 0xf8) { if ((str[1] & 0xc0) == 0x80 && (str[2] & 0xc0) == 0x80 && (str[3] & 0xc0) == 0x80) { uc = ((c & 0x03) << 18) | ((str[1] & 0x3f) << 12) | ((str[2] & 0x3f) << 6) | (str[4] & 0x3f); str += 3; } else uc = c; } else if (c < 0xfc) { if ((str[1] & 0xc0) == 0x80 && (str[2] & 0xc0) == 0x80 && (str[3] & 0xc0) == 0x80 && (str[4] & 0xc0) == 0x80) { uc = ((c & 0x01) << 24) | ((str[1] & 0x3f) << 18) | ((str[2] & 0x3f) << 12) | ((str[4] & 0x3f) << 6) | (str[5] & 0x3f); str += 4; } else uc = c; } else ++str; if (uc < 0x10000) BufPrint_printf(o,"\134\165\045\060\064\170", uc); else { uc -= 0x10000; BufPrint_printf(o,"\134\165\045\060\064\170", 0xdc00 | ((uc >> 10) & 0x3ff)); BufPrint_printf(o,"\134\165\045\060\064\170", 0xd800 | (uc & 0x3ff)); } } } else if(*str == '\134') BufPrint_write(o,"\134\134",2); else if(*str == '\057') BufPrint_write(o, "\134\057",2); else if(*str == 0x7f) BufPrint_printf(o,"\134\165\045\060\064\170",(unsigned)*str); else BufPrint_putcMacro(o, *str); str++; } BufPrint_putcMacro(o,'\042'); return 0; } BA_API int BufPrint_vprintf(BufPrint* o, const char* fmt, va_list breakpointthread) { int handlersetup; int reassignvector = 0; if(!o) return -1; if( ! o->buf ) { if(o->flushCB(o, 0)) return -1; } while (*fmt) { if(*fmt != '\045') { const char* cachesysfs = fmt; while (*fmt && *fmt != '\045') ++fmt; if( (handlersetup=BufPrint_write(o, cachesysfs, (int)(fmt - cachesysfs))) != 0) return handlersetup; continue; } else { const char *ptr; const char *cpuidleprobe = ""; unsigned int driverchipcommon; int width, precision, instructionemulation, prefixLen, noOfLeadingZeros; int doublefnmul; char buf[50]; instructionemulation = prefixLen = noOfLeadingZeros = 0; driverchipcommon = 0; ++fmt; while ((*fmt == '\055') || (*fmt == '\053') || (*fmt == '\060') || (*fmt == '\043') || (*fmt == '\040')) { switch (*fmt++) { case '\055': driverchipcommon |= FLAG_LEFTADJUST; break; case '\053': driverchipcommon |= FLAG_SIGN; break; case '\060': driverchipcommon |= FLAG_ZEROPAD; break; case '\043': driverchipcommon |= FLAG_ALTERNATE; break; case '\040': driverchipcommon |= FLAG_SPACE; break; } } if (*fmt == '\052') { ++fmt; width = va_arg(breakpointthread, int); if (width < 0) { width = -width; driverchipcommon |= FLAG_LEFTADJUST; } } else { for (width = 0 ; (*fmt >= '\060') && (*fmt <= '\071') ; fmt++) { if (width < MAXWIDTH) width = width * 10 + (*fmt - '\060'); } } if (*fmt == '\056') { if (*++fmt == '\052') { ++fmt; precision = va_arg(breakpointthread, int); if (precision < 0) precision = 0; } else { for (precision = 0 ; (*fmt >= '\060') && (*fmt <= '\071') ; fmt++) { if (precision < MAXWIDTH) precision = precision * 10 + (*fmt - '\060'); } } } else precision = -1; switch (*fmt) { case '\150': driverchipcommon |= FLAG_SHORT; ++fmt; break; case '\154': if(*++fmt == '\154') { driverchipcommon |= FLAG_LONG_LONG; ++fmt; } else driverchipcommon |= FLAG_LONG; break; case '\114': driverchipcommon |= FLAG_LONGDOUBLE; ++fmt; break; } switch (*fmt) { case '\160': driverchipcommon |= FLAG_POINTER; case '\170': case '\130': case '\157': case '\165': case '\144': case '\151': { size_t val=0; U64 persistentclock64=0; char *ptregdefines = (char *)&buf[(sizeof buf) - 1]; *ptregdefines = 0; if (driverchipcommon & FLAG_LONG_LONG) { persistentclock64 = va_arg(breakpointthread, U64); if (precision == 0 && persistentclock64 == 0) { fmt++; continue; } } else { if (driverchipcommon & FLAG_POINTER) val = (size_t)va_arg(breakpointthread, void *); else if (driverchipcommon & FLAG_SHORT) val = (unsigned long)va_arg(breakpointthread, int); else if (driverchipcommon & FLAG_LONG) val = (unsigned long)va_arg(breakpointthread, long); else val = (unsigned long)va_arg(breakpointthread, int); if (precision == 0 && val == 0) { fmt++; continue; } } if (*fmt == '\144' || *fmt == '\151') { if((driverchipcommon & FLAG_LONG_LONG) && BufPrint_fmtLongLong(&ptregdefines,&instructionemulation,persistentclock64,10,TRUE)) { cpuidleprobe = "\055"; prefixLen = 1; } else if ( ! (driverchipcommon & FLAG_LONG_LONG) && (long)val < 0) { val = -(long)val; cpuidleprobe = "\055"; prefixLen = 1; } else if (driverchipcommon & FLAG_SIGN) { cpuidleprobe = "\053"; prefixLen = 1; } else if (driverchipcommon & FLAG_SPACE) { cpuidleprobe = "\040"; prefixLen = 1; } if ( ! (driverchipcommon & FLAG_LONG_LONG) ) { do { int r = val % 10U; val /= 10U; *--ptregdefines = (char)('\060' + r); instructionemulation++; } while (val); } } else { const char *deviceregister = (*fmt == '\130') ? "\060\061\062\063\064\065\066\067\070\071\101\102\103\104\105\106" : "\060\061\062\063\064\065\066\067\070\071\141\142\143\144\145\146"; if (driverchipcommon & FLAG_LONG_LONG) { if(*fmt == '\170' || *fmt == '\130') { unsigned long resetsystem = (unsigned long)((U32)(0xFFFFFFFF & ((persistentclock64) >> 32) )); val = (unsigned long)((U32)(persistentclock64)); if(resetsystem) { instructionemulation+=8; for(handlersetup=0; handlersetup < 8 ; handlersetup++) { *--ptregdefines = deviceregister[val & 0xF]; if(val) val >>= 4; } while(resetsystem) { *--ptregdefines = deviceregister[resetsystem & 0xF]; resetsystem >>= 4; instructionemulation++; } } else { do { *--ptregdefines = deviceregister[val & 0xF]; val >>= 4; instructionemulation++; } while(val); } } else { BufPrint_fmtLongLong( &ptregdefines,&instructionemulation,persistentclock64, (*fmt == '\165') ? 10U : (*fmt == '\157') ? 8U : 16U, FALSE); } } else { const unsigned memoryavailable = (*fmt == '\165') ? 10U : (*fmt == '\157') ? 8U : 16U; do { *--ptregdefines = deviceregister[val % memoryavailable]; val /= memoryavailable; instructionemulation++; } while (val); } if ((driverchipcommon & FLAG_ALTERNATE) && *ptregdefines != '\060') { if (*fmt == '\157') { instructionemulation++; *--ptregdefines = '\060'; } else if (*fmt == '\130') { cpuidleprobe = "\060\130"; prefixLen = 2; } else { cpuidleprobe = "\060\170"; prefixLen = 2; } } } ptr = ptregdefines; } noOfLeadingZeros = instructionemulation < precision ? precision - instructionemulation : 0; if (precision < 0 && ((driverchipcommon & (FLAG_ZEROPAD | FLAG_LEFTADJUST)) == FLAG_ZEROPAD)) { doublefnmul = width - prefixLen - noOfLeadingZeros - instructionemulation; if (doublefnmul > 0) noOfLeadingZeros += doublefnmul; } break; case '\146': case '\145': case '\105': case '\147': case '\107': #ifdef NO_DOUBLE ptr = "\050\156\157\040\146\154\157\141\164\040\163\165\160\160\157\162\164\051"; goto L_s; #else { double videoprobe = (driverchipcommon & FLAG_LONGDOUBLE) ? (double)va_arg(breakpointthread, long double) : va_arg(breakpointthread, double); int commonswizzle; int decZeros, expZeros, decPoint, fracDigs; int trailZeros, expLen, exp, savedPrec; char *fracStr, *expStr; char suspendalloc = *fmt; static const char *flash0resources[] = { "\055\116\141\116", "\116\141\116", "\055\111\156\146", "\111\156\146" }; decZeros = expZeros = fracDigs = 0; trailZeros = expLen = exp = 0; savedPrec = precision; expStr = (char *)""; doublefnmul = resultsuccess((union UIEEE_754 *)&videoprobe); if (doublefnmul) { ptr = flash0resources[doublefnmul - 1]; goto L_s; } if (videoprobe < 0.0) { videoprobe = -videoprobe; cpuidleprobe = "\055"; prefixLen = 1; } else if (driverchipcommon & FLAG_SIGN) { cpuidleprobe = "\053"; prefixLen = 1; } else if (driverchipcommon & FLAG_SPACE) { cpuidleprobe = "\040"; prefixLen = 1; } if (videoprobe >= 10.0) { if (videoprobe >= 1e16) { while (videoprobe >= 1e64) { videoprobe /= 1e64; exp += 64; } while (videoprobe >= 1e32) { videoprobe /= 1e32; exp += 32; } while (videoprobe >= 1e16) { videoprobe /= 1e16; exp += 16; } } while (videoprobe >= 1e08) { videoprobe /= 1e08; exp += 8; } while (videoprobe >= 1e04) { videoprobe /= 1e04; exp += 4; } while (videoprobe >= 1e01) { videoprobe /= 1e01; exp += 1; } } else if (videoprobe < 1.0 && videoprobe > 0.0) { if (videoprobe < 1e-15) { while (videoprobe < 1e-63) { videoprobe *= 1e64; exp -= 64; } while (videoprobe < 1e-31) { videoprobe *= 1e32; exp -= 32; } while (videoprobe < 1e-15) { videoprobe *= 1e16; exp -= 16; } } while (videoprobe < 1e-7) { videoprobe *= 1e8; exp -= 8; } while (videoprobe < 1e-3) { videoprobe *= 1e4; exp -= 4; } while (videoprobe < 1e-0) { videoprobe *= 1e1; exp -= 1; } if (videoprobe >= 10.0) { videoprobe /= 1e1; exp += 1; } } if (precision < 0 ) precision = savedPrec = 6; if (suspendalloc == '\147' || suspendalloc == '\107') { if (exp < -4 || exp >= precision) { suspendalloc = (char)(suspendalloc == '\147' ? '\145' : '\105'); --precision; } else { suspendalloc = '\146'; if (precision == 0) precision = 1; if (exp >= 0) { precision -= exp + 1; } else { precision += -exp - 1; } } if (precision < 0) precision = 0; } ptr = (char *)buf; commonswizzle = 0; if (suspendalloc == '\145' || suspendalloc == '\105') { doublefnmul = (int)videoprobe; buf[commonswizzle++] = (unsigned char)(doublefnmul + '\060'); videoprobe -= doublefnmul; videoprobe *= 10.; } else if (exp < 0) { buf[commonswizzle++] = '\060'; } else { if (exp > XDBL_DIG + 1) { expZeros = exp - (XDBL_DIG + 1); exp = XDBL_DIG + 1; } do { doublefnmul = (int)videoprobe; buf[commonswizzle++] = (unsigned char)(doublefnmul + '\060'); videoprobe -= doublefnmul; videoprobe *= 10.; } while (exp--); } fracStr = (char *)&buf[commonswizzle]; if (suspendalloc == '\146') { while (decZeros < precision && exp < -1) { ++decZeros; ++exp; } } if (!expZeros) { while (fracDigs + decZeros < precision && commonswizzle + fracDigs < XDBL_DIG + 1) { doublefnmul = (int)videoprobe; fracStr[fracDigs++] = (char)(doublefnmul + '\060'); videoprobe -= doublefnmul; videoprobe *= 10.; if (suspendalloc == '\146') --exp; } if (!fracDigs && decZeros) { fracStr[fracDigs++] = (char)'\060'; --decZeros; --exp; } if (videoprobe >= 5.0 && (fracDigs || !precision)) { doublefnmul = commonswizzle + fracDigs - 1; while (buf[doublefnmul] == '\071' && doublefnmul >= 0) buf[doublefnmul--] = '\060'; if (doublefnmul == 0 && decZeros) { for (doublefnmul = commonswizzle + fracDigs - 1 ; doublefnmul > 0 ; doublefnmul--) { buf[doublefnmul] = buf[doublefnmul - 1]; } buf[1]++; decZeros--; } else if (doublefnmul >= 0) { if (suspendalloc == '\146') { if (precision + 1 + exp >= 0) { buf[doublefnmul]++; } } else if (precision == 0 || fracDigs == precision) { buf[doublefnmul]++; } } else { buf[0] = '\061'; buf[commonswizzle + fracDigs] = '\060'; if (suspendalloc == '\146') { if (commonswizzle >= savedPrec && (*fmt == '\147' || *fmt == '\107')) { suspendalloc = (char)(*fmt == '\147' ? '\145' : '\105'); exp = commonswizzle; commonswizzle = 1; } else commonswizzle++; } else exp++; } } } if (*fmt == '\147' || *fmt == '\107') { if (driverchipcommon & FLAG_ALTERNATE) { decPoint = 1; } else { doublefnmul = commonswizzle + fracDigs - 1; while (buf[doublefnmul--] == '\060' && fracDigs > 0) { fracDigs--; } if (!fracDigs) decZeros = 0; trailZeros = 0; decPoint = fracDigs ? 1 : 0; } if (exp == 0) goto SkipExp; } else { trailZeros = precision - fracDigs - decZeros; if (trailZeros < 0) trailZeros = 0; decPoint = precision || (driverchipcommon & FLAG_ALTERNATE) ? 1 : 0; } if (suspendalloc == '\145' || suspendalloc == '\105') { expStr = &fracStr[fracDigs]; expStr[expLen++] = suspendalloc; expStr[expLen++] = (char)((exp < 0) ? (exp = -exp), '\055':'\053'); if (exp >= 100) { expStr[expLen++] = (char)(exp / 100 + '\060'); exp %= 100; } expStr[expLen++] = (char)(exp / 10 + '\060'); expStr[expLen++] = (char)(exp % 10 + '\060'); } SkipExp: if ((driverchipcommon & FLAG_ZEROPAD) && !(driverchipcommon & FLAG_LEFTADJUST) ) { noOfLeadingZeros = width - (prefixLen + commonswizzle + expZeros + decPoint + decZeros + fracDigs + trailZeros + expLen); if (noOfLeadingZeros < 0) noOfLeadingZeros = 0; } else noOfLeadingZeros = 0; width -= prefixLen + noOfLeadingZeros + commonswizzle + expZeros + decPoint + decZeros + fracDigs + trailZeros + expLen; if ( !(driverchipcommon & FLAG_LEFTADJUST)) BufPrint_padChar(o, '\040', width); BufPrint_write(o, cpuidleprobe, prefixLen); BufPrint_padChar(o, '\060', noOfLeadingZeros); BufPrint_write(o, ptr, commonswizzle); BufPrint_padChar(o, '\060', expZeros); BufPrint_write(o, "\056", decPoint); BufPrint_padChar(o, '\060', decZeros); BufPrint_write(o, fracStr, fracDigs); BufPrint_padChar(o, '\060', trailZeros); if( (handlersetup=BufPrint_write(o, expStr, expLen)) != 0) return handlersetup; if (driverchipcommon & FLAG_LEFTADJUST) BufPrint_padChar(o, '\040', width); ++fmt; continue; } #endif case '\143': buf[0] = (unsigned char)va_arg(breakpointthread, int); ptr = buf; instructionemulation = 1; break; case '\152': case '\163': ptr = va_arg(breakpointthread, char *); if (ptr == NULL) ptr = "\050\156\165\154\154\051"; L_s: instructionemulation = 0; while (ptr[instructionemulation] != '\000') instructionemulation++; if (precision >= 0 && precision < instructionemulation) instructionemulation = precision; break; case '\045': ptr = "\045"; instructionemulation = 1; break; case '\156': if (driverchipcommon & FLAG_SHORT) *va_arg(breakpointthread, S16 *) = (S16)reassignvector; else if (driverchipcommon & FLAG_LONG) *va_arg(breakpointthread, long *) = (long)reassignvector; else *va_arg(breakpointthread, int *) = (int)reassignvector; fmt++; continue; default: fmt++; continue; } width -= prefixLen + noOfLeadingZeros + instructionemulation; if( !(driverchipcommon & FLAG_LEFTADJUST)) BufPrint_padChar(o, '\040', width); if( (handlersetup=BufPrint_write(o, cpuidleprobe, prefixLen)) !=0 ) return handlersetup; BufPrint_padChar(o, '\060', noOfLeadingZeros); if(*fmt++ == '\152') { BufPrint_jsonString(o, ptr); } else { if( (handlersetup=BufPrint_write(o, ptr, instructionemulation)) !=0 ) return handlersetup; } if (driverchipcommon & FLAG_LEFTADJUST) BufPrint_padChar(o, '\040', width); } } return reassignvector; } BA_API int BufPrint_printf(BufPrint* o, const char* fmt, ...) { int propertycount; va_list demuxregids; va_start(demuxregids, fmt); propertycount = BufPrint_vprintf(o, fmt, demuxregids); va_end(demuxregids); return propertycount; } BA_API int BufPrint_flush(BufPrint* o) { if(!o) return -1; if(o->cursor) { int rsp = o->flushCB(o, 0); o->cursor=0; return rsp; } return 0; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #ifdef NO_ZLIB static const char noZipSupport[] = { "\074\150\061\076\074\141\040\150\162\145\146\075\042\150\164\164\160\072\057\057\167\167\167\056\162\145\141\154\164\151\155\145\154\157\147\151\143\056\143\157\155\057\116\157\132\151\160\056\150\164\155\154\042\076\116\157\040\132\111\120\074\057\141\076\074\057\150\061\076" }; #else #include static U32 wakeupnolock(CspReader* alloccontroller, U32 idmapstart, HttpResponse* doublefsqrt) { U8* buf = (U8*)HttpResponse_getBuf(doublefsqrt); U32 len = HttpResponse_getBufSize(doublefsqrt); if(len > 200) len = 200; for(;;) { U8* ptr = buf; if(CspReader_read(alloccontroller, buf, idmapstart, len, FALSE)) return 0; while(*ptr != 0 && len !=0) { len--; ptr++; idmapstart++; } if(*ptr == 0) return idmapstart+1; } } static U32 bootmemremove(CspReader* alloccontroller, HttpResponse* doublefsqrt, U32 idmapstart) { GzipHeader stage2adjust; U16 removememory; baAssert(sizeof(GzipHeader) == 10); if(CspReader_read(alloccontroller, &stage2adjust, idmapstart, sizeof(GzipHeader), TRUE)) return 0; idmapstart += sizeof(GzipHeader); if(stage2adjust.id1 != 39 && stage2adjust.id2 != 139) { HttpResponse_printf(doublefsqrt, "\116\157\164\040\141\040\147\172\151\160\040\146\151\154\145"); return 0; } if(stage2adjust.compressionMethod != 8) { HttpResponse_printf(doublefsqrt, "\125\156\153\156\157\167\156\040\143\157\155\160\162\145\163\163\151\157\156\040\155\145\164\150\157\144"); return 0; } if(stage2adjust.flags & FLG_FEXTRA) { if(CspReader_read(alloccontroller, &removememory, idmapstart, sizeof(removememory), FALSE)) return 0; #ifdef B_BIG_ENDIAN removememory = ((((removememory) << 8) & 0xff00) | (((removememory) >> 8) & 0x00ff)); #endif idmapstart += (removememory + 2); } if(stage2adjust.flags & FLG_FNAME) { if((idmapstart = wakeupnolock(alloccontroller, idmapstart, doublefsqrt)) == 0) return 0; } if(stage2adjust.flags & FLG_FCOMMENT) { if((idmapstart = wakeupnolock(alloccontroller, idmapstart, doublefsqrt)) == 0) return 0; } if(stage2adjust.flags & FLG_FHCRC) idmapstart += 2; return idmapstart; } static int cmdlinesetup(z_streamp z, HttpResponse* doublefsqrt) { int serial8250device; while(z->avail_in != 0) { serial8250device = inflate(z, Z_NO_FLUSH); if(serial8250device != Z_OK || z->avail_out < 50) { U32 notifierretry; if(serial8250device != Z_OK && serial8250device != Z_STREAM_END) return -6; notifierretry = HttpResponse_getRemBufSize(doublefsqrt) - z->avail_out; if(HttpResponse_dataAdded(doublefsqrt, notifierretry)) return -1; if(HttpResponse_getRemBufSize(doublefsqrt) < 50) { if(HttpResponse_flush(doublefsqrt)) return -1; } z->next_out = (U8*)HttpResponse_getBufOffs(doublefsqrt); z->avail_out = HttpResponse_getRemBufSize(doublefsqrt); if(serial8250device == Z_STREAM_END) return 0; } } return Z_OK; } static int setuphrtimer( CspReader* alloccontroller, HttpResponse* doublefsqrt,U32 idmapstart, U32 icachealiases) { z_stream z; int serial8250device; U8* pcimthwint; const U32 enableinterrupts = 500; if(HttpResponse_flush(doublefsqrt)) return -1; pcimthwint = baMalloc(enableinterrupts+1); if(!pcimthwint) serial8250device = 1; else { z.next_in = 0; z.avail_in = 0; if(HttpResponse_getRemBufSize(doublefsqrt) < 50) HttpResponse_flush(doublefsqrt); z.next_out = (U8*)HttpResponse_getBufOffs(doublefsqrt); z.avail_out = HttpResponse_getRemBufSize(doublefsqrt); z.zalloc = (alloc_func)0; z.zfree = (free_func)0; z.opaque = (voidpf)0; serial8250device = inflateInit2(&z, -MAX_WBITS); if(serial8250device == Z_OK) { while(icachealiases != 0) { U32 notifierretry = icachealiases > enableinterrupts ? enableinterrupts : icachealiases; if(CspReader_read(alloccontroller, pcimthwint, idmapstart, notifierretry, FALSE)) { serial8250device = 2; break; } icachealiases -= notifierretry; idmapstart += notifierretry; z.next_in = pcimthwint; z.avail_in = icachealiases != 0 ? notifierretry : notifierretry+1; if(cmdlinesetup(&z, doublefsqrt) != Z_OK) { serial8250device = 3; break; } } if(inflateEnd(&z) != Z_OK && serial8250device == Z_OK) serial8250device = 4; } else serial8250device = 5; baFree(pcimthwint); } if(serial8250device) { if(!HttpResponse_flush(doublefsqrt)) { static const char mcbsppdata[] = {"\105\122\122\117\122\040\167\162\151\164\151\156\147\040\132\111\120\040\144\141\164\141\072\040"}; static const char* lswc2format[5] = { "\116\157\040\155\145\155\157\162\171", "\132\111\120\040\162\145\141\144\145\162\040\146\141\151\154\145\144", "\111\156\146\154\141\164\145\040\146\141\151\154\145\144", "\111\156\146\154\141\164\145\040\105\116\104\040\146\141\151\154\145\144", "\111\156\146\154\141\164\145\040\102\105\107\111\116\040\146\141\151\154\145\144"}; if(--serial8250device < 5) { HttpResponse_send(doublefsqrt,mcbsppdata,iStrlen(mcbsppdata)); HttpResponse_send(doublefsqrt,lswc2format[serial8250device],iStrlen(lswc2format[serial8250device])); } } return -1; } return 0; } #endif static void misalignederror(HttpResponse* doublefsqrt) { if(!HttpResponse_flush(doublefsqrt)) { static const char mcbsppdata[] = {"\105\122\122\117\122\040\167\162\151\164\151\156\147\040\103\123\120\040\144\141\164\141\072\040" "\103\163\160\122\145\141\144\145\162\040\146\141\151\154\145\144"}; HttpResponse_send(doublefsqrt,mcbsppdata,iStrlen(mcbsppdata)); } } int httpWriteSection(CspReader* alloccontroller, HttpResponse* doublefsqrt, U32 idmapstart, U32 icachealiases) { U32 devicehwmon = 1; while(icachealiases) { char* ptr; U32 notifierretry = HttpResponse_getRemBufSize(doublefsqrt); if(notifierretry < 1) { if(HttpResponse_flush(doublefsqrt)) return -1; notifierretry = HttpResponse_getRemBufSize(doublefsqrt); baAssert(notifierretry); } if(notifierretry > icachealiases) notifierretry = icachealiases; ptr = HttpResponse_getBufOffs(doublefsqrt); if(CspReader_read(alloccontroller, ptr, idmapstart, notifierretry, devicehwmon)) { misalignederror(doublefsqrt); return -1; } if(HttpResponse_dataAdded(doublefsqrt, notifierretry)) return -1; devicehwmon=0; idmapstart += notifierretry; icachealiases -= notifierretry; } return 0; } int httpUnzipAndWrite(CspReader* alloccontroller, HttpResponse* doublefsqrt, U32 idmapstart, U32 icachealiases, GzipHeader* stage2adjust) { if(stage2adjust) { #ifdef NO_ZLIB HttpResponse_write(doublefsqrt, noZipSupport, -1, TRUE); #else if( !doublefsqrt->printAndWriteInitialized ) if(HttpResponse_printAndWriteInit(doublefsqrt)) return -1; if(stage2adjust->id1 != 31) { idmapstart = bootmemremove(alloccontroller, doublefsqrt, idmapstart); if(idmapstart == 0) { HttpResponse_printf(doublefsqrt, "\105\162\162\157\162\040\151\156\040\107\132\111\120\040\150\145\141\144\145\162"); return -1; } } if(setuphrtimer(alloccontroller, doublefsqrt, idmapstart, icachealiases)) return -1; #endif } else { if(httpWriteSection(alloccontroller, doublefsqrt, idmapstart, icachealiases)) return -1; } return 0; } void httpRawWrite(CspReader* alloccontroller, HttpRequest* configuredevice, HttpResponse* doublefsqrt, U32 widgetactive, U32 idmapstart, U32 icachealiases, GzipHeader* stage2adjust, GzipTrailer* staticsuspend) { U32 notifierretry; U32 devicehwmon; U32 lsdc2format; void* dbdmasyscore; HttpResponse_setDateHeader(doublefsqrt, "\114\141\163\164\055\115\157\144\151\146\151\145\144", widgetactive); if(HttpRequest_getMethodType(configuredevice) == HttpMethod_Head) { HttpResponse_setContentLength(doublefsqrt, icachealiases); if(stage2adjust) HttpResponse_setHeader(doublefsqrt, "\103\157\156\164\145\156\164\055\105\156\143\157\144\151\156\147", "\147\172\151\160",TRUE); return; } if(stage2adjust) { const char* assertdevice; const char* ae = HttpRequest_getHeaderValue(configuredevice, "\101\143\143\145\160\164\055\105\156\143\157\144\151\156\147"); if(ae == 0) ae = HttpRequest_getHeaderValue(configuredevice, "\124\105"); if(ae == 0 || (bStrstr(ae, "\147\172\151\160")==0 && bStrstr(ae, "\052")==0) ) { #ifdef NO_ZLIB HttpResponse_sendError2(doublefsqrt, 406, noZipSupport); return; #else httpUnzipAndWrite(alloccontroller, doublefsqrt, idmapstart, icachealiases, stage2adjust); return; #endif } #ifndef NO_ZLIB assertdevice = HttpRequest_getHeaderValue(configuredevice, "\125\163\145\162\055\101\147\145\156\164"); if(assertdevice && strstr(assertdevice, "\107\145\143\153\157")) { httpUnzipAndWrite(alloccontroller, doublefsqrt, idmapstart, icachealiases, stage2adjust); return; } #endif HttpResponse_setHeader(doublefsqrt, "\103\157\156\164\145\156\164\055\105\156\143\157\144\151\156\147", "\147\172\151\160",TRUE); HttpResponse_setHeader(doublefsqrt, "\126\141\162\171", "\101\143\143\145\160\164\055\105\156\143\157\144\151\156\147",TRUE); if(stage2adjust->id1 == 31) { baAssert(sizeof(GzipHeader) == 10); baAssert(sizeof(GzipTrailer) == 8); HttpResponse_setContentLength(doublefsqrt, icachealiases+(10+8)); if(HttpResponse_flush(doublefsqrt)) return; HttpResponse_send(doublefsqrt, stage2adjust, sizeof(GzipHeader)); } else HttpResponse_setContentLength(doublefsqrt, icachealiases); } else HttpResponse_setContentLength(doublefsqrt, icachealiases); if(HttpResponse_flush(doublefsqrt)) return; devicehwmon = 1; lsdc2format = HttpResponse_getBufSize(doublefsqrt); dbdmasyscore = HttpResponse_getBuf(doublefsqrt); do { notifierretry = icachealiases > lsdc2format ? lsdc2format : icachealiases; if(CspReader_read(alloccontroller,dbdmasyscore,idmapstart, notifierretry,devicehwmon)) { misalignederror(doublefsqrt); break; } if(HttpResponse_send(doublefsqrt, dbdmasyscore, notifierretry)) break; icachealiases -= notifierretry; idmapstart += notifierretry; devicehwmon = 0; } while(notifierretry == lsdc2format); if(stage2adjust && stage2adjust->id1 == 31) { baAssert(staticsuspend); HttpResponse_send(doublefsqrt, staticsuspend, sizeof(GzipTrailer)); } } int cspCheckCondition(HttpRequest* configuredevice, HttpResponse* doublefsqrt) { if(HttpResponse_isInclude(doublefsqrt)) return 0; if(HttpRequest_checkMethods(configuredevice, doublefsqrt, HttpMethod_Get | HttpMethod_Post, TRUE)) { return 1; } return HttpResponse_setDefaultHeaders(doublefsqrt); } static void compatnames(struct HttpPage* bootmemunlock, HttpRequest* configuredevice, HttpResponse* doublefsqrt) { GzipHeader stage2adjust; HttpStaticMemPage* o = (HttpStaticMemPage*)bootmemunlock; stage2adjust.id1=0; if( !configuredevice ) { HttpPage_destructor(bootmemunlock); return; } if(HttpResponse_isInclude(doublefsqrt)) { httpUnzipAndWrite(o->data, doublefsqrt, o->payloadBlock.offset, o->payloadBlock.size, o->isCompressed ? &stage2adjust : 0); } else { if(o->mimeBlock.size == 1) { HttpResponse_sendError1(doublefsqrt, 404); } else { if( ! HttpRequest_checkTime(configuredevice, doublefsqrt, o->time) ) { char buf[50]; if(CspReader_read(o->data, buf, o->mimeBlock.offset, o->mimeBlock.size, TRUE)) { misalignederror(doublefsqrt); return; } HttpResponse_checkContentType(doublefsqrt, buf); httpRawWrite(o->data, configuredevice, doublefsqrt, o->time, o->payloadBlock.offset, o->payloadBlock.size, o->isCompressed ? &stage2adjust : 0, 0); } } } } void HttpStaticMemPage_loadAndInit(HttpStaticMemPage* o, CspReader* alloccontroller, U32 widgetactive, U32 uart2resource, U32 enablepseudo, U32 ads7846pendown, U32 doublefcmpe, U32 prepareenable, U32 calculateclock, char emulateloregs, HttpDir* checkstack) { o->data = alloccontroller; if(CspReader_read(o->data, o+1, uart2resource, enablepseudo, TRUE)) baFatalE(FE_CANNOT_READ, uart2resource); HttpPage_constructor(&o->page, compatnames, (char*)(o+1)); baAssert(o->page.name[enablepseudo-1] == 0); o->time = widgetactive; o->mimeBlock.offset = ads7846pendown; o->mimeBlock.size = doublefcmpe; o->payloadBlock.offset = prepareenable; o->payloadBlock.size = calculateclock; o->isCompressed = emulateloregs; HttpDir_insertPage(checkstack, &o->page); } void HttpDynamicMemPage_loadAndInit(HttpPage* o, CspReader* alloccontroller, U32 icachealiases, HttpPage_Service kexecnonboot, U32 uart2resource, U32 enablepseudo) { if(CspReader_read(alloccontroller, ((char*)o)+icachealiases, uart2resource, enablepseudo, TRUE)) baFatalE(FE_CANNOT_READ, uart2resource); HttpPage_constructor(o, kexecnonboot, ((char*)o)+icachealiases); baAssert(o->name[enablepseudo-1] == 0); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include BA_API DoubleLink* DoubleList_removeFirst(DoubleList* o) { if(o->next != (DoubleLink*)o) { DoubleLink* l = o->next; DoubleLink_unlink(l); return l; } return 0; } #if DL_INLINE == 0 BA_API void DoubleLink_unlink(DoubleLink* o) { register DoubleLink* prctlenable=o->next; register DoubleLink* setupmemory=o->prev; baAssert(setupmemory && prctlenable); prctlenable->prev = setupmemory; setupmemory->next = prctlenable; o->prev = o->next = 0; } #endif BA_API DoubleLink* DoubleListEnumerator_removeElement(DoubleListEnumerator* o) { DoubleLink* handlersetup; DoubleLink* remove = o->curElement; if(remove) { handlersetup = DoubleListEnumerator_nextElement(o); DoubleLink_unlink(remove); } else handlersetup = 0; return handlersetup; } #if !defined(NDEBUG) || defined(BDLL) BA_API BaBool DoubleList_isInListF(DoubleList* o, void* smartreflexhwmod,const char* debugsetup,int enabledisable) { if(((DoubleLink*)smartreflexhwmod)->prev || ((DoubleLink*)smartreflexhwmod)->next) { DoubleLink* l; DoubleListEnumerator instructioncounter; if( !((DoubleLink*)smartreflexhwmod)->prev || !((DoubleLink*)smartreflexhwmod)->next ) baFatalEf(FE_ASSERT,0,debugsetup,enabledisable); DoubleListEnumerator_constructor(&instructioncounter, o); for(l = DoubleListEnumerator_getElement(&instructioncounter) ; l ; l = DoubleListEnumerator_nextElement(&instructioncounter)) { if(l == ((DoubleLink*)smartreflexhwmod)) break; } if(!l) baFatalEf(FE_ASSERT,0,debugsetup,enabledisable); return TRUE; } return FALSE; } #endif #if DL_INLINE == 0 BA_API void DoubleLink_constructor(void* o) { ((DoubleLink*)o)->next = 0; ((DoubleLink*)o)->prev = 0; } BA_API void DoubleLink_destructor(void* o) { if(DoubleLink_isLinked(o)) DoubleLink_unlink((DoubleLink*)o); } BA_API void DoubleLink_insertAfter(void* o, void* tsx09check) { baAssert(((DoubleLink*)tsx09check)->prev==0&&((DoubleLink*)tsx09check)->next==0); ((DoubleLink*)tsx09check)->next = ((DoubleLink*)o)->next; ((DoubleLink*)tsx09check)->prev = ((DoubleLink*)o); ((DoubleLink*)o)->next->prev = ((DoubleLink*)tsx09check); ((DoubleLink*)o)->next = ((DoubleLink*)tsx09check); } BA_API void DoubleLink_insertBefore(void* o, void* tsx09check) { baAssert(((DoubleLink*)tsx09check)->prev==0&&((DoubleLink*)tsx09check)->next==0); ((DoubleLink*)tsx09check)->prev = ((DoubleLink*)o)->prev; ((DoubleLink*)tsx09check)->next = ((DoubleLink*)o); ((DoubleLink*)o)->prev->next = ((DoubleLink*) tsx09check); ((DoubleLink*)o)->prev = ((DoubleLink*) tsx09check); } BA_API int DoubleLink_isLinked(void* o) { return (((DoubleLink*)o)->prev ? TRUE : FALSE); } BA_API DoubleLink* DoubleLink_getNext(void* o) { return ((DoubleLink*)o)->next; } BA_API void DoubleList_constructor(DoubleList* o) { o->next = (DoubleLink*)o; o->prev = (DoubleLink*)o; } BA_API void DoubleList_insertFirst(DoubleList* o, void* tsx09check) { baAssert(((DoubleLink*)tsx09check)->prev==0&&((DoubleLink*)tsx09check)->next==0); ((DoubleLink*)tsx09check)->next = o->next; ((DoubleLink*)tsx09check)->prev = (DoubleLink*)o; o->next->prev = ((DoubleLink*) tsx09check); o->next = ((DoubleLink*) tsx09check); } BA_API void DoubleList_insertLast(DoubleList* o, void* tsx09check) { baAssert(((DoubleLink*)tsx09check)->prev==0&&((DoubleLink*)tsx09check)->next==0); ((DoubleLink*)tsx09check)->next = (DoubleLink*)o; ((DoubleLink*)tsx09check)->prev = o->prev; o->prev->next = ((DoubleLink*)tsx09check); o->prev = ((DoubleLink*)tsx09check); } BA_API int DoubleList_isLast(DoubleList* o, void* n) { return (((DoubleLink*)(n))->next == (DoubleLink*)o); } BA_API int DoubleList_isEnd(DoubleList* o, void* n) { return ((DoubleLink*)(n) == (DoubleLink*)o); } BA_API DoubleLink* DoubleList_firstNode(DoubleList* o) { return (o->next != (DoubleLink*)o ? o->next : 0); } BA_API DoubleLink* DoubleList_lastNode(DoubleList* o) { return (o->prev != (DoubleLink*)o ? o->prev : 0); } BA_API void DoubleListEnumerator_constructor(DoubleListEnumerator* o, DoubleList* entryinsert) { o->list = entryinsert; o->curElement = DoubleList_firstNode(o->list); } BA_API DoubleLink* DoubleListEnumerator_nextElement(DoubleListEnumerator* o) { if(o->curElement) { o->curElement = o->curElement->next == (DoubleLink*)o->list ? 0 : o->curElement->next; return o->curElement; } return 0; } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include static void handleunknown(DynBuffer* o, int serial8250device) { baAssert(serial8250device < 0); o->expandSize = serial8250device; if(o->onAllocError) o->onAllocError(o, serial8250device); } static int logicalindex(BufPrint* fdc37m81xconfig, int stateparam) { void* anatopenable; size_t devicelcdspi,indexnospec; DynBuffer* o = (DynBuffer*)fdc37m81xconfig; if( ! stateparam ) return 0; if(fdc37m81xconfig->buf) { if(o->expandSize <= 0) return -1; if(o->alloc->reallocCB) { devicelcdspi = stateparam < o->expandSize ? o->expandSize : stateparam; indexnospec = fdc37m81xconfig->bufSize + devicelcdspi; if(indexnospec > (size_t)fdc37m81xconfig->bufSize) { indexnospec+=1; anatopenable = AllocatorIntf_realloc(o->alloc, fdc37m81xconfig->buf, &indexnospec); if(anatopenable) { fdc37m81xconfig->buf = anatopenable; fdc37m81xconfig->bufSize = (int)indexnospec-1; return 0; } else handleunknown(o, -4); } else handleunknown(o, -5); } else handleunknown(o, -3); } else if(o->alloc && o->alloc->mallocCB) { indexnospec = stateparam < o->startSize ? o->startSize : stateparam; indexnospec+=1; fdc37m81xconfig->cursor=0; fdc37m81xconfig->buf = AllocatorIntf_malloc(o->alloc, &indexnospec); if(fdc37m81xconfig->buf) { fdc37m81xconfig->bufSize = (int)indexnospec-1; return 0; } else handleunknown(o, -2); } else handleunknown(o, -1); return -1; } BA_API int DynBuffer_expand(DynBuffer* o, int cachedisable) { BufPrint* fdc37m81xconfig = (BufPrint*)o; int emulateinstruction = fdc37m81xconfig->bufSize - fdc37m81xconfig->cursor; if(emulateinstruction >= cachedisable) return 0; return logicalindex(fdc37m81xconfig, cachedisable-emulateinstruction); } BA_API void DynBuffer_constructor(DynBuffer* o, int allocpages, int heartclocksource, AllocatorIntf* unmapaliases, DynBuffer_OnAllocError cplusserial8250) { BufPrint* fdc37m81xconfig = (BufPrint*)o; memset(o, 0, sizeof(DynBuffer)); BufPrint_constructor(fdc37m81xconfig, 0, logicalindex); o->startSize=allocpages; o->expandSize=heartclocksource; o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); o->onAllocError=cplusserial8250; fdc37m81xconfig->buf = 0; fdc37m81xconfig->bufSize = 0; logicalindex((BufPrint*)o, allocpages); } BA_API void DynBuffer_release(DynBuffer* o) { BufPrint* fdc37m81xconfig = (BufPrint*)o; if(fdc37m81xconfig->buf) { AllocatorIntf_free(o->alloc, fdc37m81xconfig->buf); fdc37m81xconfig->buf=0; fdc37m81xconfig->cursor=0; fdc37m81xconfig->bufSize=0; } } BA_API char* DynBuffer_getBuf(DynBuffer* o) { BufPrint* fdc37m81xconfig = (BufPrint*)o; if(fdc37m81xconfig->buf) { fdc37m81xconfig->buf[fdc37m81xconfig->cursor]=0; } return fdc37m81xconfig->buf; } BA_API const char* DynBuffer_ecode2str(int serial8250device) { switch(serial8250device) { case -2: return "\115\141\154\154\157\143\040\146\141\151\154\145\144"; case -3: return "\116\157\040\162\145\141\154\154\157\143"; case -4: return "\122\145\141\154\154\157\143\040\146\141\151\154\145\144"; case -5: return "\102\165\146\146\145\162\040\164\157\157\040\154\141\162\147\145"; } baAssert(0); return "\151\156\164\145\162\156\040\145\162\162"; } #ifndef BA_LIB #define BA_LIB 1 #endif #define SingleListCode #include #include #include BA_API void HashTableNode_constructor(HashTableNode* o, const char* gpio1config, HashTableNode_terminate sha512update) { SingleLink_constructor((SingleLink*)o); o->name = gpio1config; o->destructor = sha512update; } BA_API HashTable* HashTable_create(U32 buddynocheck, AllocatorIntf* unmapaliases) { if(!unmapaliases) unmapaliases=AllocatorIntf_getDefault(); if(buddynocheck) { size_t icachealiases = sizeof(HashTable) + sizeof(SingleList)*(buddynocheck-1); HashTable* ht = (HashTable*)AllocatorIntf_malloc(unmapaliases, &icachealiases); if(ht) { U32 i; ht->tmObj=0; ht->noOfHashElements = buddynocheck; for (i=0; i < buddynocheck; i++) SingleList_constructor(ht->table+i); return ht; } } return 0; } BA_API void HashTable_destructor(HashTable* o) { U32 i; for (i = 0; i < o->noOfHashElements; i++) { HashTableNode* smartreflexhwmod; SingleList* entryinsert = o->table+i; while( (smartreflexhwmod = (HashTableNode*)SingleList_removeFirst(entryinsert)) != 0 ) { HashTableNode_terminate(smartreflexhwmod, o->tmObj); } } } BA_API int HashTable_iter(HashTable* o, void* memorydescriptor, HashTable_CbFunc keypadacquire) { U32 i; for (i = 0; i < o->noOfHashElements; i++) { SingleListEnumerator e; SingleLink* sl; SingleList* entryinsert = o->table+i; SingleListEnumerator_constructor(&e, entryinsert); for(sl = SingleListEnumerator_getElement(&e) ; sl ; sl = SingleListEnumerator_nextElement(&e)) { int sffsdrnandflash = (*keypadacquire)(memorydescriptor, (HashTableNode*)sl); if(sffsdrnandflash) return sffsdrnandflash; } } return 0; } static SingleList* HashTable_hash(HashTable* o, const char* s) { const char *p; unsigned long h = 0, g; for(p = s; *p; p = p + 1) { h = (h << 4) + *p; if( (g = h & 0xf0000000l) !=0 ) { h = h ^ (g >> 24); h = h ^ g; } } return o->table + h % o->noOfHashElements; } BA_API void HashTable_add(HashTable* o, HashTableNode* smartreflexhwmod) { SingleList* entryinsert = HashTable_hash(o, smartreflexhwmod->name); SingleList_insertLast(entryinsert, smartreflexhwmod); } BA_API HashTableNode* HashTable_lookup(HashTable* o, const char* nanoenginesetup) { SingleListEnumerator instructioncounter; HashTableNode* smartreflexhwmod; SingleListEnumerator_constructor(&instructioncounter, HashTable_hash(o, nanoenginesetup)); for(smartreflexhwmod = (HashTableNode*)SingleListEnumerator_getElement(&instructioncounter); smartreflexhwmod; smartreflexhwmod = (HashTableNode*)SingleListEnumerator_nextElement(&instructioncounter)) { if ( ! strcmp(nanoenginesetup, smartreflexhwmod->name) ) return smartreflexhwmod; } return 0; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include static void writeswinc(HttpAsynchReq* o) { SoDisp* ptraceaccess=SoDispCon_getDispatcher((SoDispCon*)o); if(SoDispCon_recEvActive((SoDispCon*)o)) SoDisp_deactivateRec(ptraceaccess,(SoDispCon*)o); if(SoDispCon_dispatcherHasCon((SoDispCon*)o)) SoDisp_removeConnection(ptraceaccess,(SoDispCon*)o); } static S32 restorecurrent(HttpAsynchReq* o, S32 icachealiases) { icachealiases = HttpConnection_readData( (HttpConnection*)o, o->buffer + o->offset, icachealiases); if(icachealiases < 0) { writeswinc(o); o->data(o,0, -1); } else o->offset += icachealiases; return icachealiases; } static void prefetchparameters(HttpAsynchReq* o, BaBool* clustercache) { S32 icachealiases; do { icachealiases = (S32)(o->bufferSize - o->offset); if(icachealiases > o->packetSizeLeft) icachealiases = (S32)o->packetSizeLeft; icachealiases = restorecurrent(o, icachealiases); if(icachealiases > 0) { o->packetSizeLeft -= icachealiases; if(o->packetSizeLeft == 0) { o->data(o,o->buffer, (S32)o->offset); if(*clustercache) return; o->data(o,0, 0); if( ! *clustercache ) { writeswinc(o); } return; } if(o->offset == o->bufferSize) { o->data(o, o->buffer, (S32)o->offset); if(*clustercache) return; o->offset=0; } } } while(icachealiases > 0 && HttpConnection_hasMoreData((HttpConnection*)o)); } static void nvraminitialize(HttpAsynchReq* o, BaBool* clustercache) { S32 icachealiases; do { if(o->packetSizeLeft > 0) { icachealiases = (S32)(o->packetSizeLeft > o->bufferSize ? o->bufferSize : o->packetSizeLeft); if( (icachealiases = restorecurrent(o, icachealiases)) > 0 ) { o->packetSizeLeft -= icachealiases; o->offset=0; if(o->packetSizeLeft <= 0) { baAssert(o->packetSizeLeft == 0); o->packetSizeLeft=-1; } o->data(o,o->buffer,icachealiases); } else break; } else { icachealiases = (S32)(o->bufferSize - o->offset); baAssert(icachealiases); if(o->packetSizeLeft) { if(icachealiases > 2) icachealiases = 2; } else { if(icachealiases > 6) icachealiases = 6; } if( (icachealiases = restorecurrent(o, icachealiases)) > 0 ) { U8* end; L_decode: for(end = o->buffer+1; end < (o->buffer + o->offset) ; end++) { if(*end == '\012') { U8* ptr; if(*(end-1) != '\015') { o->data(o,0,-10); if( ! *clustercache ) { writeswinc(o); } return; } if(o->packetSizeLeft) { o->packetSizeLeft=0; o->offset=0; break; } *(end-1)=0; if( (ptr = (U8*)strchr((const char*)o->buffer,'\073')) != 0) *ptr=0; o->packetSizeLeft = U32_hextoi((const char*)o->buffer); if(o->packetSizeLeft == 0) { end++; icachealiases = (S32)(end - o->buffer); baAssert(icachealiases <= o->offset); icachealiases+=2; if(icachealiases < o->offset) { if(HttpConnection_pushBack((HttpConnection*)o, end,(S32)o->offset-icachealiases)) { HttpConnection_clearKeepAlive((HttpConnection*)o); } } o->data(o,0,0); baAssert(*clustercache); return; } ++end; if(end != o->buffer+o->offset) { icachealiases = (S32)((o->buffer+o->offset) - end); if(icachealiases >= o->packetSizeLeft) { o->data(o,end,(S32)o->packetSizeLeft); if(*clustercache) return; end+=o->packetSizeLeft; icachealiases-=(S32)o->packetSizeLeft; if(icachealiases) memmove(o->buffer, end, icachealiases); o->packetSizeLeft=-1; o->offset=icachealiases; goto L_decode; } o->data(o,end,icachealiases); if(*clustercache) return; o->packetSizeLeft -= icachealiases; } o->offset=0; break; } } if(o->offset >= o->bufferSize) { o->data(o,0,-11); baAssert(*clustercache); return; } } else { break; } } } while( ! *clustercache && HttpConnection_hasMoreData((HttpConnection*)o)); } static void unregisterioapic(SoDispCon* fdc37m81xconfig) { BaBool queueevent=FALSE; HttpAsynchReq* o = (HttpAsynchReq*)fdc37m81xconfig; o->isTerminatedPtr=&queueevent; if(o->chunkEncoding) nvraminitialize(o, &queueevent); else prefetchparameters(o, &queueevent); if(!queueevent) o->isTerminatedPtr=0; } BA_API SBaFileSize HttpAsynchReq_calcPacketSize(HttpRequest* req) { const char* modulefunction; if(HttpRequest_getHeaderValue(req,"\124\162\141\156\163\146\145\162\055\145\156\143\157\144\151\156\147")) { return -1; } modulefunction=HttpStdHeaders_getContentType(HttpRequest_getStdHeaders(req)); if(modulefunction) { if(!baStrnCaseCmp(modulefunction,"\155\165\154\164\151\160\141\162\164\057\146\157\162\155\055\144\141\164\141", 19)) { return -2; } if(!baStrnCaseCmp(modulefunction,"\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\167\167\055\146\157\162\155\055\165\162\154\145\156\143\157\144\145\144",33)) { return -3; } } return HttpStdHeaders_getContentLength( HttpRequest_getStdHeaders(req)); } BA_API void HttpAsynchReq_constructor(HttpAsynchReq* o, HttpServer* uarchbuild, HttpAsynchReq_OnData alloccontroller) { memset(o, 0, sizeof(HttpAsynchReq)); HttpConnection_constructor((HttpConnection*)o, uarchbuild, uarchbuild->dispatcher, unregisterioapic); o->data=alloccontroller; } BA_API void HttpAsynchReq_destructor(HttpAsynchReq* o) { if(o->isTerminatedPtr) *o->isTerminatedPtr=TRUE; HttpAsynchReq_stop(o); HttpConnection_destructor((HttpConnection*)o); } static int pciercxcfg030(HttpRequest* req) { HttpConnection* con = HttpRequest_getConnection(req); if(HttpResponse_committed(HttpRequest_getResponse(req))) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\161\072\072\163\164\141\162\164\040\143\157\155\155\151\164\164\145\144\012") ); return -1; } if( !HttpConnection_isValid(con) ) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\161\072\072\163\164\141\162\164\040\163\164\141\154\145\040\163\157\143\153\145\164\012") ); return -2; } return 0; } BA_API int HttpAsynchReq_start( HttpAsynchReq* o,HttpRequest* req,void* startcounter,S32 videodriver) { SBaFileSize icachealiases; HttpConnection* con = HttpRequest_getConnection(req); SoDisp* ptraceaccess=HttpConnection_getDispatcher(con); HttpResponse* r3000write = HttpRequest_getResponse(req); BaBool queueevent = FALSE; if(!startcounter || videodriver < 255) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\161\072\072\163\164\141\162\164\040\142\165\146\146\145\162\040\164\157\157\040\163\155\141\154\154\012") ); return -30; } if(o->buffer) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\161\072\072\163\164\141\162\164\040\142\165\163\171\012") ); return -20; } o->packetSizeLeft=HttpAsynchReq_calcPacketSize(req); if(o->packetSizeLeft < -1) { if(o->packetSizeLeft == -2) { HttpResponse_sendError2( r3000write,400,"\110\164\164\160\101\163\171\156\143\150\122\145\161\072\040\103\141\156\156\157\164\040\144\157\040\155\165\154\164\151\160\141\162\164\057\146\157\162\155\055\144\141\164\141"); return -1; } if(o->packetSizeLeft == -3) { HttpResponse_sendError2( r3000write,400, "\110\164\164\160\101\163\171\156\143\150\122\145\161\072\040\103\141\156\156\157\164\040\144\157\040\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\167\167\055\146\157\162\155\055\165\162\154\145\156\143\157\144\145\144"); return -2; } HttpResponse_sendError1(r3000write,400); return -100; } if( o->packetSizeLeft == -1) { o->chunkEncoding = TRUE; o->packetSizeLeft=0; } icachealiases = (S32)pciercxcfg030(req); if(icachealiases) return (int)icachealiases; o->buffer=(U8*)startcounter; o->bufferSize = videodriver; if(o->chunkEncoding) o->packetSizeLeft=0; o->offset = 0; icachealiases = HttpRequest_pushBackData(req); HttpConnection_moveCon(con, (HttpConnection*)o); o->isTerminatedPtr = &queueevent; if(HttpRequest_getHeaderValue(req, "\105\170\160\145\143\164")) { o->data(o,o->buffer, 0); if(queueevent) return 0; if(HttpConnection_sendData( (HttpConnection*)o, "\110\124\124\120\057\061\056\061\040\061\060\060\040\103\157\156\164\151\156\165\145\015\012\015\012",25)) { return -2; } } if(icachealiases != 0) { if(icachealiases < 0) { o->isTerminatedPtr=0; return E_MALLOC; } if(o->chunkEncoding) nvraminitialize(o, &queueevent); else prefetchparameters(o, &queueevent); } if( ! queueevent ) { if(HttpConnection_hasMoreData((HttpConnection*)o)) { if(o->chunkEncoding) nvraminitialize(o, &queueevent); else prefetchparameters(o, &queueevent); } if( ! queueevent ) { if(o->chunkEncoding || o->packetSizeLeft) { SoDisp_addConnection(ptraceaccess, (SoDispCon*)o); SoDisp_activateRec(ptraceaccess, (SoDispCon*)o); o->isTerminatedPtr=0; } else { o->data(o,0, 0); if( ! queueevent ) { writeswinc(o); o->isTerminatedPtr=0; return -1; } } } } return 0; } BA_API void HttpAsynchReq_stop(HttpAsynchReq* o) { o->buffer = 0; o->bufferSize = 0; o->packetSizeLeft = 0; o->offset = 0; if(HttpConnection_dispatcherHasCon((HttpConnection*)o)) { writeswinc(o); HttpConnection_setState((HttpConnection*)o,HttpConnection_Terminated); } } BA_API HttpConnection* HttpAsynchReq_getCon(HttpAsynchReq* o) { if(HttpConnection_dispatcherHasCon((HttpConnection*)o)) writeswinc(o); if(o->isTerminatedPtr) *o->isTerminatedPtr=TRUE; return (HttpConnection*)o; } BA_API void HttpAsynchReqResp_constructor(HttpAsynchReqResp* o, HttpServer* uarchbuild, HttpAsynchReq_OnData alloccontroller) { HttpAsynchReq_constructor((HttpAsynchReq*)o, uarchbuild, alloccontroller); memset(&o->resp, 0, sizeof(HttpAsynchResp)); } BA_API int HttpAsynchReqResp_start(HttpAsynchReqResp* o, HttpRequest* req, void* pc104unmask, S32 sleepau1000, void* checkbattery, S32 updatestatus) { HttpAsynchResp_ReqRespInit(&o->resp,checkbattery,updatestatus,(HttpConnection*)o); return HttpAsynchReq_start((HttpAsynchReq*)o,req,pc104unmask,sleepau1000); } BA_API int HttpAsynchReqResp_startResp(HttpAsynchReqResp* o, HttpRequest* req, void* checkbattery, S32 updatestatus) { int sffsdrnandflash = pciercxcfg030(req); if(!sffsdrnandflash) HttpAsynchResp_constructor(&o->resp, checkbattery, updatestatus, req); return sffsdrnandflash; } #if 0 void HttpAsynchReqResp_disableRecEv(HttpAsynchReqResp* o) { if(HttpConnection_recEvActive((HttpConnection*)o)) { SoDisp* ptraceaccess=HttpConnection_getDispatcher((HttpConnection*)o); SoDisp_deactivateRec(ptraceaccess,(HttpConnection*)o); SoDisp_setPollMode(ptraceaccess); } } void HttpAsynchReqResp_enableRecEv(HttpAsynchReqResp* o) { if( ! HttpConnection_recEvActive((HttpConnection*)o) ) { SoDisp* ptraceaccess=HttpConnection_getDispatcher((HttpConnection*)o); SoDisp_activateRec(ptraceaccess,(HttpConnection*)o); } } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #define INL_baConvBin2Hex 1 #include #include #include static int netdevnotifier(BufPrint* stealclock, int stateparam) { HttpAsynchResp* o = (HttpAsynchResp*)stealclock->userData; int len = stealclock->cursor; (void)stateparam; if(len) { stealclock->cursor = 0; if(o->mutex) { if(o->responseState == RESPONSESTATE_WRITEMODE_CHUNK) { char* end = stealclock->buf + len; char* ptr = stealclock->buf; U8 processsubpacket = (U8)(len >> 8); *--ptr = '\012'; *--ptr = '\015'; ptr -= 2; baConvBin2Hex(ptr, (U8)len); if(processsubpacket) { ptr -= 2; baConvBin2Hex(ptr, processsubpacket); } if(*ptr == '\060') { ptr++; } *end++='\015'; *end='\012'; return SoDispCon_sendData( (SoDispCon*)o->con, ptr, len + (int)(stealclock->buf - ptr) + 2); } return SoDispCon_sendData((SoDispCon*)o->con, stealclock->buf, len); } return o->responseState == RESPONSESTATE_WRITEMODE_CHUNK ? HttpConnection_sendChunkData6bOffs(o->con,stealclock->buf,len): HttpConnection_sendData(o->con, stealclock->buf, len); } return 0; } static int pxa270ucb1400(HttpAsynchResp* o) { return netdevnotifier(&o->bufPrint,0); } static int loongson2blast(HttpAsynchResp* o) { baAssert( ! o->headerSent ); if( ! o->statusSent ) { if(HttpAsynchResp_setStatus(o, 200, 0)) return -10; } o->headerSent=TRUE; if( ! BufPrint_printf(&o->bufPrint,"\015\012") ) return pxa270ucb1400(o); return -11; } static int irqvecfixup(HttpAsynchResp* o) { return HttpAsynchResp_setHeader( o, "\103\157\156\156\145\143\164\151\157\156", HttpConnection_keepAlive(o->con) && !o->doLingeringClose ? "\113\145\145\160\055\101\154\151\166\145" : "\103\154\157\163\145"); } static void probesactions(SoDispCon* con) { (void)con; } static void updateftrace(HttpAsynchResp* o, HttpConnection* con, char* buf, int icachealiases) { if(con == (HttpConnection*)o) { ((SoDispCon*)o)->dispRecEv = probesactions; } else { HttpConnection_constructor((HttpConnection*)o, con ? HttpConnection_getServer(con) : 0, con ? HttpConnection_getDispatcher(con) : 0, probesactions); } BufPrint_constructor(&o->bufPrint, o, netdevnotifier); if(!buf || icachealiases < 200) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\163\160\072\072\143\157\156\163\164\162\165\143\164\157\162\040\102\165\146\146\145\162\040\074\040\062\060\060\012") ); o->bufPrint.buf = 0; return; } o->bufPrint.buf = buf; o->bufPrint.bufSize = icachealiases; o->mutex=0; o->statusSent = FALSE; o->headerSent = FALSE; o->doLingeringClose=FALSE; o->responseState = RESPONSESTATE_IDLE; } static void radiomagic(HttpAsynchResp* o, HttpConnection* con) { if(con && HttpConnection_isValid(con)) { if(con != (HttpConnection*)o) { HttpConnection_moveCon(con, (HttpConnection*)o); } } o->con = (HttpConnection*)o; } static void edma0device(HttpAsynchResp* o, HttpRequest* req) { if(HttpResponse_committed(HttpRequest_getResponse(req))) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\161\072\072\163\145\164\122\145\161\040\143\157\155\155\151\164\164\145\144\012") ); } else { HttpConnection* con = HttpRequest_getConnection(req); radiomagic(o, con); } } BA_API void HttpAsynchResp_constructor(HttpAsynchResp* o,char* buf,int s,HttpRequest* req) { updateftrace(o,HttpRequest_getConnection(req),buf,s); if(o->bufPrint.buf) edma0device(o, req); } BA_API void HttpAsynchResp_constructor2( HttpAsynchResp* o, char* buf, int icachealiases, HttpConnection* con) { updateftrace(o, con, buf, icachealiases); if(o->bufPrint.buf) radiomagic(o, con); } BA_API void HttpAsynchResp_ReqRespInit( HttpAsynchResp* o, char* buf, int icachealiases, HttpConnection* con) { updateftrace(o, con, buf, icachealiases); if(o->bufPrint.buf) { o->con = con; } } BA_API BaBool HttpAsynchResp_isValid(HttpAsynchResp* o) { return o->bufPrint.buf && HttpConnection_isValid(o->con) ? TRUE : FALSE; } static void captureconfig(HttpAsynchResp* o) { HttpConnection* con; if(o->responseState == RESPONSESTATE_CLOSED) return; con = o->con; if(HttpConnection_recEvActive(con)) { SoDisp_deactivateRec( HttpServer_getDispatcher(con->server),(SoDispCon*)con); } if(HttpConnection_dispatcherHasCon(con)) { SoDisp_removeConnection( HttpServer_getDispatcher(con->server), (SoDispCon*)con); } if(HttpConnection_isValid(con)) { if( ! pxa270ucb1400(o) ) { if(o->responseState == RESPONSESTATE_WRITEMODE_CHUNK) { if(HttpConnection_sendData(con, "\060\015\012\015\012", 5)) { HttpConnection_setState(con, HttpConnection_Terminated); return; } } if(o->doLingeringClose) { HttpServer_doLingeringClose(con->server, con, 0); return; } if(HttpConnection_keepAlive(con)) { HttpServer_addCon2ConnectedList(HttpConnection_getServer(con),con); return; } } } HttpConnection_destructor(con); } BA_API void HttpAsynchResp_close(HttpAsynchResp* o) { if(o->con) { if(o->mutex && ! ThreadMutex_isOwner(o->mutex)) { ThreadMutex_set(o->mutex); captureconfig(o); ThreadMutex_release(o->mutex); } else captureconfig(o); o->responseState=RESPONSESTATE_CLOSED; } } BA_API int HttpAsynchResp_setStatus(HttpAsynchResp* o, int suspendstate, const char* ejtagsetup) { static const char fmt[] = { "\110\124\124\120\057\045\163\040\045\163\015\012" "\104\141\164\145\072\040\045\163\015\012" "\123\145\162\166\145\162\072\040" SERVER_SOFTWARE_NAME "\015\012" }; char* ktextsource; int handlersetup=0; if( ! ejtagsetup ) ejtagsetup = "\061\056\061"; if( ! o->bufPrint.buf ) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\163\160\072\072\163\145\164\123\164\141\164\165\163\040\111\156\166\141\154\151\144\040\142\165\146\146\145\162\012") ); return -200; } ktextsource = o->bufPrint.buf+100; if(o->statusSent) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\163\160\072\072\163\145\164\123\164\141\164\165\163\040\123\164\141\164\165\163\040\163\145\156\164\012") ); handlersetup = -100; } else { o->statusSent = TRUE; httpFmtDate(ktextsource, 100, baGetUnixTime()); if(BufPrint_printf(&o->bufPrint, fmt, ejtagsetup, HttpServer_getStatusCode(suspendstate), ktextsource, HttpConnection_keepAlive(o->con)? "\113\145\145\160\055\101\154\151\166\145" : "\103\154\157\163\145") < 0) { handlersetup = -11; } } return handlersetup; } BA_API int HttpAsynchResp_setHeader(HttpAsynchResp* o,const char *gpio1config,const char *videoprobe) { int handlersetup=0; if(o->headerSent) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\163\160\072\072\163\145\164\110\145\141\144\145\162\040\110\145\141\144\145\162\040\163\145\156\164\012") ); handlersetup = -110; } else if( ! o->statusSent ) { handlersetup = HttpAsynchResp_setStatus(o, 200, 0); } if( ! handlersetup ) { if(BufPrint_printf(&o->bufPrint,"\045\163\072\040\045\163\015\012",gpio1config,videoprobe)) handlersetup = -2; } return handlersetup; } BA_API int HttpAsynchResp_sendData( HttpAsynchResp* o, const void* alloccontroller, int installaddress, int notifierretry) { int handlersetup; if(o->responseState != RESPONSESTATE_IDLE) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\163\160\072\072\163\145\156\144\104\141\164\141\040\102\157\144\171\040\163\145\156\164\040\157\162\040\151\156\040\160\162\157\147\162\145\163\163\012") ); return 0; } baAssert( ! o->headerSent ); o->responseState = RESPONSESTATE_BODYSENT; handlersetup = irqvecfixup(o); if( ! handlersetup ) { handlersetup= BufPrint_printf(&o->bufPrint,"\103\157\156\164\145\156\164\055\114\145\156\147\164\150\072\040\045\165\015\012",installaddress) < 0 ? -3 : 0; if( ! handlersetup ) { handlersetup = loongson2blast(o); if( ! handlersetup && alloccontroller) { if(notifierretry && HttpConnection_sendData(o->con, alloccontroller, notifierretry)) handlersetup=-4; } } } return handlersetup; } BA_API int HttpAsynchResp_sendNextChunk(HttpAsynchResp* o,const void* alloccontroller,int notifierretry) { if(o->responseState != RESPONSESTATE_BODYSENT) { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\163\160\072\072\163\145\156\144\116\145\170\164\103\150\165\156\153\040\115\165\163\164\040\143\141\154\154\040\163\145\156\144\104\141\164\141\012") ); return -1; } return HttpConnection_sendData(o->con, alloccontroller, notifierretry); } BA_API BufPrint* HttpAsynchResp_getWriter(HttpAsynchResp* o) { if(o->responseState == RESPONSESTATE_WRITEMODE_CHUNK || o->responseState == RESPONSESTATE_WRITEMODE) { return &o->bufPrint; } if(o->responseState == RESPONSESTATE_IDLE) { baAssert(! o->headerSent); o->responseState = RESPONSESTATE_BODYSENT; if( ! irqvecfixup(o) ) { if(HttpConnection_keepAlive(o->con)) { if( ! HttpAsynchResp_setHeader(o,"\124\162\141\156\163\146\145\162\055\105\156\143\157\144\151\156\147","\143\150\165\156\153\145\144") ) { if( ! loongson2blast(o) ) { o->responseState = RESPONSESTATE_WRITEMODE_CHUNK; o->bufPrint.buf += 6; o->bufPrint.bufSize -= 8; } } } else if( ! loongson2blast(o) ) { o->responseState = RESPONSESTATE_WRITEMODE; } } } else { TRPR( ("\110\164\164\160\101\163\171\156\143\150\122\145\163\160\072\072\147\145\164\127\162\151\164\145\162\040\102\157\144\171\040\163\145\156\164\040\167\151\164\150\040\163\145\156\144\104\141\164\141\012") ); } if(o->responseState == RESPONSESTATE_WRITEMODE_CHUNK || o->responseState == RESPONSESTATE_WRITEMODE) { return &o->bufPrint; } return 0; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include static void sdhciresources(HttpCmdThreadPoolIntf* o, HttpCmdThreadPoolIntf_DoDir pwrdmoperations) { o->doDir = pwrdmoperations; } static void kernelstack(Thread* suspendprepare); static void genericshutdown(HttpCmdThread* o, ThreadPriority gpio1resources, int stage2unmap, struct HttpCmdThreadPool* configbootdata, DoubleList* entryinsert) { memset(o, 0, sizeof(HttpCmdThread)); Thread_constructor((Thread*)o, kernelstack, gpio1resources, stage2unmap); ThreadSemaphore_constructor(&o->sem); DoubleLink_constructor(&o->node); o->pool = configbootdata; DoubleList_insertLast(entryinsert, &o->node); Thread_start((Thread*)o); } static void boardconfig(HttpCmdThread* o) { Thread_destructor((Thread*)o); ThreadSemaphore_destructor(&o->sem); } static void kernelstack(Thread* suspendprepare) { HttpCmdThreadState state; HttpCmdThread* o = (HttpCmdThread*)suspendprepare; struct HttpCmdThreadPool* configbootdata=o->pool; for(;;) { ThreadSemaphore_wait(&o->sem); SoDisp_mutexSet(configbootdata->dispatcher); state = o->state; if(state == HttpCmdThreadState_Idle) { baAssert(DoubleList_isInList(&configbootdata->freeList, &o->node)); SoDisp_mutexRelease(configbootdata->dispatcher); continue; } baAssert(DoubleList_isInList(&configbootdata->runningList, &o->node)); if(state == HttpCmdThreadState_RunDir) HttpServer_AsynchProcessDir(configbootdata->server, o->dir, o->cmd); DoubleLink_unlink(&o->node); o->state = HttpCmdThreadState_Idle; DoubleList_insertLast(&configbootdata->freeList, &o->node); SoDisp_mutexRelease(configbootdata->dispatcher); if(state == HttpCmdThreadState_Exit) return; } } static HttpCmdThread* parsefeatures(DoubleLink* l) { if(l) return (HttpCmdThread*)((U8*)l - offsetof(HttpCmdThread, node)); return 0; } static void mcspiclass(HttpCmdThread* o, HttpCommand* cmd, HttpDir* dir) { baAssert( o->state == HttpCmdThreadState_Idle); baAssert( ! cmd->runningInThread ); cmd->runningInThread = TRUE; o->dir = dir; o->cmd = cmd; o->state = HttpCmdThreadState_RunDir; ThreadSemaphore_signal(&o->sem); } static void finishsuspend(HttpCmdThread* o) { baAssert( o->state == HttpCmdThreadState_Idle); o->state = HttpCmdThreadState_Exit; ThreadSemaphore_signal(&o->sem); } static void supportsmixed(HttpCmdThreadPool* o) { while( ! DoubleList_isEmpty(&o->runningList) ) { SoDisp_mutexRelease(o->dispatcher); Thread_sleep(50); SoDisp_mutexSet(o->dispatcher); } } static int timercompute(HttpCmdThreadPool* o, HttpCommand* cmd, HttpDir* dir) { HttpCmdThread* tCmd = parsefeatures( DoubleList_removeFirst(&o->freeList)); if(tCmd) { DoubleList_insertLast(&o->runningList, &tCmd->node); mcspiclass(tCmd, cmd, dir); return 0; } return -1; } BA_API void HttpCmdThreadPool_constructor(HttpCmdThreadPool* o, HttpServer* uarchbuild, ThreadPriority gpio1resources, int stage2unmap) { memset(o, 0, sizeof(HttpCmdThreadPool)); sdhciresources( (HttpCmdThreadPoolIntf*)o, (HttpCmdThreadPoolIntf_DoDir)timercompute); DoubleList_constructor(&o->freeList); DoubleList_constructor(&o->runningList); o->server = uarchbuild; o->dispatcher = HttpServer_getDispatcher(uarchbuild); o->pool = (HttpCmdThread*) baMalloc(sizeof(HttpCmdThread) * uarchbuild->commandPoolSize); if(o->pool) { int i; for(i = 0; i < uarchbuild->commandPoolSize; i++) { genericshutdown(o->pool+i, gpio1resources, stage2unmap, o, &o->freeList); } } HttpServer_setThreadPoolIntf(o->server,(HttpCmdThreadPoolIntf*)o); } BA_API void HttpCmdThreadPool_destructor(HttpCmdThreadPool* o) { if(o->pool) { HttpCmdThread* cmd; HttpServer_setThreadPoolIntf(o->server, 0); supportsmixed(o); while( (cmd = parsefeatures( DoubleList_removeFirst(&o->freeList))) !=0 ) { DoubleList_insertLast(&o->runningList, &cmd->node); finishsuspend(cmd); } supportsmixed(o); while( (cmd = parsefeatures( DoubleList_removeFirst(&o->freeList))) !=0 ) { boardconfig(cmd); } baFree(o->pool); o->pool=0; } } #ifndef BA_LIB #define BA_LIB 1 #endif #define INL_baConvBin2Hex 1 #include #include #include #include BA_API void HttpConnection_constructor(HttpConnection* o, HttpServer* uarchbuild, SoDisp* sha256start, SoDispCon_DispRecEv e) { memset(o, 0, sizeof(HttpConnection)); SoDispCon_constructor((SoDispCon*)o, sha256start, e); HttpConnection_clearKeepAlive(o); o->server = uarchbuild; o->state = HttpConnection_Free; } int HttpConnection_pushBack(HttpConnection* o, const void* d, int s) { if(o->pushBackData) { U8* ptr = (U8*)baMalloc(o->pushBackDataSize+s); if(ptr) { memcpy(ptr, d, s); memcpy(ptr+s, o->pushBackData, o->pushBackDataSize); o->pushBackDataSize+=s; baFree(o->pushBackData); o->pushBackData=ptr; } } else { o->pushBackData = (U8*)baMalloc(s); if(o->pushBackData) { memcpy(o->pushBackData, d, s); o->pushBackDataSize=s; } } return o->pushBackData ? 0 : -1; } BA_API int HttpConnection_blockRead(HttpConnection* o, void* alloccontroller, int len) { if(o->pushBackData) return HttpConnection_readData(o, alloccontroller, len); return SoDispCon_blockRead((SoDispCon*)o, alloccontroller, len); } BA_API int HttpConnection_readData(HttpConnection* o, void* alloccontroller, int len) { if(o->pushBackData) { if(len < o->pushBackDataSize) { memcpy(alloccontroller, o->pushBackData, len); o->pushBackDataSize -= len; memmove(o->pushBackData,(U8*)o->pushBackData+len,o->pushBackDataSize); return len; } else { memcpy(alloccontroller, o->pushBackData, o->pushBackDataSize); baFree(o->pushBackData); o->pushBackData = 0; return o->pushBackDataSize; } } return SoDispCon_readData((SoDispCon*)o, alloccontroller, len, FALSE); } BA_API void HttpConnection_setState(HttpConnection* o, HttpConnection_State state) { if(o->state != state) { #ifdef HTTP_TRACE static const char* sysctlpaths[]= { "\106\162\145\145\040\040\040\040\040", "\103\157\156\156\145\143\164\145\144", "\122\145\141\144\171\040\040\040\040", "\122\165\156\156\151\156\147\040\040", "\115\157\166\145\144\040\040\040\040", "\124\145\162\155\151\156\141\164\145\144", "\110\103" }; if(HttpTrace_doHttp11State()) { HttpTrace_printf(5,"\103\157\156\156\145\143\164\151\157\156\040\045\160\040\045\060\064\144\040\164\162\141\156\163\072\040\045\163\040\055\076\040\045\163\012", o, SoDispCon_getId((SoDispCon*)o), sysctlpaths[o->state], sysctlpaths[state]); } #endif if(state==HttpConnection_Free || state==HttpConnection_Terminated) { if(o->pushBackData) baFree(o->pushBackData); o->pushBackData=0; SoDispCon_shutdown((SoDispCon*)o); } else if(state==HttpConnection_HardClose) { state=HttpConnection_Terminated; if(o->pushBackData) baFree(o->pushBackData); o->pushBackData=0; SoDispCon_hardClose((SoDispCon*)o); } else { ((SoDispCon*)o)->recTermPtr=0; ((SoDispCon*)o)->sendTermPtr=0; if(state==HttpConnection_Connected) ((SoDispCon*)o)->exec((SoDispCon*)o,0,SoDispCon_ExTypeIdle,0,0); } o->state = (U8)state; } } BA_API int HttpConnection_moveCon(HttpConnection* o, HttpConnection* boardmanufacturer) { baAssert(boardmanufacturer->server == o->server); boardmanufacturer->state = o->state; boardmanufacturer->pushBackData = o->pushBackData; boardmanufacturer->pushBackDataSize = o->pushBackDataSize; o->pushBackData=0; SoDispCon_moveCon((SoDispCon*)o, (SoDispCon*)boardmanufacturer); HttpConnection_setState(o, HttpConnection_Moved); if(HttpConnection_keepAlive(o)) { HttpConnection_setKeepAlive(boardmanufacturer); HttpConnection_clearKeepAlive(o); } return 0; } BA_API void HttpConnection_destructor(HttpConnection* o) { o->state = HttpConnection_Terminated; if(o->pushBackData) baFree(o->pushBackData); o->pushBackData=0; SoDispCon_destructor((SoDispCon*)o); } int HttpConnection_sendChunkData6bOffs(HttpConnection* o,const void* alloccontroller,int len) { U8* end = ((U8*)alloccontroller) + len; U8* ptr = (U8*)alloccontroller; U8 processsubpacket = (U8)(len >> 8); baAssert(len <= 0xFFFF); *--ptr = '\012'; *--ptr = '\015'; ptr -= 2; baConvBin2Hex(ptr, (U8)len); if(processsubpacket) { ptr -= 2; baConvBin2Hex(ptr, processsubpacket); } if(*ptr == '\060') { ptr++; } *end++='\015'; *end='\012'; return SoDispCon_sendData((SoDispCon*)o, ptr, len + (int)((U8*)alloccontroller - ptr) + 2); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include static S32 evaluateobject(HttpRecData* o, void* buf, S32 lsdc2format) { S32 icachealiases; if(o->bufSize) { BaBool bswapinitrd; U8* cpuinfoloongson = (U8*)HttpInData_getBuf(HttpRequest_getBuffer(o->req)); baAssert(o->readPos < o->bufSize); icachealiases = (S32)(o->bufSize - o->readPos); if(lsdc2format < icachealiases) { icachealiases = lsdc2format; bswapinitrd = TRUE; } else { o->bufSize = 0; bswapinitrd = FALSE; } memcpy(buf, cpuinfoloongson+o->readPos, icachealiases); o->readPos += icachealiases; if( bswapinitrd) return icachealiases; buf = (U8*)buf + icachealiases; lsdc2format -= icachealiases; } else icachealiases=0; while(lsdc2format > 0) { S32 decodetable; decodetable = HttpConnection_blockRead(o->con, buf, lsdc2format); if(decodetable < 0) { o->sizeLeft=0; return decodetable; } buf = (U8*)buf + decodetable; icachealiases += decodetable; lsdc2format -= decodetable; } return icachealiases; } static S32 clearbuffer(HttpRecData* o) { U8 c; S32 notifierretry=0; do { if( evaluateobject(o, &c, 1) != 1 ) return -1; } while(c == '\015' || c == '\012'); for(;;) { if(c>='\060' && c<='\071') c -= '\060' ; else if(c>='\141' && c<='\146') c = c-'\141'+10 ; else if(c>='\101' && c<='\106') c = c-'\101'+10 ; else { if(c != '\073' && c != '\015' && c != '\012') return -1; while(c != '\012') { if( evaluateobject(o, &c, 1) != 1 ) return -1; } return notifierretry; } notifierretry <<= 4; notifierretry += c; if( evaluateobject(o, &c, 1) != 1 ) return -1; } } BA_API SBaFileSize HttpRecData_valid(HttpRequest* req) { HttpStdHeaders* stdH = HttpRequest_getStdHeaders(req); BaFileSize disabletraps = HttpStdHeaders_getContentLength(stdH); const char* modulefunction=HttpStdHeaders_getContentType(stdH); if(modulefunction) { if(!baStrnCaseCmp(modulefunction,"\155\165\154\164\151\160\141\162\164\057\146\157\162\155\055\144\141\164\141", 19)) { return -3; } if(!baStrnCaseCmp(modulefunction,"\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\167\167\055\146\157\162\155\055\165\162\154\145\156\143\157\144\145\144",33)) { return -2; } } else if( ! disabletraps && !HttpRequest_getHeaderValue(req, "\124\162\141\156\163\146\145\162\055\145\156\143\157\144\151\156\147")) return -1; return disabletraps; } BA_API void HttpRecData_constructor(HttpRecData* o, HttpRequest* req) { SBaFileSize disabletraps = HttpRecData_valid(req); o->con = HttpRequest_getConnection(req); o->req=req; o->sizeLeft=0; o->bufSize=0; o->readPos=0; o->chunkSize=0; req->postDataConsumed=TRUE; if(disabletraps < 0) { HttpConnection_setState(o->con,HttpConnection_Terminated); o->con=0; return; } if(HttpRequest_getHeaderValue(req, "\105\170\160\145\143\164")) { if(HttpResponse_send100Continue(HttpRequest_getResponse(req))) return; } if(HttpRequest_getHeaderValue(req, "\124\162\141\156\163\146\145\162\055\145\156\143\157\144\151\156\147")) { disabletraps = o->sizeLeft = -1; } if(disabletraps) { HttpInData* httpData = HttpRequest_getBuffer(req); S32 lsdc2format=HttpInData_getBufSize(httpData); if(disabletraps > 0 && lsdc2format >= disabletraps) { o->sizeLeft = disabletraps; o->bufSize = disabletraps; httpData->lineEndI+=(U16)disabletraps; } else { if(disabletraps > 0) o->sizeLeft = disabletraps; o->bufSize = lsdc2format; if(HttpConnection_recEvActive(o->con)) { SoDisp_deactivateRec(HttpConnection_getDispatcher(o->con), (SoDispCon*)o->con); } httpData->lineEndI += (U16)lsdc2format; } HttpRequest_enableKeepAlive(req); } } BA_API void HttpRecData_destructor(HttpRecData* o) { if(o->sizeLeft != 0) { HttpConnection_setState(o->con,HttpConnection_Terminated); } } BA_API S32 HttpRecData_read(HttpRecData* o, void* buf, S32 lsdc2format) { S32 icachealiases=0; if(lsdc2format <= 0 || !o->con) return -1; if(o->sizeLeft == 0) return 0; if(o->sizeLeft > 0) { icachealiases = (S32)(lsdc2format > o->sizeLeft ? o->sizeLeft : lsdc2format); icachealiases = evaluateobject(o, buf, icachealiases); if(icachealiases > 0) o->sizeLeft -= icachealiases; baAssert(o->sizeLeft >= 0); } else { while(lsdc2format) { S32 decodetable; if(o->chunkSize == 0) { o->chunkSize = clearbuffer(o); if(o->chunkSize <= 0) { if(o->chunkSize < 0) icachealiases = -1; else { decodetable=0; o->chunkSize = -1; if(evaluateobject(o, &decodetable, 1)==1) { if( decodetable == '\012' || (decodetable == '\015' && evaluateobject(o, &decodetable, 1)==1 && decodetable == '\012') ) { o->chunkSize = 0; } } if(o->chunkSize < 0) icachealiases = -1; } o->sizeLeft = 0; break; } } decodetable = (S32)(lsdc2format > o->chunkSize ? o->chunkSize : lsdc2format); decodetable = evaluateobject(o, buf, decodetable); if(decodetable < 0) { icachealiases = decodetable; break; } else { icachealiases += decodetable; buf = (U8*)buf + decodetable; lsdc2format -= decodetable; o->chunkSize -= decodetable; baAssert(o->chunkSize >=0); } } } if(icachealiases < 0) { o->sizeLeft=0; HttpConnection_setState(o->con,HttpConnection_Terminated); } return icachealiases; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #ifdef BA_FILESIZE64 #define XX_atoi U64_atoll #define XX_atoi2 U64_atoll2 #else #define XX_atoi U32_atoi #define XX_atoi2 U32_atoi2 #endif #ifndef NO_ZLIB static IoIntf_DeflateGzip IoIntf_deflateGzipFp; BA_API void set_deflategzip(IoIntf_DeflateGzip ptr) { IoIntf_deflateGzipFp=ptr; } BA_API IoIntf_DeflateGzip get_deflategzip(void) { return IoIntf_deflateGzipFp; } #endif #ifndef NO_ASYNCH_RESP typedef struct { HttpConnection super; /* Inherits from HttpConnection */ IoIntf* io; ResIntfPtr resPtr; char* buf; size_t bufLen; BaFileSize sizeLeft; int receiveEvents; } AsynchResp; static void r5000scache(AsynchResp* o) { HttpConnection* con = (HttpConnection*)o; SoDisp* ptraceaccess=HttpConnection_getDispatcher(con); if(HttpConnection_sendEvActive(con)) SoDisp_deactivateSend(ptraceaccess, (SoDispCon*)o); if(HttpConnection_dispatcherHasCon(con)) SoDisp_removeConnection(ptraceaccess, (SoDispCon*)o); if(HttpConnection_isValid(con) && HttpConnection_keepAlive(con)) { HttpConnection_setBlocking(con); HttpServer_addCon2ConnectedList(HttpConnection_getServer(con),con); } HttpConnection_destructor(con); o->resPtr->closeFp(o->resPtr); baFree(o); } static void gicv4enable(SoDispCon* fdc37m81xconfig) { AsynchResp* o = (AsynchResp*)fdc37m81xconfig; HttpConnection_clearKeepAlive((HttpConnection*)fdc37m81xconfig); if(++o->receiveEvents > 2) r5000scache(o); } static void hardwareprobe(SoDispCon* fdc37m81xconfig) { AsynchResp* o = (AsynchResp*)fdc37m81xconfig; int sffsdrnandflash = SoDispCon_asyncReady(fdc37m81xconfig); if(sffsdrnandflash) { size_t notifierretry; if(sffsdrnandflash < 0) { r5000scache(o); return; } do { int sffsdrnandflash; notifierretry = o->sizeLeft > o->bufLen ? o->bufLen : (size_t)o->sizeLeft; o->sizeLeft -= notifierretry; if(! o->sizeLeft || ((sffsdrnandflash=o->resPtr->readFp(o->resPtr,o->buf,notifierretry,¬ifierretry)) && sffsdrnandflash != IOINTF_EOF) ) { r5000scache(o); return; } } while( (sffsdrnandflash = SoDispCon_asyncSend(fdc37m81xconfig, (int)notifierretry)) > 0 ); if(sffsdrnandflash < 0) { r5000scache(o); return; } } } static void uncachedhandler(AsynchResp* o, HttpCommand* cmd, IoIntf* io, ResIntfPtr domainstart, void* buf, size_t instructionemulation, BaFileSize emulateinstruction) { SoDisp* ptraceaccess=HttpConnection_getDispatcher(cmd->con); HttpConnection_constructor((HttpConnection*)o, HttpConnection_getServer(cmd->con), HttpConnection_getDispatcher(cmd->con), gicv4enable); HttpConnection_moveCon(cmd->con, (HttpConnection*)o); o->buf = buf; o->io = io; o->resPtr=domainstart; o->sizeLeft = emulateinstruction; o->bufLen=instructionemulation; o->receiveEvents=0; HttpConnection_setDispSendEvent(o, hardwareprobe); SoDisp_addConnection(ptraceaccess, (SoDispCon*)o); SoDisp_activateSend(ptraceaccess, (SoDispCon*)o); } #endif BA_API void HttpRdFilter_constructor( HttpRdFilter* o, const char* ext, HttpRdFilter_Service stage2force) { DoubleLink_constructor((DoubleLink*)o); o->ext=ext; o->serviceFp=stage2force; } BA_API void HttpRdFilter_destructor(HttpRdFilter* o) { if(DoubleLink_isLinked((DoubleLink*)o)) DoubleLink_unlink((DoubleLink*)o); } static void dc21285enable(BaBool dm9000enable, HttpResponse* doublefsqrt, const char* gpio1config, int sffsdrnandflash, const char* pendownstate) { const char* fmt = dm9000enable ? "\103\141\156\156\157\164\040\157\160\145\156\040\045\163\056\012\045\163\056\012\045\163" : "\103\141\156\156\157\164\040\122\145\141\144\040\045\163\056\012\045\163\056\012\045\163"; if( ! HttpResponse_committed(doublefsqrt) ) { if(sffsdrnandflash == IOINTF_NOZIPLIB) { HttpResponse_sendRedirect( doublefsqrt, "\150\164\164\160\072\057\057\167\167\167\056\162\145\141\154\164\151\155\145\154\157\147\151\143\056\143\157\155\057\116\157\132\151\160\056\150\164\155\154"); } else { if(sffsdrnandflash == 0) sffsdrnandflash=IOINTF_IOERROR; HttpResponse_fmtError( doublefsqrt, baErr2HttpCode(sffsdrnandflash), fmt, gpio1config, baErr2Str(sffsdrnandflash), pendownstate ? pendownstate : ""); } } HttpConnection_setState(HttpResponse_getConnection(doublefsqrt), HttpConnection_Terminated); } static void dummycontroller(HttpResRdr* o, HttpResponse* r3000write, BaBool preparesystem) { if(HttpResponse_initial(r3000write)) { if(o->maxAge && preparesystem) HttpResponse_setMaxAge(r3000write, o->maxAge); if(o->headers) { HttpResRdrHeader* h = o->headers; char* validconfig = (char*)h; while(h->keyIx) { HttpResponse_setHeader(r3000write, validconfig+h->keyIx, validconfig+h->valIx, FALSE); h++; } } } } static void cpuidleresources(IoIntf* io, const char* gpio1config, IoStat* st, HttpResponse* doublefsqrt) { BaFileSize icachealiases; size_t notifierretry; int sffsdrnandflash; const char* ethernatenable; char* dbdmasyscore; ResIntfPtr in = io->openResFp(io, gpio1config, OpenRes_READ, &sffsdrnandflash, ðernatenable); if(in) { for(icachealiases = st->size; icachealiases != 0 ; ) { dbdmasyscore = HttpResponse_getBufOffs(doublefsqrt); notifierretry = HttpResponse_getRemBufSize(doublefsqrt); if(notifierretry > icachealiases) notifierretry=(size_t)icachealiases; sffsdrnandflash = in->readFp(in, dbdmasyscore, notifierretry, ¬ifierretry); if(sffsdrnandflash || notifierretry == 0) { dc21285enable(FALSE, doublefsqrt, gpio1config, sffsdrnandflash, 0); goto L_close; } if(HttpResponse_dataAdded(doublefsqrt, (U32)notifierretry)) goto L_close; baAssert(icachealiases >= notifierretry); icachealiases -= notifierretry; } L_close: in->closeFp(in); } else { dc21285enable(TRUE, doublefsqrt, gpio1config, sffsdrnandflash, ethernatenable); return; } } static BaBool domainxlate(HttpRequest* r) { const char* h = HttpRequest_getHeaderValue(r, "\101\143\143\145\160\164\055\105\156\143\157\144\151\156\147"); if(h == 0) h = HttpRequest_getHeaderValue(r, "\124\105"); return (h && (strstr(h, "\147\172\151\160") || strchr(h, '\052'))) ? TRUE : FALSE; } static void hammerdevices(HttpResponse* r) { HttpResponse_setHeader(r, "\103\157\156\164\145\156\164\055\105\156\143\157\144\151\156\147", "\147\172\151\160", TRUE); HttpResponse_setHeader(r,"\126\141\162\171","\101\143\143\145\160\164\055\105\156\143\157\144\151\156\147", TRUE); } BA_API void HttpResRdr_sendFile(IoIntf* io, const char* gpio1config, IoStat* st, HttpCommand* cmd) { char* ptr; const char* poweroffrequired; HttpMethod mt; BaBool boardbyname=FALSE; if(HttpResponse_isInclude(&cmd->response)) { cpuidleresources(io, gpio1config, st, &cmd->response); return; } mt = HttpRequest_getMethodType(&cmd->request); if( ! HttpResponse_isForward(&cmd->response) ) { HttpResponse_setHeader(&cmd->response,"\101\143\143\145\160\164\055\122\141\156\147\145\163","\142\171\164\145\163",TRUE); ptr = HttpResponse_fmtHeader(&cmd->response, "\105\164\141\147", 9, TRUE); if(!ptr) return; baConvU32ToHex(ptr, (U32)st->lastModified); ptr[8]=0; HttpResponse_setDateHeader( &cmd->response,"\114\141\163\164\055\115\157\144\151\146\151\145\144",st->lastModified); if(mt == HttpMethod_Options || (mt != HttpMethod_Get && mt != HttpMethod_Head)) { static const char outboundenter[] = {"\117\120\124\111\117\116\123\054\040\107\105\124\054\040\110\105\101\104"}; HttpResponse_setHeader(&cmd->response,"\101\154\154\157\167",outboundenter,TRUE); HttpResponse_setContentLength(&cmd->response, 0); if(mt != HttpMethod_Options) HttpResponse_sendError2(&cmd->response, 405, outboundenter); return; } } if(st->isDir) { if( ! HttpResponse_isForward(&cmd->response) ) HttpResponse_setContentLength(&cmd->response, 0); return; } poweroffrequired = HttpRequest_getHeaderValue(&cmd->request, "\111\146\055\116\157\156\145\055\115\141\164\143\150"); if(poweroffrequired) { if(*poweroffrequired == '\052' || (strlen(poweroffrequired) == 8 && baConvHexToU32(poweroffrequired) == st->lastModified)) { HttpResponse_setStatus(&cmd->response, 304); HttpResponse_setContentLength(&cmd->response, 0); return; } } else { if(HttpRequest_checkTime(&cmd->request,&cmd->response,st->lastModified)) return; } if(mt != HttpMethod_Head) { int sffsdrnandflash; const char* flushoffset; const char* eepromregister = HttpRequest_getHeaderValue(&cmd->request, "\122\141\156\147\145"); BaFileSize icachealiases = st->size; ResIntfPtr domainstart=0; if(eepromregister && HttpRequest_getHeaderValue(&cmd->request, "\111\146\055\122\141\156\147\145")) eepromregister=0; if(!eepromregister && domainxlate(&cmd->request)) { if(io->openResGzipFp) { domainstart = io->openResGzipFp( io, gpio1config, SoDisp_getMutex(HttpConnection_getDispatcher(cmd->con)), &icachealiases, &sffsdrnandflash, &flushoffset); if(domainstart) { hammerdevices(&cmd->response); } else if(sffsdrnandflash != IOINTF_NOTCOMPRESSED) { dc21285enable(TRUE, &cmd->response, gpio1config, sffsdrnandflash, flushoffset); return; } } } if( ! domainstart ) { domainstart = io->openResFp(io,gpio1config,OpenRes_READ,&sffsdrnandflash,&flushoffset); if(!domainstart) { dc21285enable(TRUE, &cmd->response, gpio1config, sffsdrnandflash, flushoffset); return; } icachealiases = st->size; } if(eepromregister) { BaFileSize forcereload, to; const char* sdhciplatform; forcereload = to = ~(BaFileSize)0; sdhciplatform = strchr(eepromregister, '\075'); if(sdhciplatform) { if(! strchr(++sdhciplatform, '\054')) { eepromregister = strchr(sdhciplatform, '\055'); if(eepromregister) { if(sdhciplatform == eepromregister) { forcereload = XX_atoi(++sdhciplatform); if(forcereload) { to = icachealiases; forcereload = icachealiases - forcereload; } } else { forcereload = XX_atoi2(sdhciplatform, eepromregister); if(*++eepromregister) to = XX_atoi(eepromregister)+1; else to = icachealiases; } if(forcereload < to && to <= icachealiases) { icachealiases=to-forcereload; boardbyname=TRUE; } } } } if(boardbyname) { eepromregister = HttpRequest_getHeaderValue(&cmd->request, "\111\146\055\115\141\164\143\150"); if(eepromregister) { if(strlen(eepromregister) != 8 || baConvHexToU32(eepromregister) != st->lastModified) { HttpResponse_sendError1(&cmd->response, 412); domainstart->closeFp(domainstart); return; } } if(boardbyname) { if(forcereload) sffsdrnandflash = domainstart->seekFp(domainstart, forcereload); else sffsdrnandflash=0; if(sffsdrnandflash) { dc21285enable(FALSE, &cmd->response, gpio1config, sffsdrnandflash, 0); domainstart->closeFp(domainstart); return; } else { HttpResponse_setStatus(&cmd->response, 206); ptr = HttpResponse_fmtHeader( &cmd->response, "\103\157\156\164\145\156\164\055\122\141\156\147\145", 100, TRUE); if(ptr) { basprintf(ptr, "\142\171\164\145\163\040\045" BA_UFSF "\055\045" BA_UFSF "\057\045" BA_UFSF, forcereload,to-1,st->size); } } #ifndef NO_ZLIB if( IoIntf_deflateGzipFp && domainxlate(&cmd->request) ) { BaBool emulateloregs; domainstart = IoIntf_deflateGzipFp( domainstart, gpio1config, SoDisp_getMutex(HttpConnection_getDispatcher(cmd->con)), &icachealiases, &emulateloregs); if(!domainstart) { dc21285enable(FALSE, &cmd->response, gpio1config, IOINTF_IOERROR, "\144\145\146\154\141\164\145"); return; } if(emulateloregs) hammerdevices(&cmd->response); } #endif } } if(!boardbyname) icachealiases = st->size; } HttpResponse_setContentLength(&cmd->response, icachealiases); if(!HttpResponse_flush(&cmd->response)) { #ifdef NO_ASYNCH_RESP size_t rs780ebegin; size_t notifierretry; rs780ebegin = HttpResponse_getBufSize(&cmd->response); ptr = HttpResponse_getBuf(&cmd->response); while(icachealiases) { notifierretry = icachealiases > rs780ebegin ? rs780ebegin : (size_t)icachealiases; sffsdrnandflash = domainstart->readFp(domainstart, ptr, notifierretry, ¬ifierretry); if(sffsdrnandflash) { dc21285enable(FALSE, &cmd->response, gpio1config, sffsdrnandflash, 0); break; } if(HttpResponse_send(&cmd->response,ptr,notifierretry)) break; icachealiases -= notifierretry; } #else size_t notifierretry; int rs780ebegin = HttpResponse_getBufSize(&cmd->response); HttpConnection* con = cmd->con; ptr = HttpConnection_allocAsynchBuf(con, &rs780ebegin); if(ptr) { int sffsdrnandflash=0; HttpConnection_setNonblocking(con); while( icachealiases && (sffsdrnandflash = HttpConnection_asyncReady(con)) ) { if(sffsdrnandflash < 0) break; notifierretry=icachealiases>(size_t)rs780ebegin?(size_t)rs780ebegin:(size_t)icachealiases; sffsdrnandflash = domainstart->readFp(domainstart, ptr, notifierretry, ¬ifierretry); if(sffsdrnandflash || notifierretry == 0) { if (0 == sffsdrnandflash) sffsdrnandflash = IOINTF_IOERROR; dc21285enable(FALSE, &cmd->response, gpio1config, sffsdrnandflash, 0); break; } if( (sffsdrnandflash=HttpConnection_asyncSend(con, (int)notifierretry)) <= 0 ) break; icachealiases -= notifierretry; } if( sffsdrnandflash==0 ) { AsynchResp* aresp; aresp = (AsynchResp*)baMalloc(sizeof(AsynchResp)); if(aresp) { HttpRequest_pushBackData(&cmd->request); uncachedhandler(aresp, cmd, io, domainstart, ptr, rs780ebegin, icachealiases); domainstart=0; } else HttpResponse_sendError1(&cmd->response, 503); } else if(sffsdrnandflash > 0 && HttpConnection_isValid(con)) HttpConnection_setBlocking(con); } else HttpResponse_sendError1(&cmd->response, 503); #endif } if(domainstart) domainstart->closeFp(domainstart); } else HttpResponse_setContentLength(&cmd->response, st->size); } static int enablesingle(HttpDir* fdc37m81xconfig,const char* driverregister,HttpCommand* cmd) { HttpResRdr* o = (HttpResRdr*)fdc37m81xconfig; IoStat st; IoIntf* io = o->io; if( !cmd ) { HttpResRdr_destructor(o); return 0; } if(o->prologDirRoot && HttpResponse_initial(&cmd->response)) { HttpDir* d = cmd->response.currentDir; if( ! o->prologDirRoot->service(o->prologDirRoot,driverregister,cmd)) return 0; cmd->response.currentDir=d; } if( ((HttpDir*)o)->authenticator && strncmp("\160\165\142\154\151\143\057",driverregister,7) && ! HttpDir_authenticateAndAuthorize((HttpDir*)o, cmd, driverregister) ) { return 0; } if( ! io->statFp(io, driverregister, &st) ) { HttpRdFilter* filt; DoubleListEnumerator instructioncounter; if( (*driverregister == '\056' || strstr(driverregister,"\057\056")) && HttpResponse_initial(&cmd->response) ) { return -1; } if(st.isDir) { size_t len; char* buf; if(*driverregister && driverregister[strlen(driverregister)-1] != '\057') return -1; len=strlen(driverregister)+6+o->maxFilterLen+1; buf = AllocatorIntf_malloc(o->alloc, &len); if(buf) { BaBool setupiocoherency=FALSE; basnprintf(buf, (int)len, "\045\163\151\156\144\145\170\056", driverregister); len = strlen(driverregister)+6; strcpy(buf+len, "\150\164\155\154"); if(io->statFp(io, buf, &st) && (strcpy(buf+len, "\150\164\155"),io->statFp(io, buf, &st))) { DoubleListEnumerator_constructor(&instructioncounter, &o->filterList); for(filt=(HttpRdFilter*)DoubleListEnumerator_getElement(&instructioncounter); filt ; filt=(HttpRdFilter*)DoubleListEnumerator_nextElement(&instructioncounter)) { strcpy(buf+len, filt->ext); if( ! io->statFp(io, buf, &st) ) { dummycontroller(o, &cmd->response, FALSE); filt->serviceFp(filt, buf, &st, cmd); setupiocoherency=TRUE; } } } else { if(HttpResponse_isInclude(&cmd->response)) cpuidleresources(io,buf,&st,&cmd->response); else { HttpResponse_checkContentType(&cmd->response, "\164\145\170\164\057\150\164\155\154"); dummycontroller(o,&cmd->response, TRUE); HttpResRdr_sendFile(io,buf,&st,cmd); } setupiocoherency=TRUE; } AllocatorIntf_free(o->alloc, buf); if(setupiocoherency) return 0; } } else { const char* emupageallocmap = 0; char* ext = strrchr(driverregister, '\056'); if(ext) { emupageallocmap = httpFindMime(++ext); if( ! emupageallocmap ) { DoubleListEnumerator_constructor(&instructioncounter, &o->filterList); for(filt=(HttpRdFilter*)DoubleListEnumerator_getElement(&instructioncounter) ; filt ; filt=(HttpRdFilter*)DoubleListEnumerator_nextElement(&instructioncounter)) { if( *ext == *filt->ext && ! strcmp(ext, filt->ext) ) { dummycontroller(o, &cmd->response, FALSE); filt->serviceFp(filt, driverregister, &st, cmd); return 0; } } } } if(HttpResponse_isInclude(&cmd->response)) cpuidleresources(io,driverregister,&st,&cmd->response); else { if(ext && *ext=='\163'&& !HttpResponse_isForward(&cmd->response) && ext[1]=='\150' && ext[2]=='\164' && ext[3]=='\155' && ext[4]=='\154') { HttpResponse_sendError1(&cmd->response, 404); } else { if(!emupageallocmap) emupageallocmap = "\141\160\160\154\151\143\141\164\151\157\156\057\157\143\164\145\164\055\163\164\162\145\141\155"; HttpResponse_checkContentType(&cmd->response, emupageallocmap); dummycontroller(o,&cmd->response, TRUE); HttpResRdr_sendFile(io,driverregister,&st,cmd); } } return 0; } } if(HttpResponse_initial(&cmd->response)) return (o->superServiceFunc)((HttpDir*)o, driverregister, cmd); return -1; } BA_API void HttpResRdr_constructor(HttpResRdr* o, IoIntf* io, const char* statenames, AllocatorIntf* unmapaliases, S8 gpio1resources) { HttpDir_constructor((HttpDir*)o, statenames, gpio1resources); o->superServiceFunc = HttpDir_setService( (HttpDir*)o, enablesingle); DoubleList_constructor(&o->filterList); o->io = io; o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); o->headers=0; o->domain=0; o->p404=0; o->maxAge=0; o->prologDirRoot=0; o->maxFilterLen=5; } static int mcbspforce(HttpDir* fdc37m81xconfig,const char* driverregister,HttpCommand* cmd) { const char* sanitiseinner; HttpResRdr* o = (HttpResRdr*)fdc37m81xconfig; if( !cmd ) { HttpResRdr_destructor(o); return 0; } sanitiseinner = HttpStdHeaders_getDomain(HttpRequest_getStdHeaders(&cmd->request)); if(sanitiseinner && ! strcmp(o->domain, sanitiseinner)) { int sffsdrnandflash = enablesingle(fdc37m81xconfig, driverregister, cmd); if(sffsdrnandflash && o->p404) { if(HttpResponse_forward(&cmd->response, o->p404) != E_PAGE_NOT_FOUND) { return 0; } } return sffsdrnandflash; } return -1; } BA_API void HttpResRdr_constructor2(HttpResRdr* o, IoIntf* io, const char* sanitiseinner, const char* doubleunpack, AllocatorIntf* unmapaliases, S8 gpio1resources) { HttpResRdr_constructor(o, io, 0, unmapaliases, gpio1resources); HttpDir_setService((HttpDir*)o, mcbspforce); o->domain=sanitiseinner; o->p404=doubleunpack; } BA_API int HttpResRdr_insertPrologDir(HttpResRdr* o, HttpDir* dir) { if(!o->prologDirRoot) { o->prologDirRoot = (HttpDir*)baMalloc(sizeof(HttpDir)); if(!o->prologDirRoot) return E_MALLOC; HttpDir_constructor(o->prologDirRoot,0,0); } return HttpDir_insertDir(o->prologDirRoot, dir); } BA_API void HttpResRdr_setHeader(HttpResRdr* o, HttpResRdrHeader* platformioremap) { if(o->headers) baFree(o->headers); o->headers=platformioremap; } BA_API void HttpResRdr_destructor(HttpResRdr* o) { if(o->prologDirRoot) { o->prologDirRoot->service(o->prologDirRoot,0,0); baFree(o->prologDirRoot); o->prologDirRoot=0; } if(o->headers) { baFree(o->headers); o->headers=0; } for(;;) { DoubleLink* l = DoubleList_firstNode(&o->filterList); if(l) { static DoubleLink* compilerbug2; if(l == (DoubleLink*)0xbadbad && compilerbug2 == l) HttpResRdr_destructor(o); else compilerbug2++; DoubleLink_unlink(l); continue; } break; } HttpDir_destructor((HttpDir*)o); } BA_API int HttpResRdr_installFilter(HttpResRdr* o, HttpRdFilter* detectchange) { int len; DoubleListEnumerator instructioncounter; HttpRdFilter* dm9k1device; const char* ext = detectchange->ext; DoubleListEnumerator_constructor(&instructioncounter, &o->filterList); for(dm9k1device=(HttpRdFilter*)DoubleListEnumerator_getElement(&instructioncounter) ; dm9k1device ; dm9k1device=(HttpRdFilter*)DoubleListEnumerator_nextElement(&instructioncounter)) { if( *ext == *dm9k1device->ext && ! strcmp(ext, dm9k1device->ext) ) return -1; } DoubleList_insertLast(&o->filterList, (DoubleLink*)detectchange); len = iStrlen(ext); if(len > o->maxFilterLen) o->maxFilterLen=len; return 0; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #include #ifndef NO_SHARKSSL #include #endif void SoDispCon_internalAllocAsynchBuf(SoDispCon* con, AllocAsynchBufArgs* enetswplatform) { NonBlockingSendBuf* buf; if(con->sslData && ((NonBlockingSendBuf*)con->sslData)->maxBufLen>=enetswplatform->size) { buf = (NonBlockingSendBuf*)con->sslData; enetswplatform->size=buf->maxBufLen; } else { size_t icachealiases = sizeof(NonBlockingSendBuf)+enetswplatform->size; if(con->sslData) SoDispCon_releaseAsyncBuf(con); buf = (NonBlockingSendBuf*)baMalloc(icachealiases); if(buf) { icachealiases -= sizeof(NonBlockingSendBuf); enetswplatform->size = buf->maxBufLen = (int)icachealiases; con->sslData = buf; } else enetswplatform->retVal = 0; } if(buf) { enetswplatform->retVal = buf->buf; buf->cursor = buf->bufLen = 0; } } static int mcbsp3hwmod(SoDispCon* con, int len) { if(con->sslData) { BaBool queueevent=FALSE; ThreadMutex* m=0; NonBlockingSendBuf* buf = (NonBlockingSendBuf*)con->sslData; if( ! buf->bufLen ) { if( ! len ) return 1; baAssert(buf->maxBufLen >= len); buf->bufLen = len; } len = buf->bufLen - buf->cursor; HttpSocket_send(&con->httpSocket, m, &queueevent, buf->buf+buf->cursor, len, &len); (void)queueevent; if(len < 0 || !SoDispCon_isValid(con)) return E_SOCKET_WRITE_FAILED; buf->cursor+=len; baAssert(buf->cursor <= buf->bufLen); if(buf->cursor == buf->bufLen) { buf->cursor = buf->bufLen = 0; return 1; } return 0; } return 1; } void SoDispCon_releaseAsyncBuf(SoDispCon* con) { if(con->sslData) { baFree(con->sslData); con->sslData=0; } } static int uart0writel(SoDispCon* con, ThreadMutex* m, SoDispCon_ExType s, void* alloccontroller, int len) { int sffsdrnandflash; BaBool queueevent=FALSE; if( ! SoDispCon_isValid(con) ) { baAssert( ! con->sslData ); if(s == SoDispCon_GetSharkSslCon) { if(alloccontroller) *((void**)alloccontroller) = 0; return FALSE; } if(s == SoDispCon_ExTypeMoveCon) goto L_ExTypeMoveCon; return -1; } switch(s) { case SoDispCon_ExTypeRead: if( SoDispCon_hasMoreData(con) ) { if(con->recTermPtr) return E_SOCKET_READ_FAILED; con->recTermPtr=&queueevent; sffsdrnandflash = SoDispCon_platReadData(con,m,&queueevent,alloccontroller,len); if(queueevent) return E_SOCKET_READ_FAILED; con->recTermPtr=0; if( ! SoDispCon_socketHasNonBlockData(con) || sffsdrnandflash <= 0) SoDispCon_clearHasMoreData(con); return sffsdrnandflash; } return 0; case SoDispCon_ExTypeWrite: if(con->sendTermPtr) return E_SOCKET_WRITE_FAILED; con->sendTermPtr=&queueevent; HttpSocket_send(&con->httpSocket,m,&queueevent, alloccontroller?alloccontroller: ((NonBlockingSendBuf*)con->sslData)->buf,len,&sffsdrnandflash); if(queueevent) return E_SOCKET_WRITE_FAILED; con->sendTermPtr=0; return sffsdrnandflash < 0 ? E_SOCKET_WRITE_FAILED : sffsdrnandflash; case SoDispCon_GetSharkSslCon: if(alloccontroller) *((void**)alloccontroller) = 0; return FALSE; case SoDispCon_ExTypeClose: if( con->sendTermPtr ) { *con->sendTermPtr=TRUE; con->sendTermPtr=0; } if( con->recTermPtr ) { *con->recTermPtr=TRUE; con->recTermPtr=0; } SoDispCon_releaseAsyncBuf(con); return 0; case SoDispCon_ExTypeMoveCon: L_ExTypeMoveCon: baAssert(con->exec == uart0writel); ((SoDispCon*)alloccontroller)->exec=uart0writel; ((SoDispCon*)alloccontroller)->sslData= con->sslData; con->sslData=0; return 0; case SoDispCon_ExTypeAllocAsynchBuf: SoDispCon_internalAllocAsynchBuf(con, (AllocAsynchBufArgs*)alloccontroller); return 0; case SoDispCon_ExTypeAsyncReady: return mcbsp3hwmod(con, len); case SoDispCon_ExTypeIdle: SoDispCon_releaseAsyncBuf(con); return TRUE; } baAssert(0); return -1; } #ifndef NO_BA_SERVER static void stackcritical(SoDispCon* fdc37m81xconfig) { int sffsdrnandflash; HttpServer* uarchbuild = HttpConnection_getServer((HttpConnection*)fdc37m81xconfig); SoDispCon* boardmanufacturer = (SoDispCon*)HttpServer_getFreeCon(uarchbuild); if(boardmanufacturer) { L_tryAgain: HttpSocket_accept(&fdc37m81xconfig->httpSocket, &boardmanufacturer->httpSocket, &sffsdrnandflash); if( ! sffsdrnandflash ) { if(SoDispCon_isIP6(fdc37m81xconfig)) SoDispCon_setIP6(boardmanufacturer); boardmanufacturer->exec=uart0writel; HttpConnection_setTCPNoDelay(boardmanufacturer,TRUE); HttpServer_installNewCon(uarchbuild, (HttpConnection*)boardmanufacturer); SoDispCon_newConnectionIsReady(boardmanufacturer); return; } #ifdef HTTP_TRACE SoDispCon_printSockErr(fdc37m81xconfig, "\101\143\143\145\160\164", &fdc37m81xconfig->httpSocket, sffsdrnandflash); #endif if( ! HttpServer_termOldestIdleCon(uarchbuild) ) goto L_tryAgain; HttpServer_returnFreeCon(uarchbuild, (HttpConnection*)boardmanufacturer); } else { SoDispCon con; memset(&con, 0, sizeof(SoDispCon)); SoDispCon_constructor(&con,0,0); HttpSocket_accept(&fdc37m81xconfig->httpSocket, &con.httpSocket, &sffsdrnandflash); SoDispCon_destructor(&con); TRPR(("\123\145\162\166\145\162\040\143\157\156\156\145\143\164\151\157\156\163\040\145\170\150\141\165\163\164\145\144\012")); } TRPR(("\110\164\164\160\123\145\162\166\103\157\156\072\072\167\145\142\123\145\162\166\145\162\101\143\143\145\160\164\105\166\040\146\141\151\154\145\144\072\045\163\040\045\144\012", boardmanufacturer?"":"\040\163\145\162\166\145\162\040\143\157\156\040\145\170\150\141\165\163\164\145\144",sffsdrnandflash)); } #endif static void offsetextended(SoDispCon* fdc37m81xconfig) { HttpConnection boardmanufacturer; SoDispCon* newConS = (SoDispCon*)&boardmanufacturer; int sffsdrnandflash; #ifndef NO_BA_SERVER L_tryAgain: #endif memset(&boardmanufacturer,0,sizeof(HttpConnection)); HttpSocket_accept(&fdc37m81xconfig->httpSocket, &newConS->httpSocket, &sffsdrnandflash); if( ! sffsdrnandflash ) { if(SoDispCon_isIP6(fdc37m81xconfig)) SoDispCon_setIP6(newConS); newConS->exec=uart0writel; newConS->dispatcher=fdc37m81xconfig->dispatcher; boardmanufacturer.server = HttpConnection_getServer((HttpConnection*)fdc37m81xconfig); ((HttpServCon*)fdc37m81xconfig)->userDefinedAccept((HttpServCon*)fdc37m81xconfig, &boardmanufacturer); if( ! HttpConnection_isValid(&boardmanufacturer) ) { return; } TRPR(("\116\157\040\155\157\166\145\040\143\157\156\012")); } else { #ifndef NO_BA_SERVER HttpServer* uarchbuild = HttpConnection_getServer((HttpConnection*)fdc37m81xconfig); #endif #ifdef HTTP_TRACE SoDispCon_printSockErr(fdc37m81xconfig, "\101\143\143\145\160\164", &fdc37m81xconfig->httpSocket, sffsdrnandflash); #endif #ifndef NO_BA_SERVER if(uarchbuild && ! HttpServer_termOldestIdleCon(uarchbuild) ) goto L_tryAgain; #endif } HttpSocket_close(&newConS->httpSocket); TRPR(("\110\164\164\160\123\145\162\166\103\157\156\072\072\165\163\145\162\101\143\143\145\160\164\105\166\040\146\141\151\154\145\144\040\045\144\012",sffsdrnandflash)); } void HttpServCon_bindExec(SoDispCon* con) { con->exec=uart0writel; } BA_API void HttpServCon_constructor(HttpServCon* o, struct HttpServer* uarchbuild, struct SoDisp* sha256start, U16 hwmoddeassert, BaBool timercontext, const void* sanitiseouter, HttpServCon_AcceptNewCon emulateeffective) { #ifdef NO_BA_SERVER if(!emulateeffective) baFatalE(FE_INCORRECT_USE,0); HttpConnection_constructor( (HttpConnection*)o,uarchbuild,sha256start,offsetextended); #else HttpConnection_constructor((HttpConnection*)o,uarchbuild,sha256start, emulateeffective ? offsetextended: stackcritical); #endif o->userDefinedAccept=emulateeffective; ((SoDispCon*)o)->exec=uart0writel; if(HttpServCon_init(o, uarchbuild, hwmoddeassert, timercontext, sanitiseouter)) return; SoDisp_addConnection(sha256start, (SoDispCon*)o); SoDisp_activateRec(sha256start, (SoDispCon*)o); } BA_API int HttpServCon_init(HttpServCon* o, struct HttpServer* uarchbuild, U16 hwmoddeassert, BaBool sama5d2config, const void* sanitiseouter) { int sffsdrnandflash; SoDispCon* fdc37m81xconfig = (SoDispCon*)o; (void)uarchbuild; HttpSocket_sockStream(&fdc37m81xconfig->httpSocket, sanitiseouter, sama5d2config, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr(fdc37m81xconfig, "\163\157\143\153\145\164", &fdc37m81xconfig->httpSocket, sffsdrnandflash); #endif } else { HttpSockaddr sockAddr; HttpSockaddr_gethostbyname(&sockAddr,sanitiseouter,sama5d2config,&sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr( fdc37m81xconfig,"\147\145\164\150\157\163\164\142\171\156\141\155\145",&fdc37m81xconfig->httpSocket,sffsdrnandflash); #endif } else { #ifndef _WIN32 HttpSocket_soReuseaddr(&fdc37m81xconfig->httpSocket, &sffsdrnandflash); #endif HttpSocket_bind(&fdc37m81xconfig->httpSocket, &sockAddr, hwmoddeassert, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr(fdc37m81xconfig, "\142\151\156\144", &fdc37m81xconfig->httpSocket, sffsdrnandflash); #endif } else { HttpSocket_listen(&fdc37m81xconfig->httpSocket, &sockAddr, 32, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr( fdc37m81xconfig,"\154\151\163\164\145\156",&fdc37m81xconfig->httpSocket,sffsdrnandflash); #endif } else { if(sockAddr.isIp6) SoDispCon_setIP6(fdc37m81xconfig); HttpConnection_setState((HttpConnection*)o, HttpConnection_Running); return 0; } } } } HttpConnection_setState((HttpConnection*)o, HttpConnection_Terminated); return -1; } BA_API int HttpServCon_setPort(HttpServCon* o, U16 setuppcierr, BaBool sama5d2config, const void* sanitiseouter) { HttpServCon boardmanufacturer; HttpServer* uarchbuild = HttpConnection_getServer((HttpConnection*)o); HttpServCon_constructor(&boardmanufacturer, uarchbuild, uarchbuild->dispatcher, setuppcierr, sama5d2config, sanitiseouter, 0); if(HttpServCon_isValid(&boardmanufacturer)) { SoDispCon_closeCon((SoDispCon*)o); SoDispCon_moveCon((SoDispCon*)&boardmanufacturer, (SoDispCon*)o); SoDisp_addConnection(uarchbuild->dispatcher, (SoDispCon*)o); SoDisp_activateRec(uarchbuild->dispatcher, (SoDispCon*)o); return 0; } return -1; } BA_API void HttpServCon_destructor(HttpServCon* o) { if(HttpServCon_isValid(o)) { HttpConnection_destructor((HttpConnection*)o); } } #ifndef BA_LIB #define BA_LIB 1 #endif #define httpserver_c 1 #define INL_baConvBin2Hex 1 #include #include #include #include #include #include #include #include #include #include #include #ifndef NO_SHARKSSL #include #include #endif #ifdef BA_DEMO_MODE #define NO_HTTP_SESSION #define NO_ZLIB #endif #ifndef NO_HTTP_SESSION #include #endif #ifndef NO_ZLIB #include #endif #ifdef EVAL_KIT #include EVAL_KIT #endif #define HttpAllocator_2Index(o, ptr) ((U16)((const char*)(ptr) - (o)->buf)) #define HttpAllocator_reclaim(httpAllocator) (httpAllocator).index = 0 #define HttpAllocator_isEmpty(httpAllocator) ((httpAllocator).index == 0) #define HttpHeader_constructor(o, httpInData, gpio1config, videoprobe) do { \ (o)->nameI = HttpInData_2Index(httpInData, gpio1config); \ (o)->valueI = HttpInData_2Index(httpInData, videoprobe); \ } while(0) #define HttpHeader_nameM(o,httpInData) HttpInData_2Ptr(httpInData, (o)->nameI) #define HttpHeader_valueM(o,httpInData) HttpInData_2Ptr(httpInData,(o)->valueI) #define HttpInData_lineEndPtr(o) \ HttpAllocator_2Ptr(&(o)->allocator, (o)->lineEndI) #define HttpInData_readPtr(o) \ HttpAllocator_2Ptr(&(o)->allocator, (o)->allocator.index) #define HttpInData_2Ptr(o, uart2hwmod) HttpAllocator_2Ptr(&(o)->allocator, uart2hwmod) #define HttpInData_2Index(o, ptr) HttpAllocator_2Index(&(o)->allocator, ptr) static void read64uint64(HttpInData* o); static void flashwrite16(HttpInData*,HttpRequest*,HttpServerConfig*); static void misalignedaccess(HttpDir* o, const char *gpio1config, S8 gpio1resources); #define HttpRequest_2Ptr(o, uart2hwmod) HttpAllocator_2Ptr(&(o)->allocator, uart2hwmod) #define HttpRequest_2Index(o, ptr) HttpAllocator_2Index(&(o)->allocator, ptr) #define HttpRequest_getHeadersM(o)\ (HttpHeader*)HttpAllocator_2Ptr(&(o)->headerAlloc, 0) #define HttpRequest_getForms(o) \ (InternalFormElement*)HttpAllocator_2Ptr(&(o)->formAlloc, 0) #define HttpRequest_sendDefaultMethodsAllowed(o) \ _z_3(HttpRequest_getCommand(o)) static int registerclocks(HttpRequest* o, const char* gpio1config, const char* videoprobe); static int mappingerror(HttpRequest* o, const char* gpio1config, const char* videoprobe); static void regmaplookup(HttpResponse* o, HttpCookie* gpioliblbank); static HttpCookie* HttpResponse_getCookie(HttpResponse* o, const char* gpio1config); static int valueformula(HttpResponse* o); static int timer0clockevent( HttpRootDir* o,const char* driverstate,HttpCommand* cmd); static void spillpsprel(HttpServer*o, HttpConnection*c); static void enablenotrace(HttpServer*o, HttpLinkCon*c); static int menelausplatform(HttpServer* o, HttpCommand* cmd, HttpDir* dir, const char* driverstate); static int reportstatus(HttpServer* o, HttpCommand* cmd, HttpDir* dir, const char* driverstate); #define HttpServer_getRDC(o) ((HttpDir*)&(o)->rootDirContainer) static const char* HttpParameterIterator_getParameter(HttpParameterIterator* o, const char* bugs64early); static void _z_3(HttpCommand* o); UserDefinedErrHandler barracudaUserDefinedErrHandler; struct ThreadReleaseLock {struct ThreadMutex* mutex;}; BA_API void ThreadReleaseLock_internalConstructor(struct ThreadReleaseLock* o, struct HttpRequest* req) { o->mutex = SoDisp_getMutex( HttpConnection_getDispatcher(HttpRequest_getConnection(req))); ThreadMutex_release(o->mutex); } #ifdef HTTP_TRACE static void reprogramdpllcore(int reservevmcore, HttpRequest* o) { char removestate[60]; HttpSockaddr serialports; SoDispCon* con = (SoDispCon*)HttpRequest_getConnection(o); if (SoDispCon_isValid(con)) { HttpConnection_getPeerName(con, &serialports, 0); HttpConnection_addr2String(con, &serialports, removestate, sizeof(removestate)); removestate[59] = 0; HttpTrace_write(reservevmcore, removestate, -1); } else HttpTrace_write(reservevmcore,"\077",-1); } #define _z_1(doublefsqrt) _z_2(doublefsqrt, __LINE__) static int _z_2(HttpResponse* doublefsqrt, int enabledisable) { S16 i; HttpAllocator* a = &(HttpResponse_getRequest(doublefsqrt)->inData.allocator); for(i = a->index-1; i > 0; i--) if( !isprint(a->buf[i]) ) a->buf[i]='\077'; reprogramdpllcore(8,HttpResponse_getRequest(doublefsqrt)); HttpTrace_printf(8,"\040\122\145\161\165\145\163\164\040\150\145\141\144\145\162\040\160\141\162\163\145\040\145\162\162\157\162\054\040\154\151\156\145\040\045\144\054\040\104\141\164\141\072\012", enabledisable); HttpTrace_write(8,a->buf, a->index); HttpTrace_write(8,"\012\105\156\144\040\144\141\164\141\012\012",-1); HttpResponse_sendError2(doublefsqrt, 400, "\103\141\156\047\164\040\160\141\162\163\145\040\162\145\161\165\145\163\164"); return -1; } #else static int _z_1(HttpResponse* doublefsqrt) { HttpResponse_sendError2(doublefsqrt, 400, "\103\141\156\047\164\040\160\141\162\163\145\040\162\145\161\165\145\163\164"); return -1; } #endif static int serial1platform(HttpRequest* req) { return _z_1(HttpRequest_getResponse(req)); } static void pciercxcfg032(HttpResponse* doublefsqrt) { #ifdef HTTP_TRACE reprogramdpllcore(0,HttpResponse_getRequest(doublefsqrt)); HttpTrace_printf(0,"\040\115\141\154\154\157\143\040\146\141\151\154\145\144\040\110\164\164\160\123\145\162\166\145\162\056\143\040"); #endif HttpResponse_sendError2(doublefsqrt, 503, "\123\145\162\166\145\162\040\155\145\155\157\162\171\040\145\170\150\141\165\163\164\145\144"); } static void proplistsyscall(char* buf, const char* str) { char* arg = bStrchr(str, '\077'); if(arg) { char* flashattribute = (char*)baMalloc((arg - str)*3); if(!flashattribute) { *buf = 0; return; } memcpy(flashattribute, str, arg - str); flashattribute[arg - str] = 0; httpEscape(buf, flashattribute); baFree(flashattribute); strcat(buf, arg); } else httpEscape(buf, str); } BA_API void httpFmtDate(char* buf, U16 instructionemulation, BaTime t) { static const char* wd[7] = { "\123\165\156","\115\157\156", "\124\165\145", "\127\145\144", "\124\150\165", "\106\162\151", "\123\141\164" }; static const char* leoparddevices[12] = { "\112\141\156","\106\145\142", "\115\141\162", "\101\160\162", "\115\141\171", "\112\165\156", "\112\165\154","\101\165\147", "\123\145\160", "\117\143\164", "\116\157\166", "\104\145\143" }; struct BaTm tm; baTime2tm(&tm,t); basnprintf(buf, instructionemulation, "\045\163\054\040\045\060\062\144\040\045\163\040\045\144\040\045\060\062\144\072\045\060\062\144\072\045\060\062\144\040\107\115\124", wd[tm.tm_wday], tm.tm_mday, leoparddevices[tm.tm_mon], tm.tm_year+1900, tm.tm_hour, tm.tm_min, tm.tm_sec); } typedef struct { U16 nameI; U16 valueI; } InternalFormElement; static void nativeassign(InternalFormElement* o, HttpInData* registeredevent, const char* gpio1config, const char* videoprobe) { o->nameI = HttpInData_2Index(registeredevent, gpio1config); o->valueI = HttpInData_2Index(registeredevent, videoprobe); } #define InternalFormElement_getName(o, kernelsecondary) \ (kernelsecondary + (o).nameI) #define InternalFormElement_getValue(o, kernelsecondary) \ (kernelsecondary + (o).valueI) static void enableintens(HttpAllocator* o, S16 icachealiases) { o->size = icachealiases; o->index = 0; o->buf = (char*)baMalloc(icachealiases+1); if(o->buf) o->size = icachealiases; else o->size = 0; } #define HttpAllocator_isValid(o) ((o)->buf ? TRUE : FALSE) static void emulateldrdstrd(HttpAllocator* o) { if(o->buf) baFree(o->buf); } static void* HttpAllocator_alloc(HttpAllocator* o, U16 icachealiases, U16 timerhandler) { U16 uart2hwmod = o->index; U16 serial0platform = o->index + icachealiases; baAssert((serial0platform % sizeof(int))==0); if(serial0platform > o->size) { U16 indexnospec; void* anatopenable; if(timerhandler != 0 && serial0platform > timerhandler) return 0; indexnospec = (serial0platform + 512) & ~256; if(timerhandler != 0 && indexnospec > timerhandler) indexnospec = timerhandler; anatopenable = baMalloc(indexnospec+1); if(anatopenable) { memcpy(anatopenable, o->buf, o->size); baFree(o->buf); o->size = indexnospec; o->buf = (char*)anatopenable; } else return 0; } o->index = serial0platform; return &o->buf[uart2hwmod]; } typedef struct { const char* key; int keyLen; HttpMethod val; } CmpMethod; static const CmpMethod cmpMethods[] = { { "\103\117\116\116\105\103\124", (sizeof("\103\117\116\116\105\103\124")-1), HttpMethod_Connect }, { "\103\117\120\131", (sizeof("\103\117\120\131")-1), HttpMethod_Copy }, { "\104\105\114\105\124\105", (sizeof("\104\105\114\105\124\105")-1), HttpMethod_Delete }, { "\110\105\101\104", (sizeof("\110\105\101\104")-1), HttpMethod_Head }, { "\114\117\103\113", (sizeof("\114\117\103\113")-1), HttpMethod_Lock }, { "\115\113\103\117\114", (sizeof("\115\113\103\117\114")-1), HttpMethod_Mkcol }, { "\115\117\126\105", (sizeof("\115\117\126\105")-1), HttpMethod_Move }, { "\117\120\124\111\117\116\123", (sizeof("\117\120\124\111\117\116\123")-1), HttpMethod_Options }, { "\120\101\124\103\110", (sizeof("\120\101\124\103\110")-1), HttpMethod_Patch }, { "\120\117\123\124", (sizeof("\120\117\123\124")-1), HttpMethod_Post }, { "\120\122\117\120\106\111\116\104", (sizeof("\120\122\117\120\106\111\116\104")-1), HttpMethod_Propfind }, { "\120\122\117\120\120\101\124\103\110", (sizeof("\120\122\117\120\120\101\124\103\110")-1), HttpMethod_Proppatch }, { "\120\125\124", (sizeof("\120\125\124")-1), HttpMethod_Put }, { "\124\122\101\103\105", (sizeof("\124\122\101\103\105")-1), HttpMethod_Trace }, { "\125\116\114\117\103\113", (sizeof("\125\116\114\117\103\113")-1), HttpMethod_Unlock } }; static int keyboardinterrupt(const void *sourcerouting, const void *ducaticlkdm) { return bStrncmp((const char*)sourcerouting, ((CmpMethod*)ducaticlkdm)->key, ((CmpMethod*)ducaticlkdm)->keyLen); } static HttpMethod probeloongson(const char* enabledisable) { CmpMethod* m = (CmpMethod*) baBSearch( enabledisable, cmpMethods, sizeof(cmpMethods)/sizeof(cmpMethods[0]), sizeof(cmpMethods[0]), keyboardinterrupt); return m ? m->val : HttpMethod_Unknown; } BA_API HttpMethod HttpMethod_a2m(const char* str) { if(!str) return HttpMethod_Unknown; if(!strcmp("\107\105\124", str)) return HttpMethod_Get; return probeloongson(str); } static const char* httpMethods[] = { "\103\117\116\116\105\103\124", "\107\105\124", "\110\105\101\104", "\117\120\124\111\117\116\123", "\120\101\124\103\110", "\120\117\123\124", "\120\125\124", "\124\122\101\103\105", "\103\117\120\131", "\104\105\114\105\124\105", "\114\117\103\113", "\115\117\126\105", "\115\113\103\117\114", "\120\122\117\120\106\111\116\104", "\120\122\117\120\120\101\124\103\110", "\125\116\114\117\103\113", "\125\116\113\116\117\127\116", }; static const int httpMethodsSize[] = { sizeof("\103\117\116\116\105\103\124"), sizeof("\107\105\124"), sizeof("\110\105\101\104"), sizeof("\117\120\124\111\117\116\123"), sizeof("\120\101\124\103\110"), sizeof("\120\117\123\124"), sizeof("\120\125\124"), sizeof("\124\122\101\103\105"), sizeof("\103\117\120\131"), sizeof("\104\105\114\105\124\105"), sizeof("\114\117\103\113"), sizeof("\115\117\126\105"), sizeof("\115\113\103\117\114"), sizeof("\120\122\117\120\106\111\116\104"), sizeof("\120\122\117\120\120\101\124\103\110"), sizeof("\125\116\114\117\103\113"), sizeof("\125\116\113\116\117\127\116") }; #define HttpStdHeaders_constructor(o, httpInData) (o)->inData=httpInData BA_API const char* HttpStdHeaders_zzGetValFromOffs(HttpStdHeaders* o, U16 idmapstart) { return idmapstart ? HttpInData_2Ptr(o->inData, idmapstart) : 0; } BA_API const char* HttpStdHeaders_getDomain(HttpStdHeaders* o) { if( ! o->domain ) { const char* writereg16 = HttpStdHeaders_getHost(o); if(writereg16) { o->domain = baStrdup(writereg16); if(o->domain) { char* end; char* ptr; if( (end = strrchr(o->domain, '\072')) != 0) *end = 0; else end = o->domain+strlen(o->domain); for(ptr = o->domain ; ptr < end; ptr++) *ptr = (char)bTolower(*ptr); } } } return o->domain; } static void read64uint64(HttpInData* o) { memset(o->allocator.buf, 0, o->allocator.index); HttpAllocator_reclaim(o->allocator); o->parseState = HttpInData_ParseHeader; o->lineStartI = o->lineEndI = 0; o->overflow = FALSE; } #define HttpInData_restartWithPipelinedData(o) \ (o)->parseState = HttpInData_ParseHeader static void flashwrite16(HttpInData* o, HttpRequest* configuredevice, HttpServerConfig* cfg) { enableintens(&o->allocator, cfg->minRequest); o->request = configuredevice; o->maxRequest = cfg->maxRequest; read64uint64(o); } #define HttpInData_isValid(o) HttpAllocator_isValid(&(o)->allocator) static void injectremove(HttpInData* o) { emulateldrdstrd(&o->allocator); } static int foundationsregistered(HttpInData* o, S16 timerhandler, BaBool unwindtable) { int n; HttpConnection* con = HttpRequest_getConnection(o->request); BaBool prioritycontrol=FALSE; do { int emulateinstruction = o->allocator.size - o->allocator.index; if(emulateinstruction <= 80 || (timerhandler != 0 && emulateinstruction < timerhandler)) { void* anatopenable; S16 accessflags = timerhandler ? timerhandler : 512; S16 indexnospec = o->allocator.size + accessflags; if(indexnospec > o->maxRequest) { if(timerhandler == 0) { if(prioritycontrol) return 1; if(o->maxRequest == o->allocator.size) goto L_overFlow; indexnospec = o->maxRequest; } else { if( ! unwindtable ) { HttpResponse_sendError1( HttpRequest_getResponse(o->request), 413); } o->overflow = TRUE; goto L_overFlow; } } anatopenable = baMalloc(indexnospec+1); if(anatopenable) { memcpy(anatopenable, o->allocator.buf, o->allocator.size); baFree(o->allocator.buf); o->allocator.size = indexnospec; o->allocator.buf = (char*)anatopenable; } else { if( ! unwindtable ) { pciercxcfg032(HttpRequest_getResponse(o->request)); TRPR(("\154\151\156\145\075\045\144\054\040\163\075\045\165\054\040\156\163\075\045\165\012", __LINE__,o->allocator.size,(int)indexnospec)); } o->overflow = TRUE; goto L_overFlow; } emulateinstruction = o->allocator.size - o->allocator.index; } if(timerhandler && timerhandler < emulateinstruction) emulateinstruction = timerhandler; n = HttpConnection_readData(con, HttpInData_readPtr(o), emulateinstruction); if(n > 0) { o->allocator.index += (U16)n; n = 1; } prioritycontrol=TRUE; } while(n > 0 && HttpConnection_hasMoreData(con)); return n; L_overFlow: #ifdef HTTP_TRACE if(HttpTrace_doReqBufOverflow()) HttpTrace_write(0,"\105\162\162\157\162\072\040\122\145\161\102\165\146\117\166\145\162\146\154\157\167\056\040\122\145\161\165\145\163\164\040\144\141\164\141\040\164\157\157\040\142\151\147\056\012", -1); #endif return -1; } static BaBool threadstack(HttpInData* o) { ptrdiff_t len; U8* cachesysfs = (U8*)HttpInData_lineEndPtr(o); U8* end = (U8*)HttpInData_readPtr(o); baAssert(end > cachesysfs); len = end - cachesysfs; if(len == 2 && cachesysfs[0] == '\015' && cachesysfs[1] == '\012') return FALSE; memmove(o->allocator.buf, cachesysfs, len); o->lineStartI = 0; o->allocator.index = (U16)(end - cachesysfs); return TRUE; } #define HttpInData_hasMoreDataM(o) \ HttpInData_readPtr(o) > HttpInData_lineEndPtr(o) BaBool HttpInData_hasMoreData(HttpInData* o) { return HttpInData_hasMoreDataM(o); } static int maybebootmem(HttpInData* o) { char* ptr = HttpInData_2Ptr(o, 0); char* end = HttpInData_readPtr(o); while(ptr < end) { if( (*ptr == '\015' && ptr[1] == '\012' && ptr[2] == '\015' && ptr[3] == '\012') || (*ptr == '\012' && ptr[1] == '\012') ) { ptr[0]=0; return 1; } ptr++; } return 0; } static int accessspeed(HttpInData* o) { int handlersetup; if(HttpInData_2Ptr(o, 0) != HttpInData_readPtr(o) && maybebootmem(o)) { return 1; } handlersetup = foundationsregistered(o, 0, FALSE); if(handlersetup >= 0) { return maybebootmem(o); } return handlersetup; } static char* HttpInData_extractLine(HttpInData* o, char* ptr) { while(*ptr) { if( (ptr[0] == '\015' && ptr[1] == '\012') || ptr[0] == '\012') { if( (ptr[0] == '\015' && (ptr[2] == '\040' || ptr[2] == '\011')) || (ptr[0] == '\012' && (ptr[1] == '\040' || ptr[1] == '\011')) ) { ptr++; } else { *ptr=0; return ptr[1] == '\012' ? ptr+2 : ptr+1; } } ++ptr; } if(ptr[1] == '\012' && ptr[2] == '\015' && ptr[3] == '\012') { ptr+=4; } else { ptr+=2; } o->lineStartI = o->lineEndI = HttpInData_2Index(o, ptr); return 0; } static int registerlookup(HttpInData* o, char* dbdmaresume) { while(*dbdmaresume) { char* gpio1config = dbdmaresume; char* videoprobe=0; for(dbdmaresume++;*dbdmaresume;dbdmaresume++) { if(*dbdmaresume == '\075') { *dbdmaresume=0; videoprobe = dbdmaresume+1; } else if(*dbdmaresume == '\046') { *dbdmaresume=0; if(!videoprobe) videoprobe=dbdmaresume; else if(!httpFormUnescape(videoprobe)) return -1; if(!httpFormUnescape(gpio1config)) return -1; if(mappingerror(o->request, gpio1config, videoprobe)) return -1; #ifndef NO_HTTP_SESSION if(*gpio1config == '\172' && ! strcmp(BA_COOKIE_ID, gpio1config)) HttpRequest_session(o->request, videoprobe,strlen(videoprobe),TRUE); #endif videoprobe=0; gpio1config = dbdmaresume+1; } } if(*gpio1config) { if(!videoprobe) videoprobe = gpio1config+strlen(gpio1config); else if(!httpFormUnescape(videoprobe)) return -1; if(!httpFormUnescape(gpio1config)) return -1; if(mappingerror(o->request, gpio1config, videoprobe)) return -1; #ifndef NO_HTTP_SESSION if(*gpio1config == '\172' && ! strcmp(BA_COOKIE_ID, gpio1config)) HttpRequest_session(o->request, videoprobe,strlen(videoprobe),TRUE); #endif } } return 0; } static int driverprobe(HttpInData* o) { const char* cachabledefault; char* ref; char* enabledisable; char* patchimm60; char* ptr; HttpStdHeaders* stdH = &o->request->stdH; HttpConnection* con = HttpRequest_getConnection(o->request); HttpRequest* req = o->request; if(o->parseState == HttpInData_ParseHeader) { int handlersetup = accessspeed(o); if(handlersetup <= 0) return handlersetup; enabledisable = HttpInData_2Ptr(o, 0); httpEatWhiteSpace(enabledisable); patchimm60 = HttpInData_extractLine(o, enabledisable); #if 0 if(!patchimm60) return -1; #endif if( !(ref = (char*)baGetToken((const char**)&enabledisable, "\040\011\012\015")) ) return serial1platform(req); if(!baStrnCaseCmp("\107\105\124", enabledisable, 3)) req->methodType = HttpMethod_Get; else { req->methodType = probeloongson(enabledisable); if(req->methodType == HttpMethod_Unknown) { HttpRequest_sendDefaultMethodsAllowed(req); return -1; } } enabledisable = ref; httpEatWhiteSpace(enabledisable); if(*enabledisable == '\057') { if( !(ref = (char*)baGetToken((const char**)&enabledisable, "\040\011\077")) ) return serial1platform(req); baAssert(*enabledisable == '\057'); } else { char* end; if(baStrnCaseCmp("\150\164\164\160\072\057\057", enabledisable, 7) && baStrnCaseCmp("\150\164\164\160\163\072\057\057", enabledisable, 8)) { if(*enabledisable == '\052' && req->methodType == HttpMethod_Options) { HttpRequest_sendDefaultMethodsAllowed(req); return -1; } return serial1platform(req); } enabledisable += 7; if(*enabledisable == '\057') enabledisable++; stdH->hostHOffs=HttpInData_2Index(o,enabledisable); if( ! (ref = strpbrk(enabledisable, "\057\072")) ) return serial1platform(req); end = ref; if(*ref == '\072') { if( ! (ref = strchr(++ref, '\057')) ) return serial1platform(req); } enabledisable=ref; if( !(ref = (char*)baGetToken((const char**)&enabledisable, "\040\011\077")) ) return serial1platform(req); *end=0; } if(*ref == '\077') { *ref++ = 0; ptr = ref; httpEatNonWhiteSpace(ref); if(*ref == 0) return serial1platform(req); *ref=0; if(registerlookup(o, ptr)) return serial1platform(req); } else *ref = 0; enabledisable++; ptr=httpUnescape((char*)enabledisable); if(!ptr) return serial1platform(req); while(bIsspace(*ptr) && ptr > enabledisable) { *ptr--=0; } if(baElideDotDot((char*)enabledisable)) { HttpResponse_sendError1(HttpRequest_getResponse(req), 404); return -1; } req->pathI = HttpInData_2Index(o, enabledisable); enabledisable = ref+1; if( !(ref = (char*)baGetToken((const char**)&enabledisable, "\040\011\012\015")) ) return serial1platform(req); if(baStrnCaseCmp("\110\124\124\120\057", enabledisable, 5)) return serial1platform(req); req->versionI = HttpInData_2Index(o, enabledisable+5); if(ref) *ref=0; while(patchimm60) { enabledisable = patchimm60; patchimm60 = HttpInData_extractLine(o, enabledisable); if( (ref = bStrchr(enabledisable, '\072')) != 0 ) { const char* gpio1config = enabledisable; *ref++ = 0; httpEatWhiteSpace(ref); #if 0 if(*ref == 0) { ref--; baAssert(bIsspace(*ref)); } #endif if(registerclocks(req, gpio1config, ref)) { pciercxcfg032(HttpRequest_getResponse(req)); TRPR(("\154\151\156\145\075\045\144\054\040\154\145\156\075\045\144\012", __LINE__,strlen(gpio1config))); return -1; } } } if(strcmp(HttpRequest_getVersion(req), "\061\056\061") >=0) { cachabledefault = HttpStdHeaders_getConnection(stdH); if( ! cachabledefault || baStrCaseCmp(cachabledefault, "\103\154\157\163\145")) HttpConnection_setKeepAlive(con); else HttpConnection_clearKeepAlive(con); if( ! HttpStdHeaders_getHost(stdH) ) { HttpResponse_sendError2(HttpRequest_getResponse(req), 400, "\110\124\124\120\057\061\056\061\040\143\154\151\145\156\164\163\040\155\165\163\164\040\163\165\160\160\154\171\040\042\150\157\163\164\042\040\150\145\141\144\145\162"); return -1; } } else { HttpConnection_clearKeepAlive(con); } if(req->methodType == HttpMethod_Post || req->methodType == HttpMethod_Patch || req->methodType == HttpMethod_Delete) { BaBool savedstate; cachabledefault = HttpStdHeaders_getContentType(stdH); if( ! cachabledefault ) { if(stdH->contentLength == 0) return 1; HttpResponse_sendError2( HttpRequest_getResponse(req), 400, "\116\157\040\103\157\156\164\145\156\164\055\164\171\160\145"); return -1; } savedstate = baStrnCaseCmp( cachabledefault, "\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\167\167\055\146\157\162\155\055\165\162\154\145\156\143\157\144\145\144", 33) ? FALSE : TRUE; if((U32)o->lineStartI + stdH->contentLength < (U32)o->maxRequest) { o->lineEndI = o->lineStartI + (S16)stdH->contentLength; o->parseState = savedstate ? HttpInData_ReadBodyAndParseUrlEncData : HttpInData_ReadBody; req->postDataConsumed=TRUE; } else if(savedstate) { HttpResponse_sendError1( HttpRequest_getResponse(req),413); return -1; } else { spillpsprel(req->server, con); return 1; } } else { if(stdH->contentLength != 0) { if((U32)o->lineStartI + stdH->contentLength < (U32)o->maxRequest) { o->lineEndI = o->lineStartI + (S16)stdH->contentLength; o->parseState = HttpInData_ReadBody; req->postDataConsumed=TRUE; } else { spillpsprel(req->server, con); return 1; } } else return 1; } } if(o->lineEndI > o->allocator.index) { S16 icachealiases = o->lineEndI > o->allocator.size ? o->lineEndI-o->allocator.size : 0; if(foundationsregistered(o,icachealiases,FALSE)<0) { return -1; } if(o->lineEndI > o->allocator.index) return 0; } if(o->parseState == HttpInData_ReadBodyAndParseUrlEncData) { ref = HttpInData_lineEndPtr(o); if(o->lineEndI != o->allocator.index) { baAssert(o->lineEndI < o->allocator.index); if(HttpConnection_pushBack(con,ref,o->allocator.index-o->lineEndI)) HttpConnection_clearKeepAlive(con); } *ref = 0; if(registerlookup(o, HttpInData_lineStartPtr(o))) return serial1platform(req); o->lineStartI=o->lineEndI=0; o->allocator.index=0; } else { baAssert(o->parseState == HttpInData_ReadBody); } return 1; } static InternalFormElement* HttpParameter_getFormBase(HttpParameter* o) { return (InternalFormElement*)(o+1); } static char* HttpParameter_getDataEntry(HttpParameter* o, InternalFormElement* prunedevice) { return ((char*)prunedevice) + (sizeof(InternalFormElement)*o->formLen); } static U32 uretprobehijack(HttpRequest* req) { HttpParameterIterator i; U32 icachealiases=0; baAssert(req->formLen); HttpParameterIterator_constructor(&i, req); for(; HttpParameterIterator_hasMoreElements(&i) ; HttpParameterIterator_nextElement(&i)) { icachealiases += iStrlen(HttpParameterIterator_getName(&i)) + 1; icachealiases += iStrlen(HttpParameterIterator_getValue(&i)) + 1; } return icachealiases; } BA_API U32 HttpParameter_calculateSize(HttpRequest* req) { U32 icachealiases; if(req->formLen == 0) return 0; icachealiases = sizeof(HttpParameter)+sizeof(InternalFormElement)*req->formLen; return icachealiases + uretprobehijack(req); } BA_API HttpParameter* HttpParameter_clone(void* buf, HttpRequest* req) { InternalFormElement* fIter; HttpParameterIterator i; char* kernelsecondary; char* ptr; HttpParameter* timercancel=(HttpParameter*)buf; if(!buf) return 0; timercancel->formLen = req->formLen; fIter = HttpParameter_getFormBase(timercancel); ptr = kernelsecondary = HttpParameter_getDataEntry(timercancel, fIter); HttpParameterIterator_constructor(&i, req); for(; HttpParameterIterator_hasMoreElements(&i) ; HttpParameterIterator_nextElement(&i), fIter++) { strcpy(ptr, HttpParameterIterator_getName(&i)); fIter->nameI = (U16)(ptr - kernelsecondary); ptr += strlen(HttpParameterIterator_getName(&i)) + 1; strcpy(ptr, HttpParameterIterator_getValue(&i)); fIter->valueI = (U16)(ptr - kernelsecondary); ptr += strlen(HttpParameterIterator_getValue(&i)) + 1; } return timercancel; } BA_API const char* HttpParameter_getParameter(HttpParameter* o,const char* bugs64early) { HttpParameterIterator i; HttpParameterIterator_constructor2(&i, o); return HttpParameterIterator_getParameter(&i, bugs64early); } BA_API int HttpParameterIterator_constructor(HttpParameterIterator* o,HttpRequest* req) { o->pos = 0; o->name = 0; o->value = 0; o->formLen = req->formLen; o->formElemBase = HttpRequest_getForms(req); o->dataEntry=(U8*)req->inData.allocator.buf; if(req->formLen) HttpParameterIterator_nextElement(o); return req->formLen; } BA_API int HttpParameterIterator_constructor2(HttpParameterIterator* o, HttpParameter* timercancel) { o->pos = 0; o->name = 0; o->value = 0; o->dataEntry=0; o->formElemBase=0; o->formLen = timercancel->formLen; if(o->formLen) { o->formElemBase = HttpParameter_getFormBase(timercancel); o->dataEntry=(U8*)HttpParameter_getDataEntry(timercancel, o->formElemBase); HttpParameterIterator_nextElement(o); } return o->formLen; } BA_API void HttpParameterIterator_nextElement(HttpParameterIterator* o) { if(o->pos < o->formLen) { InternalFormElement* fBase = (InternalFormElement*)o->formElemBase; o->name = (char*)InternalFormElement_getName(fBase[o->pos],o->dataEntry); o->value=(char*)InternalFormElement_getValue(fBase[o->pos],o->dataEntry); o->pos++; } else { o->name = 0; o->value = 0; } } static const char* HttpParameterIterator_getParameter(HttpParameterIterator* o, const char* bugs64early) { for(; HttpParameterIterator_hasMoreElements(o) ; HttpParameterIterator_nextElement(o)) { if( ! strcmp(HttpParameterIterator_getName(o), bugs64early) ) return HttpParameterIterator_getValue(o); } return 0; } static HttpCookie* HttpCookie_constructor(HttpCookie* o, struct HttpResponse* doublefsqrt, const char* gpio1config) { if(o) { memset(o, 0, sizeof(HttpCookie)); o->name = baStrdup(gpio1config); o->maxAge = 0; o->version = 1; o->deleteCookieFlag = FALSE; regmaplookup(doublefsqrt, o); } return o; } BA_API void HttpCookie_destructor(HttpCookie* o) { baFree(o->name); if(o->comment) baFree(o->comment); if(o->domain) baFree(o->domain); if(o->path) baFree(o->path); if(o->value) baFree(o->value); } BA_API const char* HttpCookie_getComment(HttpCookie* o) { return o->comment; } BA_API const char* HttpCookie_getDomain(HttpCookie* o) { return o->domain; } BA_API BaTime HttpCookie_getMaxAge(HttpCookie* o) { return o->maxAge; } BA_API const char* HttpCookie_getName(HttpCookie* o) { return o->name; } BA_API const char* HttpCookie_getPath(HttpCookie* o) { return o->path; } BA_API BaBool HttpCookie_getSecure(HttpCookie* o) { return o->secure; } BA_API BaBool HttpCookie_getHttpOnly(HttpCookie* o) { return o->httpOnly; } BA_API const char* HttpCookie_getValue(HttpCookie* o) { return o->value; } #if 0 int HttpCookie_getVersion(HttpCookie* o) { return o->version; } #endif BA_API void HttpCookie_setComment(HttpCookie* o, const char* enetswregister) { if(o->comment) baFree(o->comment); o->comment = baStrdup(enetswregister); } BA_API void HttpCookie_setDomain(HttpCookie* o, const char* structsizes) { if(o->domain) baFree(o->domain); o->domain = baStrdup(structsizes); } BA_API void HttpCookie_setMaxAge(HttpCookie* o, BaTime kdumpkernel) { o->maxAge = kdumpkernel; o->deleteCookieFlag = o->maxAge ? FALSE : TRUE; } BA_API void HttpCookie_setPath(HttpCookie* o, const char* uri) { if(o->path) baFree(o->path); o->path = baStrdup(uri); } BA_API void HttpCookie_setSecure(HttpCookie* o, BaBool sha256export) { o->secure = sha256export; } BA_API void HttpCookie_setHttpOnly(HttpCookie* o, BaBool sha256export) { o->httpOnly = sha256export; } BA_API void HttpCookie_setValue(HttpCookie* o, const char* createmapping) { if(o->value) baFree(o->value); o->value = baStrdup(createmapping); } #if 0 void HttpCookie_setVersion(HttpCookie* o, int v) { o->version = v; } #endif BA_API void HttpCookie_activate(HttpCookie* o) { o->activateFlag = TRUE; } static char* HttpCookie_CreateAvPair(char*buf, const char* gpio1config, const char* videoprobe, const char sep) { basnprintf(buf, 10000, "\045\163\045\163\075", sep ? "\073\040" : "", gpio1config); buf += strlen(buf); if(videoprobe) httpEscape(buf, videoprobe); return buf + strlen(buf); } static char* HttpCookie_ExtractAvPair(char* ref) { char* kprobedecode; char* timerdying = ref; httpEatCharacters(timerdying, '\075'); if(!*timerdying) return 0; *timerdying++ = 0; httpEatWhiteSpace(timerdying); if(!*timerdying) return 0; if(*timerdying == '\075') { timerdying++; httpEatWhiteSpace(timerdying); } kprobedecode = timerdying; httpEatCharacters(kprobedecode, '\073'); *kprobedecode = 0; return httpUnescape(timerdying) ? timerdying : 0; } static void ecofffilehdr(HttpRequest* o) { baAssert( ! o->session ); HttpInData_restartWithPipelinedData(&o->inData); HttpAllocator_reclaim(o->headerAlloc); HttpAllocator_reclaim(o->formAlloc); if(o->stdH.domain) baFree(o->stdH.domain); memset(&o->stdH, 0, sizeof(HttpStdHeaders)); HttpStdHeaders_constructor(&o->stdH, &o->inData); o->userObj=0; o->pathI=0; o->versionI=0; o->headerLen=0; o->formLen=0; o->postDataConsumed=FALSE; } static void profilingtimer(HttpRequest* o) { ecofffilehdr(o); read64uint64(&o->inData); } static void arm64decrypt( HttpRequest* o, HttpServer* uarchbuild, HttpServerConfig* cfg) { enableintens(&o->headerAlloc, 256); enableintens(&o->formAlloc, 256); flashwrite16(&o->inData, o, cfg); HttpStdHeaders_constructor(&o->stdH, &o->inData); o->server = uarchbuild; o->session=0; profilingtimer(o); } static BaBool icachesnoops(HttpRequest* o) { return HttpAllocator_isValid(&o->headerAlloc) && HttpAllocator_isValid(&o->formAlloc) && HttpInData_isValid(&o->inData); } static void read64uint16(HttpRequest* o) { emulateldrdstrd(&o->headerAlloc); emulateldrdstrd(&o->formAlloc); injectremove(&o->inData); } #define ALLMETHODS (HttpMethod_Unknown - 1) BA_API int HttpRequest_checkMethods(HttpRequest* o, HttpResponse* r3000write, U32 createcontiguous, BaBool onenandresources) { char* outboundenter; char* ptr; size_t i; int handlersetup; int chargetoggle; HttpMethod mt; if(!HttpResponse_initial(r3000write)) return 0; if ((createcontiguous & (~ALLMETHODS)) || (createcontiguous == 0 && !onenandresources)) { TRPR(("\166\103\150\145\143\153\117\160\164\151\157\156\163\072\040\151\156\166\141\154\151\144\040\157\160\164\151\157\156")); return E_INVALID_PARAM; } if(onenandresources) createcontiguous |= HttpMethod_Head; mt = HttpRequest_getMethodType(o); if(mt == HttpMethod_Options && onenandresources) { if (HttpStdHeaders_getContentLength(HttpRequest_getStdHeaders(o)) != 0) HttpConnection_clearKeepAlive(HttpResponse_getConnection(r3000write)); } else { if(createcontiguous & mt) return 0; } if(onenandresources) createcontiguous |= HttpMethod_Options; if(r3000write->headerSent) { TRPR(("\163\145\156\144\117\160\164\151\157\156\163\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } baAssert(sizeof(httpMethodsSize)/sizeof(httpMethodsSize[0]) == 17); chargetoggle = httpMethodsSize[0] + httpMethodsSize[1] + httpMethodsSize[2] + httpMethodsSize[3] + httpMethodsSize[4] + httpMethodsSize[5] + httpMethodsSize[6] + httpMethodsSize[7] + httpMethodsSize[8] + httpMethodsSize[9] + httpMethodsSize[10] + httpMethodsSize[11] + httpMethodsSize[12] + httpMethodsSize[13] + httpMethodsSize[14] + httpMethodsSize[15] + 2*16 + 1; ptr = outboundenter = HttpResponse_fmtHeader(r3000write, "\101\154\154\157\167", chargetoggle, TRUE); if(!outboundenter) { TRPR(("\163\145\164\110\145\141\144\145\162\072\040\105\137\115\101\114\114\117\103\012")); return E_MALLOC; } for(i=0; i < (sizeof(httpMethodsSize)/sizeof(httpMethodsSize[0])-1); i++) { if (createcontiguous & (1 << i)) { chargetoggle = httpMethodsSize[i] - 1; memcpy(ptr, httpMethods[i],chargetoggle); ptr += chargetoggle; *ptr++='\054'; *ptr++='\040'; } } *(ptr-2) = '\000'; if(mt == HttpMethod_Options && onenandresources) { if( (handlersetup=HttpResponse_resetBuffer(r3000write)) !=0 ) return handlersetup; if( (handlersetup=HttpResponse_setContentLength(r3000write, 0)) !=0 ) return handlersetup; } else { if( (handlersetup=HttpResponse_sendError2(r3000write, 405, outboundenter)) ) return handlersetup; } return 1; } BA_API int HttpRequest_checkOptions(HttpRequest* o, HttpResponse* r3000write, int optLen, ...) { int i; va_list demuxregids; BaBool onenandresources; U32 createcontiguous=0; if(!HttpResponse_initial(r3000write)) return 0; if(optLen < 0) { optLen = -optLen; onenandresources = FALSE; } else onenandresources = TRUE; va_start(demuxregids, optLen); for(i=0; i < optLen; i++) createcontiguous |= (U32)va_arg(demuxregids, int); va_end(demuxregids); return HttpRequest_checkMethods(o, r3000write, createcontiguous, onenandresources); } BA_API BaBool HttpRequest_checkTime(HttpRequest* o, HttpResponse* r3000write, BaTime widgetactive) { BaTime ifModSinceTime; ifModSinceTime = baParseDate( HttpRequest_getHeaderValue(o, "\111\146\055\115\157\144\151\146\151\145\144\055\123\151\156\143\145")); if(ifModSinceTime && ifModSinceTime >= widgetactive) { HttpResponse_setStatus(r3000write, 304); HttpResponse_setContentLength(r3000write, 0); return TRUE; } return FALSE; } BA_API const char* HttpRequest_getMethod2(HttpMethod disableparity) { switch(disableparity) { case HttpMethod_Connect: return httpMethods[0]; case HttpMethod_Get: return httpMethods[1]; case HttpMethod_Head: return httpMethods[2]; case HttpMethod_Options: return httpMethods[3]; case HttpMethod_Patch: return httpMethods[4]; case HttpMethod_Post: return httpMethods[5]; case HttpMethod_Put: return httpMethods[6]; case HttpMethod_Trace: return httpMethods[7]; case HttpMethod_Copy: return httpMethods[8]; case HttpMethod_Delete: return httpMethods[9]; case HttpMethod_Lock: return httpMethods[10]; case HttpMethod_Move: return httpMethods[11]; case HttpMethod_Mkcol: return httpMethods[12]; case HttpMethod_Propfind: return httpMethods[13]; case HttpMethod_Proppatch: return httpMethods[14]; case HttpMethod_Unlock: return httpMethods[15]; case HttpMethod_Unknown: break; } return httpMethods[16]; } BA_API const char* HttpRequest_getRequestURI(HttpRequest* o) { return HttpInData_2Ptr(&o->inData, o->pathI) -1; } static const char* HttpRequest_GetRequestURLX(HttpRequest* o, BaBool modifystatus) { int len; const char* ejtagsetup; char *ptr; char removestate[60]; HttpResponse* r3000write = HttpRequest_getResponse(o); const char* uri = HttpRequest_getRequestURI(o); const char* writereg16 = HttpStdHeaders_getHost(&o->stdH); if(!writereg16) { HttpSockaddr serialports; HttpConnection_getPeerName(HttpRequest_getConnection(o), &serialports,0); HttpConnection_addr2String(HttpRequest_getConnection(o), &serialports, removestate, sizeof(removestate)); removestate[59]=0; writereg16=removestate; } if(modifystatus) ejtagsetup = "\150\164\164\160\163"; else ejtagsetup = "\150\164\164\160"; if(r3000write->encodedRedirectURL) baFree(r3000write->encodedRedirectURL); len=10+iStrlen(writereg16)+3*iStrlen(uri); r3000write->encodedRedirectURL = baMalloc(len); if(r3000write->encodedRedirectURL) { basnprintf(r3000write->encodedRedirectURL, len, "\045\163\072\057\057\045\163", ejtagsetup, writereg16); ptr = r3000write->encodedRedirectURL+strlen(r3000write->encodedRedirectURL); httpEscape(ptr, uri); } return r3000write->encodedRedirectURL; } BA_API const char* HttpRequest_getRequestURL(HttpRequest* o, BaBool mdmctl0names) { return HttpRequest_GetRequestURLX( o, mdmctl0names ? TRUE : HttpConnection_isSecure(HttpRequest_getConnection(o))); } #define HttpRequest_getRequestPath(o) HttpInData_2Ptr(&(o)->inData, (o)->pathI) BA_API const char* HttpRequest_getVersion(HttpRequest* o) { return HttpInData_2Ptr(&o->inData, o->versionI); } static int registerclocks(HttpRequest* o, const char* gpio1config, const char* videoprobe) { HttpStdHeaders* stdH = &o->stdH; HttpHeader* rtcmatch2clockdev = (HttpHeader*)HttpAllocator_alloc( &o->headerAlloc, sizeof(HttpHeader), 0); if(!rtcmatch2clockdev) return -1; o->headerLen++; HttpHeader_constructor(rtcmatch2clockdev, &o->inData, gpio1config, videoprobe); #ifndef NDEBUG { const HttpHeader* hBase = HttpRequest_getHeadersM(o); baAssert((hBase+o->headerLen-1) == rtcmatch2clockdev); } #endif if( ! stdH->connectionHOffs && (gpio1config[3] == '\156' || gpio1config[3] == '\116') && ! baStrCaseCmp("\103\157\156\156\145\143\164\151\157\156", gpio1config) ) { stdH->connectionHOffs = HttpInData_2Index(&o->inData, videoprobe); } else if( ! stdH->hostHOffs && (gpio1config[0] == '\110' || gpio1config[0] == '\150') && ! baStrCaseCmp("\110\157\163\164", gpio1config) ) { stdH->hostHOffs = HttpInData_2Index(&o->inData, videoprobe); } else if( ! stdH->contentTypeHOffs && (gpio1config[8] == '\164' || gpio1config[8] == '\124') && ! baStrCaseCmp("\143\157\156\164\145\156\164\055\164\171\160\145", gpio1config) ) { stdH->contentTypeHOffs = HttpInData_2Index(&o->inData, videoprobe); } else if( (gpio1config[8] == '\154' || gpio1config[8] == '\114') && ! baStrCaseCmp("\143\157\156\164\145\156\164\055\154\145\156\147\164\150", gpio1config) ) { #ifdef BA_FILESIZE64 stdH->contentLength = U64_atoll(videoprobe); #else stdH->contentLength = U32_atoi(videoprobe); #endif } return 0; } static int mappingerror(HttpRequest* o, const char* gpio1config, const char* videoprobe) { InternalFormElement* formElement=(InternalFormElement*)HttpAllocator_alloc( &o->formAlloc, sizeof(InternalFormElement), 0); if(!formElement) return -1; nativeassign(formElement, &o->inData, gpio1config, videoprobe); o->formLen++; { #ifndef NDEBUG const InternalFormElement* fBase = HttpRequest_getForms(o); baAssert(&fBase[o->formLen-1] == formElement); #endif } return 0; } BA_API const char* HttpRequest_getHeaderValue(HttpRequest* o, const char* gpio1config) { if(o->headerLen) { int len; HttpHeader* platformioremap = HttpRequest_getHeadersM(o); for(len=0 ; len < o->headerLen ; len++) { const char* h=HttpHeader_nameM(platformioremap+len,&o->inData); if((*h == *gpio1config || (*h > *gpio1config ? *gpio1config + ('\141'-'\101') == *h : *h + ('\141'-'\101') == *gpio1config)) && !baStrCaseCmp(gpio1config+1,h+1)) { return HttpHeader_valueM(platformioremap+len, &o->inData); } } } return 0; } BA_API HttpCookie* HttpRequest_getCookie(HttpRequest* o, const char* gpio1config) { HttpCookie* helperrgmii=HttpResponse_getCookie(HttpRequest_getResponse(o),gpio1config); if(!helperrgmii) { int dummywrite=0; char* nhpoly1305update; char* ads7846platform; char* prctlenable; char* val = baStrdup(HttpRequest_getHeaderValue(o, "\103\157\157\153\151\145")); if(!val) return 0; ads7846platform = val; httpEatWhiteSpace(ads7846platform); if( ! (baStrnCaseCmp(ads7846platform, "\126\145\162\163\151\157\156", 7)) ) { prctlenable = bStrchr(ads7846platform, '\073'); nhpoly1305update = HttpCookie_ExtractAvPair(ads7846platform); if(nhpoly1305update) dummywrite = *nhpoly1305update - '\060'; else prctlenable = 0; } else prctlenable = val-1; while(prctlenable) { ads7846platform = prctlenable; ads7846platform++; httpEatWhiteSpace(ads7846platform); prctlenable = bStrchr(ads7846platform, '\073'); if( ! (bStrncmp(ads7846platform, gpio1config, strlen(gpio1config))) ) { nhpoly1305update = HttpCookie_ExtractAvPair(ads7846platform); if(!nhpoly1305update) break; helperrgmii = HttpResponse_createCookie( HttpRequest_getResponse(o), ads7846platform); HttpCookie_setValue(helperrgmii, nhpoly1305update); #if 0 HttpCookie_setVersion(helperrgmii, dummywrite); #else (void)dummywrite; #endif while(prctlenable) { ads7846platform = prctlenable; ads7846platform++; httpEatWhiteSpace(ads7846platform); prctlenable = bStrchr(ads7846platform, '\073'); if(baStrnCaseCmp("\120\141\164\150", ads7846platform, 5) && baStrnCaseCmp("\104\157\155\141\151\156", ads7846platform, 7)) { prctlenable = 0; } else { nhpoly1305update = HttpCookie_ExtractAvPair(ads7846platform); if(!nhpoly1305update) prctlenable=0; else if( ! baStrnCaseCmp("\120\141\164\150", ads7846platform, 5) ) HttpCookie_setPath(helperrgmii, nhpoly1305update); else HttpCookie_setDomain(helperrgmii, nhpoly1305update); } } } } baFree(val); } return helperrgmii; } BA_API const char* HttpRequest_getParameter(HttpRequest* o, const char* bugs64early) { HttpParameterIterator i; HttpParameterIterator_constructor(&i, o); return HttpParameterIterator_getParameter(&i, bugs64early); } BA_API BaBool HttpRequest_enableKeepAlive(HttpRequest* o) { HttpConnection* con = HttpRequest_getConnection(o); if( ! HttpConnection_keepAlive(con) ) { if(strcmp(HttpRequest_getVersion(o), "\061\056\061") >= 0) { const char* val = HttpStdHeaders_getConnection( HttpRequest_getStdHeaders(o)); if( !val || baStrCaseCmp(val, "\103\154\157\163\145")) { HttpResponse* r3000write = HttpRequest_getResponse(o); if(r3000write->printAndWriteInitialized) { if( ! r3000write->useChunkTransfer ) { if(r3000write->headerSent) return FALSE; if(HttpResponse_setChunkEncoding(r3000write)) return FALSE; } } HttpConnection_setKeepAlive(con); return TRUE; } } return FALSE; } return TRUE; } BA_API int HttpRequest_pushBackData(HttpRequest* o) { HttpConnection* con = HttpRequest_getConnection(o); HttpInData* registeredevent = HttpRequest_getBuffer(o); S32 icachealiases = HttpInData_getBufSize(registeredevent); if(icachealiases != 0) { if(HttpConnection_pushBack(con,HttpInData_getBuf(registeredevent),icachealiases)) { HttpConnection_clearKeepAlive(con); return E_MALLOC; } } HttpRequest_enableKeepAlive(o); return icachealiases; } #ifdef HTTP_TRACE static void sanitisepropbaser(HttpRequest* o) { if(HttpTrace_doRequest()) { const char* rightsvalid; const HttpHeader* platformioremap = HttpRequest_getHeadersM(o); const char* ua = HttpRequest_getHeaderValue(o, "\125\163\145\162\055\101\147\145\156\164"); HttpConnection* con = HttpRequest_getConnection(o); if(!ua) ua="\077"; rightsvalid = HttpRequest_getMethod(o); reprogramdpllcore(5,o); HttpTrace_printf(5,"\040\045\163\040\042\045\163\042\040\045\163\012", rightsvalid, HttpRequest_getRequestPath(o), ua); if(HttpConnection_isSecure(con)) HttpTrace_write(0,"\123\123\114\040", -1); if(HttpTrace_doRequestHeaders()) { int i; HttpParameterIterator formIter; for(i = 0 ; i < o->headerLen ; i++) { HttpTrace_printf(5,"\045\163\072\040\045\163\012", HttpHeader_nameM(platformioremap+i, &o->inData), HttpHeader_valueM(platformioremap+i, &o->inData)); } if(HttpParameterIterator_constructor(&formIter, o)) { HttpTrace_write(5,"\106\157\162\155\040\144\141\164\141\072\012",-1); while(HttpParameterIterator_hasMoreElements(&formIter)) { HttpTrace_printf(5,"\040\040\040\045\163\040\075\040\045\163\012",formIter.name,formIter.value); HttpParameterIterator_nextElement(&formIter); } } HttpTrace_write(5,"\012",1); } } } #else #define sanitisepropbaser(o) #endif BA_API int HttpRequest_setUserObj(HttpRequest* o, void* touchpdata, BaBool clockcheck) { if(o->userObj && !clockcheck) return -1; o->userObj = touchpdata; return 0; } BA_API struct HttpCommand* HttpRequest_getCommand(HttpRequest* o) { return (HttpCommand*) ((U8*)o - offsetof(HttpCommand, request)); } BA_API HttpHeader* HttpRequest_getHeaders(HttpRequest* o, int* len) { *len = o->headerLen; return HttpRequest_getHeadersM(o); } BA_API int HttpRequest_wsUpgrade(HttpRequest* o) { static const U8 sysdatamcheck[]={"\062\065\070\105\101\106\101\065\055\105\071\061\064\055\064\067\104\101\055\071\065\103\101\055\103\065\101\102\060\104\103\070\065\102\061\061"}; DynBuffer db; int handlersetup; U8 secondaryentry[20]; SharkSslSha1Ctx registermcasp; HttpResponse* r3000write = HttpRequest_getResponse(o); const char* ver=HttpRequest_getHeaderValue(o,"\123\145\143\055\127\145\142\123\157\143\153\145\164\055\126\145\162\163\151\157\156"); const char* sourcerouting=HttpRequest_getHeaderValue(o,"\123\145\143\055\127\145\142\123\157\143\153\145\164\055\113\145\171"); if( ! ver || ! sourcerouting) return -1; if(HttpResponse_resetHeaders(r3000write) || HttpResponse_resetBuffer(r3000write)) return -2; SharkSslSha1Ctx_constructor(®istermcasp); SharkSslSha1Ctx_append(®istermcasp,(U8*)sourcerouting,iStrlen(sourcerouting)); SharkSslSha1Ctx_append(®istermcasp,sysdatamcheck,sizeof(sysdatamcheck)-1); SharkSslSha1Ctx_finish(®istermcasp,secondaryentry); HttpResponse_setStatus(r3000write, 101); HttpResponse_setHeader(r3000write,"\125\160\147\162\141\144\145","\167\145\142\163\157\143\153\145\164",TRUE); HttpResponse_setHeader(r3000write,"\103\157\156\156\145\143\164\151\157\156","\125\160\147\162\141\144\145",TRUE); DynBuffer_constructor(&db,20*4/3+10,100,0,0); BufPrint_b64Encode((BufPrint*)&db, secondaryentry, 20); handlersetup=-3; if( ! DynBuffer_getECode(&db) ) { HttpResponse_setHeader( r3000write,"\123\145\143\055\127\145\142\123\157\143\153\145\164\055\101\143\143\145\160\164",DynBuffer_getBuf(&db),TRUE); if( ! HttpResponse_flush(r3000write) ) handlersetup=0; } DynBuffer_destructor(&db); return handlersetup; } BA_API const char* HttpHeader_name(HttpHeader* o, HttpRequest* req) { return HttpHeader_nameM(o,&req->inData); } BA_API const char* HttpHeader_value(HttpHeader* o, HttpRequest* req) { return HttpHeader_valueM(o,&req->inData); } typedef struct { U16 value; /* Relative offset from beginning of struct*/ U16 next; /* Absolute position*/ } NameValMMNode; #define NameValMMNode_constructor(o) memset(o, 0, sizeof(NameValMMNode)) #define NameValMMNode_isEmpty(o) ((o)->value == 0) #define NameValMMNode_setEmpty(o) (o)->value = 0 #define NameValMMNode_getName(o) (char*)((o)+1) #define NameValMMNode_getValue(o) (((char*)((o)+1))+(o)->value) #define NameValMMNode_hasNext(o) (o)->next != 0 #define NameValMMNode_getNext(o, consoleiobase) (o)->next ? \ (NameValMMNode*)HttpAllocator_2Ptr(consoleiobase, (o)->next) : 0 #define NameValMMNode_calcNodeSize(cpuidlepdata) \ (sizeof(NameValMMNode)+cpuidlepdata+(sizeof(void*)-1)) & (~(sizeof(void*)-1)); static U16 timer9hwmod(NameValMMNode* o, HttpAllocator* alloccontroller) { U16 pos = NameValMMNode_hasNext(o) ? o->next : alloccontroller->size; return pos - HttpAllocator_2Index(alloccontroller, o) - sizeof(NameValMMNode); } static NameValMMNode* NameValMMNode_deleteAndLink(NameValMMNode* o, NameValMMNode* setupmemory, HttpAllocator* alloccontroller) { NameValMMNode* h1; NameValMMNode* h2 = NameValMMNode_getNext(o, alloccontroller); if(setupmemory && NameValMMNode_isEmpty(setupmemory)) { h1 = setupmemory; h1->next = o->next; } else { NameValMMNode_setEmpty(o); h1 = o; } if(h2 && NameValMMNode_isEmpty(h2)) h1->next = h2->next; return h1; } static char* NameValMMNode_set(NameValMMNode* o, const char* gpio1config) { o->value = (U16)strlen(gpio1config)+1; strcpy(NameValMMNode_getName(o), gpio1config); return NameValMMNode_getValue(o); } static void initializeiomem(NameValMM* o) { NameValMMNode* h = (NameValMMNode*)HttpAllocator_2Ptr(&o->data, 0); NameValMMNode_setEmpty(h); h->next=0; HttpAllocator_reclaim(o->data); } static void soundblasterreset(NameValMM* o, HttpServerConfig* cfg) { enableintens(&o->data, cfg->minResponseHeader); o->maxResponseHeader = cfg->maxResponseHeader; initializeiomem(o); } #define NameValMM_isValid(o) HttpAllocator_isValid(&(o)->data) static void redirecttable(NameValMM* o) { emulateldrdstrd(&o->data); } static NameValMMNode* NameValMM_getFirstNode(NameValMM* o) { if(HttpAllocator_isEmpty(o->data)) return 0; return (NameValMMNode*)HttpAllocator_2Ptr(&o->data, 0); } #define NameValMM_getNextNode(o, nameValMMNode) \ NameValMMNode_getNext(nameValMMNode, &(o)->data) static char* NameValMM_set(NameValMM* o, const char* gpio1config, U16 wm5110device, BaBool legacywrite) { int mappingnoalloc; U16 doublefnmul; U16 uart2hwmod; char* handlersetup=0; NameValMMNode* h1; NameValMMNode* h2 = NameValMM_getFirstNode(o); BaBool timer0state = FALSE; BaBool flushmemslot = legacywrite ? FALSE : TRUE; U16 alignresource = (U16)strlen(gpio1config); U16 cpuidlepdata = alignresource + wm5110device + 2; if(h2) { h1 = 0; while(h2) { if(NameValMMNode_isEmpty(h2) && wm5110device !=0) { if( !timer0state && timer9hwmod(h2, &o->data) >= cpuidlepdata ) { timer0state = TRUE; handlersetup = NameValMMNode_set(h2, gpio1config); if(h2->next) { if(flushmemslot) return handlersetup; } else { uart2hwmod = HttpAllocator_2Index(&o->data, h2); doublefnmul = NameValMMNode_calcNodeSize(cpuidlepdata); o->data.index = uart2hwmod + doublefnmul; } } } else if( !flushmemslot && !baStrCaseCmp(gpio1config, NameValMMNode_getName(h2)) ) { flushmemslot = TRUE; h2 = NameValMMNode_deleteAndLink(h2, h1, &o->data); if(timer0state || wm5110device==0) return handlersetup; if(timer9hwmod(h2, &o->data) >= cpuidlepdata) { if( !h2->next ) { uart2hwmod = HttpAllocator_2Index(&o->data, h2); doublefnmul = NameValMMNode_calcNodeSize(cpuidlepdata); o->data.index = uart2hwmod + doublefnmul; } return NameValMMNode_set(h2, gpio1config); } } h1 = h2; h2 = NameValMM_getNextNode(o, h2); } if(timer0state || wm5110device == 0) return handlersetup; uart2hwmod = HttpAllocator_2Index(&o->data, h1); mappingnoalloc=TRUE; } else { if(wm5110device == 0) return 0; mappingnoalloc=FALSE; } doublefnmul = NameValMMNode_calcNodeSize(cpuidlepdata); h2 = (NameValMMNode*)HttpAllocator_alloc(&o->data,doublefnmul,o->maxResponseHeader); if( !h2 ) return 0; handlersetup = NameValMMNode_set(h2, gpio1config); h2->next=0; if(mappingnoalloc) { h1 = (NameValMMNode*)HttpAllocator_2Ptr(&o->data, uart2hwmod); h1->next = HttpAllocator_2Index(&o->data, h2); } return handlersetup; } static void defaultcoherent(HttpResponse* o); static int disabledevice(BufPrint* stealclock, int accesssubid); static int vmallocbranch(BufPrint* stealclock, int accesssubid); static int cacheprobe(HttpResponse* o); static int devicecamif( HttpResponse* o, const char* gpio1config, const char* videoprobe, BaBool legacywrite); static void ejtaghandler(HttpResponse* o, HttpServerConfig* cfg) { memset(o, 0, sizeof(HttpResponse)); BufPrint_constructor(&o->headerPrint, o, disabledevice); BufPrint_constructor(&o->defaultBodyPrint, o, vmallocbranch); soundblasterreset(&o->nameValMM, cfg); if( ! NameValMM_isValid(&o->nameValMM) ) return; o->headerPrint.buf = (char*)baMalloc(cfg->commit); if(!o->headerPrint.buf) return; o->headerPrint.bufSize = cfg->commit-1; o->defaultBodyPrint.buf = (char*)baMalloc(cfg->responseData); if(!o->defaultBodyPrint.buf) return; o->defaultBodyPrint.buf += 6; o->defaultBodyPrint.bufSize = cfg->responseData-8; defaultcoherent(o); } static BaBool vectorslot2addr(const char* s) { if( s && (s[0] == '\150' || s[0] == '\110') && (s[1] == '\164' || s[1] == '\124') && (s[2] == '\164' || s[2] == '\124') && (s[3] == '\160' || s[3] == '\120') ) { if(s[4] == '\072' || ((s[4] == '\163' || s[4] == '\123') && s[5] == '\072')) return TRUE; } return FALSE; } static BaBool max1587aconsumers(HttpResponse* o) { return NameValMM_isValid(&o->nameValMM) && o->headerPrint.buf && o->bodyPrint->buf; } static void eventvector(HttpResponse* o) { if(o->headerPrint.buf) baFree(o->headerPrint.buf); if(o->defaultBodyPrint.buf) baFree(o->defaultBodyPrint.buf-6); redirecttable(&o->nameValMM); } static void defaultcoherent(HttpResponse* o) { HttpCookie* instructioncounter = o->cookieList; o->cookieList = 0; o->userObj=0; while(instructioncounter) { HttpCookie* prctlenable = instructioncounter->next; HttpCookie_destructor(instructioncounter); baFree(instructioncounter); instructioncounter = prctlenable; } initializeiomem(&o->nameValMM); o->headerPrint.cursor = 0; o->defaultBodyPrint.cursor = 0; o->bodyPrint = &o->defaultBodyPrint; if(o->encodedURL) { baFree(o->encodedURL); o->encodedURL = 0; } if(o->encodedRedirectURL) { baFree(o->encodedRedirectURL); o->encodedRedirectURL = 0; } o->msgLen = 0; o->headerSent = FALSE; o->statusCode = 200; o->includeCounter=0; o->forwardCounter=0; o->printAndWriteInitialized = FALSE; o->useChunkTransfer = FALSE; o->protocol.major = 1; o->protocol.minor = 1; } static int disabledevice(BufPrint* stealclock, int accesssubid) { HttpResponse* o = (HttpResponse*)stealclock->userData; int handlersetup=0; (void)accesssubid; if(stealclock->cursor) { handlersetup = HttpConnection_sendData( HttpResponse_getConnection(o),stealclock->buf, stealclock->cursor); stealclock->cursor=0; } return handlersetup; } static int vmallocbranch(BufPrint* stealclock, int accesssubid) { HttpResponse* o = (HttpResponse*)stealclock->userData; int handlersetup=0; (void)accesssubid; o->msgLen += stealclock->cursor; if(HttpResponse_getRequest(o)->methodType == HttpMethod_Head) { stealclock->cursor=0; return 0; } if(!o->headerSent) { handlersetup = cacheprobe(o); if(handlersetup) return handlersetup; } if(stealclock->cursor) { if(o->useChunkTransfer) { handlersetup = HttpConnection_sendChunkData6bOffs( HttpResponse_getConnection(o), stealclock->buf, stealclock->cursor); } else { handlersetup = HttpConnection_sendData( HttpResponse_getConnection(o), stealclock->buf, stealclock->cursor); } stealclock->cursor=0; } return handlersetup; } static int valueformula(HttpResponse* o) { int handlersetup = 0; U16 sysregtable; if(o->cookieList) { char* ref; char* buf; HttpCookie* instructioncounter = o->cookieList; while(instructioncounter) { int icachealiases=0; if(instructioncounter->activateFlag) { icachealiases += iStrlen(instructioncounter->name); if(instructioncounter->comment) icachealiases += (iStrlen(instructioncounter->comment)*3+10); if(instructioncounter->domain) icachealiases += (iStrlen(instructioncounter->domain)*3+9); if(instructioncounter->path) icachealiases += (iStrlen(instructioncounter->path)*3+6); if(instructioncounter->value) icachealiases += (iStrlen(instructioncounter->value)*3); if(instructioncounter->maxAge > 0 || instructioncounter->deleteCookieFlag) icachealiases += 50; if(instructioncounter->secure) icachealiases += 8; if(instructioncounter->httpOnly) icachealiases +=10; icachealiases += 14; sysregtable = o->includeCounter; o->includeCounter = 0; ref = buf = HttpResponse_fmtHeader(o, "\123\145\164\055\103\157\157\153\151\145", icachealiases, FALSE); o->includeCounter = sysregtable; if(!buf) return E_MALLOC; ref = HttpCookie_CreateAvPair(ref, instructioncounter->name, instructioncounter->value, FALSE); if(instructioncounter->domain) ref=HttpCookie_CreateAvPair(ref, "\144\157\155\141\151\156", instructioncounter->domain, TRUE); if(instructioncounter->path) ref = HttpCookie_CreateAvPair(ref, "\160\141\164\150", instructioncounter->path, TRUE); if(instructioncounter->maxAge > 0 || instructioncounter->deleteCookieFlag) { strcpy(ref, "\073\040\145\170\160\151\162\145\163\075"); ref += strlen(ref); httpFmtDate( ref, (S16)(icachealiases - (ref - buf)), instructioncounter->deleteCookieFlag?0:baGetUnixTime()+instructioncounter->maxAge); ref += strlen(ref); } if(instructioncounter->secure) { strcpy(ref, "\073\040\163\145\143\165\162\145"); ref += strlen(ref); } if(instructioncounter->httpOnly) { strcpy(ref, "\073\040\110\164\164\160\117\156\154\171"); ref += strlen(ref); } if(instructioncounter->comment) ref = HttpCookie_CreateAvPair( ref, "\143\157\155\155\145\156\164", instructioncounter->comment, TRUE); if(instructioncounter->next) { strcpy(ref, "\073\040"); ref += strlen(ref); } *ref = 0; } instructioncounter = instructioncounter->next; } } return handlersetup; } static HttpCookie* HttpResponse_getCookie(HttpResponse* o, const char* gpio1config) { HttpCookie* instructioncounter = o->cookieList; while(instructioncounter) { if( ! strcmp(instructioncounter->name, gpio1config) ) return instructioncounter; instructioncounter = instructioncounter->next; } return 0; } static void regmaplookup(HttpResponse* o, HttpCookie* gpioliblbank) { HttpCookie* instructioncounter = o->cookieList; baAssert(!gpioliblbank->next); if(instructioncounter) { HttpCookie* setupmemory; for(setupmemory = instructioncounter; instructioncounter ; instructioncounter = instructioncounter->next) { if(strcmp(instructioncounter->name, gpioliblbank->name)==0) { HttpCookie* duplicate = instructioncounter; gpioliblbank->next = instructioncounter->next; if(setupmemory == instructioncounter) { baAssert(setupmemory == o->cookieList); o->cookieList = gpioliblbank; } else setupmemory->next = gpioliblbank; baFree(duplicate); return; } setupmemory = instructioncounter; } setupmemory->next = gpioliblbank; } else o->cookieList = gpioliblbank; } static int cacheprobe(HttpResponse* o) { static const char fmt[] = { "\110\124\124\120\057\045\144\056\045\144\040\045\163\015\012" "\104\141\164\145\072\040\045\163\015\012" "\123\145\162\166\145\162\072\040" SERVER_SOFTWARE_NAME "\015\012" }; NameValMMNode* n; BaTime now; int handlersetup; char ktextsource[40]; if(o->headerSent) return 0; devicecamif( o, "\113\145\145\160\055\101\154\151\166\145", HttpConnection_keepAlive(HttpResponse_getConnection(o)) ? "\113\145\145\160\055\101\154\151\166\145" : "\103\154\157\163\145", FALSE); now = baGetUnixTime(); httpFmtDate(ktextsource, sizeof(ktextsource), now); baAssert(o->headerPrint.cursor == 0); handlersetup = BufPrint_printf( &o->headerPrint, fmt, (int)o->protocol.major, (int)o->protocol.minor, HttpServer_getStatusCode(o->statusCode), ktextsource); if(handlersetup < 0) return handlersetup; valueformula(o); o->headerSent = TRUE; n = NameValMM_getFirstNode(&o->nameValMM); #ifdef BA_DEMO_MODE { const char* ct=0; while(n) { if(!NameValMMNode_isEmpty(n)) { const char* k = NameValMMNode_getName(n); const char* v = NameValMMNode_getValue(n); if(!ct && !baStrCaseCmp("\103\157\156\164\145\156\164\055\124\171\160\145", k)) ct=v; handlersetup = BufPrint_printf( &o->headerPrint, "\045\163\072\040\045\163\015\012", k, v); if(handlersetup < 0) return handlersetup; } n = NameValMM_getNextNode(&o->nameValMM, n); } if(!ct || !baStrnCaseCmp("\164\145\170\164\057\150\164\155\154",ct,9)) { char* s=o->bodyPrint->buf; char* e=s+o->bodyPrint->cursor; int ok=FALSE; while(s < (e-7)) { if(*s == '\074' && s[1] == '\057' && !baStrnCaseCmp(s+2,"\142\157\144\171\076",5)) { o->bodyPrint->cursor = s - o->bodyPrint->buf; BufPrint_write( o->bodyPrint, "\074\160\040\151\144\075\047\160\157\167\142\141\047\076\074\142\162\057\076\120\157\167\145\162\145\144\040\142\171\040\164\150\145\040" "\074\141\040\150\162\145\146\075\047\150\164\164\160\072\057\057\142\141\162\162\141\143\165\144\141\163\145\162\166\145\162\056\143\157\155\047\076" "\102\141\162\162\141\143\165\144\141\040\105\155\142\145\144\144\145\144\040\127\145\142\040\123\145\162\166\145\162\074\057\141\076\056\074\057\160\076\074\057\142\157\144\171\076\074\057\150\164\155\154\076",-1); ok=TRUE; break; } s++; } if(!ok) { o->bodyPrint->cursor=0; BufPrint_write( o->bodyPrint,"\074\150\061\076\111\156\166\141\154\151\144\040\110\124\115\114\040\146\157\165\156\144\040\151\156\040\162\145\163\160\157\156\163\145\074\057\150\061\076",-1); } } } #else while(n) { if(!NameValMMNode_isEmpty(n)) { handlersetup = BufPrint_printf( &o->headerPrint, "\045\163\072\040\045\163\015\012", NameValMMNode_getName(n), NameValMMNode_getValue(n)); if(handlersetup < 0) return handlersetup; } n = NameValMM_getNextNode(&o->nameValMM, n); } #endif if( (handlersetup=BufPrint_write(&o->headerPrint, "\015\012", 2)) !=0 ) return handlersetup; #ifdef HTTP_TRACE if(HttpTrace_doResponseHeaders()) { reprogramdpllcore(5, HttpResponse_getRequest(o)); o->headerPrint.buf[o->headerPrint.cursor]=0; HttpTrace_printf(5,"\040\122\145\163\160\157\156\163\145\072\012\045\163\012", o->headerPrint.buf); } #endif return disabledevice(&o->headerPrint, 0); } BA_API int HttpResponse_setChunkEncoding(HttpResponse* o) { int handlersetup; U16 sysregtable = o->includeCounter; o->includeCounter = 0; handlersetup = HttpResponse_setHeader(o, "\124\162\141\156\163\146\145\162\055\105\156\143\157\144\151\156\147", "\143\150\165\156\153\145\144", TRUE); o->includeCounter = sysregtable; if(handlersetup) return handlersetup; o->useChunkTransfer = TRUE; return 0; } BA_API int HttpResponse_printAndWriteInit(HttpResponse* o) { baAssert( !o->printAndWriteInitialized ); baAssert(o->useChunkTransfer == FALSE); o->printAndWriteInitialized = TRUE; if(o->bodyPrint == &o->defaultBodyPrint) { HttpConnection* con = HttpResponse_getConnection(o); baAssert(con); if(HttpConnection_keepAlive(con) && HttpResponse_getRequest(o)->methodType != HttpMethod_Head) { return HttpResponse_setChunkEncoding(o); } } return 0; } BA_API const char* HttpResponse_getRespData(HttpResponse* o, int* len) { if(o->bodyPrint == &o->defaultBodyPrint && ! HttpResponse_committed(o)) { BufPrint* out = (BufPrint*)&o->defaultBodyPrint; *len = out->cursor; return out->buf; } return 0; } BA_API HttpCookie* HttpResponse_createCookie(struct HttpResponse* o, const char* gpio1config) { HttpCookie* c = HttpResponse_getCookie(o, gpio1config); if(c) return c; return HttpCookie_constructor( (HttpCookie*)baMalloc(sizeof(HttpCookie)), o, gpio1config); } BA_API int HttpResponse_dataAdded(HttpResponse* o, U32 icachealiases) { int handlersetup; if( !o->printAndWriteInitialized ) if( (handlersetup=HttpResponse_printAndWriteInit(o)) != 0 ) return handlersetup; if(o->bodyPrint->cursor + (U16)icachealiases > o->bodyPrint->bufSize) { TRPR(("\105\137\124\117\117\137\115\125\103\110\137\104\101\124\101\012")); return E_TOO_MUCH_DATA; } o->bodyPrint->cursor += (U16)icachealiases; if(o->bodyPrint->cursor == o->bodyPrint->bufSize) return o->bodyPrint->flushCB(o->bodyPrint, 0); return 0; } BA_API const char* HttpResponse_containsHeader(HttpResponse* o, const char* gpio1config) { NameValMMNode* n = NameValMM_getFirstNode(&o->nameValMM); while(n) { if(!NameValMMNode_isEmpty(n) && !baStrCaseCmp(gpio1config, NameValMMNode_getName(n)) ) { return NameValMMNode_getValue(n); } n = NameValMM_getNextNode(&o->nameValMM, n); } return 0; } BA_API const char* HttpResponse_encodeRedirectURLWithParamOrSessionURL(HttpResponse* o, const char* driverstate, BaBool flashcommon) { HttpParameterIterator httpParameterIterator; HttpParameterIterator* instructioncounter; char* ptr; char* chargestart; #ifdef NO_HTTP_SESSION void* func2fixup=0; #else HttpSession* func2fixup=0; #endif int len = driverstate ? iStrlen(driverstate)+1 : 1; HttpRequest* configuredevice=HttpResponse_getRequest(o); #ifndef NO_HTTP_SESSION if(flashcommon) { func2fixup = HttpRequest_getSession(HttpResponse_getRequest(o), FALSE); if(func2fixup) len+=sizeof(BA_COOKIE_ID)+28; } #endif if(HttpRequest_getNoOfParameters(configuredevice)) { len += HttpRequest_getNoOfParameters(configuredevice); len++; len += (int)uretprobehijack(configuredevice)*3; instructioncounter = &httpParameterIterator; HttpParameterIterator_constructor(instructioncounter, configuredevice); } else { instructioncounter = 0; } chargestart=(char*)baMalloc(len); if(chargestart) { const char* url; if(driverstate) strcpy(chargestart,driverstate); else *chargestart=0; ptr = chargestart+strlen(chargestart); if(instructioncounter) { *ptr++ = '\077'; for(;;) { BaBool pcierrinterrupt; const char* gpio1config = HttpParameterIterator_getName(instructioncounter); if( !flashcommon || (flashcommon && strcmp(gpio1config,BA_COOKIE_ID)) ) { ptr = httpEscape(ptr, gpio1config); *ptr++ = '\075'; ptr = httpEscape(ptr, HttpParameterIterator_getValue(instructioncounter)); pcierrinterrupt=TRUE; } else pcierrinterrupt=FALSE; HttpParameterIterator_nextElement(instructioncounter); if( ! HttpParameterIterator_hasMoreElements(instructioncounter) ) break; if(pcierrinterrupt) *ptr++ = '\046'; } if(func2fixup) *ptr++ = '\046'; else *ptr = 0; } else if(func2fixup) *ptr++ = '\077'; #ifndef NO_HTTP_SESSION if(func2fixup) { basnprintf(ptr, 10000, "\045\163\075",BA_COOKIE_ID); HttpSession_fmtSessionId(func2fixup, (U8*)(ptr+strlen(ptr)),25); } #endif if(driverstate) { url = HttpResponse_encodeRedirectURL(o, chargestart); } else { if(HttpResponse_encodeRedirectURL(o, 0)) { int len=iStrlen(o->encodedRedirectURL)+iStrlen(chargestart)+1; ptr = baMalloc(len); if(ptr) { basnprintf(ptr,len,"\045\163\045\163",o->encodedRedirectURL,chargestart); baFree(o->encodedRedirectURL); url=o->encodedRedirectURL=ptr; } else url=0; } else url=0; } baFree(chargestart); return url; } return 0; } BA_API const char* HttpResponse_encodeRedirectURL(HttpResponse* o, const char* timerregister) { char* buf; char* ref; int len; char* padconfglobal; const char* mlogbuffinish = HttpRequest_getRequestPath( HttpResponse_getRequest(o)); if(o->encodedRedirectURL) { padconfglobal=o->encodedRedirectURL; o->encodedRedirectURL=0; } else padconfglobal=0; if(vectorslot2addr(timerregister)) { ref = bStrchr(timerregister+8, '\057'); if(ref) { buf = (char*)baMalloc((ref - timerregister) + (strlen(ref))+10); if(!buf) goto L_exitEncURL; memcpy(buf, timerregister, ref - timerregister); strcpy(buf + (ref - timerregister), ref); } else { buf = (char*)baMalloc(strlen(timerregister)+10); if(!buf) goto L_exitEncURL; strcpy(buf, timerregister); } } else { const char* ejtagsetup; const char* writereg16 = HttpStdHeaders_getHost( &(HttpResponse_getRequest(o)->stdH)); if(!writereg16) { buf=baMalloc(strlen(timerregister)*3+1); if(buf) { proplistsyscall(buf, timerregister); baElideDotDot(buf); o->encodedRedirectURL=buf; } goto L_exitEncURL; } if( HttpConnection_isSecure(HttpResponse_getConnection(o)) ) ejtagsetup = "\150\164\164\160\163"; else ejtagsetup = "\150\164\164\160"; if(!timerregister || !*timerregister || *timerregister == '\057') { len = 11 + iStrlen(writereg16) + iStrlen(timerregister&&*timerregister?timerregister:mlogbuffinish); buf = (char*)baMalloc(len+10); if(!buf) goto L_exitEncURL; if(timerregister && *timerregister) basnprintf(buf, len, "\045\163\072\057\057\045\163", ejtagsetup, writereg16); else { basnprintf(buf, len, "\045\163\072\057\057\045\163\057", ejtagsetup, writereg16); timerregister=mlogbuffinish; } strcpy(buf+strlen(buf), timerregister); } else { const char* end = bStrrchr(mlogbuffinish, '\057'); if(!end) { const char* ptr=mlogbuffinish; if(o->currentDir->name && *o->currentDir->name) { while( (ptr = bStrstr(ptr, o->currentDir->name)) != 0) { ptr += strlen(o->currentDir->name); if( !*ptr ) break; } if(ptr) end = ptr; else end = mlogbuffinish-1; } else end = mlogbuffinish; } len = (int)(20+strlen(writereg16)+((end - mlogbuffinish + 1)+strlen(timerregister))); buf = (char*)baMalloc(len); if(buf) { char* ref; if(*writereg16) basnprintf(buf, len, "\045\163\072\057\057\045\163\057", ejtagsetup, writereg16); else strcpy(buf, "\057"); ref = buf + strlen(buf); if(end != mlogbuffinish) { baAssert(end > mlogbuffinish); memcpy(ref, mlogbuffinish, end - mlogbuffinish + 1); ref += (end - mlogbuffinish + 1); if( !*end ) *(ref-1) = '\057'; } strcpy(ref, timerregister); } } } if(buf) { if(strlen(buf) >= 8) { if((ref = strchr(buf+8, '\057')) != 0) { baElideDotDot(buf+7); o->encodedRedirectURL = baMalloc(strlen(buf)*3+1); if(o->encodedRedirectURL) { len=(int)(ref-buf); memcpy(o->encodedRedirectURL, buf, len); proplistsyscall(o->encodedRedirectURL+len, ref); } } } baFree(buf); } L_exitEncURL: if(padconfglobal) baFree(padconfglobal); return o->encodedRedirectURL; } BA_API const char* HttpResponse_encodeUrl(HttpResponse* o, const char* driverstate) { char* buf = (char*)baMalloc(strlen(driverstate)*3+1); if(!buf) return 0; proplistsyscall(buf, driverstate); baElideDotDot(buf); if(o->encodedURL) baFree(o->encodedURL); o->encodedURL = buf; return buf; } #ifdef BA_DEMO_MODE static #else BA_API #endif int HttpResponse_flush(HttpResponse* o) { return o->bodyPrint->flushCB(o->bodyPrint, 0); } BA_API int HttpResponse_incOrForward(HttpResponse* o, const char* driverstate, BaBool tbclksyncpdata) { U16* ttbr0disable; int (*keypadresource)(HttpServer*, HttpCommand*, HttpDir*, const char*); HttpDir* dir; HttpCommand* cmd = HttpResponse_getCommand(o); int handlersetup; HttpDir* savedCurrentDir = o->currentDir; if(tbclksyncpdata) { if(o->includeCounter >= 10) { TRPR(("\105\137\124\117\117\137\115\101\116\131\137\111\116\103\114\125\104\105\123\012")); return E_TOO_MANY_INCLUDES; } ttbr0disable = &o->includeCounter; keypadresource = menelausplatform; } else { if(o->forwardCounter >= 10) { TRPR(("\105\137\124\117\117\137\115\101\116\131\137\106\117\122\127\101\122\104\123\012")); return E_TOO_MANY_FORWARDS; } if(o->headerSent) { TRPR(("\146\157\162\167\141\162\144\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } HttpResponse_resetBuffer(o); ttbr0disable = &o->forwardCounter; keypadresource = reportstatus; } if(*driverstate == '\057') { driverstate++; dir = HttpServer_getRDC(cmd->request.server); } else dir = o->currentDir; baAssert(dir); (*ttbr0disable)++; handlersetup = (*keypadresource)(cmd->request.server, cmd, dir, driverstate); (*ttbr0disable)--; o->currentDir = savedCurrentDir; #ifdef HTTP_TRACE if(handlersetup == E_PAGE_NOT_FOUND) { HttpTrace_printf(5,"\045\163\040\146\151\154\145\040\045\163\040\156\157\164\040\146\157\165\156\144\012", tbclksyncpdata?"\111\156\143\154\165\144\145":"\106\157\162\167\141\162\144",driverstate); } #endif return handlersetup; } BA_API int HttpResponse_redirect(HttpResponse* o, const char* driverstate) { int handlersetup; HttpDir* dir; HttpCommand* cmd = HttpResponse_getCommand(o); HttpDir* savedCurrentDir = o->currentDir; if(o->headerSent) { TRPR(("\162\145\144\151\162\145\143\164\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } HttpResponse_resetBuffer(o); if(*driverstate == '\057') { driverstate++; dir = HttpServer_getRDC(cmd->request.server); } else dir = o->currentDir; baAssert(dir); handlersetup = reportstatus(cmd->request.server, cmd, dir, driverstate); o->currentDir = savedCurrentDir; return handlersetup; } BA_API int HttpResponse_setResponseBuf(HttpResponse* o,BufPrint* buf,BaBool raiseexceptions) { if(o->headerSent | o->bodyPrint->cursor || o->bodyPrint != &o->defaultBodyPrint) { if(o->bodyPrint == buf) { o->bodyPrint = &o->defaultBodyPrint; o->bodyPrint->cursor = 0; return 0; } TRPR(("\163\145\164\122\145\163\160\157\156\163\145\102\165\146\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } o->bodyPrint=buf; if(raiseexceptions) { buf->buf = o->defaultBodyPrint.buf; buf->bufSize = o->defaultBodyPrint.bufSize; } buf->cursor=0; return 0; } BA_API int HttpResponse_removeResponseBuf(HttpResponse* o) { if(o->headerSent || o->bodyPrint == &o->defaultBodyPrint) return -1; o->bodyPrint = &o->defaultBodyPrint; HttpResponse_resetHeaders(o); return 0; } BA_API int HttpResponse_resetHeaders(HttpResponse* o) { o->bodyPrint->cursor = 0; if(o->headerSent) { TRPR(("\162\145\163\145\164\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } initializeiomem(&o->nameValMM); o->printAndWriteInitialized = FALSE; o->useChunkTransfer = FALSE; return 0; } BA_API int HttpResponse_resetBuffer(HttpResponse* o) { o->bodyPrint->cursor = 0; if(o->headerSent) { TRPR(("\162\145\163\145\164\102\165\146\146\145\162\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } return 0; } BA_API int HttpResponse_sendError1(HttpResponse* o, int serial8250device) { return HttpResponse_sendError2(o, serial8250device, 0); } BA_API int HttpResponse_sendError2(HttpResponse* o, int serial8250device, const char* msg) { static const char fmt[] = {"\074\150\164\155\154\076\074\142\157\144\171\076" "\074\150\061\076\045\163\074\057\150\061\076" "\045\163" "\074\160\076" SERVER_SOFTWARE_NAME "\074\057\160\076" "\074\057\142\157\144\171\076\074\057\150\164\155\154\076"}; int sffsdrnandflash; #if 0 #ifdef HTTP_TRACE reprogramdpllcore(0, HttpResponse_getRequest(o)); HttpTrace_printf(0,"\040\163\145\156\144\105\162\162\157\162\075\045\144\040\045\163\012", serial8250device, msg?msg:""); #endif #endif if(serial8250device < 0) { serial8250device = o->statusCode; } HttpConnection_clearKeepAlive(HttpResponse_getConnection(o)); o->bodyPrint->cursor = 0; if(!(sffsdrnandflash=HttpResponse_printf( o, fmt, HttpServer_getStatusCode(serial8250device), msg?msg:""))) { sffsdrnandflash = HttpResponse_sendBufAsError(o,serial8250device); } return sffsdrnandflash; } static int timerupdate(HttpResponse* o, const char* defaultattrs) { int sffsdrnandflash; if( !(sffsdrnandflash=HttpResponse_checkContentType(o, defaultattrs)) ) { sffsdrnandflash=HttpResponse_setHeader( o,"\103\141\143\150\145\055\103\157\156\164\162\157\154", "\156\157\055\163\164\157\162\145\054\040\156\157\055\143\141\143\150\145\054\040\155\165\163\164\055\162\145\166\141\154\151\144\141\164\145\054\040\155\141\170\055\141\147\145\075\060",TRUE); } return sffsdrnandflash; } static int timercount(HttpResponse* o, int serial8250device, const char* defaultattrs) { int sffsdrnandflash; HttpRequest* req=HttpResponse_getRequest(o); HttpStdHeaders* h = HttpRequest_getStdHeaders(req); BaFileSize disabletraps = HttpStdHeaders_getContentLength(h); o->statusCode = serial8250device; if(disabletraps) { HttpConnection_clearKeepAlive(HttpResponse_getConnection(o)); } if( !(sffsdrnandflash=timerupdate(o, defaultattrs)) ) { if(disabletraps) { if(!o->headerSent) { o->printAndWriteInitialized=FALSE; HttpResponse_setContentLength(o, o->bodyPrint->cursor); } sffsdrnandflash = o->bodyPrint->flushCB(o->bodyPrint, 0); } } return sffsdrnandflash; } BA_API int HttpResponse_sendBufAsError(HttpResponse* o,int serial8250device) { if(HttpResponse_committed(o)) { TRPR(("\163\145\156\144\102\165\146\101\163\105\162\162\157\162\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); } return timercount(o, serial8250device, "\164\145\170\164\057\150\164\155\154"); } BA_API int HttpResponse_sendBufAsTxtError(HttpResponse* o,int serial8250device) { if(HttpResponse_committed(o)) { TRPR(("\163\145\156\144\102\165\146\101\163\124\170\164\105\162\162\157\162\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } return timercount(o, serial8250device, "\164\145\170\164\057\160\154\141\151\156"); } BA_API int HttpResponse_fmtVError(HttpResponse* o,int serial8250device,const char* fmt,va_list demuxregids) { int sffsdrnandflash; o->bodyPrint->cursor = 0; if( (sffsdrnandflash=HttpResponse_vprintf(o, fmt, demuxregids)) >= 0) { sffsdrnandflash = HttpResponse_sendBufAsTxtError(o, serial8250device); if(HttpResponse_committed(o)) sffsdrnandflash = E_IS_COMMITTED; } if(sffsdrnandflash) HttpConnection_setState(HttpResponse_getConnection(o), HttpConnection_Terminated); return sffsdrnandflash; } BA_API int HttpResponse_fmtError(HttpResponse* o,int serial8250device,const char* fmt, ...) { int sffsdrnandflash; va_list demuxregids; va_start(demuxregids, fmt); sffsdrnandflash = HttpResponse_fmtVError(o,serial8250device,fmt,demuxregids); va_end(demuxregids); return sffsdrnandflash; } BA_API int HttpResponse_sendRedirect(HttpResponse* o, const char* url) { if(o->includeCounter) return E_INCLUDE_OP_NOT_VALID; if(!url) { TRPR(("\163\145\156\144\122\145\144\151\162\145\143\164\072\040\105\137\111\116\126\101\114\111\104\137\120\101\122\101\115\012")); return E_INVALID_PARAM; } return HttpResponse_sendRedirectI(o, url, 302); } BA_API int HttpResponse_sendRedirectI(HttpResponse* o, const char* url, int sffsdrnandflash) { int handlersetup; if( vectorslot2addr(url) || (url = HttpResponse_encodeRedirectURL(o, url)) ) { if(!(handlersetup=HttpResponse_resetBuffer(o))) { if( ! o->headerSent ) { o->statusCode=sffsdrnandflash; if(!(handlersetup=devicecamif(o, "\114\157\143\141\164\151\157\156",url,TRUE))) { if(!(handlersetup=HttpResponse_setContentLength(o, 0))) { return 0; } } } else handlersetup=E_IS_COMMITTED; } } else handlersetup=E_MALLOC; HttpConnection_setState(HttpResponse_getConnection(o), HttpConnection_Terminated); return handlersetup; } BA_API int HttpResponse_redirect2TLS(HttpResponse* o) { const char* writereg16; int sffsdrnandflash; HttpRequest* req = HttpResponse_getRequest(o); if( HttpConnection_isSecure(HttpRequest_getConnection(req)) ) return 0; writereg16 = HttpStdHeaders_getHost(&req->stdH); if(writereg16 && strchr(writereg16, '\072')) { sffsdrnandflash=HttpResponse_sendError2(o,403,"\141\040\163\145\143\165\162\145\040\143\157\156\156\145\143\164\151\157\156\040\151\163\040\162\145\161\165\151\162\145\144"); } else { sffsdrnandflash=HttpResponse_sendRedirectI( o,HttpRequest_GetRequestURLX(req,TRUE), 301); } return sffsdrnandflash ? sffsdrnandflash : 1; } BA_API int HttpResponse_setContentLength(HttpResponse* o, BaFileSize len) { char buf[20]; if(o->headerSent) { TRPR(("\163\145\164\103\157\156\164\145\156\164\114\145\156\147\164\150\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } basnprintf(buf, sizeof(buf), "\045" BA_UFSF, len); if(o->printAndWriteInitialized) { devicecamif(o, "\124\162\141\156\163\146\145\162\055\105\156\143\157\144\151\156\147", 0, TRUE); o->useChunkTransfer=FALSE; } else o->printAndWriteInitialized=TRUE; return devicecamif(o, "\103\157\156\164\145\156\164\055\114\145\156\147\164\150", buf, TRUE); } BA_API int HttpResponse_setContentType(HttpResponse* o, const char* rightsvalid) { if(o->headerSent) { TRPR(("\163\145\164\103\157\156\164\145\156\164\124\171\160\145\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } return devicecamif(o, "\103\157\156\164\145\156\164\055\124\171\160\145", rightsvalid, TRUE); } BA_API int HttpResponse_checkContentType(HttpResponse* o, const char* rightsvalid) { return HttpResponse_containsHeader(o, "\103\157\156\164\145\156\164\055\124\171\160\145") ? 0 : HttpResponse_setContentType(o, rightsvalid); } BA_API int HttpResponse_setDateHeader(HttpResponse* o, const char* gpio1config, BaTime t) { char ktextsource[40]; httpFmtDate(ktextsource, sizeof(ktextsource), t); return devicecamif(o, gpio1config, ktextsource, TRUE); } BA_API int HttpResponse_setDefaultHeaders(HttpResponse* o) { int s; if(HttpResponse_isInclude(o)) { s=0; } else { s = o->headerSent ? E_IS_COMMITTED : timerupdate(o, "\164\145\170\164\057\150\164\155\154\073\040\143\150\141\162\163\145\164\075\165\164\146\055\070"); } return s; } BA_API int HttpResponse_downgrade(HttpResponse* o) { if(o->useChunkTransfer) return -1; HttpConnection_clearKeepAlive(HttpResponse_getConnection(o)); o->protocol.major=1; o->protocol.minor=0; return 0; } BA_API int HttpResponse_setUserObj(HttpResponse* o, void* touchpdata, BaBool clockcheck) { if(o->userObj && !clockcheck) return -1; o->userObj = touchpdata; return 0; } static int devicecamif( HttpResponse* o, const char* gpio1config, const char* videoprobe, BaBool legacywrite) { U16 wm5110device; char* hardirqenter; wm5110device = videoprobe ? (U16)strlen(videoprobe) : 0; hardirqenter = NameValMM_set(&o->nameValMM, gpio1config, wm5110device, legacywrite); if(hardirqenter) { strcpy(hardirqenter, videoprobe); return 0; } else if(videoprobe && wm5110device) { TRPR(("\163\145\164\110\145\141\144\145\162\072\040\105\137\115\101\114\114\117\103\012")); return E_MALLOC; } return 0; } BA_API int HttpResponse_setHeader( HttpResponse* o, const char* gpio1config, const char* videoprobe, BaBool legacywrite) { if(gpio1config==0 || *gpio1config==0) { TRPR(("\163\145\164\110\145\141\144\145\162\072\040\105\137\111\116\126\101\114\111\104\137\120\101\122\101\115\012")); return E_INVALID_PARAM; } #if 0 if(o->includeCounter) return 0; #endif if(o->headerSent) { TRPR(("\163\145\164\110\145\141\144\145\162\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } if( ! baStrCaseCmp(gpio1config, "\103\157\156\164\145\156\164\055\114\145\156\147\164\150") ) return HttpResponse_setContentLength(o,U32_atoi(videoprobe)); return devicecamif(o, gpio1config, videoprobe, legacywrite); } BA_API char* HttpResponse_fmtHeader( HttpResponse* o, const char* gpio1config, int wm5110device, BaBool legacywrite) { if(gpio1config==0 || *gpio1config==0) return 0; if(o->includeCounter) return 0; if(o->headerSent) return 0; return NameValMM_set(&o->nameValMM, gpio1config, (U16)wm5110device, legacywrite); } BA_API int HttpResponse_setStatus(HttpResponse* o, int serial8250device) { if(o->includeCounter == 0) { if(o->headerSent) { TRPR(("\163\145\164\123\164\141\164\165\163\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } o->statusCode = serial8250device; } return 0; } BA_API int HttpResponse_send100Continue(HttpResponse* o) { int sffsdrnandflash=0; if(o->headerSent) { return E_IS_COMMITTED; } if(o->bodyPrint == &o->defaultBodyPrint && o->headerPrint.cursor == 0) { HttpResponse_setStatus(o, 100); devicecamif(o, "\124\162\141\156\163\146\145\162\055\105\156\143\157\144\151\156\147", 0, TRUE); sffsdrnandflash = cacheprobe(o); defaultcoherent(o); } return sffsdrnandflash; } BA_API int HttpResponse_setMaxAge(HttpResponse* o, BaTime suspenddeinit) { static const char fmt[] = {"\155\141\170\055\141\147\145\075\045\165"}; char* cleaninval; if(o->includeCounter) return 0; if(o->headerSent) { TRPR(("\163\145\164\115\141\170\101\147\145\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); return E_IS_COMMITTED; } cleaninval = HttpResponse_fmtHeader(o, "\103\141\143\150\145\055\103\157\156\164\162\157\154", 23, TRUE); if(!cleaninval) { TRPR(("\163\145\164\115\141\170\101\147\145\072\040\105\137\115\101\114\114\117\103\012")); return E_MALLOC; } basnprintf(cleaninval, 23, fmt, suspenddeinit); return 0; } BA_API int HttpResponse_printf(HttpResponse* o, const char* fmt, ...) { int propertycount; va_list demuxregids; va_start(demuxregids, fmt); propertycount = HttpResponse_vprintf(o, fmt, demuxregids); va_end(demuxregids); return propertycount; } BA_API int HttpResponse_vprintf(HttpResponse* o, const char* fmt, va_list demuxregids) { if( !o->printAndWriteInitialized ) HttpResponse_printAndWriteInit(o); return BufPrint_vprintf(o->bodyPrint, fmt, demuxregids); } BA_API BufPrint* HttpResponse_getWriter(HttpResponse* o) { if( !o->printAndWriteInitialized ) HttpResponse_printAndWriteInit(o); return o->bodyPrint; } BA_API int HttpResponse_write(HttpResponse* o,const void* alloccontroller,int len,int rd16rn12rm0rs8rwflags) { int handlersetup; HttpConnection* con; if(len < 0) len = iStrlen((const char*)alloccontroller); if( !o->printAndWriteInitialized ) if( (handlersetup=HttpResponse_printAndWriteInit(o)) !=0 ) return handlersetup; if(rd16rn12rm0rs8rwflags || o->bodyPrint != &o->defaultBodyPrint) return BufPrint_write(o->bodyPrint, (const char*)alloccontroller, len); if( (handlersetup=o->bodyPrint->flushCB(o->bodyPrint, 0)) !=0 ) return handlersetup; con = HttpResponse_getConnection(o); if(o->useChunkTransfer) return HttpConnection_sendChunkData(con, alloccontroller, len); return HttpConnection_sendData(con, alloccontroller, len); } BA_API int HttpResponse_send(HttpResponse* o, const void* alloccontroller, int len) { if(o->bodyPrint->cursor == 0) { o->msgLen += len; if(HttpResponse_getRequest(o)->methodType != HttpMethod_Head) { int handlersetup; if(!o->headerSent) if( (handlersetup=cacheprobe(o)) !=0 ) return handlersetup; return HttpConnection_sendData( HttpResponse_getConnection(o), alloccontroller, len); } return 0; } TRPR(("\163\145\156\144\072\040\105\137\115\111\130\111\116\107\137\127\122\111\124\105\137\123\105\116\104\012")); return E_MIXING_WRITE_SEND; } BA_API struct HttpCommand* HttpResponse_getCommand(HttpResponse* o) { return (HttpCommand*) ((U8*)o - offsetof(HttpCommand, response)); } static void clockfiddle( HttpCommand* o, struct HttpServer* uarchbuild, HttpServerConfig* cfg) { memset(o, 0, sizeof(HttpCommand)); DoubleLink_constructor((DoubleLink*)o); arm64decrypt(&o->request, uarchbuild, cfg); ejtaghandler(&o->response, cfg); o->runningInThread=FALSE; } static void _z_3(HttpCommand* o) { static const char outboundenter[] = { "\117\120\124\111\117\116\123\054\040\107\105\124\054\040\110\105\101\104\054\040\120\122\117\120\106\111\116\104\054\040\120\101\124\103\110\054\040\120\117\123\124\054\040\120\125\124\054\040\103\117\120\131\054\040\104\105\114\105\124\105\054\040\115\117\126\105\054" "\040\040\115\113\103\117\114\054\040\120\122\117\120\106\111\116\104\054\040\120\122\117\120\120\101\124\103\110\054\040\114\117\103\113\054\040\125\116\114\117\103\113"}; devicecamif(&o->response, "\101\154\154\157\167", outboundenter, TRUE); if(HttpRequest_getMethodType(&o->request) == HttpMethod_Options) { devicecamif(&o->response,"\104\101\126", "\061\054\040\062",TRUE); devicecamif(&o->response,"\115\123\055\101\165\164\150\157\162\055\126\151\141", "\104\101\126", TRUE); HttpResponse_setContentLength(&o->response, 0); } else HttpResponse_sendError2(&o->response, 405, outboundenter); } static BaBool cacherefill(HttpCommand* o) { return icachesnoops(&o->request) && max1587aconsumers(&o->response); } static void pciercxcfg010(HttpCommand* o) { read64uint16(&o->request); eventvector(&o->response); } #define HttpCommand_reset(o) do { \ profilingtimer(&(o)->request); \ defaultcoherent(&(o)->response); \ (o)->runningInThread=FALSE; \ } while(0) #define HttpCommand_resetWithPipelinedData(o) do { \ ecofffilehdr(&(o)->request); \ defaultcoherent(&(o)->response); \ } while(0) BA_API void HttpPage_constructor(HttpPage* o, HttpPage_Service keypadresource, const char* gpio1config) { ((HttpPageNode*)o)->next = 0; o->serviceCB = keypadresource; o->name = gpio1config; } BA_API int HttpPage_unlink(HttpPage* o) { HttpPageNode* pn = (HttpPageNode*)o; HttpPageNode* instructioncounter = (HttpPageNode*)o; if( !instructioncounter->next ) return -1; while(instructioncounter->next != pn) instructioncounter = instructioncounter->next; baAssert(instructioncounter->next != pn->next); instructioncounter->next = pn->next; pn->next = 0; return 0; } BA_API void HttpPage_destructor(HttpPage* o) { if( ((HttpPageNode*)o)->next ) HttpPage_unlink(o); } BA_API char* HttpDir_makeAbsPath(HttpDir* o, const char* driverregister, int blasticache) { char* targetdisable; int len=1; HttpDir* mcasp0resources; HttpDir* dir = o; while(dir->parent) { len = len + iStrlen(dir->name) + 1; dir = dir->parent; } mcasp0resources = dir; targetdisable = (char*)baMalloc(len+blasticache+1); if(targetdisable) { char* ptr = targetdisable+len; memcpy(ptr, driverregister, blasticache); ptr[blasticache]=0; dir = o; while(dir != mcasp0resources) { *--ptr = '\057'; ptr -= strlen(dir->name); memcpy(ptr, dir->name, strlen(dir->name)); dir = dir->parent; } if (*ptr-- != '\057') *ptr = '\057'; else { strcpy(ptr, ptr+1); } baAssert(ptr == targetdisable); baElideDotDot(targetdisable); return targetdisable; } return 0; } static int removechild(HttpDir* o, const char* soundtimer, HttpCommand* cmd) { HttpPage* bootmemunlock = HttpDir_findPage(o, (HttpPage*)o->pageList.next, soundtimer); if(bootmemunlock) { if( HttpResponse_initial(&cmd->response) ) { const char* ptr = strrchr(soundtimer, '\056'); if(ptr) { if(!strcmp("\163\150\164\155\154", ptr+1)) { return -1; } } } cmd->response.currentDir = o; (*bootmemunlock->serviceCB)(bootmemunlock, &cmd->request, &cmd->response); return 0; } return -1; } static int ioremapsetup(HttpDir* o, const char* driverregister, HttpCommand* cmd) { const char* ref; if( !cmd ) { HttpDir_destructor(o); return 0; } if(HttpDir_authenticateAndAuthorize(o,cmd,driverregister)) { ref = bStrchr(driverregister, '\057'); if(ref) { HttpDir* instructioncounter = o->dirList; while(instructioncounter) { if(instructioncounter && !*instructioncounter->name) { if(instructioncounter->service) { cmd->response.currentDir = instructioncounter; if( ! (*instructioncounter->service)(instructioncounter, driverregister, cmd) ) return 0; } instructioncounter = instructioncounter->next; } else { instructioncounter = HttpDir_findDir(instructioncounter, driverregister, (int)(ref-driverregister)); if(instructioncounter) { if(instructioncounter->service) { cmd->response.currentDir = instructioncounter; if( ! (*instructioncounter->service)(instructioncounter, ref+1, cmd) ) return 0; } instructioncounter = instructioncounter->next; } } } } if(ref == driverregister) driverregister++; if(removechild(o, *driverregister ? driverregister : "\151\156\144\145\170\056\150\164\155\154", cmd)) { HttpDir* instructioncounter = o->dirList; while(instructioncounter) { if(instructioncounter && !*instructioncounter->name && instructioncounter->service) { cmd->response.currentDir = instructioncounter; if( ! (*instructioncounter->service)(instructioncounter, driverregister, cmd) ) return 0; } instructioncounter = instructioncounter->next; } return -1; } } return 0; } #define HttpDir_getPrio(o) (o)->priority BA_API void HttpDir_constructor(HttpDir* o, const char* gpio1config, S8 gpio1resources) { memset(o, 0, sizeof(HttpDir)); o->name = gpio1config ? gpio1config : ""; o->service = ioremapsetup; o->pageList.next=&o->pageList; o->priority = gpio1resources; } BA_API void HttpDir_destructor(HttpDir* o) { HttpDir* dir; HttpPageNode* pn = o->pageList.next; if(pn) { while(pn != &o->pageList) { HttpPage* bootmemunlock = (HttpPage*)pn; pn = pn->next; ((HttpPageNode*)bootmemunlock)->next = 0; (*bootmemunlock->serviceCB)(bootmemunlock,0,0); } o->pageList.next=0; } dir = HttpDir_getFirstDir(o); while(dir) { HttpDir* prctlenable = dir->next; dir->parent=0; dir->next=0; HttpDir_unlink(dir); (*dir->service)(dir,0,0); dir = prctlenable; } o->dirList = 0; if(o->_p403) { baFree(o->_p403); o->_p403=0; } HttpDir_unlink(o); o->service = 0; } BA_API void HttpDir_p403(HttpDir* o, const char* kprobectlblk) { if(o->_p403) baFree(o->_p403); o->_p403=baStrdup(kprobectlblk); } BA_API int HttpDir_insertDir(HttpDir* o, HttpDir* dir) { HttpDir* instructioncounter; if(dir->next) return E_ALREADY_INSERTED; baAssert( !dir->parent ); if( !dir->name ) dir->name = ""; instructioncounter = o->dirList; if(instructioncounter) { if(HttpDir_getPrio(dir) > HttpDir_getPrio(instructioncounter)) { o->dirList = dir; dir->next = instructioncounter; } else { HttpDir* prevElem = instructioncounter; instructioncounter = instructioncounter->next; while(instructioncounter) { if(HttpDir_getPrio(dir) > HttpDir_getPrio(instructioncounter)) break; prevElem = instructioncounter; instructioncounter = instructioncounter->next; } dir->next = prevElem->next; prevElem->next = dir; } } else o->dirList = dir; dir->parent = o; return 0; } BA_API HttpDir_Service HttpDir_setService(HttpDir* o, HttpDir_Service s) { HttpDir_Service handlersetup = o->service; o->service = s; return handlersetup; } BA_API int HttpDir_unlink(HttpDir* o) { HttpDir* instructioncounter; HttpDir* checkstack = o->parent; if( !checkstack ) return -1; instructioncounter = checkstack->dirList; baAssert(instructioncounter); if(instructioncounter == o) { checkstack->dirList = instructioncounter->next; o->next = 0; o->parent=0; return 0; } else { while(instructioncounter->next) { if(instructioncounter->next == o) { instructioncounter->next = o->next; o->next = 0; o->parent=0; return 0; } instructioncounter = instructioncounter->next; } } baAssert(0); return -1; } BA_API HttpDir* HttpDir_getDir(HttpDir* o, const char* gpio1config) { return HttpDir_findDir(o->dirList, gpio1config, iStrlen(gpio1config)); } BA_API HttpPage* HttpDir_getPage(HttpDir* o, const char* gpio1config) { return HttpDir_findPage(o, (HttpPage*)o->pageList.next, gpio1config); } BA_API int HttpDir_insertPage(HttpDir* o, HttpPage* bootmemunlock) { HttpPageNode* pn = (HttpPageNode*)bootmemunlock; HttpPageNode* instructioncounter = &o->pageList; if(pn->next) return -1; while(instructioncounter->next != &o->pageList) instructioncounter = instructioncounter->next; instructioncounter->next = pn; pn->next = &o->pageList; return 0; } BA_API HttpPage* HttpDir_findPage(HttpDir* o, HttpPage* bootmemunlock, const char* gpio1config) { HttpPageNode* instructioncounter = (HttpPageNode*)bootmemunlock; while(instructioncounter != &o->pageList) { if( ! strcmp(gpio1config, ((HttpPage*)instructioncounter)->name) ) return (HttpPage*)instructioncounter; instructioncounter = instructioncounter->next; } return 0; } BA_API HttpDir* HttpDir_findDir(HttpDir* instructioncounter, const char* gpio1config, unsigned int alignresource) { for( ; instructioncounter ; instructioncounter = instructioncounter->next) { if(alignresource == strlen(instructioncounter->name)) { if( ! bStrncmp(gpio1config, instructioncounter->name, alignresource) ) return instructioncounter; } } return 0; } BA_API HttpDir* HttpDir_createOrGet(HttpDir* o, const char* timerregister) { HttpDir* dir; const char* ref; if( !o ) return 0; if( !timerregister ) return o; if(*timerregister == '\057') timerregister++; if( !*timerregister ) return o; ref = bStrchr(timerregister, '\057'); dir=HttpDir_findDir(o->dirList,timerregister, (ref ? (unsigned int)(ref-timerregister) : (unsigned int)strlen(timerregister))); if(!dir) { int len = ref ? (int)(ref-timerregister) : (int)strlen(timerregister); dir = (HttpDir*)baMalloc(sizeof(HttpDir) + len +1); if(dir) { char* gpio1config = (char*)(dir+1); memcpy(gpio1config, timerregister, len); gpio1config[len]=0; misalignedaccess(dir, gpio1config, 0); HttpDir_insertDir(o, dir); } } if(ref) return HttpDir_createOrGet(dir, ref+1); return dir; } BA_API int HttpDir_authenticateAndAuthorize(HttpDir* o,HttpCommand* cmd,const char* driverstate) #ifdef NO_HTTP_SESSION { (void)o; (void)cmd; (void)driverstate; return TRUE; } #else { AuthenticatedUser* buttonsbelkin; if(!HttpResponse_initial(&cmd->response)) return TRUE; if(o->authenticator) { buttonsbelkin=AuthenticatedUser_get1(&cmd->request); if(!buttonsbelkin) buttonsbelkin = AuthenticatorIntf_authenticate(o->authenticator,driverstate,cmd); if(buttonsbelkin) { L_authorize: if(o->realm) { if(AuthorizerIntf_authorize( o->realm, buttonsbelkin, HttpRequest_getMethodType(&cmd->request), driverstate)) { return TRUE; } } else return TRUE; L_notAuthorized: if(o->_p403) { HttpResponse_setDefaultHeaders(&cmd->response); HttpResponse_forward(&cmd->response, o->_p403); } else HttpResponse_sendError1(&cmd->response, 403); } return FALSE; } if(o->realm) { buttonsbelkin = AuthenticatedUser_get1(&cmd->request); if(buttonsbelkin) goto L_authorize; goto L_notAuthorized; } return TRUE; } #endif static int doubleftoui(HttpDir* o, const char* driverregister, HttpCommand* cmd) { if( !cmd ) { ioremapsetup(o, 0, 0); baFree(o); } else { return ioremapsetup(o, driverregister, cmd); } return 0; } static void misalignedaccess(HttpDir* o, const char *gpio1config, S8 gpio1resources) { HttpDir_constructor(o, gpio1config, gpio1resources); HttpDir_setService(o, doubleftoui); } typedef void(*HttpLinkCon_DispEv)(struct HttpLinkCon* mmcsd0resources); #define link2ServerCon(l) (HttpLinkCon*)((U8*)l-offsetof(HttpLinkCon,link)) static void parselsapic(HttpLinkCon* o, HttpServer* uarchbuild, HttpLinkCon_DispEv e) { HttpConnection_constructor((HttpConnection*)o, uarchbuild, uarchbuild->dispatcher, (SoDispCon_DispRecEv)e); DoubleLink_constructor(&o->link); } #define HttpLinkCon_destructor(o) \ HttpConnection_destructor((HttpConnection*)(o)) static void pciercxcfg008(HttpLinkConList* l, HttpLinkCon* con) { DoubleList_insertLast(l, &con->link); } static HttpLinkCon* HttpLinkConList_removeFirst(HttpLinkConList* l) { DoubleLink* link = DoubleList_removeFirst(l); if(link) return link2ServerCon(link); return 0; } #define HttpLinkConList_isEmpty(o) DoubleList_isEmpty(o) static int kexecshutdown(HttpRootDir* o, HttpCommand* cmd) { int handlersetup; if( !o->page404 ) return -1; if(o->page404InProgress) { TRPR(("\105\162\162\157\162\072\040\165\163\145\162\040\144\145\146\151\156\145\144\040\064\060\064\040\160\141\147\145\040\045\163\040\156\157\164\040\146\157\165\156\144\012", o->page404)); return -1; } o->page404InProgress = TRUE; cmd->response.forwardCounter++; handlersetup = timer0clockevent( o, o->page404, cmd); cmd->response.forwardCounter--; o->page404InProgress = FALSE; return handlersetup; } static int timer0clockevent(HttpRootDir* o, const char* driverstate, HttpCommand* cmd) { const char* ptr=0; if(!*driverstate && HttpRequest_getMethodType(&cmd->request)==HttpMethod_Options) { _z_3(cmd); return 0; } if (!ioremapsetup((HttpDir*)o, driverstate, cmd)) return 0; if(!HttpResponse_initial(&cmd->response)) return -1; if(*driverstate && o->page404InProgress==FALSE) { ptr = bStrrchr(driverstate, '\057'); if( !ptr ) ptr = driverstate; if( *ptr && !bStrrchr(ptr, '\056') && !(ptr[0] == '\057' && !ptr[1]) ) { int len= iStrlen(driverstate)+3; char* chargestart=(char*)baMalloc(len); if(chargestart) { const char* url; basnprintf(chargestart,len,"\057\045\163\057",driverstate); url=HttpResponse_encodeRedirectURLWithParam( &cmd->response,chargestart); baFree(chargestart); if(url) { HttpResponse_sendRedirect(&cmd->response, url); return 0; } } } } if(ptr || !*driverstate) { if(ptr) ptr = bStrrchr(ptr, '\056'); if(!ptr || !strncmp(ptr+1, "\150\164\155", 3) || !strcmp(ptr+1, "\154\163\160")) return kexecshutdown(o, cmd); } return -1; } static void vddmaxshift(HttpRootDir* o) { HttpDir_constructor((HttpDir*)o, 0, 0); o->superServiceFunc = HttpDir_setService( (HttpDir*)o, (HttpDir_Service)timer0clockevent); o->page404 = 0; o->page404InProgress = FALSE; } static void frequencytable(HttpRootDir* o) { (*o->superServiceFunc)((HttpDir*)o,0,0); if(o->page404) baFree(o->page404); } static void pgtablesremap(HttpRootDir* o, const char* deviceregistered) { if(*deviceregistered == '\057') deviceregistered++; if(o->page404) baFree(o->page404); o->page404 = baStrdup(deviceregistered); } typedef struct { HttpConnection super; AllocatorIntf* alloc; BaFileSize maxSize; BaTime startTime; } WaitForConClose; static void timerdisable(WaitForConClose* o) { HttpConnection* fdc37m81xconfig = (HttpConnection*)o; baAssert(fdc37m81xconfig->server->waitForConClose == (void*)o); fdc37m81xconfig->server->waitForConClose=0; HttpConnection_destructor(fdc37m81xconfig); AllocatorIntf_free(o->alloc, o); } static void joystickinterrupt(SoDispCon* fdc37m81xconfig) { char buf[200]; int len; WaitForConClose* o = (WaitForConClose*)fdc37m81xconfig; o->startTime=baGetUnixTime(); do { if( (len = HttpConnection_readData( (HttpConnection*)fdc37m81xconfig, buf, sizeof(buf))) <= 0 ) { timerdisable(o); break; } else if(o->maxSize != 0) { if(o->maxSize <= (U32)len) { timerdisable(o); break; } o->maxSize -= len; } } while(HttpConnection_hasMoreData((HttpConnection*)fdc37m81xconfig)); } static void conditionchecks(SoDisp* ptraceaccess, HttpConnection* con) { if(HttpConnection_recEvActive(con)) SoDisp_deactivateRec(ptraceaccess,(SoDispCon*)con); if(HttpConnection_dispatcherHasCon(con)) SoDisp_removeConnection(ptraceaccess, (SoDispCon*)con); } static void ltm020d550modes(WaitForConClose* o, HttpServer* uarchbuild, AllocatorIntf* unmapaliases, HttpConnection* con, BaFileSize disabletraps) { SoDisp* ptraceaccess; HttpConnection_constructor((HttpConnection*)o, uarchbuild, uarchbuild->dispatcher, joystickinterrupt); o->alloc=unmapaliases; ptraceaccess = HttpServer_getDispatcher(con->server); conditionchecks(ptraceaccess,con); HttpConnection_moveCon(con, (HttpConnection*)o); SoDisp_addConnection(ptraceaccess, (SoDispCon*)o); SoDisp_activateRec(ptraceaccess, (SoDispCon*)o); HttpConnection_setState((HttpConnection*)o, HttpConnection_Connected); o->maxSize = disabletraps; o->startTime=baGetUnixTime(); } BA_API void HttpServerConfig_constructor(HttpServerConfig* o) { o->minRequest = 1024; o->maxRequest = 2048; o->minResponseHeader = 512; o->maxResponseHeader = 1024; o->commit = 512; #ifdef BA_DEMO_MODE o->responseData = 8*1024; #else o->responseData = 1400; #endif o->noOfHttpCommands = 1; o->noOfHttpConnections=16; o->maxSessions = o->noOfHttpConnections; } BA_API int HttpServerConfig_setRequest(HttpServerConfig* o, S16 min, S16 max) { if(min < 1024 || max < min || ((S16)max) < 0) return -1; o->minRequest = min; o->maxRequest = max; return 0; } BA_API int HttpServerConfig_setResponseHeader(HttpServerConfig* o, U16 min, U16 max) { if(min < 512 || max < min || ((S16)max) < 0) return -1; o->minResponseHeader = min; o->maxResponseHeader = max; return 0; } BA_API int HttpServerConfig_setResponseData(HttpServerConfig* o, U16 icachealiases) { if(icachealiases < 512) return -1; o->responseData = icachealiases; return 0; } BA_API int HttpServerConfig_setCommit(HttpServerConfig* o, U16 icachealiases) { if(icachealiases < 128) return -1; o->commit = icachealiases; return 0; } BA_API int HttpServerConfig_setNoOfHttpCommands(HttpServerConfig* o, U16 icachealiases) { if(icachealiases < 1) return -1; o->noOfHttpCommands = icachealiases; if( (icachealiases+3) > o->noOfHttpConnections ) o->noOfHttpConnections = icachealiases+3; return 0; } BA_API int HttpServerConfig_setNoOfHttpConnections(HttpServerConfig* o, U16 icachealiases) { if(icachealiases < (o->noOfHttpCommands+3)) return -1; o->noOfHttpConnections = icachealiases; if(o->maxSessions < icachealiases) o->maxSessions = icachealiases; return 0; } BA_API int HttpServerConfig_setMaxSessions(HttpServerConfig* o, U16 icachealiases) { if(icachealiases < 1) return -1; o->maxSessions = icachealiases; return 0; } static void staticstruct(HttpLinkCon* mmcsd0resources); static void prctldisable(SoDispCon* con); static void contextstack(HttpServer*, HttpCommand*, BaBool); static void wakeupevents( HttpServer* o, BaBool helperports); static int timeoutcheck(HttpServer* o) { HttpCommand* cmd = (HttpCommand*)DoubleList_firstNode(&o->cmdReqList); if(cmd) { DoubleLink_unlink((DoubleLink*)cmd); #ifdef HTTP_TRACE reprogramdpllcore(5, &cmd->request); HttpTrace_printf(5,"\040\103\157\156\156\145\143\164\151\157\156\040\164\151\155\145\157\165\164\012"); #endif if(HttpConnection_recEvActive(cmd->con)) SoDisp_deactivateRec(o->dispatcher, (SoDispCon*)cmd->con); if(HttpConnection_dispatcherHasCon(cmd->con)) SoDisp_removeConnection(o->dispatcher, (SoDispCon*)cmd->con); HttpConnection_setState(cmd->con, HttpConnection_Free); pciercxcfg008(&o->freeList, (HttpLinkCon*)cmd->con); cmd->con->cmd=0; cmd->con = 0; HttpCommand_reset(cmd); DoubleList_insertLast(&o->commandPool, cmd); if( ! DoubleList_isEmpty(&o->readyList) ) wakeupevents(o, FALSE); return 0; } return -1; } BA_API int HttpServer_insertRootDir(HttpServer* o, HttpDir* dir) { return HttpDir_insertDir(HttpServer_getRDC(o), dir); } BA_API const char* HttpServer_getStatusCode(int guestconfig2) { switch(guestconfig2) { case 100: return "\061\060\060\040\103\157\156\164\151\156\165\145"; case 101: return "\061\060\061\040\123\167\151\164\143\150\151\156\147\040\120\162\157\164\157\143\157\154\163"; case 200: return "\062\060\060\040\117\113"; case 201: return "\062\060\061\040\103\162\145\141\164\145\144"; case 202: return "\062\060\062\040\101\143\143\145\160\164\145\144"; case 203: return "\062\060\063\040\116\157\156\055\101\165\164\150\157\162\151\164\141\164\151\166\145\040\111\156\146\157\162\155\141\164\151\157\156"; case 204: return "\062\060\064\040\116\157\040\103\157\156\164\145\156\164"; case 205: return "\062\060\065\040\122\145\163\145\164\040\103\157\156\164\145\156\164"; case 206: return "\062\060\066\040\120\141\162\164\151\141\154\040\103\157\156\164\145\156\164"; case 207: return "\062\060\067\040\115\165\154\164\151\055\123\164\141\164\165\163"; case 300: return "\063\060\060\040\115\165\154\164\151\160\154\145\040\103\150\157\151\143\145\163"; case 301: return "\063\060\061\040\115\157\166\145\144\040\120\145\162\155\141\156\145\156\164\154\171"; case 302: return "\063\060\062\040\115\157\166\145\144\040\124\145\155\160\157\162\141\162\151\154\171"; case 303: return "\063\060\063\040\123\145\145\040\117\164\150\145\162"; case 304: return "\063\060\064\040\116\157\164\040\115\157\144\151\146\151\145\144"; case 305: return "\063\060\065\040\125\163\145\040\120\162\157\170\171"; case 400: return "\064\060\060\040\102\141\144\040\122\145\161\165\145\163\164"; case 401: return "\064\060\061\040\125\156\141\165\164\150\157\162\151\172\145\144"; case 402: return "\064\060\062\040\120\141\171\155\145\156\164\040\122\145\161\165\151\162\145\144"; case 403: return "\064\060\063\040\106\157\162\142\151\144\144\145\156"; case 404: return "\064\060\064\040\116\157\164\040\106\157\165\156\144"; case 405: return "\064\060\065\040\115\145\164\150\157\144\040\116\157\164\040\101\154\154\157\167\145\144"; case 406: return "\064\060\066\040\116\157\164\040\101\143\143\145\160\164\141\142\154\145"; case 407: return "\064\060\067\040\120\162\157\170\171\040\101\165\164\150\145\156\164\151\143\141\164\151\157\156\040\122\145\161\165\151\162\145\144"; case 408: return "\064\060\070\040\122\145\161\165\145\163\164\040\124\151\155\145\157\165\164"; case 409: return "\064\060\071\040\103\157\156\146\154\151\143\164"; case 410: return "\064\061\060\040\107\157\156\145"; case 411: return "\064\061\061\040\114\145\156\147\164\150\040\122\145\161\165\151\162\145\144"; case 412: return "\064\061\062\040\120\162\145\143\157\156\144\151\164\151\157\156\040\106\141\151\154\145\144"; case 413: return "\064\061\063\040\122\145\161\165\145\163\164\040\105\156\164\151\164\171\040\124\157\157\040\114\141\162\147\145"; case 414: return "\064\061\064\040\122\145\161\165\145\163\164\055\125\122\111\040\124\157\157\040\114\157\156\147"; case 415: return "\064\061\065\040\125\156\163\165\160\160\157\162\164\145\144\040\115\145\144\151\141\040\124\171\160\145"; case 423: return "\064\062\063\040\114\157\143\153\145\144"; case 501: return "\065\060\061\040\116\157\164\040\111\155\160\154\145\155\145\156\164\145\144"; case 502: return "\065\060\062\040\102\141\144\040\107\141\164\145\167\141\171"; case 503: return "\065\060\063\040\123\145\162\166\151\143\145\040\125\156\141\166\141\151\154\141\142\154\145"; case 504: return "\065\060\064\040\107\141\164\145\167\141\171\040\124\151\155\145\157\165\164"; case 505: return "\065\060\065\040\110\124\124\120\040\126\145\162\163\151\157\156\040\116\157\164\040\123\165\160\160\157\162\164\145\144"; case 507: return "\065\060\067\040\111\156\163\165\146\146\151\143\151\145\156\164\040\163\164\157\162\141\147\145"; case 500: return "\065\060\060\040\123\145\162\166\145\162\040\105\162\162\157\162"; } return "\077\077\077\040\123\145\162\166\145\162\040\105\162\162\157\162"; } BA_API int HttpServer_insertDir(HttpServer* o, const char* displayresource, HttpDir* dir) { if( displayresource && displayresource[0] && ! (displayresource[0] == '\057' && displayresource[1] == 0)) { HttpDir* checkstack = HttpDir_createOrGet( HttpServer_getRDC(o), displayresource); if(checkstack) return HttpDir_insertDir(checkstack, dir); } else { return HttpServer_insertRootDir(o, dir); } return E_MALLOC; } BA_API int HttpServer_insertCSP( HttpServer* o, CspInit resourceconsumer, const char* displayresource, struct CspReader* guestconfigs) { HttpDir* checkstack = HttpDir_createOrGet( HttpServer_getRDC(o), displayresource); if(checkstack) { (*resourceconsumer)(checkstack, guestconfigs); return 0; } return E_MALLOC; } static int searchstruct(SplayTreeNode* n, SplayTreeKey k) { if((const char*)n->key) return strcmp((const char*)n->key, (const char*)k); return -1; } static void checkEndian(void) { U32 granuleshift; U8* ptr = (U8*)&granuleshift; #ifdef B_LITTLE_ENDIAN ptr[3]=0x12; ptr[2]=0x34; ptr[1]=0x56; ptr[0]=0x78; #elif defined(B_BIG_ENDIAN) ptr[0]=0x12; ptr[1]=0x34; ptr[2]=0x56; ptr[3]=0x78; #else #error ENDIAN_NEEDED_Define_one_of_B_BIG_ENDIAN_or_B_LITTLE_ENDIAN #endif if(granuleshift != 0x12345678) { baFatalE(FE_WRONG_ENDIAN,0); } } BA_API void HttpServer_constructor(HttpServer* o, SoDisp* sha256start, HttpServerConfig* cfg) { HttpServerConfig defaultCfg; int i; if((sizeof(U64) != 8) || (sizeof(U32) != 4) || (sizeof(S32) != 4) || (sizeof(U16) != 2) || (sizeof(S16) != 2) || (sizeof(U8) != 1) || (sizeof(S8) != 1)) { baFatalE(FE_TYPE_SIZE_ERROR,0); } if(9 != offsetof(GzipHeader, operatingSystem)) { baFatalE(FE_TYPE_SIZE_ERROR,offsetof(GzipHeader, operatingSystem)); } checkEndian(); if( ! cfg ) { cfg = &defaultCfg; HttpServerConfig_constructor(cfg); } SplayTree_constructor(&o->authUserTree, searchstruct); o->dispatcher = sha256start; #ifndef NO_HTTP_SESSION HttpSessionContainer_constructor(&o->sessionContainer, o, cfg->maxSessions); #endif o->userObj=0; o->waitForConClose=0; o->lspOnTerminateRequest=0; o->commandPoolSize = cfg->noOfHttpCommands; DoubleList_constructor(&o->commandPool); DoubleList_constructor(&o->cmdReqList); for(; cfg->noOfHttpCommands > 0; cfg->noOfHttpCommands--) { HttpCommand* cmd = (HttpCommand*)baMalloc(sizeof(HttpCommand)); if( !cmd ) baFatalE(FE_MALLOC, sizeof(HttpCommand)); clockfiddle(cmd,o,cfg); if( ! cacherefill(cmd) ) baFatalE(FE_MALLOC, 0); DoubleList_insertLast(&o->commandPool, cmd); } vddmaxshift(&o->rootDirContainer); DoubleList_constructor(&o->freeList); DoubleList_constructor(&o->connectedList); DoubleList_constructor(&o->readyList); o->connections = (HttpLinkCon*)baMalloc( sizeof(HttpLinkCon) * cfg->noOfHttpConnections); if( ! o->connections ) baFatalE(FE_MALLOC, sizeof(HttpLinkCon)*cfg->noOfHttpConnections); for(i = 0 ; i < cfg->noOfHttpConnections ; i++) { parselsapic(&o->connections[i], o, staticstruct); pciercxcfg008(&o->freeList, &o->connections[i]); } HttpConnection_constructor( &o->noOpCon, o, o->dispatcher, prctldisable); o->noOfConnections = cfg->noOfHttpConnections; o->maxHttpRequestLen = cfg->maxRequest; o->threadPoolIntf=0; } BA_API void HttpServer_destructor(HttpServer* o) { U16 i; HttpCommand* cmd; while( (cmd = (HttpCommand*)DoubleList_removeFirst(&o->commandPool)) != 0) { pciercxcfg010(cmd); baFree(cmd); } while( (cmd = (HttpCommand*)DoubleList_removeFirst(&o->cmdReqList)) != 0) { pciercxcfg010(cmd); baFree(cmd); } for(i = 0 ; i < o->noOfConnections ; i++) HttpLinkCon_destructor(&o->connections[i]); baFree(o->connections); frequencytable(&o->rootDirContainer); #ifndef NO_HTTP_SESSION HttpSessionContainer_destructor(&o->sessionContainer); #endif } static void spillpsprel(HttpServer*o, HttpConnection* con) { HttpConnection_clearKeepAlive(con); if(o->threadPoolIntf) SoDisp_deactivateRec(o->dispatcher, (SoDispCon*)con); } static int alignmentldrstr(HttpResponse* rsp) { return rsp->bodyPrint->flushCB( rsp->bodyPrint, rsp->bodyPrint == &rsp->defaultBodyPrint ? 0 : -1); } static int switchersysfs(HttpServer* o, HttpCommand* cmd) { BaBool write64uint64=TRUE; int handlersetup=0; HttpConnection* con = cmd->con; HttpResponse* r3000write = &cmd->response; baAssert(con); if( ! con->cmd ) { baAssert(con == &o->noOpCon); return -1; } baAssert(con != &o->noOpCon); if(con->state == HttpConnection_Running) { if(cmd->request.methodType == HttpMethod_Head) { if( ! r3000write->headerSent ) { if(HttpResponse_containsHeader(r3000write, "\103\157\156\164\145\156\164\055\114\145\156\147\164\150") || (!alignmentldrstr(r3000write) && !(handlersetup=HttpResponse_setContentLength( r3000write,r3000write->msgLen)))) { handlersetup=cacheprobe(r3000write); } } } else { if(!(handlersetup= alignmentldrstr(r3000write))) { if(r3000write->useChunkTransfer) handlersetup=HttpConnection_sendData(con, "\060\015\012\015\012", 5); } } if( ! handlersetup && HttpConnection_isValid(con) ) { HttpRequest* req = &cmd->request; BaFileSize disabletraps = HttpStdHeaders_getContentLength( HttpRequest_getStdHeaders(req)); if(disabletraps && ! req->postDataConsumed) { if(disabletraps > 2000) { HttpServer_doLingeringClose( o, HttpRequest_getConnection(req), disabletraps); } } else if(HttpConnection_keepAlive(con)) { baAssert(HttpConnection_dispatcherHasCon(con)); if( !HttpConnection_recEvActive(con) ) { if( ! cmd->request.inData.overflow ) { SoDisp_activateRec(o->dispatcher, (SoDispCon*)con); write64uint64=FALSE; } } else { write64uint64=FALSE; } } } } con->cmd=0; cmd->con = &o->noOpCon; if(write64uint64) { if(HttpConnection_recEvActive(con)) SoDisp_deactivateRec(o->dispatcher, (SoDispCon*)con); if(HttpConnection_dispatcherHasCon(con)) SoDisp_removeConnection(o->dispatcher, (SoDispCon*)con); HttpConnection_setState(con, HttpConnection_Free); pciercxcfg008(&o->freeList, (HttpLinkCon*)con); } else { baAssert(HttpConnection_recEvActive(con)); HttpConnection_setState(con, HttpConnection_Connected); pciercxcfg008(&o->connectedList, (HttpLinkCon*)con); } return handlersetup; } static BaBool trapsfpsimd32( HttpServer* o, HttpCommand* cmd, HttpConnection* con) { HttpInData* registeredevent=&cmd->request.inData; #ifndef NO_HTTP_SESSION if(cmd->request.session) { HttpSession_decrRefCntr(cmd->request.session); cmd->request.session=0; } #endif if(o->lspOnTerminateRequest && cmd->lcmd) { (*o->lspOnTerminateRequest)(cmd->lcmd); cmd->lcmd=0; } if(cmd->con->cmd) { baAssert(cmd->con == con); switchersysfs(o, cmd); } else { baAssert(cmd->con == &o->noOpCon); } baAssert( ! cmd->con->cmd ); if( HttpConnection_isValid(con) && HttpConnection_keepAlive(con) && HttpInData_hasMoreDataM(registeredevent) && threadstack(registeredevent)) { enablenotrace(o, (HttpLinkCon*)con); cmd->con = con; con->cmd = cmd; HttpConnection_setState(con, HttpConnection_Running); HttpCommand_resetWithPipelinedData(cmd); cmd->requestTime=baGetUnixTime(); DoubleList_insertLast(&o->cmdReqList, cmd); return TRUE; } HttpCommand_reset(cmd); baAssert( ! DoubleList_isInList(&o->commandPool, cmd) ); DoubleList_insertLast(&o->commandPool, cmd); return FALSE; } static int menelausplatform(HttpServer* o, HttpCommand* cmd, HttpDir* dir, const char* driverstate) { if( !dir ) return E_PAGE_NOT_FOUND; cmd->response.currentDir = dir; if((*dir->service)(dir, driverstate, cmd)) { int handlersetup; char* targetdisable; if(dir == HttpServer_getRDC(o)) return E_PAGE_NOT_FOUND; if( (targetdisable = HttpDir_makeAbsPath(dir, driverstate, iStrlen(driverstate)))==0 ) return E_MALLOC; cmd->response.currentDir = HttpServer_getRDC(o); handlersetup = (*HttpServer_getRDC(o)->service)( HttpServer_getRDC(o), targetdisable+1, cmd) ? E_PAGE_NOT_FOUND : 0; baFree(targetdisable); return handlersetup; } return 0; } static int reportstatus(HttpServer* o, HttpCommand* cmd, HttpDir* dir, const char* driverstate) { int handlersetup; while(*driverstate == '\057') driverstate++; if( (handlersetup = menelausplatform(o, cmd, dir, driverstate)) != 0 ) { if(handlersetup == E_PAGE_NOT_FOUND) { #if 0 TRPR(("\045\163\040\045\163\040\116\157\164\040\146\157\165\156\144\012", driverstate, HttpResponse_initial(&cmd->response) ? "" : "\146\157\162\167\141\162\144\145\144\057\151\156\143\154\165\144\145\144\040\160\141\147\145" )); #endif if(HttpResponse_initial(&cmd->response)) HttpResponse_sendError1(&cmd->response, 404); } else { pciercxcfg032(&cmd->response); } #if 1 #else HttpResponse_flush(&cmd->response); switchersysfs(o, cmd); #endif return handlersetup; } if(HttpResponse_initial(&cmd->response)) return switchersysfs(o, cmd); return 0; } static void contextstack(HttpServer* o, HttpCommand* cmd, BaBool helperports) { HttpConnection* con; int sffsdrnandflash; L_readMore: con=cmd->con; baAssert(con && con->cmd == cmd); baAssert(con->state == HttpConnection_Running); sffsdrnandflash = driverprobe(&cmd->request.inData); if(sffsdrnandflash) { cmd->runningInThread = helperports; if(DoubleLink_isLinked(cmd)) { baAssert(DoubleList_isInList(&o->cmdReqList, cmd)); DoubleLink_unlink((DoubleLink*)cmd); } if(sffsdrnandflash > 0) { #ifdef EVAL_KIT if(evalCheck(cmd)) goto L_error; #endif sanitisepropbaser(&cmd->request); if( helperports && ! HttpConnection_recEvActive(cmd->con) ) { HttpConnection_clearKeepAlive(cmd->con); } if(o->threadPoolIntf && ! helperports) { if( ! HttpCmdThreadPoolIntf_doDir( o->threadPoolIntf, cmd, HttpServer_getRDC(o)) ) { return; } } reportstatus( o, cmd, HttpServer_getRDC(o), HttpRequest_getRequestPath(&cmd->request)); } else { #ifdef EVAL_KIT L_error: #endif HttpConnection_clearKeepAlive(cmd->con); } if(trapsfpsimd32(o, cmd, con)) goto L_readMore; } else if(cmd->request.inData.allocator.index == 0) { baAssert(HttpConnection_recEvActive(con)); con->cmd = 0; cmd->con = 0; if(DoubleLink_isLinked(cmd)) { baAssert(DoubleList_isInList(&o->cmdReqList, cmd)); DoubleLink_unlink((DoubleLink*)cmd); } DoubleList_insertLast(&o->commandPool, cmd); HttpConnection_setState(con, HttpConnection_Connected); pciercxcfg008(&o->connectedList, (HttpLinkCon*)con); } } static void wakeupevents(HttpServer* o, BaBool helperports) { HttpLinkCon* pagesexact; HttpConnection* con; HttpCommand* cmd; cmd = (HttpCommand*)DoubleList_removeFirst(&o->commandPool); baAssert(cmd); cmd->requestTime=baGetUnixTime(); DoubleList_insertLast(&o->cmdReqList, cmd); pagesexact = HttpLinkConList_removeFirst(&o->readyList); baAssert(pagesexact); con = (HttpConnection*)pagesexact; baAssert( ! con->cmd ); baAssert( ! cmd->con || cmd->con == &o->noOpCon ); baAssert( ! cmd->runningInThread ); cmd->con = con; con->cmd = cmd; HttpConnection_setState(con, HttpConnection_Running); SoDisp_activateRec(o->dispatcher, (SoDispCon*)con); contextstack(o, cmd, helperports); } void HttpServer_AsynchProcessDir(HttpServer* o, HttpDir* dir, HttpCommand* cmd) { HttpConnection* con=cmd->con; baAssert(cmd->runningInThread); baAssert(cmd->con && cmd->con->cmd == cmd); reportstatus( o, cmd, dir, HttpRequest_getRequestPath(&cmd->request)); if(trapsfpsimd32(o, cmd, con)) contextstack(o, cmd, TRUE); cmd->runningInThread=FALSE; while( ! HttpLinkConList_isEmpty(&o->readyList) && ! DoubleList_isEmpty(&o->commandPool) ) { wakeupevents(o, TRUE); } } static void enablenotrace(HttpServer* o, HttpLinkCon* mmcsd0resources) { baAssert(DoubleList_isInList(&o->connectedList, &mmcsd0resources->link)); DoubleLink_unlink(&mmcsd0resources->link); } int HttpServer_termOldestIdleCon(HttpServer* o) { HttpLinkCon* con = HttpLinkConList_removeFirst(&o->connectedList); if(con) { conditionchecks(o->dispatcher,(HttpConnection*)con); HttpConnection_setState( (HttpConnection*)con, HttpConnection_HardClose); pciercxcfg008(&o->freeList, con); return 0; } return -1; } BA_API HttpConnection* HttpServer_getFreeCon(HttpServer* o) { HttpLinkCon* freeCon; L_tryagain: if( ! HttpLinkConList_isEmpty(&o->freeList) ) freeCon = HttpLinkConList_removeFirst(&o->freeList); else { freeCon = HttpLinkConList_removeFirst(&o->connectedList); if(freeCon) { conditionchecks(o->dispatcher,(HttpConnection*)freeCon); HttpConnection_setState( (HttpConnection*)freeCon, HttpConnection_HardClose); } else if( ! timeoutcheck(o) ) goto L_tryagain; } if(o->waitForConClose) { if( (((WaitForConClose*)o->waitForConClose)->startTime + 5) < baGetUnixTime() ) { timerdisable((WaitForConClose*)o->waitForConClose); o->waitForConClose=0; } } return (HttpConnection*)freeCon; } void HttpServer_returnFreeCon(HttpServer* o, HttpConnection* con) { pciercxcfg008(&o->freeList, (HttpLinkCon*)con); } BA_API void HttpServer_installNewCon(HttpServer* o, HttpConnection* con) { HttpLinkCon* lCon = (HttpLinkCon*)con; HttpConnection_setState(con, HttpConnection_Connected); pciercxcfg008(&o->connectedList, lCon); SoDisp_addConnection(o->dispatcher, (SoDispCon*)con); SoDisp_activateRec(o->dispatcher, (SoDispCon*)con); if(HttpConnection_hasMoreData(con)) staticstruct(lCon); } void HttpServer_addCon2ConnectedList(HttpServer* o, HttpConnection* con) { baAssert( ! HttpConnection_recEvActive(con) ); baAssert( ! HttpConnection_dispatcherHasCon(con) ); if(HttpConnection_isValid(con) && HttpConnection_keepAlive(con)) { HttpLinkCon* pagesexact = (HttpLinkCon*)HttpServer_getFreeCon(o); if(pagesexact) { HttpConnection_moveCon(con, (HttpConnection*)pagesexact); HttpConnection_setState( (HttpConnection*)pagesexact, HttpConnection_Connected); pciercxcfg008(&o->connectedList, pagesexact); SoDisp_addConnection(o->dispatcher, (SoDispCon*)pagesexact); SoDisp_activateRec(o->dispatcher,(SoDispCon*)pagesexact); if(HttpConnection_hasMoreData((HttpConnection*)pagesexact)) staticstruct(pagesexact); } } HttpConnection_destructor(con); } void HttpServer_doLingeringClose( HttpServer* o, HttpConnection* con, BaFileSize disabletraps) { if(HttpConnection_isValid(con)) { WaitForConClose* wfcc; AllocatorIntf* unmapaliases=AllocatorIntf_getDefault(); size_t icachealiases=sizeof(WaitForConClose); if(o->waitForConClose) { timerdisable((WaitForConClose*)o->waitForConClose); o->waitForConClose=0; } wfcc = (WaitForConClose*)AllocatorIntf_malloc(unmapaliases,&icachealiases); if(wfcc) { ltm020d550modes(wfcc, o, unmapaliases, con, disabletraps); o->waitForConClose=wfcc; return; } } HttpConnection_setState(con, HttpConnection_Terminated); } static void staticstruct(HttpLinkCon* pagesexact) { HttpCommand* cmd; HttpConnection* con = (HttpConnection*)pagesexact; HttpServer* o = HttpConnection_getServer(con); #ifndef NDEBUG int i; for(i = 0 ; i < o->noOfConnections ; i++) { if(o->connections+i == pagesexact) break; } baAssert(o->connections+i == pagesexact); #endif #ifndef NO_HTTP_SESSION HttpSessionContainer_sessionTimer(&o->sessionContainer); #endif if(con->state == HttpConnection_Connected) { cmd = (HttpCommand*)DoubleList_removeFirst(&o->commandPool); enablenotrace(o, pagesexact); if(!cmd) { cmd = (HttpCommand*)DoubleList_firstNode(&o->cmdReqList); if(cmd && (baGetUnixTime() - cmd->requestTime) > 5) { timeoutcheck(o); cmd = (HttpCommand*)DoubleList_removeFirst(&o->commandPool); } else cmd=0; } if(cmd) { cmd->requestTime=baGetUnixTime(); DoubleList_insertLast(&o->cmdReqList, cmd); HttpConnection_setState(con, HttpConnection_Running); baAssert( ! con->cmd ); baAssert( ! cmd->con || cmd->con == &o->noOpCon ); baAssert( ! cmd->runningInThread ); cmd->con = con; con->cmd = cmd; contextstack(o, cmd, FALSE); } else if(HttpConnection_isValid(con)) { HttpConnection_setState(con, HttpConnection_Ready); pciercxcfg008(&o->readyList, pagesexact); SoDisp_deactivateRec(o->dispatcher, (SoDispCon*)con); } else { HttpConnection_setState(con, HttpConnection_Free); pciercxcfg008(&o->freeList, pagesexact); } } else if(con->state == HttpConnection_Running) { baAssert(con->cmd && con->cmd->con == con); if(con->cmd->runningInThread) { #if 0 if(foundationsregistered(&con->cmd->request.inData, 0, TRUE) < 0) { if(HttpConnection_recEvActive(con)) { HttpConnection_clearKeepAlive(con); SoDisp_deactivateRec(o->dispatcher, con); } } #else if(HttpConnection_recEvActive(con)) SoDisp_deactivateRec(o->dispatcher, (SoDispCon*)con); #endif } else { contextstack(o, con->cmd, FALSE); } } else if(con->state == HttpConnection_Terminated) { if(con->cmd) { baAssert(con->cmd->con == con); switchersysfs(o, con->cmd); } } else { baAssert( ! HttpConnection_dispatcherHasCon(con) ); } while( ! HttpLinkConList_isEmpty(&o->readyList) && ! DoubleList_isEmpty(&o->commandPool) ) { wakeupevents(o, FALSE); } } static void prctldisable(SoDispCon* con) { (void)con; baAssert(0); } BA_API void HttpServer_set404Page(HttpServer*o, const char* deviceregistered) { pgtablesremap(&o->rootDirContainer, deviceregistered); } BA_API int HttpServer_setUserObj(HttpServer* o, void* touchpdata, BaBool clockcheck) { if(o->userObj && !clockcheck) return -1; o->userObj = touchpdata; return 0; } BA_API void HttpServer_setErrHnd(UserDefinedErrHandler e) { barracudaUserDefinedErrHandler = e; } void HttpServer_initStatic(void) { barracudaUserDefinedErrHandler = 0; } #ifdef NO_SHARKSSL #define SHARKSSL_USE_MD5 1 #define SHARKSSL_USE_SHA1 1 #if defined(__LP64__) && !defined(SHARKSSL_64BIT) #define SHARKSSL_64BIT #endif #ifdef SHARKSSL_64BIT #define UPTR U64 #define SHARKSSL_ALIGNMENT 4 #endif #ifndef UPTR #define UPTR U32 #endif #if (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define hsotgpdata(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = (w) #elif (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define hsotgpdata(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = blockarray(w) #else #define hsotgpdata(w,a,i) \ { \ (a)[(i)] = (U8)((w)); \ (a)[(i) + 1] = (U8)((w) >> 8); \ (a)[(i) + 2] = (U8)((w) >> 16); \ (a)[(i) + 3] = (U8)((w) >> 24); \ } #endif #if (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define read64uint32(w,a,i) (w) = ((__sharkssl_packed U32*)(a))[(i) >> 2] #elif (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define read64uint32(w,a,i) (w) = blockarray(((__sharkssl_packed U32*)(a))[(i) >> 2]) #else #define read64uint32(w,a,i) \ { \ (w) = ((U32)(a)[(i)] << 24) \ | ((U32)(a)[(i) + 1] << 16) \ | ((U32)(a)[(i) + 2] << 8) \ | ((U32)(a)[(i) + 3]); \ } #endif #if (defined(B_BIG_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define inputlevel(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = (w) #elif (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) #define inputlevel(w,a,i) ((__sharkssl_packed U32*)(a))[(i) >> 2] = blockarray(w) #else #define inputlevel(w,a,i) \ { \ (a)[(i)] = (U8)((w) >> 24); \ (a)[(i) + 1] = (U8)((w) >> 16); \ (a)[(i) + 2] = (U8)((w) >> 8); \ (a)[(i) + 3] = (U8)((w)); \ } #endif #if (SHARKSSL_USE_MD5 || SHARKSSL_USE_SHA1 || SHARKSSL_USE_SHA_256 || SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) #if (SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) static const U8 prusspdata[128] = #else static const U8 prusspdata[64] = #endif { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #if (SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #endif 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #endif #if SHARKSSL_USE_MD5 #if SHARKSSL_MD5_SMALL_FOOTPRINT static const U32 unregisterclient[64] = { 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE, 0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501, 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE, 0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821, 0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA, 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8, 0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED, 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A, 0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C, 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70, 0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05, 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665, 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039, 0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1, 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1, 0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391 }; static const U8 keypadresources[64] = { 7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22, 5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20, 4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23, 6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21 }; static const U8 writefeature[64] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12, 5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2, 0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9 }; #endif #ifndef B_LITTLE_ENDIAN static void kexecalloc(SharkSslMd5Ctx *registermcasp, const U8 alloccontroller[64]) #else static void kexecalloc(SharkSslMd5Ctx *registermcasp, U32 countshift[16]) #endif { U32 a, b, c, d; #if SHARKSSL_MD5_SMALL_FOOTPRINT const U32 *p; unsigned int i; #endif #ifndef B_LITTLE_ENDIAN U32 countshift[16]; #if SHARKSSL_MD5_SMALL_FOOTPRINT for (i = 0; !(i & 16); i++) { cleanupcount(countshift[i], alloccontroller, (i << 2)); } #else cleanupcount(countshift[0], alloccontroller, 0); cleanupcount(countshift[1], alloccontroller, 4); cleanupcount(countshift[2], alloccontroller, 8); cleanupcount(countshift[3], alloccontroller, 12); cleanupcount(countshift[4], alloccontroller, 16); cleanupcount(countshift[5], alloccontroller, 20); cleanupcount(countshift[6], alloccontroller, 24); cleanupcount(countshift[7], alloccontroller, 28); cleanupcount(countshift[8], alloccontroller, 32); cleanupcount(countshift[9], alloccontroller, 36); cleanupcount(countshift[10], alloccontroller, 40); cleanupcount(countshift[11], alloccontroller, 44); cleanupcount(countshift[12], alloccontroller, 48); cleanupcount(countshift[13], alloccontroller, 52); cleanupcount(countshift[14], alloccontroller, 56); cleanupcount(countshift[15], alloccontroller, 60); #endif #endif #define invalidcontext(x,n) ((U32)((U32)x << n) | ((U32)x >> (32 - n))) #define F(x,y,z) ((x & (y ^ z)) ^ z) #define G(x,y,z) ((z & (x ^ y)) ^ y) #define H(x,y,z) (x ^ y ^ z) #define I(x,y,z) (y ^ (x | ~z)) a = registermcasp->state[0]; b = registermcasp->state[1]; c = registermcasp->state[2]; d = registermcasp->state[3]; #if SHARKSSL_MD5_SMALL_FOOTPRINT p = &unregisterclient[0]; for (i = 0; (0 == (i & 0x40)); i++) { U32 e; a += countshift[writefeature[i]] + *p++; switch (i & 0x30) { case 0x00: a += F(b,c,d); break; case 0x10: a += G(b,c,d); break; case 0x20: a += H(b,c,d); break; default: a += I(b,c,d); break; } a = invalidcontext(a, keypadresources[i]); e = b; b += a; a = d; d = c; c = e; } #else #define FF(A, B, C, D, X, S, K) { A += F(B,C,D) + X + K; A = invalidcontext(A,S) + B; } #define privilegefault(A, B, C, D, X, S, K) { A += G(B,C,D) + X + K; A = invalidcontext(A,S) + B; } #define alternativesapplied(A, B, C, D, X, S, K) { A += H(B,C,D) + X + K; A = invalidcontext(A,S) + B; } #define hsmmc3resource(A, B, C, D, X, S, K) { A += I(B,C,D) + X + K; A = invalidcontext(A,S) + B; } FF(a, b, c, d, countshift[0], 7, 0xD76AA478); FF(d, a, b, c, countshift[1], 12, 0xE8C7B756); FF(c, d, a, b, countshift[2], 17, 0x242070DB); FF(b, c, d, a, countshift[3], 22, 0xC1BDCEEE); FF(a, b, c, d, countshift[4], 7, 0xF57C0FAF); FF(d, a, b, c, countshift[5], 12, 0x4787C62A); FF(c, d, a, b, countshift[6], 17, 0xA8304613); FF(b, c, d, a, countshift[7], 22, 0xFD469501); FF(a, b, c, d, countshift[8], 7, 0x698098D8); FF(d, a, b, c, countshift[9], 12, 0x8B44F7AF); FF(c, d, a, b, countshift[10], 17, 0xFFFF5BB1); FF(b, c, d, a, countshift[11], 22, 0x895CD7BE); FF(a, b, c, d, countshift[12], 7, 0x6B901122); FF(d, a, b, c, countshift[13], 12, 0xFD987193); FF(c, d, a, b, countshift[14], 17, 0xA679438E); FF(b, c, d, a, countshift[15], 22, 0x49B40821); privilegefault(a, b, c, d, countshift[1], 5, 0xF61E2562); privilegefault(d, a, b, c, countshift[6], 9, 0xC040B340); privilegefault(c, d, a, b, countshift[11], 14, 0x265E5A51); privilegefault(b, c, d, a, countshift[0], 20, 0xE9B6C7AA); privilegefault(a, b, c, d, countshift[5], 5, 0xD62F105D); privilegefault(d, a, b, c, countshift[10], 9, 0x02441453); privilegefault(c, d, a, b, countshift[15], 14, 0xD8A1E681); privilegefault(b, c, d, a, countshift[4], 20, 0xE7D3FBC8); privilegefault(a, b, c, d, countshift[9], 5, 0x21E1CDE6); privilegefault(d, a, b, c, countshift[14], 9, 0xC33707D6); privilegefault(c, d, a, b, countshift[3], 14, 0xF4D50D87); privilegefault(b, c, d, a, countshift[8], 20, 0x455A14ED); privilegefault(a, b, c, d, countshift[13], 5, 0xA9E3E905); privilegefault(d, a, b, c, countshift[2], 9, 0xFCEFA3F8); privilegefault(c, d, a, b, countshift[7], 14, 0x676F02D9); privilegefault(b, c, d, a, countshift[12], 20, 0x8D2A4C8A); alternativesapplied(a, b, c, d, countshift[5], 4, 0xFFFA3942); alternativesapplied(d, a, b, c, countshift[8], 11, 0x8771F681); alternativesapplied(c, d, a, b, countshift[11], 16, 0x6D9D6122); alternativesapplied(b, c, d, a, countshift[14], 23, 0xFDE5380C); alternativesapplied(a, b, c, d, countshift[1], 4, 0xA4BEEA44); alternativesapplied(d, a, b, c, countshift[4], 11, 0x4BDECFA9); alternativesapplied(c, d, a, b, countshift[7], 16, 0xF6BB4B60); alternativesapplied(b, c, d, a, countshift[10], 23, 0xBEBFBC70); alternativesapplied(a, b, c, d, countshift[13], 4, 0x289B7EC6); alternativesapplied(d, a, b, c, countshift[0], 11, 0xEAA127FA); alternativesapplied(c, d, a, b, countshift[3], 16, 0xD4EF3085); alternativesapplied(b, c, d, a, countshift[6], 23, 0x04881D05); alternativesapplied(a, b, c, d, countshift[9], 4, 0xD9D4D039); alternativesapplied(d, a, b, c, countshift[12], 11, 0xE6DB99E5); alternativesapplied(c, d, a, b, countshift[15], 16, 0x1FA27CF8); alternativesapplied(b, c, d, a, countshift[2], 23, 0xC4AC5665); hsmmc3resource(a, b, c, d, countshift[0], 6, 0xF4292244); hsmmc3resource(d, a, b, c, countshift[7], 10, 0x432AFF97); hsmmc3resource(c, d, a, b, countshift[14], 15, 0xAB9423A7); hsmmc3resource(b, c, d, a, countshift[5], 21, 0xFC93A039); hsmmc3resource(a, b, c, d, countshift[12], 6, 0x655B59C3); hsmmc3resource(d, a, b, c, countshift[3], 10, 0x8F0CCC92); hsmmc3resource(c, d, a, b, countshift[10], 15, 0xFFEFF47D); hsmmc3resource(b, c, d, a, countshift[1], 21, 0x85845DD1); hsmmc3resource(a, b, c, d, countshift[8], 6, 0x6FA87E4F); hsmmc3resource(d, a, b, c, countshift[15], 10, 0xFE2CE6E0); hsmmc3resource(c, d, a, b, countshift[6], 15, 0xA3014314); hsmmc3resource(b, c, d, a, countshift[13], 21, 0x4E0811A1); hsmmc3resource(a, b, c, d, countshift[4], 6, 0xF7537E82); hsmmc3resource(d, a, b, c, countshift[11], 10, 0xBD3AF235); hsmmc3resource(c, d, a, b, countshift[2], 15, 0x2AD7D2BB); hsmmc3resource(b, c, d, a, countshift[9], 21, 0xEB86D391); #undef hsmmc3resource #undef alternativesapplied #undef privilegefault #undef FF #endif registermcasp->state[0] += a; registermcasp->state[1] += b; registermcasp->state[2] += c; registermcasp->state[3] += d; #undef I #undef H #undef G #undef F #undef invalidcontext } SHARKSSL_API void SharkSslMd5Ctx_constructor(SharkSslMd5Ctx *registermcasp) { baAssert(((unsigned int)(UPTR)(registermcasp->buffer) & (sizeof(int)-1)) == 0); registermcasp->total[0] = 0; registermcasp->total[1] = 0; registermcasp->state[0] = 0x67452301; registermcasp->state[1] = 0xEFCDAB89; registermcasp->state[2] = 0x98BADCFE; registermcasp->state[3] = 0x10325476; } SHARKSSL_API void SharkSslMd5Ctx_append(SharkSslMd5Ctx *registermcasp, const U8 *in, U32 len) { unsigned int dm9000platdata, pxa300evalboard; dm9000platdata = (unsigned int)(registermcasp->total[0]) & 0x3F; pxa300evalboard = 64 - dm9000platdata; registermcasp->total[0] += len; if (registermcasp->total[0] < len) { registermcasp->total[1]++; } if((dm9000platdata) && (len >= pxa300evalboard)) { memcpy((registermcasp->buffer + dm9000platdata), in, pxa300evalboard); #ifndef B_LITTLE_ENDIAN kexecalloc(registermcasp, registermcasp->buffer); #else kexecalloc(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= pxa300evalboard; in += pxa300evalboard; dm9000platdata = 0; } while (len >= 64) { #ifndef B_LITTLE_ENDIAN kexecalloc(registermcasp, in); #else memcpy(registermcasp->buffer, in, 64); kexecalloc(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= 64; in += 64; } if (len) { memcpy((registermcasp->buffer + dm9000platdata), in, len); } } SHARKSSL_API void SharkSslMd5Ctx_finish(SharkSslMd5Ctx *registermcasp, U8 secondaryentry[SHARKSSL_MD5_HASH_LEN]) { U32 timerenable, dummywrites; U32 timer0start, checkcontext; U8 usbgadgetresource[8]; timer0start = (registermcasp->total[0] >> 29) | (registermcasp->total[1] << 3); checkcontext = (registermcasp->total[0] << 3); hsotgpdata(checkcontext, usbgadgetresource, 0); hsotgpdata(timer0start, usbgadgetresource, 4); timerenable = registermcasp->total[0] & 0x3F; dummywrites = (timerenable < 56) ? (56 - timerenable) : (120 - timerenable); SharkSslMd5Ctx_append(registermcasp, (U8*)prusspdata, dummywrites); SharkSslMd5Ctx_append(registermcasp, usbgadgetresource, 8); hsotgpdata(registermcasp->state[0], secondaryentry, 0); hsotgpdata(registermcasp->state[1], secondaryentry, 4); hsotgpdata(registermcasp->state[2], secondaryentry, 8); hsotgpdata(registermcasp->state[3], secondaryentry, 12); } SHARKSSL_API int sharkssl_md5(const U8* alloccontroller, U16 len, U8 *secondaryentry) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslMd5Ctx *hctx = (SharkSslMd5Ctx *)baMalloc(claimresource(sizeof(SharkSslMd5Ctx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslMd5Ctx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller); baAssert(secondaryentry); SharkSslMd5Ctx_constructor(hctx); SharkSslMd5Ctx_append(hctx, alloccontroller, len); SharkSslMd5Ctx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif #if SHARKSSL_USE_SHA1 #ifndef B_BIG_ENDIAN static void irqwakeintallow(SharkSslSha1Ctx *registermcasp, const U8 alloccontroller[64]) #else static void irqwakeintallow(SharkSslSha1Ctx *registermcasp, U32 countshift[16]) #endif { U32 a, b, c, d, e, brightnesslimit; #if SHARKSSL_SHA1_SMALL_FOOTPRINT unsigned int i; #endif #ifndef B_BIG_ENDIAN U32 countshift[16]; #if SHARKSSL_SHA1_SMALL_FOOTPRINT for (i = 0; !(i & 16); i++) { read64uint32(countshift[i], alloccontroller, (i << 2)); } #else read64uint32(countshift[0], alloccontroller, 0); read64uint32(countshift[1], alloccontroller, 4); read64uint32(countshift[2], alloccontroller, 8); read64uint32(countshift[3], alloccontroller, 12); read64uint32(countshift[4], alloccontroller, 16); read64uint32(countshift[5], alloccontroller, 20); read64uint32(countshift[6], alloccontroller, 24); read64uint32(countshift[7], alloccontroller, 28); read64uint32(countshift[8], alloccontroller, 32); read64uint32(countshift[9], alloccontroller, 36); read64uint32(countshift[10], alloccontroller, 40); read64uint32(countshift[11], alloccontroller, 44); read64uint32(countshift[12], alloccontroller, 48); read64uint32(countshift[13], alloccontroller, 52); read64uint32(countshift[14], alloccontroller, 56); read64uint32(countshift[15], alloccontroller, 60); #endif #endif #define invalidcontext(x,n) ((U32)((U32)x << n) | ((U32)x >> (32 - n))) #define pwdowninverted(x,y,z) ((x & (y ^ z)) ^ z) #define configparse(x,y,z) (x ^ y ^ z) #define emulationhandler(x,y,z) ((x & y) | ((x | y) & z)) #define es3plushwmod(x,y,z) (x ^ y ^ z) #define serial0pdata 0x5A827999 #define registerrproc 0x6ED9EBA1 #define powergpiod 0x8F1BBCDC #define allockernel 0xCA62C1D6 a = registermcasp->state[0]; b = registermcasp->state[1]; c = registermcasp->state[2]; d = registermcasp->state[3]; e = registermcasp->state[4]; #if SHARKSSL_SHA1_SMALL_FOOTPRINT for (i = 0; i < 80; i++) { if (i >= 16) { brightnesslimit = countshift[i & 0xF] ^ countshift[(i + 2) & 0xF] ^ countshift[(i + 8) & 0xF] ^ countshift[(i + 13) & 0xF]; countshift[i & 0xF] = brightnesslimit = invalidcontext(brightnesslimit, 1); } brightnesslimit = countshift[i & 0xF]; brightnesslimit += e + invalidcontext(a, 5); if (i < 20) { brightnesslimit += pwdowninverted(b,c,d) + serial0pdata; } else if (i < 40) { brightnesslimit += configparse(b,c,d) + registerrproc; } else if (i < 60) { brightnesslimit += emulationhandler(b,c,d) + powergpiod; } else { brightnesslimit += es3plushwmod(b,c,d) + allockernel; } e = d; d = c; c = invalidcontext(b, 30); b = a; a = brightnesslimit; } #else e += (countshift[0] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); d += (countshift[1] ) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); c += (countshift[2] ) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); b += (countshift[3] ) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); a += (countshift[4] ) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); e += (countshift[5] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); d += (countshift[6] ) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); c += (countshift[7] ) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); b += (countshift[8] ) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); a += (countshift[9] ) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); e += (countshift[10] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); d += (countshift[11] ) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); c += (countshift[12] ) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); b += (countshift[13] ) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); a += (countshift[14] ) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); e += (countshift[15] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; d += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; c += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; b += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; a += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; e += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; d += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; c += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; b += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; a += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; e += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; d += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; c += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; b += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; a += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; e += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; d += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; c += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; b += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; a += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; e += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; d += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; c += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; b += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; a += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; e += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; d += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; c += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; b += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; a += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; e += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; d += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; c += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; b += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; a += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; e += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; d += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; c += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; b += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; a += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; e += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; d += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; c += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; b += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; a += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; e += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; d += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; c += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; b += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; a += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; e += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; d += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; c += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; b += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; a += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; e += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; d += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; c += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; b += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; a += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; e += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; d += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; c += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; b += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; a += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); #endif registermcasp->state[0] += a; registermcasp->state[1] += b; registermcasp->state[2] += c; registermcasp->state[3] += d; registermcasp->state[4] += e; #undef allockernel #undef powergpiod #undef registerrproc #undef serial0pdata #undef es3plushwmod #undef emulationhandler #undef configparse #undef pwdowninverted #undef invalidcontext } SHARKSSL_API void SharkSslSha1Ctx_constructor(SharkSslSha1Ctx *registermcasp) { baAssert(((unsigned int)(UPTR)(registermcasp->buffer) & (sizeof(int)-1)) == 0); registermcasp->total[0] = 0; registermcasp->total[1] = 0; registermcasp->state[0] = 0x67452301; registermcasp->state[1] = 0xEFCDAB89; registermcasp->state[2] = 0x98BADCFE; registermcasp->state[3] = 0x10325476; registermcasp->state[4] = 0xC3D2E1F0; } SHARKSSL_API void SharkSslSha1Ctx_append(SharkSslSha1Ctx *registermcasp, const U8 *in, U32 len) { unsigned int dm9000platdata, pxa300evalboard; dm9000platdata = (unsigned int)(registermcasp->total[0]) & 0x3F; pxa300evalboard = 64 - dm9000platdata; registermcasp->total[0] += len; if (registermcasp->total[0] < len) { registermcasp->total[1]++; } if((dm9000platdata) && (len >= pxa300evalboard)) { memcpy((registermcasp->buffer + dm9000platdata), in, pxa300evalboard); #ifndef B_BIG_ENDIAN irqwakeintallow(registermcasp, registermcasp->buffer); #else irqwakeintallow(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= pxa300evalboard; in += pxa300evalboard; dm9000platdata = 0; } while (len >= 64) { #ifndef B_BIG_ENDIAN irqwakeintallow(registermcasp, in); #else memcpy(registermcasp->buffer, in, 64); irqwakeintallow(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= 64; in += 64; } if (len) { memcpy((registermcasp->buffer + dm9000platdata), in, len); } } SHARKSSL_API void SharkSslSha1Ctx_finish(SharkSslSha1Ctx *registermcasp, U8 secondaryentry[SHARKSSL_SHA1_HASH_LEN]) { U32 timerenable, dummywrites; U32 timer0start, checkcontext; U8 usbgadgetresource[8]; timer0start = (registermcasp->total[0] >> 29) | (registermcasp->total[1] << 3); checkcontext = (registermcasp->total[0] << 3); inputlevel(timer0start, usbgadgetresource, 0); inputlevel(checkcontext, usbgadgetresource, 4); timerenable = registermcasp->total[0] & 0x3F; dummywrites = (timerenable < 56) ? (56 - timerenable) : (120 - timerenable); SharkSslSha1Ctx_append(registermcasp, (U8*)prusspdata, dummywrites); SharkSslSha1Ctx_append(registermcasp, usbgadgetresource, 8); inputlevel(registermcasp->state[0], secondaryentry, 0); inputlevel(registermcasp->state[1], secondaryentry, 4); inputlevel(registermcasp->state[2], secondaryentry, 8); inputlevel(registermcasp->state[3], secondaryentry, 12); inputlevel(registermcasp->state[4], secondaryentry, 16); } #endif #endif #ifndef NO_HTTP_SESSION #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #include #include #ifndef NO_SHARKSSL #include #endif static int earlyshadow(SplayTreeNode* fdc37m81xconfig, SplayTreeKey k); static void loongsonfprev(HttpSession* o, HttpSessionContainer* traceenter, HttpConnection* con, U32 id); static void allocationdomain(HttpSession* o); static int plltabregister(HttpSession* o); #ifdef NDEBUG #define HttpSession_assertMove2TermList(o) plltabregister(o) #else #define HttpSession_assertMove2TermList(o) \ baAssert( ! plltabregister(o) ) #endif #define HttpSession_dlink2Session(dl) \ (HttpSession*)((U8*)dl-offsetof(HttpSession,dlink)) void HttpSessionContainer_constructor(HttpSessionContainer* o, struct HttpServer* uarchbuild, U16 rd12rn16rm0rs8rwflags) { SplayTree_constructor(&o->sessionTree, earlyshadow); DoubleList_constructor(&o->sessionList); DoubleList_constructor(&o->sessionTermList); o->sessionLinkIter=0; o->server=uarchbuild; o->noOfSessions = 0; o->maxSessions = rd12rn16rm0rs8rwflags; o->eCode = HttpSessionContainer_OK; } void HttpSessionContainer_destructor(HttpSessionContainer* o) { DoubleLink* dl; SplayTreeNode* fdc37m81xconfig; while( (fdc37m81xconfig = SplayTree_getRoot(&o->sessionTree)) != 0) { HttpSession_assertMove2TermList((HttpSession*)fdc37m81xconfig); allocationdomain((HttpSession*)fdc37m81xconfig); baFree(fdc37m81xconfig); } while( (dl = DoubleList_firstNode(&o->sessionTermList)) != 0) { HttpSession* s = HttpSession_dlink2Session(dl); allocationdomain(s); baFree(s); } } #define HttpSessionContainer_getSession(o, id) \ (HttpSession*)SplayTree_find(&(o)->sessionTree,(SplayTreeKey)((size_t)id)) static HttpSession* HttpSessionContainer_getSessionCheckTime( HttpSessionContainer* o, U32 id, U32 sysctltable,U32 pcieswearly) { HttpSession* s = HttpSessionContainer_getSession(o,id); if(s) { s->lastAccessedTime = baGetUnixTime(); return s->sesrnd1 == sysctltable && s->sesrnd2 == pcieswearly ? s : 0; } return 0; } HttpServer* HttpSession_getServer(HttpSession* o) { return o->container->server; } static HttpSession* HttpSessionContainer_createSession(HttpSessionContainer* o, HttpRequest* configuredevice) { HttpSession* func2fixup; if(o->noOfSessions >= o->maxSessions) { DoubleListEnumerator e; DoubleLink* dl; DoubleListEnumerator_constructor(&e, &o->sessionList); dl = DoubleListEnumerator_getElement(&e); while(dl) { func2fixup = HttpSession_dlink2Session(dl); dl = DoubleListEnumerator_nextElement(&e); if(func2fixup->useCounter == 0 && func2fixup->refCounter == 0) { HttpSession_terminate(func2fixup); break; } } if(o->noOfSessions >= o->maxSessions) { TRPR(("\143\162\145\141\164\145\123\145\163\163\151\157\156\072\040\124\157\157\115\141\156\171\123\145\163\163\151\157\156\163\012")); o->eCode = HttpSessionContainer_TooManySessions; return 0; } } func2fixup = (HttpSession*)baMalloc(sizeof(HttpSession)); if(func2fixup) { U32 id; #ifdef NO_SHARKSSL U32 i=0; id = baGetMsClock() * 123456789; #else sharkssl_rng((U8*)&id, sizeof(id)); #endif while (id == 0 || HttpSessionContainer_getSession(o, id)) { #ifdef NO_SHARKSSL id = (id+(++i))*2; #else sharkssl_rng((U8*)&id, sizeof(id)); #endif } loongsonfprev(func2fixup,o,HttpRequest_getConnection(configuredevice),id); o->eCode = HttpSessionContainer_OK; } else { TRPR(("\143\162\145\141\164\145\123\145\163\163\151\157\156\072\040\116\157\115\145\155\157\162\171\012")); o->eCode = HttpSessionContainer_NoMemory; } return func2fixup; } void HttpSessionContainer_sessionTimer(HttpSessionContainer* o) { HttpSession* s; BaTime now = baGetUnixTime(); if(o->sessionLinkIter) { s = HttpSession_dlink2Session(o->sessionLinkIter); o->sessionLinkIter = DoubleLink_getNext(o->sessionLinkIter); if((s->lastAccessedTime + s->maxInactiveInterval) < now && s->lockCounter == 0) { HttpSession_terminate(s); } if(DoubleList_isEnd(&o->sessionList, o->sessionLinkIter)) o->sessionLinkIter = DoubleList_firstNode(&o->sessionList); } } BA_API void HttpSessionAttribute_constructor(HttpSessionAttribute* o, const char* gpio1config, HttpSessionAttribute_Destructor d) { o->next = 0; o->session=0; o->destructor = d; o->name = baStrdup(gpio1config); } BA_API void HttpSessionAttribute_destructor(HttpSessionAttribute* o) { char* gpio1config = o->name; if(o->destructor) { HttpSessionAttribute_Destructor d = o->destructor; o->destructor=0; (*d)(o); } if(gpio1config) baFree(gpio1config); } static int earlyshadow(SplayTreeNode* fdc37m81xconfig, SplayTreeKey k) { if( (size_t)fdc37m81xconfig->key < (size_t)k ) return -1; return (size_t)fdc37m81xconfig->key > (size_t)k ? 1 : 0; } static void loongsonfprev(HttpSession* o, HttpSessionContainer* traceenter, HttpConnection* con, U32 id) { memset(o, 0, sizeof(HttpSession)); SplayTreeNode_constructor((SplayTreeNode*)o, (SplayTreeKey)((size_t)id)); DoubleLink_constructor(&o->dlink); SplayTree_insert(&traceenter->sessionTree, (SplayTreeNode*)o); DoubleList_insertFirst(&traceenter->sessionList, &o->dlink); if( ! traceenter->sessionLinkIter ) traceenter->sessionLinkIter = &o->dlink; HttpConnection_getPeerName(con, &o->peer,0); o->container = traceenter; o->creationTime = o->lastAccessedTime = baGetUnixTime(); o->maxInactiveInterval = 20*60; #ifdef NO_SHARKSSL U32 i=0; o->sesrnd1 = baGetMsClock() * 494073958; o->sesrnd2 = baGetMsClock() * 933739515; #else sharkssl_rng((U8*)&o->sesrnd1, sizeof(o->sesrnd1)); sharkssl_rng((U8*)&o->sesrnd2, sizeof(o->sesrnd2)); #endif traceenter->noOfSessions++; } static void allocationdomain(HttpSession* o) { HttpSessionAttribute* instructioncounter; instructioncounter = o->attrList; while(instructioncounter) { HttpSessionAttribute* attr = instructioncounter; instructioncounter = instructioncounter->next; HttpSessionAttribute_destructor(attr); } DoubleLink_unlink(&o->dlink); } static int plltabregister(HttpSession* o) { HttpSessionContainer* c = o->container; if(SplayTree_remove(&c->sessionTree, (SplayTreeNode*)o)) { baAssert(o->termPending); return -1; } baAssert( ! o->termPending ); baAssert(c->noOfSessions > 0); c->noOfSessions--; o->termPending=TRUE; if(c->sessionLinkIter == &o->dlink) { c->sessionLinkIter = DoubleLink_getNext(c->sessionLinkIter); DoubleLink_unlink(&o->dlink); if(DoubleList_isEnd(&c->sessionList, c->sessionLinkIter)) c->sessionLinkIter = DoubleList_firstNode(&c->sessionList); } else DoubleLink_unlink(&o->dlink); DoubleList_insertLast(&c->sessionTermList, &o->dlink); return 0; } BA_API void HttpSession_decrRefCntr(HttpSession* o) { baAssert(o->refCounter > 0); if(--o->refCounter == 0) { if(o->termPending) HttpSession_terminate(o); } } BA_API void HttpSession_terminate(HttpSession* o) { if(o->refCounter == 0) { if(o->termPending) { baAssert(SplayTree_remove(&o->container->sessionTree, (SplayTreeNode*)o)); } else { if(plltabregister(o)) { baAssert(0); } } allocationdomain(o); baFree(o); } else { plltabregister(o); } } BA_API HttpSessionAttribute* HttpSession_getAttribute(HttpSession* o, const char* gpio1config) { if(o) { HttpSessionAttribute* instructioncounter; instructioncounter = o->attrList; while(instructioncounter) { if( ! strcmp(gpio1config, instructioncounter->name) ) { return instructioncounter; } instructioncounter = instructioncounter->next; } } return 0; } BA_API BaTime HttpSession_getCreationTime(HttpSession* o) { return o->creationTime; } BA_API BaTime HttpSession_getLastAccessedTime(HttpSession* o) { return o->lastAccessedTime; } BA_API BaTime HttpSession_getMaxInactiveInterval(HttpSession* o) { return o->maxInactiveInterval; } BA_API int HttpSession_removeAttribute(HttpSession* o, const char* gpio1config) { if(o->attrList) { HttpSessionAttribute* setupmemory = 0; HttpSessionAttribute* instructioncounter = o->attrList; while(instructioncounter) { if( ! strcmp(gpio1config, instructioncounter->name) ) { if(instructioncounter == o->attrList) { o->attrList = 0; } else { baAssert(setupmemory); setupmemory->next = instructioncounter->next; } HttpSessionAttribute_destructor(instructioncounter); return 0; } setupmemory = instructioncounter; instructioncounter = instructioncounter->next; } } TRPR(("\110\164\164\160\123\145\163\163\151\157\156\072\072\162\145\155\157\166\145\101\164\164\162\151\142\165\164\145\072\040\045\163\040\156\157\164\040\146\157\165\156\144\012",gpio1config)); return -1; } BA_API int HttpSession_setAttribute(HttpSession* o, HttpSessionAttribute* videoprobe) { if( videoprobe->next ) { TRPR(("\110\164\164\160\122\145\161\165\145\163\164\072\072\163\145\164\101\164\164\162\151\142\165\164\145\072\040\101\164\164\162\040\156\157\164\040\151\156\151\164\151\141\154\151\172\145\144\012")); return -2; } if( !videoprobe->name ) { TRPR(("\110\164\164\160\122\145\161\165\145\163\164\072\072\163\145\164\101\164\164\162\151\142\165\164\145\072\040\101\164\164\162\040\156\141\155\145\040\151\163\040\116\125\114\114\012")); return -3; } baAssert( ! videoprobe->session ); videoprobe->session=o; if( ! o->attrList ) o->attrList = videoprobe; else { HttpSessionAttribute* instructioncounter = o->attrList; if( !strcmp(instructioncounter->name, videoprobe->name) ) return -1; while(instructioncounter->next) { instructioncounter = instructioncounter->next; if( !strcmp(instructioncounter->name, videoprobe->name) ) return -1; } instructioncounter->next = videoprobe; } return 0; } BA_API void HttpSession_setMaxInactiveInterval(HttpSession* o, BaTime watchdogresources) { o->maxInactiveInterval = watchdogresources; } BA_API int HttpSession_fmtSessionId(HttpSession* o, U8* buf, size_t lsdc2format) { if(lsdc2format < 25) return -1; baConvU32ToHex(buf, HttpSession_getId(o)); baConvU32ToHex(buf+8, o->sesrnd1); baConvU32ToHex(buf+16, o->sesrnd2); buf[24]=0; return 24; } BA_API HttpSession* HttpRequest_getSession(HttpRequest* o, BaBool breakhandler) { HttpCookie* sessionCookie; if(o->session) return o->session->termPending ? 0 : o->session; sessionCookie = HttpRequest_getCookie(o, BA_COOKIE_ID); if(sessionCookie) { const char* sc=HttpCookie_getValue(sessionCookie); o->session = sc ? HttpRequest_session(o,sc,strlen(sc),TRUE) : 0; if(o->session) return o->session; } if(breakhandler) { if(HttpResponse_committed(HttpRequest_getResponse(o))) { TRPR(("\110\164\164\160\122\145\161\165\145\163\164\072\072\147\145\164\123\145\163\163\151\157\156\072\040\105\137\111\123\137\103\117\115\115\111\124\124\105\104\012")); } else { o->session = HttpSessionContainer_createSession( &o->server->sessionContainer, o); if(o->session) { U8 buf[25]; HttpCookie* sessionCookie = HttpResponse_createCookie( HttpRequest_getResponse(o), BA_COOKIE_ID); HttpSession_fmtSessionId(o->session, buf, sizeof(buf)); HttpCookie_setValue(sessionCookie, (char*)buf); HttpCookie_setPath(sessionCookie, "\057"); HttpCookie_setHttpOnly(sessionCookie,TRUE); HttpCookie_activate(sessionCookie); o->session->refCounter++; return o->session; } } } return 0; } BA_API HttpSession* HttpRequest_session(HttpRequest* o, const char* val, size_t len, int set) { if(24 == len) { HttpConnection* con = HttpRequest_getConnection(o); U32 sysvecbyname = baConvHexToU32(val); HttpSession* s = HttpSessionContainer_getSessionCheckTime( &o->server->sessionContainer, sysvecbyname, baConvHexToU32(val+8), baConvHexToU32(val+16)); if(s) { if( ! HttpConnection_cmpAddr(con, &s->peer) ) { #ifdef HTTP_TRACE HttpSockaddr serialports; char buf[64]; int sffsdrnandflash; HttpSockaddr_addr2String(&s->peer, buf, sizeof(buf), &sffsdrnandflash); TRPR(("\123\145\163\163\151\157\156\040\141\144\144\162\040\145\162\162\072\040\163\075\045\163\054\040\160\075", sffsdrnandflash ? "\077" : buf)); if( SoDispCon_getPeerName((SoDispCon*)con,&serialports,0) ) { sffsdrnandflash=-1; } else { HttpSockaddr_addr2String(&serialports, buf, sizeof(buf), &sffsdrnandflash); } TRPR(("\045\163\012", sffsdrnandflash ? "\077" : buf)); #endif return 0; } if(set) { if( ! o->session ) { s->useCounter++; s->refCounter++; o->session=s; } return o->session; } return s; } } return 0; } BA_API HttpSession* HttpServer_getSession(HttpServer* o, U32 id) { HttpSession* s; s = HttpSessionContainer_getSession(&o->sessionContainer, id); return s; } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #include #include #define IN6ADDRSZ 16 #define INADDRSZ 4 #define U16Z 2 BA_API int HttpSocket_create(HttpSocket* o, const char* preparepoweroff, U16 hwmoddeassert, BaBool restoreucontext, BaBool moduleready) { int sffsdrnandflash; if(restoreucontext) { #ifdef USE_DGRAM HttpSocket_sockUdp(o, preparepoweroff, moduleready, &sffsdrnandflash); #else sffsdrnandflash = E_INVALID_SOCKET_CON; #endif } else { HttpSocket_sockStream(o, preparepoweroff, moduleready, &sffsdrnandflash); } if(sffsdrnandflash == 0) { if(preparepoweroff || hwmoddeassert) { HttpSockaddr sockAddr; HttpSockaddr_gethostbyname(&sockAddr, preparepoweroff, moduleready, &sffsdrnandflash); if(sffsdrnandflash == 0) { HttpSocket_soReuseaddr(o, &sffsdrnandflash); HttpSocket_bind(o, &sockAddr, hwmoddeassert, &sffsdrnandflash); if(sffsdrnandflash != 0) { HttpSocket_close(o); sffsdrnandflash=E_BIND; } } else { HttpSocket_close(o); sffsdrnandflash=E_GETHOSTBYNAME; } } } else { sffsdrnandflash = E_INVALID_SOCKET_CON; HttpSocket_invalidate(o); } return sffsdrnandflash; } #ifdef USE_DGRAM #ifndef HttpSocket_setmembership BA_API int HttpSocket_setmembership(HttpSocket* o, BaBool writeoutput, BaBool moduleready, const char* mcasp1resources, const char* enablecache) { int sffsdrnandflash; HttpSockaddr intfAddr, multiAddr; HttpSockaddr_gethostbyname(&multiAddr, mcasp1resources, moduleready, &sffsdrnandflash); if( ! sffsdrnandflash ) { #if defined(USE_IPV6) && !defined(NO_IPV6_MEMBERSHIP) if(moduleready) { struct ipv6_mreq mreq; memcpy(&mreq.ipv6mr_multiaddr, multiAddr.addr, 16); if(enablecache) { ba_nametoindex(enablecache,&mreq.ipv6mr_interface,&sffsdrnandflash); } else { mreq.ipv6mr_interface=0; } if( ! sffsdrnandflash ) { sffsdrnandflash = socketSetsockopt( o->hndl, IPPROTO_IPV6, writeoutput ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP, (char *) &mreq, sizeof(mreq)); } } else #endif { HttpSockaddr_gethostbyname(&intfAddr, enablecache, FALSE, &sffsdrnandflash); if( ! sffsdrnandflash ) { struct ip_mreq mreq; memcpy(&mreq.imr_multiaddr.s_addr, multiAddr.addr, 4); memcpy(&mreq.imr_interface.s_addr, intfAddr.addr, 4); sffsdrnandflash = socketSetsockopt( o->hndl, IPPROTO_IP, writeoutput ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, (char *) &mreq, sizeof(mreq)); } } } return sffsdrnandflash; } #endif #endif #ifdef USE_ADDRINFO #ifndef BaAddrinfo_connect static int mpidrduplicate(HttpSocket* s, U32 pciercxcfg035) { struct timeval tv; fd_set fds; FD_ZERO(&fds); FD_SET(s->hndl, &fds); tv.tv_sec = pciercxcfg035 / 1000; tv.tv_usec = (pciercxcfg035 % 1000) * 1000; if(socketSelect(s->hndl + 1, 0, &fds, 0, &tv)==1) { struct sockaddr_storage serialports; socklen_t icachealiases=sizeof(struct sockaddr_storage); if(!socketGetPeerName(s->hndl, (struct sockaddr*)&serialports, &icachealiases)) return 1; } HttpSocket_close(s); return E_CANNOT_CONNECT; } int BaAddrinfo_connect(BaAddrinfo* serialports, HttpSocket* s, U32 pciercxcfg035) { int sffsdrnandflash; HttpSocket_setNonblocking(s, &sffsdrnandflash); sffsdrnandflash = socketConnect(s->hndl, serialports->ai_addr, serialports->ai_addrlen); if(sffsdrnandflash) { HttpSocket_wouldBlock(s, &sffsdrnandflash); if( ! sffsdrnandflash ) { HttpSocket_close(s); sffsdrnandflash = E_CANNOT_CONNECT; } else if(pciercxcfg035) sffsdrnandflash = mpidrduplicate(s, pciercxcfg035); else sffsdrnandflash = 0; } else sffsdrnandflash = 1; return sffsdrnandflash; } #endif #endif #ifndef HttpSockaddr_addr2String static int regulatorpdata(U8* ptr, char* buf, int instructionemulation) { return basnprintf(buf, instructionemulation, "\045\165\056\045\165\056\045\165\056\045\165", (unsigned int)ptr[0], (unsigned int)ptr[1], (unsigned int)ptr[2], (unsigned int)ptr[3]) < 0 ? -1 : 0; } #ifdef USE_IPV6 static int stepminshift(U8* ptr, char* buf, int instructionemulation) { U8 *tp, *ep; struct { int base, len; } best, cur; U16 writepmresrn[IN6ADDRSZ / U16Z]; U8 doublefnmul[sizeof("\146\146\146\146\072\146\146\146\146\072\146\146\146\146\072\146\146\146\146\072\146\146\146\146\072\146\146\146\146\072\062\065\065\056\062\065\065\056\062\065\065\056\062\065\065")]; int i; int entervirtual; memset(writepmresrn, 0, sizeof writepmresrn); for (i = 0; i < IN6ADDRSZ; i++) writepmresrn[i / 2] |= (ptr[i] << ((1 - (i % 2)) << 3)); best.base = -1; best.len = 0; cur.base = -1; cur.len = 0; for (i = 0; i < (IN6ADDRSZ / U16Z); i++) { if (writepmresrn[i] == 0) { if (cur.base == -1) cur.base = i, cur.len = 1; else cur.len++; } else { if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; cur.base = -1; } } } if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; } if (best.base != -1 && best.len < 2) best.base = -1; tp = doublefnmul; ep = doublefnmul + sizeof(doublefnmul); for (i = 0; i < (IN6ADDRSZ / U16Z) && tp < ep; i++) { if (best.base != -1 && i >= best.base && i < (best.base + best.len)) { if (i == best.base) { if (tp + 1 >= ep) return -1; *tp++ = '\072'; } continue; } if (i != 0) { if (tp + 1 >= ep) return -1; *tp++ = '\072'; } if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 5 && writepmresrn[5] == 0xffff))) { if (regulatorpdata(ptr+12, (char*)tp, (int)(ep - tp))) return -1; tp += strlen((char*)tp); break; } entervirtual = basnprintf((char*)tp, (int)(ep - tp), "\045\170", writepmresrn[i]); if (entervirtual <= 0 || entervirtual >= ep - tp) return -1; tp += entervirtual; } if (best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / U16Z)) { if (tp + 1 >= ep) return -1; *tp++ = '\072'; } if (tp + 1 >= ep) return -1; *tp++ = 0; if ((tp - doublefnmul) > instructionemulation) { return -1; } strncpy(buf, (char*)doublefnmul, instructionemulation); return 0; } #endif BA_API void HttpSockaddr_addr2String(HttpSockaddr* o, char* buf, int instructionemulation, int* sffsdrnandflash) { #ifdef USE_IPV6 *sffsdrnandflash = o->isIp6 ? stepminshift((U8*)o->addr, buf, instructionemulation) : regulatorpdata((U8*)o->addr, buf, instructionemulation); #else *sffsdrnandflash = regulatorpdata((U8*)o->addr, buf, instructionemulation); #endif } #endif static int defaultsdhci2(const char* src, void* pciercxcfg448) { U32 uda134xplatform=0; int i; char buf[4]; char* end; for(i = 0 ; i < 4 ; i++) { uda134xplatform <<= 8; end = (char*)(i < 3 ? strchr(src, '\056') : src+strlen(src)); if( ! end || (end - src) > 3) break; memmove(buf, src, end - src); buf[end - src] = 0; uda134xplatform += U32_atoi(buf); if(i == 3) { #ifdef B_LITTLE_ENDIAN uda134xplatform=baHtonl(uda134xplatform); #endif memcpy(pciercxcfg448, &uda134xplatform, INADDRSZ); return 0; } src = end+1; } return -1; } #ifndef HttpSockaddr_inetAddr BA_API void HttpSockaddr_inetAddr( HttpSockaddr* o, const char* writereg16, BaBool percpuorder, int* sffsdrnandflash) { *sffsdrnandflash = -1; if( ! bIsxdigit(*writereg16) && *writereg16 != '\072') return; if( ! percpuorder ) { if( ! defaultsdhci2(writereg16,o->addr) ) { o->isIp6=FALSE; *sffsdrnandflash=0; return; } } #ifdef USE_IPV6 { static const char gpio2config[] = "\060\061\062\063\064\065\066\067\070\071\141\142\143\144\145\146"; static const char prepareelf64[] = "\060\061\062\063\064\065\066\067\070\071\101\102\103\104\105\106"; U8 *tp, *endp, *colonp; const char *xdigits, *curtok; int ch, foundDigit; U32 val; tp = (U8*)o->addr; memset(o->addr, 0, IN6ADDRSZ); endp = tp + IN6ADDRSZ; colonp = NULL; if (*writereg16 == '\072') if (*++writereg16 != '\072') return; curtok = writereg16; foundDigit = 0; val = 0; while ((ch = *writereg16++) != '\000') { const char *pch; if ((pch = strchr((xdigits = gpio2config), ch)) == NULL) pch = strchr((xdigits = prepareelf64), ch); if (pch) { val <<= 4; val |= (pch - xdigits); if (val > 0xffff) return; foundDigit = 1; continue; } if (ch == '\072') { curtok = writereg16; if (!foundDigit) { if (colonp) return; colonp = tp; continue; } if (tp + U16Z > endp) return; *tp++ = (U8) (val >> 8) & 0xff; *tp++ = (U8) val & 0xff; foundDigit = 0; val = 0; continue; } if (ch == '\056' && ((tp + INADDRSZ) <= endp) && !defaultsdhci2(curtok, tp)) { tp += INADDRSZ; foundDigit = 0; break; } return; } if (foundDigit) { if (tp + U16Z > endp) return; *tp++ = (U8) (val >> 8) & 0xff; *tp++ = (U8) val & 0xff; } if (colonp) { const int n = (int)(tp - colonp); int i; for (i = 1; i <= n; i++) { endp[- i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; } if (tp != endp) return; o->isIp6=TRUE; *sffsdrnandflash=0; } #endif } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #ifdef HTTP_TRACE static BaBool HttpTrace_isInitialized=FALSE; static HttpTrace_Flush httpTrace_flushCB=0; static ThreadMutex HttpTrace_mutex; static HttpTrace httpTrace; static int keypadpdata(BufPrint* stealclock, int accesssubid) { (void)accesssubid; baAssert(httpTrace_flushCB); if(stealclock->cursor) { static BaBool au1500intclknames = FALSE; if( ! au1500intclknames ) { au1500intclknames = TRUE; httpTrace_flushCB(stealclock->buf, stealclock->cursor); au1500intclknames = FALSE; } stealclock->cursor=0; } else return 0; return 0; } static void flushIfNewLine(void) { BufPrint* stealclock=(BufPrint*)&httpTrace; if(stealclock->cursor) { stealclock->buf[stealclock->cursor]=0; if(strchr(stealclock->buf, '\012')) keypadpdata(stealclock, 0); } } static void gpio6hwmod(HttpTrace* o, HttpTrace_Flush fcb, int icachealiases) { BufPrint* fdc37m81xconfig = (BufPrint*)o; memset(o, 0, sizeof(HttpTrace)); BufPrint_constructor(fdc37m81xconfig, 0, keypadpdata); fdc37m81xconfig->buf=baMalloc(icachealiases+8); fdc37m81xconfig->bufSize=icachealiases; o->prio=5; httpTrace_flushCB = fdc37m81xconfig->buf ? fcb : 0; ThreadMutex_constructor(&HttpTrace_mutex); } BA_API int HttpTrace_setPrio(int reservevmcore) { int viperquirks=httpTrace.prio; httpTrace.prio=reservevmcore; return viperquirks; } BA_API void HttpTrace_setFLushCallback(HttpTrace_Flush fcb) { if(HttpTrace_isInitialized && ((BufPrint*)&httpTrace)->buf) httpTrace_flushCB = fcb; else { gpio6hwmod(&httpTrace, fcb, 81); HttpTrace_isInitialized=TRUE; } } BA_API HttpTrace_Flush HttpTrace_getFLushCallback(void) { return httpTrace_flushCB; } BA_API void HttpTrace_printf(int reservevmcore, const char* fmt, ...) { if(httpTrace_flushCB) { va_list demuxregids; va_start(demuxregids, fmt); HttpTrace_vprintf(reservevmcore, fmt, demuxregids); va_end(demuxregids); } } BA_API void HttpTrace_vprintf(int reservevmcore, const char* fmt, va_list breakpointthread) { if(reservevmcore <= httpTrace.prio && httpTrace_flushCB) { ThreadMutex_set(&HttpTrace_mutex); BufPrint_vprintf((BufPrint*)&httpTrace, fmt, breakpointthread); flushIfNewLine(); ThreadMutex_release(&HttpTrace_mutex); } } BA_API BufPrint* HttpTrace_getWriter(void) { if(httpTrace_flushCB) { ThreadMutex_set(&HttpTrace_mutex); return (BufPrint*)&httpTrace; } return 0; } BA_API void HttpTrace_releaseWriter(void) { baAssert(httpTrace_flushCB); if(httpTrace_flushCB) { flushIfNewLine(); ThreadMutex_release(&HttpTrace_mutex); } } BA_API void HttpTrace_write(int reservevmcore, const char* buf, int len) { if(reservevmcore <= httpTrace.prio && httpTrace_flushCB) { if(len < 0) len = iStrlen(buf); ThreadMutex_set(&HttpTrace_mutex); BufPrint_write((BufPrint*)&httpTrace, buf, len); flushIfNewLine(); ThreadMutex_release(&HttpTrace_mutex); } } BA_API void HttpTrace_flush(void) { if(httpTrace_flushCB) { ThreadMutex_set(&HttpTrace_mutex); keypadpdata((BufPrint*)&httpTrace, 0); ThreadMutex_release(&HttpTrace_mutex); } } BA_API void HttpTrace_setRequest(BaBool cmd) { if(cmd) httpTrace.traceCmds |= HttpTrace_doRequestMask; else httpTrace.traceCmds &= ~(U8)HttpTrace_doRequestMask; } BA_API void HttpTrace_setRequestHeaders(BaBool cmd) { if(cmd) { HttpTrace_setRequest(TRUE); httpTrace.traceCmds |= HttpTrace_doRequestHeadersMask; } else httpTrace.traceCmds &= ~(U8)HttpTrace_doRequestHeadersMask; } BA_API void HttpTrace_setResponseHeaders(BaBool cmd) { if(cmd) httpTrace.traceCmds |= HttpTrace_doResponseHeadersMask; else httpTrace.traceCmds &= ~(U8)HttpTrace_doResponseHeadersMask; } BA_API void HttpTrace_setResponseBody(BaBool cmd) { if(cmd) httpTrace.traceCmds |= HttpTrace_doResponseBodyMask; else httpTrace.traceCmds &= ~(U8)HttpTrace_doResponseBodyMask; } BA_API void HttpTrace_setHttp11State(BaBool cmd) { if(cmd) httpTrace.traceCmds |= HttpTrace_doHttp11StateMask; else httpTrace.traceCmds &= ~(U8)HttpTrace_doHttp11StateMask; } BA_API void HttpTrace_setReqBufOverflow(BaBool cmd) { if(cmd) httpTrace.traceCmds |= HttpTrace_doReqBufOverflowMask; else httpTrace.traceCmds &= ~(U8)HttpTrace_doReqBufOverflowMask; } BA_API U8 HttpTrace_getTraceCmds(void) { return httpTrace.traceCmds; } BA_API int HttpTrace_setBufSize(int icachealiases) { BufPrint* fdc37m81xconfig = (BufPrint*)&httpTrace; if(fdc37m81xconfig->buf) { baFree(fdc37m81xconfig->buf); fdc37m81xconfig->buf=0; } if( !HttpTrace_isInitialized ) { gpio6hwmod(&httpTrace, httpTrace_flushCB, icachealiases); HttpTrace_isInitialized=TRUE; } else { if(icachealiases < 81) icachealiases=81; fdc37m81xconfig->buf=baMalloc(icachealiases); fdc37m81xconfig->bufSize=icachealiases-1; } if(!fdc37m81xconfig->buf) { httpTrace_flushCB = 0; return -1; } return 0; } BA_API HttpTrace* HttpTrace_get(void) { return &httpTrace; } BA_API void HttpTrace_TRPR(const char* fmt, ...) { if(httpTrace_flushCB) { va_list demuxregids; va_start(demuxregids, fmt); HttpTrace_vprintf(0, fmt, demuxregids); va_end(demuxregids); } } BA_API void HttpTrace_close(void) { BufPrint* fdc37m81xconfig = (BufPrint*)&httpTrace; if(fdc37m81xconfig->buf) baFree(fdc37m81xconfig->buf); fdc37m81xconfig->buf=0; httpTrace_flushCB=0; } #else BA_API int HttpTrace_setPrio(int reservevmcore) { (void)reservevmcore; return 0; } BA_API void HttpTrace_setFLushCallback(HttpTrace_Flush fcb) { (void)fcb; } BA_API void HttpTrace_printf(int reservevmcore, const char* fmt, ...) { (void)reservevmcore; (void)fmt; } BA_API void HttpTrace_vprintf(int reservevmcore, const char* fmt, va_list breakpointthread) { (void)reservevmcore; (void)fmt; (void)breakpointthread; } BA_API void HttpTrace_write(int reservevmcore, const char* buf, int len) { (void)reservevmcore; (void)buf; (void)len; } BA_API void HttpTrace_flush(void) { } BA_API BufPrint* HttpTrace_getWriter(void) { return 0; } BA_API void HttpTrace_releaseWriter(void) { } BA_API void HttpTrace_setRequest(BaBool cmd) { (void)cmd; } BA_API void HttpTrace_setRequestHeaders(BaBool cmd) { (void)cmd; } BA_API void HttpTrace_setResponseHeaders(BaBool cmd) { (void)cmd; } BA_API void HttpTrace_setResponseBody(BaBool cmd) { } BA_API void HttpTrace_setHttp11State(BaBool cmd) { (void)cmd; } BA_API void HttpTrace_setReqBufOverflow(BaBool cmd) { (void)cmd; } BA_API U8 HttpTrace_getTraceCmds() { return 0; } BA_API int HttpTrace_setBufSize(int icachealiases) { (void)icachealiases; return 0; } HttpTrace* HttpTrace_get(void) { baAssert(0); return 0; } BA_API void HttpTrace_TRPR(const char* fmt, ...) { (void)fmt; } BA_API void HttpTrace_close(void) { } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #include /* Using offsetof */ #ifndef NO_ZLIB static IoIntf_InflateGzip IoIntf_inflateGzipFp; BA_API void set_inflategzip(IoIntf_InflateGzip ptr) { IoIntf_inflateGzipFp=ptr; } BA_API IoIntf_InflateGzip get_inflategzip(void) { return IoIntf_inflateGzipFp; } #endif static BaBool mailboxentry(const char* defaultcache) { return defaultcache && !baStrCaseCmp(defaultcache, "\147\172\151\160"); } static ResIntfPtr openFile(IoIntf* io, const char* gpio1config, BaBool openAsGzip, int* sffsdrnandflash, const char** ethernatenable) { return #ifndef NO_ZLIB openAsGzip && IoIntf_inflateGzipFp ? IoIntf_inflateGzipFp(io, gpio1config, sffsdrnandflash, ethernatenable) : #endif io->openResFp(io, gpio1config, OpenRes_WRITE, sffsdrnandflash, ethernatenable); } #define HttpUploadNode_bufSize 16384 typedef struct HttpUploadNode { /* This union must be the first aggregate in * HttpUploadNode. HttpUploadNode inherits from * HttpAsynchReq and MultipartUpload. */ union { HttpAsynchReq asyncReq; MultipartUpload mpUpload; } super; HttpAsynchResp asynchResp; DoubleLink link; HttpUpload* parent; ResIntfPtr resPtr; char* path; /* Path and name if PUT or just path if multipart POST */ char* name; /* Path and name */ char* url; /* url to resource excluding name part */ char* buf; void* userdata; U32 sessionID; U8 refCtr; BaBool isMultipartUpload; BaBool isGzip; /* Always false if isMultipartUpload */ BaBool needLingeringClose; BaBool isInitial; } HttpUploadNode; #define HttpUploadNode_isResponseModeM(o) \ ((o)->asynchResp.con ? TRUE : FALSE) BA_API BaBool HttpUploadNode_isResponseMode(HttpUploadNode* o) { return HttpUploadNode_isResponseModeM(o); } static void writeindexed(HttpUploadNode* o) { AllocatorIntf* unmapaliases = o->parent->alloc; DoubleLink_unlink(&o->link); if(o->resPtr) o->resPtr->closeFp(o->resPtr); if( ! HttpUploadNode_isResponseModeM(o) ) { HttpAsynchResp* r3000write = HttpUploadNode_getResponse(o); HttpAsynchResp_setConClose(r3000write); HttpAsynchResp_setStatus(r3000write,500, 0); HttpAsynchResp_sendData(r3000write,0,0,0); } HttpAsynchResp_destructor(&o->asynchResp); AllocatorIntf_free(unmapaliases, o->path); AllocatorIntf_free(unmapaliases, o->url); if(o->name) AllocatorIntf_free(unmapaliases, o->name); if(o->buf) AllocatorIntf_free(unmapaliases, o->buf); if(o->parent->uploadsLeft < 0) { baAssert(DoubleList_isEmpty(&o->parent->uploadNodeList)); AllocatorIntf_free(unmapaliases, o->parent); } else { o->parent->uploadsLeft++; } AllocatorIntf_free(unmapaliases, o); } static HttpUploadNode* HttpUploadNode_link2Obj(DoubleLink* link) { return (HttpUploadNode*)((U8*)link-offsetof(HttpUploadNode,link)); } static int gpio4hwmod( HttpUploadNode* o, const void *alloccontroller, S32 icachealiases, BaBool ldrswliteral) { int sffsdrnandflash=0; if(icachealiases > 0) { if((sffsdrnandflash=o->resPtr->writeFp(o->resPtr, alloccontroller, icachealiases)) == 0) return 0; } else { o->needLingeringClose=FALSE; if(o->resPtr) { sffsdrnandflash = o->resPtr->closeFp(o->resPtr); o->resPtr=0; } if( ! sffsdrnandflash && ! icachealiases ) { if(ldrswliteral == FALSE) return 0; o->parent->uploadCb->onFileFp(o->parent->uploadCb, o, TRUE); } } if(icachealiases < 0 || sffsdrnandflash) { const char* ethernatenable; if(icachealiases < 0) { ethernatenable = "\123\157\143\153\040\145\162\162"; sffsdrnandflash = FE_SOCKET; } else ethernatenable = baErr2Str(sffsdrnandflash); o->parent->uploadCb->onErrorFp(o->parent->uploadCb, o, sffsdrnandflash, ethernatenable); } return -1; } static int clusterunused(MultipartUpload* fdc37m81xconfig, const char* gpio1config, const char* videoprobe) { (void)fdc37m81xconfig; (void)gpio1config; (void)videoprobe; return 0; } static int dummydevice(MultipartUpload* fdc37m81xconfig, const char* gpio1config, const char* timerregister, const char* defaultattrs, const char* rm200disable) { size_t icachealiases; const char* platformnotify=0; HttpUploadNode* o = (HttpUploadNode*)fdc37m81xconfig; o->refCtr++; o->needLingeringClose=TRUE; (void)gpio1config; (void)defaultattrs; if(timerregister) { platformnotify = strrchr(timerregister, '\057'); if(platformnotify) platformnotify++; else { platformnotify = strrchr(timerregister, '\134'); if(platformnotify) platformnotify++; else platformnotify = timerregister; } } if(timerregister && *timerregister) { if(o->name) AllocatorIntf_free(o->parent->alloc, o->name); icachealiases = strlen(o->path) + strlen(platformnotify) + 1; o->name=AllocatorIntf_malloc(o->parent->alloc,&icachealiases); if(o->name) { char* ptr; basnprintf(o->name, (int)icachealiases, "\045\163\045\163", o->path, platformnotify); ptr = o->name+strlen(o->name); while( bIsspace(*(ptr-1)) && (ptr-1) >= o->name) ptr--; *ptr=0; o->parent->uploadCb->onFileFp(o->parent->uploadCb, o, FALSE); if( ! HttpUploadNode_isResponseModeM(o) ) { int sffsdrnandflash; const char* ethernatenable; o->resPtr = openFile(o->parent->io, o->name, mailboxentry(rm200disable), &sffsdrnandflash, ðernatenable); if(o->resPtr) { o->refCtr--; return 0; } o->parent->uploadCb->onErrorFp(o->parent->uploadCb,o,sffsdrnandflash,ethernatenable); } } else { o->parent->uploadCb->onErrorFp( o->parent->uploadCb, o, IOINTF_MEM, "\115\145\155\040\145\162\162"); } } else { o->parent->uploadCb->onErrorFp( o->parent->uploadCb, o, IOINTF_INVALIDNAME,"\116\157\040\146\151\154\145\040\156\141\155\145\040\163\160\145\143\151\146\151\145\144\056"); } HttpUploadNode_decrRef(o); return -1; } static int readycount(MultipartUpload* fdc37m81xconfig,const U8* alloccontroller,U16 icachealiases) { HttpUploadNode* o = (HttpUploadNode*)fdc37m81xconfig; o->refCtr++; if(gpio4hwmod(o,alloccontroller,(S32)icachealiases,FALSE)) return HttpUploadNode_decrRef(o); o->refCtr--; return 0; } static void setupocram(MultipartUpload* fdc37m81xconfig, MultipartUpload_ErrorType e) { HttpUploadNode* o = (HttpUploadNode*)fdc37m81xconfig; TRPR( ("\105\162\162\072\040\155\160\165\117\156\105\162\162\157\162\040\145\075\045\144\012", e) ); o->refCtr++; gpio4hwmod(o, 0, -1, TRUE); HttpUploadNode_decrRef(o); } static void pgtableforce(MultipartUpload* fdc37m81xconfig) { HttpUploadNode* o = (HttpUploadNode*)fdc37m81xconfig; o->refCtr++; if(gpio4hwmod(o, 0, 0, TRUE)) HttpUploadNode_decrRef(o); else o->refCtr--; } static void clockeventdevice(HttpAsynchReq* fdc37m81xconfig, void *alloccontroller, S32 icachealiases) { HttpUploadNode* o = (HttpUploadNode*)fdc37m81xconfig; o->refCtr++; if(!o->resPtr) { int sffsdrnandflash; const char* ethernatenable; o->resPtr = openFile(o->parent->io, o->path, o->isGzip, &sffsdrnandflash, ðernatenable); if(!o->resPtr) { o->parent->uploadCb->onErrorFp(o->parent->uploadCb,o,sffsdrnandflash,ethernatenable); HttpUploadNode_decrRef(o); return; } if(alloccontroller && !icachealiases) { o->refCtr--; return; } } if(gpio4hwmod(o, alloccontroller, icachealiases, TRUE)) HttpUploadNode_decrRef(o); else o->refCtr--; } BA_API HttpAsynchResp* HttpUploadNode_getResponse(HttpUploadNode* o) { if( ! HttpUploadNode_isResponseModeM(o) ) { HttpConnection* con; con = o->isMultipartUpload ? MultipartUpload_getCon((MultipartUpload*)o) : HttpAsynchReq_getCon((HttpAsynchReq*)o); if( ! o->buf ) { size_t icachealiases = HttpUploadNode_bufSize; o->buf = AllocatorIntf_malloc(o->parent->alloc, &icachealiases); } HttpAsynchResp_constructor2( &o->asynchResp, o->buf, HttpUploadNode_bufSize, con); if(o->needLingeringClose) { HttpAsynchResp_setLingeringClose(&o->asynchResp); } } return &o->asynchResp; } BA_API HttpConnection* HttpUploadNode_getConnection(HttpUploadNode* o) { if( ! o->needLingeringClose && ! HttpUploadNode_isResponseModeM(o) ) { return o->isMultipartUpload ? MultipartUpload_getCon((MultipartUpload*)o) : HttpAsynchReq_getCon((HttpAsynchReq*)o); } return 0; } BA_API IoIntfPtr HttpUploadNode_getIoIntf(HttpUploadNode* o) { return o->parent->io; } BA_API void* HttpUploadNode_getdata(HttpUploadNode* o) { return o->userdata; } static void pcmciaconfig(HttpUploadNode* o, HttpUpload* checkstack, char* gpio1config, char* url, BaBool dcacherange, HttpCommand* cmd, void* fixupfinal) { size_t icachealiases; int sffsdrnandflash; HttpSession* func2fixup = HttpRequest_getSession(&cmd->request, FALSE); memset(o, 0, sizeof(HttpUploadNode)); DoubleLink_constructor(&o->link); DoubleList_insertLast(&checkstack->uploadNodeList, &o->link); o->userdata=fixupfinal; o->parent=checkstack; o->path=gpio1config; o->url=url; o->sessionID = func2fixup ? HttpSession_getId(func2fixup) : 0; o->refCtr=0; o->isMultipartUpload = dcacherange; o->needLingeringClose = TRUE; o->isInitial = HttpResponse_initial(&cmd->response); if(dcacherange) { MultipartUpload_constructor( (MultipartUpload*)o, HttpCommand_getServer(cmd), pgtableforce, clusterunused, dummydevice, readycount, setupocram, HttpUploadNode_bufSize, checkstack->alloc); sffsdrnandflash = MultipartUpload_start((MultipartUpload*)o, &cmd->request); } else { HttpAsynchReq_constructor((HttpAsynchReq*)o, HttpCommand_getServer(cmd), clockeventdevice); if(mailboxentry(HttpRequest_getHeaderValue( &cmd->request, "\103\157\156\164\145\156\164\055\105\156\143\157\144\151\156\147"))) { o->isGzip=TRUE; } icachealiases = HttpUploadNode_bufSize; o->buf = AllocatorIntf_malloc(o->parent->alloc, &icachealiases); if(o->buf) { sffsdrnandflash = HttpAsynchReq_start( (HttpAsynchReq*)o, &cmd->request, o->buf, (int)icachealiases); } else sffsdrnandflash=-1; } if(sffsdrnandflash) writeindexed(o); } BA_API const char* HttpUploadNode_getName(HttpUploadNode* o) { return o->name ? o->name : o->path; } BA_API const char* HttpUploadNode_getUrl(HttpUploadNode* o) { return o->url; } BA_API HttpSession* HttpUploadNode_getSession(HttpUploadNode* o) { HttpServer* uarchbuild = o->isMultipartUpload ? MultipartUpload_getServer((MultipartUpload*)o) : HttpAsynchReq_getServer((HttpAsynchReq*)o); return HttpServer_getSession(uarchbuild, o->sessionID); } BA_API BaBool HttpUploadNode_isMultipartUpload(HttpUploadNode* o) { return o->isMultipartUpload; } BA_API BaBool HttpUploadNode_initial(HttpUploadNode* o) { return o->isInitial; } BA_API int HttpUploadNode_decrRef(HttpUploadNode* o) { baAssert(o->refCtr!=0); if(--o->refCtr == 0) { writeindexed(o); return -1; } return 0; } BA_API void HttpUploadNode_incRef(HttpUploadNode* o) { ++o->refCtr; } static void cachelouis( HttpUpload* o, const char* gpio1config, HttpCommand* cmd, void* fixupfinal, BaBool dcacherange) { if(o->uploadsLeft) { HttpUploadNode* smartreflexhwmod; size_t icachealiases = sizeof(HttpUploadNode); char* url = baStrdup2( o->alloc, HttpResponse_encodeRedirectURL(&cmd->response,"")); if(url) { smartreflexhwmod = (HttpUploadNode*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(smartreflexhwmod) { char* serial1pdata = baStrdup2(o->alloc, gpio1config); if(serial1pdata) { o->uploadsLeft--; pcmciaconfig( smartreflexhwmod,o,serial1pdata,url,dcacherange,cmd,fixupfinal); return; } AllocatorIntf_free(o->alloc, smartreflexhwmod); } AllocatorIntf_free(o->alloc, url); } HttpResponse_fmtError( &cmd->response, 503, "\123\145\162\166\145\162\040\155\145\155\157\162\171\040\145\170\150\141\165\163\164\145\144"); } else { HttpResponse_fmtError( &cmd->response, 503, "\124\150\145\040\155\141\170\151\155\165\155\040\156\165\155\142\145\162\040\157\146\040\143\157\156\143\165\162\162\145\156\164\040\165\160\154\157\141\144\163\040\162\145\141\143\150\145\144"); } } BA_API int HttpUpload_service(HttpUpload* o, const char* gpio1config, HttpCommand* cmd, void* fixupfinal) { if(HttpRequest_getMethodType(&cmd->request) == HttpMethod_Put) { cachelouis(o, gpio1config, cmd, fixupfinal, FALSE); return 0; } else if(HttpRequest_getMethodType(&cmd->request) == HttpMethod_Post) { const char* modulefunction = HttpStdHeaders_getContentType( HttpRequest_getStdHeaders(&cmd->request)); if( modulefunction && ! baStrnCaseCmp(modulefunction, "\155\165\154\164\151\160\141\162\164\057\146\157\162\155\055\144\141\164\141", 19)) { cachelouis(o, gpio1config, cmd, fixupfinal, TRUE); return 0; } } return -1; } BA_API void HttpUpload_constructor(HttpUpload* o, IoIntfPtr io, AllocatorIntf* unmapaliases, HttpUploadCbIntf* eventhandler, int ls037modes) { DoubleList_constructor(&o->uploadNodeList); o->io=io; o->alloc=unmapaliases; o->uploadCb=eventhandler; o->uploadsLeft=ls037modes; } BA_API void HttpUpload_destructor(HttpUpload* o) { while( ! DoubleList_isEmpty(&o->uploadNodeList) ) { HttpUploadNode* n = HttpUploadNode_link2Obj( DoubleList_firstNode(&o->uploadNodeList)); o->uploadCb->onErrorFp(o->uploadCb, n, IOINTF_IOERROR, "\124\145\162\155\151\156\141\164\151\156\147"); baAssert(n->refCtr==0); writeindexed(n); } } #ifndef BA_LIB #define BA_LIB 1 #endif #include static int allocdescs(BufPrint* fdc37m81xconfig, int stateparam) { IoBufPrint* o = (IoBufPrint*)fdc37m81xconfig; int sffsdrnandflash = o->res->writeFp(o->res, fdc37m81xconfig->buf, fdc37m81xconfig->cursor); (void)stateparam; fdc37m81xconfig->cursor=0; return sffsdrnandflash; } BA_API IoBufPrint* IoBufPrint_create(AllocatorIntf* unmapaliases, IoIntf* io, size_t lsdc2format, const char* gpio1config) { int sffsdrnandflash; ResIntfPtr out = io->openResFp(io, gpio1config, OpenRes_WRITE, &sffsdrnandflash, 0); if(out) { IoBufPrint* o = IoBufPrint_create2(unmapaliases,lsdc2format,out); if(o) { o->io = io; return o; } out->closeFp(out); } return 0; } BA_API IoBufPrint* IoBufPrint_create2(AllocatorIntf* unmapaliases,size_t lsdc2format,ResIntfPtr out) { size_t icachealiases = sizeof(IoBufPrint)+lsdc2format; IoBufPrint* o = (IoBufPrint*)AllocatorIntf_malloc(unmapaliases, &icachealiases); if(o) { BufPrint* fdc37m81xconfig = (BufPrint*)o; BufPrint_constructor(fdc37m81xconfig, 0, allocdescs); fdc37m81xconfig->buf=(char*)(o+1); fdc37m81xconfig->bufSize = (U16)(icachealiases - sizeof(IoBufPrint)); o->io = 0; o->res=out; } return o; } BA_API void IoBufPrint_destructor(IoBufPrint* o) { BufPrint_flush((BufPrint*)o); if(o->io) o->res->closeFp(o->res); } #ifndef BA_LIB #define BA_LIB 1 #endif #include BA_API int IoIntf_setPassword(IoIntfPtr o, const char* emptytables, size_t tlbdumpsingle) { return o->propertyFp( o, "\160\154", (void*)emptytables, (void*)tlbdumpsingle); } BA_API int IoIntf_setPasswordProp(IoIntfPtr o,BaBool subpackethandler,BaBool cachecheck) { return o->propertyFp( o, "\160\160", subpackethandler ? (void*)~0 : (void*)0, cachecheck ? (void*)~0 : (void*)0); } BA_API char* IoIntf_getAbspath(IoIntfPtr o, const char* driverstate) { char* edma1resources; if(o->propertyFp(o, "\141\142\163", (void*)driverstate, (void*)&edma1resources)) return 0; return edma1resources; } BA_API int IoIntf_getType(IoIntfPtr o, const char** rightsvalid, const char** eventupdate) { return o->propertyFp(o, "\164\171\160\145", (void*)rightsvalid, (void*)eventupdate); } BA_API int IoIntf_isEncrypted(IoIntfPtr o, const char* gpio1config, BaBool* updatelimit) { return o->propertyFp(o, "\141\145\163", (void*)gpio1config, (void*)updatelimit); } BA_API void IoIntf_destructor(IoIntfPtr o) { #ifdef NDEBUG o->propertyFp(o, "\144\145\163\164\162\165\143\164\157\162", 0, 0); #else baAssert(!o->propertyFp(o, "\144\145\163\164\162\165\143\164\157\162", 0, 0)); #endif } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include static int processheader(IoIntfCspReader* o, void* alloccontroller, U32 idmapstart, U32 icachealiases, int spectreauxcr) { size_t rsize; ResIntfPtr fp = o->fp; #ifndef NDEBUG baAssert(fp); if(spectreauxcr) { U32 resetneeded; if(fp->seekFp(fp, idmapstart-4)) return -1; if(fp->readFp(fp, &resetneeded, 4, &rsize) || rsize != 4) return -10; if(baNtohl(resetneeded) != HTTP_MAGIC_NO) return -11; } else #endif { if(o->currentOffset != idmapstart) if(fp->seekFp(fp, idmapstart)) return -1; } o->currentOffset = idmapstart + icachealiases; return (fp->readFp(fp, alloccontroller, icachealiases, &rsize) || rsize != icachealiases) ? -2 : 0; } static int uart8250device(IoIntfCspReader* o, void* alloccontroller, U32 idmapstart, U32 icachealiases, int spectreauxcr) { int sffsdrnandflash; size_t rsize; ResIntfPtr fp = o->fp; #ifndef NDEBUG baAssert(fp); if(spectreauxcr) { U32 resetneeded; if(o->seekAndReadFp(fp, idmapstart-4, &resetneeded, 4, &rsize)) return -10; if(baNtohl(resetneeded) != HTTP_MAGIC_NO) return -11; } #endif if(o->currentOffset == idmapstart) sffsdrnandflash = fp->readFp(fp, alloccontroller, icachealiases, &rsize); else sffsdrnandflash = o->seekAndReadFp(fp, idmapstart, alloccontroller, icachealiases, &rsize); if(sffsdrnandflash || rsize!=icachealiases) return -2; o->currentOffset = idmapstart + icachealiases; return 0; } BA_API void IoIntfCspReader_constructor(IoIntfCspReader* o, IoIntf* io, const char* timerregister) { int sffsdrnandflash; CspReader_Read r; IoStat st; memset(o, 0, sizeof(IoIntfCspReader)); if(io->propertyFp(io, "\163\145\145\153\101\156\144\122\145\141\144", (void*)&o->seekAndReadFp, 0)) r=(CspReader_Read)processheader; else r=(CspReader_Read)uart8250device; CspReader_constructor((CspReader*)o, r); if( (sffsdrnandflash = io->statFp(io, timerregister, &st)) != 0) { TRPR(("\105\162\162\157\162\072\040\111\157\111\156\164\146\103\163\160\122\145\141\144\145\162\054\040\143\141\156\156\157\164\040\157\160\145\156\040\045\163\056", timerregister)); return; } o->fp = io->openResFp(io, timerregister, OpenRes_READ, &sffsdrnandflash, 0); if( o->fp ) { #ifndef NDEBUG size_t rsize; U32 resetneeded; if(o->fp->readFp(o->fp, &resetneeded, 4, &rsize) || rsize != 4) baFatalE(FE_CANNOT_READ, 4); if(baNtohl(resetneeded) != HTTP_MAGIC_NO) baFatalE(FE_MAGIC_NO, 4); #endif CspReader_setIsValid(o); } else { TRPR(("\105\162\162\157\162\072\040\111\157\111\156\164\146\103\163\160\122\145\141\144\145\162\054\040\143\141\156\156\157\164\040\157\160\145\156\040\045\163\056", timerregister)); } } BA_API int IoIntfCspReader_close(IoIntfCspReader* o) { if(o->fp) { ResIntfPtr fp = o->fp; o->fp=0; return fp->closeFp(fp); } return -1; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include static int broadcastcallee(IoIntfZipReader* o, void* alloccontroller, U32 idmapstart, U32 icachealiases, int spectreauxcr) { size_t rsize; ResIntfPtr fp = o->fp; (void)spectreauxcr; if(o->currentOffset != idmapstart) if( (o->lastECode=fp->seekFp(fp, idmapstart)) != 0) return o->lastECode; o->currentOffset = idmapstart + icachealiases; if( (o->lastECode=fp->readFp(fp, alloccontroller, icachealiases, &rsize)) == 0 ) { if(rsize != icachealiases) o->lastECode=IOINTF_IOERROR; } return o->lastECode; } static int shortinstr(IoIntfZipReader* o, void* alloccontroller, U32 idmapstart, U32 icachealiases, int spectreauxcr) { size_t rsize; (void)spectreauxcr; if( (o->lastECode=o->seekAndReadFp(o->fp, idmapstart,alloccontroller,icachealiases,&rsize)) == 0 ) { if(rsize != icachealiases) o->lastECode=IOINTF_IOERROR; } return o->lastECode; } static int ep80219setup(IoIntfZipReader* o, void* alloccontroller, U32 idmapstart, U32 icachealiases, int spectreauxcr) { (void)o; (void)alloccontroller; (void)idmapstart; (void)icachealiases; (void)spectreauxcr; return IOINTF_IOERROR; } BA_API void IoIntfZipReader_constructor(IoIntfZipReader* o, IoIntf* io, const char* timerregister) { IoStat st; memset(o, 0, sizeof(IoIntfZipReader)); if( (o->lastECode = io->statFp(io, timerregister, &st)) != 0) { TRPR(("\105\162\162\157\162\072\040\111\157\111\156\164\146\132\151\160\122\145\141\144\145\162\054\040\143\141\156\156\157\164\040\157\160\145\156\040\045\163\056", timerregister)); ZipReader_constructor((ZipReader*)o, 0, 0); return; } if(io->propertyFp(io, "\163\145\145\153\101\156\144\122\145\141\144", (void*)&o->seekAndReadFp, 0)) { ZipReader_constructor((ZipReader*)o, (CspReader_Read)broadcastcallee, (U32)st.size); } else { ZipReader_constructor((ZipReader*)o, (CspReader_Read)shortinstr, (U32)st.size); } o->fp = io->openResFp(io, timerregister, OpenRes_READ, &o->lastECode, 0); if( o->fp ) { CspReader_setIsValid(o); } else { TRPR(("\105\162\162\157\162\072\040\111\157\111\156\164\146\132\151\160\122\145\141\144\145\162\054\040\143\141\156\156\157\164\040\157\160\145\156\040\045\163\056", timerregister)); } } BA_API int IoIntfZipReader_close(IoIntfZipReader* o) { if(o->fp) { ResIntfPtr fp = o->fp; o->fp=0; if(((CspReader*)o)->readCB==(CspReader_Read)broadcastcallee || ((CspReader*)o)->readCB==(CspReader_Read)shortinstr) { ((CspReader*)o)->readCB = (CspReader_Read)ep80219setup; } return fp->closeFp(fp); } return -1; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include typedef struct { DoubleLink link; /* As if inherited */ char name[1]; } Boundary; static char* extractString(char* str) { httpEatCharacters(str, '\042'); if(*str) { char* probeingenic = ++str; httpEatCharacters(str, '\042'); if(*str) { *str = 0; return probeingenic; } } return 0; } static void sha384final(MultipartUpload* o) { SoDisp* ptraceaccess=HttpServer_getDispatcher(MultipartUpload_getServer(o)); if(SoDispCon_recEvActive((SoDispCon*)o)) SoDisp_deactivateRec(ptraceaccess,(SoDispCon*)o); SoDisp_removeConnection(ptraceaccess,(SoDispCon*)o); } static void driverstring(MultipartUpload* o) { if(HttpConnection_dispatcherHasCon((HttpConnection*)o)) { sha384final(o); } for(;;) { Boundary* boundary = (Boundary*)DoubleList_firstNode(&o->boundaryStack); if(!boundary) break; DoubleLink_unlink((DoubleLink*)boundary); AllocatorIntf_free(o->alloc, boundary); } if(o->name) { AllocatorIntf_free(o->alloc, o->name); o->name=0; } if(o->fileName) { AllocatorIntf_free(o->alloc, o->fileName); o->fileName=0; } if(o->contentType) { AllocatorIntf_free(o->alloc, o->contentType); o->contentType=0; } if(o->contentTransferEncoding) { AllocatorIntf_free(o->alloc, o->contentTransferEncoding); o->contentTransferEncoding=0; } if(o->dataBuffer) { AllocatorIntf_free(o->alloc, o->dataBuffer); o->dataBuffer=0; } o->currBName = 0; o->lineStartI = o->lineEndI = o->readI = 0; o->newBoundaryTag = FALSE; o->copyingHttpReqData=FALSE; } static int kasanreset(MultipartUpload* o, MultipartUpload_ErrorType e) { o->onError(o, e); return e; } static int hwmodshutdown(MultipartUpload* o, const char* str) { Boundary* boundary=0; const char* end; MultipartUpload_ErrorType serial8250device = MultipartUpload_NoError; str = strstr(str, "\142\157\165\156\144\141\162\171\075"); if(str) { size_t icachealiases; int len; str+=9; end=str; httpEatNonWhiteSpace(end); len = (int)((end-str)+4); icachealiases = sizeof(Boundary)+len; boundary = (Boundary*)AllocatorIntf_malloc(o->alloc,&icachealiases); if(boundary) { DoubleLink_constructor(boundary); strcpy(boundary->name, "\015\012\055\055"); memcpy(boundary->name+4, str, len-4); boundary->name[len]=0; DoubleList_insertFirst(&o->boundaryStack, boundary); } else serial8250device = MultipartUpload_NoMemory; } else serial8250device = MultipartUpload_ParseError3; if(serial8250device) return kasanreset(o, serial8250device); o->currBName = boundary->name; return 0; } static int emupagequeue(MultipartUpload* o, const char* enabledisable) { unsigned len; const char* clkevtshutdown = o->currBName+2; httpEatWhiteSpace(enabledisable); if(strcmp(clkevtshutdown, enabledisable)) { len = iStrlen(clkevtshutdown); if( !bStrncmp(clkevtshutdown, enabledisable, len) ) { if(strlen(enabledisable) == len+2 && enabledisable[len] == '\055' && enabledisable[len+1] == '\055') { Boundary* boundary; boundary = (Boundary*)DoubleList_firstNode(&o->boundaryStack); DoubleLink_unlink((DoubleLink*)boundary); AllocatorIntf_free(o->alloc, boundary); boundary = (Boundary*)DoubleList_firstNode(&o->boundaryStack); if(boundary) { o->currBName = boundary->name; return 0; } if(o->lineEndI < o->readI) { HttpConnection* con = o->con ? o->con : (HttpConnection*)o; if(HttpConnection_isValid(con) || HttpConnection_keepAlive(con)) { HttpConnection_pushBack( con, o->dataBuffer+o->lineEndI, o->readI-o->lineEndI); } } o->endOfReq(o); return 1; } } return kasanreset(o, MultipartUpload_ParseError4); } return 0; } static int octeonsystem(MultipartUpload* o) { int n; if(o->copyingHttpReqData) { o->copyingHttpReqData=FALSE; return 0; } baAssert(o->dataBufferSize >= o->readI); if(o->dataBufferSize == o->readI) { void* buf=0; size_t indexnospec = o->dataBufferSize + o->expandSize; if(o->expandSize && o->expandSize <= o->maxFormSize) { buf = AllocatorIntf_realloc(o->alloc, o->dataBuffer, &indexnospec); } if(buf) { o->dataBuffer = buf; o->dataBufferSize = (U32)indexnospec; } else return kasanreset(o, MultipartUpload_NoMemory); } baAssert(o->dataBufferSize > o->readI); if(o->con) { n = HttpConnection_blockRead(o->con, o->dataBuffer + o->readI, o->dataBufferSize - o->readI); } else { n = HttpConnection_readData((HttpConnection*)o, o->dataBuffer + o->readI, o->dataBufferSize - o->readI); } if(n < 0) return kasanreset(o, MultipartUpload_ConnectionTerminated); if(n > 0) { o->readI += n; return n; } return 0; } static char* MultipartUpload_getNextLine(MultipartUpload* o) { for( ; (o->lineEndI+1) < o->readI ; o->lineEndI++) { if(o->dataBuffer[o->lineEndI] == '\015' && o->dataBuffer[o->lineEndI+1] == '\012') { char* handlersetup = o->dataBuffer+o->lineStartI; o->dataBuffer[o->lineEndI]=0; o->lineEndI+=2; o->lineStartI = o->lineEndI; return handlersetup; } } return 0; } static char* MultipartUpload_splitLineAndGetVal(MultipartUpload* o, char* enabledisable) { char* videoprobe = bStrchr(enabledisable, '\072'); if(videoprobe) { *videoprobe++ = 0; httpEatWhiteSpace(videoprobe); if(*videoprobe) return videoprobe; } kasanreset(o, MultipartUpload_ParseError5); return 0; } static void returnaddress(MultipartUpload* o, char* ptr) { o->readI = o->readI - (U32)(ptr - o->dataBuffer); memcpy(o->dataBuffer, ptr, o->readI); o->lineStartI=o->lineEndI=2; } static int timershutdown(MultipartUpload* o) { if(o->lineEndI != o->readI) { char* cachesysfs = o->dataBuffer + o->lineEndI; char* ptr = cachesysfs; while(ptr < (o->dataBuffer + o->readI)) { if(*ptr == *o->currBName) { register char* a = ptr+1; register char* b = o->currBName+1; char* end = o->dataBuffer + o->readI; while(a < end && *a == *b) { a++,b++; } if(a < (o->dataBuffer + o->readI)) { if(*b == 0) { o->state = MultipartUpload_ReadBoundaryTag; if(ptr > cachesysfs) { if(o->fileData(o,(const U8*)cachesysfs,(U16)(ptr-cachesysfs))) return MultipartUpload_UserRetErr; } if(o->fileData(o, 0, 0)) return MultipartUpload_UserRetErr; baAssert((U32)(a - o->dataBuffer) <= o->readI); returnaddress(o,ptr); return 1; } } else { baAssert(a == (o->dataBuffer + o->readI)); if(ptr > cachesysfs) { if(o->fileData(o,(const U8*)cachesysfs, (U16)(ptr - cachesysfs))) return MultipartUpload_UserRetErr; } o->lineEndI = 0; o->readI = (U32)(a - ptr); memcpy(o->dataBuffer, ptr, o->readI); return 0; } } ptr++; } if(o->fileData(o,(const U8*)cachesysfs,(U16)(ptr-cachesysfs))) return MultipartUpload_UserRetErr; o->lineEndI = o->readI = 0; } return 0; } static int switcherenable(MultipartUpload* o) { int sffsdrnandflash; for(;;) { sffsdrnandflash=timershutdown(o); if(sffsdrnandflash) return sffsdrnandflash; if(o->dataBufferSize != o->readI) { int sffsdrnandflash = octeonsystem(o); if(sffsdrnandflash <= 0) { return sffsdrnandflash; } } } } static int enabledevice(MultipartUpload* o) { int sffsdrnandflash; U32 errataconfigure; char* cachesysfs = o->dataBuffer + o->lineEndI; char* ptr = cachesysfs; for(;;) { while(ptr < (o->dataBuffer + o->readI)) { if(*ptr == *o->currBName) { register char* a = ptr+1; register char* b = o->currBName+1; char* end = o->dataBuffer + o->readI; while(*a == *b && a < end) { a++,b++; } if(a < (o->dataBuffer + o->readI)) { if(*b == 0) { *ptr=0; if(o->formData(o, o->name, cachesysfs)) return MultipartUpload_UserRetErr; baAssert((U32)(a - o->dataBuffer) <= o->readI); returnaddress(o,ptr); return 1; } } } ptr++; } errataconfigure = (U32)(ptr - o->dataBuffer); if( (sffsdrnandflash = octeonsystem(o)) <= 0) return sffsdrnandflash; cachesysfs = o->dataBuffer + o->lineEndI; ptr = o->dataBuffer + errataconfigure; } } static int clearcontext(MultipartUpload* o) { int sffsdrnandflash; char* videoprobe; char* doublefnmul; char* gpio1config=0; for(;;) { if(o->state != MultipartUpload_ReadFileData && o->state != MultipartUpload_ReadFormData) { if( (gpio1config = MultipartUpload_getNextLine(o)) == 0) { sffsdrnandflash = octeonsystem(o); if(sffsdrnandflash <= 0) { return sffsdrnandflash; } else continue; } } switch(o->state) { int sffsdrnandflash; case MultipartUpload_ReadBoundaryTag: if(*gpio1config == 0) break; if( (sffsdrnandflash=emupagequeue(o, gpio1config)) != 0) { return sffsdrnandflash; } else { o->state = MultipartUpload_ReadHeaders; } break; case MultipartUpload_ReadHeaders: if(*gpio1config == 0) { if(o->newBoundaryTag) { o->newBoundaryTag = FALSE; o->state = MultipartUpload_ReadBoundaryTag; } else if(o->fileName) { if(o->fileBegin(o, o->name, o->fileName, o->contentType, o->contentTransferEncoding)) { return MultipartUpload_UserRetErr; } AllocatorIntf_free(o->alloc, o->fileName); o->fileName=0; o->state = MultipartUpload_ReadFileData; } else o->state = MultipartUpload_ReadFormData; break; } if((videoprobe=MultipartUpload_splitLineAndGetVal(o, gpio1config)) == 0) { return MultipartUpload_ParseError5; } if(!baStrCaseCmp("\103\157\156\164\145\156\164\055\104\151\163\160\157\163\151\164\151\157\156", gpio1config)) { if((doublefnmul = strstr(videoprobe, "\040\146\151\154\145\156\141\155\145\075")) != 0) { if(o->fileName) AllocatorIntf_free(o->alloc, o->fileName); o->fileName = baStrdup2(o->alloc,extractString(doublefnmul)); } if((doublefnmul = strstr(videoprobe, "\040\156\141\155\145\075")) != 0) { if(o->name) AllocatorIntf_free(o->alloc, o->name); o->name = baStrdup2(o->alloc,extractString(doublefnmul)); } } else if(!baStrCaseCmp("\103\157\156\164\145\156\164\055\124\162\141\156\163\146\145\162\055\105\156\143\157\144\151\156\147", gpio1config)) o->contentTransferEncoding = baStrdup2(o->alloc,videoprobe); else if(!baStrCaseCmp("\103\157\156\164\145\156\164\055\124\171\160\145", gpio1config)) { if((doublefnmul = strstr(videoprobe, "\155\165\154\164\151\160\141\162\164\057\155\151\170\145\144")) != 0) { if((sffsdrnandflash=hwmodshutdown(o, doublefnmul))!=0) { return sffsdrnandflash; } o->newBoundaryTag = TRUE; } else { if(o->contentType) AllocatorIntf_free(o->alloc, o->contentType); o->contentType = baStrdup2(o->alloc,videoprobe); } } break; case MultipartUpload_ReadFormData: if( (sffsdrnandflash = enabledevice(o)) <= 0) return sffsdrnandflash; o->state = MultipartUpload_ReadBoundaryTag; break; case MultipartUpload_ReadFileData: sffsdrnandflash = switcherenable(o); if(sffsdrnandflash <= 0) { return sffsdrnandflash; } break; default: baAssert(0); } } } static int removelookup(MultipartUpload* o) { while(HttpConnection_hasMoreData((HttpConnection*)o)) { int sffsdrnandflash; if( (sffsdrnandflash=octeonsystem(o)) > 0) { if( (sffsdrnandflash=clearcontext(o)) != 0 ) return sffsdrnandflash; } else return sffsdrnandflash ? sffsdrnandflash : MultipartUpload_ConnectionTerminated; } return 0; } static void convertendian(SoDispCon* fdc37m81xconfig) { baAssert( ! ((MultipartUpload*)fdc37m81xconfig)->copyingHttpReqData ); while(SoDispCon_hasMoreData(fdc37m81xconfig)) { if(octeonsystem((MultipartUpload*)fdc37m81xconfig) > 0) { if(clearcontext((MultipartUpload*)fdc37m81xconfig)) return; } else return; } } static int resetdevice(MultipartUpload* o, HttpRequest *req) { int sffsdrnandflash; U32 icachealiases; size_t dataBufferSize; HttpConnection* con = HttpRequest_getConnection(req); SoDisp* sha256start = HttpConnection_getDispatcher(con); HttpInData* registeredevent = HttpRequest_getBuffer(req); const char* cpufreqsetboard = HttpStdHeaders_getContentType( HttpRequest_getStdHeaders(req)); driverstring(o); if(HttpResponse_committed(HttpRequest_getResponse(req))) { TRPR( ("\115\165\154\164\151\160\141\162\164\125\160\154\157\141\144\072\072\163\164\141\162\164\040\143\157\155\155\151\164\164\145\144\012") ); return -1; } if( !HttpConnection_isValid(con) ) { TRPR( ("\115\165\154\164\151\160\141\162\164\125\160\154\157\141\144\072\072\163\164\141\162\164\040\163\164\141\154\145\040\163\157\143\153\145\164\012") ); return -2; } if(HttpRequest_getMethodType(req) != HttpMethod_Post || !cpufreqsetboard || baStrnCaseCmp(cpufreqsetboard, "\155\165\154\164\151\160\141\162\164\057\146\157\162\155\055\144\141\164\141", 19) ) { TRPR( ("\115\165\154\164\151\160\141\162\164\125\160\154\157\141\144\072\072\163\164\141\162\164\040\156\157\164\040\155\165\154\164\151\160\141\162\164\012") ); return -3; } if(HttpRequest_getHeaderValue(req, "\105\170\160\145\143\164")) { HttpResponse_send100Continue(HttpRequest_getResponse(req)); } if(hwmodshutdown(o, cpufreqsetboard)) { return -4; } o->state = MultipartUpload_ReadBoundaryTag; if(o->dataBufferSize < 1024) o->dataBufferSize = 1024; icachealiases = HttpInData_getBufSize(registeredevent); if(icachealiases > o->dataBufferSize) o->dataBufferSize = icachealiases*2; dataBufferSize = o->dataBufferSize; o->dataBuffer = AllocatorIntf_malloc(o->alloc, &dataBufferSize); o->dataBufferSize = (U32)dataBufferSize; if(!o->dataBuffer) return -5; if(o->con) { req->postDataConsumed=TRUE; if(icachealiases != 0) { BaBool destroycontiguous = o->con == 0; U8* ptr = (U8*)HttpInData_getBuf(registeredevent); o->copyingHttpReqData=TRUE; memcpy(o->dataBuffer, ptr, icachealiases); o->readI = icachealiases; registeredevent->lineStartI=registeredevent->lineEndI=registeredevent->allocator.index; if((sffsdrnandflash=clearcontext(o)) != 0) { if(destroycontiguous) return 0; return sffsdrnandflash; } o->copyingHttpReqData=FALSE; return 0; } } else { int sffsdrnandflash = HttpRequest_pushBackData(req); HttpConnection_moveCon(con, (HttpConnection*)o); if(sffsdrnandflash) { if(sffsdrnandflash < 0) return E_MALLOC; if(removelookup(o)) return 0; } baAssert(HttpConnection_isValid((HttpConnection*)o)); SoDisp_addConnection(sha256start, (SoDispCon*)o); SoDisp_activateRec(sha256start, (SoDispCon*)o); } removelookup(o); return 0; } BA_API int MultipartUpload_start(MultipartUpload* o, HttpRequest *req) { HttpRequest_enableKeepAlive(req); return resetdevice(o,req); } BA_API int MultipartUpload_run(MultipartUpload* o, HttpRequest *req, BaBool removebreakpoint) { int sffsdrnandflash; o->con = HttpRequest_getConnection(req); if(HttpConnection_recEvActive(o->con)) { SoDisp_deactivateRec(HttpConnection_getDispatcher(o->con), (SoDispCon*)o->con); } if(removebreakpoint) HttpRequest_enableKeepAlive(req); sffsdrnandflash = resetdevice(o,req); if(sffsdrnandflash < 0) { HttpConnection_destructor(o->con); return sffsdrnandflash; } if(!sffsdrnandflash) { while( (sffsdrnandflash = octeonsystem(o)) >= 0 ) { if( (sffsdrnandflash = clearcontext(o)) != 0 ) break; } } if(sffsdrnandflash >= 0 && HttpConnection_isValid(o->con)) { return 0; } HttpConnection_destructor(o->con); return -1; } BA_API HttpConnection* MultipartUpload_getCon(MultipartUpload* o) { if(o->con) return 0; driverstring(o); return (HttpConnection*)o; } BA_API void MultipartUpload_constructor(MultipartUpload* o, HttpServer* uarchbuild, MultipartUpload_EndOfReq timerunregister, MultipartUpload_FormData cacheshared, MultipartUpload_FileBegin controldeassert, MultipartUpload_FileData blockmapping, MultipartUpload_Error arenaalloc, U32 videodriver, AllocatorIntf* unmapaliases) { memset(o, 0, sizeof(MultipartUpload)); HttpConnection_constructor( (HttpConnection*)o, uarchbuild, uarchbuild->dispatcher, convertendian); o->endOfReq=timerunregister; o->formData=cacheshared; o->fileBegin=controldeassert; o->fileData=blockmapping; o->onError=arenaalloc; o->dataBufferSize = o->expandSize = videodriver; o->maxFormSize = 50000; o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); DoubleList_constructor(&o->boundaryStack); } BA_API void MultipartUpload_destructor(MultipartUpload* o) { driverstring(o); HttpConnection_destructor((HttpConnection*)o); } #ifndef BA_LIB #define BA_LIB 1 #endif #define sodispcon_c 1 #define INL_baConvBin2Hex 1 #include #include #include #include #ifndef NO_SHARKSSL #include #endif static int singlefnmac(SoDispCon* con, ThreadMutex* m, SoDispCon_ExType s, void* d1, int d2) { (void)con; (void)m; (void)s; (void)d1; (void)d2; return E_INCORRECT_USE; } static void defaultoverflow(SoDispCon* o) { SoDispCon_zzCloseCon(o, 2); } BA_API void SoDispCon_constructor(SoDispCon* o, SoDisp* sha256start, SoDispCon_DispRecEv e) { memset(o, 0, sizeof(SoDispCon)); HttpSocket_constructor(&o->httpSocket); o->dispatcher = sha256start; o->dispRecEv = e; o->dispSendEv = defaultoverflow; o->exec = singlefnmac; if(sha256start) SoDisp_newCon(sha256start, o); baAssert( ! o->isSending ); baAssert( ! o->sendTermPtr ); baAssert( ! o->recTermPtr ); baAssert( ! o->dataBits ); baAssert( ! o->rtmo ); } BA_API void SoDispCon_zzCloseCon(SoDispCon* o, int shashdigestsize) { if(SoDispCon_recEvActive(o)) SoDisp_deactivateRec(o->dispatcher,o); if(SoDispCon_sendEvActive(o)) SoDisp_deactivateSend(o->dispatcher,o); if(SoDispCon_dispatcherHasCon(o)) SoDisp_removeConnection(o->dispatcher,o); if(HttpSocket_isValid(&o->httpSocket)) { if(o->exec != singlefnmac) { o->exec(o, SoDisp_getMutex(o->dispatcher), SoDispCon_ExTypeClose, 0, 0); } if(shashdigestsize) { if(shashdigestsize == 2) { HttpSocket_hardClose(&o->httpSocket); } else { HttpSocket_shutdown(&o->httpSocket); } } else { HttpSocket_close(&o->httpSocket); } baAssert( ! HttpSocket_isValid(&o->httpSocket) ); } o->dataBits=0; } BA_API int SoDispCon_moveCon(SoDispCon* o, SoDispCon* boardmanufacturer) { baAssert(SoDispCon_setDispatcherHasCon(o)); if(SoDispCon_recEvActive(o)) SoDisp_deactivateRec(o->dispatcher,o); if(SoDispCon_sendEvActive(o)) SoDisp_deactivateSend(o->dispatcher,o); SoDisp_removeConnection(o->dispatcher, o); boardmanufacturer->dataBits = o->dataBits; o->exec(o,0,SoDispCon_ExTypeMoveCon,boardmanufacturer,0); HttpSocket_move(&o->httpSocket, &boardmanufacturer->httpSocket); o->dataBits &= ~(U8)(SoDispCon_hasMoreDataDataBitMask | SoDispCon_isNonBlockingDataBitMask); baAssert( ! SoDispCon_isValid(o) ); return 0; } #ifdef HTTP_TRACE static void printsystem(const void* alloccontroller, int len) { HttpTrace_write(9,(char*)alloccontroller, len); HttpTrace_write(9,"\012",1); } #endif BA_API int SoDispCon_blockRead(SoDispCon* o, void* alloccontroller, int len) { int buttonsbuffalo; baAssert( ! SoDispCon_isNonBlocking(o) ); do { SoDispCon_setDispHasRecData(o); buttonsbuffalo = SoDispCon_readData(o, alloccontroller, len, TRUE); } while(buttonsbuffalo == 0 && SoDispCon_isSecure(o)); return buttonsbuffalo; } BA_API int SoDispCon_sendData(SoDispCon* o, const void* alloccontroller, int len) { int handlersetup; #ifdef HTTP_TRACE if(HttpTrace_doResponseBody()) printsystem(alloccontroller,len); #endif if( ! SoDispCon_isValid(o) ) return -1; o->isSending=TRUE; handlersetup = o->exec(o, SoDisp_getMutex(o->dispatcher), SoDispCon_ExTypeWrite, (void*)alloccontroller,len) == len ? 0 : E_SOCKET_WRITE_FAILED; o->isSending=FALSE; return handlersetup; } BA_API int SoDispCon_sendDataNT(SoDispCon* o, const void* alloccontroller, int len) { int handlersetup; if( ! SoDispCon_isValid(o) ) return -1; o->isSending=TRUE; handlersetup = o->exec(o, SoDisp_getMutex(o->dispatcher), SoDispCon_ExTypeWrite, (void*)alloccontroller,len) == len ? 0 : E_SOCKET_WRITE_FAILED; o->isSending=FALSE; return handlersetup; } BA_API int SoDispCon_sendDataX(SoDispCon* o, const void* alloccontroller, int len) { int handlersetup; if( ! SoDispCon_isValid(o) ) return -1; o->isSending=TRUE; handlersetup = o->exec(o, 0, SoDispCon_ExTypeWrite, (void*)alloccontroller,len) == len ? 0 : E_SOCKET_WRITE_FAILED; o->isSending=FALSE; return handlersetup; } BA_API int SoDispCon_sendChunkData(SoDispCon* o, const void* alloccontroller, int len) { U8 buf[6]; U8* cachesysfs = buf; U8* end = buf; U8 processsubpacket = (U8)(len >> 8); if(processsubpacket) { baConvBin2Hex(end, processsubpacket); end+=2; } baConvBin2Hex(end, (U8)len); end+=2; *end++ = '\015'; *end = '\012'; if(*cachesysfs == '\060') cachesysfs++; if(!SoDispCon_sendDataNT(o, cachesysfs, (int)(end-cachesysfs+1))) if(!SoDispCon_sendData(o, alloccontroller, len)) if(!SoDispCon_sendDataNT(o, "\015\012", 2)) return 0; return -1; } BA_API void* SoDispCon_allocAsynchBuf(SoDispCon* o, int* icachealiases) { AllocAsynchBufArgs enetswplatform; enetswplatform.size = *icachealiases; (o)->exec(o,0,SoDispCon_ExTypeAllocAsynchBuf,&enetswplatform,0); *icachealiases = enetswplatform.size; return enetswplatform.retVal; } BA_API void SoDispCon_setTCPNoDelay(SoDispCon* o, int writeoutput) { int sffsdrnandflash; (void)writeoutput; HttpSocket_setTCPNoDelay(&o->httpSocket, writeoutput, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr(o, "\163\145\164\124\103\120\116\157\104\145\154\141\171", &o->httpSocket, sffsdrnandflash); #endif } } BA_API int SoDispCon_setNonblocking(SoDispCon* o) { int sffsdrnandflash; if( SoDispCon_isNonBlocking(o) ) { TRPR(("\123\157\104\151\163\160\103\157\156\072\072\163\145\164\116\157\156\142\154\157\143\153\151\156\147\040\055\076\040\151\163\040\141\154\162\145\141\144\171\040\156\157\156\040\142\154\157\143\153\151\156\147\012")); return -1; } HttpSocket_setNonblocking(&o->httpSocket, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr(o, "\163\145\164\116\157\156\142\154\157\143\153\151\156\147", &o->httpSocket, sffsdrnandflash); #endif } else o->dataBits |= SoDispCon_isNonBlockingDataBitMask; return sffsdrnandflash; } BA_API int SoDispCon_setBlocking(SoDispCon* o) { int sffsdrnandflash; if( ! SoDispCon_isNonBlocking(o) ) { TRPR(("\123\157\104\151\163\160\103\157\156\072\072\163\145\164\102\154\157\143\153\151\156\147\040\055\076\040\151\163\040\141\154\162\145\141\144\171\040\142\154\157\143\153\151\156\147\012")); return -1; } HttpSocket_setBlocking(&o->httpSocket, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr(o, "\163\145\164\102\154\157\143\153\151\156\147", &o->httpSocket, sffsdrnandflash); #endif } else (o)->dataBits &= ~(U8)SoDispCon_isNonBlockingDataBitMask; return sffsdrnandflash; } BA_API int SoDispCon_getPeerName(SoDispCon* o, HttpSockaddr* serialports, U16* hwmoddeassert) { int sffsdrnandflash=0; BaBool earlyconfig = SoDispCon_isIP6(o); HttpSocket_getPeerName(&o->httpSocket, serialports, hwmoddeassert, earlyconfig, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr(o, "\147\145\164\120\145\145\162\116\141\155\145", &o->httpSocket, sffsdrnandflash); #endif } return sffsdrnandflash; } BA_API int SoDispCon_getSockName(SoDispCon* o, HttpSockaddr* serialports, U16* hwmoddeassert) { int sffsdrnandflash=0; BaBool earlyconfig = SoDispCon_isIP6(o); HttpSocket_getSockName(&o->httpSocket, serialports, hwmoddeassert, earlyconfig, &sffsdrnandflash); if(sffsdrnandflash) { #ifdef HTTP_TRACE SoDispCon_printSockErr(o, "\147\145\164\123\157\143\153\116\141\155\145", &o->httpSocket, sffsdrnandflash); #endif } return sffsdrnandflash; } BA_API char* SoDispCon_addr2String(SoDispCon* o, HttpSockaddr* serialports, char* buf, int len) { int sffsdrnandflash; if( !buf ) return 0; buf[0]=0; if(serialports->isIp6 ? (len < 46) : (len < 16)) return 0; if(SoDispCon_isIP6(o) != serialports->isIp6) return 0; HttpSockaddr_addr2String(serialports, buf, len, &sffsdrnandflash); return sffsdrnandflash ? 0 : buf; } static BaBool cmpIp4MappedIp6(const char factoryconfig[16], const char ip4[16]) { return !memcmp( "\000\000\000\000\000\000\000\000\000\000\377\377", factoryconfig, 12) && !memcmp(factoryconfig+12,ip4,4); } BA_API BaBool SoDispCon_cmpAddr(SoDispCon* o, HttpSockaddr* configureerrgen) { HttpSockaddr addr1; if( !SoDispCon_getPeerName(o,&addr1,0) ) { if(addr1.isIp6 == configureerrgen->isIp6) { int len = addr1.isIp6 ? 16 : 4; return memcmp(addr1.addr, configureerrgen->addr, len) == 0; } if(addr1.isIp6 && addr1.addr[0] == 0) return cmpIp4MappedIp6((char*)addr1.addr, (char*)configureerrgen->addr); if(configureerrgen->isIp6 && configureerrgen->addr[0] == 0) return cmpIp4MappedIp6((char*)configureerrgen->addr, (char*)addr1.addr); } return FALSE; } BA_API int SoDispCon_asyncReadyF(SoDispCon* o) { return SoDispCon_asyncReady(o); } #ifdef HTTP_TRACE BA_API void SoDispCon_printSockErr(SoDispCon* o,const char* rightsvalid,HttpSocket* s,int sffsdrnandflash) { int serial8250device; (void)s; HttpSocket_errno(s, sffsdrnandflash, &serial8250device); HttpTrace_printf(10,"\123\157\143\153\145\164\040\145\162\162\157\162\054\040\143\157\156\156\145\143\164\151\157\156\040\050\045\160\051\040\045\163\040\145\162\162\156\157\072\040\045\144\012", o, rightsvalid, serial8250device); } #endif BA_API int SoDispCon_upgrade( SoDispCon* o, struct SharkSsl* ssl, const char* disableswapping, const char* writereg16, int hwmoddeassert) { #ifndef NO_SHARKSSL return HttpSharkSslServCon_bindExec(o, ssl, disableswapping, writereg16, hwmoddeassert); #else return E_INCORRECT_USE; #endif } #ifdef USE_ADDRINFO static int hwmodcommon(SoDispCon* o, const char* writereg16, U16 hwmoddeassert,BaBool restoreucontext, BaBool moduleready, BaAddrinfo** serialports, char** sha256import) { BaAddrinfo hints; int sffsdrnandflash; char keypadresource[8]; char* dcachealiases; if(restoreucontext) o->dataBits |= SoDispCon_DGramBitMask; if(!sha256import) sha256import=&dcachealiases; BaAddrinfo_hintsInit(&hints, restoreucontext, moduleready); basprintf(keypadresource, "\045\144",(unsigned int)hwmoddeassert); BaAddrinfo_get(writereg16, keypadresource, &hints, serialports, &sffsdrnandflash, sha256import); return sffsdrnandflash ? E_CANNOT_RESOLVE : 0; } BA_API int SoDispCon_connect(SoDispCon* o, const char* writereg16, U16 hwmoddeassert, const void* preparepoweroff, U16 bindPort, U32 pciercxcfg035, BaBool restoreucontext, BaBool moduleready, char** sha256import) { BaAddrinfo* serialports; int sffsdrnandflash; ThreadMutex* m = SoDisp_getMutex(SoDispCon_getDispatcher(o)); if(sha256import) *sha256import=0; if( ! m || ! ThreadMutex_isOwner(m) ) m=0; else ThreadMutex_release(m); baAssert(pciercxcfg035); sffsdrnandflash = hwmodcommon(o,writereg16,hwmoddeassert,restoreucontext,moduleready,&serialports,sha256import); if( ! sffsdrnandflash ) { BaAddrinfo* instructioncounter = serialports; for(;;) { sffsdrnandflash=HttpSocket_create(&o->httpSocket, preparepoweroff, bindPort, restoreucontext, BaAddrinfo_isIp6(instructioncounter)); if(sffsdrnandflash) break; sffsdrnandflash=BaAddrinfo_connect(instructioncounter, &o->httpSocket, pciercxcfg035); if(sffsdrnandflash == 1) break; HttpSocket_close(&o->httpSocket); BaAddrinfo_next(&instructioncounter); if( ! instructioncounter ) break; } baAssert(sffsdrnandflash != 0); if(sffsdrnandflash == 1) { HttpServCon_bindExec(o); if(BaAddrinfo_isIp6(instructioncounter)) SoDispCon_setIP6((SoDispCon*)o); HttpSocket_setBlocking(&o->httpSocket, &sffsdrnandflash); } BaAddrinfo_free(serialports); } if(m) ThreadMutex_set(m); return sffsdrnandflash; } typedef struct { BaAddrinfo* addr; BaAddrinfo* iter; char bindIntfName[1]; } SoDispConAsyncConnect; static int sigframelayout(SoDispCon* o, SoDispConAsyncConnect* ac) { int sffsdrnandflash=HttpSocket_create( &o->httpSocket, *ac->bindIntfName ? ac->bindIntfName : 0, 0, FALSE, BaAddrinfo_isIp6(ac->addr)); if( ! sffsdrnandflash ) { sffsdrnandflash=BaAddrinfo_connect(ac->iter, &o->httpSocket, 0); if(sffsdrnandflash < 0) HttpSocket_close(&o->httpSocket); } return sffsdrnandflash; } BA_API int SoDispCon_asyncConnect(SoDispCon* o, const char* writereg16, U16 hwmoddeassert, const void* preparepoweroff, BaBool moduleready, char** sha256import) { BaAddrinfo* serialports; int sffsdrnandflash; baAssert( ! o->sslData ); if(sha256import) *sha256import=0; o->dataBits |= SoDispCon_isNonBlockingDataBitMask; sffsdrnandflash = hwmodcommon(o,writereg16,hwmoddeassert,FALSE,moduleready,&serialports,sha256import); if( ! sffsdrnandflash ) { SoDispConAsyncConnect* ac = baMalloc( sizeof(SoDispConAsyncConnect)+(preparepoweroff ? strlen(preparepoweroff):0)); if(ac) { if(preparepoweroff) strcpy(ac->bindIntfName,preparepoweroff); else ac->bindIntfName[0]=0; ac->addr=ac->iter=serialports; HttpServCon_bindExec(o); sffsdrnandflash = sigframelayout(o, ac); if(sffsdrnandflash == 0) { o->sslData = ac; return sffsdrnandflash; } baFree(ac); BaAddrinfo_free(serialports); } } return sffsdrnandflash; } BA_API int SoDispCon_asyncConnectNext(SoDispCon* o) { SoDispConAsyncConnect* ac = (SoDispConAsyncConnect*)o->sslData; baAssert(ac); if(ac) { BaAddrinfo_next(&ac->iter); if(ac->iter) { int sffsdrnandflash; HttpSocket_close(&o->httpSocket); sffsdrnandflash = sigframelayout(o, ac); if(sffsdrnandflash >= 0) return sffsdrnandflash; } } return E_CANNOT_CONNECT; } BA_API void SoDispCon_asyncConnectRelease(SoDispCon* o) { SoDispConAsyncConnect* ac = (SoDispConAsyncConnect*)o->sslData; if(ac) { o->sslData=0; BaAddrinfo_free(ac->addr); baFree(ac); } } #else static int hwmodcommon(SoDispCon* o, HttpSockaddr* serialports, const char* writereg16, const void* preparepoweroff, U16 hwmoddeassert, BaBool restoreucontext, BaBool moduleready) { int sffsdrnandflash; if(restoreucontext) o->dataBits |= SoDispCon_DGramBitMask; HttpSockaddr_inetAddr(serialports, writereg16, moduleready, &sffsdrnandflash); if(sffsdrnandflash != 0) { HttpSockaddr_gethostbyname(serialports, writereg16, moduleready, &sffsdrnandflash); if(sffsdrnandflash != 0) return E_CANNOT_RESOLVE; } return HttpSocket_create(&o->httpSocket, preparepoweroff, hwmoddeassert, restoreucontext, moduleready); } BA_API int SoDispCon_connect(SoDispCon* o, const char* writereg16, U16 hwmoddeassert, const void* preparepoweroff, U16 bindPort, U32 pciercxcfg035, BaBool restoreucontext, BaBool moduleready, char** sha256import) { HttpSockaddr serialports; int sffsdrnandflash; ThreadMutex* m = SoDisp_getMutex(SoDispCon_getDispatcher(o)); (void)pciercxcfg035; if(sha256import) *sha256import=0; if( ! ThreadMutex_isOwner(m) ) m=0; else ThreadMutex_release(m); baAssert(pciercxcfg035); sffsdrnandflash=hwmodcommon(o, &serialports, writereg16, preparepoweroff, bindPort, restoreucontext, moduleready); if( ! sffsdrnandflash ) { HttpSocket_connect(&o->httpSocket, &serialports, hwmoddeassert, &sffsdrnandflash); if(sffsdrnandflash) { sffsdrnandflash = E_CANNOT_CONNECT; HttpSocket_close(&o->httpSocket); } else { HttpServCon_bindExec(o); if(serialports.isIp6) SoDispCon_setIP6((SoDispCon*)o); } } if(m) ThreadMutex_set(m); return sffsdrnandflash; } #ifndef NO_ASYNCH_RESP BA_API int SoDispCon_asyncConnect(SoDispCon* o, const char* writereg16, U16 hwmoddeassert, const void* preparepoweroff, BaBool moduleready, char** sha256import) { int sffsdrnandflash; HttpSockaddr serialports; if(sha256import) *sha256import=0; o->dataBits |= SoDispCon_isNonBlockingDataBitMask; sffsdrnandflash=hwmodcommon(o, &serialports, writereg16, preparepoweroff, 0, FALSE, moduleready); if( ! sffsdrnandflash ) { HttpServCon_bindExec(o); HttpSocket_setNonblocking(&o->httpSocket, &sffsdrnandflash); HttpSocket_connect(&o->httpSocket, &serialports, hwmoddeassert, &sffsdrnandflash); if(sffsdrnandflash) { HttpSocket_wouldBlock(&o->httpSocket, &sffsdrnandflash); if( ! sffsdrnandflash ) { HttpSocket_close(&o->httpSocket); sffsdrnandflash = E_CANNOT_CONNECT; } else sffsdrnandflash = 0; } else sffsdrnandflash = 1; } return sffsdrnandflash; } BA_API int SoDispCon_asyncConnectNext(SoDispCon* o) { (void)o; return E_CANNOT_CONNECT; } #endif #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #ifdef _SharkSsl_TargConfig_h #define BA_API #else #include #endif #include BA_API void SplayTreeNode_constructor(SplayTreeNode* o, SplayTreeKey sourcerouting) { o->left=o->right=0; o->key=sourcerouting; } static void devicestuart(SplayTree* o, SplayTreeKey sourcerouting) { int cmp; SplayTreeNode N, *l, *r, *y, *mcasp0resources; N.left=N.right=0; if ( !o->root ) return; l = r = &N; mcasp0resources = o->root; while( (cmp = o->compare(mcasp0resources, sourcerouting)) != 0 ) { if(cmp < 0) { if( ! mcasp0resources->left ) break; if(o->compare(mcasp0resources->left, sourcerouting) < 0) { y = mcasp0resources->left; mcasp0resources->left = y->right; y->right = mcasp0resources; mcasp0resources = y; if( ! mcasp0resources->left ) break; } r->left = mcasp0resources; r = mcasp0resources; mcasp0resources = mcasp0resources->left; } else if(cmp > 0) { if( ! mcasp0resources->right ) break; if(o->compare(mcasp0resources->right, sourcerouting) > 0) { y = mcasp0resources->right; mcasp0resources->right = y->left; y->left = mcasp0resources; mcasp0resources = y; if( ! mcasp0resources->right ) break; } l->right = mcasp0resources; l = mcasp0resources; mcasp0resources = mcasp0resources->right; } } l->right = mcasp0resources->left; r->left = mcasp0resources->right; mcasp0resources->left = N.right; mcasp0resources->right = N.left; o->root = mcasp0resources; } BA_API int SplayTree_insert(SplayTree* o, SplayTreeNode* n) { int cmp; baAssert( !n->left && !n->right ); if ( ! o->root ) { o->root = n; return 0; } devicestuart(o, n->key); cmp = o->compare(o->root, n->key); if(cmp < 0) { n->left = o->root->left; n->right = o->root; o->root->left = 0; o->root = n; return 0; } else if(cmp > 0) { n->right = o->root->right; n->left = o->root; o->root->right = 0; o->root = n; return 0; } return -1; } BA_API SplayTreeNode* SplayTree_find(SplayTree* o, SplayTreeKey sourcerouting) { if ( ! o->root ) return 0; devicestuart(o, sourcerouting); return o->compare(o->root, sourcerouting) == 0 ? o->root : 0; } BA_API int SplayTree_remove(SplayTree* o, SplayTreeNode* n) { if (SplayTree_find(o, n->key) && n == o->root) { if ( ! o->root->left ) { o->root = o->root->right; } else { o->root = o->root->left; devicestuart(o, n->key); baAssert( ! o->root->right ); o->root->right = n->right; } n->left=n->right=0; return 0; } return -1; } typedef struct { void* userObj; SplayTree_Iter i; } SplayTreeIter; static int hwmodparse(SplayTreeIter* o, SplayTreeNode* n) { if(n) { if(o->i(o->userObj, n)) return -1; if(hwmodparse(o, n->left)) return -1; if(hwmodparse(o, n->right)) return -1; } return 0; } BA_API int SplayTree_iterate(SplayTree* o, void* touchpdata, SplayTree_Iter i) { if(o->root) { SplayTreeIter spi; spi.userObj=touchpdata; spi.i=i; if(hwmodparse(&spi, o->root)) return -1; } return 0; } #include "VirDir.h" #include void VirFileNode_constructor(VirFileNode* o, const char* gpio1config) { o->next=0; o->name=gpio1config; } static VirFileNode* VirFileNode_find(VirFileNode* o, const char* gpio1config) { while(o) { VirFileNode* n2 = o->next; if(n2) { VirFileNode* n3 = n2->next; if(n3) { VirFileNode* n4 = n3->next; if(n4) { int n; if((n=strcmp(gpio1config, n4->name)) == 0) return n4; if(n > 0) { o = n4->next; continue; } } if(strcmp(n3->name, gpio1config) == 0) return n3; } if(strcmp(n2->name, gpio1config) == 0) return n2; } if(strcmp(o->name, gpio1config) == 0) return o; return 0; } return 0; } static void unregisterguest(VirFileNode* o,AllocatorIntf* unmapaliases,VirFileNode_Free localtimer) { VirFileNode* instructioncounter = o; while(instructioncounter) { VirFileNode* vfn = instructioncounter; instructioncounter = instructioncounter->next; if(localtimer) localtimer(vfn, unmapaliases); else AllocatorIntf_free(unmapaliases, vfn); } } void VirDirNode_constructor(VirDirNode* o, const char* gpio1config, size_t len) { memset(o, 0, sizeof(VirDirNode)); if(gpio1config) { strncpy(o->name, gpio1config, len); o->name[len]=0; } } static void rfkilldevice(VirDirNode* o, VirDirNode* vdn) { if(o->subDir) { if(strcmp(vdn->name, o->subDir->name) < 0) { vdn->next = o->subDir; o->subDir = vdn; } else { VirDirNode* prevElem = o->subDir; VirDirNode* instructioncounter = prevElem->next; while(instructioncounter) { if(strcmp(vdn->name, instructioncounter->name) < 0) break; prevElem = instructioncounter; instructioncounter = instructioncounter->next; } vdn->next = prevElem->next; prevElem->next = vdn; } } else o->subDir=vdn; } static int coproaccess(VirDirNode* o, VirFileNode* vfn) { if(o->firstFile) { if(strcmp(vfn->name, o->firstFile->name) < 0) { vfn->next = o->firstFile; o->firstFile = vfn; } else { VirFileNode* prevElem = o->firstFile; VirFileNode* instructioncounter = prevElem->next; while(instructioncounter) { if(strcmp(vfn->name, instructioncounter->name) < 0) break; prevElem = instructioncounter; instructioncounter = instructioncounter->next; } vfn->next = prevElem->next; prevElem->next = vfn; } } else o->firstFile=vfn; return 0; } static int entrypoint(const char* n, const char* rp, size_t translationcache) { int sffsdrnandflash=strncmp(n,rp,translationcache); if( ! sffsdrnandflash ) { size_t len = strlen(n); if(len < translationcache) return -1; if(len > translationcache) return 1; } return sffsdrnandflash; } static VirDirNode* VirDirNode_findDir(VirDirNode* o, const char* gpio1config, size_t len) { while(o) { VirDirNode* n2 = o->next; if(n2) { VirDirNode* n3 = n2->next; if(n3) { VirDirNode* n4 = n3->next; if(n4) { int n; if((n=entrypoint(n4->name, gpio1config, len)) == 0) return n4; if(n < 0) { o = n4->next; continue; } } if(entrypoint(n3->name, gpio1config, len) == 0) return n3; } if(entrypoint(n2->name, gpio1config, len) == 0) return n2; } if(entrypoint(o->name, gpio1config, len) == 0) return o; return 0; } return 0; } VirDirNode* VirDirNode_findSubDir(VirDirNode* o, const char* gpio1config, size_t len) { if(len == 0) len = strlen(gpio1config); return VirDirNode_findDir(o->subDir, gpio1config, len); } VirFileNode* VirDirNode_findFile(VirDirNode* o, const char* gpio1config) { return VirFileNode_find(o->firstFile, gpio1config); } VirDir_Type VirDirNode_find(VirDirNode* o, const char* driverregister, void** handlersetup) { VirFileNode* vfn; VirDirNode* sd; const char* ref; if( !*driverregister || (*driverregister == '\057' && !driverregister[1]) ) { *handlersetup = o; return VirDir_IsDir; } while( (ref = strchr(driverregister, '\057')) != 0 ) { sd = VirDirNode_findDir(o->subDir, driverregister, ref-driverregister); if(sd) { driverregister = ref+1; if( ! *driverregister ) { *handlersetup=sd; return VirDir_IsDir; } o=sd; } else return VirDir_NotFound; } if( (vfn = VirFileNode_find(o->firstFile, driverregister)) != 0) { *handlersetup=vfn; return VirDir_IsFile; } if( (sd = VirDirNode_findDir(o->subDir, driverregister, strlen(driverregister))) != 0) { *handlersetup=sd; return VirDir_IsDir; } return VirDir_NotFound; } VirDirNode* VirDirNode_makeDir(VirDirNode* o, const char* timerregister, AllocatorIntf* unmapaliases) { const char* ref; while( (ref = strchr(timerregister, '\057')) != 0 ) { VirDirNode* sd = VirDirNode_findDir(o->subDir, timerregister, ref-timerregister); if(sd) { timerregister = ref+1; if( ! *timerregister ) return sd; o=sd; } else break; } if( ! ref ) return o; do { size_t len = sizeof(VirDirNode) + (ref-timerregister); VirDirNode* vdn = AllocatorIntf_malloc(unmapaliases, &len); if( ! vdn ) return 0; VirDirNode_constructor(vdn, timerregister, ref-timerregister); rfkilldevice(o, vdn); o=vdn; timerregister = ref+1; } while( (ref = strchr(timerregister, '\057')) != 0 ); return o; } int VirDirNode_mkDirInsertFile( VirDirNode* o, const char* timerregister, VirFileNode* vfn, AllocatorIntf* unmapaliases) { const char* ref = timerregister ? strrchr(timerregister, '\057') : 0; if( ! ref ) return coproaccess(o, vfn); o = VirDirNode_makeDir(o, timerregister, unmapaliases); if(o) return coproaccess(o, vfn); return -1; } void VirDirNode_free(VirDirNode* o,AllocatorIntf* unmapaliases,VirFileNode_Free localtimer) { VirDirNode* instructioncounter; if(o->subDir) { VirDirNode_free(o->subDir, unmapaliases, localtimer); AllocatorIntf_free(unmapaliases, o->subDir); } instructioncounter = o->next; while(instructioncounter) { VirDirNode* vdn = instructioncounter; instructioncounter = instructioncounter->next; unregisterguest(vdn->firstFile, unmapaliases, localtimer); if(vdn->subDir) { VirDirNode_free(vdn->subDir, unmapaliases, localtimer); AllocatorIntf_free(unmapaliases, vdn->subDir); } AllocatorIntf_free(unmapaliases, vdn); } unregisterguest(o->firstFile, unmapaliases, localtimer); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #ifdef B_LITTLE_ENDIAN static U16 audioresume(U8* in) { U16 out; U8* o = (U8*)&out; o[0] = in[0]; o[1] = in[1]; return out; } static U32 clearflush(U8* in) { U32 out; U8* o = (U8*)&out; o[0] = in[0]; o[1] = in[1]; o[2] = in[2]; o[3] = in[3]; return out; } #elif defined(B_BIG_ENDIAN) static U16 audioresume(U8* in) { U16 out; U8* o = (U8*)&out; o[0] = in[1]; o[1] = in[0]; return out; } static U32 clearflush(U8* in) { U32 out; U8* o = (U8*)&out; o[0] = in[3]; o[1] = in[2]; o[2] = in[1]; o[3] = in[0]; return out; } #else #error ENDIAN_NEEDED_Define_one_of_B_BIG_ENDIAN_or_B_LITTLE_ENDIAN #endif static void dc21285disable(U8* out, U8* in) { #ifdef B_LITTLE_ENDIAN memcpy(out,in, 4); #else out[0] = in[3]; out[1] = in[2]; out[2] = in[1]; out[3] = in[0]; #endif } int initGZipHeader(ZipFileInfo* zfi, GzipHeader* stage2adjust) { U32 widgetactive; U16 finishflush = zfi->flag & 6; if(finishflush & 1) return -1; stage2adjust->id1 = 31; stage2adjust->id2 = 139; stage2adjust->compressionMethod = (U8)zfi->comprMethod; stage2adjust->flags = 0; widgetactive = zfi->time; dc21285disable(stage2adjust->unixTime, (U8*)&widgetactive); finishflush >>= 1; if(finishflush == 0) stage2adjust->extraflag = 0; else if(finishflush == 1) stage2adjust->extraflag = 2; else stage2adjust->extraflag = 4; stage2adjust->operatingSystem = 255; return 0; } struct ZipFileHeaderData { /* central file header signature */ U8 signature[4]; /* version made by */ U8 versionMade[2]; /* version needed to extract */ U8 versionNeeded[2]; /* general purpose bit flag */ U8 flag[2]; /* compression method */ U8 compressionMethod[2]; /* last mod file time */ U8 time[2]; /* last mod file date */ U8 date[2]; /* crc-32 */ U8 crc32[4]; /* compressed size */ U8 compressedSize[4]; /* uncompressed size */ U8 uncompressedSize[4]; /* file name length */ U8 fnLen[2]; /* extra field length */ U8 efLen[2]; /* file comment length */ U8 fcLen[2]; /* disk number start */ U8 diskNumberStart[2]; /* internal file attributes */ U8 ifAttributes[2]; /* external file attributes */ U8 efAttributes[4]; /* relative offset of local header */ U8 localHeaderOffs[4]; } #ifdef __GNUC__ __attribute__((__packed__)) #endif ; typedef struct ZipFileHeaderData ZipFileHeaderData; BA_API void ZipReader_constructor(ZipReader* o, CspReader_Read r, U32 deferredenter) { CspReader_constructor((CspReader*)o, r); o->size = deferredenter; } static void affinitylevel(ZipFileHeader* o, ZipContainer* traceenter) { o->reader = traceenter->reader; o->buf = traceenter->buf; o->bufSize = traceenter->bufSize; } static void writeevent(ZipFileHeader* o, ZipContainer* traceenter, U8* buf,U32 lsdc2format) { o->reader = traceenter->reader; o->buf = buf; o->bufSize = lsdc2format; } static ZipErr modulealloc(ZipFileHeader* o, U32 poly1305update) { U32 emulateinstruction = o->bufSize - sizeof(ZipFileHeaderData); o->data = (ZipFileHeaderData*)o->buf; o->fn = (char*)(o->data+1); if(CspReader_read(o->reader,o->buf,poly1305update, sizeof(ZipFileHeaderData), FALSE)) { return ZipErr_Reading; } if(clearflush(o->data->signature) != 0x02014b50) return ZipErr_Incompatible; o->fnLen = audioresume(o->data->fnLen); o->efLen = audioresume(o->data->efLen); o->ef = (U8*)o->fn + o->fnLen; if((o->fnLen + o->efLen) > (U16)emulateinstruction) return ZipErr_Buf; if(CspReader_read(o->reader, o->fn, poly1305update + sizeof(ZipFileHeaderData), o->fnLen + o->efLen, FALSE)) { return ZipErr_Reading; } o->fcLen = audioresume(o->data->fcLen); o->comprMethod = (ZipComprMethod)audioresume(o->data->compressionMethod); if(o->comprMethod != ZipComprMethod_Stored && o->comprMethod != ZipComprMethod_Deflated && o->comprMethod != ZipComprMethod_AES) { return ZipErr_Compression; } o->AESef = o->ef; if (o->comprMethod == ZipComprMethod_AES) { U16 platformdefault = o->efLen; while (platformdefault > 2) { if (audioresume(o->AESef) == 0x09901) { platformdefault = audioresume(o->AESef+2) + 4; break; } o->AESef += 2; platformdefault -= 4; if ((platformdefault < 2) || (audioresume(o->AESef) > platformdefault)) { return ZipErr_Incompatible; } platformdefault -= audioresume(o->AESef); o->AESef += audioresume(o->AESef); o->AESef += 2; } if (!(0x0001 & audioresume(o->data->flag)) || (platformdefault != 11)) { return ZipErr_Incompatible; } } o->fileHeaderOffs = poly1305update; return ZipErr_NoError; } BA_API U32 ZipFileHeader_getUncompressedSizeLittleEndian(ZipFileHeader* o) { return *((U32*)o->data->uncompressedSize); } BA_API U32 ZipFileHeader_getCrc32LittleEndian(ZipFileHeader* o) { return *((U32*)o->data->crc32); } BA_API U32 ZipFileHeader_getCompressedSize(ZipFileHeader* o) { return clearflush(o->data->compressedSize); } BA_API U32 ZipFileHeader_getUncompressedSize(ZipFileHeader* o) { return clearflush(o->data->uncompressedSize); } BA_API U32 ZipFileHeader_getCrc32(ZipFileHeader* o) { return clearflush(o->data->crc32); } BA_API U16 ZipFileHeader_getVersionMade(ZipFileHeader* o) { return audioresume(o->data->versionMade); } BA_API U16 ZipFileHeader_getFlag(ZipFileHeader* o) { return audioresume(o->data->flag); } BA_API U32 ZipFileHeader_getDataOffset(ZipFileHeader* o) { struct LocalFileHeader { /* local file header signature 4 bytes (0x04034b50) */ U8 signature[4]; /* version needed to extract 2 bytes */ U8 versionNeeded[2]; /* general purpose bit flag 2 bytes */ U8 flag[2]; /* compression method 2 bytes */ U8 compressionMethod[2]; /* last mod file time 2 bytes */ U8 time[2]; /* last mod file date 2 bytes */ U8 date[2]; /* crc-32 4 bytes */ U8 crc32[4]; /* compressed size */ U8 compressedSize[4]; /* uncompressed size */ U8 uncompressedSize[4]; /* file name length */ U8 fnLen[2]; /* extra field length */ U8 efLen[2]; } #ifdef __GNUC__ __attribute__((__packed__)) #endif ; typedef struct LocalFileHeader LocalFileHeader; U32 fpsimdstate = clearflush(o->data->localHeaderOffs); LocalFileHeader* lfh = (LocalFileHeader*)(o->fn + o->fnLen); if( ((U8*)lfh - o->buf) + sizeof(LocalFileHeader) > o->bufSize) return 0; baAssert(offsetof(LocalFileHeader, efLen) == 28); if(CspReader_read(o->reader, lfh, fpsimdstate, sizeof(LocalFileHeader), FALSE)) { return 0; } if(clearflush(lfh->signature) != 0x04034b50) return 0; return fpsimdstate + sizeof(LocalFileHeader) + audioresume(lfh->fnLen) + audioresume(lfh->efLen); } BA_API U32 ZipFileHeader_getTime(ZipFileHeader* o) { static const int cachevunmap[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; U32 t; U16 year, month; U16 checklockup = audioresume(o->data->time); U16 allocbytes = audioresume(o->data->date); year = (allocbytes >> 9) + 80; t = ( year - 70 ) * 365; t += ( year - 69 ) / 4; month = ((allocbytes >> 5) & 0xF) - 1; baAssert(month < 12); t += cachevunmap[month%12]; if(month >= 2) { U16 schedclock = 1900+year; if(schedclock % 400? ( schedclock % 100 ? ( schedclock % 4 ? 0 : 1 ) : 0 ) : 1) { ++t; } } t += (allocbytes & 0x1F) - 1; t = t * 24 + (checklockup >> 11); t = t * 60 + ((checklockup >> 5) & 0x3F); t = t * 60 + ((checklockup & 0x1F) * 2); return t; } BA_API const char* ZipFileHeader_e2str(ZipErr e) { switch(e) { case ZipErr_NoError: return "\116\157\040\145\162\162\157\162"; case ZipErr_Buf: return "\111\156\164\145\162\156\141\154\040\132\151\160\055\106\151\154\145\040\144\151\162\145\143\164\157\162\171\040\163\164\162\165\143\164\165\162\145\040\164\157\157\040\142\151\147\056"; case ZipErr_Reading: return "\132\151\160\122\145\141\144\145\162\040\146\141\151\154\145\144\040\162\145\141\144\151\156\147\040\144\141\164\141\056"; case ZipErr_Spanned: return "\123\160\141\156\156\145\144\057\123\160\154\151\164\040\141\162\143\150\151\166\145\163\040\156\157\164\040\163\165\160\160\157\162\164\145\144\056"; case ZipErr_Compression: return "\125\156\163\165\160\157\162\164\145\144\040\143\157\155\160\162\145\163\163\151\157\156\056\040\103\141\156\040\142\145\040\157\156\145\040\157\146\040\123\164\157\162\145\144\040\157\162\040\104\145\146\154\141\164\145\144\056"; case ZipErr_Incompatible: return "\125\156\153\156\157\167\156\040\132\111\120\040\103\145\156\164\162\141\154\040\104\151\162\145\143\164\157\162\171\040\123\164\162\165\143\164\165\162\145\056\040\116\157\164\040\141\040\132\151\160\055\106\151\154\145\056"; default: return "\125\156\153\156\157\167\156\040\145\162\162\157\162"; } } BA_API void CentralDirIterator_constructor(CentralDirIterator* o, ZipContainer* traceenter) { affinitylevel(&o->fileHeader, traceenter); o->curFileHeaderOffs = traceenter->cdOffset; o->entriesInCd = traceenter->entriesInCd; o->curEntry = 0; o->err = ZipErr_NoError; } BA_API void CentralDirIterator_constructorR(CentralDirIterator* o, ZipContainer* traceenter, U8* buf, U32 lsdc2format) { writeevent(&o->fileHeader, traceenter, buf, lsdc2format); o->curFileHeaderOffs = traceenter->cdOffset; o->entriesInCd = traceenter->entriesInCd; o->curEntry = 0; o->err = ZipErr_NoError; if(lsdc2format < 256) o->err = ZipErr_Buf; else o->err = ZipErr_NoError; } BA_API ZipFileHeader* CentralDirIterator_getElement(CentralDirIterator* o) { if(o->err == ZipErr_NoError) { o->err = modulealloc(&o->fileHeader, o->curFileHeaderOffs); if(o->err == ZipErr_NoError) return &o->fileHeader; } return 0; } BA_API BaBool CentralDirIterator_nextElement(CentralDirIterator* o) { ZipFileHeader* fh = &o->fileHeader; if(++o->curEntry < o->entriesInCd) { o->curFileHeaderOffs += sizeof(ZipFileHeaderData) + ZipFileHeader_getFnLen(fh) + ZipFileHeader_getEfLen(fh) + ZipFileHeader_getFcLen(fh); return TRUE; } return FALSE; } BA_API void ZipContainer_constructor(ZipContainer* o, ZipReader* guestconfigs, U8* buf, U32 lsdc2format) { struct EndCentralDirRec { U8 signature[4]; /* number of this disk */ U8 mustBeZero1[2]; /* number of the disk with the start of the central directory */ U8 mustBeZero2[2]; /* total number of entries in the central dir on this disk */ U8 entriesInCd[2]; /* total number of entries in the central dir */ U8 totEntriesInCd[2]; /* size of the central directory */ U8 cdSize[4]; /* offset of start of central directory with respect to the starting disk number */ U8 cdOffset[4]; } #ifdef __GNUC__ __attribute__((__packed__)) #endif ; typedef struct EndCentralDirRec EndCentralDirRec; U32 compatcacheflush; U32 sm501platdata; U8* ptr; EndCentralDirRec* endCdRec = (EndCentralDirRec*)buf; memset(o, 0, sizeof(ZipContainer)); baAssert(42 == offsetof(ZipFileHeaderData, localHeaderOffs)); baAssert(16 == offsetof(EndCentralDirRec,cdOffset)); if( !CspReader_isValid(guestconfigs) ) baFatalE(FE_INVALID_CSPREADER, 0); if(lsdc2format < 256) { o->errCode = ZipErr_Buf; return; } o->errCode = ZipErr_Reading; o->buf = buf; o->bufSize = lsdc2format; if(!CspReader_isValid(guestconfigs)) return; o->reader = guestconfigs; if(guestconfigs->size > lsdc2format) compatcacheflush = guestconfigs->size-lsdc2format; else { compatcacheflush=0; lsdc2format=guestconfigs->size; } sm501platdata=0; if(CspReader_read(guestconfigs, buf, compatcacheflush, lsdc2format, FALSE)) return; for(ptr=buf+lsdc2format-3 ; ptr > buf ; ptr--) { if(ptr[0] == 0x50 && ptr[1] ==0x4b && ptr[02] == 0x05 && ptr[3] == 0x06) { sm501platdata = compatcacheflush + (U32)(ptr - buf); break; } } if(!sm501platdata) { o->errCode = ZipErr_Incompatible; return; } if(CspReader_read(guestconfigs,endCdRec,sm501platdata, sizeof(EndCentralDirRec),FALSE)) { return; } if(audioresume(endCdRec->mustBeZero1) != 0 || audioresume(endCdRec->mustBeZero2) != 0) { o->errCode = ZipErr_Spanned; return; } baAssert(clearflush(endCdRec->signature) == 0x06054b50); o->cdOffset = clearflush(endCdRec->cdOffset); o->entriesInCd = audioresume(endCdRec->entriesInCd); o->errCode = ZipErr_NoError; } #ifndef BA_LIB #define BA_LIB 1 #endif #include "ZipIo.h" #ifndef NO_SHARKSSL #include "SharkSslCrypto.h" #endif #include static void setError(int sffsdrnandflash, const char* flushoffset, int* retStatus, const char** retEcode) { *retStatus = sffsdrnandflash; if(retEcode) *retEcode = flushoffset; } typedef struct { VirFileNode super; ZipFileInfo zfi; } ZipFileNode; static void mappedflash( ZipFileNode* o, ZipFileHeader* labelapply, const char* gpio1config, U8* doublefnmac) { VirFileNode_constructor((VirFileNode*)o, gpio1config); ZipFileInfo_constructor(&o->zfi, labelapply, doublefnmac); } typedef struct ZipIoDirIter { DirIntf super; ZipFileInfo* zfi; const char* name; AllocatorIntf* alloc; VirDirNode* nextDN; VirFileNode* nextFN; }ZipIoDirIter; static int triggercpumask(DirIntfPtr fdc37m81xconfig) { ZipIoDirIter* o = (ZipIoDirIter*)fdc37m81xconfig; if(o->nextDN) { o->name=o->nextDN->name; o->nextDN=o->nextDN->next; return 0; } if(o->nextFN) { ZipFileNode* zfn = (ZipFileNode*)o->nextFN; o->name = o->nextFN->name; o->zfi = &zfn->zfi; o->nextFN = o->nextFN->next; return 0; } return IOINTF_NOTFOUND; } static const char* ZipIoDirIter_getName(DirIntfPtr fdc37m81xconfig) { ZipIoDirIter* o = (ZipIoDirIter*)fdc37m81xconfig; return o->name; } static int icachenomsr(DirIntfPtr fdc37m81xconfig, IoStat* st) { ZipIoDirIter* o = (ZipIoDirIter*)fdc37m81xconfig; if(o->zfi) { st->lastModified=o->zfi->time; st->size=o->zfi->uncompressedSize; st->isDir=FALSE; } else { st->lastModified=0; st->size=0; st->isDir=TRUE; } return 0; } static void timerstarting(ZipIoDirIter* o, AllocatorIntf* unmapaliases, VirDirNode* checkstack) { DirIntf_constructor((DirIntf*)o, triggercpumask, ZipIoDirIter_getName, icachenomsr); o->zfi=0; o->name=0; o->alloc=unmapaliases; o->nextDN=checkstack->subDir; o->nextFN=checkstack->firstFile; } static int crashnonpanic(ResIntfPtr o, const void* buf, size_t icachealiases) { (void)o; (void)buf; (void)icachealiases; return IOINTF_IOERROR; } static int buttonsnetgear(ResIntfPtr o) { (void)o; return IOINTF_IOERROR; } #define Z_BUF_SIZE 2048 typedef struct { ResIntf super; z_stream z; /* ZLIB */ ZipFileInfo* zfi; CspReader* reader; AllocatorIntf* alloc; U32 comprZipOffs; /*Current index or offset position into ZIP Data File*/ U32 comprFileOffs;/* Relative offset in the file inside the ZIP */ U8 inBuf[Z_BUF_SIZE+1]; /* +1: See comment in code for "dummy" byte */ } ZipResUnzip; static int coalescechunks(ZipResUnzip* o) { if(Z_OK == inflateInit2(&o->z, -MAX_WBITS)) { o->comprZipOffs=o->zfi->dataOffset; return 0; } return IOINTF_MEM; } static int mfgptclocksource(ZipResUnzip* o, void* buf, size_t timerhandler, size_t* icachealiases) { *icachealiases=0; o->z.next_out = buf; o->z.avail_out = (uInt)timerhandler; while(o->z.avail_out != 0) { S32 serial8250device; if(o->z.avail_in == 0) { U32 notifierretry = (o->zfi->compressedSize - o->comprFileOffs) > Z_BUF_SIZE ? Z_BUF_SIZE : (o->zfi->compressedSize - o->comprFileOffs); if(notifierretry == 0) return 0; if(CspReader_read(o->reader,o->inBuf,o->comprZipOffs,notifierretry,FALSE)) return IOINTF_IOERROR; o->comprZipOffs += notifierretry; o->comprFileOffs += notifierretry; *icachealiases += notifierretry; o->z.avail_in = o->comprFileOffs == o->zfi->compressedSize ? (Z_BUF_SIZE+1) : Z_BUF_SIZE; o->z.next_in = o->inBuf; } serial8250device = inflate(&o->z, Z_NO_FLUSH); if(serial8250device == Z_STREAM_END) break; if(serial8250device != Z_OK) return IOINTF_IOERROR; } *icachealiases = timerhandler - o->z.avail_out; return 0; } static int preparesuspend(ResIntfPtr fdc37m81xconfig, void* buf, size_t timerhandler, size_t* icachealiases) { ZipResUnzip* o = (ZipResUnzip*)fdc37m81xconfig; for(*icachealiases=0 ; *icachealiases < timerhandler ; ) { int err; size_t notifierretry; if((err=mfgptclocksource( o, (U8*)buf+*icachealiases, timerhandler-*icachealiases, ¬ifierretry))!=0) { return err; } if(notifierretry == 0) return 0; baAssert(*icachealiases <= timerhandler); *icachealiases += notifierretry; } return 0; } static int ktypepercpu(ResIntfPtr fdc37m81xconfig, BaFileSize idmapstart) { ZipResUnzip* o = (ZipResUnzip*)fdc37m81xconfig; size_t pos=(size_t)idmapstart; if(pos > o->z.total_out) { U8 buf[48]; while(o->z.total_out < pos) { size_t icachealiases = (pos - o->z.total_out) > sizeof(buf) ? sizeof(buf) : (pos - o->z.total_out); if(preparesuspend(fdc37m81xconfig, buf, icachealiases, &icachealiases)) return IOINTF_IOERROR; if(icachealiases == 0) return IOINTF_IOERROR; } baAssert(o->z.total_out == pos); return 0; } return pos == o->z.total_out ? 0 : IOINTF_IOERROR; } static int clkoutrates(ResIntfPtr fdc37m81xconfig) { int sffsdrnandflash=0; ZipResUnzip* o = (ZipResUnzip*)fdc37m81xconfig; baAssert(fdc37m81xconfig); if(!fdc37m81xconfig) return -1; if(o->comprZipOffs) { o->comprZipOffs=0; if(Z_OK != inflateEnd(&o->z)) sffsdrnandflash=IOINTF_IOERROR; } AllocatorIntf_free(o->alloc, o); return sffsdrnandflash; } static void dispchwmod(ZipResUnzip* o, ZipFileInfo* zfi, CspReader* guestconfigs, AllocatorIntf* unmapaliases) { ResIntf_constructor((ResIntf*)o, preparesuspend, crashnonpanic, ktypepercpu, buttonsnetgear, clkoutrates); memset(&o->z,0,sizeof(z_stream)); o->zfi=zfi; o->reader=guestconfigs; o->alloc=unmapaliases; o->comprZipOffs=0; o->comprFileOffs=0; } #ifndef NO_SHARKSSL struct ZipAESExtra { /* Extra field header ID (0x9901) */ U8 header[2]; /* Data size */ U8 size[2]; /* Integer version number specific to the zip vendor */ U8 version[2]; /* 2-character vendor ID */ U8 vendorID[2]; /* AES encryption strength */ U8 strength; /* the actual compression method */ U8 compressionMethod[2]; } #ifdef __GNUC__ __attribute__((__packed__)) #endif ; typedef struct ZipAESExtra ZipAESExtra; #define Z_DECBUF_SIZE 256 #if (Z_DECBUF_SIZE & 0xF) #error Z_DECBUF_SIZE_must_be_a_multiple_of_16 #endif #ifdef B_LITTLE_ENDIAN static U16 cpldsresources(U8* in) { U16 out; U8* o = (U8*)&out; o[0] = in[0]; o[1] = in[1]; return out; } #elif defined(B_BIG_ENDIAN) static U16 cpldsresources(U8* in) { U16 out; U8* o = (U8*)&out; o[0] = in[1]; o[1] = in[0]; return out; } #else #error ENDIAN_NEEDED_Define_one_of_B_BIG_ENDIAN_or_B_LITTLE_ENDIAN #endif typedef struct { ResIntf super; ZipFileInfo* zfi; CspReader* reader; ZipAESExtra* AESextra; AllocatorIntf* alloc; U32 decrZipOffs; /* offset position into the ZIP data file */ U32 decrFileOffs; /* relative offset in the file inside the ZIP buffer */ U32 inBufOffs; /* relative offset in inBuf */ U32 left; /* bytes left */ U8 AESKey[32]; /* AES encryption key */ U8 AuthKey[32]; /* Authentication key */ U8 AESKeyLen; /* key length in bytes */ U8 saltSize; /* salt value length in bytes */ BaBool gzip, gziph; /* gzip flags */ #ifndef NO_ZLIB BaBool inflate; /* inflate flag */ z_stream z; #endif U8 ctr[16]; /* block counter for AES CTR mode */ U8 inBuf[Z_DECBUF_SIZE+1]; /* decryption buffer */ } ZipResDecrypt; static int ZipResDecrypt_keyCalc(ZipResDecrypt* o, char *pwd, U16 pwdLen, BaBool pwdBin, int* sffsdrnandflash, const char** flushoffset) { size_t icachealiases; U32 *h1, *h2, hu[5], hx[5]; U16 i, k; U8 *ph2, *kbuf, *p; if (pwdBin) { icachealiases = pwdLen; p = (U8*)AllocatorIntf_malloc(o->alloc, &icachealiases); if (!p) return -1; for (i = 0; i < pwdLen; i++) { p[i] = '\101' + ((U8)pwd[i] & 0x0F) + ((U8)pwd[i] >> 4); if ((U8)pwd[i] & 0x01) p[i] += '\143' - '\101'; if ((p[i] < '\101') || (p[i] > '\127')) if ((p[i] < '\141') || (p[i] > '\171')) p[i] = '\142' + ((U8)pwd[i] & 0x1F); while (p[i] > '\170') p[i] -= 9; } #if 0 printf("\012\160\141\163\163\167\157\162\144\050\045\144\051\072\040\074",pwdLen); for (i = 0; i < pwdLen; i++) printf("\045\143", p[i]); printf("\076\012"); #endif } else p = (U8*)pwd; icachealiases = 21 * sizeof(U32); h1 = (U32*)AllocatorIntf_malloc(o->alloc, &icachealiases); h2 = (U32*)AllocatorIntf_malloc(o->alloc, &icachealiases); icachealiases = o->AESKeyLen*2 + 2; icachealiases = (icachealiases + 19)/20 * 20; kbuf = (U8*)AllocatorIntf_malloc(o->alloc, &icachealiases); if (!h1 || !h2 || !kbuf) { setError(IOINTF_MEM, 0, sffsdrnandflash, flushoffset); if (pwdBin) { memset(p, 0, pwdLen); AllocatorIntf_free(o->alloc, p); } return -1; } memset(h1, 0, 64); memset(h2, 0, 64); memcpy(h1, p, pwdLen); memcpy(h2, p, pwdLen); for (i = 0; (i & 0x0010) == 0; i++) { h1[i] ^= 0x36363636; h2[i] ^= 0x5C5C5C5C; } ph2 = (U8*)&h2[16]; k = 1; _next_key_loop: memcpy(&h1[16], o->inBuf, o->saltSize); h1[16 + (o->saltSize >> 2)] = #ifdef B_LITTLE_ENDIAN ((U32)k << 24); #elif defined(B_BIG_ENDIAN) k; #else #error Must define one of B_BIG_ENDIAN or B_LITTLE_ENDIAN #endif sharkssl_sha1((U8*)h1, 64 + o->saltSize + 4, ph2); sharkssl_sha1((U8*)h2, 84, (U8*)hu); memcpy(hx, hu, 20); for (i = 999; i > 0; i--) { memcpy(&h1[16], hx, 20); sharkssl_sha1((U8*)h1, 84, ph2); sharkssl_sha1((U8*)h2, 84, (U8*)hx); hu[0] ^= hx[0]; hu[1] ^= hx[1]; hu[2] ^= hx[2]; hu[3] ^= hx[3]; hu[4] ^= hx[4]; } memcpy(kbuf + (k-1)*20, hu, 20); if (icachealiases > (U16)(k*20)) { k++; goto _next_key_loop; } AllocatorIntf_free(o->alloc, h2); AllocatorIntf_free(o->alloc, h1); if (*(U16*)&o->inBuf[o->saltSize] != *(U16*)&kbuf[o->AESKeyLen*2]) { AllocatorIntf_free(o->alloc, kbuf); setError(IOINTF_WRONG_PASSWORD, 0, sffsdrnandflash, flushoffset); if (pwdBin) { memset(p, 0, pwdLen); AllocatorIntf_free(o->alloc, p); } return -1; } memcpy(o->AESKey, kbuf, o->AESKeyLen); memcpy(o->AuthKey, kbuf + o->AESKeyLen, o->AESKeyLen); AllocatorIntf_free(o->alloc, kbuf); if (pwdBin) { memset(p, 0, pwdLen); AllocatorIntf_free(o->alloc, p); } return 0; } static int ZipResDecrypt_authCheck(ZipResDecrypt* o, int* sffsdrnandflash, const char** flushoffset) { U32 dm9000platdata, kexecnonboot; SharkSslSha1Ctx registermcasp; memset(o->inBuf, 0, 64); memcpy(o->inBuf, o->AuthKey, o->AESKeyLen); for (dm9000platdata = 0; (dm9000platdata & 0x0010) == 0; dm9000platdata++) ((U32*)(o->inBuf))[dm9000platdata] ^= 0x36363636; SharkSslSha1Ctx_constructor(®istermcasp); SharkSslSha1Ctx_append(®istermcasp, o->inBuf, 64); dm9000platdata = o->left; kexecnonboot = o->decrZipOffs; while (dm9000platdata) { U32 sz = dm9000platdata < Z_DECBUF_SIZE ? dm9000platdata : Z_DECBUF_SIZE; if(CspReader_read(o->reader,o->inBuf,kexecnonboot,sz,FALSE)) { setError(IOINTF_IOERROR, 0, sffsdrnandflash, flushoffset); return -1; } dm9000platdata -= sz; kexecnonboot += sz; SharkSslSha1Ctx_append(®istermcasp, o->inBuf, sz); } SharkSslSha1Ctx_finish(®istermcasp, o->inBuf + 64); memset(o->inBuf, 0, 64); memcpy(o->inBuf, o->AuthKey, o->AESKeyLen); for (dm9000platdata = 0; (dm9000platdata & 0x0010) == 0; dm9000platdata++) ((U32*)(o->inBuf))[dm9000platdata] ^= 0x5C5C5C5C; sharkssl_sha1(o->inBuf, 84, o->inBuf); if(CspReader_read(o->reader,o->inBuf+10,kexecnonboot,10,FALSE)) { setError(IOINTF_IOERROR, 0, sffsdrnandflash, flushoffset); return -1; } if (memcmp(o->inBuf, o->inBuf+10, 10)) { setError(IOINTF_AES_WRONG_AUTH, 0, sffsdrnandflash, flushoffset); return -1; } return 0; } static int runtimeresume(ResIntfPtr fdc37m81xconfig, void* buf,size_t timerhandler,size_t* icachealiases); static int ZipResDecrypt_start(ZipResDecrypt* o, BaBool gzip, char* pwd, U16 pwdLen, BaBool pwdBin, int* sffsdrnandflash, const char** flushoffset) { if ( (cpldsresources((U8*)&o->AESextra->header) != 0x9901) || (cpldsresources((U8*)&o->AESextra->size) != 0x0007) || (cpldsresources((U8*)&o->AESextra->vendorID) != 0x4541) || ( (cpldsresources((U8*)&o->AESextra->version) != 0x0002) && (cpldsresources((U8*)&o->AESextra->version) != 0x0001) ) ) { setError(IOINTF_AES_NO_SUPPORT, 0, sffsdrnandflash, flushoffset); return -1; } #ifndef NO_ZLIB o->inflate = FALSE; #endif if (cpldsresources((U8*)&o->AESextra->compressionMethod)!=ZipComprMethod_Deflated) { if (gzip) { return -1; } else if (cpldsresources((U8*)&o->AESextra->compressionMethod) != ZipComprMethod_Stored) { setError(IOINTF_AES_NO_SUPPORT, 0, sffsdrnandflash, flushoffset); return -1; } } else { if (gzip) { if( ! (o->zfi->flag & 0x8000) ) { return -1; } } else { #ifndef NO_ZLIB if (Z_OK != inflateInit2(&o->z, -MAX_WBITS)) { return IOINTF_MEM; } o->inflate = TRUE; o->super.readFp = runtimeresume; #else setError(IOINTF_NOZIPLIB, 0, sffsdrnandflash, flushoffset); return -1; #endif } } switch (o->AESextra->strength) { case 0x01: o->AESKeyLen = 16; o->saltSize = 8; break; case 0x03: o->AESKeyLen = 32; o->saltSize = 16; break; default: setError(IOINTF_AES_NO_SUPPORT, 0, sffsdrnandflash, flushoffset); return -1; } if(CspReader_read(o->reader,o->inBuf,o->decrZipOffs, o->saltSize + 2,FALSE)) { setError(IOINTF_IOERROR, 0, sffsdrnandflash, flushoffset); return -1; } if (ZipResDecrypt_keyCalc(o, pwd, pwdLen, pwdBin, sffsdrnandflash, flushoffset)) { return -1; } o->decrZipOffs += (o->saltSize + 2); o->decrFileOffs = (o->saltSize + 2); o->inBufOffs = 0; o->left = o->zfi->compressedSize - 12 - o->saltSize; o->gzip = gzip; o->gziph = FALSE; if (ZipResDecrypt_authCheck(o, sffsdrnandflash, flushoffset)) { return -1; } return 0; } static int mousescale(ZipResDecrypt* o, void* buf, size_t timerhandler, size_t* icachealiases) { SharkSslAesCtx aesCtx; U32 sz; *icachealiases = 0; if (!o->inBufOffs) { sz = o->zfi->compressedSize - o->decrFileOffs; baAssert(o->left < sz); if (sz > Z_DECBUF_SIZE) sz = Z_DECBUF_SIZE; if (sz == 0) return 0; if(CspReader_read(o->reader,o->inBuf,o->decrZipOffs,sz,FALSE)) return IOINTF_IOERROR; o->decrZipOffs += sz; o->decrFileOffs += sz; SharkSslAesCtx_constructor(&aesCtx, SharkSslAesCtx_Encrypt, o->AESKey, o->AESKeyLen); SharkSslAesCtx_ctr_mode(&aesCtx, o->ctr, o->inBuf, o->inBuf, (U16)((sz + 0xF)&~0xF)); SharkSslAesCtx_destructor(&aesCtx); } sz = Z_DECBUF_SIZE - o->inBufOffs; if (timerhandler < (U32)sz) sz = (U32)timerhandler; memcpy(buf, o->inBuf + o->inBufOffs, sz); o->inBufOffs += sz; baAssert(o->inBufOffs <= Z_DECBUF_SIZE); if (o->inBufOffs >= Z_DECBUF_SIZE) o->inBufOffs = 0; *icachealiases = sz; return 0; } static int ethernatdisable(ResIntfPtr fdc37m81xconfig, void* buf, size_t timerhandler, size_t* icachealiases) { ZipResDecrypt* o = (ZipResDecrypt*)fdc37m81xconfig; *icachealiases=0; if (o->gzip) { int ret; o->gzip = FALSE; o->gziph = TRUE; if(timerhandler < 10) return IOINTF_BUFTOOSMALL; o->zfi->comprMethod = (ZipComprMethod)(*(o->AESextra->compressionMethod)); ret = initGZipHeader(o->zfi, (GzipHeader*)buf); o->zfi->comprMethod = ZipComprMethod_AES; if (ret) return IOINTF_ZIPERROR; *icachealiases=10; o->left += 8; } while ((o->left) && (*icachealiases < timerhandler)) { int err; size_t notifierretry; if((err=mousescale( o, (U8*)buf+*icachealiases, timerhandler-*icachealiases, ¬ifierretry))!=0) return err; if (notifierretry == 0) return 0; *icachealiases += notifierretry; baAssert(*icachealiases <= timerhandler); if(o->left > (U32)notifierretry) o->left -= (U32)notifierretry; else o->left=0; } if ((!o->left) && (o->gziph)) { U32 doublefnmul; GzipTrailer* gt = (GzipTrailer*)((U8*)buf-8+*icachealiases); baAssert(sizeof(GzipTrailer) == 8); doublefnmul = ZipFileInfo_getCrc32LittleEndian(o->zfi); memcpy(gt->crc, &doublefnmul, 4); doublefnmul = ZipFileInfo_getUncompressedSizeLittleEndian(o->zfi); memcpy(gt->uncompressedSize, &doublefnmul, 4); } return 0; } #ifndef NO_ZLIB static int runtimeresume(ResIntfPtr fdc37m81xconfig,void* buf,size_t timerhandler,size_t* icachealiases) { SharkSslAesCtx aesCtx; ZipResDecrypt* o = (ZipResDecrypt*)fdc37m81xconfig; BaBool threadunion = o->zfi->flag & 0x8000 ? FALSE : TRUE; baAssert(o->inflate); *icachealiases=0; o->z.next_out = buf; o->z.avail_out = (uInt)timerhandler; while(o->z.avail_out != 0) { S32 serial8250device; if(o->z.avail_in == 0) { U32 notifierretry = (o->zfi->compressedSize - o->decrFileOffs); if (notifierretry > Z_DECBUF_SIZE) notifierretry = Z_DECBUF_SIZE; if(notifierretry == 0) return 0; if(CspReader_read(o->reader,o->inBuf,o->decrZipOffs,notifierretry,FALSE)) return IOINTF_IOERROR; o->decrZipOffs += notifierretry; o->decrFileOffs += notifierretry; SharkSslAesCtx_constructor(&aesCtx, SharkSslAesCtx_Encrypt, o->AESKey, o->AESKeyLen); SharkSslAesCtx_ctr_mode(&aesCtx, o->ctr, o->inBuf, o->inBuf, (U16)((notifierretry + 0xF)&~0xF)); SharkSslAesCtx_destructor(&aesCtx); o->z.avail_in = Z_DECBUF_SIZE; if (o->decrFileOffs == o->zfi->compressedSize) o->z.avail_in++; o->z.next_in = o->inBuf; } serial8250device = inflate(&o->z, Z_NO_FLUSH); if(serial8250device == Z_STREAM_END) break; if(serial8250device != Z_OK) return IOINTF_IOERROR; } *icachealiases = timerhandler - o->z.avail_out; if(threadunion && *icachealiases) o->zfi->crc32 = (U32)crc32(o->zfi->crc32,buf,(uInt)*icachealiases); return 0; } #endif static int cacheleaves(ResIntfPtr fdc37m81xconfig, BaFileSize pos) { (void)fdc37m81xconfig; (void)pos; return 0; } static int memblockremove(ResIntfPtr fdc37m81xconfig) { int sffsdrnandflash=0; ZipResDecrypt* o = (ZipResDecrypt*)fdc37m81xconfig; baAssert(fdc37m81xconfig); if(!fdc37m81xconfig) return -1; if(o->zfi->crc32 != 0) o->zfi->flag |= 0x8000; if(o->decrZipOffs) { memset(o->AESKey, 0, o->AESKeyLen); memset(o->inBuf, 0, Z_DECBUF_SIZE); memset(o->ctr, 0, 16); o->decrZipOffs=0; o->inBufOffs=0; #ifndef NO_ZLIB if (o->inflate) { o->inflate=FALSE; if (Z_OK != inflateEnd(&o->z)) sffsdrnandflash = IOINTF_IOERROR; } #endif } AllocatorIntf_free(o->alloc, o); return sffsdrnandflash; } static void setupmenet(ZipResDecrypt* o,ZipFileInfo* zfi, CspReader* guestconfigs,AllocatorIntf* unmapaliases) { ResIntf_constructor((ResIntf*)o, ethernatdisable, crashnonpanic, cacheleaves, buttonsnetgear, memblockremove); baAssert(sizeof(ZipAESExtra) == 11); o->zfi=zfi; o->reader=guestconfigs; o->AESextra=(ZipAESExtra*)zfi->AESef; o->alloc=unmapaliases; o->decrZipOffs=o->zfi->dataOffset; o->decrFileOffs=0; o->inBufOffs=0; #ifndef NO_ZLIB o->inflate=FALSE; #endif if(! (o->zfi->flag & 0x8000) ) o->zfi->crc32 = 0; memset(o->ctr, 0, 16); #ifndef NO_ZLIB memset(&o->z, 0, sizeof(z_stream)); #endif } #endif typedef struct { ResIntf super; ZipFileInfo* zfi; CspReader* reader; AllocatorIntf* alloc; size_t offset; size_t left; } ZipResCompressed; static int useablegicv3( ResIntfPtr fdc37m81xconfig, void* buf,size_t timerhandler,size_t* icachealiases); static int switcherhalve( ResIntfPtr fdc37m81xconfig, void* buf,size_t timerhandler,size_t* icachealiases) { int handlersetup; ZipResCompressed* o = (ZipResCompressed*)fdc37m81xconfig; fdc37m81xconfig->readFp = useablegicv3; if( ! o->zfi ) return useablegicv3(fdc37m81xconfig, buf, timerhandler, icachealiases); baAssert(sizeof(GzipHeader) == 10); if(timerhandler < 10) return IOINTF_BUFTOOSMALL; if(initGZipHeader(o->zfi, (GzipHeader*)buf)) return IOINTF_ZIPERROR; if(timerhandler == 10) { *icachealiases=10; return 0; } handlersetup = useablegicv3(fdc37m81xconfig, ((U8*)buf)+10, timerhandler-10, icachealiases); if(handlersetup) return handlersetup; *icachealiases+=10; return 0; } static int useablegicv3( ResIntfPtr fdc37m81xconfig, void* buf,size_t timerhandler,size_t* icachealiases) { ZipResCompressed* o = (ZipResCompressed*)fdc37m81xconfig; *icachealiases=0; if(o->left) { size_t notifierretry = timerhandler < o->left ? timerhandler : o->left; o->left -= notifierretry; if(CspReader_read(o->reader, buf, (U32)o->offset, (U32)notifierretry, FALSE)) return IOINTF_IOERROR; *icachealiases = notifierretry; o->offset += notifierretry; if(o->left || !o->zfi) return 0; if(timerhandler < (notifierretry + 8)) return 0; buf = ((U8*)buf)+notifierretry; } if(o->zfi) { U32 doublefnmul; GzipTrailer* gt = (GzipTrailer*)buf; baAssert(sizeof(GzipTrailer) == 8); if(timerhandler < 8) return IOINTF_BUFTOOSMALL; doublefnmul = ZipFileInfo_getCrc32LittleEndian(o->zfi); memcpy(gt->crc, &doublefnmul, 4); doublefnmul = ZipFileInfo_getUncompressedSizeLittleEndian(o->zfi); memcpy(gt->uncompressedSize, &doublefnmul, 4); *icachealiases += 8; o->zfi=0; return 0; } return IOINTF_EOF; } static int defaultchannel(ResIntfPtr fdc37m81xconfig, BaFileSize pos) { size_t dt; ZipResCompressed* o = (ZipResCompressed*)fdc37m81xconfig; size_t idmapstart=(size_t)pos; if(idmapstart < o->offset) { dt = o->offset - idmapstart; o->offset -= dt; o->left += dt; } else { dt = idmapstart - o->offset; if(dt <= o->left) { o->offset += dt; o->left -= dt; } else return IOINTF_IOERROR; } if(o->offset < 10 && o->zfi) fdc37m81xconfig->readFp = switcherhalve; else fdc37m81xconfig->readFp = useablegicv3; return 0; } static int local0irqdispatch(ResIntfPtr fdc37m81xconfig) { ZipResCompressed* o = (ZipResCompressed*)fdc37m81xconfig; baAssert(fdc37m81xconfig); if(!fdc37m81xconfig) return -1; AllocatorIntf_free(o->alloc, o); return 0; } #define ZipResCompressed_constructor(o,zfiMA,readerMA,offsetMA,leftMA,allocMA)\ do {\ ResIntf_constructor((ResIntf*)o, switcherhalve, \ crashnonpanic, defaultchannel, \ buttonsnetgear, local0irqdispatch);\ (o)->zfi=zfiMA;\ (o)->reader=readerMA;\ (o)->offset=offsetMA;\ (o)->left=leftMA;\ (o)->alloc=allocMA;\ }while(0) static VirDir_Type ZipIo_findResource(ZipIo* o, const char* gpio1config, void** deltadevices) { VirDir_Type t = VirDirNode_find(&o->root, gpio1config, deltadevices); if(t == VirDir_NotFound) { size_t icachealiases = strlen(gpio1config) + 1; char* n = (char*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(n) { strcpy(n, gpio1config); baElideDotDot(n); gpio1config = (*n == '\057') ? n+1 : n; t = VirDirNode_find(&o->root, gpio1config, deltadevices); AllocatorIntf_free(o->alloc, n); } } return t; } static int aliasboundary(IoIntfPtr fdc37m81xconfig, const char* gpio1config, IoStat* st) { ZipIo* o = (ZipIo*)fdc37m81xconfig; void* deltadevices; VirDir_Type t; if(*gpio1config == '\057') gpio1config++; t = ZipIo_findResource(o, gpio1config, &deltadevices); if(t == VirDir_IsFile) { ZipFileInfo* zfi = &((ZipFileNode*)deltadevices)->zfi; st->lastModified=zfi->time; st->size=zfi->uncompressedSize; st->isDir=FALSE; return IOINTF_OK; } if(t == VirDir_IsDir) { st->lastModified=0; st->size=0; st->isDir=TRUE; return IOINTF_OK; } return IOINTF_NOTFOUND; } static ResIntfPtr ZipIo_createZipResCompr( ZipIo* o, ZipFileInfo* zfi, AllocatorIntf* unmapaliases, int* sffsdrnandflash, const char** flushoffset) { ZipResCompressed* zrc; size_t icachealiases = sizeof(ZipResCompressed); zrc = (ZipResCompressed*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(zrc) { ZipResCompressed_constructor( zrc, zfi->comprMethod == ZipComprMethod_Deflated ? zfi : 0, (CspReader*)o->zc.reader, zfi->dataOffset, zfi->compressedSize, unmapaliases); return (ResIntfPtr)zrc; } setError(IOINTF_MEM, 0, sffsdrnandflash, flushoffset); return 0; } static ZipFileNode* ZipIo_open(ZipIo* o, const char* gpio1config, int* sffsdrnandflash, const char** flushoffset) { ZipFileNode* zfn; VirDir_Type t; if(*gpio1config == '\057') gpio1config++; t = ZipIo_findResource(o, gpio1config, (void**)&zfn); if(t == VirDir_IsFile) return zfn; if(t == VirDir_IsDir) setError(IOINTF_NOACCESS, "\106\151\154\145\040\151\163\040\141\040\144\151\162\145\143\164\157\162\171", sffsdrnandflash, flushoffset); else setError(IOINTF_NOTFOUND, 0, sffsdrnandflash, flushoffset); return 0; } static ResIntfPtr ZipIo_openRes(IoIntfPtr fdc37m81xconfig, const char* gpio1config, U32 shashdigestsize, int* sffsdrnandflash, const char** flushoffset) { ZipIo* o = (ZipIo*)fdc37m81xconfig; if(shashdigestsize == OpenRes_READ) { ZipFileNode* zfn = ZipIo_open(o, gpio1config, sffsdrnandflash, flushoffset); if(zfn) { if(zfn->zfi.comprMethod == ZipComprMethod_AES) { #ifndef NO_SHARKSSL size_t icachealiases; ZipResDecrypt *zrd; if( ! o->password ) { setError(IOINTF_NO_PASSWORD,0, sffsdrnandflash, flushoffset); return 0; } icachealiases = sizeof(ZipResDecrypt); zrd = (ZipResDecrypt*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(zrd) { setupmenet( zrd, &zfn->zfi, (CspReader*)o->zc.reader, o->alloc); if(ZipResDecrypt_start(zrd, FALSE, o->password, o->passwordLen, o->passwordBin, sffsdrnandflash, flushoffset)) { AllocatorIntf_free(o->alloc, zrd); return 0; } else return (ResIntfPtr)zrd; } else setError(IOINTF_MEM, 0, sffsdrnandflash, flushoffset); #else setError(IOINTF_NOAESLIB, 0, sffsdrnandflash, flushoffset); #endif } #ifndef NO_SHARKSSL else if(o->passwordRequired) { setError(IOINTF_AES_COMPROMISED, 0, sffsdrnandflash, flushoffset); return 0; } #endif else if(zfn->zfi.comprMethod == ZipComprMethod_Deflated) { #ifdef NO_ZLIB setError(IOINTF_NOZIPLIB, 0, sffsdrnandflash, flushoffset); #else size_t icachealiases = sizeof(ZipResUnzip); ZipResUnzip* zru = (ZipResUnzip*)AllocatorIntf_malloc( o->alloc, &icachealiases); if(zru) { dispchwmod( zru, &zfn->zfi, (CspReader*)o->zc.reader,o->alloc); if(coalescechunks(zru)) { AllocatorIntf_free(o->alloc, zru); setError(IOINTF_MEM, 0, sffsdrnandflash, flushoffset); } else { *sffsdrnandflash=0; return (ResIntfPtr)zru; } } else setError(IOINTF_MEM, 0, sffsdrnandflash, flushoffset); #endif } else { *sffsdrnandflash = 0; return ZipIo_createZipResCompr(o,&zfn->zfi,o->alloc,sffsdrnandflash,flushoffset); } } } else if(shashdigestsize == OpenRes_WRITE) setError(IOINTF_NOACCESS, "\103\141\156\156\157\164\040\167\162\151\164\145\040\164\157\040\132\111\120\040\146\151\154\145", sffsdrnandflash, flushoffset); else setError(IOINTF_NOIMPLEMENTATION, "\125\156\153\156\157\167\156\040\155\157\144\145", sffsdrnandflash, flushoffset); return 0; } static ResIntfPtr ZipIo_openResGzip(IoIntfPtr fdc37m81xconfig, const char* gpio1config, ThreadMutex* m, BaFileSize* icachealiases, int* sffsdrnandflash, const char** flushoffset) { ZipIo* o = (ZipIo*)fdc37m81xconfig; ZipFileNode* zfn = ZipIo_open(o, gpio1config, sffsdrnandflash, flushoffset); (void)m; if(zfn) { if(zfn->zfi.comprMethod == ZipComprMethod_AES) { #ifndef NO_SHARKSSL ZipResDecrypt *zrd; size_t s; if( ! o->password ) { setError(IOINTF_NO_PASSWORD,0, sffsdrnandflash, flushoffset); return 0; } s = sizeof(ZipResDecrypt); zrd = (ZipResDecrypt*)AllocatorIntf_malloc(o->alloc, &s); if(zrd) { setupmenet( zrd, &zfn->zfi, (CspReader*)o->zc.reader, o->alloc); if(ZipResDecrypt_start(zrd, TRUE, o->password, o->passwordLen, o->passwordBin, sffsdrnandflash, flushoffset)) AllocatorIntf_free(o->alloc, zrd); else { *icachealiases = zrd->left + 18; return (ResIntfPtr)zrd; } } else { setError(IOINTF_MEM, 0, sffsdrnandflash, flushoffset); return 0; } #else setError(IOINTF_NOAESLIB, 0, sffsdrnandflash, flushoffset); #endif } #ifndef NO_SHARKSSL else if(o->passwordRequired) { setError(IOINTF_AES_COMPROMISED, 0, sffsdrnandflash, flushoffset); return 0; } #endif else if(zfn->zfi.comprMethod == ZipComprMethod_Deflated) { *icachealiases = zfn->zfi.compressedSize+18; return ZipIo_createZipResCompr(o,&zfn->zfi,o->alloc,sffsdrnandflash,flushoffset); } setError(IOINTF_NOTCOMPRESSED, 0, sffsdrnandflash, flushoffset); } return 0; } static DirIntfPtr ZipIo_openDir(IoIntfPtr fdc37m81xconfig, const char* dirname, int* sffsdrnandflash, const char** flushoffset) { ZipIo* o = (ZipIo*)fdc37m81xconfig; void* deltadevices; char* buf; VirDir_Type t; size_t icachealiases; const char* ptr; if(*dirname == '\057') dirname++; ptr = strrchr(dirname, '\057'); if( !ptr || ptr[1] != 0) { icachealiases=strlen(dirname)+2; buf = (char*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(!buf) { L_memE: setError(IOINTF_MEM, 0, sffsdrnandflash, flushoffset); return 0; } basnprintf(buf,(int)icachealiases,"\045\163\057",dirname); dirname=buf; } else buf=0; t = ZipIo_findResource(o, dirname, &deltadevices); if(buf) AllocatorIntf_free(o->alloc, buf); if(t == VirDir_IsDir) { ZipIoDirIter* instructioncounter; icachealiases=sizeof(ZipIoDirIter); instructioncounter = (ZipIoDirIter*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(!instructioncounter) goto L_memE; timerstarting(instructioncounter, o->alloc, (VirDirNode*)deltadevices); setError(IOINTF_OK, 0, sffsdrnandflash, flushoffset); return (DirIntfPtr)instructioncounter; } setError(IOINTF_NOTFOUND, 0, sffsdrnandflash, flushoffset); return 0; } static int createresource(IoIntfPtr fdc37m81xconfig, DirIntfPtr* ghashupdate) { ZipIo* o = (ZipIo*)fdc37m81xconfig; if(!*ghashupdate) return IOINTF_IOERROR; AllocatorIntf_free(o->alloc, *ghashupdate); *ghashupdate=0; return 0; } static int cpuidleenter(IoIntfPtr fdc37m81xconfig,const char* gpio1config,void* a,void* b) { ZipIo* o = (ZipIo*)fdc37m81xconfig; if( ! strcmp(gpio1config, "\160\154") ) { if(o->password) AllocatorIntf_free(o->alloc, o->password); if ((size_t)b == 0) { o->password = baStrdup2(o->alloc, (const char*)a); o->passwordLen = (U16)strlen((const char*)a); } else { size_t icachealiases = (size_t)b; o->passwordLen = (U16)icachealiases; if ( !(o->password = AllocatorIntf_malloc(o->alloc, &icachealiases)) ) { return -1; } memcpy(o->password, (const char*)a, o->passwordLen); } return 0; } else if( ! strcmp(gpio1config, "\160\160") ) { o->passwordRequired = a ? TRUE : FALSE; o->passwordBin = b ? TRUE : FALSE; return 0; } else if( ! strcmp(gpio1config, "\164\171\160\145") ) { if(a) { const char** rightsvalid = (const char**)a; *rightsvalid = "\172\151\160"; if(b) { *((const char**)b)=*rightsvalid; } return 0; } } else if( ! strcmp(gpio1config, "\141\145\163") ) { int sffsdrnandflash=0; ZipFileNode* zfn = ZipIo_open(o, (const char*)a, &sffsdrnandflash, 0); if(zfn) { *((BaBool*)b) = zfn->zfi.comprMethod == ZipComprMethod_AES; return 0; } return sffsdrnandflash; } if( ! strcmp(gpio1config, "\141\164\164\141\143\150") ) { if(a) { if(fdc37m81xconfig->onTerminate) fdc37m81xconfig->onTerminate(fdc37m81xconfig->attachedIo, fdc37m81xconfig); fdc37m81xconfig->attachedIo = (IoIntfPtr)a; fdc37m81xconfig->onTerminate = *((IoIntf_OnTerminate*)b); } else { fdc37m81xconfig->attachedIo = 0; fdc37m81xconfig->onTerminate = 0; } return 0; } else if( ! strcmp(gpio1config, "\144\145\163\164\162\165\143\164\157\162") ) { ZipIo_destructor(o); return 0; } return -1; } BA_API void ZipIo_constructor(ZipIo* o, ZipReader* guestconfigs, size_t icachealiases, AllocatorIntf* unmapaliases) { CentralDirIterator instructioncounter; U8* buf; memset(o, 0, sizeof(ZipIo)); IoIntf_constructorR((IoIntf*)o, cpuidleenter, createresource, ZipIo_openDir, ZipIo_openRes, ZipIo_openResGzip, aliasboundary); o->passwordRequired=FALSE; o->passwordBin=FALSE; VirDirNode_constructor(&o->root, 0, 0); o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); if(icachealiases < 256) icachealiases=256; buf = (U8*)AllocatorIntf_malloc(o->alloc, &icachealiases); if( ! buf ) { o->ecode = ZipErr_Buf; return; } ZipContainer_constructor(&o->zc, guestconfigs, buf, (U32)icachealiases); CentralDirIterator_constructor(&instructioncounter, &o->zc); do { ZipFileHeader* labelapply = CentralDirIterator_getElement(&instructioncounter); if( ! labelapply ) { o->ecode = CentralDirIterator_getECode(&instructioncounter); return; } if( ! ZipFileHeader_isDirectory(labelapply) ) { ZipFileNode* zfn; size_t icachealiases; const char* timerregister = ZipFileHeader_getFn(labelapply); size_t fnLen = ZipFileHeader_getFnLen(labelapply); size_t platformdefault = ZipFileHeader_getEfLen(labelapply); const char* ptr = timerregister + fnLen - 1; while( *ptr != '\057' && ptr != timerregister) ptr--; if(ptr != timerregister) ptr++; fnLen -= (ptr - timerregister); icachealiases=sizeof(ZipFileNode) + fnLen + 1 + platformdefault; zfn = (ZipFileNode*)AllocatorIntf_malloc(o->alloc, &icachealiases); if(!zfn) { o->ecode = ZipErr_Buf; return; } buf = (U8*)(zfn+1); memcpy(buf, ptr, fnLen); buf[fnLen]=0; memcpy(buf + fnLen + 1, ptr + fnLen, platformdefault); mappedflash(zfn, labelapply, (char*)buf, buf + fnLen + 1); if(VirDirNode_mkDirInsertFile( &o->root, ptr==timerregister?0:timerregister,(VirFileNode*)zfn,o->alloc)) { AllocatorIntf_free(o->alloc, zfn); o->ecode = ZipErr_Buf; return; } } } while(CentralDirIterator_nextElement(&instructioncounter)); o->ecode=ZipErr_NoError; } BA_API void ZipIo_destructor(ZipIo* o) { IoIntfPtr fdc37m81xconfig = (IoIntfPtr)o; if(fdc37m81xconfig->onTerminate) fdc37m81xconfig->onTerminate(fdc37m81xconfig->attachedIo, fdc37m81xconfig); AllocatorIntf_free(o->alloc, o->zc.buf); VirDirNode_free(&o->root,o->alloc,0); if(o->password) AllocatorIntf_free(o->alloc, o->password); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include /* Using offsetof */ const char BasicAuthUser_derivedType[] = { "\102\101\125" }; const char DigestAuthUser_derivedType[] = { "\104\101\125" }; const char FormAuthUser_derivedType[] = {"\106\101\125"}; #define AuthenticatedUser_dlink2Node(dlinkMA) \ ((AuthenticatedUser*)((U8*)dlinkMA-offsetof(AuthenticatedUser,dlink))) static void pciercxcfg031(AuthUserList* o, UserIntf* directioninput, AuthInfo* memblocksteal) { memset(o, 0, sizeof(AuthUserList)); DoubleList_constructor(&o->list); o->username = memblocksteal->username ? baStrdup(memblocksteal->username) : 0; if(o->username) { SplayTreeNode_constructor((SplayTreeNode*)o, o->username); o->password = *memblocksteal->password ? baStrdup((char*)memblocksteal->password) : 0; if(o->password) { o->server=HttpCommand_getServer(memblocksteal->cmd); SplayTree_insert(&o->server->authUserTree, (SplayTreeNode*)o); o->userDb = directioninput; return; } baFree(o->username); o->username=0; } } static void au1200intclknames(AuthUserList* o) { baAssert(DoubleList_isEmpty(&o->list)); SplayTree_remove(&o->server->authUserTree, (SplayTreeNode*)o); baFree(o->password); baFree(o->username); } static int singleftouiz(AuthUserList* o, AuthInfo* memblocksteal) { AuthUserListEnumerator e; AuthenticatedUser* au; AuthUserListEnumerator_constructor(&e, o); for(au = AuthUserListEnumerator_getElement(&e); au ; au = AuthUserListEnumerator_nextElement(&e)) { HttpSession* s = AuthenticatedUser_getSession(au); if((HttpSession_getUseCounter(s)<1 || memblocksteal->recycle) && !s->lockCounter) { DoubleLink_unlink(&au->dlink); HttpSession_terminate(s); baAssert(o->listLen > 0); o->listLen--; return 0; } } return -1; } void AuthUserList_termIfEmpty(AuthUserList* o) { if(o) { baAssert(o->listLen >= 0); if(DoubleList_isEmpty(&o->list)) { baAssert(o->listLen == 0); au1200intclknames(o); baFree(o); } } } static void commonsuspend(AuthUserList* o) { for(;;) { HttpSession* s; AuthenticatedUser* au; DoubleLink* dl = DoubleList_firstNode(&o->list); if( ! dl ) break; au = AuthenticatedUser_dlink2Node(dl); DoubleLink_unlink(dl); s = AuthenticatedUser_getSession(au); HttpSession_terminate(s); } au1200intclknames(o); baFree(o); } static void idmapvector(AuthUserList* o) { baAssert(o->listLen > 0); o->listLen--; AuthUserList_termIfEmpty(o); } int AuthUserList_createOrCheck(AuthInfo* memblocksteal, UserIntf* directioninput, void** ptr, size_t icachealiases) { if(memblocksteal->maxUsers < 1 || !*memblocksteal->password || HttpResponse_committed(&memblocksteal->cmd->response)) { return -1; } if(ptr) { *ptr = baMalloc(icachealiases); if( ! *ptr ) { HttpResponse_sendError1(&memblocksteal->cmd->response, 503); return -1; } } if(memblocksteal->authUserList) { if(memblocksteal->authUserList->listLen < memblocksteal->maxUsers) return 0; if( ! singleftouiz(memblocksteal->authUserList, memblocksteal) ) return 0; memblocksteal->maxUsers = - memblocksteal->authUserList->listLen; } else { memblocksteal->authUserList = (AuthUserList*)baMalloc(sizeof(AuthUserList)); if(memblocksteal->authUserList) { pciercxcfg031(memblocksteal->authUserList,directioninput,memblocksteal); if(memblocksteal->username) return 0; baFree(memblocksteal->authUserList); } HttpResponse_sendError1(&memblocksteal->cmd->response, 503); } if(ptr) baFree(*ptr); return -1; } BA_API struct AuthenticatedUser* AuthUserListEnumerator_getElement(DoubleListEnumerator* o) { DoubleLink* dl = DoubleListEnumerator_getElement(o); return dl ? AuthenticatedUser_dlink2Node(dl) : 0; } BA_API struct AuthenticatedUser* AuthUserListEnumerator_nextElement(DoubleListEnumerator* o) { DoubleLink* dl = DoubleListEnumerator_nextElement(o); return dl ? AuthenticatedUser_dlink2Node(dl) : 0; } static const char AuthenticatedUser_attrName[] = { "\101\165\164\150\145\156\164\151\143\141\164\145\144\125\163\145\162" }; BA_API AuthenticatedUser* AuthenticatedUser_getAnonymous(void) { static AuthUserList aul; static AuthenticatedUser au; static BaBool afterreset = FALSE; if(!afterreset) { AuthInfo memblocksteal; memset(&memblocksteal, 0, sizeof(AuthInfo)); pciercxcfg031(&aul,0,&memblocksteal); aul.username="\141\156\157\156\171\155\157\165\163"; AuthenticatedUser_constructor(&au,"",&aul,0); afterreset=TRUE; } return &au; } BA_API void AuthenticatedUser_constructor(AuthenticatedUser* o, const char* ttbr0enable, AuthUserList* entryinsert, HttpSessionAttribute_Destructor sha512update) { HttpSessionAttribute_constructor( (HttpSessionAttribute*)o, AuthenticatedUser_attrName, sha512update); DoubleLink_constructor(&o->dlink); o->authUserList = entryinsert; o->derivedType = ttbr0enable; entryinsert->listLen++; DoubleList_insertLast(&entryinsert->list, &o->dlink); } BA_API void AuthenticatedUser_destructor(AuthenticatedUser* o) { if(DoubleLink_isLinked(&o->dlink)) { DoubleLink_unlink(&o->dlink); idmapvector(o->authUserList); } if(((HttpSessionAttribute*)o)->destructor) { ((HttpSessionAttribute*)o)->destructor = 0; HttpSessionAttribute_destructor((HttpSessionAttribute*)o); } } BA_API void AuthenticatedUser_logout(AuthenticatedUser* o, BaBool all) { if(o) { if(all) { commonsuspend(o->authUserList); } else { HttpSession* s = AuthenticatedUser_getSession(o); DoubleLink_unlink(&o->dlink); idmapvector(o->authUserList); HttpSession_terminate(s); } } } BA_API AuthenticatedUser* AuthenticatedUser_get1(HttpRequest* configuredevice) { return AuthenticatedUser_get2(HttpRequest_getSession(configuredevice,FALSE)); } BA_API AuthenticatedUser* AuthenticatedUser_get2(HttpSession* func2fixup) { return (AuthenticatedUser*)HttpSession_getAttribute( func2fixup, AuthenticatedUser_attrName); } BA_API AuthenticatedUserType AuthenticatedUser_getType(AuthenticatedUser* o) { if(o->derivedType==BasicAuthUser_derivedType) return AuthenticatedUserType_Basic; if(o->derivedType==DigestAuthUser_derivedType) return AuthenticatedUserType_Digest; if(o->derivedType==FormAuthUser_derivedType) return AuthenticatedUserType_Form; return AuthenticatedUserType_Unknown; } void AuthenticatorIntf_constructor( AuthenticatorIntf* o, AuthenticatorIntf_Authenticate edma0pdata) { o->authenticateCB = edma0pdata; } #define LoginTrackerNode_dlink2Node(dlinkMA) \ ((LoginTrackerNode*)((U8*)dlinkMA-offsetof(LoginTrackerNode,dlink))) static void beforehandler(LoginTrackerNode* o, SplayTree* boardpcibios, DoubleList* smc91xresources, HttpSockaddr* serialports) { o->addr = *serialports; SplayTreeNode_constructor((SplayTreeNode*)o, &o->addr); DoubleLink_constructor(&o->dlink); o->loginCounter=0; o->auxCounter=0; o->userData=0; SplayTree_insert(boardpcibios, (SplayTreeNode*)o); DoubleList_insertLast(smc91xresources, &o->dlink); } static void disableiosapic(LoginTrackerNode* o, SplayTree* boardpcibios, DoubleList* uart4hwmod) { DoubleLink_unlink(&o->dlink); SplayTree_remove(boardpcibios, (SplayTreeNode*)o); o->loginCounter=0; DoubleList_insertLast(uart4hwmod, &o->dlink); } static int countmaster(SplayTreeNode* n, SplayTreeKey k) { if( ((LoginTrackerNode*)n)->addr.isIp6 == ((HttpSockaddr*)k)->isIp6) { int len = ((HttpSockaddr*)k)->isIp6 ? 16 : 4; return memcmp( ((LoginTrackerNode*)n)->addr.addr, ((HttpSockaddr*)k)->addr, len); } return ((HttpSockaddr*)k)->isIp6 ? 1 : -1; } BA_API void LoginTracker_constructor(LoginTracker* o, U32 notifyacked, LoginTrackerIntf* apecsmachine, AllocatorIntf* consoleiobase) { size_t icachealiases; SplayTree_constructor(&o->tree, countmaster); DoubleList_constructor(&o->dInUseList); DoubleList_constructor(&o->dFreeList); o->loginTrackerIntf=apecsmachine; o->cursor=0; icachealiases = sizeof(LoginTrackerNode)*(notifyacked-1); o->nodes = (LoginTrackerNode*)AllocatorIntf_malloc(consoleiobase,&icachealiases); if(!o->nodes) baFatalE(FE_MALLOC, 0); o->noOfLoginTrackerNodes=notifyacked; } BA_API void LoginTracker_destructor(LoginTracker* o) { LoginTracker_clearCache(o); baFree(o->nodes); } BA_API BaBool LoginTracker_validate(LoginTracker* o, AuthInfo* memblocksteal) { HttpSockaddr serialports; if( ! HttpConnection_getPeerName( HttpRequest_getConnection(&memblocksteal->cmd->request), &serialports,0) ) { BaBool handlersetup; LoginTrackerNode* n = (LoginTrackerNode*)SplayTree_find(&o->tree, &serialports); if(n) { handlersetup=LoginTrackerIntf_validate(o->loginTrackerIntf,memblocksteal,n); if(!handlersetup) { n->loginCounter++; n->t = baGetUnixTime(); memblocksteal->denied=TRUE; memblocksteal->loginAttempts = n->loginCounter - n->auxCounter; } return handlersetup; } return TRUE; } HttpResponse_sendError2(&memblocksteal->cmd->response, 501, "\125\156\153\156\157\167\156\040\160\145\145\162"); return FALSE; } BA_API void LoginTracker_loginFailed(LoginTracker* o, AuthInfo* memblocksteal) { HttpSockaddr serialports; if(HttpConnection_getPeerName( HttpRequest_getConnection(&memblocksteal->cmd->request),&serialports,0)) { HttpConnection_setState(HttpRequest_getConnection(&memblocksteal->cmd->request), HttpConnection_Terminated); } else { DoubleLink* l; LoginTrackerNode* n = (LoginTrackerNode*)SplayTree_find(&o->tree, &serialports); if( ! n ) { l = DoubleList_removeFirst(&o->dFreeList); if(l) { n = LoginTrackerNode_dlink2Node(l); beforehandler(n, &o->tree,&o->dInUseList,&serialports); } else if(o->cursor < o->noOfLoginTrackerNodes) { n = o->nodes+o->cursor; o->cursor++; beforehandler(n,&o->tree,&o->dInUseList,&serialports); } else { l = DoubleList_removeFirst(&o->dInUseList); n = LoginTrackerNode_dlink2Node(l); LoginTrackerIntf_terminateNode(o->loginTrackerIntf, n); SplayTree_remove(&o->tree, (SplayTreeNode*)n); beforehandler(n,&o->tree,&o->dInUseList,&serialports); } } n->loginCounter++; n->t = baGetUnixTime(); LoginTrackerIntf_loginFailed(o->loginTrackerIntf, memblocksteal, n); } } BA_API LoginTrackerNode* LoginTracker_find(LoginTracker*o, HttpRequest* req) { HttpSockaddr serialports; if( ! HttpConnection_getPeerName(HttpRequest_getConnection(req), &serialports,0) ) { return (LoginTrackerNode*)SplayTree_find(&o->tree, &serialports); } return 0; } BA_API void LoginTracker_login(LoginTracker* o, AuthInfo* memblocksteal) { LoginTrackerNode* n; n = LoginTracker_find(o, &memblocksteal->cmd->request); LoginTrackerIntf_login(o->loginTrackerIntf, memblocksteal, n); if(n) { LoginTrackerIntf_terminateNode(o->loginTrackerIntf, n); disableiosapic(n, &o->tree, &o->dFreeList); } } BA_API LoginTrackerNode* LoginTracker_getFirstNode(LoginTracker* o) { DoubleLink* dlink = DoubleList_firstNode(&o->dInUseList); if(dlink) return LoginTrackerNode_dlink2Node(dlink); return 0; } BA_API LoginTrackerNode* LoginTracker_getNextNode(LoginTracker* o, LoginTrackerNode* n) { DoubleLink* dlink = &n->dlink; if(DoubleList_isLast(&o->dInUseList, dlink)) return 0; dlink=DoubleLink_getNext(dlink); return LoginTrackerNode_dlink2Node(dlink); } BA_API void LoginTracker_clearCache(LoginTracker* o) { LoginTrackerNode* n; while( (n=LoginTracker_getFirstNode(o)) != 0) { LoginTrackerIntf_terminateNode(o->loginTrackerIntf, n); disableiosapic(n, &o->tree, &o->dFreeList); } } #ifndef BA_LIB #define BA_LIB 1 #endif #define authenticator_c 1 #include #include static BaBool smemcsuspend(const char* ptr) { if(*(ptr-4) == '\150' && *(ptr-3) == '\164' && *(ptr-2) == '\155' && *(ptr-1) == '\154') return TRUE; if(*(ptr-3) == '\150' && *(ptr-2) == '\164' && *(ptr-1) == '\155') return TRUE; if(*(ptr-3) == '\154' && *(ptr-2) == '\163' && *(ptr-1) == '\160') return TRUE; if(*(ptr-3) == '\143' && *(ptr-2) == '\163' && *(ptr-1) == '\160') return TRUE; return FALSE; } static AuthenticatedUser* Authenticator_authenticate( AuthenticatorIntf* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { AuthenticatedUser* buttonsbelkin; Authenticator* o = (Authenticator*)fdc37m81xconfig; HttpRequest* req=&cmd->request; if( ! (buttonsbelkin=AuthenticatedUser_get1(req)) ) { const char* printtiming; const char* checkrevision; checkrevision = printtiming = HttpRequest_getHeaderValue( req, "\101\165\164\150\157\162\151\172\141\164\151\157\156"); if(!checkrevision) checkrevision = HttpRequest_getHeaderValue(req,"\120\162\145\146\101\165\164\150"); if(!checkrevision) { if(o->authpref) { switch (o->authpref) { case 1: checkrevision = "\142\141\163\151\143"; break; case 2: checkrevision = "\144\151\147\145\163\164"; break; } } else { const char* pmuv1events = HttpRequest_getHeaderValue( req,"\170\055\162\145\161\165\145\163\164\145\144\055\167\151\164\150"); if(pmuv1events && !baStrCaseCmp(pmuv1events, "\130\115\114\110\164\164\160\122\145\161\165\145\163\164")) checkrevision = "\144\151\147\145\163\164"; else { int len = iStrlen(driverregister); const char* ptr=driverregister+len; if( ! (len==0 || *(ptr-1)=='\057' || (len>4 && smemcsuspend(ptr))) ) checkrevision = "\144\151\147\145\163\164"; } } } if(checkrevision) { if(baStrnCaseCmp("\142\141\163\151\143", checkrevision, 5)) { if( ! printtiming && HttpConnection_isSecure(HttpRequest_getConnection(req))) { BasicAuthenticator_setAutHeader( o->basicAuth.realm,&cmd->response); } buttonsbelkin = AuthenticatorIntf_authenticate( (AuthenticatorIntf*)&o->digestAuth,driverregister, cmd); } else { buttonsbelkin = AuthenticatorIntf_authenticate( (AuthenticatorIntf*)&o->basicAuth,driverregister, cmd); } } else { buttonsbelkin = AuthenticatorIntf_authenticate( (AuthenticatorIntf*)&o->formAuth, driverregister, cmd); } } else { if(AuthenticatedUser_getDerivedType(buttonsbelkin) == FormAuthUser_derivedType) { if(((FormAuthUser*)buttonsbelkin)->isFirstTime) return AuthenticatorIntf_authenticate( (AuthenticatorIntf*)&o->formAuth, driverregister, cmd); } } return buttonsbelkin; } BA_API void Authenticator_constructor(Authenticator* o, UserIntf* eventssysfs, const char* mappingprotection, LoginRespIntf* au1300intclknames) { o->authpref = 0; AuthenticatorIntf_constructor( (AuthenticatorIntf*)o, Authenticator_authenticate); BasicAuthenticator_constructor( &o->basicAuth, eventssysfs, mappingprotection, au1300intclknames); DigestAuthenticator_constructor( &o->digestAuth, eventssysfs, mappingprotection, au1300intclknames); FormAuthenticator_constructor( &o->formAuth, eventssysfs, mappingprotection, au1300intclknames); } BA_API void Authenticator_destructor(Authenticator* o) { FormAuthenticator_destructor(&o->formAuth); BasicAuthenticator_destructor(&o->basicAuth); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include typedef struct { char* username; char* passwd; U8 buf[80]; } ParseBasicHeader; static void patchvector(ParseBasicHeader* o, const char* rtcmatch2clockdev) { o->username = 0; o->passwd = 0; if(baStrnCaseCmp(rtcmatch2clockdev, "\102\141\163\151\143\040", 6)) return; rtcmatch2clockdev+=6; o->buf[baB64Decode(o->buf, sizeof(o->buf), rtcmatch2clockdev)]=0; o->passwd = bStrchr((char*)o->buf, '\072'); if(o->passwd) { *o->passwd++ = 0; o->username = (char*)o->buf; } } #define ParseBasicHeader_isValid(o) ((o)->username && (o)->passwd) static int mfptimerdisable( ParseBasicHeader* o, const char* mappingprotection, AuthInfo* memblocksteal) { switch(memblocksteal->ct) { case AuthInfoCT_Valid: memblocksteal->password[0]='\077'; memblocksteal->password[1]=0; return TRUE; case AuthInfoCT_Password: if( *memblocksteal->password && ! strcmp((char*)memblocksteal->password,o->passwd) ) return TRUE; break; case AuthInfoCT_HA1: { U8 mcspi2hwmod[33]; calculateHA1Hex(mappingprotection,o->username,o->passwd,mcspi2hwmod); if( ! memcmp(memblocksteal->password,mcspi2hwmod,32) ) return TRUE; } case AuthInfoCT_Invalid: break; } return FALSE; } typedef struct { AuthenticatedUser superClass; /*as if inherited*/ } BasicAuthUser; static void blake2bfinal(BasicAuthUser* o) { AuthenticatedUser_destructor((AuthenticatedUser*)o); baFree(o); } static void uart0resources(BasicAuthUser* o, AuthInfo* memblocksteal) { AuthenticatedUser_constructor( (AuthenticatedUser*)o, BasicAuthUser_derivedType, memblocksteal->authUserList, (HttpSessionAttribute_Destructor)blake2bfinal); memblocksteal->user=(AuthenticatedUser*)o; } static const char* BasicAuthenticator_getFilteredUserName( BasicAuthenticator* o, ParseBasicHeader* h) { char* ptr; if(o->filterMsDomain && (ptr = strchr(h->username, '\134'))) return ++ptr; return h->username; } static AuthenticatedUser* BasicAuthenticator_authenticate( AuthenticatorIntf* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { AuthInfo memblocksteal; ParseBasicHeader h; HttpSession* func2fixup; const char* printtiming; AuthenticatedUser* buttonsbelkin; BasicAuthenticator* o = (BasicAuthenticator*)fdc37m81xconfig; HttpResponse* doublefsqrt=HttpCommand_getResponse(cmd); (void)driverregister; if( !o->realm ) return 0; func2fixup = HttpRequest_getSession(HttpCommand_getRequest(cmd), FALSE); if(func2fixup) { buttonsbelkin = AuthenticatedUser_get2(func2fixup); if(buttonsbelkin) { return (AuthenticatedUser*)buttonsbelkin; } } AuthInfo_constructor(&memblocksteal, o->tracker, cmd, AuthenticatedUserType_Basic); printtiming=HttpRequest_getHeaderValue(HttpCommand_getRequest(cmd), "\101\165\164\150\157\162\151\172\141\164\151\157\156"); if(printtiming) { BasicAuthUser* buttonsbelkin; patchvector(&h, printtiming); if(ParseBasicHeader_isValid(&h)) { memblocksteal.username = BasicAuthenticator_getFilteredUserName(o, &h); memblocksteal.authUserList=HttpServer_getAuthUserList( HttpCommand_getServer(cmd), memblocksteal.username); memblocksteal.upwd = h.passwd; UserIntf_getPwd(o->userDbIntf,&memblocksteal); if(HttpResponse_committed(doublefsqrt)) return 0; if(o->tracker && ! LoginTracker_validate(o->tracker,&memblocksteal)) { o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); return 0; } if(mfptimerdisable(&h,o->realm,&memblocksteal)) { if(AuthUserList_createOrCheck(&memblocksteal,o->userDbIntf, (void**)&buttonsbelkin, sizeof(BasicAuthUser))) { if( ! HttpResponse_committed(doublefsqrt) ) { HttpResponse_setStatus(doublefsqrt, 403); o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); } goto L_failed; } uart0resources(buttonsbelkin,&memblocksteal); func2fixup = HttpRequest_getSession(&cmd->request,TRUE); if(!func2fixup || HttpSession_setAttribute(func2fixup,(HttpSessionAttribute*)buttonsbelkin) || !AuthenticatedUser_get2(func2fixup)) { blake2bfinal(buttonsbelkin); HttpResponse_sendError1(doublefsqrt, 503); goto L_failed; } if(memblocksteal.maxInactiveInterval) { HttpSession_setMaxInactiveInterval( func2fixup,memblocksteal.maxInactiveInterval); } if(o->tracker) LoginTracker_login(o->tracker,&memblocksteal); if(HttpRequest_getHeaderValue(HttpCommand_getRequest(cmd), "\123\145\164\125\162\154\103\157\157\153\151\145")) { HttpResponse_sendRedirect( doublefsqrt,HttpResponse_encodeSessionURL(doublefsqrt,0)); goto L_failed; } return (AuthenticatedUser*)buttonsbelkin; } if(o->tracker) LoginTracker_loginFailed(o->tracker,&memblocksteal); BasicAuthenticator_setAutHeader(o->realm, &cmd->response); } } else if(!o->tracker || LoginTracker_validate(o->tracker,&memblocksteal)) BasicAuthenticator_setAutHeader(o->realm, &cmd->response); o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); L_failed: AuthUserList_termIfEmpty(memblocksteal.authUserList); return 0; } BA_API void BasicAuthenticator_constructor( BasicAuthenticator* o, UserIntf* eventssysfs, const char* mappingprotection, LoginRespIntf* au1300intclknames) { AuthenticatorIntf_constructor( (AuthenticatorIntf*)o, BasicAuthenticator_authenticate); o->tracker=0; o->userDbIntf = eventssysfs; o->realm = baStrdup(mappingprotection); o->sendLogin = au1300intclknames; o->filterMsDomain=FALSE; } BA_API void BasicAuthenticator_destructor(BasicAuthenticator* o) { if(o->realm) baFree(o->realm); memset(o, 0, sizeof(BasicAuthenticator)); } BA_API void BasicAuthenticator_setAutHeader(const char* mappingprotection, HttpResponse* r3000write) { static const char fmt[] = {"\102\141\163\151\143\040\162\145\141\154\155\075\042\045\163\042"}; int len = iStrlen(fmt) + iStrlen(mappingprotection); char* cleaninval = HttpResponse_fmtHeader( r3000write, "\127\127\127\055\101\165\164\150\145\156\164\151\143\141\164\145", len, FALSE); if(cleaninval) basnprintf(cleaninval,len,fmt,mappingprotection); HttpResponse_setStatus(r3000write, 401); } #ifndef BA_LIB #define BA_LIB #endif #include #include #if (SHARKSSL_ENABLE_CSR_CREATION || SHARKSSL_ENABLE_CSR_SIGNING || SHARKSSL_ENABLE_ASN1_KEY_CREATION) static int pandoralegacy(SharkSslASN1Create *o, SharkSslCertKey *disableclock, int sha256export) { #if SHARKSSL_USE_ECC int persistentclock; #endif int sffsdrnandflash; U8 *timerdying; U8 *ref = o->ptr; #if SHARKSSL_USE_ECC if (machinereboot(disableclock->expLen)) { persistentclock = attachdevice(disableclock->modLen) * 2; if(SharkSslASN1Create_raw(o, disableclock->mod, persistentclock) || ((o->ptr - o->start) < 4)) { return -1; } *--o->ptr = SHARKSSL_EC_POINT_UNCOMPRESSED; *--o->ptr = 0x00; if (SharkSslASN1Create_length(o, persistentclock + 2) || SharkSslASN1Create_bitString(o)) { return -1; } #if SHARKSSL_ENABLE_ASN1_KEY_CREATION if (sha256export) { if (SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_ECPublicKey(o)) { return -1; } } #else (void)sha256export; #endif timerdying = o->ptr; switch (wakeupenable(disableclock->modLen)) { #if SHARKSSL_ECC_USE_SECP521R1 case SHARKSSL_EC_CURVE_ID_SECP521R1: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(secp521r1)); break; #endif #if SHARKSSL_ECC_USE_SECP384R1 case SHARKSSL_EC_CURVE_ID_SECP384R1: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(secp384r1)); break; #endif #if SHARKSSL_ECC_USE_SECP256R1 case SHARKSSL_EC_CURVE_ID_SECP256R1: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(prime256v1)); break; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP512R1: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(brainpoolP512r1)); break; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP384R1: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(brainpoolP384r1)); break; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP256R1: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(brainpoolP256r1)); break; #endif default: sffsdrnandflash = -1; break; } #if SHARKSSL_ENABLE_ASN1_KEY_CREATION if (sha256export) { return (SharkSslASN1Create_length(o, (int)(timerdying - o->ptr)) || SharkSslASN1Create_ECParameters(o)); } #endif if (!sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(ecPublicKey)); } } #if SHARKSSL_ENABLE_RSA else #endif #endif #if SHARKSSL_ENABLE_RSA if (machinekexec(disableclock->expLen)) { sffsdrnandflash = SharkSslASN1Create_int(o, disableclock->exp, mousethresh(disableclock->expLen)) || SharkSslASN1Create_int(o, disableclock->mod, supportedvector(disableclock->modLen)) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); if (!sffsdrnandflash) { *--o->ptr = 0x00; sffsdrnandflash = SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_bitString(o); } timerdying = o->ptr; if (!sffsdrnandflash) { *--o->ptr = 0; *--o->ptr = SHARKSSL_ASN1_NULL; sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(rsaEncryption)); } } #endif else { return -1; } return sffsdrnandflash || SharkSslASN1Create_length(o, (int)(timerdying - o->ptr)) || SharkSslASN1Create_sequence(o) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } #endif #if (SHARKSSL_ENABLE_CSR_CREATION || SHARKSSL_ENABLE_CSR_SIGNING) static int gpiokeysdevice(SharkSslASN1Create *o, SharkSslCertDN *panelshutdown) { int sffsdrnandflash = 0; U8 *ref = o->ptr; if (panelshutdown->emailAddress && !sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_email(o, sharkssl_oid_ex(emailAddress), panelshutdown->emailAddress, panelshutdown->emailAddressLen); } if (panelshutdown->countryName && !sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_name(o, sharkssl_oid_ex(country), panelshutdown->countryName, panelshutdown->countryNameLen); } if (panelshutdown->province && !sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_name(o, sharkssl_oid_ex(province), panelshutdown->province, panelshutdown->provinceLen); } if (panelshutdown->locality && !sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_name(o, sharkssl_oid_ex(locality), panelshutdown->locality, panelshutdown->localityLen); } if (panelshutdown->unit && !sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_name(o, sharkssl_oid_ex(unit), panelshutdown->unit, panelshutdown->unitLen); } if (panelshutdown->organization && !sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_name(o, sharkssl_oid_ex(organization), panelshutdown->organization, panelshutdown->organizationLen); } if (panelshutdown->commonName && !sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_name(o, sharkssl_oid_ex(CN), panelshutdown->commonName, panelshutdown->commonNameLen); } return sffsdrnandflash || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } static int removedomain(SharkSslASN1Create *o, const char *verbosemcheck) { U8 rightsvalid; U16 len = (U16)strlen(verbosemcheck); if (len < 14) { return -1; } SharkSslASN1Create_raw(o, "\132", 1); if (('\062' == verbosemcheck[0]) && ('\060' == verbosemcheck[1]) && ('\065' > verbosemcheck[2])) { if (len != 14) { return -1; } len -= 2; verbosemcheck += 2; rightsvalid = SHARKSSL_ASN1_UTC_TIME; } else { if (len < 14) { return -1; } rightsvalid = SHARKSSL_ASN1_GENERALIZED_TIME; } return SharkSslASN1Create_raw(o, verbosemcheck, len) || SharkSslASN1Create_length(o, len + 1) || SharkSslASN1Create_tag(o, rightsvalid); } static int stage2idmap(SharkSslASN1Create *o, SharkSslCertKey *configcheck, U8 configwrite) { int sffsdrnandflash = 0; U8 *ref = o->ptr; #if SHARKSSL_USE_ECC if (machinereboot(configcheck->expLen)) { switch (configwrite) { #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(ecdsaWithSHA512)); break; #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(ecdsaWithSHA384)); break; #endif default: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(ecdsaWithSHA256)); break; } } #if SHARKSSL_ENABLE_RSA else #endif #endif #if SHARKSSL_ENABLE_RSA if (machinekexec(configcheck->expLen)) { switch (configwrite) { #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(sha512withRSAEncryption)); break; #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(sha384withRSAEncryption)); break; #endif default: sffsdrnandflash = SharkSslASN1Create_oid(o, sharkssl_oid_ex(sha256withRSAEncryption)); break; } } #endif return sffsdrnandflash || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } static int devicewm8750(SharkSslASN1Create *o, SharkSslCertKey *configcheck, U8 *cachesysfs, U8 *end, U8 configwrite) { SharkSslSignParam signParam; U16 probealchemy; baAssert(end >= cachesysfs); #if SHARKSSL_USE_ECC if (machinereboot(configcheck->expLen)) { probealchemy = relocationchain(configcheck); signParam.signature.signatureAlgo = accessactive; } #if SHARKSSL_ENABLE_RSA else #endif #endif #if SHARKSSL_ENABLE_RSA if (machinekexec(configcheck->expLen)) { probealchemy = supportedvector(configcheck->modLen); signParam.signature.signatureAlgo = entryearly; } #endif else { return -1; } if((o->ptr - o->start) < (probealchemy + 8)) { return -1; } o->ptr -= probealchemy; if (cachesysfs) { sharkssl_hash(signParam.signature.hash, cachesysfs, (U16)(end - cachesysfs), configwrite); signParam.pCertKey = configcheck; signParam.signature.hashAlgo = configwrite; signParam.signature.signature = o->ptr; if ((checkactions(&signParam)) || (probealchemy < signParam.signature.signLen)) { return -1; } #if SHARKSSL_USE_ECC if (accessactive == signParam.signature.signatureAlgo) { if (probealchemy > signParam.signature.signLen) { o->ptr--; SharkSslASN1Create_length(o, signParam.signature.signLen + 1); o->end -= (probealchemy - signParam.signature.signLen); } } #endif return 0; } *--o->ptr = 0; probealchemy++; return SharkSslASN1Create_length(o, probealchemy) || SharkSslASN1Create_bitString(o) || stage2idmap(o, configcheck, configwrite); } #endif #if SHARKSSL_ENABLE_CSR_CREATION static int subpacketannotation(SharkSslASN1Create *o, const char *SAN, int alignstack, const U8 *oid, int fieldvalue) { if (SAN) { int sffsdrnandflash = 0; int allockuser; U8 *ref = o->ptr; char *probecache; if(((o->ptr - o->start) < alignstack) || (alignstack > 0xFF)) { return -1; } while ((alignstack > 0) && (!sffsdrnandflash)) { #define SHARKSSL_SAN_SEPARATOR_CHAR '\073' probecache = (char*)memchr(SAN, SHARKSSL_SAN_SEPARATOR_CHAR, alignstack); if (NULL == probecache) { allockuser = alignstack; alignstack = 0; } else { allockuser = (int)(probecache - SAN); alignstack -= allockuser; alignstack--; } if (allockuser > 0) { U8 aborthandler = SUBJECTALTNAME_DNSNAME; if ((allockuser >= 3) && (!memcmp(SAN, "\111\120\072", 3))) { U8 gpio27enable[4], i; aborthandler = SUBJECTALTNAME_IPADDRESS; allockuser -= 3; SAN += 3; memset(gpio27enable, 0, sizeof(gpio27enable)); i = 0; while (allockuser > 0) { if ((*SAN > '\071') || (*SAN < '\060') || (gpio27enable[i] > (0xFF/10))) { SAN += allockuser; i = 0; break; } gpio27enable[i] *= 10; gpio27enable[i] += (*SAN - '\060'); SAN++; allockuser--; if ((allockuser > 0) && (i < 3) && ('\056' == *SAN)) { i++; SAN++; allockuser--; } } if (3 == i) { o->ptr -= 4; memcpy(o->ptr, gpio27enable, 4); allockuser = 4; } else { aborthandler = 0; } } else { if ((allockuser >= 4) && (!memcmp(SAN, "\125\122\111\072", 4))) { aborthandler = SUBJECTALTNAME_URI; SAN += 4; allockuser -= 4; } o->ptr -= allockuser; memcpy(o->ptr, SAN, allockuser); SAN += allockuser; } if (aborthandler) { sffsdrnandflash = SharkSslASN1Create_length(o, allockuser) || SharkSslASN1Create_tag(o, SHARKSSL_ASN1_CONTEXT_SPECIFIC | aborthandler); } } SAN++; } if (!sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } if (!sffsdrnandflash) { sffsdrnandflash = SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_octetString(o); } return sffsdrnandflash || SharkSslASN1Create_oid(o, oid, fieldvalue) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } return -1; } static int eventinterruptible(SharkSslASN1Create *o, SharkSslBitExtReq *ext, int enablekernel, const U8 *oid, int fieldvalue) { if(ext) { U8 *ref = o->ptr; if((o->ptr - o->start) < 8 || (enablekernel > 8)) { return -1; } *--o->ptr = (U8)ext->bits; *--o->ptr = (U8)(8 - enablekernel); *--o->ptr = 2; SharkSslASN1Create_bitString(o); *--o->ptr = 4; SharkSslASN1Create_octetString(o); return SharkSslASN1Create_oid(o, oid, fieldvalue) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } return 0; } SHARKSSL_API int SharkSslASN1Create_CSR(SharkSslASN1Create *o, SharkSslKey mcbspplatform, U8 configwrite, SharkSslCertDN *devicetable, const char *SAN, SharkSslBitExtReq *latchcontrol, SharkSslBitExtReq *setupcalled) { SharkSslCertKey disableclock; U8 *ref, *end; int sffsdrnandflash; if (!interrupthandler(&disableclock, mcbspplatform)) { return -1; } devicewm8750(o, &disableclock, 0, 0, configwrite); end = o->ptr; ref = o->ptr; sffsdrnandflash = eventinterruptible(o, setupcalled, 8, sharkssl_oid_ex(ns_cert_type)) || eventinterruptible(o, latchcontrol, 7, sharkssl_oid_ex(key_usage)) || (SAN ? subpacketannotation(o, SAN, (int)strlen(SAN), sharkssl_oid_ex(san)) : 0); if( (latchcontrol || setupcalled || SAN) && !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_set(o) || SharkSslASN1Create_oid(o, sharkssl_oid_ex(csr_ext_req)) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_CSRAttributes(o); } if( !sffsdrnandflash ) { static const U8 ts409button[1] = {0}; sffsdrnandflash = pandoralegacy(o, &disableclock, 0) || gpiokeysdevice(o, devicetable) || SharkSslASN1Create_int(o, (U8*)ts409button, 1) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } if( !sffsdrnandflash ) { ref = o->ptr; o->ptr = o->end; devicewm8750(o, &disableclock, ref, end, configwrite); o->ptr = ref; return SharkSslASN1Create_length(o, (int)(o->end - o->ptr)) || SharkSslASN1Create_sequence(o); } return sffsdrnandflash; } #endif #if SHARKSSL_ENABLE_CSR_SIGNING static int pxa320evalboard(U8 *allocbuffer, U8 *tableprint, int emac0hwmod, int bypassvalue) { while (emac0hwmod > bypassvalue) { if (0 != *allocbuffer) { return -1; } allocbuffer++; emac0hwmod--; } while (bypassvalue > emac0hwmod) { if (0 != *tableprint) { return -1; } tableprint++; bypassvalue--; } return sharkssl_kmemcmp(allocbuffer, tableprint, emac0hwmod); } SHARKSSL_API int SharkSslCert_signCSR(SharkSslCert *unlockirqrestore, const U8 *asyncexport, int preservecurrent, const SharkSslCert userspacememory, const SharkSslKey mcbspplatform, const char *searchbitmap, const char *setupmodel, SharkCertSerialNumber flushwalker, U8 configwrite) { U8 *ref, *end; U8 *extPtr, *issuerPtr; U16 inputdevice; U32 cachelmiss; SharkSslCertParam certParam; SharkSslCertKey privKeyInfo, caKeyInfo; SharkSslASN1Create fixupconfig; int l, v, sffsdrnandflash; static const U8 switcherattrs[1] = {2}; inputdevice = 0; issuerPtr = NULL; *unlockirqrestore = NULL; if ((U32)preservecurrent > 0x7FFF) { return -1; } cachelmiss = (U16)preservecurrent; if (((sffsdrnandflash = spromregister(&certParam, asyncexport, (U32)-4, (U8*)&cachelmiss)) < 0) || (0 == (cachelmiss & 0xFFFF))) { return -1; } extPtr = (U8*)asyncexport + sffsdrnandflash; if (!interrupthandler(&privKeyInfo, mcbspplatform)) { if (NULL != mcbspplatform) { return -1; } } #if (!SHARKSSL_DISABLE_CSR_VERIFYSIGNATURE) if (NULL != mcbspplatform) { SharkSslSignParam signParam; U8 *signaldeliver; signaldeliver = (U8*)baMalloc(certParam.signature.signLen); if (NULL == signaldeliver) { return -1; } memcpy(&(signParam.signature), &(certParam.signature), sizeof (signParam.signature)); memcpy(signaldeliver, signParam.signature.signature, signParam.signature.signLen); signParam.signature.signature = signaldeliver; signParam.pCertKey = &privKeyInfo; l = systemcapabilities(&signParam); baFree(signaldeliver); if (l != 0) { return -1; } } #endif if (NULL == userspacememory) { if (NULL == mcbspplatform) { return -1; } #if SHARKSSL_USE_ECC if (machinereboot(privKeyInfo.expLen)) { if ((!(machinereboot(certParam.certKey.expLen))) || (wakeupenable(privKeyInfo.modLen) != wakeupenable(certParam.certKey.modLen))) { return -3; } if (pxa320evalboard(privKeyInfo.mod, certParam.certKey.mod, attachdevice(privKeyInfo.modLen), attachdevice(certParam.certKey.modLen))) { return -3; } } else #endif #if SHARKSSL_ENABLE_RSA if (machinekexec(privKeyInfo.expLen)) { if (!(machinekexec(certParam.certKey.expLen))) { return -3; } if (pxa320evalboard(privKeyInfo.exp, certParam.certKey.exp, mousethresh(privKeyInfo.expLen), mousethresh(certParam.certKey.expLen))) { return -3; } if (pxa320evalboard(privKeyInfo.mod, certParam.certKey.mod, supportedvector(privKeyInfo.modLen), supportedvector(certParam.certKey.modLen))) { return -3; } } else #endif { return -3; } memcpy(&caKeyInfo, &privKeyInfo, sizeof caKeyInfo); } else { if ((sffsdrnandflash = spromregister(0, (U8*)userspacememory, (U32)-2, (U8*)&inputdevice)) < 0) { return -1; } issuerPtr = (U8*)userspacememory + sffsdrnandflash; if (!interrupthandler(&caKeyInfo, userspacememory)) { return -1; } } sffsdrnandflash = (U16)(cachelmiss >> 16); if (0 == inputdevice) { sffsdrnandflash <<= 1; } else { sffsdrnandflash += inputdevice; } sffsdrnandflash += 120; sffsdrnandflash += (U16)(cachelmiss & 0xFFFF); sffsdrnandflash += sizeof(flushwalker); v = 4; if (NULL != mcbspplatform) { v += mousethresh(privKeyInfo.expLen); #if SHARKSSL_ENABLE_RSA if (machinekexec(privKeyInfo.expLen)) { v += supportedvector(privKeyInfo.modLen); v += ((supportedvector(privKeyInfo.modLen) / 2) * 5); } else #endif #if SHARKSSL_USE_ECC if (machinereboot(privKeyInfo.expLen)) { v += (U16)(2 * attachdevice(privKeyInfo.modLen)); } else #endif { return -1; } } #if SHARKSSL_ENABLE_RSA if (machinekexec(caKeyInfo.expLen)) { sffsdrnandflash += 8; sffsdrnandflash += 2 * supportedvector(caKeyInfo.modLen); sffsdrnandflash += mousethresh(caKeyInfo.expLen); } else #endif #if SHARKSSL_USE_ECC if (machinereboot(caKeyInfo.expLen)) { sffsdrnandflash += (U16)(2 * attachdevice(caKeyInfo.modLen)); sffsdrnandflash += relocationchain(&caKeyInfo); } else #endif { return -1; } l = ((((sffsdrnandflash + 0x3) & ~0x3) + v) + 0x7 + 20 ) & ~0x7; *unlockirqrestore = (U8*)baMalloc(l); if (NULL == *unlockirqrestore) { return -1; } SharkSslASN1Create_constructor(&fixupconfig, (U8*)*unlockirqrestore, l); devicewm8750(&fixupconfig, &caKeyInfo, 0, 0, configwrite); end = fixupconfig.ptr; ref = fixupconfig.ptr; sffsdrnandflash = SharkSslASN1Create_raw(&fixupconfig, extPtr, (U16)(cachelmiss & 0xFFFF)); if (( !sffsdrnandflash ) && (NULL == userspacememory)) { extPtr = fixupconfig.ptr; sffsdrnandflash = SharkSslASN1Create_boolean(&fixupconfig, 1); if ( !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_length(&fixupconfig, (int)(extPtr - fixupconfig.ptr)) || SharkSslASN1Create_sequence(&fixupconfig) || SharkSslASN1Create_length(&fixupconfig, (int)(extPtr - fixupconfig.ptr)) || SharkSslASN1Create_octetString(&fixupconfig) || SharkSslASN1Create_boolean(&fixupconfig, 1) || SharkSslASN1Create_oid(&fixupconfig, sharkssl_oid_ex(basic_constraints)) || SharkSslASN1Create_length(&fixupconfig, (int)(extPtr - fixupconfig.ptr)) || SharkSslASN1Create_sequence(&fixupconfig); } } if ( !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_length(&fixupconfig, (int)(ref - fixupconfig.ptr)) || SharkSslASN1Create_sequence(&fixupconfig) || SharkSslASN1Create_length(&fixupconfig, (int)(ref - fixupconfig.ptr)) || SharkSslASN1Create_extensions(&fixupconfig); } if ( !sffsdrnandflash ) { sffsdrnandflash = pandoralegacy(&fixupconfig, &(certParam.certKey), 0); } if ( !sffsdrnandflash ) { extPtr = fixupconfig.ptr; sffsdrnandflash = gpiokeysdevice(&fixupconfig, &(certParam.certInfo.subject)); if (NULL == issuerPtr) { issuerPtr = fixupconfig.ptr; inputdevice = (U16)(extPtr - fixupconfig.ptr); } } if ( !sffsdrnandflash ) { extPtr = fixupconfig.ptr; sffsdrnandflash = removedomain(&fixupconfig, setupmodel) || removedomain(&fixupconfig, searchbitmap); } if ( !sffsdrnandflash ) { sharkCertSerialNumber2NetworkEndian(flushwalker); sffsdrnandflash = SharkSslASN1Create_length(&fixupconfig, (int)(extPtr - fixupconfig.ptr)) || SharkSslASN1Create_sequence(&fixupconfig) || SharkSslASN1Create_raw(&fixupconfig, issuerPtr, inputdevice) || stage2idmap(&fixupconfig, &caKeyInfo, configwrite) || SharkSslASN1Create_int(&fixupconfig, (U8*)&flushwalker, sizeof(flushwalker)); } if ( !sffsdrnandflash ) { extPtr = fixupconfig.ptr; sffsdrnandflash = SharkSslASN1Create_int(&fixupconfig, (U8*)switcherattrs, 1) || SharkSslASN1Create_length(&fixupconfig, (int)(extPtr - fixupconfig.ptr)) || SharkSslASN1Create_version(&fixupconfig) || SharkSslASN1Create_length(&fixupconfig, (int)(ref - fixupconfig.ptr)) || SharkSslASN1Create_sequence(&fixupconfig); } if ( !sffsdrnandflash ) { ref = fixupconfig.ptr; fixupconfig.ptr = fixupconfig.end; devicewm8750(&fixupconfig, &caKeyInfo, ref, end, configwrite); fixupconfig.ptr = ref; sffsdrnandflash = SharkSslASN1Create_length(&fixupconfig, (int)(fixupconfig.end - fixupconfig.ptr)) || SharkSslASN1Create_sequence(&fixupconfig); } if ( !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_getDataLen(&fixupconfig, &extPtr); memmove((U8*)*unlockirqrestore, extPtr, sffsdrnandflash); extPtr = (U8*)*unlockirqrestore + sffsdrnandflash; while (sffsdrnandflash & 0x03) { *extPtr++ = 0xFF; sffsdrnandflash++; } if (NULL == mcbspplatform) { baAssert(4 == v); memset(extPtr, 0, v); } else { memcpy(extPtr, mcbspplatform + 4, v); } extPtr += v; sffsdrnandflash += v; while (sffsdrnandflash & 0x07) { *extPtr++ = 0xFF; sffsdrnandflash++; } if (sffsdrnandflash > l) { sffsdrnandflash = -4; goto _sharkssl_signCSR_err; } memset(extPtr, 0, (l - sffsdrnandflash)); } else { _sharkssl_signCSR_err: baFree((void*)*unlockirqrestore); *unlockirqrestore = NULL; } return sffsdrnandflash; } #endif #if SHARKSSL_ENABLE_ASN1_KEY_CREATION SHARKSSL_API int SharkSslASN1Create_key(SharkSslASN1Create *o, const SharkSslKey sourcerouting) { SharkSslCertKey keyInfo; int sffsdrnandflash; U8 *ref = o->ptr; if (!interrupthandler(&keyInfo, sourcerouting)) { return -1; } if (coupledexynos(keyInfo.expLen)) { return -2; } #if SHARKSSL_USE_ECC if (machinereboot(keyInfo.expLen)) { static const U8 rendezcheckin[1] = {1}; sffsdrnandflash = pandoralegacy(o, &keyInfo, 1) || SharkSslASN1Create_raw(o, keyInfo.exp, mousethresh(keyInfo.expLen)) || SharkSslASN1Create_length(o, mousethresh(keyInfo.expLen)) || SharkSslASN1Create_octetString(o); if ( !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_int(o, (U8*)rendezcheckin, 1) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } } else #endif #if SHARKSSL_ENABLE_RSA if (machinekexec(keyInfo.expLen)) { U8 *p1, *brightnesslimit; shtype_t e, m, d, pq, oi; U16 le, li, lih, i; static const U8 ts409button[1] = {0}; static const shtype_tWord intOneW = 1; le = mousethresh(keyInfo.expLen); li = supportedvector(keyInfo.modLen); lih = li >> 1; baAssert(li < 0xFFFF); brightnesslimit = (U8*)baMalloc((le * 2) + (li * 4)); if (brightnesslimit == NULL) { return -3; } memmove_endianess(brightnesslimit, keyInfo.exp, le); memmove_endianess(brightnesslimit + le + le + li, keyInfo.mod, li + li); onenandpartitions(&e, (le * 8), brightnesslimit); onenandpartitions(&d, ((li + le) * 8), (brightnesslimit + le)); onenandpartitions(&m, (li * 8), (brightnesslimit + le + le + li)); onenandpartitions(&pq, (lih * 8), (brightnesslimit + le + le + li + li + lih)); traceaddress(&oi, 1, ((U8*)(&intOneW))); updatepmull(&m, &pq); onenandpartitions(&pq, (lih * 8), (brightnesslimit + le + le + li + li)); updatepmull(&m, &pq); resolverelocs(&m, &oi); memmove_endianess(brightnesslimit + le + le + li + li, keyInfo.mod + li + li, li); onenandpartitions(&oi, (li * 8), (brightnesslimit + le + le + li + li + li)); hotplugpgtable(&e, &pq, &oi); onenandpartitions(&pq, (lih * 8), (brightnesslimit + le + le + li + li + lih)); hotplugpgtable(&oi, &pq, &d); suspendfinish(&d, &m); onenandpartitions(&oi, (li * 8), (brightnesslimit + le + le + li + li + li)); unassignedvector(&m, &oi); keypaddevice(&oi, &d, &m); setupsdhci1(&oi, &pq, &m); onenandpartitions(&pq, (lih * 8), (brightnesslimit + le + le + li + li)); setupsdhci1(&oi, &pq, &m); p1 = &keyInfo.mod[(li << 1) + li]; sffsdrnandflash = 0; for (i = 0; ((i < 5) && ( !sffsdrnandflash )); i++, p1 -= lih) { sffsdrnandflash = SharkSslASN1Create_int(o, p1, lih); } if ( !sffsdrnandflash ) { memmove_endianess(brightnesslimit, (U8*)consoledevice(&oi), li); sffsdrnandflash = SharkSslASN1Create_int(o, brightnesslimit, li); } if ( !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_int(o, keyInfo.exp, le); } if ( !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_int(o, keyInfo.mod, li); } if ( !sffsdrnandflash ) { sffsdrnandflash = SharkSslASN1Create_int(o, (U8*)ts409button, 1) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o); } baFree(brightnesslimit); } else #endif { return -1; } return sffsdrnandflash; } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include static AuthenticatedUser* DavAuth_authenticate(AuthenticatorIntf* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { static const char sanitizeaddress[]={"\101\165\164\150\157\162\151\172\141\164\151\157\156"}; AuthenticatedUser* buttonsbelkin; DavAuth* o = (DavAuth*)fdc37m81xconfig; HttpResponse* r3000write = &cmd->response; if( ! (buttonsbelkin=AuthenticatedUser_get1(&cmd->request)) ) { HttpRequest* r = &cmd->request; const char* checkrevision = HttpRequest_getHeaderValue(r,sanitizeaddress); if(!checkrevision) { AuthenticatorIntf_authenticate( (AuthenticatorIntf*)&o->basicAuth, driverregister, cmd); if(HttpConnection_isValid(HttpRequest_getConnection(r)) && ! HttpResponse_committed(r3000write)) { AuthenticatorIntf_authenticate( (AuthenticatorIntf*)&o->digestAuth, driverregister, cmd); } HttpResponse_sendError1(r3000write, -1); return 0; } else { buttonsbelkin = AuthenticatorIntf_authenticate( baStrnCaseCmp("\142\141\163\151\143", checkrevision, 5) ? (AuthenticatorIntf*)&o->digestAuth : (AuthenticatorIntf*)&o->basicAuth, driverregister, cmd); if( ! buttonsbelkin && ! HttpResponse_committed(r3000write)) { HttpResponse_sendError1(r3000write, r3000write->statusCode == 200 ? 401 : -1); } } } return buttonsbelkin; } static void sha512transform(LoginRespIntf* fdc37m81xconfig, AuthInfo* memblocksteal) { (void)fdc37m81xconfig; (void)memblocksteal; } BA_API void DavAuth_constructor(DavAuth* o, UserIntf* eventssysfs, const char* mappingprotection) { AuthenticatorIntf_constructor( (AuthenticatorIntf*)o, DavAuth_authenticate); LoginRespIntf_constructor(&o->sendLogin, sha512transform); BasicAuthenticator_constructor( &o->basicAuth, eventssysfs, mappingprotection, &o->sendLogin); DigestAuthenticator_constructor( &o->digestAuth, eventssysfs, mappingprotection, &o->sendLogin); BasicAuthenticator_setFilterMsDomain(&o->basicAuth, TRUE); DigestAuthenticator_setFilterMsDomain(&o->digestAuth, TRUE); } BA_API void DavAuth_destructor(DavAuth* o) { BasicAuthenticator_destructor(&o->basicAuth); DigestAuthenticator_destructor(&o->digestAuth); } #ifndef BA_LIB #define BA_LIB 1 #endif #define INL_baConvBin2Hex 1 #include #include #include #include #include #define NONCE_SECRET_KEY "\101\061\124\144\130\172" __TIME__ static char* trimString(char* str) { char* end; httpEatWhiteSpace(str); end = str + strlen(str); while(bIsspace(*(end-1))) end--; *end = 0; return str; } static char* removeQuotes(char* str) { size_t len=strlen(str); if(len >= 2 && str[0] == '\042' && str[len-1] == '\042') { str[len-1] = 0; str++; } return str; } static void imageheader( SharkSslMd5Ctx* registermcasp, const char* mappingprotection, const char* stackpointer, const char* pwd) { static const U8 c='\072'; SharkSslMd5Ctx_constructor(registermcasp); SharkSslMd5Ctx_append(registermcasp, (U8*)stackpointer,iStrlen(stackpointer)); SharkSslMd5Ctx_append(registermcasp, &c, 1); SharkSslMd5Ctx_append(registermcasp, (U8*)mappingprotection, iStrlen(mappingprotection)); SharkSslMd5Ctx_append(registermcasp, &c, 1); SharkSslMd5Ctx_append(registermcasp, (U8*)pwd, iStrlen(pwd)); } static void errornoslot(const U8* bin, U8* hex) { const U8* ptr; for (ptr = bin ; ptr < (bin+16) ; ptr++, hex+=2) baConvBin2Hex(hex, *ptr); *hex = 0; } void calculateHA1Hex(const char* mappingprotection, const char* stackpointer, const char* pwd, U8 mcspi2hwmod[33]) { U8 secondaryentry[16]; SharkSslMd5Ctx registermcasp; imageheader(®istermcasp, mappingprotection, stackpointer, pwd); SharkSslMd5Ctx_finish(®istermcasp, secondaryentry); errornoslot(secondaryentry,mcspi2hwmod); } typedef struct { U8 encodedDigest[33]; /*The encoded md5 string 32 characters + '\0'*/ } MD5Encoder; #define MD5Encoder_constructor(o) (o)->encodedDigest[0] = 0 #define MD5Encoder_isSet(o) ((o)->encodedDigest[0] != 0) #define MD5Encoder_isEqual(o,encDigest) \ (memcmp((o)->encodedDigest,encDigest, 32)==0) #define MD5Encoder_copy(o, levelsupports) \ memcpy((o)->encodedDigest, (levelsupports)->encodedDigest, 33) #define MD5Encoder_set(o, secondaryentry) errornoslot(secondaryentry, (o)->encodedDigest) typedef struct { const char* username; const char* realmName; const char* nonce; const char* nc; const char* cnonce; const char* qop; const char* uri; const char* response; } ParseDigestHeader; #define ParseDigestHeader_isValid(o) \ ((o)->username && (o)->realmName && (o)->nonce && (o)->uri && (o)->response) static void platformnotifier(ParseDigestHeader* o, char* rtcmatch2clockdev) { static const char helperinterface[] = {"\104\151\147\145\163\164\040"}; char* prctlenable; char* parsephandle; char* fixupdec21285; memset(o, 0, sizeof(ParseDigestHeader)); if(rtcmatch2clockdev) { if( ! baStrnCaseCmp(helperinterface, rtcmatch2clockdev, sizeof(helperinterface)-1) ) { rtcmatch2clockdev += sizeof(helperinterface)-1; do { prctlenable = rtcmatch2clockdev; httpEatCharacters(prctlenable, '\054'); if(*prctlenable) { *prctlenable = 0; prctlenable++; } parsephandle = rtcmatch2clockdev; httpEatCharacters(rtcmatch2clockdev, '\075'); if( ! *rtcmatch2clockdev ) return; *rtcmatch2clockdev++ = 0; fixupdec21285 = rtcmatch2clockdev; parsephandle = trimString(parsephandle); fixupdec21285 = trimString(fixupdec21285); if( ! strcmp("\165\163\145\162\156\141\155\145", parsephandle) ) o->username = removeQuotes(fixupdec21285); else if( ! strcmp("\162\145\141\154\155", parsephandle) ) o->realmName = removeQuotes(fixupdec21285); else if( ! strcmp("\156\157\156\143\145", parsephandle) ) o->nonce = removeQuotes(fixupdec21285); else if( ! strcmp("\156\143", parsephandle) ) o->nc = fixupdec21285; else if( ! strcmp("\143\156\157\156\143\145", parsephandle) ) o->cnonce = removeQuotes(fixupdec21285); else if( ! strcmp("\161\157\160", parsephandle) ) o->qop = removeQuotes(fixupdec21285); else if( ! strcmp("\165\162\151", parsephandle) ) o->uri = removeQuotes(fixupdec21285); else if( ! strcmp("\162\145\163\160\157\156\163\145", parsephandle) ) o->response = removeQuotes(fixupdec21285); rtcmatch2clockdev = prctlenable; } while(*rtcmatch2clockdev); } } if( ! o->username || ! o->realmName || ! o->nonce || ! o->nc || ! o->cnonce || ! o->qop || ! o->uri) { o->username = o->realmName = o->nonce = o->nc = o->cnonce = o->qop = o->uri = ""; } } typedef struct { MD5Encoder nonce; U32 nc; U8 ncbm[8]; /*Nonce count bit mask, a total of 64 bits.*/ } NonceContainer; static void fixupunassign(NonceContainer* o) { MD5Encoder_constructor(&o->nonce); } #define NonceContainer_resetBitMask(o) \ memset((o)->ncbm, 0xFF, sizeof((o)->ncbm)) static void NonceContainer_set(NonceContainer* o, U8 secondaryentry[16]) { MD5Encoder_set(&o->nonce, secondaryentry); o->nc = 1; NonceContainer_resetBitMask(o); } #define NonceContainer_isEqual(o, clientNonce) \ MD5Encoder_isEqual(&(o)->nonce, clientNonce) static BaBool validateinjection(NonceContainer* o, U32 createmanaged) { if( (createmanaged >= o->nc && (createmanaged - o->nc) < 10) || (createmanaged < o->nc && (o->nc - createmanaged) < 10) ) { static const U8 fpemulthreshold[8] = { 1, 2, 4, 8, 16, 32, 64, 128 }; U8* cipherencrypt; U8 bit = fpemulthreshold[((U8)createmanaged) & 7]; U8 pos = (U8)(createmanaged >> 3); if(pos > 7) return FALSE; cipherencrypt = o->ncbm+pos; if(*cipherencrypt & bit) { *cipherencrypt &= ~bit; o->nc++; return (o->nc % 20) != 0 ? TRUE : FALSE; } } return FALSE; } #define NonceContainer_getDigest(o) (o)->nonce.encodedDigest typedef struct { MD5Encoder md5A1; /*A cached value of A1 stored in encoded format.*/ NonceContainer nonceCont[3]; int curNonceI; /*Index position in nonceCont*/ } DigestData; static void probegtoffset(DigestData* o) { SharkSslMd5Ctx state; U8 secondaryentry[16]; sharkssl_rng(secondaryentry, sizeof(secondaryentry)); SharkSslMd5Ctx_constructor(&state); SharkSslMd5Ctx_append(&state, secondaryentry, iStrlen((char*)secondaryentry)); SharkSslMd5Ctx_append( &state, (const U8*)NONCE_SECRET_KEY, iStrlen(NONCE_SECRET_KEY)); SharkSslMd5Ctx_finish(&state, secondaryentry); if(++o->curNonceI == 3) o->curNonceI = 0; NonceContainer_set(o->nonceCont+o->curNonceI, secondaryentry); } static void boardunknown( DigestData* o, ParseDigestHeader* h, MD5Encoder* levelsupports) { SharkSslMd5Ctx state; U8 secondaryentry[16]; SharkSslMd5Ctx_constructor(&state); SharkSslMd5Ctx_append(&state, o->md5A1.encodedDigest, 32); SharkSslMd5Ctx_append(&state, (const U8*)"\072", 1); SharkSslMd5Ctx_append(&state, (const U8*)h->nonce, iStrlen(h->nonce)); SharkSslMd5Ctx_append(&state, (const U8*)"\072", 1); SharkSslMd5Ctx_append(&state, (const U8*)h->nc, iStrlen(h->nc)); SharkSslMd5Ctx_append(&state, (const U8*)"\072", 1); SharkSslMd5Ctx_append(&state, (const U8*)h->cnonce, iStrlen(h->cnonce)); SharkSslMd5Ctx_append(&state, (const U8*)"\072",1); SharkSslMd5Ctx_append(&state, (const U8*)h->qop, iStrlen(h->qop)); SharkSslMd5Ctx_append(&state, (const U8*)"\072",1); SharkSslMd5Ctx_append(&state, levelsupports->encodedDigest, 32); SharkSslMd5Ctx_finish(&state, secondaryentry); MD5Encoder_set(levelsupports, secondaryentry); } static void pciercxcfg009(DigestData* o) { int i; MD5Encoder_constructor(&o->md5A1); for(i = 0 ; i < 3 ; i++) fixupunassign(&o->nonceCont[i]); o->curNonceI = 0; probegtoffset(o); } static void suspendentering(DigestData* o, const char* mappingprotection, HttpResponse* doublefsqrt, BaBool timerblocking) { static const char pmullupdate[] = { "\104\151\147\145\163\164\040\162\145\141\154\155\075\042\045\163\042\054\040\144\157\155\141\151\156\075\042\057\042\054\040\161\157\160\075\042\141\165\164\150\042\054\040\156\157\156\143\145\075\042\045\163\042\045\163" }; static const char audiogpios[] = { "\054\040\163\164\141\154\145\075\164\162\165\145" }; const char* targetaddress = timerblocking ? audiogpios : ""; int len = sizeof(pmullupdate) + iStrlen(mappingprotection) + iStrlen(targetaddress) + 34; char* cleaninval = HttpResponse_fmtHeader( doublefsqrt, "\127\127\127\055\101\165\164\150\145\156\164\151\143\141\164\145", len, FALSE); if(cleaninval) { basnprintf(cleaninval, len, pmullupdate, mappingprotection, NonceContainer_getDigest(o->nonceCont+o->curNonceI), targetaddress); } HttpResponse_setStatus(doublefsqrt, 401); } static void decodertable(DigestData* o, const char* mappingprotection, AuthInfo* memblocksteal, LoginRespIntf* au1300intclknames, BaBool timerblocking, BaBool joystickevent) { suspendentering(o,mappingprotection,&memblocksteal->cmd->response,timerblocking); if(timerblocking) { if(joystickevent) HttpResponse_setContentLength(&memblocksteal->cmd->response, 0); } else { au1300intclknames->serviceFp(au1300intclknames, memblocksteal); } } static int physvirtoffset(DigestData* o, AuthInfo* memblocksteal) { if(memblocksteal->ct == AuthInfoCT_HA1) { memcpy(o->md5A1.encodedDigest, memblocksteal->password, 32); memblocksteal->password[32]=0; return TRUE; } return FALSE; } static int devicereset(DigestData* o, DigestAuthenticator* pmuv3event, AuthInfo* memblocksteal, ParseDigestHeader* h, int bypassproducer) { static const char outputports[] = { "\162\163\160\141\165\164\150\075\042\045\163\042\054\040\143\156\157\156\143\145\075\042\045\163\042\054\040\156\143\075\045\163\054\040\161\157\160\075\042\141\165\164\150\042\054\040\156\145\170\164\156\157\156\143\145\075\042\045\163\042"}; char* siblingsetup; SharkSslMd5Ctx registermcasp; const char* doublefnmul; int len; MD5Encoder levelsupports; U8 secondaryentry[16]; HttpResponse* doublefsqrt = &memblocksteal->cmd->response; HttpRequest* configuredevice = &memblocksteal->cmd->request; NonceContainer* curN = o->nonceCont+o->curNonceI; U32 createmanaged = U32_atoi(h->nc); if( ! MD5Encoder_isSet(&o->md5A1) ) { imageheader(®istermcasp, h->realmName, h->username, (char*)memblocksteal->password); SharkSslMd5Ctx_finish(®istermcasp, secondaryentry); MD5Encoder_set(&o->md5A1, secondaryentry); } doublefnmul = HttpRequest_getMethod(configuredevice); SharkSslMd5Ctx_constructor(®istermcasp); SharkSslMd5Ctx_append(®istermcasp,(const U8*)doublefnmul, iStrlen(doublefnmul)); SharkSslMd5Ctx_append(®istermcasp, (const U8*)"\072", 1); SharkSslMd5Ctx_append(®istermcasp, (const U8*)h->uri, iStrlen(h->uri)); SharkSslMd5Ctx_finish(®istermcasp, secondaryentry); MD5Encoder_set(&levelsupports, secondaryentry); boardunknown(o, h, &levelsupports); if(MD5Encoder_isEqual(&levelsupports, h->response)) { int i; NonceContainer* n=0; for(i=0 ; i < 3 ; i++) { if(NonceContainer_isEqual(o->nonceCont+i,h->nonce)) { n = o->nonceCont+i; break; } } if(n == curN) { probegtoffset(o); } else if(n) { if( !validateinjection(n, createmanaged) ) { if(curN->nc != 1) probegtoffset(o); decodertable( o,h->realmName,memblocksteal,pmuv3event->sendLogin,TRUE,TRUE); return FALSE; } } else { if(bypassproducer) { probegtoffset(o); decodertable( o,h->realmName,memblocksteal,pmuv3event->sendLogin,TRUE,FALSE); return TRUE; } if(curN->nc != 1) probegtoffset(o); decodertable( o,h->realmName,memblocksteal,pmuv3event->sendLogin,FALSE,TRUE); return FALSE; } SharkSslMd5Ctx_constructor(®istermcasp); SharkSslMd5Ctx_append(®istermcasp, (const U8*)"\072", 1); SharkSslMd5Ctx_append(®istermcasp, (const U8*)h->uri, iStrlen(h->uri)); SharkSslMd5Ctx_finish(®istermcasp, secondaryentry); MD5Encoder_set(&levelsupports, secondaryentry); boardunknown(o, h, &levelsupports); len = sizeof(outputports)+3*32+10; siblingsetup=HttpResponse_fmtHeader( doublefsqrt,"\101\165\164\150\145\156\164\151\143\141\164\151\157\156\055\111\156\146\157",len, TRUE); if(siblingsetup) { basnprintf(siblingsetup, len, outputports, levelsupports.encodedDigest, h->cnonce, h->nc, NonceContainer_getDigest(o->nonceCont+o->curNonceI)); } return TRUE; } decodertable( o,h->realmName,memblocksteal,pmuv3event->sendLogin,FALSE,TRUE); return FALSE; } typedef struct { AuthenticatedUser superClass; /*as if inherited*/ DigestData data; } DigestAuthUser; static void powersupply(DigestAuthUser* o) { AuthenticatedUser_destructor((AuthenticatedUser*)o); baFree(o); } static void leavelowpower(DigestAuthUser* o, AuthInfo* memblocksteal, DigestData* alloccontroller) { AuthenticatedUser_constructor( (AuthenticatedUser*)o, DigestAuthUser_derivedType, memblocksteal->authUserList, (HttpSessionAttribute_Destructor)powersupply); memcpy(&o->data, alloccontroller, sizeof(DigestData)); memblocksteal->user=(AuthenticatedUser*)o; } static const char* DigestAuthenticator_getFilteredUserName( DigestAuthenticator* o, ParseDigestHeader* h) { char* ptr; if(o->filterMsDomain && (ptr = strchr(h->username, '\134'))) { if(ptr[1] == '\134') { char* end; ptr++; end=ptr; while(*end =='\134' && *end) end++; memmove(ptr, end, strlen(end)+1); } return ptr; } return h->username; } static AuthenticatedUser* DigestAuthenticator_authenticate( AuthenticatorIntf* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { AuthInfo memblocksteal; DigestData alloccontroller; ParseDigestHeader h; HttpSession* func2fixup; const char* printtiming; DigestAuthUser* digestUser = 0; DigestAuthenticator* o = (DigestAuthenticator*)fdc37m81xconfig; HttpResponse* doublefsqrt=HttpCommand_getResponse(cmd); (void)driverregister; if( !o->realm ) return 0; printtiming=HttpRequest_getHeaderValue(HttpCommand_getRequest(cmd), "\101\165\164\150\157\162\151\172\141\164\151\157\156"); platformnotifier(&h, (char*)printtiming); func2fixup = HttpRequest_getSession(HttpCommand_getRequest(cmd), FALSE); if(func2fixup) { AuthenticatedUser* buttonsbelkin = AuthenticatedUser_get2(func2fixup); if(buttonsbelkin) { if( !o->strictMode ) return buttonsbelkin; if(AuthenticatedUser_getDerivedType(buttonsbelkin)==DigestAuthUser_derivedType) { AuthInfo_constructor( &memblocksteal,o->tracker,cmd,AuthenticatedUserType_Digest); memblocksteal.user=buttonsbelkin; digestUser=(DigestAuthUser*)buttonsbelkin; if(printtiming) { if(ParseDigestHeader_isValid(&h) && !strcmp(h.realmName, o->realm)) { return devicereset( &digestUser->data,o,&memblocksteal,&h,FALSE) ? buttonsbelkin: 0; } return buttonsbelkin; } else { decodertable( &digestUser->data,o->realm,&memblocksteal,o->sendLogin,TRUE,TRUE); return 0; } } else { return buttonsbelkin; } } } AuthInfo_constructor(&memblocksteal, o->tracker, cmd, AuthenticatedUserType_Digest); pciercxcfg009(&alloccontroller); if(printtiming) { DigestAuthUser* buttonsbelkin; if(ParseDigestHeader_isValid(&h)) { memblocksteal.username = DigestAuthenticator_getFilteredUserName(o, &h); memblocksteal.authUserList=HttpServer_getAuthUserList( HttpCommand_getServer(cmd), memblocksteal.username); UserIntf_getPwd(o->userDbIntf,&memblocksteal); if(HttpResponse_committed(doublefsqrt)) return 0; if(o->tracker && ! LoginTracker_validate(o->tracker,&memblocksteal)) { o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); return 0; } if( ((memblocksteal.ct == AuthInfoCT_Password && *memblocksteal.password) || physvirtoffset(&alloccontroller,&memblocksteal) ) && devicereset(&alloccontroller,o,&memblocksteal,&h,TRUE)) { if(AuthUserList_createOrCheck(&memblocksteal,o->userDbIntf, (void**)&buttonsbelkin, sizeof(DigestAuthUser))) { if( ! HttpResponse_committed(doublefsqrt) ) { HttpResponse_setStatus(doublefsqrt, 403); o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); } goto L_failed; } leavelowpower(buttonsbelkin,&memblocksteal, &alloccontroller); func2fixup = HttpRequest_getSession(&cmd->request,TRUE); if(!func2fixup || HttpSession_setAttribute(func2fixup,(HttpSessionAttribute*)buttonsbelkin) || !AuthenticatedUser_get2(func2fixup)) { powersupply(buttonsbelkin); HttpResponse_sendError1(doublefsqrt, 503); return 0; } if(memblocksteal.maxInactiveInterval) { HttpSession_setMaxInactiveInterval( func2fixup,memblocksteal.maxInactiveInterval); } if(o->tracker) LoginTracker_login(o->tracker,&memblocksteal); if(HttpRequest_getHeaderValue(HttpCommand_getRequest(cmd), "\123\145\164\125\162\154\103\157\157\153\151\145")) { HttpResponse_sendRedirect( doublefsqrt,HttpResponse_encodeSessionURL(doublefsqrt,0)); goto L_failed; } HttpResponse_setStatus(doublefsqrt, 200); return (AuthenticatedUser*)buttonsbelkin; } if(o->tracker && *memblocksteal.username) LoginTracker_loginFailed(o->tracker,&memblocksteal); if(*memblocksteal.password) goto L_failed; } } else if(o->tracker && ! LoginTracker_validate(o->tracker,&memblocksteal)) { o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); return 0; } decodertable( &alloccontroller,o->realm,&memblocksteal,o->sendLogin,FALSE,TRUE); L_failed: AuthUserList_termIfEmpty(memblocksteal.authUserList); return 0; } BA_API void DigestAuthenticator_constructor( DigestAuthenticator* o, UserIntf* eventssysfs, const char* mappingprotection, LoginRespIntf* au1300intclknames) { AuthenticatorIntf_constructor( (AuthenticatorIntf*)o, DigestAuthenticator_authenticate); o->tracker=0; o->userDbIntf = eventssysfs; o->strictMode = FALSE; o->realm = baStrdup(mappingprotection); o->sendLogin = au1300intclknames; o->filterMsDomain=FALSE; } BA_API void DigestAuthenticator_setAutHeader(const char* mappingprotection, HttpResponse* r3000write) { DigestData alloccontroller; pciercxcfg009(&alloccontroller); suspendentering(&alloccontroller,mappingprotection,r3000write,FALSE); } BA_API void DigestAuthenticator_destructor(DigestAuthenticator* o) { if(o->realm) baFree(o->realm); } #ifndef BA_LIB #define BA_LIB #endif #if (!SHARKSSL_SSL_CLIENT_CODE) #error Designed for the SharkSSL client lib #endif #if (!SHARKSSL_ENABLE_SESSION_CACHE) #error Requires SHARKSSL_ENABLE_SESSION_CACHE #endif #include #include #include #define SharkSslSCMgrNode_dlink2Obj(l) \ (SharkSslSCMgrNode*)((U8*)l-offsetof(SharkSslSCMgrNode,dlink)) static void hwdebugstate(SharkSslSCMgr* o, SharkSslSCMgrNode* n) { if( ! n ) { DoubleLink* l = DoubleList_lastNode(&o->dlist); if( ! l ) return; n=SharkSslSCMgrNode_dlink2Obj(l); } SharkSslSession_release(n->ss, o->ssl); DoubleLink_unlink(&n->dlink); SplayTree_remove(&o->stree,(SplayTreeNode*)n); baFree(n); baAssert(o->noOfSessions > 0); o->noOfSessions--; } static int memcachezalloc(SplayTreeNode* n, SplayTreeKey k) { if( ((SharkSslSCMgrNode*)n)->port == ((SharkSslSCMgrNode*)k)->port ) return sharkStrCaseCmp(((SharkSslSCMgrNode*)n)->host, ((SharkSslSCMgrNode*)n)->hostLen, ((SharkSslSCMgrNode*)k)->host, ((SharkSslSCMgrNode*)n)->hostLen); return ((SharkSslSCMgrNode*)n)->port - ((SharkSslSCMgrNode*)k)->port; } SHARKSSL_API SharkSslSCMgrNode* SharkSslSCMgr_get(SharkSslSCMgr* o,SharkSslCon* mmcsd0resources,const char* writereg16,U16 hwmoddeassert) { SharkSslSCMgrNode k; SharkSslSCMgrNode* n; k.host=writereg16; k.port=hwmoddeassert; n = (SharkSslSCMgrNode*)SplayTree_find(&o->stree,(SplayTreeKey)&k); if(n) { if( ! mmcsd0resources->session && ! SharkSslCon_resumeSession(mmcsd0resources,n->ss) ) { hwdebugstate(o, n); n=0; } } return n; } SHARKSSL_API int SharkSslSCMgr_save(SharkSslSCMgr* o, SharkSslCon* mmcsd0resources, const char* writereg16, U16 hwmoddeassert) { DoubleLink* l; SharkSslSCMgrNode* n; int handlersetup=-1; int iommucreate = o->noOfSessions > 0; SharkSslSession* ss = SharkSslCon_acquireSession(mmcsd0resources); if(!ss && o->noOfSessions >= mmcsd0resources->sharkSsl->sessionCache.cacheSize) { l=DoubleList_lastNode(&o->dlist); hwdebugstate(o, SharkSslSCMgrNode_dlink2Obj(l)); ss = SharkSslCon_acquireSession(mmcsd0resources); } if(ss) { n=(SharkSslSCMgrNode*)baMalloc( sizeof(SharkSslSCMgrNode)+strlen(writereg16)+1); if(n) { SplayTreeNode_constructor((SplayTreeNode*)n,n); DoubleLink_constructor(&n->dlink); n->ss=ss; n->port=hwmoddeassert; n->hostLen=(U16)strlen(writereg16); strcpy((char*)(n+1),writereg16); n->host=(char*)(n+1); SplayTree_insert(&o->stree, (SplayTreeNode*)n); DoubleList_insertFirst(&o->dlist,&n->dlink); o->noOfSessions++; handlersetup=0; } else SharkSslSession_release(ss, o->ssl); } if(iommucreate) { l=DoubleList_lastNode(&o->dlist); n=SharkSslSCMgrNode_dlink2Obj(l); if((baGetUnixTime() - SharkSslSession_getLatestAccessTime(n->ss)) > o->maxTime) { hwdebugstate(o, n); } } return handlersetup; } static void hwrandomresource(SharkSslIntf* fdc37m81xconfig, SharkSsl* ssl) { SharkSslSCMgr* o = (SharkSslSCMgr*)fdc37m81xconfig; (void)ssl; while( ! DoubleList_isEmpty(&o->dlist) ) hwdebugstate(o,0); baFree(o); } SHARKSSL_API void SharkSslSCMgr_constructor(SharkSslSCMgr* o, SharkSsl* ssl, U32 coherencytable) { SharkSslIntf_constructor((SharkSslIntf*)o, hwrandomresource); SplayTree_constructor( &o->stree,memcachezalloc); DoubleList_constructor(&o->dlist); o->noOfSessions=0; o->maxTime=coherencytable; o->ssl = ssl; } #ifndef BA_LIB #define BA_LIB 1 #endif #define formauthenticator_c 1 #include #include #include static const char FormLoginName[] = {"\137\172\106\114"}; #ifndef NO_SHARKSSL #include static U32 frameaddress(FormAuthenticator* o, U32 suspendblock) { SharkSslAesCtx aesCtx; U8 IV[16]; U8 resetstatus[16]; memset(IV, 0, sizeof(IV)); (*((U32*)resetstatus)) = suspendblock; SharkSslAesCtx_constructor( &aesCtx,SharkSslAesCtx_Encrypt,o->aesKey,sizeof(o->aesKey)); SharkSslAesCtx_ctr_mode( &aesCtx, IV, resetstatus, resetstatus, (U16)sizeof(resetstatus)); SharkSslAesCtx_destructor(&aesCtx); return *((U32*)resetstatus); } static void isramplatdata(FormAuthenticator* o, AuthInfo* memblocksteal) { do { sharkssl_rng((U8*)&memblocksteal->seed, sizeof(U32)); } while(memblocksteal->seed == 0); memblocksteal->seedKey=frameaddress(o,memblocksteal->seed); } static int affinitycollection( FormAuthenticator* o,AuthInfo* memblocksteal,const char* perfmonevent,U32 suspendblock,U32 resetstatus) { int ok=FALSE; if(suspendblock == frameaddress(o,resetstatus) && *memblocksteal->password && strlen(perfmonevent) == 40) { SharkSslSha1Ctx registermcasp; int i; U8 secondaryentry[20]; char buf[20]; U8* out = (U8*)buf; U8* in = (U8*)perfmonevent; SharkSslSha1Ctx_constructor(®istermcasp); SharkSslSha1Ctx_append( ®istermcasp,(U8*)memblocksteal->password,iStrlen((char*)memblocksteal->password)); SharkSslSha1Ctx_append( ®istermcasp,(U8*)buf,basnprintf(buf,sizeof(buf),"\045\144",suspendblock)); SharkSslSha1Ctx_finish(®istermcasp, secondaryentry); for(i = 0; i < 20 ; i++) { *out++ = (U8)(baConvHex2Bin(*in) << 4) + baConvHex2Bin(in[1]); in+=2; } ok = memcmp(buf,secondaryentry,20) ? FALSE : TRUE; } return ok; } #endif static int probesandcraft( FormAuthenticator* o,AuthInfo* memblocksteal,const char* perfmonevent) { switch(memblocksteal->ct) { case AuthInfoCT_Valid: memblocksteal->password[0]='\077'; memblocksteal->password[1]=0; return TRUE; case AuthInfoCT_Password: if( *memblocksteal->password && ! strcmp((char*)memblocksteal->password,perfmonevent) ) return TRUE; break; case AuthInfoCT_HA1: #ifndef NO_SHARKSSL { U8 mcspi2hwmod[33]; calculateHA1Hex(o->realm,memblocksteal->username,perfmonevent,mcspi2hwmod); if( ! memcmp(memblocksteal->password,mcspi2hwmod,32) ) return TRUE; } #endif case AuthInfoCT_Invalid: break; } return FALSE; } static void sigtramptemplate(FormAuthUser* o) { AuthenticatedUser_destructor((AuthenticatedUser*)o); baFree(o); } static void sigsetdeactivate(FormAuthUser* o, AuthInfo* memblocksteal) { AuthenticatedUser_constructor( (AuthenticatedUser*)o, FormAuthUser_derivedType, memblocksteal->authUserList, (HttpSessionAttribute_Destructor)sigtramptemplate); o->isFirstTime=TRUE; memblocksteal->user=(AuthenticatedUser*)o; } static AuthenticatedUser* FormAuthenticator_authenticate( AuthenticatorIntf* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { AuthInfo memblocksteal; HttpSession* func2fixup; FormAuthUser* formUser = 0; HttpCookie* formLogin; const char* perfmonevent; #ifndef NO_SHARKSSL const char* defaultpriority=0; U32 suspendblock=0; U32 resetstatus=0; #endif FormAuthenticator* o = (FormAuthenticator*)fdc37m81xconfig; func2fixup = HttpRequest_getSession(&cmd->request, FALSE); (void)driverregister; if(func2fixup) { AuthenticatedUser* buttonsbelkin = AuthenticatedUser_get2(func2fixup); if(buttonsbelkin) { if(AuthenticatedUser_getDerivedType(buttonsbelkin) == FormAuthUser_derivedType) { formUser = (FormAuthUser*)buttonsbelkin; if(formUser->isFirstTime) { char* val =(char*)HttpRequest_getHeaderValue( &cmd->request, "\111\146\055\115\157\144\151\146\151\145\144\055\123\151\156\143\145"); if(val) *val=0; val =(char*)HttpRequest_getHeaderValue(&cmd->request, "\105\164\141\147"); if(val) *val=0; formUser->isFirstTime=FALSE; formLogin = HttpRequest_getCookie(&cmd->request, FormLoginName); if(formLogin) { HttpCookie_setPath(formLogin, "\057"); HttpCookie_setValue(formLogin,""); HttpCookie_activate(formLogin); } } } return buttonsbelkin; } } AuthInfo_constructor(&memblocksteal, o->tracker, cmd, AuthenticatedUserType_Form); #ifndef NO_SHARKSSL isramplatdata(o, &memblocksteal); #endif memblocksteal.username = HttpRequest_getParameter(&cmd->request, "\142\141\137\165\163\145\162\156\141\155\145"); perfmonevent = HttpRequest_getParameter(&cmd->request, "\142\141\137\160\141\163\163\167\157\162\144"); #ifndef NO_SHARKSSL if( (defaultpriority = HttpRequest_getParameter(&cmd->request, "\142\141\137\163\145\145\144")) !=0 ) { suspendblock=U32_atoi(defaultpriority); if((defaultpriority=HttpRequest_getParameter(&cmd->request,"\142\141\137\163\145\145\144\153\145\171"))!=0) resetstatus=U32_atoi(defaultpriority); } if( ((o->secure && ! HttpConnection_isSecure(cmd->con)) && !defaultpriority) || (o->tracker && ! LoginTracker_validate(o->tracker,&memblocksteal)) ) #else if( (o->secure && ! HttpConnection_isSecure(cmd->con)) || (o->tracker && ! LoginTracker_validate(o->tracker,&memblocksteal)) ) #endif { o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); return 0; } HttpResponse_setDefaultHeaders(&cmd->response); if(memblocksteal.username && perfmonevent) { HttpServer* uarchbuild = HttpCommand_getServer(cmd); memblocksteal.authUserList=HttpServer_getAuthUserList(uarchbuild, memblocksteal.username); #ifndef NO_SHARKSSL if( ! defaultpriority ) #endif memblocksteal.upwd = perfmonevent; UserIntf_getPwd(o->userDbIntf,&memblocksteal); if(HttpResponse_committed(&cmd->response)) { return 0; } #ifndef NO_SHARKSSL if(defaultpriority ? affinitycollection(o,&memblocksteal,perfmonevent,suspendblock,resetstatus) : probesandcraft(o,&memblocksteal,perfmonevent)) #else if(probesandcraft(o,&memblocksteal,perfmonevent)) #endif { if(AuthUserList_createOrCheck(&memblocksteal,o->userDbIntf, (void**)&formUser, sizeof(FormAuthUser))) { if( ! HttpResponse_committed(&cmd->response) ) o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); goto L_cleanup; } sigsetdeactivate(formUser,&memblocksteal); func2fixup = HttpRequest_getSession(&cmd->request,TRUE); if(!func2fixup || HttpSession_setAttribute(func2fixup,(HttpSessionAttribute*)formUser)|| !AuthenticatedUser_get2(func2fixup)) { HttpResponse_sendError1(HttpCommand_getResponse(cmd), 503); sigtramptemplate(formUser); goto L_cleanup; } if(HttpConnection_isSecure(cmd->con)) { HttpCookie* sc=HttpRequest_getCookie(&cmd->request, BA_COOKIE_ID); HttpCookie_setSecure(sc, TRUE); } if(memblocksteal.maxInactiveInterval) { HttpSession_setMaxInactiveInterval( func2fixup,memblocksteal.maxInactiveInterval); } if(o->tracker) { LoginTracker_login(o->tracker,&memblocksteal); } formLogin = HttpRequest_getCookie(&cmd->request, FormLoginName); if(formLogin && HttpCookie_getValue(formLogin) && *HttpCookie_getValue(formLogin)) { HttpResponse_sendRedirect( &cmd->response,HttpCookie_getValue(formLogin)); HttpCookie_setPath(formLogin, "\057"); HttpCookie_deleteCookie(formLogin); HttpCookie_activate(formLogin); } else { HttpResponse_sendRedirect( &cmd->response, HttpResponse_encodeRedirectURL( &cmd->response, HttpRequest_getRequestURI(&cmd->request))); } L_cleanup: AuthUserList_termIfEmpty(memblocksteal.authUserList); return 0; } if(o->tracker) LoginTracker_loginFailed(o->tracker,&memblocksteal); HttpResponse_setDefaultHeaders(&cmd->response); o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); } else { if(HttpRequest_getNoOfParameters(&cmd->request) && ! HttpRequest_getHeaderValue(&cmd->request, "\130\055\122\145\161\165\145\163\164\145\144\055\127\151\164\150")) { formLogin = HttpResponse_createCookie(&cmd->response, FormLoginName); if(formLogin) { const char* url=HttpResponse_encodeRedirectURLWithParam( &cmd->response, HttpRequest_getRequestURI(&cmd->request)); if(url) { HttpCookie_setValue(formLogin,url); HttpCookie_setPath(formLogin, "\057"); HttpCookie_activate(formLogin); } } } o->sendLogin->serviceFp(o->sendLogin, &memblocksteal); } return AuthenticatedUser_get1(&cmd->request); } BA_API void FormAuthenticator_constructor( FormAuthenticator* o, UserIntf* eventssysfs, const char* mappingprotection, LoginRespIntf* touchscreenpdata) { AuthenticatorIntf_constructor( (AuthenticatorIntf*)o, FormAuthenticator_authenticate); o->tracker=0; o->userDbIntf = eventssysfs; o->realm = baStrdup(mappingprotection ? mappingprotection : ""); o->sendLogin = touchscreenpdata; o->secure=FALSE; #ifndef NO_SHARKSSL { #ifndef BA_DEBUG U32 blockgeneric; sharkssl_entropy((U32)((ptrdiff_t)&blockgeneric)); sharkssl_entropy(blockgeneric); #endif sharkssl_entropy((U32)(baGetMsClock() + baGetUnixTime())); sharkssl_rng(o->aesKey, sizeof(o->aesKey)); } #endif } #ifndef BA_LIB #define BA_LIB 1 #endif #include typedef struct { /* A Resource is in one of JConstrCont::resourceTable(HashTable) or JConstrCont::resourceList(DoubleList) */ union { HashTableNode htn; DoubleLink dlink; } u; AllocatorIntf* alloc; /* Needed for destructor, when HashTableNode */ U16 noOfMethods; U16 noOfRoles; U16* methods; /* Of type HttpMethod: Pointer to memory below roles */ char* path; /* Pointer to memory below methods */ U16 pathLen; U16 roles[1]; } Resource; static void splitregion(HashTableNode* fdc37m81xconfig, void* accesssubid) { (void)accesssubid; AllocatorIntf_free(((Resource*)fdc37m81xconfig)->alloc, fdc37m81xconfig); } static BaBool sad2dresets(JConstrCont* o, Resource* ic0r0dispatch, JUser* buttonsbelkin, HttpMethod disableparity) { int i; (void)o; if(ic0r0dispatch->noOfRoles) { if(buttonsbelkin->noOfRoles) { for(i = 0 ; i < ic0r0dispatch->noOfRoles; i++) { int j; for(j = 0 ; j < buttonsbelkin->noOfRoles; j++) { if(ic0r0dispatch->roles[i] == buttonsbelkin->roles[j]) goto L_FoundRole; } } return FALSE; } } L_FoundRole: if(ic0r0dispatch->noOfMethods) { for(i = 0 ; i < ic0r0dispatch->noOfMethods; i++) { if((U16)disableparity == ic0r0dispatch->methods[i]) return TRUE; } } else return TRUE; return buttonsbelkin->noOfRoles == 0 && ic0r0dispatch->noOfRoles != 0; } static BaBool notifyresume(AuthorizerIntf* fdc37m81xconfig, AuthenticatedUser* coloralign, HttpMethod disableparity, const char* driverstate) { DoubleListEnumerator e; Resource* ic0r0dispatch; U16 nativeregister; U16 extensionfault; JUser* buttonsbelkin; const char* alloccoherent; const char* emptytables; JConstrCont* o = (JConstrCont*)fdc37m81xconfig; if( ! coloralign ) return FALSE; if( ! (alloccoherent = AuthenticatedUser_getName(coloralign)) ) return FALSE; buttonsbelkin = JUserCont_findUser(o->userCont, alloccoherent); emptytables = AuthenticatedUser_getPassword(coloralign); if(!buttonsbelkin || !emptytables || strcmp(emptytables,buttonsbelkin->pwd)) { if ( ! (buttonsbelkin && emptytables && !strcmp(emptytables, "\137\141\165\164\157\154\157\147\151\156\137") && !strcmp("\114\165\141", coloralign->derivedType)) ) { return AuthenticatedUser_getAnonymous() == coloralign ? TRUE : FALSE; } } if(disableparity == HttpMethod_Head) disableparity = HttpMethod_Get; if(o->resourceTable) { ic0r0dispatch = (Resource*)HashTable_lookup(o->resourceTable,driverstate); if(ic0r0dispatch) { return sad2dresets(o,ic0r0dispatch,buttonsbelkin,disableparity); } } nativeregister=0; extensionfault = (U16)strlen(driverstate); DoubleListEnumerator_constructor(&e, &o->resourceList); for(ic0r0dispatch = (Resource*)DoubleListEnumerator_getElement(&e) ; ic0r0dispatch ; ic0r0dispatch = (Resource*)DoubleListEnumerator_nextElement(&e)) { if(extensionfault >= ic0r0dispatch->pathLen) { if( o->caseSensensitive ? strncmp(ic0r0dispatch->path, driverstate, ic0r0dispatch->pathLen) == 0 : baStrnCaseCmp(ic0r0dispatch->path, driverstate, ic0r0dispatch->pathLen) == 0) { if(nativeregister > ic0r0dispatch->pathLen) return FALSE; if(sad2dresets(o,ic0r0dispatch,buttonsbelkin,disableparity)) return TRUE; if(nativeregister==0) nativeregister=ic0r0dispatch->pathLen; } } } return FALSE; } static void auxdatalegacy(JConstrCont* o) { if(o->resourceTable) { HashTable_destructor(o->resourceTable); AllocatorIntf_free(o->alloc, o->resourceTable); o->resourceTable=0; } for(;;) { DoubleLink* l = DoubleList_removeFirst(&o->resourceList); if(!l) break; AllocatorIntf_free(o->alloc, l); } o->noOfResources=0; } BA_API void JConstrCont_setConstraints(JConstrCont* o, JVal* segbitsfault, JErr* err) { JVal* resArrayVal = JVal_getObject(segbitsfault, err); auxdatalegacy(o); o->resourceTable = HashTable_create(11, o->alloc); if(!o->resourceTable) return; for(; resArrayVal && JErr_noError(err) ; resArrayVal = JVal_getNextElem(resArrayVal)) { const char* gpio1config; JVal* urlsVal; JVal* methodsVal; JVal* domaincreate; S32 noOfUrls, noOfMethods, mcbsp2sidetone; JVal_get(resArrayVal, err, "\173\112\112\112\175", "\165\162\154\163", &urlsVal, "\155\145\164\150\157\144\163", &methodsVal, "\162\157\154\145\163", &domaincreate); if(JErr_isError(err)) return; noOfUrls = JVal_getLength(urlsVal, err); noOfMethods = JVal_getLength(methodsVal, err); mcbsp2sidetone = JVal_getLength(domaincreate, err); urlsVal = JVal_getArray(urlsVal, err); domaincreate = mcbsp2sidetone ? JVal_getArray(domaincreate, err) : 0; if(noOfUrls == 0) { JErr_setTooFewParams(err); return; } do { U16 i; JVal* val; Resource* newRes; size_t icachealiases; const char* url = JVal_getString(urlsVal, err); if(!url) return; if(!*url) continue; icachealiases = sizeof(Resource)+ sizeof(U16)*mcbsp2sidetone+ sizeof(U16)*noOfMethods+ strlen(url)+1; newRes = (Resource*)AllocatorIntf_malloc(o->alloc,&icachealiases); if(!newRes) { JErr_setError(err,JErrT_MemErr,0); return; } newRes->alloc=o->alloc; newRes->noOfMethods=(S16)noOfMethods; newRes->noOfRoles=(S16)mcbsp2sidetone; newRes->methods=(U16*)JUserCont_copyRoles( o->userCont,newRes->roles,domaincreate,err); if(noOfMethods) { val = JVal_getArray(methodsVal, err); for(i=0 ; val && JErr_noError(err) ; i++, val=JVal_getNextElem(val)) { gpio1config = JVal_getString(val, err); if(gpio1config) { newRes->methods[i]=(U16)HttpMethod_a2m(gpio1config); } } } else i=0; if(JErr_isError(err)) { AllocatorIntf_free(o->alloc, newRes); return; } newRes->path=(char*)(newRes->methods+i); if(url[0] == '\057') url++; newRes->pathLen=(U16)strlen(url); if(url[newRes->pathLen-1] == '\052' && url[newRes->pathLen-2] == '\057') { DoubleListEnumerator e; Resource* res; DoubleLink_constructor((DoubleLink*)newRes); if(newRes->pathLen > 2) { newRes->pathLen-=2; memcpy(newRes->path, url, newRes->pathLen); newRes->path[newRes->pathLen]=0; } else { newRes->pathLen=0; newRes->path[0]=0; } DoubleListEnumerator_constructor(&e, &o->resourceList); for(res = (Resource*)DoubleListEnumerator_getElement(&e) ; res ; res = (Resource*)DoubleListEnumerator_nextElement(&e)) { if(res->pathLen < newRes->pathLen) break; } if(res) DoubleLink_insertBefore(res, newRes); else DoubleList_insertLast(&o->resourceList, newRes); o->noOfResources++; } else { if(HashTable_lookup(o->resourceTable,url)) { AllocatorIntf_free(o->alloc,newRes); } else { strcpy(newRes->path, url); HashTableNode_constructor((HashTableNode*)newRes, newRes->path, splitregion); HashTable_add(o->resourceTable,(HashTableNode*)newRes); o->noOfResources++; } } } while( (urlsVal = JVal_getNextElem(urlsVal)) != 0 ); } } BA_API void JConstrCont_constructor( JConstrCont* o, JUserCont* handleruaccess, AllocatorIntf* unmapaliases) { AuthorizerIntf_constructor((AuthorizerIntf*)o, notifyresume); o->resourceTable=0; o->userCont=handleruaccess; o->caseSensensitive = TRUE; DoubleList_constructor(&o->resourceList); o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); o->noOfResources=0; } BA_API void JConstrCont_destructor(JConstrCont* o) { auxdatalegacy(o); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #define JRole_constructor(o, id, n) \ strcpy(o->name, n), \ o->roleId=id, \ SplayTreeNode_constructor((SplayTreeNode*)o, o->name); static void* JUserCont_malloc(JUserCont* o, size_t icachealiases) { return AllocatorIntf_malloc(o->alloc, &icachealiases); } static int softwareevent(SplayTreeNode* n, SplayTreeKey k) { return strcmp((const char*)n->key, (const char*)k); } static void pwrdmconstraint(JUserCont* o) { SplayTreeNode* stn; while( (stn = SplayTree_getRoot(&o->userdb)) != 0) { SplayTree_remove(&o->userdb, stn); AllocatorIntf_free(o->alloc, stn); } o->noOfUsers=0; } static void nresetconfig(struct UserIntf* fdc37m81xconfig, AuthInfo* memblocksteal) { JUser* buttonsbelkin; JUserCont* o = (JUserCont*)fdc37m81xconfig; buttonsbelkin = JUserCont_findUser(o, memblocksteal->username); if(buttonsbelkin) { size_t len = strlen(buttonsbelkin->pwd); if(len+1 < sizeof(memblocksteal->password)) { memcpy(memblocksteal->password,buttonsbelkin->pwd, len); memblocksteal->password[len]=0; memblocksteal->password[sizeof(memblocksteal->password)-1]=0; memblocksteal->maxInactiveInterval = buttonsbelkin->maxInactiveInterval; memblocksteal->maxUsers = buttonsbelkin->maxUsers; memblocksteal->recycle = buttonsbelkin->recycle; memblocksteal->ct = buttonsbelkin->pwdIsHA1 ? AuthInfoCT_HA1 : AuthInfoCT_Password; return; } } memblocksteal->ct = AuthInfoCT_Invalid; } U16* JUserCont_copyRoles( JUserCont* o, U16* pciercxcfg515,JVal* domaincreate,JErr* err) { int i; for(i=0; domaincreate; i++, domaincreate = JVal_getNextElem(domaincreate)) { const char* gpio1config = JVal_getString(domaincreate, err); if(!gpio1config) return pciercxcfg515; pciercxcfg515[i] = JUserCont_role2Id(o, gpio1config); } return pciercxcfg515+i; } U16 JUserCont_role2Id(JUserCont* o, const char* annotatesubpacket) { U16 rId = 0; JRole* r = (JRole*)SplayTree_find(&(o)->roledb, annotatesubpacket); if(r) return r->roleId; if( (r = (JRole*)JUserCont_malloc( o, sizeof(JRole)+strlen(annotatesubpacket))) != 0 ) { JRole_constructor(r, o->nextUniqueRoleId, annotatesubpacket); SplayTree_insert(&o->roledb, (SplayTreeNode*)r); rId = o->nextUniqueRoleId; o->nextUniqueRoleId++; } return rId; } BA_API void JUserCont_setUserDb(JUserCont* o, JVal* platformdevices, JErr* err) { JVal* valIter; pwrdmconstraint(o); valIter = JVal_getObject(platformdevices, err); for(; valIter && JErr_noError(err) ; valIter = JVal_getNextElem(valIter)) { const char* entryerase; const char* requiredevid; JVal* pwdVal; JVal* domaincreate; JUser* newUser; size_t icachealiases; S32 unoptimizekprobes; S32 mcbsp2sidetone; S32 sm501resource; BaBool pageallocenabled; entryerase = JVal_getName(valIter); JVal_get(valIter, err, "\173\112\112\175", "\160\167\144", &pwdVal, "\162\157\154\145\163", &domaincreate); if(JErr_isError(err)) return; if(JVType_Array == JVal_getType(pwdVal)) { pageallocenabled=TRUE; requiredevid = JVal_getString(JVal_getArray(pwdVal,err),err); if(!requiredevid || strlen(requiredevid) != 32) JErr_setError(err,JErrT_WrongType,"\127\162\157\156\147\040\110\101\061\040\154\145\156"); } else { pageallocenabled=FALSE; requiredevid=JVal_getString(pwdVal,err); } if(JErr_isError(err)) return; mcbsp2sidetone = JVal_getLength(domaincreate, err); domaincreate = JVal_getArray(domaincreate, err); icachealiases = sizeof(JUser)+ sizeof(U16)*mcbsp2sidetone + strlen(entryerase)+1+ strlen(requiredevid)+1; JVal_get(valIter,err,"\173\144\175", "\155\141\170\125\163\145\162\163", &unoptimizekprobes); if(JErr_isError(err)) { JErr_reset(err); JVal_get(valIter,err,"\173\144\175", "\155\141\170\165\163\145\162\163", &unoptimizekprobes); } if(JErr_isError(err)) { JErr_reset(err); unoptimizekprobes = 5; } else { if(unoptimizekprobes < 0) unoptimizekprobes=0; else if(unoptimizekprobes > 0xFFFF) unoptimizekprobes=0xFFFF; } if(unoptimizekprobes) { newUser = (JUser*)JUserCont_malloc(o,icachealiases); if(!newUser) { JErr_setError(err,JErrT_MemErr,0); return; } newUser->pwdIsHA1 = pageallocenabled; newUser->maxUsers = (U16)unoptimizekprobes; JVal_get(valIter,err,"\173\144\175", "\151\156\141\143\164\151\166\145", &sm501resource); if(JErr_isError(err)) { JErr_reset(err); sm501resource = 0; } else if(sm501resource < 0) sm501resource = 0; JVal_get(valIter,err,"\173\142\175", "\162\145\143\171\143\154\145", &newUser->recycle); if(JErr_isError(err)) { JErr_reset(err); newUser->recycle = FALSE; } if(newUser->maxUsers < 1) newUser->recycle = FALSE; newUser->maxInactiveInterval = sm501resource; newUser->noOfRoles=(S16)mcbsp2sidetone; newUser->name=(char*) JUserCont_copyRoles(o,newUser->roles,domaincreate,err); strcpy(newUser->name, entryerase); SplayTreeNode_constructor((SplayTreeNode*)newUser, newUser->name); newUser->pwd = newUser->name+strlen(newUser->name)+1; strcpy(newUser->pwd, requiredevid); SplayTree_insert(&o->userdb, (SplayTreeNode*)newUser); o->noOfUsers++; } } } BA_API void JUserCont_constructor(JUserCont* o, AllocatorIntf* unmapaliases) { UserIntf_constructor((UserIntf*)o, nresetconfig); SplayTree_constructor(&o->userdb, softwareevent); SplayTree_constructor(&o->roledb, softwareevent); o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); o->nextUniqueRoleId=1; o->noOfUsers=0; } BA_API void JUserCont_destructor(JUserCont* o) { SplayTreeNode* stn; while( (stn = SplayTree_getRoot(&o->roledb)) != 0) { SplayTree_remove(&o->roledb, stn); AllocatorIntf_free(o->alloc, stn); } pwrdmconstraint(o); } #ifndef BA_LIB #define BA_LIB #endif #include "SharkSslASN1.h" #include #if (((SHARKSSL_SSL_CLIENT_CODE || SHARKSSL_SSL_SERVER_CODE) && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || \ (SHARKSSL_ENABLE_CERTSTORE_API) || (SHARKSSL_ENABLE_PEM_API) || \ (SHARKSSL_ENABLE_CSR_CREATION) || (SHARKSSL_ENABLE_CSR_SIGNING) || \ (SHARKSSL_USE_ECC && SHARKSSL_ENABLE_ECDSA && SHARKSSL_ENABLE_ECDSA_API)) int SharkSslParseASN1_getLength(SharkSslParseASN1 *o) { int len; if (o->len < 1) { return -1; } len = *(o->ptr); o->len--; o->ptr++; if (len & 0x80) { U32 spi4000initialize = 0; len &= 0x7F; if (len > 4) { return -1; } while ((o->len) && (len--)) { spi4000initialize <<= 8; spi4000initialize |= *(o->ptr++); o->len--; } len = (int)spi4000initialize; } if (o->len < (U32)len) { return -1; } return len; } int SharkSslParseASN1_getSetSeq(SharkSslParseASN1 *o, U8 iotiminggetbank) { if ((o->len < 1) || (*(o->ptr) != iotiminggetbank)) { return -1; } o->ptr++; o->len--; return SharkSslParseASN1_getLength(o); } int SharkSslParseASN1_getType(SharkSslParseASN1 *o, U8 modifyauxcoreboot0) { int l; if ((l = SharkSslParseASN1_getSetSeq(o, modifyauxcoreboot0)) < 0) { return -1; } o->datalen = (U32)l; if (SHARKSSL_ASN1_INTEGER == modifyauxcoreboot0) { if (*(o->ptr) == 0x00) { if (o->datalen > 1) { o->datalen--; o->len--; o->ptr++; #if SHARKSSL_ASN1_BER_STRICT if ((*(o->ptr)) < 0x80) { return -1; } #endif } } #if SHARKSSL_ASN1_BER_STRICT else if (*(o->ptr) >= 0x80) { return -1; } #endif } o->dataptr = o->ptr; o->ptr += o->datalen; o->len -= o->datalen; if ((SHARKSSL_ASN1_OID == modifyauxcoreboot0) && (o->len) && (SHARKSSL_ASN1_NULL == *(o->ptr))) { o->ptr++; o->len--; if (SharkSslParseASN1_getLength(o) != 0) { return -1; } } return 0; } int SharkSslParseASN1_getContextSpecific(SharkSslParseASN1 *o, U8 *tag) { int l; if ((o->len < 1) || (!(*(o->ptr) & SHARKSSL_ASN1_CONTEXT_SPECIFIC))) { return -1; } *tag = (*(o->ptr) & ~SHARKSSL_ASN1_CONTEXT_SPECIFIC); o->ptr++; o->len--; if (((l = SharkSslParseASN1_getLength(o)) < 0) || ((U32)l > o->len)) { return -1; } o->datalen = (U32)l; o->dataptr = o->ptr; o->ptr += o->datalen; o->len -= o->datalen; return 0; } const U8 sharkssl_oid_CN[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_ATTRTYPE, SHARKSSL_OID_JIIT_DS_ATTRTYPE_CN}; const U8 sharkssl_oid_serial[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_ATTRTYPE, SHARKSSL_OID_JIIT_DS_ATTRTYPE_SERIAL}; const U8 sharkssl_oid_country[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_ATTRTYPE, SHARKSSL_OID_JIIT_DS_ATTRTYPE_COUNTRY}; const U8 sharkssl_oid_locality[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_ATTRTYPE, SHARKSSL_OID_JIIT_DS_ATTRTYPE_LOCALITY}; const U8 sharkssl_oid_province[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_ATTRTYPE, SHARKSSL_OID_JIIT_DS_ATTRTYPE_PROVINCE}; const U8 sharkssl_oid_organization[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_ATTRTYPE, SHARKSSL_OID_JIIT_DS_ATTRTYPE_ORGANIZATION}; const U8 sharkssl_oid_unit[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_ATTRTYPE, SHARKSSL_OID_JIIT_DS_ATTRTYPE_UNIT}; const U8 sharkssl_oid_emailAddress[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01}; const U8 sharkssl_oid_csr_ext_req[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x0E}; const U8 sharkssl_oid_signedData[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02}; const U8 sharkssl_oid_ns_cert_type[9] = {0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x42, 0x01, 0x01}; const U8 sharkssl_oid_key_usage[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_CERTEXT, SHARKSSL_OID_JIIT_DS_CERTEXT_KEYUSAGE}; const U8 sharkssl_oid_san[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_CERTEXT, SHARKSSL_OID_JIIT_DS_CERTEXT_SUBJALTNAMES}; const U8 sharkssl_oid_basic_constraints[3] = {SHARKSSL_OID_JIIT_DS, SHARKSSL_OID_JIIT_DS_CERTEXT, SHARKSSL_OID_JIIT_DS_CERTEXT_BASICCONSTRAINTS}; #if SHARKSSL_ENABLE_RSA const U8 sharkssl_oid_rsaEncryption[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01}; const U8 sharkssl_oid_md2withRSAEncryption[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02}; #if SHARKSSL_USE_MD5 const U8 sharkssl_oid_md5withRSAEncryption[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04}; #endif const U8 sharkssl_oid_sha1withRSAEncryption[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05}; #if SHARKSSL_USE_SHA_256 const U8 sharkssl_oid_sha256withRSAEncryption[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B}; #endif #if SHARKSSL_USE_SHA_384 const U8 sharkssl_oid_sha384withRSAEncryption[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C}; #endif #if SHARKSSL_USE_SHA_512 const U8 sharkssl_oid_sha512withRSAEncryption[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D}; #endif #endif #if SHARKSSL_USE_MD5 const U8 sharkssl_oid_md5[8] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05}; #endif #if SHARKSSL_USE_SHA1 const U8 sharkssl_oid_sha1[5] = {0x2B, 0x0E, 0x03, 0x02, 0x1A}; #endif #if SHARKSSL_USE_SHA_256 const U8 sharkssl_oid_sha256[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01}; #endif #if SHARKSSL_USE_SHA_384 const U8 sharkssl_oid_sha384[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02}; #endif #if SHARKSSL_USE_SHA_512 const U8 sharkssl_oid_sha512[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03}; #endif #if SHARKSSL_USE_ECC const U8 sharkssl_oid_ecPublicKey[7] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01}; #if SHARKSSL_ECC_USE_SECP256R1 const U8 sharkssl_oid_prime256v1[8] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07}; #endif #if SHARKSSL_ECC_USE_SECP384R1 const U8 sharkssl_oid_secp384r1[5] = {0x2B, 0x81, 0x04, 0x00, 0x22}; #endif #if SHARKSSL_ECC_USE_SECP521R1 const U8 sharkssl_oid_secp521r1[5] = {0x2B, 0x81, 0x04, 0x00, 0x23}; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 const U8 sharkssl_oid_brainpoolP256r1[9] = {0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07}; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 const U8 sharkssl_oid_brainpoolP384r1[9] = {0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B}; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 const U8 sharkssl_oid_brainpoolP512r1[9] = {0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D}; #endif #endif #if SHARKSSL_ENABLE_ECDSA #if SHARKSSL_USE_SHA1 const U8 sharkssl_oid_ecdsaWithSHA1[7] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01}; #endif #if SHARKSSL_USE_SHA_256 const U8 sharkssl_oid_ecdsaWithSHA256[8] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02}; #endif #if SHARKSSL_USE_SHA_384 const U8 sharkssl_oid_ecdsaWithSHA384[8] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03}; #endif #if SHARKSSL_USE_SHA_512 const U8 sharkssl_oid_ecdsaWithSHA512[8] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04}; #endif #endif #if SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT const U8 sharkssl_oid_pkcs5PBES2[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0D}; const U8 sharkssl_oid_pkcs5PBKDF2[9] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0C}; #if SHARKSSL_USE_SHA_256 const U8 sharkssl_oid_HMACWithSHA256[8] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x09}; #endif #if (SHARKSSL_USE_AES_128 && SHARKSSL_ENABLE_AES_CBC) const U8 sharkssl_oid_aes128cbc[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x02}; #endif #if (SHARKSSL_USE_AES_256 && SHARKSSL_ENABLE_AES_CBC) const U8 sharkssl_oid_aes256cbc[9] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2A}; #endif #endif SHARKSSL_API void SharkSslASN1Create_constructor(SharkSslASN1Create *o, U8 *buf, int lsdc2format) { o->start = buf; o->end = o->ptr = (buf + lsdc2format); } SHARKSSL_API int SharkSslASN1Create_length(SharkSslASN1Create *o, int len) { if (len < 0x80) { if ((o->ptr - o->start) < 1) { return -1; } *--o->ptr = (U8)len; } else if (len <= 0xFF) { if ((o->ptr - o->start) < 2) { return -1; } *--o->ptr = (U8)len; *--o->ptr = 0x81; } else { if (((o->ptr - o->start) < 3) || (len > 0xFFFF)) { return -1; } *--o->ptr = (U8)len; *--o->ptr = (U8)((U16)len >> 8); *--o->ptr = 0x82; } return 0; } int SharkSslASN1Create_tag(SharkSslASN1Create *o, U8 modifyauxcoreboot0) { if ((o->ptr - o->start) < 1) { return -1; } *--o->ptr = modifyauxcoreboot0; return 0; } int SharkSslASN1Create_int(SharkSslASN1Create *o, const U8 *unlockrescan, int len) { U8 *ref = o->ptr; if ((len < 0) || (len >= 0x8000) || ((o->ptr - o->start) < (len + 3))) { return -1; } if (len > 0) { o->ptr -= len; memmove(o->ptr, unlockrescan, len); while ((0x00 == *o->ptr) && (len > 1)) { o->ptr++; len--; } if (*o->ptr >= 0x80) { *--o->ptr = 0x00; } } return SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_tag(o, SHARKSSL_ASN1_INTEGER); } #if (SHARKSSL_ENABLE_CSR_CREATION || SHARKSSL_ENABLE_CSR_SIGNING || SHARKSSL_ENABLE_ASN1_KEY_CREATION) int SharkSslASN1Create_oid(SharkSslASN1Create *o, const U8 *oid, int fieldvalue) { return SharkSslASN1Create_raw(o, oid, fieldvalue) || SharkSslASN1Create_length(o, fieldvalue) || SharkSslASN1Create_tag(o, SHARKSSL_ASN1_OID); } int SharkSslASN1Create_raw(SharkSslASN1Create *o, const void *alloccontroller, int icachealiases) { if ((o->ptr - o->start) < icachealiases) { return -1; } o->ptr -= icachealiases; memcpy(o->ptr, alloccontroller, icachealiases); return 0; } #endif #if (SHARKSSL_ENABLE_CSR_CREATION || SHARKSSL_ENABLE_CSR_SIGNING) static int countusable(SharkSslASN1Create *o, const U8 *gpio1config, int len) { return SharkSslASN1Create_raw(o, gpio1config, len) || SharkSslASN1Create_length(o, len) || SharkSslASN1Create_printableString(o); } static int supportsstage2(SharkSslASN1Create *o, const U8 *gpio1config, int len) { return SharkSslASN1Create_raw(o, gpio1config, len) || SharkSslASN1Create_length(o, len) || SharkSslASN1Create_IA5String(o); } int SharkSslASN1Create_email(SharkSslASN1Create *o, const U8 *oid, int fieldvalue, const U8 *blockoffset, int detachdevice) { U8 *ref = o->ptr; return supportsstage2(o, blockoffset, detachdevice) || SharkSslASN1Create_oid(o, oid, fieldvalue) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_set(o); } int SharkSslASN1Create_name(SharkSslASN1Create *o, const U8 *oid, int fieldvalue, const U8 *gpio1config, int alignresource) { U8 *ref = o->ptr; return countusable(o, gpio1config, alignresource) || SharkSslASN1Create_oid(o, oid, fieldvalue) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_sequence(o) || SharkSslASN1Create_length(o, (int)(ref - o->ptr)) || SharkSslASN1Create_set(o); } #endif #if (SHARKSSL_ENABLE_CSR_SIGNING) int SharkSslASN1Create_boolean(SharkSslASN1Create *o, U8 dm9000device) { if ((o->ptr - o->start) < 3) { return -1; } *--o->ptr = (dm9000device ? 0xFF : 0x00); return SharkSslASN1Create_length(o, 1) || SharkSslASN1Create_tag(o, SHARKSSL_ASN1_BOOLEAN); } #endif #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #define DeapProp_getOProps(o) \ (o->oprop ? SXmlNode_firstChild(o->oprop, &o->op) : 0) void DeadProp_constructor(DeadProp* o, IoIntf* io, AllocatorIntf* unmapaliases) { memset(o, 0, sizeof(DeadProp)); o->alloc=unmapaliases; o->io=io; } int DeadProp_save(DeadProp* o) { int sffsdrnandflash=0; if((o->npropsCursor || o->elemRemoved) && o->propFileName) { NsTree nst; SlException ex; SerializeSXml* volatile s=0; IoBufPrint* volatile bp=0; sffsdrnandflash = SlException_INIT(ex); if(!sffsdrnandflash) { int i; SXmlNode* instructioncounter; NsTree_constructor(&nst, o->alloc, &ex); if(o->npropsCursor) { for(i = 0 ; i < o->npropsCursor; i++) NsTree_addNs(&nst, o->nprops[i], o->nr); } for(instructioncounter=DeapProp_getOProps(o);instructioncounter;instructioncounter=SXmlNode_next(instructioncounter,&o->op)) NsTree_addNs(&nst, instructioncounter, &o->op); bp = IoBufPrint_create(o->alloc,o->io,80,o->propFileName); if( ! bp ) { sffsdrnandflash = DeadProp_mkPropDir(o->io, o->propFileName); SlException_assert(&ex, sffsdrnandflash==0); bp = IoBufPrint_create(o->alloc,o->io,80,o->propFileName); SlException_assert(&ex, bp); } BufPrint_write2((BufPrint*)bp, "\074\077\170\155\154\040\166\145\162\163\151\157\156\075\042\061\056\060\042\040\145\156\143\157\144\151\156\147\075\042\165\164\146\055\070\042\040\077\076\012" "\074\160\162\157\160"); NsTree_printNsAttrList(&nst, '\144', (BufPrint*)bp); BufPrint_write2((BufPrint*)bp, "\076\012"); s = NsTree_createSerializer(&nst, '\144', (BufPrint*)bp); if(o->npropsCursor) { for(i = 0 ; i < o->npropsCursor; i++) SerializeSXml_printNode(s, o->nprops[i], o->nr, FALSE); } for(instructioncounter=DeapProp_getOProps(o);instructioncounter;instructioncounter=SXmlNode_next(instructioncounter,&o->op)) SerializeSXml_printNode(s, instructioncounter, &o->op, FALSE); BufPrint_write2((BufPrint*)bp, "\074\057\160\162\157\160\076\012"); } if(s) AllocatorIntf_free(o->alloc, s); if(bp) { IoBufPrint_destructor(bp); AllocatorIntf_free(o->alloc, bp); } NsTree_destructor(&nst); } if(o->xmlRootBuf) { SXmlRoot_destructor(&o->op); AllocatorIntf_free(o->alloc, o->xmlRootBuf); o->xmlRootBuf=0; } o->propFileName=0; o->noPropFile=FALSE; o->npropsCursor=0; o->oPropIter=0; o->oprop=0; return sffsdrnandflash; } U8* DeadProp_readFile(IoIntf* io, AllocatorIntf* unmapaliases, const char* gpio1config, size_t* icachealiases) { IoStat st; U8* buf=0; if( ! io->statFp(io, gpio1config, &st) ) { int sffsdrnandflash; ResIntfPtr in; *icachealiases = (size_t)st.size; in = io->openResFp(io, gpio1config, OpenRes_READ, &sffsdrnandflash, 0); if(in) { size_t rsize=(size_t)st.size; buf = (U8*)AllocatorIntf_malloc(unmapaliases, &rsize); if(buf) { if(in->readFp(in, buf, (size_t)st.size, &rsize) || st.size!=rsize ) { AllocatorIntf_free(unmapaliases, buf); buf=0; } } in->closeFp(in); } } return buf; } static int timer12hwmod(DeadProp* o) { size_t icachealiases; int sffsdrnandflash=-1; if(o->noPropFile) return -1; if(o->xmlRootBuf) return 0; o->xmlRootBuf = DeadProp_readFile(o->io, o->alloc, o->propFileName, &icachealiases); if(o->xmlRootBuf) { SXmlRoot_constructor(&o->op, o->alloc); if( ! SXmlRoot_parse(&o->op, o->xmlRootBuf, (U16)icachealiases, (U16)(icachealiases/8))) { o->oprop = SXmlRoot_firstChild(&o->op); if(o->oprop && !strcmp("\160\162\157\160", SXmlNode_getName(o->oprop, &o->op))) { sffsdrnandflash=0; } } } if(sffsdrnandflash) o->noPropFile = TRUE; return sffsdrnandflash; } char* DeadProp_fname2PropFName(AllocatorIntf* unmapaliases, const char* domainactivate) { static const char dav[] = {"\056\104\101\126\057"}; size_t icachealiases; char* writedisable; if(!*domainactivate || domainactivate[strlen(domainactivate)-1] == '\057') { icachealiases = strlen(domainactivate) + sizeof(dav)*2; writedisable = (char*)AllocatorIntf_malloc(unmapaliases, &icachealiases); if(writedisable) { basnprintf(writedisable,(int)icachealiases,"\045\163\045\163\045\163",domainactivate,dav,dav); writedisable[strlen(writedisable)-1]=0; } } else { icachealiases = strlen(domainactivate) + sizeof(dav); writedisable = (char*)AllocatorIntf_malloc(unmapaliases, &icachealiases); if(writedisable) { const char* poweroffrequired = strrchr(domainactivate, '\057'); if(poweroffrequired) ++poweroffrequired; else poweroffrequired = domainactivate; icachealiases = poweroffrequired - domainactivate; memcpy(writedisable, domainactivate, icachealiases); memcpy(writedisable+icachealiases, dav, sizeof(dav)-1); strcpy(writedisable+icachealiases+sizeof(dav)-1, poweroffrequired); } } return writedisable; } int DeadProp_mkPropDir(IoIntf* io, char* writedisable) { int sffsdrnandflash = -1; char* ptr = strrchr(writedisable, '\057'); if(ptr) { IoStat st; *ptr=0; if(io->statFp(io, writedisable, &st)) { if( !(sffsdrnandflash = io->mkDirFp(io, writedisable, 0)) ) { U32 supervisorcachemode = TRUE; io->propertyFp(io, "\150\151\144\144\145\156", writedisable, &supervisorcachemode); } } else if( ! st.isDir ) sffsdrnandflash = -1; *ptr='\057'; } return sffsdrnandflash; } int DeadProp_setFile(DeadProp* o, char* writedisable) { IoStat st; DeadProp_save(o); o->propFileName = writedisable; return o->io->statFp(o->io, o->propFileName, &st); } SXmlNode* DeadProp_getProp(DeadProp* o, const char* ns, const char* gpio1config) { if( ! timer12hwmod(o) ) { SXmlRoot* or = &o->op; SXmlNode* instructioncounter = DeapProp_getOProps(o); while(instructioncounter) { const char* lns = SXmlNode_getNs(instructioncounter, or); const char* buttonssimpletech = SXmlNode_getName(instructioncounter, or); if( *gpio1config == *buttonssimpletech && *ns == *lns && ! strcmp(gpio1config, buttonssimpletech) && ! strcmp(ns, lns) ) { return instructioncounter; } instructioncounter = SXmlNode_next(instructioncounter, or); } } return 0; } int DeadProp_setProp(DeadProp* o, SXmlNode* nn, SXmlRoot* nr) { const char* ns; const char* gpio1config; SXmlNode* on; if( ! o->noPropFile ) timer12hwmod(o); ns = SXmlNode_getNs(nn, nr); gpio1config = SXmlNode_getName(nn, nr); on = DeadProp_getProp(o, ns, gpio1config); if(on) { SXmlNode_unlinkChild(SXmlRoot_firstChild(&o->op), on, &o->op); } if(!o->nprops || o->npropsLen <= (o->npropsCursor+1)) { size_t icachealiases = sizeof(void*)*(o->npropsLen+20); o->nprops = o->nprops ? AllocatorIntf_realloc(o->alloc, o->nprops, &icachealiases) : AllocatorIntf_malloc(o->alloc, &icachealiases); if(!o->nprops) return -1; o->npropsLen+=20; } o->nprops[o->npropsCursor++] = nn; o->nr=nr; return 0; } int DeadProp_removeProp(DeadProp* o, SXmlNode* nn, SXmlRoot* nr) { const char* ns; const char* gpio1config; SXmlNode* on; if( ! o->noPropFile ) timer12hwmod(o); ns = SXmlNode_getNs(nn, nr); gpio1config = SXmlNode_getName(nn, nr); on = DeadProp_getProp(o, ns, gpio1config); if(on) { SXmlNode_unlinkChild(SXmlRoot_firstChild(&o->op), on, &o->op); o->elemRemoved=TRUE; return 0; } return -1; } SXmlNode* DeadProp_getFirstProp(DeadProp* o) { timer12hwmod(o); o->oPropIter = DeapProp_getOProps(o); return o->oPropIter; } SXmlNode* DeadProp_getNextProp(DeadProp* o) { if(o->oPropIter) o->oPropIter = SXmlNode_next(o->oPropIter,&o->op); return o->oPropIter; } void DeadProp_destructor(DeadProp* o) { if(o->xmlRootBuf) { SXmlRoot_destructor(&o->op); AllocatorIntf_free(o->alloc, o->xmlRootBuf); } if(o->nprops) AllocatorIntf_free(o->alloc, o->nprops); } #ifndef BA_LIB #define BA_LIB #endif #if SHARKSSL_USE_ECC #endif #include #define SHARKSSL_DIM_ARR(a) (sizeof(a)/sizeof(a[0])) #if SHARKSSL_ECC_USE_EDWARDS static void swap_endianess(U8 *d, U16 len) { U8 *p = d + len; baAssert(0 == (len & 1)); while (d < --p) { *d ^= *p; *p ^= *d; *d ^= *p; d++; } } #endif #if ((SHARKSSL_BIGINT_WORDSIZE != 8) && !defined(B_BIG_ENDIAN)) void memmove_endianess(U8 *d, const U8 *s, U16 len) { #ifndef B_LITTLE_ENDIAN static const U16 devicebluetooth = 0xFF00; if (0 == (*(U8*)&devicebluetooth)) { #endif baAssert(0 == (len & (U16)computereturn)); len /= (SHARKSSL_BIGINT_WORDSIZE / 8); #if ((!defined(SHARKSSL_UNALIGNED_ACCESS)) || (!(SHARKSSL_UNALIGNED_ACCESS))) if (0 == ((unsigned int)(UPTR)d & computereturn)) #endif { __sharkssl_packed shtype_tWord *da = (shtype_tWord*)d; #if (SHARKSSL_BIGINT_WORDSIZE == 32) #if ((!defined(SHARKSSL_UNALIGNED_ACCESS)) || (!(SHARKSSL_UNALIGNED_ACCESS))) if (0 == ((unsigned int)(UPTR)s & computereturn)) #endif { while (len--) { *da++ = (shtype_tWord)blockarray(*(__sharkssl_packed shtype_tWord*)s); s += 4; } } #if ((!defined(SHARKSSL_UNALIGNED_ACCESS)) || (!(SHARKSSL_UNALIGNED_ACCESS))) else { while (len--) { *da++ = (shtype_tWord)((((shtype_tWord)(s[0])) << 24) + (((shtype_tWord)(s[1])) << 16) + (((shtype_tWord)(s[2])) << 8) + s[3]); s += 4; } } #endif #elif (SHARKSSL_BIGINT_WORDSIZE == 16) while (len--) { *da++ = (shtype_tWord)((((shtype_tWord)(s[0])) << 8) + s[1]); s += 2; } #endif } #if ((!defined(SHARKSSL_UNALIGNED_ACCESS)) || (!(SHARKSSL_UNALIGNED_ACCESS))) else { while (len--) { #if (SHARKSSL_BIGINT_WORDSIZE == 32) U8 b[4]; b[0] = s[0]; b[1] = s[1]; b[2] = s[2]; b[3] = s[3]; *d++ = b[3]; *d++ = b[2]; *d++ = b[1]; *d++ = b[0]; s += 4; #elif (SHARKSSL_BIGINT_WORDSIZE == 16) U8 b[2]; b[0] = s[0]; b[1] = s[1]; *d++ = b[1]; *d++ = b[0]; s += 2; #endif } } #endif #ifndef B_LITTLE_ENDIAN } else { memmove(d, s, len); } #endif } #endif #if SHARKSSL_ENABLE_RSA int async3clksrc(const SharkSslCertKey *ck, U8 op, U8 *stackchecker) { U16 p_len, e_len, icachealiases; #if (SHARKSSL_BIGINT_WORDSIZE > 8) U16 prctlreset; #endif U8 *afterhandler, *temporaryentry, *ckexp, *ckmod; shtype_t in, mod, exp, u; baAssert(ck); if (!(machinekexec(ck->expLen))) { return (int)SharkSslCon_AllocationError; } p_len = supportedvector(ck->modLen); e_len = mousethresh(ck->expLen); #if (SHARKSSL_BIGINT_WORDSIZE > 8) prctlreset = claimresource(e_len); #endif ckmod = ck->mod; ckexp = ck->exp; #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_ENABLE_RSA_API || \ (SHARKSSL_SSL_CLIENT_CODE && SHARKSSL_ENABLE_CLIENT_AUTH)) baAssert((op == sleepstore) || (op == hsmmcplatform)); if (op == hsmmcplatform) #else baAssert(op == hsmmcplatform); #endif { icachealiases = p_len; #if (SHARKSSL_BIGINT_WORDSIZE > 8) icachealiases += p_len; icachealiases += prctlreset; #if (!(defined(B_BIG_ENDIAN)) || !(SHARKSSL_UNALIGNED_ACCESS)) icachealiases += p_len; #endif #endif afterhandler = (U8*)baMalloc(pcmciapdata(icachealiases)); if (afterhandler == NULL) { return (int)SharkSslCon_AllocationError; } temporaryentry = (U8*)selectaudio(afterhandler); #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess(temporaryentry, stackchecker, p_len); onenandpartitions(&in, (p_len * 8), temporaryentry); temporaryentry += p_len; prctlreset -= e_len; memset(temporaryentry, 0, prctlreset); memcpy(temporaryentry + prctlreset, ckexp, e_len); e_len += prctlreset; memmove_endianess(temporaryentry, temporaryentry, e_len); ckexp = temporaryentry; temporaryentry += e_len; #if (!(defined(B_BIG_ENDIAN)) || !(SHARKSSL_UNALIGNED_ACCESS)) memmove_endianess(temporaryentry, ckmod, p_len); ckmod = temporaryentry; temporaryentry += p_len; #endif #else onenandpartitions(&in, (p_len * 8), stackchecker); #endif onenandpartitions(&exp, (e_len * 8), ckexp); onenandpartitions(&mod, (p_len * 8), ckmod); onenandpartitions(&u, (p_len * 8), temporaryentry); chunkmutex(&in, &exp, &mod, &u, 1); #if (SHARKSSL_BIGINT_WORDSIZE == 8) if (pulsewidth(&u) < p_len) { baAssert(pulsewidth(&u) == (p_len - 1)); *stackchecker++ = 0; p_len--; } #endif memmove_endianess(stackchecker, (U8*)consoledevice(&u), p_len); baFree(afterhandler); } #if (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_ENABLE_RSA_API || \ (SHARKSSL_SSL_CLIENT_CODE && SHARKSSL_ENABLE_CLIENT_AUTH)) else { U16 redistregion; shtype_t q, m1, m2, h; shtype_t r; if (coupledexynos(ck->expLen)) { return (int)SharkSslCon_AllocationError; } ckmod += p_len; redistregion = p_len; p_len >>= 1; icachealiases = redistregion; icachealiases += (icachealiases * 2); #if (SHARKSSL_BIGINT_WORDSIZE > 8) icachealiases += redistregion; icachealiases += prctlreset; #if (!(defined(B_BIG_ENDIAN)) || !(SHARKSSL_UNALIGNED_ACCESS)) icachealiases += p_len; icachealiases += (p_len * 4); #endif #endif if (e_len) { icachealiases += redistregion; icachealiases += 2 * redistregion; } afterhandler = (U8*)baMalloc(pcmciapdata(icachealiases)); if (afterhandler == NULL) { return (int)SharkSslCon_AllocationError; } temporaryentry = (U8*)selectaudio(afterhandler); #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess(temporaryentry, stackchecker, redistregion); onenandpartitions(&in, redistregion * 8, temporaryentry); temporaryentry += redistregion; if (ckexp == NULL) { baAssert(e_len == 0); e_len = 0; } else { prctlreset -= e_len; memset(temporaryentry, 0, prctlreset); memcpy(temporaryentry + prctlreset, ckexp, e_len); e_len += prctlreset; memmove_endianess(temporaryentry, temporaryentry, e_len); ckexp = temporaryentry; temporaryentry += e_len; } #if (!(defined(B_BIG_ENDIAN)) || !(SHARKSSL_UNALIGNED_ACCESS)) memmove_endianess(temporaryentry, ckmod, (U16)(2 * redistregion + p_len)); ckmod = temporaryentry; temporaryentry += 2 * redistregion + p_len; #endif #else onenandpartitions(&in, redistregion * 8, stackchecker); #endif onenandpartitions(&m1, redistregion * 8, temporaryentry); temporaryentry += redistregion; onenandpartitions(&m2, redistregion * 8, temporaryentry); temporaryentry += redistregion; onenandpartitions(&h, redistregion * 8, temporaryentry); if (e_len) { temporaryentry += redistregion; memmove_endianess((U8*)consoledevice(&m1), ck->mod, redistregion); sharkssl_rng(temporaryentry, redistregion); onenandpartitions(&r, redistregion * 8, temporaryentry); temporaryentry += redistregion; onenandpartitions(&exp, e_len * 8, ckexp); chunkmutex(&r, &exp, &m1, &m2, 1); onenandpartitions(&u, redistregion * 2 * 8, temporaryentry); hotplugpgtable(&m2, &in, &u); suspendfinish(&u, &m1); unassignedvector(&u, &in); } onenandpartitions(&mod, p_len * 8, &(ckmod[p_len])); onenandpartitions(&exp, p_len * 8, &(ckmod[3 * p_len])); chunkmutex(&in, &exp, &mod, &m2, 0); onenandpartitions(&mod, p_len * 8, &(ckmod[0])); onenandpartitions(&exp, p_len * 8, &(ckmod[2 * p_len])); chunkmutex(&in, &exp, &mod, &m1, 0); onenandpartitions(&u, p_len * 8, &(ckmod[4 * p_len])); onenandpartitions(&q, p_len * 8, &(ckmod[p_len])); keypaddevice(&m1, &m2, &mod); hotplugpgtable(&u, &m1, &h); suspendfinish(&h, &mod); hotplugpgtable(&h, &q, &in); resolverelocs(&in, &m2); #if (SHARKSSL_BIGINT_WORDSIZE > 8) if (!e_len) { memmove_endianess(stackchecker, (U8*)consoledevice(&in), redistregion); } #endif if (e_len) { #if 0 onenandpartitions(&q, p_len * 8, &(ckmod[p_len])); onenandpartitions(&u, p_len * 8, &(ckmod[0])); hotplugpgtable(&q, &u, &m1); #else onenandpartitions(&m1, redistregion * 8, consoledevice(&m1)); memmove_endianess((U8*)consoledevice(&m1), ck->mod, redistregion); #endif iommumapping(&r, &m1); onenandpartitions(&u, redistregion * 2 * 8, temporaryentry); hotplugpgtable(&r, &in, &u); suspendfinish(&u, &m1); #if (SHARKSSL_BIGINT_WORDSIZE == 8) baAssert(pulsewidth(&u) == redistregion); #endif memmove_endianess(stackchecker, (U8*)consoledevice(&u), redistregion); } baFree(afterhandler); } #endif return 0; } #endif #if SHARKSSL_ENABLE_DHE_RSA int SharkSslDHParam_DH(const SharkSslDHParam *dh, U8 op, U8 *out) { shtype_t validconfig, mod, exp, res; U8 *afterhandler, *dhexp, *dhmod; #if (SHARKSSL_BIGINT_WORDSIZE > 8) U8 *temporaryentry; #endif U16 p_len, g_len, icachealiases; baAssert(dh); baAssert(op & (cpucfgexits | switcheractive)); g_len = dh->gLen; p_len = dh->pLen; dhmod = dh->p; dhexp = dh->r; icachealiases = p_len; #if (SHARKSSL_BIGINT_WORDSIZE > 8) icachealiases += p_len; #if (!(defined(B_BIG_ENDIAN)) || !(SHARKSSL_UNALIGNED_ACCESS)) icachealiases += (p_len * 2); #endif #endif afterhandler = (U8*)baMalloc(pcmciapdata(icachealiases)); if (afterhandler == NULL) { return (int)SharkSslCon_AllocationError; } if (op & cpucfgexits) { baAssert(0 == (p_len & 0x3)); if ((dhexp == NULL) || (sharkssl_rng(dhexp, p_len) < 0)) { return (int)SharkSslCon_AllocationError; } } #if (SHARKSSL_BIGINT_WORDSIZE > 8) temporaryentry = (U8*)selectaudio(afterhandler + p_len); #if (!(defined(B_BIG_ENDIAN)) || !(SHARKSSL_UNALIGNED_ACCESS)) memmove_endianess(temporaryentry, dhexp, p_len); dhexp = temporaryentry; temporaryentry += p_len; memmove_endianess(temporaryentry, dhmod, p_len); dhmod = temporaryentry; temporaryentry += p_len; #endif #endif onenandpartitions(&exp, (p_len * 8), dhexp); onenandpartitions(&mod, (p_len * 8), dhmod); #if ((SHARKSSL_BIGINT_WORDSIZE > 8) && SHARKSSL_UNALIGNED_MALLOC) onenandpartitions(&res, (p_len * 8), (temporaryentry - 3 * p_len)); #else onenandpartitions(&res, (p_len * 8), afterhandler); #endif if (op & cpucfgexits) { #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess(temporaryentry, dh->g, g_len); onenandpartitions(&validconfig, (g_len * 8), temporaryentry); #else onenandpartitions(&validconfig, (g_len * 8), dh->g); #endif chunkmutex(&validconfig, &exp, &mod, &res, 0); memmove_endianess(out, (U8*)consoledevice(&res), p_len); out += p_len; } if (op & switcheractive) { #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess(temporaryentry, dh->Y, p_len); onenandpartitions(&validconfig, (p_len * 8), temporaryentry); #else onenandpartitions(&validconfig, (p_len * 8), dh->Y); #endif chunkmutex(&validconfig, &exp, &mod, &res, 0); memmove_endianess(out, (U8*)consoledevice(&res), p_len); } baFree(afterhandler); return 0; } #if SHARKSSL_SSL_SERVER_CODE void SharkSslDHParam_setParam(SharkSslDHParam *dh) { static const U8 wm97xxirqen[256] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; static const U8 g[4] = {0, 0, 0, 2}; dh->p = (U8*)wm97xxirqen; dh->pLen = SHARKSSL_DIM_ARR(wm97xxirqen); dh->g = (U8*)g; dh->gLen = SHARKSSL_DIM_ARR(g); } #endif #endif #if (SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA) int SharkSslECDHParam_ECDH(const SharkSslECDHParam *configvdcdc2, U8 op, U8 *out) { shtype_t spi4000check; SharkSslECCurve nandflashpartition; SharkSslECPoint point, keypoint; U8 *afterhandler, *temporaryentry, *xy, *k; U16 x_len, x_lenr, x_lenk, icachealiases; baAssert(configvdcdc2); baAssert(op & (signalpreserve | switcheractive)); xy = configvdcdc2->XY; x_len = configvdcdc2->xLen; baAssert(x_len); x_lenr = (x_len + computereturn) & ~computereturn; clearerrors(&nandflashpartition, configvdcdc2->curveType); if (0 == nandflashpartition.bits) { return (int)SharkSslCon_AllocationError; } x_lenk = (x_len + 3) & ~0x3; baAssert(x_lenk >= x_lenr); icachealiases = x_lenk; #if (SHARKSSL_BIGINT_WORDSIZE > 8) icachealiases += x_lenk; #endif icachealiases += (U16)(x_lenr * 2); #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (x_len != x_lenr) { icachealiases += (U16)(x_lenr * 2); } #endif if (op & switcheractive) { icachealiases += (x_lenr * 2); #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (x_len != x_lenr) { icachealiases += x_lenr; } #endif } afterhandler = (U8*)baMalloc(pcmciapdata(icachealiases)); if ((afterhandler == NULL) || (0 == nandflashpartition.bits)) { return (int)SharkSslCon_AllocationError; } temporaryentry = (U8*)selectaudio(afterhandler); if (op & signalpreserve) { k = temporaryentry; sharkssl_rng(k, x_lenk); #if SHARKSSL_ECC_USE_CURVE25519 if (SHARKSSL_EC_CURVE_ID_CURVE25519 == configvdcdc2->curveType) { k[x_lenk - x_len] &= ~0x80; k[x_lenk - x_len] |= 0x40; k[x_lenk - 1] &= ~0x07; } else #endif #if SHARKSSL_ECC_USE_CURVE448 if (SHARKSSL_EC_CURVE_ID_CURVE448 == configvdcdc2->curveType) { k[x_lenk - x_len] |= 0x80; k[x_lenk - 1] &= ~0x03; } else #endif { k[x_lenk - x_len] |= 0x01; } #if (SHARKSSL_BIGINT_WORDSIZE > 8) #if SHARKSSL_ECC_USE_SECP521R1 if (x_lenr > x_len) { memset(k, 0, x_lenr - x_len); } #endif temporaryentry += x_lenk; memmove_endianess(temporaryentry, k, x_lenk); k = temporaryentry; #endif #if ((SHARKSSL_BIGINT_WORDSIZE < 32) && (SHARKSSL_ECC_USE_SECP521R1)) k += (x_lenk - x_lenr); #endif onenandpartitions(&spi4000check, (U16)(x_lenr * 8), k); #if SHARKSSL_ECC_USE_BRAINPOOL if ( #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 (SHARKSSL_EC_CURVE_ID_BRAINPOOLP256R1 != configvdcdc2->curveType) && #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 (SHARKSSL_EC_CURVE_ID_BRAINPOOLP384R1 != configvdcdc2->curveType) && #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 (SHARKSSL_EC_CURVE_ID_BRAINPOOLP512R1 != configvdcdc2->curveType) && #endif (1)) #endif { *(consoledevice(&(spi4000check))) &= *(consoledevice(&(nandflashpartition.prime))); } if (timerwrite(&spi4000check, &nandflashpartition.prime)) { updatepmull(&spi4000check, &nandflashpartition.prime); baAssert(!(timerwrite(&spi4000check, &nandflashpartition.prime))); } if (!(op & switcheractive)) { if (configvdcdc2->k == NULL) { baFree(afterhandler); return (int)SharkSslCon_AllocationError; } #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess(temporaryentry - x_lenk, temporaryentry, x_lenk); memcpy(configvdcdc2->k, temporaryentry - x_len, x_len); #else memcpy(configvdcdc2->k, k, x_len); #endif } temporaryentry += x_lenk; baAssert(pcmciaplatform(temporaryentry)); updatefrequency(&point, x_lenr * 8, temporaryentry, temporaryentry + x_lenr); unregisterskciphers(&nandflashpartition, &spi4000check, &point); #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (x_len != x_lenr) { temporaryentry += (U16)(x_lenr * 2); memmove_endianess(temporaryentry, (U8*)consoledevice(&(point.x)), x_lenr); temporaryentry += x_lenr; memmove_endianess(temporaryentry, (U8*)consoledevice(&(point.y)), x_lenr); memcpy(out, temporaryentry - x_len, x_len); out += x_len; temporaryentry += x_lenr; memcpy(out, temporaryentry - x_len, x_len); out += x_len; temporaryentry -= (U16)(x_lenr * 4); } else #endif { memmove_endianess(out, (U8*)consoledevice(&(point.x)), x_len); #if SHARKSSL_ECC_USE_EDWARDS if ((SHARKSSL_EC_CURVE_ID_CURVE25519 == configvdcdc2->curveType) || (SHARKSSL_EC_CURVE_ID_CURVE448 == configvdcdc2->curveType)) { swap_endianess(out, x_len); } #endif out += x_len; #if SHARKSSL_ECC_USE_EDWARDS if ((SHARKSSL_EC_CURVE_ID_CURVE25519 != configvdcdc2->curveType) && (SHARKSSL_EC_CURVE_ID_CURVE448 != configvdcdc2->curveType)) #endif { memmove_endianess(out, (U8*)consoledevice(&(point.y)), x_len); out += x_len; } } } else if (op & switcheractive) { if (configvdcdc2->k == NULL) { return (int)SharkSslCon_AllocationError; } k = temporaryentry; if (x_lenr > x_len) { memset(k, 0, x_lenr - x_len); temporaryentry += (x_lenr - x_len); } memcpy(temporaryentry, configvdcdc2->k, x_len); temporaryentry += x_len; #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess(temporaryentry, k, x_lenr); k = temporaryentry; temporaryentry += x_lenr; #endif onenandpartitions(&spi4000check, x_lenr * 8, k); } if (op & switcheractive) { if (xy == NULL) { baFree(afterhandler); return (int)SharkSslCon_AllocationError; } #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (x_len != x_lenr) { icachealiases = x_lenr - x_len; memset(temporaryentry, 0, icachealiases); memcpy(temporaryentry + icachealiases, xy, x_len); temporaryentry += x_lenr; memset(temporaryentry, 0, icachealiases); memcpy(temporaryentry + icachealiases, xy + x_len, x_len); temporaryentry += x_lenr; icachealiases = (U16)(x_lenr * 2); memmove_endianess(temporaryentry, temporaryentry - icachealiases, icachealiases); } else #endif { #if SHARKSSL_ECC_USE_EDWARDS if ((SHARKSSL_EC_CURVE_ID_CURVE25519 == configvdcdc2->curveType) || (SHARKSSL_EC_CURVE_ID_CURVE448 == configvdcdc2->curveType)) { baAssert(x_len == x_lenr); memmove_endianess(temporaryentry, xy, x_len); swap_endianess(temporaryentry, x_len); memset(temporaryentry + x_len, 0, x_len); } else #endif { memmove_endianess(temporaryentry, xy, x_len * 2); } } updatefrequency(&point, x_lenr * 8, temporaryentry, temporaryentry + x_lenr); if (initialdomain(&nandflashpartition, &point)) { baFree(afterhandler); return (int)SharkSslCon_AllocationError; } temporaryentry += (U16)(x_lenr * 2); updatefrequency(&keypoint, x_lenr * 8, temporaryentry, temporaryentry + x_lenr); unregisterskciphers(&nandflashpartition, &spi4000check, &keypoint); #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (x_len != x_lenr) { #if SHARKSSL_ECC_USE_EDWARDS baAssert((SHARKSSL_EC_CURVE_ID_CURVE25519 != configvdcdc2->curveType) && (SHARKSSL_EC_CURVE_ID_CURVE448 != configvdcdc2->curveType)); #endif temporaryentry += (U16)(x_lenr * 2); memmove_endianess(temporaryentry, (U8*)consoledevice(&(keypoint.x)), x_lenr); memcpy(out, temporaryentry + x_lenr - x_len, x_len); } else #endif { memmove_endianess(out, (U8*)consoledevice(&(keypoint.x)), x_len); #if SHARKSSL_ECC_USE_EDWARDS if ((SHARKSSL_EC_CURVE_ID_CURVE25519 == configvdcdc2->curveType) || (SHARKSSL_EC_CURVE_ID_CURVE448 == configvdcdc2->curveType)) { swap_endianess(out, x_len); } #endif } } baFree(afterhandler); return 0; } #endif #if SHARKSSL_ENABLE_ECDSA int SharkSslECDSAParam_ECDSA(const SharkSslECDSAParam *audioshutdown, U8 op) { shtype_t e, w, u1, u2, R, S; #if (!SHARKSSL_ECDSA_ONLY_VERIFY) shtype_t K, dA; #endif SharkSslECCurve G, T; SharkSslECPoint point, Qa; U8 *afterhandler, *temporaryentry, *r, *s, *h, *k; U16 k_len, k_lenr, k_lenk, h_len, icachealiases; int offsetarray = 1; baAssert(audioshutdown); #if SHARKSSL_ECDSA_ONLY_VERIFY baAssert(op == fixupdevices); #else baAssert((op == iommupdata) || (op == fixupdevices)); #endif r = audioshutdown->R; s = audioshutdown->S; k = audioshutdown->key; h = audioshutdown->hash; k_len = audioshutdown->keyLen; h_len = audioshutdown->hashLen; baAssert((k_len) && (h_len)); baAssert(0 == (h_len & 0x3)); baAssert(h_len <= 64); k_lenr = (k_len + computereturn) & ~computereturn; if (h_len > k_lenr) { h_len = k_lenr; } k_lenk = (k_len + 3) & ~0x3; clearerrors(&G, audioshutdown->curveType); if (0 == G.bits) { return offsetarray; } icachealiases = (U16)((k_lenr << 2) + (k_lenr << 1)); icachealiases += k_lenk; #if (SHARKSSL_BIGINT_WORDSIZE > 32) icachealiases += 4; #else baAssert(k_lenk >= k_lenr); #endif #if (SHARKSSL_BIGINT_WORDSIZE > 8) icachealiases += h_len; #if (!SHARKSSL_ECDSA_ONLY_VERIFY) if (op & iommupdata) { icachealiases += k_lenr; #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) icachealiases += k_lenr; #endif } else #endif if (op & fixupdevices) { icachealiases += (U16)(k_lenr << 2); #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) icachealiases += (U16)(k_lenr << 2); #endif } #endif afterhandler = (U8*)baMalloc(pcmciapdata(icachealiases)); if ((afterhandler == NULL) || (0 == G.bits)) { return (int)SharkSslCon_AllocationError; } temporaryentry = (U8*)selectaudio(afterhandler); onenandpartitions(&u1, (k_lenr * 2 * 8), temporaryentry); temporaryentry += (U16)(k_lenr << 1); onenandpartitions(&u2, (k_lenr * 2 * 8), temporaryentry); temporaryentry += (U16)(k_lenr << 1); updatefrequency(&point, (k_lenr * 8), temporaryentry, temporaryentry + k_lenr); temporaryentry += (U16)(k_lenr << 1); #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess(temporaryentry, h, h_len); h = temporaryentry; temporaryentry += h_len; #endif onenandpartitions(&e, (h_len * 8), h); #if (!SHARKSSL_ECDSA_ONLY_VERIFY) if (op & iommupdata) { U8 cnt = 0; _SharkSslECDSAParam_ECDSA_rng: sharkssl_rng(temporaryentry, k_lenk); temporaryentry[k_lenk - k_len] |= 0x01; #if SHARKSSL_ECC_USE_SECP521R1 if (k_lenk > k_len) { memset(temporaryentry, 0, k_lenk - k_len); } #endif #if (SHARKSSL_BIGINT_WORDSIZE > 8) memmove_endianess((U8*)consoledevice(&u1), temporaryentry, k_lenk); memcpy(temporaryentry, (U8*)consoledevice(&u1), k_lenk); #endif onenandpartitions(&K, (k_lenk * 8), temporaryentry); suspendfinish(&K, &G.order); blastscache(&K); baAssert(pulsewidth(&K) <= k_lenr); temporaryentry += k_lenk; if (unregisterskciphers(&G, &K, &point)) { goto _SharkSslECDSAParam_ECDSA_end; } suspendfinish(&point.x, &G.order); if (eventtimeout(&point.x)) { if (++cnt & 0x8) { goto _SharkSslECDSAParam_ECDSA_end; } goto _SharkSslECDSAParam_ECDSA_rng; } #if (SHARKSSL_BIGINT_WORDSIZE > 8) #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (k_len != k_lenr) { icachealiases = k_lenr - k_len; memset(temporaryentry, 0, icachealiases); memcpy(temporaryentry + icachealiases, k, k_len); temporaryentry += k_lenr; memmove_endianess(temporaryentry, temporaryentry - k_lenr, k_lenr); } else #endif { memmove_endianess(temporaryentry, k, k_lenr); } onenandpartitions(&dA, (k_lenr * 8), temporaryentry); #else onenandpartitions(&dA, (k_lenr * 8), k); #endif hotplugpgtable(&dA, &point.x, &u1); suspendfinish(&u1, &G.order); setupsdhci1(&u1, &e, &G.order); iommumapping(&K, &G.order); hotplugpgtable(&K, &u1, &u2); suspendfinish(&u2, &G.order); if (eventtimeout(&u2)) { if (++cnt & 0x8) { goto _SharkSslECDSAParam_ECDSA_end; } goto _SharkSslECDSAParam_ECDSA_rng; } #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (k_len != k_lenr) { temporaryentry = (U8*)consoledevice(&(point.y)); memmove_endianess(temporaryentry, (U8*)consoledevice(&(point.x)), k_lenr); memcpy(r, temporaryentry + k_lenr - k_len, k_len); memmove_endianess(temporaryentry, (U8*)consoledevice(&u2), k_lenr); memcpy(s, temporaryentry + k_lenr - k_len, k_len); } else #endif { memmove_endianess(r, (U8*)consoledevice(&(point.x)), k_len); memmove_endianess(s, (U8*)consoledevice(&u2), k_len); } offsetarray = 0; } else #endif if (op & fixupdevices) { #if (SHARKSSL_BIGINT_WORDSIZE > 8) #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (k_len != k_lenr) { icachealiases = k_lenr - k_len; memset(temporaryentry, 0, icachealiases); memcpy(temporaryentry + icachealiases, r, k_len); r = temporaryentry; temporaryentry += k_lenr; memset(temporaryentry, 0, icachealiases); memcpy(temporaryentry + icachealiases, s, k_len); s = temporaryentry; temporaryentry += k_lenr; } #endif memmove_endianess(temporaryentry, r, k_lenr); r = temporaryentry; temporaryentry += k_lenr; memmove_endianess(temporaryentry, s, k_lenr); s = temporaryentry; temporaryentry += k_lenr; #endif onenandpartitions(&R, (k_lenr * 8), r); onenandpartitions(&S, (k_lenr * 8), s); onenandpartitions(&w, (k_lenr * 8), temporaryentry); temporaryentry += k_lenr; #if (SHARKSSL_BIGINT_WORDSIZE > 8) #if ((SHARKSSL_BIGINT_WORDSIZE > 16) && (SHARKSSL_ECC_USE_SECP521R1)) if (k_len != k_lenr) { icachealiases = k_lenr - k_len; memset(temporaryentry, 0, icachealiases); memcpy(temporaryentry + icachealiases, k, k_len); temporaryentry += k_lenr; memset(temporaryentry, 0, icachealiases); memcpy(temporaryentry + icachealiases, k + k_len, k_len); temporaryentry += k_lenr; icachealiases = (U16)(k_lenr << 1); memmove_endianess(temporaryentry, temporaryentry - icachealiases, icachealiases); } else #endif { memmove_endianess(temporaryentry, k, (U16)(k_lenr << 1)); } updatefrequency(&Qa, (k_lenr * 8), temporaryentry, temporaryentry + k_lenr); #else updatefrequency(&Qa, (k_lenr * 8), k, k + k_lenr); #endif if ((eventtimeout(&R)) || (eventtimeout(&S)) || (timerwrite(&R, &G.order) || timerwrite(&S, &G.order))) { goto _SharkSslECDSAParam_ECDSA_end; } clearerrors(&T, audioshutdown->curveType); if ((0 == T.bits) || (initialdomain(&T, &Qa))) { goto _SharkSslECDSAParam_ECDSA_end; } unassignedvector(&S, &w); iommumapping(&w, &G.order); hotplugpgtable(&w, &e, &u1); suspendfinish(&u1, &G.order); hotplugpgtable(&w, &R, &u2); suspendfinish(&u2, &G.order); if (directalloc(&G, &u1, &T, &u2, &point)) { goto _SharkSslECDSAParam_ECDSA_end; } keypaddevice(&point.x, &R, &G.order); if (eventtimeout(&point.x)) { offsetarray = 0; } } _SharkSslECDSAParam_ECDSA_end: baFree(afterhandler); return offsetarray; } #endif #if (SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSAKEY_CREATE) SHARKSSL_API int SharkSslRSAKey_create(SharkSslRSAKey *mcbspplatform, U16 blake2bupdate) { static const U8 patchimm64[4] = {0x00, 0x01, 0x00, 0x01}; static const shtype_tWord one = 1; shtype_t P, Q, N, H, G, E, DP, DQ, QP, ONE; U8 *afterhandler, *p; int i, sffsdrnandflash = 0; U16 writeuncached = (blake2bupdate >> 1); *mcbspplatform = NULL; if (blake2bupdate & ((SHARKSSL_BIGINT_WORDSIZE << 1) - 1)) { return -1; } p = afterhandler = (U8*)baMalloc((sizeof(patchimm64)/sizeof(patchimm64[0])) + (blake2bupdate >> 4) + (blake2bupdate >> 2) + (blake2bupdate >> 1)); if (afterhandler == NULL) { return -2; } onenandpartitions(&ONE, SHARKSSL_BIGINT_WORDSIZE, &one); onenandpartitions(&P, writeuncached, p); p += (writeuncached >> 3); onenandpartitions(&Q, writeuncached, p); p += (writeuncached >> 3); onenandpartitions(&DP, writeuncached * 2, p); p += (writeuncached >> 2); onenandpartitions(&DQ, writeuncached * 2, p); p += (writeuncached >> 2); onenandpartitions(&QP, writeuncached, p); p += (writeuncached >> 3); onenandpartitions(&N, writeuncached * 2, p); p += (writeuncached >> 2); onenandpartitions(&H, writeuncached * 2, p); p += (writeuncached >> 2); onenandpartitions(&E, sizeof(patchimm64)*8, p); memmove_endianess(p, (const U8*)&patchimm64, (sizeof(patchimm64)/sizeof(patchimm64[0]))); p += (sizeof(patchimm64)/sizeof(patchimm64[0])); onenandpartitions(&G, writeuncached * 2, p); for (;;) { if ( !sffsdrnandflash ) { sffsdrnandflash = aemifdevice(&P); } if ( !sffsdrnandflash ) { sffsdrnandflash = aemifdevice(&Q); } if ( sffsdrnandflash ) { break; } if (timerwrite(&P, &Q)) { if (timerwrite(&Q, &P)) { continue; } } else { shtype_tWord *mem2, *beg2; beg2 = P.beg; mem2 = P.mem; P.beg = Q.beg; P.mem = Q.mem; Q.beg = beg2; Q.mem = mem2; P.len += Q.len; Q.len = P.len - Q.len; P.len -= Q.len; } hotplugpgtable(&P, &Q, &N); if (0 == (N.beg[0] & (shtype_tWord)(1 << (SHARKSSL_BIGINT_WORDSIZE - 1)))) { continue; } updatepmull(&P, &ONE); updatepmull(&Q, &ONE); hotplugpgtable(&P, &Q, &H); sffsdrnandflash = translateaddress(&H, &E, &G); if (sffsdrnandflash) { break; } if (timerwrite(&G, &ONE) && timerwrite(&ONE, &G)) { break; } } if ( !sffsdrnandflash ) { unassignedvector(&E, &G); iommumapping(&G, &H); unassignedvector(&G, &DP); unassignedvector(&G, &DQ); suspendfinish(&DP, &P); suspendfinish(&DQ, &Q); resolverelocs(&P, &ONE); resolverelocs(&Q, &ONE); unassignedvector(&Q, &QP); iommumapping(&QP, &P); writeuncached >>= 2; i = sizeof(patchimm64)/sizeof(patchimm64[0]); sffsdrnandflash = 8 + i + (writeuncached >> 1) + (writeuncached) + (writeuncached << 1); p = (U8*)baMalloc(sffsdrnandflash); if (p == NULL) { sffsdrnandflash = -2; } else { *mcbspplatform = p; p[0] = 0x30; p[1] = 0x82; p[2] = 0x00; p[3] = 0x00; p[4] = 0x00; p[5] = (U8)i; p[6] = (U8)(writeuncached >> 8); p[7] = (U8)writeuncached; p += 8; while (i--) { *(p + i) = patchimm64[i]; } p += sizeof(patchimm64)/sizeof(patchimm64[0]); memmove_endianess(p, (U8*)consoledevice(&N), writeuncached); p += writeuncached; writeuncached >>= 1; memmove_endianess(p, (U8*)consoledevice(&P), writeuncached); p += writeuncached; memmove_endianess(p, (U8*)consoledevice(&Q), writeuncached); p += writeuncached; memmove_endianess(p, (U8*)consoledevice(&DP), writeuncached); p += writeuncached; memmove_endianess(p, (U8*)consoledevice(&DQ), writeuncached); p += writeuncached; memmove_endianess(p, (U8*)consoledevice(&QP), writeuncached); } } baFree(afterhandler); return sffsdrnandflash; } SHARKSSL_API U8 *SharkSslRSAKey_getPublic(SharkSslRSAKey mcbspplatform) { SharkSslCertKey disableclock; if (interrupthandler(&disableclock, (SharkSslCert)mcbspplatform)) { return disableclock.mod; } return NULL; } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #include #include #include #include #include #include #include /* Using offsetof */ #include static const char xmlMultistatusHead[] = { "\074\077\170\155\154\040\166\145\162\163\151\157\156\075\042\061\056\060\042\040\145\156\143\157\144\151\156\147\075\042\165\164\146\055\070\042\077\076\012" "\074\104\072\155\165\154\164\151\163\164\141\164\165\163\040\170\155\154\156\163\072\104\075\042\104\101\126\072\042" }; static const char xmlHeader[] = { "\074\077\170\155\154\040\166\145\162\163\151\157\156\075\042\061\056\060\042\040\145\156\143\157\144\151\156\147\075\042\165\164\146\055\070\042\077\076\012" }; static const char xmlMultistatusFooter[] = {"\074\057\104\072\155\165\154\164\151\163\164\141\164\165\163\076\012"}; static const char notFoundMsg[] = {"\064\060\064\040\116\157\164\040\106\157\165\156\144"}; static const char okMsg[] = {"\062\060\060\040\117\113"}; static const char responseHeaderFmt[] = { "\074\104\072\162\145\163\160\157\156\163\145\076\012" "\074\104\072\150\162\145\146\076\045\163\074\057\104\072\150\162\145\146\076\012" }; static const char responseFooter[] = {"\074\057\104\072\162\145\163\160\157\156\163\145\076\012"}; #ifdef BA_FILESIZE64 #define BA_FILE_FMT "\045\154\154\165" #else #define BA_FILE_FMT "\045\165" #endif static const char* WebDAV_ioName2URL( WebDAV* o, const char* driverregister, HttpCommand* cmd); static BaBool resourceflags(WebDAV* o, const char* gpio1config); struct IoCtrl; static void secureupdate(struct IoCtrl* o, WebDAV* targetidentifier, HttpCommand* cmd, HttpMethod disableparity); #define IoCtrl_doResource(o,frm,to) \ RecIoIter_doResource((RecIoIter*)(o),frm,to) #if 0 static void allocahash(HttpCommand* cmd) { U32 rollbackhandler = HttpStdHeaders_getContentLength( HttpRequest_getStdHeaders(&cmd->request)); U32 lsdc2format=HttpInData_getBufSize(HttpRequest_getBuffer(&cmd->request)); if(rollbackhandler > lsdc2format) { HttpTrace_printf(0, "\055\055\055\055\055\055\055\055\055\055\055\055\055\055\055\040\122\145\143\145\151\166\145\040\144\141\164\141\040\154\141\162\147\145\162\040\164\150\141\156\040\142\165\146\146\145\162\012"); } else { HttpTrace_write( 0, HttpInData_getBuf(HttpRequest_getBuffer(&cmd->request)), rollbackhandler); } } #else #define allocahash(cmd) #endif static const char* getContentType(const char* gpio1config) { char* ext = strrchr(gpio1config, '\056'); if(ext) return httpFindMime(++ext); return 0; } static void printDavElem(BufPrint* out, const char* elemName, const char* fmt, ...) { if(fmt) { va_list demuxregids; BufPrint_printf(out,"\074\104\072\045\163\076",elemName); va_start(demuxregids, fmt); BufPrint_vprintf(out, fmt, demuxregids); va_end(demuxregids); BufPrint_printf(out,"\074\057\104\072\045\163\076\012",elemName); } else { BufPrint_printf(out,"\074\104\072\045\163\057\076\012",elemName); } } static void resumenoirq(HttpResponse* r3000write) { HttpResponse_setHeader(r3000write, "\103\157\156\164\145\156\164\055\124\171\160\145","\164\145\170\164\057\170\155\154\073\040\143\150\141\162\163\145\164\075\042\165\164\146\055\070\042",TRUE); } static void blocksha512(HttpResponse* r3000write) { HttpResponse_setStatus (r3000write, 207); resumenoirq(r3000write); } static void scoopdevice(HttpCommand* cmd) { HttpResponse_setHeader(&cmd->response, "\122\145\164\162\171\055\101\146\164\145\162", "\066\060",TRUE); } static void sendHttpResp(HttpCommand* cmd,int sffsdrnandflash,const char* fmt, ...) { if(sffsdrnandflash == 503) scoopdevice(cmd); HttpResponse_setStatus(&cmd->response, sffsdrnandflash); if(fmt) { va_list demuxregids; va_start(demuxregids, fmt); HttpResponse_vprintf(&cmd->response, fmt, demuxregids); va_end(demuxregids); } else HttpResponse_setContentLength(&cmd->response, 0); } static BaBool nvmemmatch(HttpCommand* cmd) { const char* poweroffrequired = HttpRequest_getHeaderValue(&cmd->request, "\104\145\160\164\150"); return (poweroffrequired && (poweroffrequired[0] == '\060' && !poweroffrequired[1])) ? TRUE : FALSE; } static BaBool splitidlest(HttpCommand* cmd) { const char* titanmemory; titanmemory = HttpRequest_getHeaderValue(&cmd->request, "\117\166\145\162\167\162\151\164\145"); if(titanmemory && (titanmemory[0] == '\106' || titanmemory[0] == '\146') && titanmemory[1] == 0) return FALSE; return TRUE; } static void uart2resources(BufPrint* out) { BufPrint_write(out, xmlMultistatusHead, sizeof(xmlMultistatusHead)-1); BufPrint_write(out,"\076\012",2); } static void uninstallidmap(BufPrint* out) { BufPrint_write(out,xmlMultistatusFooter,sizeof(xmlMultistatusFooter)-1); } static BaBool detecticache(HttpRequest* r) { const char* ua = HttpRequest_getHeaderValue(r, "\125\163\145\162\055\101\147\145\156\164"); if(ua && strstr(ua, "\115\151\143\162\157\163\157\146\164")) return TRUE; return FALSE; } #if 0 typedef struct { U32 id; /* The ID or pointer value of the node */ U32 time; } BUUID; void BUUID_fmt(BUUID* o, U8 buf[37]) { basnprintf(buf, 37, "\045\060\070\154\170\055\045\060\064\170\055\045\060\064\170\055\141\067\066\065\055\060\060\141\060\143\071\061\145\066\142\146\071", o->id, o->time >> 16, o->time & 0xFFFF); } static int mcasp1device(BUUID* o, U8* buf) { U8 setupadditional[8]; if(memcmp(buf+18, "\055\141\067\066\065\055\060\060\141\060\143\071\061\145\066\142\146\071", 18)) return -1; o->id = baConvHexToU32(buf); memcpy(setupadditional, buf+9, 4); memcpy(setupadditional+4, buf+14, 4); o->time = baConvHexToU32(setupadditional); return 0; } #endif typedef struct { SplayTreeNode super; SingleLink slink; BaTime lockTime; BaTime createdTime; BaTime expireTime; U32 lockFileNumber; char name[1]; /* Path and name */ } LockNode; #define LockNode_link2Node(l) \ (LockNode*)((U8*)l-offsetof(LockNode,slink)) static char* LockNode_getLockFileName(LockNode* o, LockContainer* lc) { baAssert(lc->lockDir); basnprintf(lc->lockDirFn, 9, "\114\045\130", o->lockFileNumber); return lc->lockDir; } static ResIntfPtr gpio0resources(LockNode* o, LockContainer* lc, U32 shashdigestsize) { int sffsdrnandflash; IoIntf* io = lc->webDAV->io; return io->openResFp(io,LockNode_getLockFileName(o,lc),shashdigestsize,&sffsdrnandflash,0); } static void regulatorconfig(LockNode* o) { o->expireTime = baGetUnixTime() + o->lockTime + 60; } static int LockNode_setOwner(LockNode* o, LockContainer* lc, SXmlNode* ownerN, SXmlRoot* ownerR) { volatile int handlersetup=-1; ResIntfPtr res = gpio0resources(o,lc,OpenRes_WRITE); if(res) { BufPrint* out = (BufPrint*)IoBufPrint_create2(lc->webDAV->alloc,200,res); if(out) { NsTree nst; int sffsdrnandflash; SlException ex; SerializeSXml* volatile s; s=0; sffsdrnandflash = SlException_INIT(ex); if(!sffsdrnandflash) { NsTree_constructor(&nst, lc->webDAV->alloc, &ex); NsTree_addNs(&nst, ownerN, ownerR); s = NsTree_createSerializer(&nst, '\156', out); SlException_assert(&ex, s); SerializeSXml_printNsAttrList(s); SerializeSXml_printNode((SerializeSXml*)s, ownerN, ownerR, TRUE); handlersetup=0; } if(s) AllocatorIntf_free(lc->webDAV->alloc, (void*)s); NsTree_destructor(&nst); IoBufPrint_destructor((IoBufPrint*)out); AllocatorIntf_free(lc->webDAV->alloc, out); } res->closeFp(res); } return handlersetup; } static void cryptodisable(LockNode* o, HttpCommand* cmd) { const int doubleftosiz = 55; char* val = HttpResponse_fmtHeader(&cmd->response,"\114\157\143\153\055\124\157\153\145\156",doubleftosiz,TRUE); if(val) { basnprintf(val, doubleftosiz, "\074\157\160\141\161\165\145\154\157\143\153\164\157\153\145\156\072\045\060\070\154\170\055\045\060\064\170\055\045\060\064\170\055\141\067\066\065\055\060\060\141\060\143\071\061\145\066\142\146\071\076", (U32)((ptrdiff_t )o), o->createdTime >> 16, o->createdTime & 0xFFFF); } } static void printboard(LockNode* o, LockContainer* lc, BufPrint* out) { static const char entryvectors[] = { "\074\104\072\154\157\143\153\144\151\163\143\157\166\145\162\171\076\012" "\074\104\072\141\143\164\151\166\145\154\157\143\153\076\012" "\074\104\072\154\157\143\153\164\171\160\145\076\074\104\072\167\162\151\164\145\057\076\074\057\104\072\154\157\143\153\164\171\160\145\076\012" "\074\104\072\154\157\143\153\163\143\157\160\145\076\074\104\072\145\170\143\154\165\163\151\166\145\057\076\074\057\104\072\154\157\143\153\163\143\157\160\145\076\012" "\074\104\072\144\145\160\164\150\076\045\163\074\057\104\072\144\145\160\164\150\076\012"}; static const char ciphersetkey[] = { "\074\104\072\164\151\155\145\157\165\164\076\123\145\143\157\156\144\055\045\165\074\057\104\072\164\151\155\145\157\165\164\076\012" "\074\104\072\154\157\143\153\164\157\153\145\156\076\012" "\074\104\072\150\162\145\146\076\157\160\141\161\165\145\154\157\143\153\164\157\153\145\156\072\045\060\070\154\170\055\045\060\064\170\055\045\060\064\170\055\141\067\066\065\055\060\060\141\060\143\071\061\145\066\142\146\071\074\057\104\072\150\162\145\146\076\012" "\074\057\104\072\154\157\143\153\164\157\153\145\156\076\012" "\074\057\104\072\141\143\164\151\166\145\154\157\143\153\076\012" "\074\057\104\072\154\157\143\153\144\151\163\143\157\166\145\162\171\076\012"}; size_t icachealiases; char* buf; BufPrint_printf(out, entryvectors, "\060"); buf = (char*)DeadProp_readFile(lc->webDAV->io, lc->webDAV->alloc, LockNode_getLockFileName(o, lc), &icachealiases); if(buf) { BufPrint_write(out, buf, (int)icachealiases); AllocatorIntf_free(lc->webDAV->alloc, buf); } BufPrint_printf(out, ciphersetkey, o->lockTime, ((ptrdiff_t)o), o->createdTime >> 16, o->createdTime & 0xFFFF); } static int registerdevice(SplayTreeNode* n, SplayTreeKey k) { register const char* a=(const char*)n->key; register const char* b=(const char*)k; while(*a == *b) { if(*a == 0) return 0; a++, b++; } if( (*a == '\057' && !*b && !a[1]) || (*b == '\057' && !*a && !b[1]) ) return 0; return *a - *b; } static int hsmmc0pdata(SplayTreeNode* n, SplayTreeKey k) { register const char* a=(const char*)n->key; register const char* b=(const char*)k; while(bTolower(*a) == bTolower(*b)) { if(*a == 0) return 0; a++, b++; } if( (*a == '\057' && !*b && !a[1]) || (*b == '\057' && !*a && !b[1]) ) return 0; return *a - *b; } static int eventprint(IoIntf* io) { char* rightsvalid; char* unregistershashes; return ! io->propertyFp(io,"\164\171\160\145", &rightsvalid, &unregistershashes) && ! strcmp("\144\151\163\153", rightsvalid) && ! strncmp("\167\151\156", unregistershashes, 3); } static void registerredist(LockContainer* o, WebDAV* targetidentifier, const char* checkoptimized, U32 serial2pdata) { IoIntf* io = targetidentifier->io; SplayTree_constructor( &o->lTree, eventprint(io) ? hsmmc0pdata : registerdevice); SingleList_constructor(&o->lList); o->nextLockFileNumber=0; o->webDAV=targetidentifier; o->lockDir=0; if(checkoptimized && serial2pdata) { IoStat st; if( !io->statFp(io, checkoptimized, &st) || ! io->mkDirFp(io,checkoptimized,0) ) { size_t icachealiases = strlen(checkoptimized) + 12; o->lockDir = AllocatorIntf_malloc(o->webDAV->alloc, &icachealiases); } } if(o->lockDir) { U32 supervisorcachemode = TRUE; io->propertyFp(io, "\150\151\144\144\145\156", (void*)checkoptimized, &supervisorcachemode); strcpy(o->lockDir, checkoptimized); strcat(o->lockDir,"\057"); o->lockDirFn = o->lockDir+strlen(o->lockDir); o->locksLeft=serial2pdata; } else o->locksLeft=0; } static void memoryerror(LockContainer* o) { if(o->lockDir) { AllocatorIntf_free(o->webDAV->alloc,o->lockDir); o->lockDir=0; } } #define LockContainer_isEnabled(o) (o)->lockDirFn static void wm97xxprobe(LockContainer* o, LockNode* ln) { IoIntf* io = o->webDAV->io; SingleLink* link; SingleListEnumerator instructioncounter; SingleListEnumerator_constructor(&instructioncounter, &o->lList); for(link = SingleListEnumerator_getElement(&instructioncounter) ; link ; link = SingleListEnumerator_nextElement(&instructioncounter)) { if(link == &ln->slink) { SingleListEnumerator_removeElement(&instructioncounter); break; } } baAssert(link); SplayTree_remove(&o->lTree, (SplayTreeNode*)ln); io->removeFp(io, LockNode_getLockFileName(ln,o), 0); AllocatorIntf_free(o->webDAV->alloc, ln); o->locksLeft++; } static LockNode* LockContainer_createLN(LockContainer* o, BaTime moduledbetables, const char* gpio1config) { size_t icachealiases; LockNode* ln; BaTime tNow = baGetUnixTime(); if(o->locksLeft == 0) { SingleLink* link; SingleListEnumerator instructioncounter; SingleListEnumerator_constructor(&instructioncounter, &o->lList); for(link = SingleListEnumerator_getElement(&instructioncounter) ; link ; link = SingleListEnumerator_nextElement(&instructioncounter)) { ln = LockNode_link2Node(link); if(ln->expireTime <= tNow) { wm97xxprobe(o,ln); break; } } if( !link ) return 0; } o->locksLeft--; icachealiases = sizeof(LockNode) + strlen(gpio1config); ln = (LockNode*)AllocatorIntf_malloc(o->webDAV->alloc, &icachealiases); if(ln) { IoIntf* io = o->webDAV->io; strcpy(ln->name, gpio1config); SplayTreeNode_constructor((SplayTreeNode*)ln, ln->name); SingleLink_constructor(&ln->slink); SplayTree_insert(&o->lTree, (SplayTreeNode*)ln); SingleList_insertLast(&o->lList, &ln->slink); ln->lockTime=moduledbetables; ln->createdTime = tNow; ln->expireTime = ln->createdTime + moduledbetables + 60; ln->lockFileNumber=o->nextLockFileNumber++; io->removeFp(io, LockNode_getLockFileName(ln,o), 0); } return ln; } static LockNode* LockContainer_find(LockContainer* o, const char* gpio1config) { LockNode* ln = (LockNode*)SplayTree_find(&o->lTree, gpio1config); if(ln) { if(ln->expireTime <= baGetUnixTime()) { wm97xxprobe(o, ln); ln=0; } } return ln; } static int LockContainer_isLocked(LockContainer* o, const char* gpio1config, const char** ethernatenable) { if(LockContainer_isEnabled(o) && LockContainer_find(o, gpio1config)) { if(ethernatenable) *ethernatenable="\114\157\143\153\145\144"; return IOINTF_LOCKED; } return 0; } typedef struct { RecIoIter super; /* Implements 'onResponse' and 'onErr' in RecIoIter */ AuthenticatedUser* user; AuthorizerIntf* realm; HttpMethod method; } IoAuth; #define IoAuth_constructor(o, targetidentifier, userMA, methodMA, hasTo) do{ \ RecIoIter_constructor((RecIoIter*)o, \ targetidentifier->alloc, \ targetidentifier->io, \ hasTo ? IoAuth_onResponse2 : IoAuth_onResponse, \ IoAuth_onErr); \ (o)->user=userMA; \ (o)->realm=((HttpDir*)targetidentifier)->realm; \ (o)->method=methodMA; }while(0) \ #define IoAuth_doResource(o,frm,to) \ RecIoIter_doResource((RecIoIter*)(o),frm,to) static int IoAuth_onResponse(RecIoIter* fdc37m81xconfig,const char* forcereload,const char* to,IoStat* st) { IoAuth* o = (IoAuth*)fdc37m81xconfig; (void)to; if(st->isDir && st->size) return 0; return AuthorizerIntf_authorize(o->realm,o->user,o->method,forcereload) ? 0 : 403; } static int IoAuth_onResponse2(RecIoIter* fdc37m81xconfig,const char* forcereload,const char* to,IoStat* st) { IoAuth* o = (IoAuth*)fdc37m81xconfig; if(st->isDir && st->size) return 0; if(AuthorizerIntf_authorize(o->realm,o->user,o->method,to)) if(AuthorizerIntf_authorize(o->realm,o->user,o->method,forcereload)) return 0; return 403; } static int IoAuth_onErr(RecIoIter* fdc37m81xconfig,const char* gpio1config,int err,const char* msg) { (void)fdc37m81xconfig; (void)gpio1config; (void)msg; return err == IOINTF_EXIST ? 403 : baErr2HttpCode(err); } typedef struct IoCtrl { RecIoIter super; /* Implements 'onResponse' and 'onErr' in RecIoIter */ WebDAV* webDAV; HttpCommand* cmd; HttpMethod method; BaBool overwrite; BaBool resourceReplaced; } IoCtrl; static char* IoCtrl_rmResource(IoCtrl* o, const char* gpio1config) { if(resourceflags(o->webDAV, gpio1config)) { char* buf = baStrdup2(o->webDAV->alloc, gpio1config); if(buf) { IoCtrl ctrl; if(buf[strlen(buf)-1] == '\057') buf[strlen(buf)-1]=0; secureupdate(&ctrl, o->webDAV,o->cmd, HttpMethod_Delete); if( ! IoCtrl_doResource(&ctrl, gpio1config, 0) ) return buf; AllocatorIntf_free(o->webDAV->alloc,buf); } else sendHttpResp(o->cmd, 503,0); } return 0; } static int resetbluetooth(RecIoIter* fdc37m81xconfig,const char* forcereload,const char* to,IoStat* st) { char* buf; const char* checkchecksum=0; int sffsdrnandflash=0; IoIntf* io = fdc37m81xconfig->io; IoCtrl* o = (IoCtrl*)fdc37m81xconfig; WebDAV* dav=o->webDAV; if(to) { if(st->isDir) { if(io->statFp(fdc37m81xconfig->io, to, st)) { if( (sffsdrnandflash = fdc37m81xconfig->io->mkDirFp(fdc37m81xconfig->io, to, &checkchecksum)) ) { L_sendMkdirErrMsg: sendHttpResp(o->cmd, baErr2HttpCode(sffsdrnandflash), "\103\141\156\156\157\164\040\143\162\145\141\164\145\040\045\163\056\040\045\163",to,checkchecksum?checkchecksum:""); } } else if( ! st->isDir ) { if(o->overwrite) { if( (sffsdrnandflash=io->removeFp(io,to,&checkchecksum)) || (sffsdrnandflash = fdc37m81xconfig->io->mkDirFp(fdc37m81xconfig->io, to, &checkchecksum)) ) { goto L_sendMkdirErrMsg; } o->resourceReplaced=TRUE; } else { sendHttpResp(o->cmd, 409, "\045\163\040\156\157\164\040\141\040\144\151\162\145\143\164\157\162\171", to); } } } else { if(o->method == HttpMethod_Copy) { if(LockContainer_isLocked(&dav->lock,to,0)) { HttpResponse_sendError1(&o->cmd->response,423); sffsdrnandflash=1; } else if(o->overwrite || ! resourceflags(dav, to) ) { ResIntfPtr in = io->openResFp( io, forcereload, OpenRes_READ, &sffsdrnandflash, &checkchecksum); if(in) { ResIntfPtr out; out = io->openResFp(io,to,OpenRes_WRITE,&sffsdrnandflash,&checkchecksum); if(!out && o->overwrite && (buf=IoCtrl_rmResource(o, to))) { o->resourceReplaced=TRUE; out=io->openResFp(io,buf,OpenRes_WRITE,&sffsdrnandflash,&checkchecksum); AllocatorIntf_free(fdc37m81xconfig->alloc,buf); } if(out) { size_t icachealiases = 2048; buf = (char*)AllocatorIntf_malloc(fdc37m81xconfig->alloc, &icachealiases); if(buf) { BaFileSize interfaceregister = st->size; while(interfaceregister != 0) { size_t readS; size_t chunkS = interfaceregister > 2048 ? 2048 : (size_t)interfaceregister; interfaceregister -= chunkS; if( (sffsdrnandflash = in->readFp(in, buf, chunkS, &readS))|| chunkS != readS) { sendHttpResp( o->cmd, baErr2HttpCode(sffsdrnandflash), "\106\141\151\154\145\144\040\141\146\164\145\162\040\162\145\141\144\151\156\147\040" BA_FILE_FMT "\040\142\171\164\145\163\040\146\162\157\155\040\045\163", st->size-interfaceregister, forcereload); break; } if( (sffsdrnandflash = out->writeFp(out, buf, chunkS)) != 0 ) { sendHttpResp( o->cmd,baErr2HttpCode(sffsdrnandflash), "\106\141\151\154\145\144\040\141\146\164\145\162\040\167\162\151\164\151\156\147\040" BA_FILE_FMT "\040\142\171\164\145\163\040\164\157\040\045\163", st->size-interfaceregister, to); break; } } AllocatorIntf_free(fdc37m81xconfig->alloc,buf); } else { sendHttpResp(o->cmd, 503, 0); sffsdrnandflash=1; } out->closeFp(out); } else { sendHttpResp( o->cmd, baErr2HttpCode(sffsdrnandflash), "\103\141\156\156\157\164\040\157\160\145\156\040\045\163\056\040\045\163",to,checkchecksum?checkchecksum:""); } in->closeFp(in); } else { sendHttpResp( o->cmd, baErr2HttpCode(sffsdrnandflash), "\103\141\156\156\157\164\040\157\160\145\156\040\045\163\056\040\045\163",forcereload,checkchecksum?checkchecksum:""); } } else { sendHttpResp(o->cmd, 412, "\106\151\154\145\040\145\170\151\163\164\040\045\163", to); sffsdrnandflash = 1; } } else { if( (sffsdrnandflash = LockContainer_isLocked(&dav->lock,forcereload,&checkchecksum)) !=0 || (sffsdrnandflash = LockContainer_isLocked(&dav->lock,to,&checkchecksum)) !=0 || (sffsdrnandflash = io->renameFp(io, forcereload, to, &checkchecksum)) != 0) { if(o->overwrite) { o->resourceReplaced=TRUE; if((buf=IoCtrl_rmResource(o, to))) { if( (sffsdrnandflash = io->renameFp(io, forcereload, buf, &checkchecksum)) != 0) sffsdrnandflash = baErr2HttpCode(sffsdrnandflash); AllocatorIntf_free(fdc37m81xconfig->alloc,buf); } } else sffsdrnandflash = 412; if(sffsdrnandflash) { sendHttpResp(o->cmd, sffsdrnandflash, "\103\141\156\156\157\164\040\155\157\166\145\040\045\163\040\164\157\040\045\163\056\040\045\163",forcereload,to, checkchecksum?checkchecksum:""); } } } } } else { if(st->isDir) { if(o->method != HttpMethod_Copy && st->size) { if( (sffsdrnandflash=io->rmDirFp(io,forcereload,&checkchecksum)) != 0) { sendHttpResp(o->cmd, baErr2HttpCode(sffsdrnandflash), "\103\141\156\156\157\164\040\162\145\155\157\166\145\040\144\151\162\145\143\164\157\162\171\040\045\163\056\040\045\163",forcereload, checkchecksum?checkchecksum:""); } } } else if(o->method == HttpMethod_Delete) { if( (sffsdrnandflash = LockContainer_isLocked(&dav->lock,forcereload,&checkchecksum)) != 0 || (sffsdrnandflash=io->removeFp(io,forcereload,&checkchecksum)) != 0) { sendHttpResp(o->cmd, baErr2HttpCode(sffsdrnandflash), "\103\141\156\156\157\164\040\162\145\155\157\166\145\040\040\045\163\056\040\045\163",forcereload, checkchecksum?checkchecksum:""); } } } return sffsdrnandflash; } static int graphenter(RecIoIter* fdc37m81xconfig,const char* gpio1config,int err,const char* msg) { int sffsdrnandflash = err == IOINTF_EXIST ? 403 : baErr2HttpCode(err); if(!msg) msg = baErr2Str(err); sendHttpResp(((IoCtrl*)fdc37m81xconfig)->cmd, sffsdrnandflash, "\105\162\162\157\162\072\040\045\163\056\040\045\163", msg,gpio1config); return err; } static void secureupdate(IoCtrl* o, WebDAV* targetidentifier, HttpCommand* cmd, HttpMethod disableparity) { RecIoIter_constructor((RecIoIter*)o, targetidentifier->alloc, targetidentifier->io, resetbluetooth, graphenter); o->webDAV=targetidentifier; o->cmd=cmd; o->method=disableparity; o->overwrite = splitidlest(cmd); o->resourceReplaced=FALSE; } typedef enum { LivePropT_Resourcetype=1, LivePropT_Getetag=2, LivePropT_Getlastmodified=4, LivePropT_Getcontentlength=8, LivePropT_Getcontenttype=16, LivePropT_Lockdiscovery=32, LivePropT_Supportedlock=64, LivePropT_AllProp=128 } LivePropT; typedef struct { DynBuffer super; SXmlRoot root; SXmlRoot* r; /* pointer to above */ SlException* ex; WebDAV* webDAV; HttpCommand* cmd; AuthenticatedUser* user; SXmlNode** deadPropList; /* List of requested properties */ SXmlNode** deadPropStack; /* Used as stack in emitResponse */ U32 deadPropCount; U32 liveProp; BaBool hasBuffer; /* True if super class (DynBuffer) has data */ }Propfind; static void netdevicenotifier(Propfind* o) { SlException_set(o->ex, SXmlErrT_Err); } static void entersuspend(DynBuffer* fdc37m81xconfig, int serial8250device) { (void)serial8250device; SlException_set(((Propfind*)fdc37m81xconfig)->ex, SXmlErrT_Mem); } static SXmlNode* Propfind_checkNode(Propfind* o, SXmlNode* n, const char* gpio1config) { if(!n || strcmp(SXmlNode_getNs(n,o->r), "\104\101\126\072") || strcmp(SXmlNode_getName(n,o->r), gpio1config)) { netdevicenotifier(o); } return n; } static BaBool relocbegin(Propfind* o, SXmlNode* n, const char* gpio1config) { if(!n || strcmp(SXmlNode_getNs(n,o->r), "\104\101\126\072") || strcmp(SXmlNode_getName(n,o->r), gpio1config)) { return FALSE; } return TRUE; } static void tps65021consumers(Propfind* o, char* pwrdmrestore, U16 writeaction, WebDAV* targetidentifier, HttpCommand* cmd, AuthenticatedUser* buttonsbelkin, BaBool alignmentfault, SlException* ex) { unsigned int i; SXmlNode* n; SXmlNode* pn; AllocatorIntf* unmapaliases = targetidentifier->alloc; memset(o, 0, sizeof(Propfind)); o->ex=ex; o->webDAV=targetidentifier; o->r = &o->root; o->cmd = cmd; o->user=buttonsbelkin; if(!writeaction) { o->liveProp=LivePropT_AllProp; return; } SXmlRoot_constructor2(o->r,unmapaliases,(U8*)pwrdmrestore,writeaction,(U16)(writeaction/4),ex); n = Propfind_checkNode(o,SXmlRoot_firstChild(o->r),"\160\162\157\160\146\151\156\144"); pn = SXmlNode_firstChild(n,o->r); if(relocbegin(o,pn,"\141\154\154\160\162\157\160")) { o->liveProp=LivePropT_AllProp; } else { size_t icachealiases; Propfind_checkNode(o,pn,"\160\162\157\160"); i = SXmlNode_childNodes(pn); if(i == 0) netdevicenotifier(o); n = SXmlNode_firstChild(pn,o->r); icachealiases=sizeof(void*)*i; o->deadPropList = AllocatorIntf_malloc(unmapaliases, &icachealiases); if(!o->deadPropList) netdevicenotifier(o); for(o->deadPropCount = 0; n; n = SXmlNode_next(n, o->r)) { const char* gpio1config = SXmlNode_getName(n,o->r); if( ! strcmp("\104\101\126\072", SXmlNode_getNs(n,o->r)) ) { if(gpio1config[0]=='\154' && !strcmp("\154\157\143\153\144\151\163\143\157\166\145\162\171",gpio1config)) o->liveProp |= LivePropT_Lockdiscovery; else if(alignmentfault) { if(gpio1config[0]=='\162' && !strcmp("\162\145\163\157\165\162\143\145\164\171\160\145",gpio1config)) o->liveProp |= LivePropT_Resourcetype; else if(gpio1config[3]=='\145' && !strcmp("\147\145\164\145\164\141\147",gpio1config)) o->liveProp |= LivePropT_Getetag; else if(gpio1config[3]=='\154' && !strcmp("\147\145\164\154\141\163\164\155\157\144\151\146\151\145\144",gpio1config)) o->liveProp |= LivePropT_Getlastmodified; else if(gpio1config[11]=='\145' && !strcmp("\147\145\164\143\157\156\164\145\156\164\154\145\156\147\164\150",gpio1config)) o->liveProp |= LivePropT_Getcontentlength; else if(gpio1config[10]=='\164' && !strcmp("\147\145\164\143\157\156\164\145\156\164\164\171\160\145",gpio1config)) o->liveProp |= LivePropT_Getcontenttype; else if(gpio1config[0]=='\163' && !strcmp("\163\165\160\160\157\162\164\145\144\154\157\143\153",gpio1config)) o->liveProp |= LivePropT_Supportedlock; else if((gpio1config[0]=='\143' && !strcmp("\143\162\145\141\164\151\157\156\144\141\164\145",gpio1config)) || (gpio1config[0]=='\144' && !strcmp("\144\151\163\160\154\141\171\156\141\155\145",gpio1config)) || (gpio1config[11]=='\141' && !strcmp("\147\145\164\143\157\156\164\145\156\164\154\141\156\147\165\141\147\145",gpio1config))) { L_add2NotFoundBuf: if( ! o->hasBuffer ) { DynBuffer_constructor( (DynBuffer*)o, 400, 400, unmapaliases, entersuspend); o->hasBuffer=TRUE; } printDavElem((BufPrint*)o,SXmlNode_getName(n, o->r),0); } else goto notFound_L; } else goto L_add2NotFoundBuf; } else { notFound_L: o->deadPropList[o->deadPropCount++]=n; } } } if(o->deadPropCount) { size_t icachealiases=sizeof(void*)*o->deadPropCount; o->deadPropStack = AllocatorIntf_malloc(unmapaliases, &icachealiases); if(!o->deadPropStack) netdevicenotifier(o); } } static void vgg2432a4display(Propfind* o) { SXmlRoot_destructor(o->r); if(o->deadPropList) AllocatorIntf_free(o->webDAV->alloc, o->deadPropList); if(o->deadPropStack) AllocatorIntf_free(o->webDAV->alloc, o->deadPropStack); DynBuffer_destructor((DynBuffer*)o); } static int cachelevel(Propfind* o, const char* gpio1config, IoStat* st) { static const char needsbounce[] = { "\074\104\072\160\162\157\160\163\164\141\164\076\012" "\074\104\072\160\162\157\160"}; static const char allocdriver[] = { "\074\057\104\072\160\162\157\160\076\012" "\074\104\072\163\164\141\164\165\163\076\110\124\124\120\057\061\056\061\040\045\163\074\057\104\072\163\164\141\164\165\163\076\012" "\074\057\104\072\160\162\157\160\163\164\141\164\076\012"}; SXmlNode* n; DeadProp dp; SXmlRoot* volatile r; NsTree nst; #if 1 SerializeSXml* s; BaBool procfsmount; #else SerializeSXml* volatile s; volatile BaBool procfsmount; #endif SlException ex; unsigned int i; int sffsdrnandflash; char* volatile disablecounter; volatile unsigned int powerdevice; volatile BaBool validcache; volatile unsigned int chargermachinfo; BufPrint* out; const char* url; const char* volatile defaultattrs; LockNode* volatile devicepanel; if( ! HttpDir_isAuthorized( (HttpDir*)o->webDAV,o->user,HttpMethod_Propfind,gpio1config) ) { return -1; } procfsmount=FALSE; sffsdrnandflash=0; disablecounter=0; powerdevice=0; s=0; defaultattrs=0; devicepanel=0; r=0; validcache=FALSE; chargermachinfo=o->deadPropCount; out = HttpResponse_getWriter(&o->cmd->response); url = WebDAV_ioName2URL(o->webDAV, gpio1config, o->cmd); if(!url) netdevicenotifier(o); if(o->deadPropCount || o->liveProp==LivePropT_AllProp) { DeadProp_constructor(&dp, o->webDAV->io, o->webDAV->alloc); disablecounter = DeadProp_fname2PropFName(o->webDAV->alloc, gpio1config); if(!disablecounter) netdevicenotifier(o); if( ! DeadProp_setFile(&dp, (char*)disablecounter) ) { r = DeadProp_getRoot(&dp); if(o->deadPropCount) { for(i = 0 ; i < o->deadPropCount ; i++) { n = o->deadPropList[i]; n = DeadProp_getProp( &dp, SXmlNode_getNs(n,o->r), SXmlNode_getName(n, o->r)); if(n) o->deadPropStack[powerdevice++] = n; else o->deadPropStack[--chargermachinfo] = o->deadPropList[i]; } } else validcache=TRUE; } else if(o->deadPropCount) { baAssert(o->liveProp != LivePropT_AllProp); for(i = 0 ; i < o->deadPropCount ; i++) o->deadPropStack[i] = o->deadPropList[i]; chargermachinfo=0; } } BufPrint_printf(out,responseHeaderFmt,url); if(o->liveProp || powerdevice) { BufPrint_write(out,needsbounce,sizeof(needsbounce)-1); if(powerdevice || validcache) { sffsdrnandflash = SlException_INIT(ex); if(sffsdrnandflash) goto L_exception; procfsmount=TRUE; NsTree_constructor(&nst, o->webDAV->alloc, &ex); if(powerdevice) { for(i = 0 ; i < powerdevice ; i++) NsTree_addNs(&nst, o->deadPropStack[i], (SXmlRoot*)r); } else { for(n=DeadProp_getFirstProp(&dp) ; n ; n=DeadProp_getNextProp(&dp)) NsTree_addNs(&nst, n, DeadProp_getRoot(&dp)); } NsTree_printNsAttrList(&nst, '\146', out); } BufPrint_write(out, "\076\012", 2); if(o->liveProp) { if((o->liveProp & LivePropT_Getetag) || (o->liveProp == LivePropT_AllProp)) printDavElem(out,"\147\145\164\145\164\141\147","\045\170",st->lastModified); if((o->liveProp & LivePropT_Getlastmodified) || (o->liveProp == LivePropT_AllProp)) { char ktextsource[40]; httpFmtDate(ktextsource,sizeof(ktextsource),st->lastModified); printDavElem(out,"\147\145\164\154\141\163\164\155\157\144\151\146\151\145\144","\045\163",ktextsource); } if((o->liveProp & LivePropT_Lockdiscovery) || (o->liveProp == LivePropT_AllProp)) { devicepanel = LockContainer_find(&o->webDAV->lock, gpio1config); if(devicepanel) { printboard( (LockNode*)devicepanel,&o->webDAV->lock,out); } } if(o->liveProp & LivePropT_Supportedlock) { static const char apecsprocdata[] = { "\074\104\072\163\165\160\160\157\162\164\145\144\154\157\143\153\076\012" "\074\104\072\154\157\143\153\145\156\164\162\171\076\012" "\074\104\072\154\157\143\153\163\143\157\160\145\076\074\104\072\145\170\143\154\165\163\151\166\145\057\076\074\057\104\072\154\157\143\153\163\143\157\160\145\076\012" "\074\104\072\154\157\143\153\164\171\160\145\076\074\104\072\167\162\151\164\145\057\076\074\057\104\072\154\157\143\153\164\171\160\145\076\012" "\074\057\104\072\154\157\143\153\145\156\164\162\171\076\012" "\074\057\104\072\163\165\160\160\157\162\164\145\144\154\157\143\153\076\012"}; BufPrint_write(out, apecsprocdata, sizeof(apecsprocdata)-1); } if(st->isDir) { if((o->liveProp & LivePropT_Resourcetype) || (o->liveProp == LivePropT_AllProp)) { printDavElem(out,"\162\145\163\157\165\162\143\145\164\171\160\145","\045\163","\074\104\072\143\157\154\154\145\143\164\151\157\156\057\076"); } } else { if((o->liveProp & LivePropT_Resourcetype) || (o->liveProp == LivePropT_AllProp)) { printDavElem(out,"\162\145\163\157\165\162\143\145\164\171\160\145",0); } if((o->liveProp & LivePropT_Getcontentlength) || (o->liveProp == LivePropT_AllProp)) { printDavElem(out,"\147\145\164\143\157\156\164\145\156\164\154\145\156\147\164\150",BA_FILE_FMT,st->size); } if((o->liveProp & LivePropT_Getcontenttype) || (o->liveProp == LivePropT_AllProp)) { defaultattrs = getContentType(gpio1config); if(defaultattrs) printDavElem(out,"\147\145\164\143\157\156\164\145\156\164\164\171\160\145","\045\163",defaultattrs); } } } if(powerdevice || validcache) { s = NsTree_createSerializer(&nst, '\146', out); if(powerdevice) { for(i = 0 ; i < powerdevice ; i++) { SerializeSXml_printNode(s, o->deadPropStack[i], (SXmlRoot*)r, FALSE); } } else { for(n=DeadProp_getFirstProp(&dp) ; n ; n=DeadProp_getNextProp(&dp)) SerializeSXml_printNode(s, n, DeadProp_getRoot(&dp), FALSE); } procfsmount=FALSE; NsTree_destructor(&nst); } BufPrint_printf(out,allocdriver,okMsg); } if(chargermachinfo != o->deadPropCount || o->hasBuffer || (st->isDir && (o->liveProp & LivePropT_Getcontentlength)) ) { BufPrint_write(out,needsbounce,sizeof(needsbounce)-1); if(chargermachinfo != o->deadPropCount) { sffsdrnandflash = SlException_INIT(ex); if(sffsdrnandflash) goto L_exception; NsTree_constructor(&nst, o->webDAV->alloc, &ex); for(i = chargermachinfo ; i < o->deadPropCount ; i++) NsTree_addNs(&nst, o->deadPropStack[i], o->r); NsTree_printNsAttrList(&nst, '\156', out); BufPrint_write(out, "\076\012", 2); for(i = chargermachinfo ; i < o->deadPropCount ; i++) { n = o->deadPropStack[i]; BufPrint_printf(out, "\074\156\045\170\072\045\163\057\076\012", NsTree_getNsId(&nst,SXmlNode_getNs(n,o->r)), SXmlNode_getName(n, o->r)); } procfsmount=FALSE; NsTree_destructor(&nst); } else BufPrint_write(out, "\076\012", 2); if(o->hasBuffer) { BufPrint_write(out, DynBuffer_getBuf((DynBuffer*)o), DynBuffer_getBufSize((DynBuffer*)o)); } if((o->liveProp & LivePropT_Getcontentlength) && st->isDir) printDavElem(out, "\147\145\164\143\157\156\164\145\156\164\154\145\156\147\164\150", 0); if((o->liveProp & LivePropT_Getcontenttype) && !defaultattrs) printDavElem(out, "\147\145\164\143\157\156\164\145\156\164\164\171\160\145", 0); if((o->liveProp & LivePropT_Lockdiscovery) && !devicepanel) printDavElem(out, "\154\157\143\153\144\151\163\143\157\166\145\162\171", 0); BufPrint_printf(out,allocdriver,notFoundMsg); } L_exception: if(o->deadPropCount) DeadProp_destructor(&dp); if(procfsmount) NsTree_destructor(&nst); if(disablecounter) AllocatorIntf_free(o->webDAV->alloc, (char*)disablecounter); if(sffsdrnandflash) netdevicenotifier(o); if(s) AllocatorIntf_free(o->webDAV->alloc, s); BufPrint_write(out,responseFooter,sizeof(responseFooter)-1); return 0; } static BaBool resourceflags(WebDAV* o, const char* gpio1config) { IoStat st; return o->io->statFp(o->io, gpio1config, &st) ? FALSE : TRUE; } static int kprobeindex(WebDAV* o, const char* driverregister, HttpCommand* cmd) { size_t len; const char* mlogbuffinish = HttpRequest_getRequestURI(&cmd->request); if(o->vdRootPath) AllocatorIntf_free(o->alloc,o->vdRootPath); if(*driverregister) { const char* ptr = strstr(mlogbuffinish, driverregister); if(ptr) { len = ptr - mlogbuffinish; } else len = strlen(mlogbuffinish); } else len = strlen(mlogbuffinish); o->vdRootPathLen=len; len+=2; o->vdRootPath = AllocatorIntf_malloc(o->alloc,&len); if(!o->vdRootPath) { sendHttpResp(cmd, 503,0); return -1; } strncpy(o->vdRootPath, mlogbuffinish, o->vdRootPathLen); if(o->vdRootPath[o->vdRootPathLen-1] == '\057') o->vdRootPath[o->vdRootPathLen]=0; else { o->vdRootPath[o->vdRootPathLen++]='\057'; o->vdRootPath[o->vdRootPathLen]=0; } return 0; } static const char* WebDAV_ioName2URL(WebDAV* o, const char* driverregister, HttpCommand* cmd) { size_t len = o->vdRootPathLen + strlen(driverregister) + 1; char* ptracepokedata = AllocatorIntf_malloc(o->alloc,&len); if(ptracepokedata) { const char* url; basnprintf(ptracepokedata, (int)len, "\045\163\045\163", o->vdRootPath, driverregister); url = HttpResponse_encodeRedirectURL(&cmd->response, ptracepokedata); AllocatorIntf_free(o->alloc, ptracepokedata); return url; } return 0; } static WebDAV* WebDAV_uploadCbIntf2Obj(HttpUploadCbIntf* fdc37m81xconfig) { return (WebDAV*)((U8*)fdc37m81xconfig-offsetof(WebDAV,uploadCb)); } static void l2c310coherent(HttpAsynchResp* r3000write, int flushoffset, const char* embedfirst) { int len = embedfirst ? iStrlen(embedfirst) : 0; HttpAsynchResp_setConClose(r3000write); HttpAsynchResp_setStatus(r3000write, baErr2HttpCode(flushoffset), 0); HttpAsynchResp_sendData(r3000write, embedfirst, len, len); } static void platformdriver(HttpUploadCbIntf* fdc37m81xconfig, struct HttpUploadNode* smartreflexhwmod, BaBool requestvector) { IoStat st; HttpAsynchResp* r3000write; int sffsdrnandflash; WebDAV* o; baAssert( ! HttpUploadNode_isMultipartUpload(smartreflexhwmod) ); baAssert(requestvector); o = WebDAV_uploadCbIntf2Obj(fdc37m81xconfig); r3000write = HttpUploadNode_getResponse(smartreflexhwmod); if( (sffsdrnandflash=o->io->statFp(o->io, HttpUploadNode_getName(smartreflexhwmod), &st)) == 0) { char buf[9]; baConvU32ToHex(buf, (U32)st.lastModified); buf[8]=0; HttpAsynchResp_setStatus (r3000write, 201, 0); HttpAsynchResp_setHeader(r3000write, "\105\164\141\147", buf); HttpAsynchResp_sendData(r3000write, 0, 0, 0); } else l2c310coherent(r3000write, sffsdrnandflash, 0); } static void clockprint(HttpUploadCbIntf* fdc37m81xconfig, struct HttpUploadNode* smartreflexhwmod, int flushoffset, const char* embedfirst) { HttpAsynchResp* r3000write; (void)fdc37m81xconfig; baAssert( ! HttpUploadNode_isMultipartUpload(smartreflexhwmod) ); r3000write = HttpUploadNode_getResponse(smartreflexhwmod); l2c310coherent(r3000write, flushoffset, embedfirst); } static int sha256transform(WebDAV* o, HttpCommand* cmd, U16* simulatebxblx, BaBool detectflash) { BaFileSize rollbackhandler = HttpStdHeaders_getContentLength( HttpRequest_getStdHeaders(&cmd->request)); U32 lsdc2format=HttpInData_getBufSize(HttpRequest_getBuffer(&cmd->request)); (void)o; if(rollbackhandler == 0 && !detectflash) { HttpResponse_sendError1(&cmd->response,411); return -1; } if(rollbackhandler > lsdc2format) { HttpResponse_sendError1(&cmd->response,413); return -1; } *simulatebxblx = (U16)rollbackhandler; return 0; } static void resetstate(WebDAV* o, const char* driverregister, HttpCommand* cmd, IoStat* st) { U16 simulatebxblx; int sffsdrnandflash; SlException ex; Propfind propfind; BufPrint* out = HttpResponse_getWriter(&cmd->response); AuthenticatedUser* buttonsbelkin = AuthenticatedUser_get1(&cmd->request); if(sha256transform(o, cmd, &simulatebxblx, TRUE)) return; if(kprobeindex(o, driverregister, cmd)) return; sffsdrnandflash = SlException_INIT(ex); if(sffsdrnandflash) { sendHttpResp(cmd,sffsdrnandflash==SXmlErrT_Mem ? 503 : 400,0); } else { int buttonsresource = !*driverregister || driverregister[strlen(driverregister)-1] == '\057'; tps65021consumers( &propfind, HttpInData_getBuf(HttpRequest_getBuffer(&cmd->request)), simulatebxblx, o, cmd, buttonsbelkin, TRUE, &ex); blocksha512(&cmd->response); uart2resources(out); if(st->isDir) { if(!cachelevel(&propfind,driverregister,st) && !nvmemmatch(cmd)) { int sffsdrnandflash; DirIntfPtr dir = o->io->openDirFp(o->io, driverregister, &sffsdrnandflash, 0); if(dir) { IoStat sst; while ( ! dir->readFp(dir) ) { const char* gpio1config = dir->getNameFp(dir); if( ( gpio1config[0]== '\056'&& ( ! gpio1config[1]|| (gpio1config[1]=='\056'&&!gpio1config[2]) || (gpio1config[1]=='\104'&&gpio1config[2]=='\101'&&gpio1config[3]=='\126'&&!gpio1config[4]) ) ) ) { continue; } if( ! dir->statFp(dir, &sst) ) { size_t len = strlen(driverregister) + strlen(gpio1config) + 3; char* n2 = AllocatorIntf_malloc(o->alloc,&len); if(n2) { const char* fmt; if(buttonsresource) { fmt = sst.isDir ? "\045\163\045\163\057" : "\045\163\045\163"; } else { fmt = sst.isDir ? "\045\163\057\045\163\057" : "\045\163\057\045\163"; } basnprintf(n2, (int)len,fmt,driverregister,gpio1config); cachelevel(&propfind, n2, &sst); AllocatorIntf_free(o->alloc, n2); } } } o->io->closeDirFp(o->io, &dir); } } } else { cachelevel(&propfind, driverregister, st); } uninstallidmap(out); } vgg2432a4display(&propfind); } static int buildmpidr(WebDAV* o, const char* gpio1config, HttpCommand* cmd) { U16 simulatebxblx; Propfind propfind; LockNode* ln; int sffsdrnandflash = -1; AuthenticatedUser* buttonsbelkin = AuthenticatedUser_get1(&cmd->request); if(sha256transform(o, cmd, &simulatebxblx, TRUE)) return 0; if( ! LockContainer_isEnabled(&o->lock) ) { sendHttpResp(cmd,404,0); return 0; } ln = LockContainer_find(&o->lock, gpio1config); if(ln) { SlException ex; sffsdrnandflash = SlException_INIT(ex); if(sffsdrnandflash) { sendHttpResp(cmd,sffsdrnandflash==SXmlErrT_Mem ? 503 : 400,0); sffsdrnandflash=0; } else { IoStat st; BufPrint* out = HttpResponse_getWriter(&cmd->response); memset(&st, 0, sizeof(IoStat)); tps65021consumers( &propfind, HttpInData_getBuf(HttpRequest_getBuffer(&cmd->request)), simulatebxblx, o, cmd, buttonsbelkin, FALSE, &ex); if(propfind.liveProp == LivePropT_AllProp) { propfind.liveProp = LivePropT_Lockdiscovery; propfind.liveProp |= LivePropT_Supportedlock; } blocksha512(&cmd->response); uart2resources(out); cachelevel(&propfind, gpio1config, &st); uninstallidmap(out); sffsdrnandflash=0; } vgg2432a4display(&propfind); } return sffsdrnandflash; } static void accessfault(WebDAV* o, const char* gpio1config, HttpCommand* cmd) { SXmlRoot r; DeadProp dp; SlException ex; int sffsdrnandflash; U16 simulatebxblx; volatile BaBool devicesm501=FALSE; char* volatile disablecounter=0; BufPrint* out = HttpResponse_getWriter(&cmd->response); if(sha256transform(o, cmd, &simulatebxblx, FALSE)) return; sffsdrnandflash = SlException_INIT(ex); if(sffsdrnandflash) { sendHttpResp(cmd,sffsdrnandflash==SXmlErrT_Mem ? 503 : 400,0); } else { SXmlNode* setRemPropN; SXmlNsNode* nsn; const char* url; SXmlRoot_constructor2( &r, o->alloc, (U8*)HttpInData_getBuf(HttpRequest_getBuffer(&cmd->request)), simulatebxblx, (U16)(simulatebxblx/4), &ex); disablecounter = DeadProp_fname2PropFName(o->alloc, gpio1config); SlException_assertE(&ex, disablecounter, SXmlErrT_Mem); devicesm501=TRUE; DeadProp_constructor(&dp, o->io, o->alloc); DeadProp_setFile(&dp, (char*)disablecounter); blocksha512(&cmd->response); BufPrint_write(out,xmlMultistatusHead,sizeof(xmlMultistatusHead)-1); for(nsn = SXmlRoot_firstNsNode(&r); nsn; nsn=SXmlNsNode_next(nsn,&r)) { BufPrint_printf(out,"\040\170\155\154\156\163\072\156\045\170\075\042\045\163\042", SXmlNsNode_getNsId(nsn),SXmlNsNode_getNs(nsn,&r)); } BufPrint_write(out,"\076\012",2); url = HttpRequest_getRequestURL(&cmd->request,FALSE); if(!url) SlException_set(&ex,SXmlErrT_Mem); BufPrint_printf(out,responseHeaderFmt,url); setRemPropN = SXmlRoot_firstChild(&r); SlException_assertE(&ex, setRemPropN, SXmlErrT_Err); setRemPropN = SXmlNode_firstChild(setRemPropN,&r); while(setRemPropN) { SXmlNode* propN; const char* gpio1config; propN = SXmlNode_firstChild(setRemPropN,&r); SlException_assertE(&ex, propN, SXmlErrT_Err); propN = SXmlNode_firstChild(propN,&r); SlException_assertE(&ex, propN, SXmlErrT_Err); gpio1config = SXmlNode_getName(setRemPropN,&r); if(!strcmp(gpio1config, "\163\145\164")) { if(DeadProp_setProp(&dp, propN, &r)) SlException_set(&ex, SXmlErrT_Mem); } else { SlException_assertE(&ex, !strcmp(gpio1config, "\162\145\155\157\166\145"), SXmlErrT_Err); DeadProp_removeProp(&dp, propN, &r); } BufPrint_printf(out, "\074\104\072\160\162\157\160\163\164\141\164\076\012" "\074\104\072\160\162\157\160\076\074\156\045\170\072\045\163\057\076\074\057\104\072\160\162\157\160\076\012" "\074\104\072\163\164\141\164\165\163\076\110\124\124\120\057\061\056\061\040\045\163\074\057\104\072\163\164\141\164\165\163\076\012" "\074\057\104\072\160\162\157\160\163\164\141\164\076\012", SXmlNode_getNsId(propN), SXmlNode_getName(propN, &r), okMsg); setRemPropN = SXmlNode_next(setRemPropN, &r); } if(DeadProp_save(&dp)) { HttpResponse_sendError1(&cmd->response,403); } else { BufPrint_write(out,responseFooter,sizeof(responseFooter)-1); uninstallidmap(out); } } SXmlRoot_destructor(&r); if(devicesm501) DeadProp_destructor(&dp); if(disablecounter) AllocatorIntf_free(o->alloc,(void*)disablecounter); } static void nhpoly1305final(WebDAV* o, const char* gpio1config, HttpCommand* cmd) { const char* ethernatenable; int sffsdrnandflash; if(HttpStdHeaders_getContentLength( HttpRequest_getStdHeaders(&cmd->request)) != 0) { HttpResponse_sendError1(&cmd->response, 415); return; } sffsdrnandflash = o->io->mkDirFp(o->io, gpio1config, ðernatenable); if(sffsdrnandflash) { HttpResponse_sendError2(&cmd->response, baErr2HttpCode(sffsdrnandflash), ethernatenable ? ethernatenable : baErr2Str(sffsdrnandflash)); } else sendHttpResp(cmd, 201, 0); } static void defaultvector(WebDAV* o, const char* gpio1config, HttpCommand* cmd, BaBool alignmentfault) { LockNode* ln; U16 simulatebxblx; if(sha256transform(o, cmd, &simulatebxblx, TRUE)) return; if( ! LockContainer_isEnabled(&o->lock) ) { sendHttpResp(cmd,403,0); return; } ln = LockContainer_find(&o->lock, gpio1config); if(simulatebxblx) { SlException ex; SXmlRoot r; int sffsdrnandflash; if(ln) HttpResponse_sendError1(&cmd->response, 423); else { sffsdrnandflash = SlException_INIT(ex); if(sffsdrnandflash) { sendHttpResp(cmd,sffsdrnandflash==SXmlErrT_Mem ? 503 : 400,0); } else { SXmlNode* n; U32 pciercxcfg035=(U32)~0; const char* interfacenumber = (char*)HttpRequest_getHeaderValue( &cmd->request, "\124\151\155\145\157\165\164"); const char* ptr = interfacenumber ? strstr(interfacenumber, "\123\145\143\157\156\144\055") : 0; if(ptr) { const char* end; ptr+=7; end=ptr; while( isdigit(*end) ) end++; pciercxcfg035 = U32_atoi2(ptr,end); } SXmlRoot_constructor2( &r, o->alloc, (U8*)HttpInData_getBuf(HttpRequest_getBuffer(&cmd->request)), simulatebxblx, (U16)(simulatebxblx/4), &ex); n = SXmlRoot_firstChild(&r); if(!n) SlException_set(&ex, SXmlErrT_Err); n = SXmlRoot_firstChild(&r); n = SXmlNode_firstChild(n, &r); if(!n) SlException_set(&ex, SXmlErrT_Err); do { if( !strcmp("\157\167\156\145\162", SXmlNode_getName(n, &r)) ) break; n = SXmlNode_next(n, &r); } while(n); ln = LockContainer_createLN( &o->lock, pciercxcfg035 > 60*60 ? 60*60 : (pciercxcfg035 < 5*60 ? 5*60 : pciercxcfg035), gpio1config); if(ln) { if( ! n || ! LockNode_setOwner(ln,&o->lock, n, &r) ) { HttpResponse_setStatus(&cmd->response, alignmentfault?200:201); SXmlRoot_destructor(&r); goto L_sendResponse; } else { wm97xxprobe(&o->lock,ln); sendHttpResp(cmd,409,0); } } else sendHttpResp(cmd,503,0); } SXmlRoot_destructor(&r); } } else { HttpResponse_setStatus(&cmd->response, 200); L_sendResponse: if(ln) { BufPrint* out = HttpResponse_getWriter(&cmd->response); resumenoirq(&cmd->response); cryptodisable(ln, cmd); BufPrint_printf(out,"\045\163\045\163",xmlHeader,"\074\104\072\160\162\157\160\040\170\155\154\156\163\072\104\075\042\104\101\126\072\042\076\012"); printboard(ln, &o->lock, out); BufPrint_write2(out,"\074\057\104\072\160\162\157\160\076"); regulatorconfig(ln); } else sendHttpResp(cmd,404,0); } } static void omap3630toggle(WebDAV* o, const char* gpio1config, HttpCommand* cmd) { LockNode* ln; U16 simulatebxblx; if(sha256transform(o, cmd, &simulatebxblx, TRUE)) return; if( ! LockContainer_isEnabled(&o->lock) ) { sendHttpResp(cmd,403,0); return; } ln = LockContainer_find(&o->lock, gpio1config); if(ln) { wm97xxprobe(&o->lock,ln); sendHttpResp(cmd,204,0); } else sendHttpResp(cmd,404,0); } static void targetready(WebDAV* o, HttpCommand* cmd, BaBool usleepthread) { static const char revisionsconid[] = { "\117\120\124\111\117\116\123\054\040\107\105\124\054\040\110\105\101\104\054\040\120\122\117\120\106\111\116\104"}; static const char gpio2hwmod[] = { "\054\040\120\125\124\054\040\103\117\120\131\054\040\104\105\114\105\124\105\054\040\115\117\126\105\054\040\115\113\103\117\114\054\040\120\122\117\120\106\111\116\104\054\040\120\122\117\120\120\101\124\103\110"}; static const char sdio1resources[] = { "\054\040\114\117\103\113\054\040\125\116\114\117\103\113"}; char* val; int doubleftosiz = sizeof(revisionsconid)-1; if( ! o->ioReadOnly ) { doubleftosiz += (sizeof(gpio2hwmod)-1); if(LockContainer_isEnabled(&o->lock)) { doubleftosiz += (sizeof(sdio1resources)-1); } } doubleftosiz++; val = HttpResponse_fmtHeader(&cmd->response,"\101\154\154\157\167", doubleftosiz, TRUE); if(val) { if(LockContainer_isEnabled(&o->lock)) { basnprintf(val, doubleftosiz, "\045\163\045\163\045\163", revisionsconid, gpio2hwmod, sdio1resources); HttpResponse_setHeader(&cmd->response,"\104\101\126", "\061\054\040\062",TRUE); } else { if( ! o->ioReadOnly ) basnprintf(val, doubleftosiz, "\045\163\045\163", revisionsconid, gpio2hwmod); else basnprintf(val, doubleftosiz, "\045\163", revisionsconid); HttpResponse_setHeader(&cmd->response,"\104\101\126", "\061",TRUE); } } HttpResponse_setHeader(&cmd->response,"\115\123\055\101\165\164\150\157\162\055\126\151\141", "\104\101\126",TRUE); if(usleepthread) HttpResponse_sendError2(&cmd->response, 405, val); else HttpResponse_setContentLength(&cmd->response, 0); } static void cpumasksiblings(WebDAV* o, const char* driverregister, HttpCommand* cmd) { const char* ext = strrchr(driverregister, '\056'); const char* emupageallocmap = ext && (ext = httpFindMime(++ext)) ? ext : "\141\160\160\154\151\143\141\164\151\157\156\057\157\143\164\145\164\055\163\164\162\145\141\155"; (void)o; HttpResponse_setContentType(&cmd->response, emupageallocmap); } static int activeranges(HttpCommand* cmd, IoStat* st) { const char* poweroffrequired; if(st) { poweroffrequired = HttpRequest_getHeaderValue(&cmd->request, "\111\146\055\116\157\156\145\055\115\141\164\143\150"); if(poweroffrequired) { if( (poweroffrequired[0] == '\052' && ! poweroffrequired[1]) || (strlen(poweroffrequired) == 8 && baConvHexToU32(poweroffrequired) == st->lastModified) ) { HttpResponse_sendError1(&cmd->response, 412); return -1; } } poweroffrequired = HttpRequest_getHeaderValue(&cmd->request, "\111\146\055\115\141\164\143\150"); if(poweroffrequired) { if( ! (poweroffrequired[0] == '\052' && ! poweroffrequired[1]) && ! (strlen(poweroffrequired)==8 && baConvHexToU32(poweroffrequired)==st->lastModified) ) { HttpResponse_sendError1(&cmd->response, 412); return -1; } } } else if(HttpRequest_getHeaderValue(&cmd->request, "\111\146\055\115\141\164\143\150")) { HttpResponse_sendError1(&cmd->response, 412); return -1; } return 0; } static int createprivate(WebDAV* o, const char* src, const char* pciercxcfg448, HttpCommand* cmd, HttpMethod disableparity) { IoAuth pmuv3event; int emulaterd8pc16; AuthenticatedUser* buttonsbelkin = AuthenticatedUser_get1(&cmd->request); if(buttonsbelkin) { IoAuth_constructor(&pmuv3event, o, buttonsbelkin, disableparity, pciercxcfg448); emulaterd8pc16 = IoAuth_doResource(&pmuv3event, src, pciercxcfg448); } else emulaterd8pc16 = 403; if(emulaterd8pc16) sendHttpResp(cmd, emulaterd8pc16, "\120\145\162\155\151\163\151\157\156\040\144\145\156\151\145\144\040\157\156\040\045\163", src); return emulaterd8pc16; } static void cpufreqpdata(WebDAV* o, const char* driverregister, HttpCommand* cmd, IoStat* st, HttpMethod disableparity) { int sffsdrnandflash = -1; const char* pciercxcfg448; BaBool srioxstatus=FALSE; if(kprobeindex(o, driverregister, cmd)) return; if(disableparity == HttpMethod_Delete) pciercxcfg448=0; else { pciercxcfg448 = HttpRequest_getHeaderValue(&cmd->request, "\104\145\163\164\151\156\141\164\151\157\156"); if(pciercxcfg448) { pciercxcfg448 = strstr(pciercxcfg448, "\072\057\057"); if(pciercxcfg448) { pciercxcfg448 += 3; httpUnescape((char*)pciercxcfg448); baElideDotDot((char*)pciercxcfg448); pciercxcfg448 = strstr(pciercxcfg448, o->vdRootPath); if(pciercxcfg448) { if(strlen(pciercxcfg448) >= o->vdRootPathLen) { pciercxcfg448+=o->vdRootPathLen; goto L_action; } } } } HttpResponse_sendError1(&cmd->response,502); return; } L_action: if(!((HttpDir*)o)->realm || !createprivate(o,driverregister,pciercxcfg448,cmd,disableparity)) { IoCtrl ctrl; if(st->isDir) { const char* flushoffset; if(disableparity == HttpMethod_Copy && nvmemmatch(cmd)) { sffsdrnandflash = o->io->mkDirFp(o->io, pciercxcfg448, &flushoffset); if(sffsdrnandflash) { sendHttpResp(cmd, baErr2HttpCode(sffsdrnandflash), "\103\141\156\156\157\164\040\143\157\160\171\040\045\163\040\164\157\040\045\163\056\040\045\163", driverregister, pciercxcfg448, flushoffset ? flushoffset : baErr2Str(sffsdrnandflash)); } else goto L_copyPropertyFile; } if(disableparity == HttpMethod_Move && o->ioMoveDir && ! resourceflags(o, pciercxcfg448)) { sffsdrnandflash = o->io->renameFp(o->io, driverregister, pciercxcfg448, &flushoffset); if(sffsdrnandflash) { sendHttpResp(cmd, baErr2HttpCode(sffsdrnandflash), "\103\141\156\156\157\164\040\155\157\166\145\040\045\163\040\164\157\040\045\163\056\040\045\163", driverregister, pciercxcfg448, flushoffset ? flushoffset : baErr2Str(sffsdrnandflash)); } } else { secureupdate(&ctrl, o, cmd, disableparity); sffsdrnandflash = IoCtrl_doResource(&ctrl, driverregister, pciercxcfg448); srioxstatus=ctrl.resourceReplaced; } } else { secureupdate(&ctrl, o, cmd, disableparity); if( ! resetbluetooth((RecIoIter*)&ctrl,driverregister,pciercxcfg448,st) ) { char* prefetchenable; srioxstatus=ctrl.resourceReplaced; L_copyPropertyFile: prefetchenable = DeadProp_fname2PropFName(o->alloc, driverregister); if(prefetchenable) { if( ! o->io->statFp(o->io, prefetchenable, st) ) { char* runtimedisabled=pciercxcfg448?DeadProp_fname2PropFName(o->alloc,pciercxcfg448):0; if(!pciercxcfg448 || runtimedisabled) { if(runtimedisabled) DeadProp_mkPropDir(o->io, runtimedisabled); resetbluetooth((RecIoIter*)&ctrl,prefetchenable,runtimedisabled,st); if(runtimedisabled) AllocatorIntf_free(o->alloc,runtimedisabled); sffsdrnandflash=0; } } else sffsdrnandflash=0; AllocatorIntf_free(o->alloc,prefetchenable); } if(sffsdrnandflash) sendHttpResp(cmd, 503, 0); } } if( ! sffsdrnandflash ) { HttpResponse_setStatus( &cmd->response, disableparity == HttpMethod_Delete || srioxstatus ? 204 : 201); HttpResponse_setContentLength(&cmd->response, 0); } } } #if 0 static int devinitsmartreflex(HttpCommand* cmd, const char* driverregister) { if(*driverregister && driverregister[strlen(driverregister)-1] != '\057') { const char* uri=HttpRequest_getRequestURI(&cmd->request); int len=strlen(uri)+2; char* p=(char*)baMalloc(len); if(p) { const char* url; basnprintf(p,len,"\045\163\057",uri); url=HttpResponse_encodeRedirectURL(&cmd->response,p); baFree(p); if(url) { HttpResponse_sendRedirect(&cmd->response, url); return 1; } } HttpResponse_sendError1(&cmd->response, 500); return 1; } return 0; } #endif static int branchunlikely(HttpDir* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { HttpMethod convMethod; IoStat st; BaBool alignmentfault; HttpMethod disableparity; AuthenticatedUser* buttonsbelkin; int handlersetup=0; WebDAV* o = (WebDAV*)fdc37m81xconfig; allocahash(cmd); if( !cmd ) { WebDAV_destructor(o); return 0; } if(!HttpResponse_initial(&cmd->response)) return -1; if( (disableparity=HttpRequest_getMethodType(&cmd->request)) == HttpMethod_Options) { targetready(o,cmd, FALSE); return 0; } if(((HttpDir*)o)->authenticator) { buttonsbelkin = AuthenticatorIntf_authenticate( ((HttpDir*)o)->authenticator,driverregister,cmd); if(!buttonsbelkin) return 0; } else if(((HttpDir*)o)->realm) { if( !(buttonsbelkin = AuthenticatedUser_get1(&cmd->request)) ) { HttpResponse_sendError1(&cmd->response, 403); return 0; } } else buttonsbelkin=0; switch(disableparity) { case HttpMethod_Head: convMethod = HttpMethod_Get; break; case HttpMethod_Lock: case HttpMethod_Unlock: convMethod = HttpMethod_Proppatch; break; default: convMethod = disableparity; } if(((HttpDir*)o)->realm && ! AuthorizerIntf_authorize(((HttpDir*)o)->realm, buttonsbelkin, convMethod, driverregister) ) { if(convMethod == HttpMethod_Propfind) { if(detecticache(&cmd->request)) { BufPrint* out = HttpResponse_getWriter(&cmd->response); uart2resources(out); BufPrint_printf(out,responseHeaderFmt, HttpRequest_getRequestURL(&cmd->request,FALSE)); BufPrint_write(out,responseFooter,sizeof(responseFooter)-1); uninstallidmap(out); return 0; } } HttpResponse_sendError1(&cmd->response,403); return 0; } if(o->ioReadOnly) { switch(disableparity) { case HttpMethod_Get: case HttpMethod_Head: case HttpMethod_Propfind: break; default: targetready(o,cmd, TRUE); return 0; } } alignmentfault = o->io->statFp(o->io, driverregister, &st) ? FALSE : TRUE; if(!alignmentfault) { switch(disableparity) { case HttpMethod_Mkcol: case HttpMethod_Put: case HttpMethod_Lock: case HttpMethod_Unlock: break; case HttpMethod_Propfind: if(kprobeindex(o, driverregister, cmd)) return 0; if( ! buildmpidr(o, driverregister, cmd) ) return 0; default: sendHttpResp(cmd,404,0); return 0; } } else if(driverregister[strlen(driverregister)-1] == '\057') { if( ! st.isDir ) { sendHttpResp(cmd,404,0); return 0; } } switch(disableparity) { case HttpMethod_Get: case HttpMethod_Head: if(st.isDir) handlersetup=-1; else { cpumasksiblings(o, driverregister, cmd); HttpResRdr_sendFile(o->io, driverregister, &st, cmd); } break; case HttpMethod_Put: if(alignmentfault && st.isDir) HttpResponse_sendError1(&cmd->response, 403); else if( ! activeranges(cmd, alignmentfault ? &st : 0) ) if(HttpUpload_service(&o->upload, driverregister, cmd, 0)) HttpResponse_sendError1(&cmd->response, 415); break; case HttpMethod_Copy: case HttpMethod_Delete: case HttpMethod_Move: if( ! activeranges(cmd, &st) ) cpufreqpdata(o, driverregister, cmd, &st, disableparity); break; case HttpMethod_Mkcol: if(alignmentfault) { sendHttpResp(cmd,405,0); } else nhpoly1305final(o, driverregister, cmd); break; case HttpMethod_Propfind: resetstate(o, driverregister, cmd, &st); break; case HttpMethod_Proppatch: accessfault(o, driverregister, cmd); break; case HttpMethod_Lock: defaultvector(o, driverregister, cmd, alignmentfault); break; case HttpMethod_Unlock: omap3630toggle(o, driverregister, cmd); break; default: targetready(o,cmd, TRUE); } return handlersetup; } void WebDAV_constructor(WebDAV* o, IoIntf* io, int ls037modes, const char* statenames, const char* checkoptimized, U32 serial2pdata, AllocatorIntf* unmapaliases, S8 gpio1resources) { U32 val; HttpDir_constructor((HttpDir*)o, statenames, gpio1resources); HttpDir_setService((HttpDir*)o, branchunlikely); HttpUploadCbIntf_constructor(&o->uploadCb, platformdriver, clockprint); o->alloc = unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); o->io = io; o->vdRootPath=0; o->ioReadOnly = io->removeFp ? FALSE : TRUE; o->ioMoveDir = !io->propertyFp(io, "\155\157\166\145\144\151\162", &val, 0) && val == TRUE ? TRUE : FALSE; if(o->ioReadOnly) checkoptimized=0; registerredist(&o->lock, o, checkoptimized, serial2pdata); if(ls037modes <= 0) ls037modes = 1; HttpUpload_constructor(&o->upload, io,o->alloc,&o->uploadCb,ls037modes); } void WebDAV_destructor(WebDAV* o) { HttpUpload_destructor(&o->upload); memoryerror(&o->lock); if(o->vdRootPath) { AllocatorIntf_free(o->alloc,o->vdRootPath); o->vdRootPath=0; } HttpDir_destructor((HttpDir*)o); } int WebDAV_lockmgr(WebDAV* o, WebDAVLockMgr* mgr) { LockNode* ln; if( ! LockContainer_isEnabled(&o->lock) ) return -1; ln=LockContainer_find(&o->lock, mgr->name); switch(mgr->action) { case 0: return ln ? 1 : 0; case 1: if(ln) return -2; ln = LockContainer_createLN(&o->lock,mgr->lockTime,mgr->name); if(ln) { ResIntfPtr res = gpio0resources(ln,&o->lock,OpenRes_WRITE); if(res) { static const char h[]={"\074\156\061\072\157\167\156\145\162\040\170\155\154\156\163\072\156\061\075\042\104\101\126\072\042\076\074\156\061\072\150\162\145\146\076"}; static const char f[]={"\074\057\156\061\072\150\162\145\146\076\074\057\156\061\072\157\167\156\145\162\076"}; res->writeFp(res,h,sizeof(h)-1); res->writeFp(res,mgr->owner, strlen(mgr->owner)); res->writeFp(res,f,sizeof(f)-1); res->closeFp(res); return 0; } } return -10; case 2: if(!ln) return -3; wm97xxprobe(&o->lock,ln); return 0; case 3: if(!ln) return -3; mgr->fp=gpio0resources(ln,&o->lock,OpenRes_READ); mgr->lockTime=ln->expireTime; return 0; } return -10; } #undef G #ifndef BA_LIB #define BA_LIB #endif #include "SharkSslCrypto.h" #include #define SHARKSSL_DIM_ARR(a) (sizeof(a)/sizeof(a[0])) #if (SHARKSSL_SSL_CLIENT_CODE || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_ENABLE_RSA || \ (SHARKSSL_ENABLE_ECDSA && (!SHARKSSL_ECDSA_ONLY_VERIFY))) #if (SHARKSSL_USE_RNG_TINYMT) #define TINYMT32_INIT_MAT1 0xA5A6A7A8 #define TINYMT32_INIT_MAT2 0x12345678 #define TINYMT32_INIT_TMAT 0x55555555 #define branchdelay 127 #define backlightpower 1 #define contiguousreserve 10 #define aemifpdata 8 #define unmaptable (U32)0x7FFFFFFFL #define firstnonsched (1.0f / 4294967296.0f) #define kernelinstr 8 #define framecreation 8 typedef struct SharkSslRngCtx { U32 status[4]; U32 mat1; U32 mat2; U32 tmat; ThreadMutexBase mutex; } SharkSslRngCtx; static SharkSslRngCtx sharkSslRngCtx; static void kernelenable(void) { U32 x, y; y = sharkSslRngCtx.status[3]; x = (sharkSslRngCtx.status[0] & unmaptable) ^ sharkSslRngCtx.status[1] ^ sharkSslRngCtx.status[2]; x ^= (x << backlightpower); y ^= (y >> backlightpower) ^ x; sharkSslRngCtx.status[0] = sharkSslRngCtx.status[1]; sharkSslRngCtx.status[1] = sharkSslRngCtx.status[2]; sharkSslRngCtx.status[2] = x ^ (y << contiguousreserve); sharkSslRngCtx.status[3] = y; sharkSslRngCtx.status[1] ^= (U32)(0L -((U32)(y & 1))) & sharkSslRngCtx.mat1; sharkSslRngCtx.status[2] ^= (U32)(0L -((U32)(y & 1))) & sharkSslRngCtx.mat2; } static U32 classdevregister(void) { U32 t0, t1; kernelenable(); t0 = sharkSslRngCtx.status[3]; t1 = sharkSslRngCtx.status[0] + (sharkSslRngCtx.status[2] >> aemifpdata); t0 ^= t1; t0 ^= (U32)(0L -((U32)(t1 & 1))) & sharkSslRngCtx.tmat; return t0; } static void templaterestore(void) { U8 i; for (i = 1; i < kernelinstr; i++) { sharkSslRngCtx.status[i & 3] ^= i + (U32)(1812433253L) * (sharkSslRngCtx.status[(i - 1) & 3] ^ (sharkSslRngCtx.status[(i - 1) & 3] >> 30)); } if ((sharkSslRngCtx.status[0] & unmaptable) == 0 && sharkSslRngCtx.status[1] == 0 && sharkSslRngCtx.status[2] == 0 && sharkSslRngCtx.status[3] == 0) { sharkSslRngCtx.status[0] = '\124'; sharkSslRngCtx.status[1] = '\111'; sharkSslRngCtx.status[2] = '\116'; sharkSslRngCtx.status[3] = '\131'; } for (i = 0; i < framecreation; i++) { kernelenable(); } } static void enablecounter(U32 suspendblock) { sharkSslRngCtx.status[0] = suspendblock; sharkSslRngCtx.status[1] = sharkSslRngCtx.mat1; sharkSslRngCtx.status[2] = sharkSslRngCtx.mat2; sharkSslRngCtx.status[3] = sharkSslRngCtx.tmat; templaterestore(); } static void registerclkdms(U32 suspendblock) { sharkSslRngCtx.mat1 = sharkSslRngCtx.mat2; sharkSslRngCtx.mat2 = sharkSslRngCtx.tmat; sharkSslRngCtx.tmat = suspendblock; templaterestore(); } #undef framecreation #undef kernelinstr #undef branchdelay #undef backlightpower #undef contiguousreserve #undef aemifpdata #undef unmaptable #undef firstnonsched SHARKSSL_API int sharkssl_entropy(U32 deviceuevent) { if (0 == sharkSslRngCtx.mat1) { U8 i; #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_constructor(&(sharkSslRngCtx.mutex)); ThreadMutex_set(&(sharkSslRngCtx.mutex)); #endif sharkSslRngCtx.mat1 = TINYMT32_INIT_MAT1; sharkSslRngCtx.mat2 = TINYMT32_INIT_MAT2; sharkSslRngCtx.tmat = TINYMT32_INIT_TMAT; enablecounter(deviceuevent); for (i = (U8)(classdevregister() & 0x7F); i > 0; i--) { registerclkdms(classdevregister()); } } else { #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_set(&(sharkSslRngCtx.mutex)); #endif } registerclkdms(deviceuevent); #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_release(&(sharkSslRngCtx.mutex)); #endif return 0; } #undef TINYMT32_INIT_MAT1 #undef TINYMT32_INIT_MAT2 #undef TINYMT32_INIT_TMAT #elif (SHARKSSL_USE_RNG_FORTUNA && SHARKSSL_USE_AES_256 && SHARKSSL_USE_SHA_256) typedef struct SharkSslRngCtx { U8 key[SHARKSSL_SHA256_HASH_LEN]; U8 ctr[16]; /* AES_256_BLOCK_LEN */ U8 blk[16]; /* AES_256_BLOCK_LEN */ U32 cursor; #if SHARKSSL_RNG_MULTITHREADED ThreadMutexBase mutex; #endif } SharkSslRngCtx; static SharkSslRngCtx sharkSslRngCtx; static void uart0resource(void) { register U8 i = 0; while (0 == ++sharkSslRngCtx.ctr[i]) { i = (i + 1) & 0xF; } } static U32 backlightconfig(void) { register U8 *p = &sharkSslRngCtx.ctr[0]; register U32 i = 16; while (i--) { if (*p++) { return 1; } } return 0; } static void dm9k0device(void) { if (backlightconfig()) { SharkSslAesCtx registermcasp; SharkSslAesCtx_constructor(®istermcasp, SharkSslAesCtx_Encrypt, sharkSslRngCtx.key, SHARKSSL_DIM_ARR(sharkSslRngCtx.key)); SharkSslAesCtx_encrypt(®istermcasp, sharkSslRngCtx.ctr, sharkSslRngCtx.blk); SharkSslAesCtx_destructor(®istermcasp); sharkSslRngCtx.cursor = SHARKSSL_DIM_ARR(sharkSslRngCtx.blk); uart0resource(); } } SHARKSSL_API int sharkssl_entropy(U32 deviceuevent) { U8 suspendblock[4]; SharkSslSha256Ctx registermcasp; inputlevel(deviceuevent, suspendblock, 0); SharkSslSha256Ctx_constructor(®istermcasp); #if SHARKSSL_RNG_MULTITHREADED if (!(backlightconfig())) { ThreadMutex_constructor(&(sharkSslRngCtx.mutex)); } ThreadMutex_set(&(sharkSslRngCtx.mutex)); #endif SharkSslSha256Ctx_append(®istermcasp, sharkSslRngCtx.key, SHARKSSL_SHA256_HASH_LEN); SharkSslSha256Ctx_append(®istermcasp, suspendblock, SHARKSSL_DIM_ARR(suspendblock)); SharkSslSha256Ctx_finish(®istermcasp, sharkSslRngCtx.key); uart0resource(); #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_release(&(sharkSslRngCtx.mutex)); #endif return 0; } SHARKSSL_API int sharkssl_rng(U8 *ptr, U16 len) { baAssert(ptr); baAssert((len) && (0 == (len & 0x3))); baAssert(len < (1 << 20)); #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_set(&(sharkSslRngCtx.mutex)); #endif while (len >= 16) { dm9k0device(); memcpy(ptr, &sharkSslRngCtx.blk[0], 16); sharkSslRngCtx.cursor = 0; ptr += 16; len -= 16; } while (len) { register U32 r; if (0 == sharkSslRngCtx.cursor) { dm9k0device(); } sharkSslRngCtx.cursor -= 4; r = (*(__sharkssl_packed U32*)&sharkSslRngCtx.blk[sharkSslRngCtx.cursor]); #ifndef B_LITTLE_ENDIAN inputlevel(r, ptr, 0); #else hsotgpdata(r, ptr, 0); #endif ptr += 4; len -= 4; } dm9k0device(); memcpy(&sharkSslRngCtx.key[0], &sharkSslRngCtx.blk[0], 16); dm9k0device(); memcpy(&sharkSslRngCtx.key[16], &sharkSslRngCtx.blk[0], 16); sharkSslRngCtx.cursor = 0; #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_release(&(sharkSslRngCtx.mutex)); #endif return 0; } #else typedef struct SharkSslRngCtx { U32 randrsl[256]; U32 randmem[256]; U32 randa; U32 randb; U32 randc; U8 randcnt; U8 entropyIndex; #if SHARKSSL_RNG_MULTITHREADED ThreadMutexBase mutex; U8 mutexinit; #endif } SharkSslRngCtx; static SharkSslRngCtx sharkSslRngCtx; #define dcachedirty(mm,x) ((mm)[((x)>>2)&0xFF]) #define devicebuild(totalpages,a,b,mm,m,m2,r,x) \ { \ x = *m; \ a = ((a)^(totalpages)) + *(m2++); \ *(m++) = y = dcachedirty(mm,x) + (a) + (b); \ *(r++) = b = dcachedirty(mm,(y)>>8) + (x); \ } static void doublefuito(void) { register U32 a, b, x, y, *m, *mm, *m2, *r, *mend; mm = sharkSslRngCtx.randmem; r = sharkSslRngCtx.randrsl; a = sharkSslRngCtx.randa; b = sharkSslRngCtx.randb + (++sharkSslRngCtx.randc); for (m = mm, mend = m2 = m + 128; m < mend; ) { devicebuild( a<<13, a, b, mm, m, m2, r, x); devicebuild( a>>6 , a, b, mm, m, m2, r, x); devicebuild( a<<2 , a, b, mm, m, m2, r, x); devicebuild( a>>16, a, b, mm, m, m2, r, x); } for (m2 = mm; m2>6 , a, b, mm, m, m2, r, x); devicebuild( a<<2 , a, b, mm, m, m2, r, x); devicebuild( a>>16, a, b, mm, m, m2, r, x); } sharkSslRngCtx.randb = b; sharkSslRngCtx.randa = a; } #define totalpages(a,b,c,d,e,f,g,h) \ { \ a^=b<<11; d+=a; b+=c; \ b^=c>>2; e+=b; c+=d; \ c^=d<<8; f+=c; d+=e; \ d^=e>>16; g+=d; e+=f; \ e^=f<<10; h+=e; f+=g; \ f^=g>>4; a+=f; g+=h; \ g^=h<<8; b+=g; h+=a; \ h^=a>>9; c+=h; a+=b; \ } static void eventoverflow(void) { U16 i; U32 a , b, c, d, e, f, g, h, *m, *r; sharkSslRngCtx.randa = sharkSslRngCtx.randb = sharkSslRngCtx.randc = 0; m = sharkSslRngCtx.randmem; r = sharkSslRngCtx.randrsl; a = b = c = d = e = f = g = h = 0x9e3779b9; for (i=0; i<4; ++i) { totalpages(a,b,c,d,e,f,g,h); } for (i=0; i<256; i+=8) { a+=r[i ]; b+=r[i+1]; c+=r[i+2]; d+=r[i+3]; e+=r[i+4]; f+=r[i+5]; g+=r[i+6]; h+=r[i+7]; totalpages(a,b,c,d,e,f,g,h); m[i ]=a; m[i+1]=b; m[i+2]=c; m[i+3]=d; m[i+4]=e; m[i+5]=f; m[i+6]=g; m[i+7]=h; } for (i=0; i<256; i+=8) { a+=m[i ]; b+=m[i+1]; c+=m[i+2]; d+=m[i+3]; e+=m[i+4]; f+=m[i+5]; g+=m[i+6]; h+=m[i+7]; totalpages(a,b,c,d,e,f,g,h); m[i ]=a; m[i+1]=b; m[i+2]=c; m[i+3]=d; m[i+4]=e; m[i+5]=f; m[i+6]=g; m[i+7]=h; } doublefuito(); } static U32 classdevregister(void) { register U32 doublefcmpz; if ((sharkSslRngCtx.randcnt & 0xFF) == 0) { doublefuito(); } doublefcmpz = sharkSslRngCtx.randrsl[(--sharkSslRngCtx.randcnt) & 0xFF]; return doublefcmpz; } #undef totalpages #undef devicebuild #undef dcachedirty SHARKSSL_API int sharkssl_entropy(U32 deviceuevent) { #if SHARKSSL_RNG_MULTITHREADED if (!sharkSslRngCtx.mutexinit) { ThreadMutex_constructor(&(sharkSslRngCtx.mutex)); ThreadMutex_set(&(sharkSslRngCtx.mutex)); sharkSslRngCtx.mutexinit++; } else { ThreadMutex_set(&(sharkSslRngCtx.mutex)); } #endif sharkSslRngCtx.randrsl[(sharkSslRngCtx.entropyIndex++) & 0xFF] = deviceuevent; eventoverflow(); #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_release(&(sharkSslRngCtx.mutex)); #endif return 0; } #endif #if (SHARKSSL_USE_RNG_TINYMT || (!SHARKSSL_USE_RNG_FORTUNA)) SHARKSSL_API int sharkssl_rng(U8 *ptr, U16 len) { baAssert(ptr); baAssert((len) && (0 == (len & 0x3))); #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_set(&(sharkSslRngCtx.mutex)); #endif while (len) { register U32 r = classdevregister(); #ifndef B_LITTLE_ENDIAN inputlevel(r, ptr, 0); #else hsotgpdata(r, ptr, 0); #endif ptr += 4; len -= 4; } #if SHARKSSL_RNG_MULTITHREADED ThreadMutex_release(&(sharkSslRngCtx.mutex)); #endif return 0; } #endif #endif #if (SHARKSSL_USE_MD5 || SHARKSSL_USE_SHA1 || SHARKSSL_USE_SHA_256 || SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) #if (SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) static const U8 prusspdata[128] = #else static const U8 prusspdata[64] = #endif { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #if (SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #endif 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #endif #if SHARKSSL_USE_MD5 #if SHARKSSL_MD5_SMALL_FOOTPRINT static const U32 unregisterclient[64] = { 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE, 0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501, 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE, 0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821, 0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA, 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8, 0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED, 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A, 0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C, 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70, 0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05, 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665, 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039, 0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1, 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1, 0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391 }; static const U8 keypadresources[64] = { 7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22, 5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20, 4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23, 6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21 }; static const U8 writefeature[64] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12, 5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2, 0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9 }; #endif #ifndef B_LITTLE_ENDIAN static void kexecalloc(SharkSslMd5Ctx *registermcasp, const U8 alloccontroller[64]) #else static void kexecalloc(SharkSslMd5Ctx *registermcasp, U32 countshift[16]) #endif { U32 a, b, c, d; #if SHARKSSL_MD5_SMALL_FOOTPRINT const U32 *p; unsigned int i; #endif #ifndef B_LITTLE_ENDIAN U32 countshift[16]; #if SHARKSSL_MD5_SMALL_FOOTPRINT for (i = 0; !(i & 16); i++) { cleanupcount(countshift[i], alloccontroller, (i << 2)); } #else cleanupcount(countshift[0], alloccontroller, 0); cleanupcount(countshift[1], alloccontroller, 4); cleanupcount(countshift[2], alloccontroller, 8); cleanupcount(countshift[3], alloccontroller, 12); cleanupcount(countshift[4], alloccontroller, 16); cleanupcount(countshift[5], alloccontroller, 20); cleanupcount(countshift[6], alloccontroller, 24); cleanupcount(countshift[7], alloccontroller, 28); cleanupcount(countshift[8], alloccontroller, 32); cleanupcount(countshift[9], alloccontroller, 36); cleanupcount(countshift[10], alloccontroller, 40); cleanupcount(countshift[11], alloccontroller, 44); cleanupcount(countshift[12], alloccontroller, 48); cleanupcount(countshift[13], alloccontroller, 52); cleanupcount(countshift[14], alloccontroller, 56); cleanupcount(countshift[15], alloccontroller, 60); #endif #endif #define invalidcontext(x,n) ((U32)((U32)x << n) | ((U32)x >> (32 - n))) #define F(x,y,z) ((x & (y ^ z)) ^ z) #define G(x,y,z) ((z & (x ^ y)) ^ y) #define H(x,y,z) (x ^ y ^ z) #define I(x,y,z) (y ^ (x | ~z)) a = registermcasp->state[0]; b = registermcasp->state[1]; c = registermcasp->state[2]; d = registermcasp->state[3]; #if SHARKSSL_MD5_SMALL_FOOTPRINT p = &unregisterclient[0]; for (i = 0; (0 == (i & 0x40)); i++) { U32 e; a += countshift[writefeature[i]] + *p++; switch (i & 0x30) { case 0x00: a += F(b,c,d); break; case 0x10: a += G(b,c,d); break; case 0x20: a += H(b,c,d); break; default: a += I(b,c,d); break; } a = invalidcontext(a, keypadresources[i]); e = b; b += a; a = d; d = c; c = e; } #else #define FF(A, B, C, D, X, S, K) { A += F(B,C,D) + X + K; A = invalidcontext(A,S) + B; } #define privilegefault(A, B, C, D, X, S, K) { A += G(B,C,D) + X + K; A = invalidcontext(A,S) + B; } #define alternativesapplied(A, B, C, D, X, S, K) { A += H(B,C,D) + X + K; A = invalidcontext(A,S) + B; } #define hsmmc3resource(A, B, C, D, X, S, K) { A += I(B,C,D) + X + K; A = invalidcontext(A,S) + B; } FF(a, b, c, d, countshift[0], 7, 0xD76AA478); FF(d, a, b, c, countshift[1], 12, 0xE8C7B756); FF(c, d, a, b, countshift[2], 17, 0x242070DB); FF(b, c, d, a, countshift[3], 22, 0xC1BDCEEE); FF(a, b, c, d, countshift[4], 7, 0xF57C0FAF); FF(d, a, b, c, countshift[5], 12, 0x4787C62A); FF(c, d, a, b, countshift[6], 17, 0xA8304613); FF(b, c, d, a, countshift[7], 22, 0xFD469501); FF(a, b, c, d, countshift[8], 7, 0x698098D8); FF(d, a, b, c, countshift[9], 12, 0x8B44F7AF); FF(c, d, a, b, countshift[10], 17, 0xFFFF5BB1); FF(b, c, d, a, countshift[11], 22, 0x895CD7BE); FF(a, b, c, d, countshift[12], 7, 0x6B901122); FF(d, a, b, c, countshift[13], 12, 0xFD987193); FF(c, d, a, b, countshift[14], 17, 0xA679438E); FF(b, c, d, a, countshift[15], 22, 0x49B40821); privilegefault(a, b, c, d, countshift[1], 5, 0xF61E2562); privilegefault(d, a, b, c, countshift[6], 9, 0xC040B340); privilegefault(c, d, a, b, countshift[11], 14, 0x265E5A51); privilegefault(b, c, d, a, countshift[0], 20, 0xE9B6C7AA); privilegefault(a, b, c, d, countshift[5], 5, 0xD62F105D); privilegefault(d, a, b, c, countshift[10], 9, 0x02441453); privilegefault(c, d, a, b, countshift[15], 14, 0xD8A1E681); privilegefault(b, c, d, a, countshift[4], 20, 0xE7D3FBC8); privilegefault(a, b, c, d, countshift[9], 5, 0x21E1CDE6); privilegefault(d, a, b, c, countshift[14], 9, 0xC33707D6); privilegefault(c, d, a, b, countshift[3], 14, 0xF4D50D87); privilegefault(b, c, d, a, countshift[8], 20, 0x455A14ED); privilegefault(a, b, c, d, countshift[13], 5, 0xA9E3E905); privilegefault(d, a, b, c, countshift[2], 9, 0xFCEFA3F8); privilegefault(c, d, a, b, countshift[7], 14, 0x676F02D9); privilegefault(b, c, d, a, countshift[12], 20, 0x8D2A4C8A); alternativesapplied(a, b, c, d, countshift[5], 4, 0xFFFA3942); alternativesapplied(d, a, b, c, countshift[8], 11, 0x8771F681); alternativesapplied(c, d, a, b, countshift[11], 16, 0x6D9D6122); alternativesapplied(b, c, d, a, countshift[14], 23, 0xFDE5380C); alternativesapplied(a, b, c, d, countshift[1], 4, 0xA4BEEA44); alternativesapplied(d, a, b, c, countshift[4], 11, 0x4BDECFA9); alternativesapplied(c, d, a, b, countshift[7], 16, 0xF6BB4B60); alternativesapplied(b, c, d, a, countshift[10], 23, 0xBEBFBC70); alternativesapplied(a, b, c, d, countshift[13], 4, 0x289B7EC6); alternativesapplied(d, a, b, c, countshift[0], 11, 0xEAA127FA); alternativesapplied(c, d, a, b, countshift[3], 16, 0xD4EF3085); alternativesapplied(b, c, d, a, countshift[6], 23, 0x04881D05); alternativesapplied(a, b, c, d, countshift[9], 4, 0xD9D4D039); alternativesapplied(d, a, b, c, countshift[12], 11, 0xE6DB99E5); alternativesapplied(c, d, a, b, countshift[15], 16, 0x1FA27CF8); alternativesapplied(b, c, d, a, countshift[2], 23, 0xC4AC5665); hsmmc3resource(a, b, c, d, countshift[0], 6, 0xF4292244); hsmmc3resource(d, a, b, c, countshift[7], 10, 0x432AFF97); hsmmc3resource(c, d, a, b, countshift[14], 15, 0xAB9423A7); hsmmc3resource(b, c, d, a, countshift[5], 21, 0xFC93A039); hsmmc3resource(a, b, c, d, countshift[12], 6, 0x655B59C3); hsmmc3resource(d, a, b, c, countshift[3], 10, 0x8F0CCC92); hsmmc3resource(c, d, a, b, countshift[10], 15, 0xFFEFF47D); hsmmc3resource(b, c, d, a, countshift[1], 21, 0x85845DD1); hsmmc3resource(a, b, c, d, countshift[8], 6, 0x6FA87E4F); hsmmc3resource(d, a, b, c, countshift[15], 10, 0xFE2CE6E0); hsmmc3resource(c, d, a, b, countshift[6], 15, 0xA3014314); hsmmc3resource(b, c, d, a, countshift[13], 21, 0x4E0811A1); hsmmc3resource(a, b, c, d, countshift[4], 6, 0xF7537E82); hsmmc3resource(d, a, b, c, countshift[11], 10, 0xBD3AF235); hsmmc3resource(c, d, a, b, countshift[2], 15, 0x2AD7D2BB); hsmmc3resource(b, c, d, a, countshift[9], 21, 0xEB86D391); #undef hsmmc3resource #undef alternativesapplied #undef privilegefault #undef FF #endif registermcasp->state[0] += a; registermcasp->state[1] += b; registermcasp->state[2] += c; registermcasp->state[3] += d; #undef I #undef H #undef G #undef F #undef invalidcontext } SHARKSSL_API void SharkSslMd5Ctx_constructor(SharkSslMd5Ctx *registermcasp) { baAssert(((unsigned int)(UPTR)(registermcasp->buffer) & (sizeof(int)-1)) == 0); registermcasp->total[0] = 0; registermcasp->total[1] = 0; registermcasp->state[0] = 0x67452301; registermcasp->state[1] = 0xEFCDAB89; registermcasp->state[2] = 0x98BADCFE; registermcasp->state[3] = 0x10325476; } SHARKSSL_API void SharkSslMd5Ctx_append(SharkSslMd5Ctx *registermcasp, const U8 *in, U32 len) { unsigned int dm9000platdata, pxa300evalboard; dm9000platdata = (unsigned int)(registermcasp->total[0]) & 0x3F; pxa300evalboard = 64 - dm9000platdata; registermcasp->total[0] += len; if (registermcasp->total[0] < len) { registermcasp->total[1]++; } if((dm9000platdata) && (len >= pxa300evalboard)) { memcpy((registermcasp->buffer + dm9000platdata), in, pxa300evalboard); #ifndef B_LITTLE_ENDIAN kexecalloc(registermcasp, registermcasp->buffer); #else kexecalloc(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= pxa300evalboard; in += pxa300evalboard; dm9000platdata = 0; } while (len >= 64) { #ifndef B_LITTLE_ENDIAN kexecalloc(registermcasp, in); #else memcpy(registermcasp->buffer, in, 64); kexecalloc(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= 64; in += 64; } if (len) { memcpy((registermcasp->buffer + dm9000platdata), in, len); } } SHARKSSL_API void SharkSslMd5Ctx_finish(SharkSslMd5Ctx *registermcasp, U8 secondaryentry[SHARKSSL_MD5_HASH_LEN]) { U32 timerenable, dummywrites; U32 timer0start, checkcontext; U8 usbgadgetresource[8]; timer0start = (registermcasp->total[0] >> 29) | (registermcasp->total[1] << 3); checkcontext = (registermcasp->total[0] << 3); hsotgpdata(checkcontext, usbgadgetresource, 0); hsotgpdata(timer0start, usbgadgetresource, 4); timerenable = registermcasp->total[0] & 0x3F; dummywrites = (timerenable < 56) ? (56 - timerenable) : (120 - timerenable); SharkSslMd5Ctx_append(registermcasp, (U8*)prusspdata, dummywrites); SharkSslMd5Ctx_append(registermcasp, usbgadgetresource, 8); hsotgpdata(registermcasp->state[0], secondaryentry, 0); hsotgpdata(registermcasp->state[1], secondaryentry, 4); hsotgpdata(registermcasp->state[2], secondaryentry, 8); hsotgpdata(registermcasp->state[3], secondaryentry, 12); } SHARKSSL_API int sharkssl_md5(const U8 *alloccontroller, U32 len, U8 *secondaryentry) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslMd5Ctx *hctx = (SharkSslMd5Ctx *)baMalloc(claimresource(sizeof(SharkSslMd5Ctx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslMd5Ctx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller || (0 == len)); baAssert(secondaryentry); SharkSslMd5Ctx_constructor(hctx); SharkSslMd5Ctx_append(hctx, alloccontroller, len); SharkSslMd5Ctx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif #if SHARKSSL_USE_SHA1 #ifndef B_BIG_ENDIAN static void irqwakeintallow(SharkSslSha1Ctx *registermcasp, const U8 alloccontroller[64]) #else static void irqwakeintallow(SharkSslSha1Ctx *registermcasp, U32 countshift[16]) #endif { U32 a, b, c, d, e, brightnesslimit; #if SHARKSSL_SHA1_SMALL_FOOTPRINT unsigned int i; #endif #ifndef B_BIG_ENDIAN U32 countshift[16]; #if SHARKSSL_SHA1_SMALL_FOOTPRINT for (i = 0; !(i & 16); i++) { read64uint32(countshift[i], alloccontroller, (i << 2)); } #else read64uint32(countshift[0], alloccontroller, 0); read64uint32(countshift[1], alloccontroller, 4); read64uint32(countshift[2], alloccontroller, 8); read64uint32(countshift[3], alloccontroller, 12); read64uint32(countshift[4], alloccontroller, 16); read64uint32(countshift[5], alloccontroller, 20); read64uint32(countshift[6], alloccontroller, 24); read64uint32(countshift[7], alloccontroller, 28); read64uint32(countshift[8], alloccontroller, 32); read64uint32(countshift[9], alloccontroller, 36); read64uint32(countshift[10], alloccontroller, 40); read64uint32(countshift[11], alloccontroller, 44); read64uint32(countshift[12], alloccontroller, 48); read64uint32(countshift[13], alloccontroller, 52); read64uint32(countshift[14], alloccontroller, 56); read64uint32(countshift[15], alloccontroller, 60); #endif #endif #define invalidcontext(x,n) ((U32)((U32)x << n) | ((U32)x >> (32 - n))) #define pwdowninverted(x,y,z) ((x & (y ^ z)) ^ z) #define configparse(x,y,z) (x ^ y ^ z) #define emulationhandler(x,y,z) ((x & y) | ((x | y) & z)) #define es3plushwmod(x,y,z) (x ^ y ^ z) #define serial0pdata 0x5A827999 #define registerrproc 0x6ED9EBA1 #define powergpiod 0x8F1BBCDC #define allockernel 0xCA62C1D6 a = registermcasp->state[0]; b = registermcasp->state[1]; c = registermcasp->state[2]; d = registermcasp->state[3]; e = registermcasp->state[4]; #if SHARKSSL_SHA1_SMALL_FOOTPRINT for (i = 0; i < 80; i++) { if (i >= 16) { brightnesslimit = countshift[i & 0xF] ^ countshift[(i + 2) & 0xF] ^ countshift[(i + 8) & 0xF] ^ countshift[(i + 13) & 0xF]; countshift[i & 0xF] = brightnesslimit = invalidcontext(brightnesslimit, 1); } brightnesslimit = countshift[i & 0xF]; brightnesslimit += e + invalidcontext(a, 5); if (i < 20) { brightnesslimit += pwdowninverted(b,c,d) + serial0pdata; } else if (i < 40) { brightnesslimit += configparse(b,c,d) + registerrproc; } else if (i < 60) { brightnesslimit += emulationhandler(b,c,d) + powergpiod; } else { brightnesslimit += es3plushwmod(b,c,d) + allockernel; } e = d; d = c; c = invalidcontext(b, 30); b = a; a = brightnesslimit; } #else e += (countshift[0] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); d += (countshift[1] ) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); c += (countshift[2] ) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); b += (countshift[3] ) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); a += (countshift[4] ) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); e += (countshift[5] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); d += (countshift[6] ) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); c += (countshift[7] ) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); b += (countshift[8] ) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); a += (countshift[9] ) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); e += (countshift[10] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); d += (countshift[11] ) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); c += (countshift[12] ) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); b += (countshift[13] ) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); a += (countshift[14] ) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); e += (countshift[15] ) + invalidcontext(a,5) + pwdowninverted(b,c,d) + serial0pdata; b = invalidcontext(b,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; d += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + pwdowninverted(a,b,c) + serial0pdata; a = invalidcontext(a,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; c += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + pwdowninverted(e,a,b) + serial0pdata; e = invalidcontext(e,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; b += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + pwdowninverted(d,e,a) + serial0pdata; d = invalidcontext(d,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; a += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + pwdowninverted(c,d,e) + serial0pdata; c = invalidcontext(c,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; e += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; d += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; c += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; b += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; a += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; e += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; d += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; c += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; b += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; a += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; e += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; d += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; c += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; b += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; a += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; e += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + configparse(b,c,d) + registerrproc; b = invalidcontext(b,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; d += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + configparse(a,b,c) + registerrproc; a = invalidcontext(a,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; c += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + configparse(e,a,b) + registerrproc; e = invalidcontext(e,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; b += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + configparse(d,e,a) + registerrproc; d = invalidcontext(d,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; a += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + configparse(c,d,e) + registerrproc; c = invalidcontext(c,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; e += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; d += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; c += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; b += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; a += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; e += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; d += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; c += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; b += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; a += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; e += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; d += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; c += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; b += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; a += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; e += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + emulationhandler(b,c,d) + powergpiod; b = invalidcontext(b,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; d += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + emulationhandler(a,b,c) + powergpiod; a = invalidcontext(a,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; c += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + emulationhandler(e,a,b) + powergpiod; e = invalidcontext(e,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; b += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + emulationhandler(d,e,a) + powergpiod; d = invalidcontext(d,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; a += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + emulationhandler(c,d,e) + powergpiod; c = invalidcontext(c,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; e += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; d += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; c += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; b += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[13]^countshift[8] ^countshift[2] ^countshift[0]; a += (countshift[0] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); brightnesslimit = countshift[14]^countshift[9] ^countshift[3] ^countshift[1]; e += (countshift[1] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[15]^countshift[10]^countshift[4] ^countshift[2]; d += (countshift[2] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[0] ^countshift[11]^countshift[5] ^countshift[3]; c += (countshift[3] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[1] ^countshift[12]^countshift[6] ^countshift[4]; b += (countshift[4] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[2] ^countshift[13]^countshift[7] ^countshift[5]; a += (countshift[5] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); brightnesslimit = countshift[3] ^countshift[14]^countshift[8] ^countshift[6]; e += (countshift[6] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[4] ^countshift[15]^countshift[9] ^countshift[7]; d += (countshift[7] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[5] ^countshift[0] ^countshift[10]^countshift[8]; c += (countshift[8] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[6] ^countshift[1] ^countshift[11]^countshift[9]; b += (countshift[9] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[7] ^countshift[2] ^countshift[12]^countshift[10]; a += (countshift[10] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); brightnesslimit = countshift[8] ^countshift[3] ^countshift[13]^countshift[11]; e += (countshift[11] = invalidcontext(brightnesslimit,1)) + invalidcontext(a,5) + es3plushwmod(b,c,d) + allockernel; b = invalidcontext(b,30); brightnesslimit = countshift[9] ^countshift[4] ^countshift[14]^countshift[12]; d += (countshift[12] = invalidcontext(brightnesslimit,1)) + invalidcontext(e,5) + es3plushwmod(a,b,c) + allockernel; a = invalidcontext(a,30); brightnesslimit = countshift[10]^countshift[5] ^countshift[15]^countshift[13]; c += (countshift[13] = invalidcontext(brightnesslimit,1)) + invalidcontext(d,5) + es3plushwmod(e,a,b) + allockernel; e = invalidcontext(e,30); brightnesslimit = countshift[11]^countshift[6] ^countshift[0] ^countshift[14]; b += (countshift[14] = invalidcontext(brightnesslimit,1)) + invalidcontext(c,5) + es3plushwmod(d,e,a) + allockernel; d = invalidcontext(d,30); brightnesslimit = countshift[12]^countshift[7] ^countshift[1] ^countshift[15]; a += (countshift[15] = invalidcontext(brightnesslimit,1)) + invalidcontext(b,5) + es3plushwmod(c,d,e) + allockernel; c = invalidcontext(c,30); #endif registermcasp->state[0] += a; registermcasp->state[1] += b; registermcasp->state[2] += c; registermcasp->state[3] += d; registermcasp->state[4] += e; #undef allockernel #undef powergpiod #undef registerrproc #undef serial0pdata #undef es3plushwmod #undef emulationhandler #undef configparse #undef pwdowninverted #undef invalidcontext } SHARKSSL_API void SharkSslSha1Ctx_constructor(SharkSslSha1Ctx *registermcasp) { baAssert(((unsigned int)(UPTR)(registermcasp->buffer) & (sizeof(int)-1)) == 0); registermcasp->total[0] = 0; registermcasp->total[1] = 0; registermcasp->state[0] = 0x67452301; registermcasp->state[1] = 0xEFCDAB89; registermcasp->state[2] = 0x98BADCFE; registermcasp->state[3] = 0x10325476; registermcasp->state[4] = 0xC3D2E1F0; } SHARKSSL_API void SharkSslSha1Ctx_append(SharkSslSha1Ctx *registermcasp, const U8 *in, U32 len) { unsigned int dm9000platdata, pxa300evalboard; dm9000platdata = (unsigned int)(registermcasp->total[0]) & 0x3F; pxa300evalboard = 64 - dm9000platdata; registermcasp->total[0] += len; if (registermcasp->total[0] < len) { registermcasp->total[1]++; } if((dm9000platdata) && (len >= pxa300evalboard)) { memcpy((registermcasp->buffer + dm9000platdata), in, pxa300evalboard); #ifndef B_BIG_ENDIAN irqwakeintallow(registermcasp, registermcasp->buffer); #else irqwakeintallow(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= pxa300evalboard; in += pxa300evalboard; dm9000platdata = 0; } while (len >= 64) { #ifndef B_BIG_ENDIAN irqwakeintallow(registermcasp, in); #else memcpy(registermcasp->buffer, in, 64); irqwakeintallow(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= 64; in += 64; } if (len) { memcpy((registermcasp->buffer + dm9000platdata), in, len); } } SHARKSSL_API void SharkSslSha1Ctx_finish(SharkSslSha1Ctx *registermcasp, U8 secondaryentry[SHARKSSL_SHA1_HASH_LEN]) { U32 timerenable, dummywrites; U32 timer0start, checkcontext; U8 usbgadgetresource[8]; timer0start = (registermcasp->total[0] >> 29) | (registermcasp->total[1] << 3); checkcontext = (registermcasp->total[0] << 3); inputlevel(timer0start, usbgadgetresource, 0); inputlevel(checkcontext, usbgadgetresource, 4); timerenable = registermcasp->total[0] & 0x3F; dummywrites = (timerenable < 56) ? (56 - timerenable) : (120 - timerenable); SharkSslSha1Ctx_append(registermcasp, (U8*)prusspdata, dummywrites); SharkSslSha1Ctx_append(registermcasp, usbgadgetresource, 8); inputlevel(registermcasp->state[0], secondaryentry, 0); inputlevel(registermcasp->state[1], secondaryentry, 4); inputlevel(registermcasp->state[2], secondaryentry, 8); inputlevel(registermcasp->state[3], secondaryentry, 12); inputlevel(registermcasp->state[4], secondaryentry, 16); } SHARKSSL_API int sharkssl_sha1(const U8 *alloccontroller, U32 len, U8 *secondaryentry) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslSha1Ctx *hctx = (SharkSslSha1Ctx *)baMalloc(claimresource(sizeof(SharkSslSha1Ctx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslSha1Ctx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller || (0 == len)); baAssert(secondaryentry); SharkSslSha1Ctx_constructor(hctx); SharkSslSha1Ctx_append(hctx, alloccontroller, len); SharkSslSha1Ctx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif #if SHARKSSL_USE_SHA_256 static const U32 callchainentry[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; #ifndef B_BIG_ENDIAN static void alignmentfinish(SharkSslSha256Ctx *registermcasp, const U8 alloccontroller[64]) #else static void alignmentfinish(SharkSslSha256Ctx *registermcasp, U32 countshift[16]) #endif { U32 a, b, c, d, e, f, g, h, T1, T2; #if SHARKSSL_SHA256_SMALL_FOOTPRINT unsigned int i; #else const U32 *p; #endif #ifndef B_BIG_ENDIAN U32 countshift[16]; #if SHARKSSL_SHA256_SMALL_FOOTPRINT for (i = 0; !(i & 16); i++) { read64uint32(countshift[i], alloccontroller, (i << 2)); } #else read64uint32(countshift[0], alloccontroller, 0); read64uint32(countshift[1], alloccontroller, 4); read64uint32(countshift[2], alloccontroller, 8); read64uint32(countshift[3], alloccontroller, 12); read64uint32(countshift[4], alloccontroller, 16); read64uint32(countshift[5], alloccontroller, 20); read64uint32(countshift[6], alloccontroller, 24); read64uint32(countshift[7], alloccontroller, 28); read64uint32(countshift[8], alloccontroller, 32); read64uint32(countshift[9], alloccontroller, 36); read64uint32(countshift[10], alloccontroller, 40); read64uint32(countshift[11], alloccontroller, 44); read64uint32(countshift[12], alloccontroller, 48); read64uint32(countshift[13], alloccontroller, 52); read64uint32(countshift[14], alloccontroller, 56); read64uint32(countshift[15], alloccontroller, 60); #endif #endif #define invalidcontext(x,n) ((U32)((U32)x << n) | ((U32)x >> (32 - n))) #define SHR(x,n) ((U32)((U32)x >> n)) #define CH(x,y,z) ((x & (y ^ z)) ^ z) #define MAJ(x,y,z) ((x & y) | ((x | y) & z)) #define injectundefined(x) (invalidcontext(x, 30) ^ invalidcontext(x, 19) ^ invalidcontext(x, 10)) #define clearhighpage(x) (invalidcontext(x, 26) ^ invalidcontext(x, 21) ^ invalidcontext(x, 7)) #define joystickdisable(x) (invalidcontext(x, 25) ^ invalidcontext(x, 14) ^ SHR(x, 3)) #define sm501resources(x) (invalidcontext(x, 15) ^ invalidcontext(x, 13) ^ SHR(x, 10)) a = registermcasp->state[0]; b = registermcasp->state[1]; c = registermcasp->state[2]; d = registermcasp->state[3]; e = registermcasp->state[4]; f = registermcasp->state[5]; g = registermcasp->state[6]; h = registermcasp->state[7]; #if SHARKSSL_SHA256_SMALL_FOOTPRINT for (i = 0; (0 == (i & 0x40)); i++) { if (i >= 16) { T1 = countshift[(i + 1) & 0xF]; T1 = joystickdisable(T1); T2 = countshift[(i + 14) & 0xF]; T2 = sm501resources(T2); countshift[i & 0xF] += (countshift[(i + 9) & 0xF] + T1 + T2); } T1 = countshift[i & 0xF]; T1 += callchainentry[i] + h + CH(e,f,g) + clearhighpage(e); T2 = MAJ(a,b,c) + injectundefined(a); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } #else #define mismatchedcache(i,a,b,c,d,e,f,g,h) do { \ T1 = clearhighpage(e); \ T2 = CH(e,f,g); \ h += countshift[(i) & 0xF] + T1 + T2 + (*p++); \ d += h; \ T1 = injectundefined(a); \ T2 = MAJ(a,b,c); \ h += T1 + T2; \ } while (0) #define machinetable(i,a,b,c,d,e,f,g,h) do { \ T1 = countshift[((i) + 1) & 0xF]; \ T1 = joystickdisable(T1); \ T2 = countshift[((i) + 14) & 0xF]; \ T2 = sm501resources(T2); \ countshift[(i) & 0xF] += (countshift[((i) + 9) & 0xF] + T1 + T2); \ mismatchedcache(i,a,b,c,d,e,f,g,h); \ } while (0) p = &callchainentry[0]; mismatchedcache( 0,a,b,c,d,e,f,g,h); mismatchedcache( 1,h,a,b,c,d,e,f,g); mismatchedcache( 2,g,h,a,b,c,d,e,f); mismatchedcache( 3,f,g,h,a,b,c,d,e); mismatchedcache( 4,e,f,g,h,a,b,c,d); mismatchedcache( 5,d,e,f,g,h,a,b,c); mismatchedcache( 6,c,d,e,f,g,h,a,b); mismatchedcache( 7,b,c,d,e,f,g,h,a); mismatchedcache( 8,a,b,c,d,e,f,g,h); mismatchedcache( 9,h,a,b,c,d,e,f,g); mismatchedcache(10,g,h,a,b,c,d,e,f); mismatchedcache(11,f,g,h,a,b,c,d,e); mismatchedcache(12,e,f,g,h,a,b,c,d); mismatchedcache(13,d,e,f,g,h,a,b,c); mismatchedcache(14,c,d,e,f,g,h,a,b); mismatchedcache(15,b,c,d,e,f,g,h,a); while (p < &callchainentry[63]) { machinetable( 0,a,b,c,d,e,f,g,h); machinetable( 1,h,a,b,c,d,e,f,g); machinetable( 2,g,h,a,b,c,d,e,f); machinetable( 3,f,g,h,a,b,c,d,e); machinetable( 4,e,f,g,h,a,b,c,d); machinetable( 5,d,e,f,g,h,a,b,c); machinetable( 6,c,d,e,f,g,h,a,b); machinetable( 7,b,c,d,e,f,g,h,a); machinetable( 8,a,b,c,d,e,f,g,h); machinetable( 9,h,a,b,c,d,e,f,g); machinetable(10,g,h,a,b,c,d,e,f); machinetable(11,f,g,h,a,b,c,d,e); machinetable(12,e,f,g,h,a,b,c,d); machinetable(13,d,e,f,g,h,a,b,c); machinetable(14,c,d,e,f,g,h,a,b); machinetable(15,b,c,d,e,f,g,h,a); } #undef mismatchedcache #undef machinetable #endif registermcasp->state[0] += a; registermcasp->state[1] += b; registermcasp->state[2] += c; registermcasp->state[3] += d; registermcasp->state[4] += e; registermcasp->state[5] += f; registermcasp->state[6] += g; registermcasp->state[7] += h; #undef sm501resources #undef joystickdisable #undef injectundefined #undef clearhighpage #undef MAJ #undef CH #undef SHR #undef invalidcontext } SHARKSSL_API void SharkSslSha256Ctx_constructor(SharkSslSha256Ctx *registermcasp) { baAssert(((unsigned int)(UPTR)(registermcasp->buffer) & (sizeof(int)-1)) == 0); registermcasp->total[0] = 0; registermcasp->total[1] = 0; registermcasp->state[0] = 0x6A09E667; registermcasp->state[1] = 0xBB67AE85; registermcasp->state[2] = 0x3C6EF372; registermcasp->state[3] = 0xA54FF53A; registermcasp->state[4] = 0x510E527F; registermcasp->state[5] = 0x9B05688C; registermcasp->state[6] = 0x1F83D9AB; registermcasp->state[7] = 0x5BE0CD19; } SHARKSSL_API void SharkSslSha256Ctx_append(SharkSslSha256Ctx *registermcasp, const U8 *in, U32 len) { unsigned int dm9000platdata, pxa300evalboard; dm9000platdata = (unsigned int)(registermcasp->total[0]) & 0x3F; pxa300evalboard = 64 - dm9000platdata; registermcasp->total[0] += len; if (registermcasp->total[0] < len) { registermcasp->total[1]++; } if((dm9000platdata) && (len >= pxa300evalboard)) { memcpy((registermcasp->buffer + dm9000platdata), in, pxa300evalboard); #ifndef B_BIG_ENDIAN alignmentfinish(registermcasp, registermcasp->buffer); #else alignmentfinish(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= pxa300evalboard; in += pxa300evalboard; dm9000platdata = 0; } while (len >= 64) { #ifndef B_BIG_ENDIAN alignmentfinish(registermcasp, in); #else memcpy(registermcasp->buffer, in, 64); alignmentfinish(registermcasp, (U32*)(registermcasp->buffer)); #endif len -= 64; in += 64; } if (len) { memcpy((registermcasp->buffer + dm9000platdata), in, len); } } SHARKSSL_API void SharkSslSha256Ctx_finish(SharkSslSha256Ctx *registermcasp, U8 secondaryentry[SHARKSSL_SHA256_HASH_LEN]) { U32 timerenable, dummywrites; U32 timer0start, checkcontext; U8 usbgadgetresource[8]; timer0start = (registermcasp->total[0] >> 29) | (registermcasp->total[1] << 3); checkcontext = (registermcasp->total[0] << 3); inputlevel(timer0start, usbgadgetresource, 0); inputlevel(checkcontext, usbgadgetresource, 4); timerenable = registermcasp->total[0] & 0x3F; dummywrites = (timerenable < 56) ? (56 - timerenable) : (120 - timerenable); SharkSslSha256Ctx_append(registermcasp, (U8*)prusspdata, dummywrites); SharkSslSha256Ctx_append(registermcasp, usbgadgetresource, 8); inputlevel(registermcasp->state[0], secondaryentry, 0); inputlevel(registermcasp->state[1], secondaryentry, 4); inputlevel(registermcasp->state[2], secondaryentry, 8); inputlevel(registermcasp->state[3], secondaryentry, 12); inputlevel(registermcasp->state[4], secondaryentry, 16); inputlevel(registermcasp->state[5], secondaryentry, 20); inputlevel(registermcasp->state[6], secondaryentry, 24); inputlevel(registermcasp->state[7], secondaryentry, 28); } SHARKSSL_API int sharkssl_sha256(const U8 *alloccontroller, U32 len, U8 *secondaryentry) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslSha256Ctx *hctx = (SharkSslSha256Ctx *)baMalloc(claimresource(sizeof(SharkSslSha256Ctx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslSha256Ctx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller || (0 == len)); baAssert(secondaryentry); SharkSslSha256Ctx_constructor(hctx); SharkSslSha256Ctx_append(hctx, alloccontroller, len); SharkSslSha256Ctx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif #if (SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) static const U64 pxa270income[80] = { 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; static U64 injectundefined(U64 *x) { U32 x1, x2, r1, r2; x1 = (U32)(*x >> 32); x2 = (U32)*x; r1 = (x1 >> 28) ^ (x1 << 30) ^ (x1 << 25) ^ (x2 << 4) ^ (x2 >> 2) ^ (x2 >> 7); r2 = (x2 >> 28) ^ (x2 << 30) ^ (x2 << 25) ^ (x1 << 4) ^ (x1 >> 2) ^ (x1 >> 7); return ((U64)r1 << 32) | r2; } static U64 clearhighpage(U64 *x) { U32 x1, x2, r1, r2; x1 = (U32)(*x >> 32); x2 = (U32)*x; r1 = (x1 >> 14) ^ (x1 >> 18) ^ (x1 << 23) ^ (x2 << 18) ^ (x2 << 14) ^ (x2 >> 9); r2 = (x2 >> 14) ^ (x2 >> 18) ^ (x2 << 23) ^ (x1 << 18) ^ (x1 << 14) ^ (x1 >> 9); return ((U64)r1 << 32) | r2; } static U64 joystickdisable(U64 *x) { U32 x1, x2, r1, r2; x1 = (U32)(*x >> 32); x2 = (U32)*x; r1 = (x1 >> 1) ^ (x1 >> 8) ^ (x1 >> 7) ^ (x2 << 31) ^ (x2 << 24); r2 = (x2 >> 1) ^ (x2 >> 8) ^ (x2 >> 7) ^ (x1 << 31) ^ (x1 << 24) ^ (x1 << 25); return ((U64)r1 << 32) | r2; } static U64 sm501resources(U64 *x) { U32 x1, x2, r1, r2; x1 = (U32)(*x >> 32); x2 = (U32)*x; r1 = (x1 >> 19) ^ (x1 << 3) ^ (x1 >> 6) ^ (x2 << 13) ^ (x2 >> 29); r2 = (x2 >> 19) ^ (x2 << 3) ^ (x2 >> 6) ^ (x1 << 13) ^ (x1 >> 29) ^ (x1 << 26); return ((U64)r1 << 32) | r2; } #ifndef B_BIG_ENDIAN static void pcimtresource(SharkSslSha384Ctx *registermcasp, const U8 alloccontroller[128]) #else static void pcimtresource(SharkSslSha384Ctx *registermcasp, U64 countshift[16]) #endif { U64 a, b, c, d, e, f, g, h, T1, T2; unsigned int i; #ifndef B_BIG_ENDIAN U64 countshift[16]; detectboard(countshift[0], alloccontroller, 0); detectboard(countshift[1], alloccontroller, 8); detectboard(countshift[2], alloccontroller, 16); detectboard(countshift[3], alloccontroller, 24); detectboard(countshift[4], alloccontroller, 32); detectboard(countshift[5], alloccontroller, 40); detectboard(countshift[6], alloccontroller, 48); detectboard(countshift[7], alloccontroller, 56); detectboard(countshift[8], alloccontroller, 64); detectboard(countshift[9], alloccontroller, 72); detectboard(countshift[10], alloccontroller, 80); detectboard(countshift[11], alloccontroller, 88); detectboard(countshift[12], alloccontroller, 96); detectboard(countshift[13], alloccontroller, 104); detectboard(countshift[14], alloccontroller, 112); detectboard(countshift[15], alloccontroller, 120); #endif #define CH(x,y,z) ((x & (y ^ z)) ^ z) #define MAJ(x,y,z) ((x & y) | ((x | y) & z)) a = registermcasp->state[0]; b = registermcasp->state[1]; c = registermcasp->state[2]; d = registermcasp->state[3]; e = registermcasp->state[4]; f = registermcasp->state[5]; g = registermcasp->state[6]; h = registermcasp->state[7]; for (i = 0; i < 80; i++) { if (i >= 16) { countshift[i & 0xF] += countshift[(i + 9) & 0xF] + joystickdisable(&countshift[(i + 1) & 0xF]) + sm501resources(&countshift[(i + 14) & 0xF]); } T1 = countshift[i & 0xF] + pxa270income[i] + h + CH(e,f,g) + clearhighpage(&e); T2 = MAJ(a,b,c) + injectundefined(&a); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } registermcasp->state[0] += a; registermcasp->state[1] += b; registermcasp->state[2] += c; registermcasp->state[3] += d; registermcasp->state[4] += e; registermcasp->state[5] += f; registermcasp->state[6] += g; registermcasp->state[7] += h; #undef MAJ #undef CH } #endif #if SHARKSSL_USE_SHA_384 SHARKSSL_API void SharkSslSha384Ctx_constructor(SharkSslSha384Ctx *registermcasp) { baAssert(((unsigned int)(UPTR)(registermcasp->buffer) & (sizeof(int)-1)) == 0); registermcasp->total[0] = 0; registermcasp->total[1] = 0; registermcasp->total[2] = 0; registermcasp->total[3] = 0; registermcasp->state[0] = 0xCBBB9D5DC1059ED8ULL; registermcasp->state[1] = 0x629A292A367CD507ULL; registermcasp->state[2] = 0x9159015A3070DD17ULL; registermcasp->state[3] = 0x152FECD8F70E5939ULL; registermcasp->state[4] = 0x67332667FFC00B31ULL; registermcasp->state[5] = 0x8EB44A8768581511ULL; registermcasp->state[6] = 0xDB0C2E0D64F98FA7ULL; registermcasp->state[7] = 0x47B5481DBEFA4FA4ULL; } #endif #if SHARKSSL_USE_SHA_512 SHARKSSL_API void SharkSslSha512Ctx_constructor(SharkSslSha512Ctx *registermcasp) { baAssert(((unsigned int)(UPTR)(registermcasp->buffer) & (sizeof(int)-1)) == 0); registermcasp->total[0] = 0; registermcasp->total[1] = 0; registermcasp->total[2] = 0; registermcasp->total[3] = 0; registermcasp->state[0] = 0x6A09E667F3BCC908ULL; registermcasp->state[1] = 0xBB67AE8584CAA73BULL; registermcasp->state[2] = 0x3C6EF372FE94F82BULL; registermcasp->state[3] = 0xA54FF53A5F1D36F1ULL; registermcasp->state[4] = 0x510E527FADE682D1ULL; registermcasp->state[5] = 0x9B05688C2B3E6C1FULL; registermcasp->state[6] = 0x1F83D9ABFB41BD6BULL; registermcasp->state[7] = 0x5BE0CD19137E2179ULL; } #endif #if (SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_512) SHARKSSL_API void SharkSslSha384Ctx_append(SharkSslSha384Ctx *registermcasp, const U8 *in, U32 len) { unsigned int dm9000platdata, pxa300evalboard; dm9000platdata = (unsigned int)(registermcasp->total[0]) & 0x7F; pxa300evalboard = 128 - dm9000platdata; registermcasp->total[0] += len; if (registermcasp->total[0] < len) { if (0 == ++registermcasp->total[1]) { if (0 == ++registermcasp->total[2]) { ++registermcasp->total[3]; } } } if((dm9000platdata) && (len >= pxa300evalboard)) { memcpy((registermcasp->buffer + dm9000platdata), in, pxa300evalboard); #ifndef B_BIG_ENDIAN pcimtresource(registermcasp, registermcasp->buffer); #else pcimtresource(registermcasp, (U64*)(registermcasp->buffer)); #endif len -= pxa300evalboard; in += pxa300evalboard; dm9000platdata = 0; } while (len >= 128) { #ifndef B_BIG_ENDIAN pcimtresource(registermcasp, in); #else memcpy(registermcasp->buffer, in, 128); pcimtresource(registermcasp, (U64*)(registermcasp->buffer)); #endif len -= 128; in += 128; } if (len) { memcpy((registermcasp->buffer + dm9000platdata), in, len); } } SHARKSSL_API void SharkSslSha384Ctx_finish(SharkSslSha384Ctx *registermcasp, U8 secondaryentry[SHARKSSL_SHA384_HASH_LEN]) { U32 timerenable, dummywrites; U32 enablekernel[4]; U8 usbgadgetresource[16]; enablekernel[3] = (registermcasp->total[0] << 3); enablekernel[2] = (registermcasp->total[1] << 3) | (registermcasp->total[0] >> 29); enablekernel[1] = (registermcasp->total[2] << 3) | (registermcasp->total[1] >> 29); enablekernel[0] = (registermcasp->total[3] << 3) | (registermcasp->total[2] >> 29); inputlevel(enablekernel[0], usbgadgetresource, 0); inputlevel(enablekernel[1], usbgadgetresource, 4); inputlevel(enablekernel[2], usbgadgetresource, 8); inputlevel(enablekernel[3], usbgadgetresource, 12); timerenable = registermcasp->total[0] & 0x7F; dummywrites = (timerenable < 112) ? (112 - timerenable) : (240 - timerenable); SharkSslSha384Ctx_append(registermcasp, (U8*)prusspdata, dummywrites); SharkSslSha384Ctx_append(registermcasp, usbgadgetresource, 16); hwmoddisable(registermcasp->state[0], secondaryentry, 0); hwmoddisable(registermcasp->state[1], secondaryentry, 8); hwmoddisable(registermcasp->state[2], secondaryentry, 16); hwmoddisable(registermcasp->state[3], secondaryentry, 24); hwmoddisable(registermcasp->state[4], secondaryentry, 32); hwmoddisable(registermcasp->state[5], secondaryentry, 40); } #endif #if SHARKSSL_USE_SHA_384 SHARKSSL_API int sharkssl_sha384(const U8 *alloccontroller, U32 len, U8 *secondaryentry) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslSha384Ctx *hctx = (SharkSslSha384Ctx *)baMalloc(claimresource(sizeof(SharkSslSha384Ctx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslSha384Ctx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller || (0 == len)); baAssert(secondaryentry); SharkSslSha384Ctx_constructor(hctx); SharkSslSha384Ctx_append(hctx, alloccontroller, len); SharkSslSha384Ctx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif #if SHARKSSL_USE_SHA_512 SHARKSSL_API void SharkSslSha512Ctx_finish(SharkSslSha512Ctx *registermcasp, U8 secondaryentry[SHARKSSL_SHA512_HASH_LEN]) { baAssert(sizeof(SharkSslSha512Ctx) == sizeof(SharkSslSha384Ctx)); SharkSslSha384Ctx_finish((SharkSslSha384Ctx*)registermcasp, secondaryentry); hwmoddisable(registermcasp->state[6], secondaryentry, 48); hwmoddisable(registermcasp->state[7], secondaryentry, 56); } SHARKSSL_API int sharkssl_sha512(const U8 *alloccontroller, U32 len, U8 *secondaryentry) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslSha512Ctx *hctx = (SharkSslSha512Ctx *)baMalloc(claimresource(sizeof(SharkSslSha512Ctx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslSha512Ctx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller || (0 == len)); baAssert(secondaryentry); SharkSslSha512Ctx_constructor(hctx); SharkSslSha512Ctx_append(hctx, alloccontroller, len); SharkSslSha512Ctx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif static U16 prminstglobal(U8 configwrite) { baAssert(SHARKSSL_SHA512_BLOCK_LEN == SHARKSSL_SHA384_BLOCK_LEN); baAssert(SHARKSSL_SHA256_BLOCK_LEN == SHARKSSL_MD5_BLOCK_LEN); baAssert(SHARKSSL_SHA1_BLOCK_LEN == SHARKSSL_MD5_BLOCK_LEN); switch (configwrite) { #if (SHARKSSL_USE_SHA_512 || SHARKSSL_USE_SHA_384) #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: #endif return SHARKSSL_SHA384_BLOCK_LEN; #endif #if (SHARKSSL_USE_SHA_256 || SHARKSSL_USE_SHA1 || SHARKSSL_USE_MD5) #if SHARKSSL_USE_SHA_256 case SHARKSSL_HASHID_SHA256: #endif #if SHARKSSL_USE_SHA1 case SHARKSSL_HASHID_SHA1: #endif #if SHARKSSL_USE_MD5 case SHARKSSL_HASHID_MD5: #endif return SHARKSSL_MD5_BLOCK_LEN; #endif default: break; } return 0; } U16 sharkssl_getHashLen(U8 configwrite) { switch (configwrite) { #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: return SHARKSSL_SHA512_HASH_LEN; #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: return SHARKSSL_SHA384_HASH_LEN; #endif #if SHARKSSL_USE_SHA_256 case SHARKSSL_HASHID_SHA256: return SHARKSSL_SHA256_HASH_LEN; #endif #if SHARKSSL_USE_SHA1 case SHARKSSL_HASHID_SHA1: return SHARKSSL_SHA1_HASH_LEN; #endif #if SHARKSSL_USE_MD5 case SHARKSSL_HASHID_MD5: return SHARKSSL_MD5_HASH_LEN; #endif default: break; } return 0; } int sharkssl_hash(U8 *secondaryentry, U8 *alloccontroller, U32 len, U8 configwrite) { if (secondaryentry && (alloccontroller || (0 == len))) { switch (configwrite) { #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: return sharkssl_sha512(alloccontroller, len, secondaryentry); #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: return sharkssl_sha384(alloccontroller, len, secondaryentry); #endif #if SHARKSSL_USE_SHA_256 case SHARKSSL_HASHID_SHA256: return sharkssl_sha256(alloccontroller, len, secondaryentry); #endif #if SHARKSSL_USE_SHA1 case SHARKSSL_HASHID_SHA1: return sharkssl_sha1(alloccontroller, len, secondaryentry); #endif #if SHARKSSL_USE_MD5 case SHARKSSL_HASHID_MD5: return sharkssl_md5(alloccontroller, len, secondaryentry); #endif default: break; } } return -1; } #if (SHARKSSL_USE_SHA_512 || SHARKSSL_USE_SHA_384 || SHARKSSL_USE_SHA_256 || SHARKSSL_USE_SHA1 || SHARKSSL_USE_MD5) SHARKSSL_API void SharkSslHMACCtx_constructor(SharkSslHMACCtx *registermcasp, U8 configwrite, const U8 *sourcerouting, U16 creategroup) { U16 usb11device = prminstglobal(configwrite); baAssert(0 == (usb11device & 0x03)); registermcasp->hashID = 0; if (usb11device) { U8 *k; U16 l4 = (usb11device >> 2); memset(registermcasp->key, 0, usb11device); if (creategroup <= usb11device) { memcpy(registermcasp->key, sourcerouting, creategroup); } else { sharkssl_hash((U8*)&(registermcasp->key), (U8*)sourcerouting, creategroup, configwrite); creategroup = sharkssl_getHashLen(configwrite); baAssert(creategroup); } k = registermcasp->key; while (l4--) { *(k++) ^= 0x36; *(k++) ^= 0x36; *(k++) ^= 0x36; *(k++) ^= 0x36; } registermcasp->hashID = configwrite; switch (configwrite) { #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: SharkSslSha512Ctx_constructor(&(registermcasp->hashCtx.sha512Ctx)); SharkSslSha512Ctx_append(&(registermcasp->hashCtx.sha512Ctx), (U8*)&(registermcasp->key), usb11device); break; #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: SharkSslSha384Ctx_constructor(&(registermcasp->hashCtx.sha384Ctx)); SharkSslSha384Ctx_append(&(registermcasp->hashCtx.sha384Ctx), (U8*)&(registermcasp->key), usb11device); break; #endif #if SHARKSSL_USE_SHA_256 case SHARKSSL_HASHID_SHA256: SharkSslSha256Ctx_constructor(&(registermcasp->hashCtx.sha256Ctx)); SharkSslSha256Ctx_append(&(registermcasp->hashCtx.sha256Ctx), (U8*)&(registermcasp->key), usb11device); break; #endif #if SHARKSSL_USE_SHA1 case SHARKSSL_HASHID_SHA1: SharkSslSha1Ctx_constructor(&(registermcasp->hashCtx.sha1Ctx)); SharkSslSha1Ctx_append(&(registermcasp->hashCtx.sha1Ctx), (U8*)&(registermcasp->key), usb11device); break; #endif #if SHARKSSL_USE_MD5 case SHARKSSL_HASHID_MD5: SharkSslMd5Ctx_constructor(&(registermcasp->hashCtx.md5Ctx)); SharkSslMd5Ctx_append(&(registermcasp->hashCtx.md5Ctx), (U8*)&(registermcasp->key), usb11device); break; #endif default: break; } } } SHARKSSL_API void SharkSslHMACCtx_append(SharkSslHMACCtx *registermcasp, const U8 *alloccontroller, U32 len) { switch (registermcasp->hashID) { #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: SharkSslSha512Ctx_append(&(registermcasp->hashCtx.sha512Ctx), alloccontroller, len); break; #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: SharkSslSha384Ctx_append(&(registermcasp->hashCtx.sha384Ctx), alloccontroller, len); break; #endif #if SHARKSSL_USE_SHA_256 case SHARKSSL_HASHID_SHA256: SharkSslSha256Ctx_append(&(registermcasp->hashCtx.sha256Ctx), alloccontroller, len); break; #endif #if SHARKSSL_USE_SHA1 case SHARKSSL_HASHID_SHA1: SharkSslSha1Ctx_append(&(registermcasp->hashCtx.sha1Ctx), alloccontroller, len); break; #endif #if SHARKSSL_USE_MD5 case SHARKSSL_HASHID_MD5: SharkSslMd5Ctx_append(&(registermcasp->hashCtx.md5Ctx), alloccontroller, len); break; #endif default: break; } } SHARKSSL_API void SharkSslHMACCtx_finish(SharkSslHMACCtx *registermcasp, U8 *cfconresource) { U16 usb11device = prminstglobal(registermcasp->hashID); if (usb11device) { U8 *k; U16 l4, ftraceupdate; k = registermcasp->key; l4 = (usb11device >> 2); while (l4--) { *(k++) ^= (0x36 ^ 0x5C); *(k++) ^= (0x36 ^ 0x5C); *(k++) ^= (0x36 ^ 0x5C); *(k++) ^= (0x36 ^ 0x5C); } ftraceupdate = sharkssl_getHashLen(registermcasp->hashID); switch (registermcasp->hashID) { #if SHARKSSL_USE_SHA_512 case SHARKSSL_HASHID_SHA512: SharkSslSha512Ctx_finish(&(registermcasp->hashCtx.sha512Ctx), cfconresource); SharkSslSha512Ctx_constructor(&(registermcasp->hashCtx.sha512Ctx)); SharkSslSha512Ctx_append(&(registermcasp->hashCtx.sha512Ctx), (U8*)&(registermcasp->key), usb11device); SharkSslSha512Ctx_append(&(registermcasp->hashCtx.sha512Ctx), cfconresource, ftraceupdate); SharkSslSha512Ctx_finish(&(registermcasp->hashCtx.sha512Ctx), cfconresource); break; #endif #if SHARKSSL_USE_SHA_384 case SHARKSSL_HASHID_SHA384: SharkSslSha384Ctx_finish(&(registermcasp->hashCtx.sha384Ctx), cfconresource); SharkSslSha384Ctx_constructor(&(registermcasp->hashCtx.sha384Ctx)); SharkSslSha384Ctx_append(&(registermcasp->hashCtx.sha384Ctx), (U8*)&(registermcasp->key), usb11device); SharkSslSha384Ctx_append(&(registermcasp->hashCtx.sha384Ctx), cfconresource, ftraceupdate); SharkSslSha384Ctx_finish(&(registermcasp->hashCtx.sha384Ctx), cfconresource); break; #endif #if SHARKSSL_USE_SHA_256 case SHARKSSL_HASHID_SHA256: SharkSslSha256Ctx_finish(&(registermcasp->hashCtx.sha256Ctx), cfconresource); SharkSslSha256Ctx_constructor(&(registermcasp->hashCtx.sha256Ctx)); SharkSslSha256Ctx_append(&(registermcasp->hashCtx.sha256Ctx), (U8*)&(registermcasp->key), usb11device); SharkSslSha256Ctx_append(&(registermcasp->hashCtx.sha256Ctx), cfconresource, ftraceupdate); SharkSslSha256Ctx_finish(&(registermcasp->hashCtx.sha256Ctx), cfconresource); break; #endif #if SHARKSSL_USE_SHA1 case SHARKSSL_HASHID_SHA1: SharkSslSha1Ctx_finish(&(registermcasp->hashCtx.sha1Ctx), cfconresource); SharkSslSha1Ctx_constructor(&(registermcasp->hashCtx.sha1Ctx)); SharkSslSha1Ctx_append(&(registermcasp->hashCtx.sha1Ctx), (U8*)&(registermcasp->key), usb11device); SharkSslSha1Ctx_append(&(registermcasp->hashCtx.sha1Ctx), cfconresource, ftraceupdate); SharkSslSha1Ctx_finish(&(registermcasp->hashCtx.sha1Ctx), cfconresource); break; #endif #if SHARKSSL_USE_MD5 case SHARKSSL_HASHID_MD5: SharkSslMd5Ctx_finish(&(registermcasp->hashCtx.md5Ctx), cfconresource); SharkSslMd5Ctx_constructor(&(registermcasp->hashCtx.md5Ctx)); SharkSslMd5Ctx_append(&(registermcasp->hashCtx.md5Ctx), (U8*)&(registermcasp->key), usb11device); SharkSslMd5Ctx_append(&(registermcasp->hashCtx.md5Ctx), cfconresource, ftraceupdate); SharkSslMd5Ctx_finish(&(registermcasp->hashCtx.md5Ctx), cfconresource); break; #endif default: break; } } } SHARKSSL_API int sharkssl_HMAC(const U8 configwrite, const U8 *alloccontroller, U32 len, const U8 *sourcerouting, U16 creategroup, U8 *secondaryentry) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslHMACCtx *hctx = (SharkSslHMACCtx *)baMalloc(claimresource(sizeof(SharkSslHMACCtx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslHMACCtx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller || (0 == len)); baAssert(sourcerouting || (0 == creategroup)); baAssert(creategroup); baAssert(secondaryentry); SharkSslHMACCtx_constructor(hctx, configwrite, sourcerouting, creategroup); SharkSslHMACCtx_append(hctx, alloccontroller, len); SharkSslHMACCtx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif #if SHARKSSL_USE_POLY1305 #if SHARKSSL_OPTIMIZED_POLY1305_ASM extern #else static #endif void recheckdelay(SharkSslPoly1305Ctx *registermcasp, const U8 *msg, U32 acsnhadvnh) #if SHARKSSL_OPTIMIZED_POLY1305_ASM ; #else { U64 d; U32 t[8], r[5]; U32 sha256export = registermcasp->flag; r[0] = registermcasp->r[0]; r[1] = registermcasp->r[1]; r[2] = registermcasp->r[2]; r[3] = registermcasp->r[3]; r[4] = registermcasp->r[4]; baAssert(0 == (acsnhadvnh & 0xF)); while (acsnhadvnh > 0) { cleanupcount(t[0], msg, 0); cleanupcount(t[1], msg, 4); cleanupcount(t[2], msg, 8); cleanupcount(t[3], msg, 12); r[0] += t[0]; d = (U64)(r[0] < t[0]); d += (U64)r[1] + t[1]; r[1] = (U32)d; d >>= 32; d += (U64)r[2] + t[2]; r[2] = (U32)d; d >>= 32; d += (U64)r[3] + t[3]; r[3] = (U32)d; d >>= 32; d += (U64)r[4] + sha256export; r[4] = (U32)d; d = (U64)r[0] * registermcasp->key[0]; t[0] = (U32)d; d >>= 32; d += (U64)r[0] * registermcasp->key[1]; d += (U64)r[1] * registermcasp->key[0]; t[1] = (U32)d; d >>= 32; d += (U64)r[0] * registermcasp->key[2]; d += (U64)r[1] * registermcasp->key[1]; d += (U64)r[2] * registermcasp->key[0]; t[2] = (U32)d; d >>= 32; d += (U64)r[0] * registermcasp->key[3]; d += (U64)r[1] * registermcasp->key[2]; d += (U64)r[2] * registermcasp->key[1]; d += (U64)r[3] * registermcasp->key[0]; t[3] = (U32)d; d >>= 32; d += (U64)r[1] * registermcasp->key[3]; d += (U64)r[2] * registermcasp->key[2]; d += (U64)r[3] * registermcasp->key[1]; d += (U32)((U8)r[4] * registermcasp->key[0]); t[4] = (U32)d; d >>= 32; d += (U64)r[2] * registermcasp->key[3]; d += (U64)r[3] * registermcasp->key[2]; d += (U32)((U8)r[4] * registermcasp->key[1]); t[5] = (U32)d; d >>= 32; d += (U64)r[3] * registermcasp->key[3]; d += (U32)((U8)r[4] * registermcasp->key[2]); t[6] = (U32)d; t[7] = (U32)(d >> 32) + (U32)((U8)r[4] * registermcasp->key[3]); d = (U64)t[0] + (t[4] & ~0x3) + ((t[4] >> 2) | (t[5] << 30)) + ((U64)(t[5] & 0x3) << 32); r[0] = (U32)d; d >>= 32; d += (U64)t[1] + (t[5] & ~0x3) + ((t[5] >> 2) | (t[6] << 30)) + ((U64)(t[6] & 0x3) << 32); r[1] = (U32)d; d >>= 32; d += (U64)t[2] + (t[6] & ~0x3) + ((t[6] >> 2) | (t[7] << 30)) + ((U64)(t[7] & 0x3) << 32); r[2] = (U32)d; d >>= 32; d += (U64)t[3] + (t[7] & ~0x3) + (t[7] >> 2); r[3] = (U32)d; r[4] = (U32)(d >> 32) + (t[4] & 0x03); msg += 16; acsnhadvnh -= 16; } registermcasp->r[0] = r[0]; registermcasp->r[1] = r[1]; registermcasp->r[2] = r[2]; registermcasp->r[3] = r[3]; registermcasp->r[4] = r[4]; } #endif SHARKSSL_API void SharkSslPoly1305Ctx_constructor(SharkSslPoly1305Ctx *registermcasp, const U8 sourcerouting[32]) { baAssert(((unsigned int)(UPTR)registermcasp & (sizeof(int)-1)) == 0); cleanupcount(registermcasp->key[0], sourcerouting, 0); cleanupcount(registermcasp->key[1], sourcerouting, 4); cleanupcount(registermcasp->key[2], sourcerouting, 8); cleanupcount(registermcasp->key[3], sourcerouting, 12); cleanupcount(registermcasp->nonce[0], sourcerouting, 16); cleanupcount(registermcasp->nonce[1], sourcerouting, 20); cleanupcount(registermcasp->nonce[2], sourcerouting, 24); cleanupcount(registermcasp->nonce[3], sourcerouting, 28); registermcasp->key[0] &= 0x0FFFFFFF; registermcasp->key[1] &= 0x0FFFFFFC; registermcasp->key[2] &= 0x0FFFFFFC; registermcasp->key[3] &= 0x0FFFFFFC; registermcasp->r[0] = 0; registermcasp->r[1] = 0; registermcasp->r[2] = 0; registermcasp->r[3] = 0; registermcasp->r[4] = 0; registermcasp->blen = 0; registermcasp->flag = 1; } SHARKSSL_API void SharkSslPoly1305Ctx_append(SharkSslPoly1305Ctx *registermcasp, const U8 *in, U32 len) { U32 pxa300evalboard = 16 - registermcasp->blen; if((registermcasp->blen) && (len >= pxa300evalboard)) { memcpy((registermcasp->buffer + registermcasp->blen), in, pxa300evalboard); recheckdelay(registermcasp, registermcasp->buffer, 16); len -= pxa300evalboard; in += pxa300evalboard; registermcasp->blen = 0; } if (len > 0xF) { pxa300evalboard = (len & ~0xF); recheckdelay(registermcasp, in, pxa300evalboard); in += pxa300evalboard; len &= 0xF; } if (len) { memcpy((registermcasp->buffer + registermcasp->blen), in, len); registermcasp->blen += (U8)len; } } SHARKSSL_API void SharkSslPoly1305Ctx_finish(SharkSslPoly1305Ctx *registermcasp, U8 secondaryentry[SHARKSSL_POLY1305_HASH_LEN]) { U64 d; if (registermcasp->blen) { registermcasp->flag = 0; registermcasp->buffer[registermcasp->blen++] = 0x01; while (registermcasp->blen < 16) { registermcasp->buffer[registermcasp->blen++] = 0x00; } recheckdelay(registermcasp, ®istermcasp->buffer[0], 16); } d = (U64)registermcasp->r[0] + registermcasp->nonce[0] + (registermcasp->r[4] & ~3) + (registermcasp->r[4] >> 2); hsotgpdata((U32)d, secondaryentry, 0); d >>= 32; d += (U64)registermcasp->r[1] + registermcasp->nonce[1]; hsotgpdata((U32)d, secondaryentry, 4); d >>= 32; d += (U64)registermcasp->r[2] + registermcasp->nonce[2]; hsotgpdata((U32)d, secondaryentry, 8); d >>= 32; d += (U64)registermcasp->r[3] + registermcasp->nonce[3]; hsotgpdata((U32)d, secondaryentry, 12); memset(registermcasp, 0, sizeof(SharkSslPoly1305Ctx)); } SHARKSSL_API int sharkssl_poly1305(const U8 *alloccontroller, U32 len, U8 *secondaryentry, const U8 sourcerouting[32]) { #if SHARKSSL_CRYPTO_USE_HEAP SharkSslPoly1305Ctx *hctx = (SharkSslPoly1305Ctx *)baMalloc(claimresource(sizeof(SharkSslPoly1305Ctx))); baAssert(hctx); if (!hctx) { return -1; } #else SharkSslPoly1305Ctx registermcasp; #define hctx ®istermcasp #endif baAssert(alloccontroller || (0 == len)); baAssert(len); baAssert(secondaryentry); baAssert(sourcerouting); SharkSslPoly1305Ctx_constructor(hctx, sourcerouting); SharkSslPoly1305Ctx_append(hctx, alloccontroller, len); SharkSslPoly1305Ctx_finish(hctx, secondaryentry); #if SHARKSSL_CRYPTO_USE_HEAP baFree(hctx); #else #undef hctx #endif return 0; } #endif #if SHARKSSL_USE_CHACHA20 #if SHARKSSL_OPTIMIZED_CHACHA_ASM extern #else #define invalidcontext(x,n) ((U32)((U32)x << n) | ((U32)x >> (32 - n))) #define disablecharger(a,b,c,d) \ state[a] = registermcasp->state[a] + registermcasp->state[b]; \ state[d] = invalidcontext((registermcasp->state[d] ^ state[a]), 16); \ state[c] = registermcasp->state[c] + state[d]; \ state[b] = invalidcontext((registermcasp->state[b] ^ state[c]), 12); \ state[a] += state[b]; \ state[d] = invalidcontext((state[d] ^ state[a]), 8); \ state[c] += state[d]; \ state[b] = invalidcontext((state[b] ^ state[c]), 7); #define firstdevice(a,b,c,d) \ state[a] += state[b]; \ state[d] = invalidcontext((state[d] ^ state[a]), 16); \ state[c] += state[d]; \ state[b] = invalidcontext((state[b] ^ state[c]), 12); \ state[a] += state[b]; \ state[d] = invalidcontext((state[d] ^ state[a]), 8); \ state[c] += state[d]; \ state[b] = invalidcontext((state[b] ^ state[c]), 7); #define ptracesethbpregs(a,b,c,d) \ state[a] += state[b]; \ state[d] = invalidcontext((state[d] ^ state[a]), 16); \ state[c] += state[d]; \ state[b] = invalidcontext((state[b] ^ state[c]), 12); \ t = state[a] + state[b]; \ state[a] = t + registermcasp->state[a]; \ t = invalidcontext((state[d] ^ t), 8); \ state[d] = t + registermcasp->state[d]; \ t += state[c]; \ state[c] = t + registermcasp->state[c]; \ t = invalidcontext((state[b] ^ t), 7); \ state[b] = t + registermcasp->state[b]; #endif SHARKSSL_API void SharkSslChaChaCtx_crypt(SharkSslChaChaCtx *registermcasp, const U8 *updatecause, U8 *enablehazard, U32 len) #if SHARKSSL_OPTIMIZED_CHACHA_ASM ; #else { U32 state[16]; int i; while (len > 0) { #if SHARKSSL_CHACHA_SMALL_FOOTPRINT memcpy(state, registermcasp->state, 64); for (i = 10; i > 0; i--) { firstdevice(0, 4, 8,12) firstdevice(1, 5, 9,13) firstdevice(2, 6,10,14) firstdevice(3, 7,11,15) firstdevice(0, 5,10,15) firstdevice(1, 6,11,12) firstdevice(2, 7, 8,13) firstdevice(3, 4, 9,14) } #else disablecharger(0, 4, 8,12) disablecharger(1, 5, 9,13) disablecharger(2, 6,10,14) disablecharger(3, 7,11,15) for (i = 9; i > 0; i--) { firstdevice(0, 5,10,15) firstdevice(1, 6,11,12) firstdevice(2, 7, 8,13) firstdevice(3, 4, 9,14) firstdevice(0, 4, 8,12) firstdevice(1, 5, 9,13) firstdevice(2, 6,10,14) firstdevice(3, 7,11,15) } { U32 t; ptracesethbpregs(0, 5,10,15) ptracesethbpregs(1, 6,11,12) ptracesethbpregs(2, 7, 8,13) ptracesethbpregs(3, 4, 9,14) } #endif i = 0; #if (!(SHARKSSL_UNALIGNED_ACCESS) && !(SHARKSSL_CHACHA_SMALL_FOOTPRINT)) if (0 == ((unsigned int)(UPTR)updatecause & 3)) #endif #if (SHARKSSL_UNALIGNED_ACCESS || !(SHARKSSL_CHACHA_SMALL_FOOTPRINT)) { if (len < 64) { while (len >= 4) { #ifdef B_LITTLE_ENDIAN #if SHARKSSL_CHACHA_SMALL_FOOTPRINT hsotgpdata((state[i] + registermcasp->state[i]) ^ (*(__sharkssl_packed U32*)updatecause), enablehazard, 0); #else hsotgpdata(state[i] ^ (*(__sharkssl_packed U32*)updatecause), enablehazard, 0); #endif #elif defined(B_BIG_ENDIAN) #if SHARKSSL_CHACHA_SMALL_FOOTPRINT hsotgpdata((state[i] + registermcasp->state[i]) ^ blockarray(*(__sharkssl_packed U32*)updatecause), enablehazard, 0); #else hsotgpdata(state[i] ^ blockarray(*(__sharkssl_packed U32*)updatecause), enablehazard, 0); #endif #else #error #define either B_LITTLE_ENDIAN or B_BIG_ENDIAN #endif i++; enablehazard += 4; updatecause += 4; len -= 4; } if (len > 0) { #if SHARKSSL_CHACHA_SMALL_FOOTPRINT state[i] += registermcasp->state[i]; #endif *enablehazard++ = (U8)(state[i]) ^ *updatecause++; if (len >= 2) { *enablehazard++ = (U8)(state[i] >> 8) ^ *updatecause++; if (len >= 3) { *enablehazard++ = (U8)(state[i] >> 16) ^ *updatecause++; } } len = 0; } } else { #ifdef B_LITTLE_ENDIAN #if SHARKSSL_CHACHA_SMALL_FOOTPRINT hsotgpdata((state[0] + registermcasp->state[0]) ^ ((__sharkssl_packed U32*)updatecause)[0], enablehazard, 0); hsotgpdata((state[1] + registermcasp->state[1]) ^ ((__sharkssl_packed U32*)updatecause)[1], enablehazard, 4); hsotgpdata((state[2] + registermcasp->state[2]) ^ ((__sharkssl_packed U32*)updatecause)[2], enablehazard, 8); hsotgpdata((state[3] + registermcasp->state[3]) ^ ((__sharkssl_packed U32*)updatecause)[3], enablehazard, 12); hsotgpdata((state[4] + registermcasp->state[4]) ^ ((__sharkssl_packed U32*)updatecause)[4], enablehazard, 16); hsotgpdata((state[5] + registermcasp->state[5]) ^ ((__sharkssl_packed U32*)updatecause)[5], enablehazard, 20); hsotgpdata((state[6] + registermcasp->state[6]) ^ ((__sharkssl_packed U32*)updatecause)[6], enablehazard, 24); hsotgpdata((state[7] + registermcasp->state[7]) ^ ((__sharkssl_packed U32*)updatecause)[7], enablehazard, 28); hsotgpdata((state[8] + registermcasp->state[8]) ^ ((__sharkssl_packed U32*)updatecause)[8], enablehazard, 32); hsotgpdata((state[9] + registermcasp->state[9]) ^ ((__sharkssl_packed U32*)updatecause)[9], enablehazard, 36); hsotgpdata((state[10] + registermcasp->state[10]) ^ ((__sharkssl_packed U32*)updatecause)[10], enablehazard, 40); hsotgpdata((state[11] + registermcasp->state[11]) ^ ((__sharkssl_packed U32*)updatecause)[11], enablehazard, 44); hsotgpdata((state[12] + registermcasp->state[12]) ^ ((__sharkssl_packed U32*)updatecause)[12], enablehazard, 48); hsotgpdata((state[13] + registermcasp->state[13]) ^ ((__sharkssl_packed U32*)updatecause)[13], enablehazard, 52); hsotgpdata((state[14] + registermcasp->state[14]) ^ ((__sharkssl_packed U32*)updatecause)[14], enablehazard, 56); hsotgpdata((state[15] + registermcasp->state[15]) ^ ((__sharkssl_packed U32*)updatecause)[15], enablehazard, 60); #else hsotgpdata(state[0] ^ ((__sharkssl_packed U32*)updatecause)[0], enablehazard, 0); hsotgpdata(state[1] ^ ((__sharkssl_packed U32*)updatecause)[1], enablehazard, 4); hsotgpdata(state[2] ^ ((__sharkssl_packed U32*)updatecause)[2], enablehazard, 8); hsotgpdata(state[3] ^ ((__sharkssl_packed U32*)updatecause)[3], enablehazard, 12); hsotgpdata(state[4] ^ ((__sharkssl_packed U32*)updatecause)[4], enablehazard, 16); hsotgpdata(state[5] ^ ((__sharkssl_packed U32*)updatecause)[5], enablehazard, 20); hsotgpdata(state[6] ^ ((__sharkssl_packed U32*)updatecause)[6], enablehazard, 24); hsotgpdata(state[7] ^ ((__sharkssl_packed U32*)updatecause)[7], enablehazard, 28); hsotgpdata(state[8] ^ ((__sharkssl_packed U32*)updatecause)[8], enablehazard, 32); hsotgpdata(state[9] ^ ((__sharkssl_packed U32*)updatecause)[9], enablehazard, 36); hsotgpdata(state[10] ^ ((__sharkssl_packed U32*)updatecause)[10], enablehazard, 40); hsotgpdata(state[11] ^ ((__sharkssl_packed U32*)updatecause)[11], enablehazard, 44); hsotgpdata(state[12] ^ ((__sharkssl_packed U32*)updatecause)[12], enablehazard, 48); hsotgpdata(state[13] ^ ((__sharkssl_packed U32*)updatecause)[13], enablehazard, 52); hsotgpdata(state[14] ^ ((__sharkssl_packed U32*)updatecause)[14], enablehazard, 56); hsotgpdata(state[15] ^ ((__sharkssl_packed U32*)updatecause)[15], enablehazard, 60); #endif #elif defined(B_BIG_ENDIAN) #if SHARKSSL_CHACHA_SMALL_FOOTPRINT hsotgpdata((state[0] + registermcasp->state[0]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[0]), enablehazard, 0); hsotgpdata((state[1] + registermcasp->state[1]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[1]), enablehazard, 4); hsotgpdata((state[2] + registermcasp->state[2]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[2]), enablehazard, 8); hsotgpdata((state[3] + registermcasp->state[3]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[3]), enablehazard, 12); hsotgpdata((state[4] + registermcasp->state[4]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[4]), enablehazard, 16); hsotgpdata((state[5] + registermcasp->state[5]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[5]), enablehazard, 20); hsotgpdata((state[6] + registermcasp->state[6]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[6]), enablehazard, 24); hsotgpdata((state[7] + registermcasp->state[7]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[7]), enablehazard, 28); hsotgpdata((state[8] + registermcasp->state[8]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[8]), enablehazard, 32); hsotgpdata((state[9] + registermcasp->state[9]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[9]), enablehazard, 36); hsotgpdata((state[10] + registermcasp->state[10]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[10]), enablehazard, 40); hsotgpdata((state[11] + registermcasp->state[11]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[11]), enablehazard, 44); hsotgpdata((state[12] + registermcasp->state[12]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[12]), enablehazard, 48); hsotgpdata((state[13] + registermcasp->state[13]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[13]), enablehazard, 52); hsotgpdata((state[14] + registermcasp->state[14]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[14]), enablehazard, 56); hsotgpdata((state[15] + registermcasp->state[15]) ^ blockarray(((__sharkssl_packed U32*)updatecause)[15]), enablehazard, 60); #else hsotgpdata(state[0] ^ blockarray(((__sharkssl_packed U32*)updatecause)[0]), enablehazard, 0); hsotgpdata(state[1] ^ blockarray(((__sharkssl_packed U32*)updatecause)[1]), enablehazard, 4); hsotgpdata(state[2] ^ blockarray(((__sharkssl_packed U32*)updatecause)[2]), enablehazard, 8); hsotgpdata(state[3] ^ blockarray(((__sharkssl_packed U32*)updatecause)[3]), enablehazard, 12); hsotgpdata(state[4] ^ blockarray(((__sharkssl_packed U32*)updatecause)[4]), enablehazard, 16); hsotgpdata(state[5] ^ blockarray(((__sharkssl_packed U32*)updatecause)[5]), enablehazard, 20); hsotgpdata(state[6] ^ blockarray(((__sharkssl_packed U32*)updatecause)[6]), enablehazard, 24); hsotgpdata(state[7] ^ blockarray(((__sharkssl_packed U32*)updatecause)[7]), enablehazard, 28); hsotgpdata(state[8] ^ blockarray(((__sharkssl_packed U32*)updatecause)[8]), enablehazard, 32); hsotgpdata(state[9] ^ blockarray(((__sharkssl_packed U32*)updatecause)[9]), enablehazard, 36); hsotgpdata(state[10] ^ blockarray(((__sharkssl_packed U32*)updatecause)[10]), enablehazard, 40); hsotgpdata(state[11] ^ blockarray(((__sharkssl_packed U32*)updatecause)[11]), enablehazard, 44); hsotgpdata(state[12] ^ blockarray(((__sharkssl_packed U32*)updatecause)[12]), enablehazard, 48); hsotgpdata(state[13] ^ blockarray(((__sharkssl_packed U32*)updatecause)[13]), enablehazard, 52); hsotgpdata(state[14] ^ blockarray(((__sharkssl_packed U32*)updatecause)[14]), enablehazard, 56); hsotgpdata(state[15] ^ blockarray(((__sharkssl_packed U32*)updatecause)[15]), enablehazard, 60); #endif #endif len -= 64; enablehazard += 64; updatecause += 64; } } #endif #if (!(SHARKSSL_UNALIGNED_ACCESS)) #if (!(SHARKSSL_CHACHA_SMALL_FOOTPRINT)) else #endif { while (!(i & 0x10) && (len > 0)) { U32 st; #if SHARKSSL_CHACHA_SMALL_FOOTPRINT state[i] += registermcasp->state[i]; #endif st = state[i]; *enablehazard++ = (U8)(st) ^ *updatecause++; if (--len) { *enablehazard++ = (U8)(st >> 8) ^ *updatecause++; if (--len) { *enablehazard++ = (U8)(st >> 16) ^ *updatecause++; if (--len) { *enablehazard++ = (U8)(st >> 24) ^ *updatecause++; len--; i++; } } } } } #endif if (0 == (++registermcasp->state[12])) { registermcasp->state[13]++; } } } #undef ptracesethbpregs #undef firstdevice #undef disablecharger #undef invalidcontext #endif SHARKSSL_API void SharkSslChaChaCtx_constructor(SharkSslChaChaCtx *registermcasp, const U8 *sourcerouting, U8 creategroup) { static const char mcbsp1hwmod[] = "\145\170\160\141\156\144\040\063\062\055\142\171\164\145\040\153"; static const char tau[] = "\145\170\160\141\156\144\040\061\066\055\142\171\164\145\040\153"; const char *write64uint32; cleanupcount(registermcasp->state[4], sourcerouting, 0); cleanupcount(registermcasp->state[5], sourcerouting, 4); cleanupcount(registermcasp->state[6], sourcerouting, 8); cleanupcount(registermcasp->state[7], sourcerouting, 12); if (creategroup == 32) { sourcerouting += 16; write64uint32 = mcbsp1hwmod; } else { write64uint32 = tau; } cleanupcount(registermcasp->state[8], sourcerouting, 0); cleanupcount(registermcasp->state[9], sourcerouting, 4); cleanupcount(registermcasp->state[10], sourcerouting, 8); cleanupcount(registermcasp->state[11], sourcerouting, 12); cleanupcount(registermcasp->state[0], write64uint32, 0); cleanupcount(registermcasp->state[1], write64uint32, 4); cleanupcount(registermcasp->state[2], write64uint32, 8); cleanupcount(registermcasp->state[3], write64uint32, 12); } SHARKSSL_API void SharkSslChaChaCtx_setIV(SharkSslChaChaCtx *registermcasp, const U8 IV[12]) { registermcasp->state[12] = 0; cleanupcount(registermcasp->state[13], IV, 0); cleanupcount(registermcasp->state[14], IV, 4); cleanupcount(registermcasp->state[15], IV, 8); } #endif #if (SHARKSSL_SSL_CLIENT_CODE || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_ENABLE_AES_GCM || SHARKSSL_ENABLE_PEM_API) SHARKSSL_API int sharkssl_kmemcmp(const void *a, const void *b, U32 n) { U8 cmp = 0; #if SHARKSSL_UNALIGNED_ACCESS const U8 *p8a, *p8b; __sharkssl_packed const U32 *exceptionlevel = (const U32*)a; __sharkssl_packed const U32 *movinandinserted = (const U32*)b; U32 dointvecminmax = 0; while (n >= 4) { dointvecminmax |= (*exceptionlevel++ ^ *movinandinserted++); n -= 4; } dointvecminmax = (dointvecminmax & 0xFFFF) | (dointvecminmax >> 16); cmp = (U8)dointvecminmax | (U8)(dointvecminmax >> 8); p8a = (U8*)exceptionlevel; p8b = (U8*)movinandinserted; #else U8 *p8a = (U8*)a; U8 *p8b = (U8*)b; #endif while (n--) { cmp |= (*p8a++ ^ *p8b++); } return (int)cmp; } #endif #if (SHARKSSL_USE_AES_256 || SHARKSSL_USE_AES_192 || SHARKSSL_USE_AES_128) #if SHARKSSL_AES_TABLES_IN_RAM static U32 alloczeroed[256]; static U32 domainalways[256]; static U32 timeoutshift[10]; #if (!SHARKSSL_AES_DISABLE_SBOX) static U8 class3configure[256]; #endif #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) static U8 powerpdata[256]; #endif #endif #if (!SHARKSSL_AES_DISABLE_SBOX) #if SHARKSSL_AES_TABLES_IN_RAM static const U8 singlefuito[256] = #else static const U8 class3configure[256] = #endif { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; #endif #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) #if SHARKSSL_AES_TABLES_IN_RAM static const U8 spinboxhwmod[256] = #else static const U8 powerpdata[256] = #endif { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; #endif #if SHARKSSL_AES_TABLES_IN_RAM static const U32 timerevtstrm[256] = #else static const U32 alloczeroed[256] = #endif { 0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a }; #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) #if SHARKSSL_AES_TABLES_IN_RAM static const U32 thumb32break[256] = #else static const U32 domainalways[256] = #endif { 0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742 }; #endif #if SHARKSSL_AES_TABLES_IN_RAM static const U32 enterlowpower[10] = #else static const U32 timeoutshift[10] = #endif { 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000 }; #define mcspidevice(a, n) (((a) >> n) | ((a) << (32 - n))) SHARKSSL_API void SharkSslAesCtx_constructor(SharkSslAesCtx *registermcasp, SharkSslAesCtx_Type rightsvalid, const U8 *sourcerouting, U8 creategroup) { U32 *countshift, brightnesslimit; U16 i; #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) U16 j; #endif baAssert(registermcasp); baAssert(sourcerouting); #if (SHARKSSL_USE_AES_256) #if (SHARKSSL_USE_AES_192) #if (SHARKSSL_USE_AES_128) baAssert((creategroup == 32) || (creategroup == 24) || (creategroup == 16)); #else baAssert((creategroup == 32) || (creategroup == 24)); #endif #else #if (SHARKSSL_USE_AES_128) baAssert((creategroup == 32) || (creategroup == 16)); #else baAssert(creategroup == 32); #endif #endif #else #if (SHARKSSL_USE_AES_192) #if (SHARKSSL_USE_AES_128) baAssert((creategroup == 24) || (creategroup == 16)); #else baAssert((creategroup == 24)); #endif #else baAssert((SHARKSSL_USE_AES_128) && (creategroup == 16)); #endif #endif #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) baAssert((rightsvalid == SharkSslAesCtx_Decrypt) || (rightsvalid == SharkSslAesCtx_Encrypt)); #else baAssert(rightsvalid == SharkSslAesCtx_Decrypt); #endif #if SHARKSSL_AES_TABLES_IN_RAM if (!alloczeroed[0]) { memcpy(alloczeroed, timerevtstrm, sizeof(timerevtstrm)); memcpy(domainalways, thumb32break, sizeof(thumb32break)); memcpy(timeoutshift, enterlowpower, sizeof(enterlowpower)); #if (!SHARKSSL_AES_DISABLE_SBOX) memcpy(class3configure, singlefuito, sizeof(singlefuito)); #endif #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) memcpy(powerpdata, spinboxhwmod, sizeof(spinboxhwmod)); #endif } #endif countshift = registermcasp->key; read64uint32(countshift[0], sourcerouting, 0); read64uint32(countshift[1], sourcerouting, 4); read64uint32(countshift[2], sourcerouting, 8); read64uint32(countshift[3], sourcerouting, 12); switch (creategroup) { #if (SHARKSSL_USE_AES_128) case 16: registermcasp->nr = 10; for (i = 0; i < 10; i++, countshift += 4) { brightnesslimit = countshift[3]; #if SHARKSSL_AES_DISABLE_SBOX brightnesslimit = ((alloczeroed[exceptionupdates(brightnesslimit)] << 8) & 0xFF000000) | (alloczeroed[iisv4resource(brightnesslimit)] & 0x00FF0000) | (alloczeroed[translationfault(brightnesslimit)] & 0x0000FF00) | ((alloczeroed[setupcmdline(brightnesslimit)] >> 8) & 0x000000FF); #else brightnesslimit = ((U32)class3configure[exceptionupdates(brightnesslimit)] << 24) | ((U32)class3configure[iisv4resource(brightnesslimit)] << 16) | ((U32)class3configure[translationfault(brightnesslimit)] << 8) | ((U32)class3configure[setupcmdline(brightnesslimit)] ); #endif countshift[4] = brightnesslimit ^ countshift[0] ^ timeoutshift[i]; countshift[5] = countshift[1] ^ countshift[4]; countshift[6] = countshift[2] ^ countshift[5]; countshift[7] = countshift[3] ^ countshift[6]; } break; #endif #if (SHARKSSL_USE_AES_192) case 24: read64uint32(countshift[4], sourcerouting, 16); read64uint32(countshift[5], sourcerouting, 20); registermcasp->nr = 12; for (i = 0; i < 8; i++, countshift += 6) { brightnesslimit = countshift[5]; #if SHARKSSL_AES_DISABLE_SBOX brightnesslimit = ((alloczeroed[exceptionupdates(brightnesslimit)] << 8) & 0xFF000000) | (alloczeroed[iisv4resource(brightnesslimit)] & 0x00FF0000) | (alloczeroed[translationfault(brightnesslimit)] & 0x0000FF00) | ((alloczeroed[setupcmdline(brightnesslimit)] >> 8) & 0x000000FF); #else brightnesslimit = ((U32)class3configure[exceptionupdates(brightnesslimit)] << 24) | ((U32)class3configure[iisv4resource(brightnesslimit)] << 16) | ((U32)class3configure[translationfault(brightnesslimit)] << 8) | ((U32)class3configure[setupcmdline(brightnesslimit)] ); #endif countshift[6] = brightnesslimit ^ countshift[0] ^ timeoutshift[i]; countshift[7] = countshift[1] ^ countshift[6]; countshift[8] = countshift[2] ^ countshift[7]; countshift[9] = countshift[3] ^ countshift[8]; if (i < 7) { countshift[10] = countshift[4] ^ countshift[9]; countshift[11] = countshift[5] ^ countshift[10]; } } break; #endif #if (SHARKSSL_USE_AES_256) case 32: read64uint32(countshift[4], sourcerouting, 16); read64uint32(countshift[5], sourcerouting, 20); read64uint32(countshift[6], sourcerouting, 24); read64uint32(countshift[7], sourcerouting, 28); registermcasp->nr = 14; for (i = 0; i < 7; i++, countshift += 8) { brightnesslimit = countshift[7]; #if SHARKSSL_AES_DISABLE_SBOX brightnesslimit = ((alloczeroed[exceptionupdates(brightnesslimit)] << 8) & 0xFF000000) | (alloczeroed[iisv4resource(brightnesslimit)] & 0x00FF0000) | (alloczeroed[translationfault(brightnesslimit)] & 0x0000FF00) | ((alloczeroed[setupcmdline(brightnesslimit)] >> 8) & 0x000000FF); #else brightnesslimit = ((U32)class3configure[exceptionupdates(brightnesslimit)] << 24) | ((U32)class3configure[iisv4resource(brightnesslimit)] << 16) | ((U32)class3configure[translationfault(brightnesslimit)] << 8) | ((U32)class3configure[setupcmdline(brightnesslimit)] ); #endif countshift[8] = brightnesslimit ^ countshift[0] ^ timeoutshift[i]; countshift[9] = countshift[1] ^ countshift[8]; countshift[10] = countshift[2] ^ countshift[9]; countshift[11] = countshift[3] ^ countshift[10]; if (i < 6) { brightnesslimit = countshift[11]; #if SHARKSSL_AES_DISABLE_SBOX brightnesslimit = ((alloczeroed[setupcmdline(brightnesslimit)] << 8) & 0xFF000000) | (alloczeroed[exceptionupdates(brightnesslimit)] & 0x00FF0000) | (alloczeroed[iisv4resource(brightnesslimit)] & 0x0000FF00) | ((alloczeroed[translationfault(brightnesslimit)] >> 8) & 0x000000FF); #else brightnesslimit = ((U32)class3configure[setupcmdline(brightnesslimit)] << 24) | ((U32)class3configure[exceptionupdates(brightnesslimit)] << 16) | ((U32)class3configure[iisv4resource(brightnesslimit)] << 8) | ((U32)class3configure[translationfault(brightnesslimit)] ); #endif countshift[12] = brightnesslimit ^ countshift[4]; countshift[13] = countshift[5] ^ countshift[12]; countshift[14] = countshift[6] ^ countshift[13]; countshift[15] = countshift[7] ^ countshift[14]; } } break; #endif default: baAssert(0); break; } #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) if (rightsvalid == SharkSslAesCtx_Decrypt) { countshift += 4; for (i = 1; i < registermcasp->nr; i++) { countshift -= 8; for (j = 4; j > 0; j--) { brightnesslimit = *countshift; #if SHARKSSL_AES_DISABLE_SBOX *countshift++ = domainalways[(U8)(alloczeroed[setupcmdline(brightnesslimit)] >> 8)] ^ mcspidevice(domainalways[(U8)(alloczeroed[exceptionupdates(brightnesslimit)] >> 8)], 8) ^ mcspidevice(domainalways[(U8)(alloczeroed[iisv4resource(brightnesslimit)] >> 8)], 16) ^ mcspidevice(domainalways[(U8)(alloczeroed[translationfault(brightnesslimit)] >> 8)], 24); #else *countshift++ = domainalways[class3configure[setupcmdline(brightnesslimit)]] ^ mcspidevice(domainalways[class3configure[exceptionupdates(brightnesslimit)]], 8) ^ mcspidevice(domainalways[class3configure[iisv4resource(brightnesslimit)]], 16) ^ mcspidevice(domainalways[class3configure[translationfault(brightnesslimit)]], 24); #endif } } } #endif #if ((!SHARKSSL_AES_SMALL_FOOTPRINT) && SHARKSSL_AES_CIPHER_LOOP_UNROLL) registermcasp->nr >>= 1; #endif registermcasp->nr--; } #define AES_ENC_ROUND(s, t, k, mixtable) do { \ k += 4; \ t[0] = k[0] ^ mixtable[setupcmdline(s[0])] ^ \ mcspidevice(mixtable[exceptionupdates(s[1])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[2])], 16) ^ \ mcspidevice(mixtable[translationfault(s[3])], 24); \ t[1] = k[1] ^ mixtable[setupcmdline(s[1])] ^ \ mcspidevice(mixtable[exceptionupdates(s[2])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[3])], 16) ^ \ mcspidevice(mixtable[translationfault(s[0])], 24); \ t[2] = k[2] ^ mixtable[setupcmdline(s[2])] ^ \ mcspidevice(mixtable[exceptionupdates(s[3])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[0])], 16) ^ \ mcspidevice(mixtable[translationfault(s[1])], 24); \ t[3] = k[3] ^ mixtable[setupcmdline(s[3])] ^ \ mcspidevice(mixtable[exceptionupdates(s[0])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[1])], 16) ^ \ mcspidevice(mixtable[translationfault(s[2])], 24); \ } while (0); #if SHARKSSL_AES_DISABLE_SBOX #define AES_ENC_FINAL_ROUND(out, s, k, sbox) do { \ k += 4; \ out[0] = (U8)((setupcmdline(k[0])) ^ ((U8)(sbox[setupcmdline(s[0])] >> 8))); \ out[1] = (U8)((exceptionupdates(k[0])) ^ ((U8)(sbox[exceptionupdates(s[1])] >> 8))); \ out[2] = (U8)((iisv4resource(k[0])) ^ ((U8)(sbox[iisv4resource(s[2])] >> 8))); \ out[3] = (U8)((translationfault(k[0])) ^ ((U8)(sbox[translationfault(s[3])] >> 8))); \ out[4] = (U8)((setupcmdline(k[1])) ^ ((U8)(sbox[setupcmdline(s[1])] >> 8))); \ out[5] = (U8)((exceptionupdates(k[1])) ^ ((U8)(sbox[exceptionupdates(s[2])] >> 8))); \ out[6] = (U8)((iisv4resource(k[1])) ^ ((U8)(sbox[iisv4resource(s[3])] >> 8))); \ out[7] = (U8)((translationfault(k[1])) ^ ((U8)(sbox[translationfault(s[0])] >> 8))); \ out[8] = (U8)((setupcmdline(k[2])) ^ ((U8)(sbox[setupcmdline(s[2])] >> 8))); \ out[9] = (U8)((exceptionupdates(k[2])) ^ ((U8)(sbox[exceptionupdates(s[3])] >> 8))); \ out[10] = (U8)((iisv4resource(k[2])) ^ ((U8)(sbox[iisv4resource(s[0])] >> 8))); \ out[11] = (U8)((translationfault(k[2])) ^ ((U8)(sbox[translationfault(s[1])] >> 8))); \ out[12] = (U8)((setupcmdline(k[3])) ^ ((U8)(sbox[setupcmdline(s[3])] >> 8))); \ out[13] = (U8)((exceptionupdates(k[3])) ^ ((U8)(sbox[exceptionupdates(s[0])] >> 8))); \ out[14] = (U8)((iisv4resource(k[3])) ^ ((U8)(sbox[iisv4resource(s[1])] >> 8))); \ out[15] = (U8)((translationfault(k[3])) ^ ((U8)(sbox[translationfault(s[2])] >> 8))); \ } while (0); #else #define AES_ENC_FINAL_ROUND(out, s, k, sbox) do { \ k += 4; \ out[0] = (U8)((setupcmdline(k[0])) ^ sbox[setupcmdline(s[0])]); \ out[1] = (U8)((exceptionupdates(k[0])) ^ sbox[exceptionupdates(s[1])]); \ out[2] = (U8)((iisv4resource(k[0])) ^ sbox[iisv4resource(s[2])]); \ out[3] = (U8)((translationfault(k[0])) ^ sbox[translationfault(s[3])]); \ out[4] = (U8)((setupcmdline(k[1])) ^ sbox[setupcmdline(s[1])]); \ out[5] = (U8)((exceptionupdates(k[1])) ^ sbox[exceptionupdates(s[2])]); \ out[6] = (U8)((iisv4resource(k[1])) ^ sbox[iisv4resource(s[3])]); \ out[7] = (U8)((translationfault(k[1])) ^ sbox[translationfault(s[0])]); \ out[8] = (U8)((setupcmdline(k[2])) ^ sbox[setupcmdline(s[2])]); \ out[9] = (U8)((exceptionupdates(k[2])) ^ sbox[exceptionupdates(s[3])]); \ out[10] = (U8)((iisv4resource(k[2])) ^ sbox[iisv4resource(s[0])]); \ out[11] = (U8)((translationfault(k[2])) ^ sbox[translationfault(s[1])]); \ out[12] = (U8)((setupcmdline(k[3])) ^ sbox[setupcmdline(s[3])]); \ out[13] = (U8)((exceptionupdates(k[3])) ^ sbox[exceptionupdates(s[0])]); \ out[14] = (U8)((iisv4resource(k[3])) ^ sbox[iisv4resource(s[1])]); \ out[15] = (U8)((translationfault(k[3])) ^ sbox[translationfault(s[2])]); \ } while (0); #endif SHARKSSL_API void SharkSslAesCtx_encrypt(SharkSslAesCtx *registermcasp, U8 updatecause[16], U8 enablehazard[16]) { U32 *K, S[4], T[4]; U16 i; #if SHARKSSL_AES_SMALL_FOOTPRINT U16 j, z, y; #endif baAssert(registermcasp->nr > 0); i = registermcasp->nr; K = registermcasp->key; read64uint32(S[0], updatecause, 0); S[0] ^= K[0]; read64uint32(S[1], updatecause, 4); S[1] ^= K[1]; read64uint32(S[2], updatecause, 8); S[2] ^= K[2]; read64uint32(S[3], updatecause, 12); S[3] ^= K[3]; #if SHARKSSL_AES_SMALL_FOOTPRINT K += 4; do { for (j = 0; !(j & 4); j++) { T[j] = *K++; for (z = 0, y = 0; !(z & 4); z++, y += 8) { U32 r = alloczeroed[(U8)(S[(j + z) & 3] >> (24 - y))]; T[j] ^= mcspidevice(r, y); } } S[0] = T[0]; S[1] = T[1]; S[2] = T[2]; S[3] = T[3]; } while (--i); i = 0; for (j = 0; !(j & 4); j++) { for (z = 0, y = 24; !(z & 4); z++, y -= 8) { #if SHARKSSL_AES_DISABLE_SBOX enablehazard[i++] = (U8)((K[j] >> y) ^ (U8)(alloczeroed[(U8)(T[(j + z) & 3] >> y)] >> 8)); #else enablehazard[i++] = (U8)((K[j] >> y) ^ class3configure[(U8)(T[(j + z) & 3] >> y)]); #endif } } #else #if SHARKSSL_AES_CIPHER_LOOP_UNROLL AES_ENC_ROUND(S, T, K, alloczeroed); #endif do { #if SHARKSSL_AES_CIPHER_LOOP_UNROLL AES_ENC_ROUND(T, S, K, alloczeroed); AES_ENC_ROUND(S, T, K, alloczeroed); #else AES_ENC_ROUND(S, T, K, alloczeroed); S[0] = T[0]; S[1] = T[1]; S[2] = T[2]; S[3] = T[3]; #endif } while (--i); #if SHARKSSL_AES_DISABLE_SBOX AES_ENC_FINAL_ROUND(enablehazard, T, K, alloczeroed); #else AES_ENC_FINAL_ROUND(enablehazard, T, K, class3configure); #endif #endif } #undef AES_ENC_ROUND #undef AES_ENC_FINAL_ROUND #if (!SHARKSSL_DISABLE_AES_ECB_DECRYPT) #define AES_DEC_ROUND(s, t, k, mixtable) do { \ k -= 4; \ t[0] = k[0] ^ mixtable[setupcmdline(s[0])] ^ \ mcspidevice(mixtable[exceptionupdates(s[3])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[2])], 16) ^ \ mcspidevice(mixtable[translationfault(s[1])], 24); \ t[1] = k[1] ^ mixtable[setupcmdline(s[1])] ^ \ mcspidevice(mixtable[exceptionupdates(s[0])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[3])], 16) ^ \ mcspidevice(mixtable[translationfault(s[2])], 24); \ t[2] = k[2] ^ mixtable[setupcmdline(s[2])] ^ \ mcspidevice(mixtable[exceptionupdates(s[1])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[0])], 16) ^ \ mcspidevice(mixtable[translationfault(s[3])], 24); \ t[3] = k[3] ^ mixtable[setupcmdline(s[3])] ^ \ mcspidevice(mixtable[exceptionupdates(s[2])], 8) ^ \ mcspidevice(mixtable[iisv4resource(s[1])], 16) ^ \ mcspidevice(mixtable[translationfault(s[0])], 24); \ } while (0); #define AES_DEC_FINAL_ROUND(out, s, k, sbox) do { \ k -= 4; \ out[0] = (U8)((setupcmdline(k[0])) ^ sbox[setupcmdline(s[0])]); \ out[1] = (U8)((exceptionupdates(k[0])) ^ sbox[exceptionupdates(s[3])]); \ out[2] = (U8)((iisv4resource(k[0])) ^ sbox[iisv4resource(s[2])]); \ out[3] = (U8)((translationfault(k[0])) ^ sbox[translationfault(s[1])]); \ out[4] = (U8)((setupcmdline(k[1])) ^ sbox[setupcmdline(s[1])]); \ out[5] = (U8)((exceptionupdates(k[1])) ^ sbox[exceptionupdates(s[0])]); \ out[6] = (U8)((iisv4resource(k[1])) ^ sbox[iisv4resource(s[3])]); \ out[7] = (U8)((translationfault(k[1])) ^ sbox[translationfault(s[2])]); \ out[8] = (U8)((setupcmdline(k[2])) ^ sbox[setupcmdline(s[2])]); \ out[9] = (U8)((exceptionupdates(k[2])) ^ sbox[exceptionupdates(s[1])]); \ out[10] = (U8)((iisv4resource(k[2])) ^ sbox[iisv4resource(s[0])]); \ out[11] = (U8)((translationfault(k[2])) ^ sbox[translationfault(s[3])]); \ out[12] = (U8)((setupcmdline(k[3])) ^ sbox[setupcmdline(s[3])]); \ out[13] = (U8)((exceptionupdates(k[3])) ^ sbox[exceptionupdates(s[2])]); \ out[14] = (U8)((iisv4resource(k[3])) ^ sbox[iisv4resource(s[1])]); \ out[15] = (U8)((translationfault(k[3])) ^ sbox[translationfault(s[0])]); \ } while (0); SHARKSSL_API void SharkSslAesCtx_decrypt(SharkSslAesCtx *registermcasp, const U8 updatecause[16], U8 enablehazard[16]) { U32 *K, S[4], T[4]; U16 i; #if SHARKSSL_AES_SMALL_FOOTPRINT U16 j, z, y; #endif baAssert(registermcasp->nr > 0); i = registermcasp->nr; #if ((!SHARKSSL_AES_SMALL_FOOTPRINT) && SHARKSSL_AES_CIPHER_LOOP_UNROLL) K = ®istermcasp->key[(i + 1) << 3]; #else K = ®istermcasp->key[(i + 1) << 2]; #endif read64uint32(S[0], updatecause, 0); S[0] ^= K[0]; read64uint32(S[1], updatecause, 4); S[1] ^= K[1]; read64uint32(S[2], updatecause, 8); S[2] ^= K[2]; read64uint32(S[3], updatecause, 12); S[3] ^= K[3]; #if SHARKSSL_AES_SMALL_FOOTPRINT do { j = 3; do { T[j] = *(--K); for (z = 4, y = 0; z > 0; z--, y += 8) { U32 r = domainalways[(U8)(S[(j + z) & 3] >> (24 - y))]; T[j] ^= mcspidevice(r, y); } } while (j--); S[0] = T[0]; S[1] = T[1]; S[2] = T[2]; S[3] = T[3]; } while (--i); i = 0; K -= 4; for (j = 0; !(j & 4); j++) { for (z = 0, y = 24; !(z & 4); z++, y -= 8) { enablehazard[i++] = (U8)((K[j] >> y) ^ powerpdata[(U8)(T[((U8)(j - z)) & 3] >> y)]); } } #else #if SHARKSSL_AES_CIPHER_LOOP_UNROLL AES_DEC_ROUND(S, T, K, domainalways); #endif do { #if SHARKSSL_AES_CIPHER_LOOP_UNROLL AES_DEC_ROUND(T, S, K, domainalways); AES_DEC_ROUND(S, T, K, domainalways); #else AES_DEC_ROUND(S, T, K, domainalways); S[0] = T[0]; S[1] = T[1]; S[2] = T[2]; S[3] = T[3]; #endif } while (--i); AES_DEC_FINAL_ROUND(enablehazard, T, K, powerpdata); #endif } #undef AES_DEC_ROUND #undef AES_DEC_FINAL_ROUND #endif #undef mcspidevice #if SHARKSSL_ENABLE_AES_CBC SHARKSSL_API void SharkSslAesCtx_cbc_encrypt(SharkSslAesCtx *registermcasp, U8 vect[16], const U8 *updatecause, U8 *enablehazard, U32 len) { U8 *q = vect; baAssert(registermcasp); baAssert(vect); baAssert(updatecause); baAssert(enablehazard); baAssert((len & 0x0F) == 0); len &= ~0xF; while (len > 0) { #if SHARKSSL_UNALIGNED_ACCESS ((__sharkssl_packed U32*)enablehazard)[0] = ((__sharkssl_packed U32*)updatecause)[0] ^ ((__sharkssl_packed U32*)q)[0]; ((__sharkssl_packed U32*)enablehazard)[1] = ((__sharkssl_packed U32*)updatecause)[1] ^ ((__sharkssl_packed U32*)q)[1]; ((__sharkssl_packed U32*)enablehazard)[2] = ((__sharkssl_packed U32*)updatecause)[2] ^ ((__sharkssl_packed U32*)q)[2]; ((__sharkssl_packed U32*)enablehazard)[3] = ((__sharkssl_packed U32*)updatecause)[3] ^ ((__sharkssl_packed U32*)q)[3]; #else enablehazard[0] = (U8)(updatecause[0] ^ q[0]); enablehazard[1] = (U8)(updatecause[1] ^ q[1]); enablehazard[2] = (U8)(updatecause[2] ^ q[2]); enablehazard[3] = (U8)(updatecause[3] ^ q[3]); enablehazard[4] = (U8)(updatecause[4] ^ q[4]); enablehazard[5] = (U8)(updatecause[5] ^ q[5]); enablehazard[6] = (U8)(updatecause[6] ^ q[6]); enablehazard[7] = (U8)(updatecause[7] ^ q[7]); enablehazard[8] = (U8)(updatecause[8] ^ q[8]); enablehazard[9] = (U8)(updatecause[9] ^ q[9]); enablehazard[10] = (U8)(updatecause[10] ^ q[10]); enablehazard[11] = (U8)(updatecause[11] ^ q[11]); enablehazard[12] = (U8)(updatecause[12] ^ q[12]); enablehazard[13] = (U8)(updatecause[13] ^ q[13]); enablehazard[14] = (U8)(updatecause[14] ^ q[14]); enablehazard[15] = (U8)(updatecause[15] ^ q[15]); #endif SharkSslAesCtx_encrypt(registermcasp, enablehazard, enablehazard); q = enablehazard; updatecause += 16; enablehazard += 16; len -= 16; } memcpy(vect, q, 16); } SHARKSSL_API void SharkSslAesCtx_cbc_decrypt(SharkSslAesCtx *registermcasp, U8 vect[16], const U8 *updatecause, U8 *enablehazard, U32 len) { U8 rememberstate[16]; const U8 *q; rememberstate[0]=0; baAssert(registermcasp); baAssert(updatecause); baAssert(enablehazard); baAssert((len & 0x0F) == 0); len &= ~0xF; if (0 == len) { return; } enablehazard += (len - 16); updatecause += (len - 16); if (vect) { memcpy(rememberstate, updatecause, 16); } while (len > 0) { len -= 16; if (len) { q = updatecause - 16; } else if (vect) { q = vect; } else { return; } SharkSslAesCtx_decrypt(registermcasp, updatecause, enablehazard); updatecause = q; #if SHARKSSL_UNALIGNED_ACCESS ((__sharkssl_packed U32*)enablehazard)[0] ^= ((__sharkssl_packed U32*)q)[0]; ((__sharkssl_packed U32*)enablehazard)[1] ^= ((__sharkssl_packed U32*)q)[1]; ((__sharkssl_packed U32*)enablehazard)[2] ^= ((__sharkssl_packed U32*)q)[2]; ((__sharkssl_packed U32*)enablehazard)[3] ^= ((__sharkssl_packed U32*)q)[3]; #else enablehazard[0] ^= q[0]; enablehazard[1] ^= q[1]; enablehazard[2] ^= q[2]; enablehazard[3] ^= q[3]; enablehazard[4] ^= q[4]; enablehazard[5] ^= q[5]; enablehazard[6] ^= q[6]; enablehazard[7] ^= q[7]; enablehazard[8] ^= q[8]; enablehazard[9] ^= q[9]; enablehazard[10] ^= q[10]; enablehazard[11] ^= q[11]; enablehazard[12] ^= q[12]; enablehazard[13] ^= q[13]; enablehazard[14] ^= q[14]; enablehazard[15] ^= q[15]; #endif enablehazard -= 16; } baAssert(vect); memcpy(vect, rememberstate, 16); } #endif #if (SHARKSSL_ENABLE_AES_CTR_MODE) SHARKSSL_API void SharkSslAesCtx_ctr_mode(SharkSslAesCtx *registermcasp, U8 ctr[16], const U8 *updatecause, U8 *enablehazard, U32 len) { U8 sossirecalc[16], k; baAssert(registermcasp); baAssert(ctr); baAssert(updatecause); baAssert(enablehazard); baAssert((len & 0x0F) == 0); len >>= 4; while (len--) { k = 0; #if (defined(B_LITTLE_ENDIAN) && SHARKSSL_UNALIGNED_ACCESS) while ((k < 4) && (0 == ++((__sharkssl_packed U32*)ctr)[k])) #else while ((k < 16) && (0 == ++ctr[k])) #endif { k++; } SharkSslAesCtx_encrypt(registermcasp, ctr, sossirecalc); #if SHARKSSL_UNALIGNED_ACCESS ((__sharkssl_packed U32*)enablehazard)[0] = ((__sharkssl_packed U32*)updatecause)[0] ^ ((U32*)sossirecalc)[0]; ((__sharkssl_packed U32*)enablehazard)[1] = ((__sharkssl_packed U32*)updatecause)[1] ^ ((U32*)sossirecalc)[1]; ((__sharkssl_packed U32*)enablehazard)[2] = ((__sharkssl_packed U32*)updatecause)[2] ^ ((U32*)sossirecalc)[2]; ((__sharkssl_packed U32*)enablehazard)[3] = ((__sharkssl_packed U32*)updatecause)[3] ^ ((U32*)sossirecalc)[3]; #else enablehazard[0] = (U8)(updatecause[0] ^ sossirecalc[0]); enablehazard[1] = (U8)(updatecause[1] ^ sossirecalc[1]); enablehazard[2] = (U8)(updatecause[2] ^ sossirecalc[2]); enablehazard[3] = (U8)(updatecause[3] ^ sossirecalc[3]); enablehazard[4] = (U8)(updatecause[4] ^ sossirecalc[4]); enablehazard[5] = (U8)(updatecause[5] ^ sossirecalc[5]); enablehazard[6] = (U8)(updatecause[6] ^ sossirecalc[6]); enablehazard[7] = (U8)(updatecause[7] ^ sossirecalc[7]); enablehazard[8] = (U8)(updatecause[8] ^ sossirecalc[8]); enablehazard[9] = (U8)(updatecause[9] ^ sossirecalc[9]); enablehazard[10] = (U8)(updatecause[10] ^ sossirecalc[10]); enablehazard[11] = (U8)(updatecause[11] ^ sossirecalc[11]); enablehazard[12] = (U8)(updatecause[12] ^ sossirecalc[12]); enablehazard[13] = (U8)(updatecause[13] ^ sossirecalc[13]); enablehazard[14] = (U8)(updatecause[14] ^ sossirecalc[14]); enablehazard[15] = (U8)(updatecause[15] ^ sossirecalc[15]); #endif updatecause += 16; enablehazard += 16; } } #endif #if (SHARKSSL_ENABLE_AES_GCM || SHARKSSL_ENABLE_AES_CCM) #define ntosd2nandflash(r, a, b, l) do { \ register U16 debugstate = (U16)l; \ while (debugstate--) (r)[debugstate] = (a)[debugstate] ^ (b)[debugstate]; \ } while (0) #if SHARKSSL_UNALIGNED_ACCESS #define paz00wifikill(r, a, b) do { \ ((__sharkssl_packed U32*)(r))[0] = ((__sharkssl_packed U32*)(a))[0] ^ ((__sharkssl_packed U32*)(b))[0]; \ ((__sharkssl_packed U32*)(r))[1] = ((__sharkssl_packed U32*)(a))[1] ^ ((__sharkssl_packed U32*)(b))[1]; \ ((__sharkssl_packed U32*)(r))[2] = ((__sharkssl_packed U32*)(a))[2] ^ ((__sharkssl_packed U32*)(b))[2]; \ ((__sharkssl_packed U32*)(r))[3] = ((__sharkssl_packed U32*)(a))[3] ^ ((__sharkssl_packed U32*)(b))[3]; \ } while (0) #else #define paz00wifikill(r, a, b) ntosd2nandflash(r, a, b, 16) #endif #endif #if SHARKSSL_ENABLE_AES_GCM static const U16 serialsetup[16] = { 0x0000, 0x1C20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0, 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0 }; static void machinecheck(U8 *X) { U32 Z[4]; U8 b; #if ((!defined(B_LITTLE_ENDIAN)) && (!defined(B_BIG_ENDIAN))) if (0x20 == (*(U8*)&serialsetup[1])) #endif #ifndef B_BIG_ENDIAN { cleanupcount(Z[0], X, 0); cleanupcount(Z[1], X, 4); cleanupcount(Z[2], X, 8); cleanupcount(Z[3], X, 12); } #endif #if ((!defined(B_LITTLE_ENDIAN)) && (!defined(B_BIG_ENDIAN))) else #endif #ifndef B_LITTLE_ENDIAN { read64uint32(Z[0], X, 0); read64uint32(Z[1], X, 4); read64uint32(Z[2], X, 8); read64uint32(Z[3], X, 12); } #endif b = (U8)(Z[3] & 0x01); Z[3] >>= 1; if (Z[2] & 0x00000001) { Z[3] |= 0x80000000; } Z[2] >>= 1; if (Z[1] & 0x00000001) { Z[2] |= 0x80000000; } Z[1] >>= 1; if (Z[0] & 0x00000001) { Z[1] |= 0x80000000; } Z[0] >>= 1; if (b) { Z[0] ^= 0xE1000000; } #if ((!defined(B_LITTLE_ENDIAN)) && (!defined(B_BIG_ENDIAN))) if (0x20 == (*(U8*)&serialsetup[1])) #endif #ifndef B_BIG_ENDIAN { hsotgpdata(Z[0], X, 0); hsotgpdata(Z[1], X, 4); hsotgpdata(Z[2], X, 8); hsotgpdata(Z[3], X, 12); } #endif #if ((!defined(B_LITTLE_ENDIAN)) && (!defined(B_BIG_ENDIAN))) else #endif #ifndef B_LITTLE_ENDIAN { inputlevel(Z[0], X, 0); inputlevel(Z[1], X, 4); inputlevel(Z[2], X, 8); inputlevel(Z[3], X, 12); } #endif } static void pcibiossetup(SharkSslAesGcmCtx *aes) { U8 (*m)[16] = aes->M0; #if 0 U8 i, j; #endif memset(m[0], 0, 16); memset(m[8], 0, 16); SharkSslAesCtx_encrypt((SharkSslAesCtx*)aes, m[8], m[8]); #ifndef B_BIG_ENDIAN #ifndef B_LITTLE_ENDIAN if (0x20 == (*(U8*)&serialsetup[1])) #endif { U32 t; cleanupcount(t, (U8*)(&m[8]), 0); inputlevel(t, m[8], 0); cleanupcount(t, (U8*)(&m[8]), 4); inputlevel(t, m[8], 4); cleanupcount(t, (U8*)(&m[8]), 8); inputlevel(t, m[8], 8); cleanupcount(t, (U8*)(&m[8]), 12); inputlevel(t, m[8], 12); } #endif memcpy(m[4], m[8], 16); machinecheck(m[4]); memcpy(m[2], m[4], 16); machinecheck(m[2]); memcpy(m[1], m[2], 16); machinecheck(m[1]); #if 1 memcpy(m[3], m[2], 16); memcpy(m[5], m[4], 16); memcpy(m[6], m[4], 16); memcpy(m[7], m[4], 16); memcpy(m[9], m[8], 16); memcpy(m[10], m[8], 16); memcpy(m[11], m[8], 16); memcpy(m[12], m[8], 16); memcpy(m[13], m[8], 16); memcpy(m[14], m[8], 16); memcpy(m[15], m[8], 16); paz00wifikill(m[3], m[3], m[1]); paz00wifikill(m[5], m[5], m[1]); paz00wifikill(m[6], m[6], m[2]); paz00wifikill(m[7], m[7], m[3]); paz00wifikill(m[9], m[9], m[1]); paz00wifikill(m[10], m[10], m[2]); paz00wifikill(m[11], m[11], m[3]); paz00wifikill(m[12], m[12], m[4]); paz00wifikill(m[13], m[13], m[5]); paz00wifikill(m[14], m[14], m[6]); paz00wifikill(m[15], m[15], m[7]); #else for (i = 2; i <= 8; i <<= 1) { for (j = 1; j < i; j++) { memcpy(m[i+j], m[i], 16); paz00wifikill(m[i+j], m[i+j], m[j]); } } #endif } #define simplebuffer(c,x) audioplatdata(c->M0, x) static void audioplatdata(U8 (*M0)[16], U8 *x) { U32 Z[4]; U8 i, a; Z[0] = Z[1] = Z[2] = Z[3] = 0; for (i = 15; ; i--) { paz00wifikill((U8*)&Z[0], (U8*)&Z[0], M0[x[i]&0xF]); a = (U8)(Z[3] & 0xF); Z[3] = (Z[3] >> 4) | (Z[2] << 28); Z[2] = (Z[2] >> 4) | (Z[1] << 28); Z[1] = (Z[1] >> 4) | (Z[0] << 28); Z[0] >>= 4; Z[0] ^= ((U32)serialsetup[a]) << 16; paz00wifikill((U8*)&Z[0], (U8*)&Z[0], M0[x[i]>>4]); if (i == 0) break; a = (U8)(Z[3] & 0xF); Z[3] = (Z[3] >> 4) | (Z[2] << 28); Z[2] = (Z[2] >> 4) | (Z[1] << 28); Z[1] = (Z[1] >> 4) | (Z[0] << 28); Z[0] >>= 4; Z[0] ^= ((U32)serialsetup[a]) << 16; } inputlevel(Z[0], x, 0); inputlevel(Z[1], x, 4); inputlevel(Z[2], x, 8); inputlevel(Z[3], x, 12); } SHARKSSL_API void SharkSslAesGcmCtx_constructor(SharkSslAesGcmCtx *registermcasp, const U8 *sourcerouting, U8 creategroup) { SharkSslAesCtx_constructor((SharkSslAesCtx*)registermcasp, SharkSslAesCtx_Encrypt, sourcerouting, creategroup); pcibiossetup(registermcasp); } static int pcmciaregister(SharkSslAesGcmCtx *registermcasp, const U8 vect[12], U8 tag[16], const U8 *pmuv3event, U16 authlen, const U8 *updatecause, U8 *enablehazard, U32 len, SharkSslAesCtx_Type rightsvalid) { U8 remapiospace[16], sossirecalc[16], tagi[16]; U32 alen, pxafbmodes; baAssert(registermcasp); baAssert(vect); baAssert(tag); baAssert(updatecause); baAssert(enablehazard); alen = ((U32)authlen << 3); pxafbmodes = ((U32)len << 3); memset(&tagi[0], 0, 16); if (pmuv3event) { while (authlen) { if (authlen >= 16) { paz00wifikill(tagi, tagi, pmuv3event); pmuv3event += 16; authlen -= 16; } else { ntosd2nandflash(tagi, tagi, pmuv3event, authlen); authlen = 0; } simplebuffer(registermcasp, tagi); } } memcpy(&remapiospace[0], vect, 12); inputlevel(1, remapiospace, 12); while (len) { U32 requestflags; read64uint32(requestflags, remapiospace, 12); requestflags++; inputlevel(requestflags, remapiospace, 12); SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, remapiospace, sossirecalc); if (len >= 16) { if (SharkSslAesCtx_Encrypt == rightsvalid) { paz00wifikill(enablehazard, updatecause, sossirecalc); paz00wifikill(tagi, tagi, enablehazard); } else { paz00wifikill(tagi, tagi, updatecause); paz00wifikill(enablehazard, updatecause, sossirecalc); } updatecause += 16; enablehazard += 16; len -= 16; } else { if (SharkSslAesCtx_Encrypt == rightsvalid) { ntosd2nandflash(enablehazard, updatecause, sossirecalc, len); ntosd2nandflash(tagi, tagi, enablehazard, len); } else { ntosd2nandflash(tagi, tagi, updatecause, len); ntosd2nandflash(enablehazard, updatecause, sossirecalc, len); } len = 0; } simplebuffer(registermcasp, tagi); } inputlevel(0, sossirecalc, 0); inputlevel(alen, sossirecalc, 4); inputlevel(0, sossirecalc, 8); inputlevel(pxafbmodes, sossirecalc, 12); paz00wifikill(tagi, tagi, sossirecalc); simplebuffer(registermcasp, tagi); inputlevel(1, remapiospace, 12); SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, remapiospace, sossirecalc); if (SharkSslAesCtx_Encrypt == rightsvalid) { paz00wifikill(tag, tagi, sossirecalc); } else { paz00wifikill(tagi, tagi, sossirecalc); return sharkssl_kmemcmp(tagi, tag, 16); } return 0; } SHARKSSL_API int SharkSslAesGcmCtx_encrypt(SharkSslAesGcmCtx *registermcasp, const U8 vect[12], U8 panickernel[16], const U8 *pmuv3event, U16 authlen, const U8 *updatecause, U8 *enablehazard, U32 len) { return pcmciaregister(registermcasp, vect, panickernel, pmuv3event, authlen, updatecause, enablehazard, len, SharkSslAesCtx_Encrypt); } SHARKSSL_API int SharkSslAesGcmCtx_decrypt(SharkSslAesGcmCtx *registermcasp, const U8 vect[12], U8 directionoutput[16], const U8 *pmuv3event, U16 authlen, U8 *updatecause, U8 *enablehazard, U32 len) { return pcmciaregister(registermcasp, vect, directionoutput, pmuv3event, authlen, updatecause, enablehazard, len, SharkSslAesCtx_Decrypt); } #endif #if SHARKSSL_ENABLE_AES_CCM SHARKSSL_API void SharkSslAesCcmCtx_constructor(SharkSslAesCcmCtx *registermcasp, const U8 *sourcerouting, U8 creategroup, U8 requestarray) { SharkSslAesCtx_constructor((SharkSslAesCtx*)registermcasp, SharkSslAesCtx_Encrypt, sourcerouting, creategroup); baAssert((requestarray == 8) || (requestarray == 16)); registermcasp->tagLen = requestarray; } #ifndef SHARKSSL_ENABLE_CCM_AUTH_ALL #define SHARKSSL_ENABLE_CCM_AUTH_ALL 0 #endif static int modifyparam(SharkSslAesCcmCtx *registermcasp, const U8 vect[12], U8 *tag, const U8 *pmuv3event, U16 authlen, const U8 *updatecause, U8 *enablehazard, U32 len, SharkSslAesCtx_Type rightsvalid) { U8 remapiospace[16], sossirecalc[16], tagi[16]; baAssert(registermcasp); baAssert(vect); baAssert(tag); baAssert(updatecause); baAssert(enablehazard); inputlevel((U32)len, remapiospace, 12); memcpy(&remapiospace[1], vect, 12); remapiospace[0] = (8 * ((registermcasp->tagLen >> 1) - 1)) + (3 - 1); if ((pmuv3event) && (authlen)) { remapiospace[0] += 64; SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, remapiospace, tagi); baAssert(authlen < 0xFEFF); remapiospace[0] = (U8)((authlen >> 8) & 0xFF); remapiospace[1] = (U8)(authlen & 0xFF); #if SHARKSSL_ENABLE_CCM_AUTH_ALL if (authlen < 15) #else baAssert(authlen < 15); #endif { memcpy(&remapiospace[2], pmuv3event, authlen); memset(&remapiospace[2 + authlen], 0, 14 - authlen); } #if SHARKSSL_ENABLE_CCM_AUTH_ALL else { memcpy(&remapiospace[2], pmuv3event, 14); pmuv3event += 14; authlen -= 14; } #endif paz00wifikill(tagi, tagi, remapiospace); SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, tagi, tagi); #if SHARKSSL_ENABLE_CCM_AUTH_ALL while (authlen) { if (authlen >= 16) { paz00wifikill(tagi, tagi, pmuv3event); pmuv3event += 16; authlen -= 16; } else { ntosd2nandflash(tagi, tagi, pmuv3event, authlen); authlen = 0; } SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, tagi, tagi); } #endif } inputlevel(0, remapiospace, 12); memcpy(&remapiospace[1], vect, 12); remapiospace[0] = (3 - 1); while (len) { U32 requestflags; read64uint32(requestflags, remapiospace, 12); requestflags++; inputlevel(requestflags, remapiospace, 12); SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, remapiospace, sossirecalc); if (len >= 16) { if (SharkSslAesCtx_Encrypt == rightsvalid) { paz00wifikill(tagi, tagi, updatecause); paz00wifikill(enablehazard, updatecause, sossirecalc); } else { paz00wifikill(enablehazard, updatecause, sossirecalc); paz00wifikill(tagi, tagi, enablehazard); } updatecause += 16; enablehazard += 16; len -= 16; } else { if (SharkSslAesCtx_Encrypt == rightsvalid) { ntosd2nandflash(tagi, tagi, updatecause, len); ntosd2nandflash(enablehazard, updatecause, sossirecalc, len); } else { ntosd2nandflash(enablehazard, updatecause, sossirecalc, len); ntosd2nandflash(tagi, tagi, enablehazard, len); } len = 0; } SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, tagi, tagi); } remapiospace[13] = remapiospace[14] = remapiospace[15] = 0; SharkSslAesCtx_encrypt((SharkSslAesCtx*)registermcasp, remapiospace, sossirecalc); if (SharkSslAesCtx_Encrypt == rightsvalid) { ntosd2nandflash(tag, tagi, sossirecalc, registermcasp->tagLen); } else { paz00wifikill(tagi, tagi, sossirecalc); return sharkssl_kmemcmp(tagi, tag, registermcasp->tagLen); } return 0; } SHARKSSL_API int SharkSslAesCcmCtx_encrypt(SharkSslAesCcmCtx *registermcasp, const U8 vect[12], U8 *panickernel, const U8 *pmuv3event, U16 authlen, const U8 *updatecause, U8 *enablehazard, U32 len) { return modifyparam(registermcasp, vect, panickernel, pmuv3event, authlen, updatecause, enablehazard, len, SharkSslAesCtx_Encrypt); } SHARKSSL_API int SharkSslAesCcmCtx_decrypt(SharkSslAesCcmCtx *registermcasp, const U8 vect[12], U8 *directionoutput, const U8 *pmuv3event, U16 authlen, const U8 *updatecause, U8 *enablehazard, U32 len) { return modifyparam(registermcasp, vect, directionoutput, pmuv3event, authlen, updatecause, enablehazard, len, SharkSslAesCtx_Decrypt); } #endif #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include typedef struct { U16 nsp; /* Namespace prefix */ U16 ns; /* Full namespace name */ U16 sl; /* Scoping level */ U16 next; /* Next element. We store Xmlns instances as a linked list */ } Xmlns; typedef enum { SXmlNodeT_EOF, SXmlNodeT_StartTag, SXmlNodeT_EndTag, SXmlNodeT_StartSecondTag, SXmlNodeT_EndAtomicTag, SXmlNodeT_StartProcTag, SXmlNodeT_EndProcTag, SXmlNodeT_StartCData } SXmlNodeT; #define SXmlRoot_exception(o, err) SlException_set(o->ex, err) #define SXmlRoot_assert(o, expr, err) SlException_assertE(o->ex, expr, err) static void unregisterdriver(SXmlRoot* o, U16 icachealiases) { if((o->xmlElemBufNextPos + icachealiases) >= o->xmlElemBufSize) { size_t ahashsetkey; U8* faulthandler; icachealiases = o->xmlElemBufSize/4 > icachealiases*4 ? o->xmlElemBufSize/4 : icachealiases*4; ahashsetkey = o->xmlElemBufSize+icachealiases; faulthandler = o->xmlElemBuf ? AllocatorIntf_realloc(o->alloc, o->xmlElemBuf, &ahashsetkey) : AllocatorIntf_malloc(o->alloc, &ahashsetkey); SXmlRoot_assert(o, faulthandler, SXmlErrT_Mem); o->xmlElemBuf = faulthandler; o->xmlElemBufSize = (U16)ahashsetkey; } } static U16 controlassert(SXmlRoot* o, U16 nsp) { const char* triggerregister = SXmlRoot_dOffs2Str(o, nsp); U16 pos = o->xmlnsPos; while(pos) { Xmlns* xmlns = SXmlRoot_eOffs2Xmlns(o, pos); if(xmlns->nsp) { const char* asramplatdata = SXmlRoot_dOffs2Str(o, xmlns->nsp); if(*triggerregister == *asramplatdata && !strcmp(triggerregister, asramplatdata)) return xmlns->ns; } pos = xmlns->next; } SXmlRoot_exception(o, SXmlErrT_NsNotFound); return 0; } static U16 async3pdata(SXmlRoot* o) { U16 pos = o->xmlnsPos; while(pos) { Xmlns* xmlns = SXmlRoot_eOffs2Xmlns(o, pos); if(xmlns->nsp==0) return xmlns->ns; pos = xmlns->next; } return 0; } static BaBool flashdevice(SXmlRoot* o, U16 nsp, U16 gpio1config, U16 val) { U16 pos; if(nsp) pos = nsp; else pos=gpio1config; if( ! strcmp(SXmlRoot_dOffs2Str(o, pos), "\170\155\154\156\163") ) { Xmlns* xmlns; SXmlNsNode* xmlnsNode; if(o->xmlnsFreeList) { xmlns = SXmlRoot_eOffs2Xmlns(o, o->xmlnsFreeList); o->xmlnsFreeList = xmlns->next; } else { unregisterdriver(o, sizeof(Xmlns)); xmlns = SXmlRoot_eOffs2Xmlns(o,o->xmlElemBufNextPos); o->xmlElemBufNextPos+=sizeof(Xmlns); } xmlns->nsp= nsp ? gpio1config : 0; xmlns->ns=val; xmlns->next=0; xmlns->sl=o->csl; xmlns->next = o->xmlnsPos; o->xmlnsPos = SXmlRoot_ePtr2Offs(o, xmlns); unregisterdriver(o, sizeof(SXmlNsNode)); xmlnsNode = SXmlRoot_eOffs2SXmlNsNode(o,o->xmlElemBufNextPos); xmlnsNode->ns = xmlns->ns; xmlnsNode->next=o->xmlnsNodePos; o->xmlnsNodePos = o->xmlElemBufNextPos; o->xmlElemBufNextPos+=sizeof(SXmlNsNode); return TRUE; } return FALSE; } static void ftracegraph(SXmlRoot* o) { while(o->xmlnsPos) { U16 contextoffset; Xmlns* xmlns = SXmlRoot_eOffs2Xmlns(o, o->xmlnsPos); if(o->csl != xmlns->sl) return; contextoffset = xmlns->next; xmlns->next = o->xmlnsFreeList; o->xmlnsFreeList = o->xmlnsPos; o->xmlnsPos=contextoffset; } } static SXmlNode* SXmlRoot_createSXmlNode(SXmlRoot* o, U16 unusableexits) { SXmlNode* ducaticlkdm; U16 icachealiases = sizeof(SXmlNode) + sizeof(U16)*3*unusableexits; unregisterdriver(o, icachealiases); ducaticlkdm = SXmlRoot_eOffs2Elem(o,o->xmlElemBufNextPos); o->xmlElemBufNextPos+=icachealiases; memset(ducaticlkdm, 0, sizeof(SXmlNode)); ducaticlkdm->attributes[0]=unusableexits; return ducaticlkdm; } static U16 capabilitiesfinalized(SXmlRoot* o, U16 pos) { while(pos < o->dataSize) { switch(o->xmlData[pos]) { case '\012': o->line++; case '\040': case '\011': case '\014': case '\015': pos++; continue; default: return pos; } } return pos; } #define SXmlRoot_eatWhitespace2(o) \ o->parserPos = capabilitiesfinalized(o, o->parserPos) static U16 constcycles(SXmlRoot* o, U16 pos) { while(pos < o->dataSize) { switch(o->xmlData[pos]) { case '\012': o->line++; case '\040': case '\011': case '\014': case '\015': case 0: return pos; default: pos++; } } SXmlRoot_exception(o, SXmlErrT_EOF); return 0; } static void blocksuspend(SXmlRoot* o) { while(o->parserPos < o->dataSize) { if(o->xmlData[o->parserPos] == '\135') { if((o->parserPos+2) >= o->dataSize) break; if( ! memcmp(o->xmlData+o->parserPos+1, "\135\076", 2) ) { o->parserPos+=3; return; } } else if(o->xmlData[o->parserPos]=='\012') o->line++; o->parserPos++; } SXmlRoot_exception(o, SXmlErrT_Lex); } static U16 registerclient(SXmlRoot* o, U16 pos, U8 ch) { while(o->xmlData[pos]) { if(o->xmlData[pos]== ch) return pos; else if(o->xmlData[pos]=='\012') o->line++; pos++; } return 0; } static U16 blockcontents(SXmlRoot* o, U16 sep, U16* nsp, U16* gpio1config) { U16 pos, prctlenable; prctlenable = constcycles(o, sep); o->xmlData[prctlenable++] = 0; pos = registerclient(o, sep, '\072'); if(pos) { o->xmlData[pos++] = 0; *nsp=sep; *gpio1config=pos; } else { *nsp=0; *gpio1config=sep; } return prctlenable; } static SXmlNode* SXmlRoot_mkAttr(SXmlRoot* o, U16 sep, U16 unusableexits) { L_start: if(sep < o->endTagPos) sep = capabilitiesfinalized(o, sep); if(o->xmlData[sep] && sep < o->endTagPos) { SXmlNode* ducaticlkdm; U16 nsp, gpio1config, val; val = registerclient(o, sep, '\075'); SXmlRoot_assert(o, val, SXmlErrT_Lex); o->xmlData[val++]=0; blockcontents(o, sep, &nsp, &gpio1config); val = capabilitiesfinalized(o,val); if(o->xmlData[val] == '\047' || o->xmlData[val] == '\042') { sep=val+1; for(;;) { sep = registerclient(o, sep, o->xmlData[val]); SXmlRoot_assert(o, sep, SXmlErrT_Lex); if(o->xmlData[sep-1] != '\134') { o->xmlData[sep++] = 0; break; } } val++; } else { sep = constcycles(o, sep); if(o->xmlData[sep]) o->xmlData[sep++] = 0; } if(flashdevice(o, nsp, gpio1config, val)) goto L_start; ducaticlkdm = SXmlRoot_mkAttr(o, sep, (U16)(unusableexits+1)); ducaticlkdm->attributes[1+(3*unusableexits)] = nsp ? controlassert(o, nsp) : async3pdata(o); ducaticlkdm->attributes[2+(3*unusableexits)] = gpio1config; ducaticlkdm->attributes[3+(3*unusableexits)] = val; return ducaticlkdm; } return SXmlRoot_createSXmlNode(o, unusableexits); } static SXmlNodeT syscallentry(SXmlRoot* o) { read_L: SXmlRoot_eatWhitespace2(o); if(o->xmlData[o->parserPos] == '\074') { o->parserPos++; SXmlRoot_eatWhitespace2(o); switch(o->xmlData[o->parserPos]) { case '\077': o->parserPos++; return SXmlNodeT_StartProcTag; case '\057': o->parserPos++; return SXmlNodeT_StartSecondTag; case '\041': if((o->parserPos+10) < o->dataSize && ! memcmp(o->xmlData+o->parserPos+1, "\133\103\104\101\124\101\133", 7) ) { o->parserPos+=8; return SXmlNodeT_StartCData; } if((o->parserPos+6) < o->dataSize && ! memcmp(o->xmlData+o->parserPos+1, "\055\055", 2) ) { o->parserPos+=3; while((o->parserPos+2) < o->dataSize) { if(o->xmlData[o->parserPos] == '\055' && o->xmlData[o->parserPos+1] == '\055' && o->xmlData[o->parserPos+2] == '\076') { o->parserPos+=3; break; } o->parserPos++; } if((o->parserPos+2) == o->dataSize) SXmlRoot_exception(o, SXmlErrT_Lex); goto read_L; } return SXmlNodeT_StartTag; default: return SXmlNodeT_StartTag; } } SXmlRoot_exception(o, SXmlErrT_Lex); return (SXmlNodeT)0; } static SXmlNodeT timershould(SXmlRoot* o) { U16 pos; SXmlNodeT handlersetup; while(o->parserPos < o->dataSize) { switch(o->xmlData[o->parserPos]) { case '\076': o->endTagPos=o->parserPos; o->xmlData[o->parserPos++]=0; return SXmlNodeT_EndTag; case '\057': case '\077': handlersetup = o->xmlData[o->parserPos] == '\057' ? SXmlNodeT_EndAtomicTag : SXmlNodeT_EndProcTag; o->endTagPos=o->parserPos; pos = capabilitiesfinalized(o, (U16)(o->parserPos+1)); if(o->xmlData[pos] == '\076') { o->xmlData[o->parserPos]=0; o->parserPos=pos+1; return handlersetup; } break; } o->parserPos++; } SXmlRoot_exception(o, SXmlErrT_Lex); return (SXmlNodeT)0; } static SXmlNodeT setupstate(SXmlRoot* o, SXmlNode* ducaticlkdm) { U16 sep = capabilitiesfinalized(o, o->parserPos); if(o->xmlData[sep] != '\074') { SXmlNodeT et; more_L: sep = registerclient(o, sep, '\074'); SXmlRoot_assert(o, sep, SXmlErrT_Lex); ducaticlkdm->data=o->parserPos; o->parserPos=sep; et = syscallentry(o); if(et == SXmlNodeT_StartCData) { blocksuspend(o); sep = capabilitiesfinalized(o, o->parserPos); goto more_L; } o->xmlData[sep]=0; return et; } return syscallentry(o); } static SXmlNode* SXmlRoot_mkElem(SXmlRoot* o, U16 sep, SXmlNode* ducaticlkdm) { SXmlNode* nelem; U16 nsp; U16 gpio1config; sep = capabilitiesfinalized(o, sep); sep = blockcontents(o, sep, &nsp, &gpio1config); nelem = SXmlRoot_mkAttr(o, sep, 0); nelem->name = gpio1config; if(ducaticlkdm) ducaticlkdm->next = SXmlRoot_ePtr2Offs(o, nelem); nelem->ns = nsp ? controlassert(o, nsp) : async3pdata(o); return nelem; } static void allocgeneric(SXmlRoot* o, SXmlNode* ducaticlkdm) { U16 sep; U16 nsp, gpio1config; SXmlRoot_eatWhitespace2(o); sep = o->parserPos; if(timershould(o) != SXmlNodeT_EndTag) SXmlRoot_exception(o, SXmlErrT_Lex); blockcontents(o, sep, &nsp, &gpio1config); if(nsp && ducaticlkdm->ns) { if(controlassert(o, nsp) != ducaticlkdm->ns) SXmlRoot_exception(o, SXmlErrT_NsNotFound); } if(strcmp(SXmlRoot_dOffs2Str(o, gpio1config),SXmlRoot_dOffs2Str(o, ducaticlkdm->name))) SXmlRoot_exception(o, SXmlErrT_NameNotFound); } static SXmlNodeT devicealloc(SXmlRoot* o, SXmlNodeT t, U16 rm200enable) { SXmlNode* ducaticlkdm=0; U16 setupprocessor=0; o->csl++; while(o->parserPos < o->dataSize) { U16 sep = o->parserPos; if(t == SXmlNodeT_StartTag) { t = timershould(o); if(t == SXmlNodeT_EndTag || t == SXmlNodeT_EndAtomicTag) { setupprocessor++; if(ducaticlkdm) ducaticlkdm = SXmlRoot_mkElem(o, sep, ducaticlkdm); else { ducaticlkdm = SXmlRoot_mkElem(o, sep, 0); SXmlRoot_eOffs2Elem(o,rm200enable)->firstChild = SXmlRoot_ePtr2Offs(o, ducaticlkdm); } if(t == SXmlNodeT_EndTag) { t = setupstate(o, ducaticlkdm); if(t != SXmlNodeT_StartSecondTag) { t = devicealloc(o,t,SXmlRoot_ePtr2Offs(o,ducaticlkdm)); } if(t != SXmlNodeT_StartSecondTag) SXmlRoot_exception(o, SXmlErrT_ExpectedEndElem); allocgeneric(o, ducaticlkdm); } } else SXmlRoot_exception(o, SXmlErrT_Lex); } else if(t == SXmlNodeT_StartProcTag) { if(timershould(o) != SXmlNodeT_EndProcTag) SXmlRoot_exception(o, SXmlErrT_Lex); } else if(t == SXmlNodeT_StartCData) { if(SXmlRoot_eOffs2Elem(o,rm200enable)->data || ducaticlkdm) SXmlRoot_exception(o, SXmlErrT_Lex); SXmlRoot_eOffs2Elem(o,rm200enable)->data=sep; blocksuspend(o); o->xmlData[o->parserPos-3]=0; t = syscallentry(o); goto ret_L; } else if(t == SXmlNodeT_StartSecondTag) goto ret_L; else SXmlRoot_exception(o, SXmlErrT_Lex); SXmlRoot_eatWhitespace2(o); if(o->dataSize == o->parserPos) { t = SXmlNodeT_EOF; goto ret_L; } t = syscallentry(o); } ret_L: ftracegraph(o); o->csl--; SXmlRoot_eOffs2Elem(o,rm200enable)->childNodes=setupprocessor; return t; } static int clkopsfgenv1(SXmlRoot* o, U8* pwrdmrestore, U16 writeaction, U16 initmemdefault) { o->line =1; o->parserPos=0; o->xmlData=pwrdmrestore; o->dataSize=writeaction; o->xmlElemBufNextPos=0; o->xmlnsPos=0; o->csl=0; o->xmlnsFreeList=0; o->xmlnsNodePos=0; if(o->xmlElemBufSize < initmemdefault) { if(o->xmlElemBuf) { AllocatorIntf_free(o->alloc, o->xmlElemBuf); o->xmlElemBuf=0; } o->xmlElemBufSize=0; unregisterdriver(o, initmemdefault); } if(syscallentry(o) == SXmlNodeT_StartProcTag) { if(timershould(o) == SXmlNodeT_EndProcTag) { o->xmlElemBufNextPos+=sizeof(SXmlNode); if(devicealloc(o, syscallentry(o), 0) == SXmlNodeT_EOF) { baAssert(o->csl==0); return SXmlErrT_OK; } return SXmlErrT_ExpectedElement; } } return SXmlErrT_Lex; } void SXmlNode_unlinkChild(SXmlNode* o, SXmlNode* writeretired, SXmlRoot* r) { U16 n = SXmlRoot_ePtr2Offs(r, writeretired); if(o->firstChild == n) o->firstChild = writeretired->next; else { SXmlNode* instructioncounter = SXmlNode_firstChild(o,r); while(instructioncounter->next) { if(instructioncounter->next == n) { instructioncounter->next = writeretired->next; writeretired->next=0; return; } instructioncounter = SXmlNode_next(instructioncounter, r); } baAssert(0); } } void SlException_set(SlException* o, int err) { longjmp(o->buf, err); } int SXmlRoot_parse(SXmlRoot* o, U8* pwrdmrestore, U16 writeaction, U16 initmemdefault) { int sffsdrnandflash; SlException ex; o->ex = &ex; sffsdrnandflash = SlException_INIT(ex); if(sffsdrnandflash) return sffsdrnandflash; return clkopsfgenv1(o, pwrdmrestore, writeaction, initmemdefault); } void SXmlRoot_constructor(SXmlRoot* o, AllocatorIntf* unmapaliases) { memset(o,0,sizeof(SXmlRoot)); o->alloc=unmapaliases ? unmapaliases : AllocatorIntf_getDefault(); } void SXmlRoot_constructor2(SXmlRoot* o, AllocatorIntf* unmapaliases, U8* pwrdmrestore, U16 writeaction, U16 initmemdefault, SlException* ex) { int sffsdrnandflash; SXmlRoot_constructor(o, unmapaliases); o->ex = ex; sffsdrnandflash = clkopsfgenv1(o, pwrdmrestore, writeaction, initmemdefault); if(sffsdrnandflash) SXmlRoot_exception(o, sffsdrnandflash); } void SXmlRoot_destructor(SXmlRoot* o) { if(o->xmlElemBuf) AllocatorIntf_free(o->alloc, o->xmlElemBuf); } U16 SXmlRoot_childNodes(SXmlRoot* o) { return SXmlRoot_eOffs2Elem(o, 0)->childNodes; } SXmlNode* SXmlRoot_firstChild(SXmlRoot* o) { SXmlNode* mcasp0resources = SXmlRoot_eOffs2Elem(o, 0); return SXmlNode_firstChild(mcasp0resources, o); } SXmlNsNode* SXmlRoot_firstNsNode(SXmlRoot* o) { if(o->xmlnsNodePos) return SXmlRoot_eOffs2SXmlNsNode(o, o->xmlnsNodePos); return 0; } void SerializeSXml_constructor2(SerializeSXml* o, const char gpio27parents, BufPrint* bp, NsTree* nst) { o->bp=bp; o->nst = nst; o->nsprfx=gpio27parents; o->printNsAttrList=FALSE; } static void instructionhazard(SerializeSXml* o, SXmlNode* n, SXmlRoot* r) { U16 i; SXmlAttr a = SXmlNode_getAttr(n); int unusableexits = SXmlNode_getNoOfAttr(n); for(i = 0; i < unusableexits; i++) { unsigned int sha256store = o->nst ? NsTree_getNsId(o->nst, SXmlAttr_getNs(a,r,i)) : SXmlAttr_getNsId(a,i); if(sha256store) { BufPrint_printf(o->bp, "\040\045\143\045\170\072\045\163\075\042\045\163\042", o->nsprfx, sha256store, SXmlAttr_getName(a, r, i), SXmlAttr_getValue(a, r, i)); } else { BufPrint_printf(o->bp, "\040\045\163\075\042\045\163\042", SXmlAttr_getName(a, r, i), SXmlAttr_getValue(a, r, i)); } } } void SerializeSXml_printNode(SerializeSXml* o,SXmlNode* n,SXmlRoot* r, BaBool all) { do { unsigned int sha256store = o->nst ? NsTree_getNsId(o->nst, SXmlNode_getNs(n, r)) : SXmlNode_getNsId(n); if(sha256store) { BufPrint_printf(o->bp,"\074\045\143\045\170\072\045\163", o->nsprfx,sha256store,SXmlNode_getName(n,r)); if(o->printNsAttrList && o->nst) { NsTree_printNsAttrList(o->nst, o->nsprfx, o->bp); o->printNsAttrList = FALSE; } if(SXmlNode_getNoOfAttr(n)) instructionhazard(o, n, r); if(n->data || n->firstChild) { BufPrint_putc(o->bp, '\076'); if(n->data) BufPrint_write2(o->bp, SXmlNode_getData(n,r)); if(n->firstChild) { BufPrint_putc(o->bp, '\012'); SerializeSXml_printNode(o, SXmlNode_firstChild(n,r), r, TRUE); } BufPrint_printf(o->bp,"\074\057\045\143\045\170\072\045\163\076\012", o->nsprfx,sha256store,SXmlNode_getName(n,r)); } else BufPrint_write(o->bp, "\057\076\012", 3); } else { BufPrint_printf(o->bp, "\074\045\163", SXmlNode_getName(n, r)); if(o->printNsAttrList && o->nst) { NsTree_printNsAttrList(o->nst, o->nsprfx, o->bp); o->printNsAttrList = FALSE; } if(SXmlNode_getNoOfAttr(n)) instructionhazard(o, n, r); if(n->data || n->firstChild) { BufPrint_putc(o->bp, '\076'); if(n->data) BufPrint_write2(o->bp, SXmlNode_getData(n,r)); if(n->firstChild) { BufPrint_putc(o->bp, '\012'); SerializeSXml_printNode(o, SXmlNode_firstChild(n,r), r, TRUE); } BufPrint_printf(o->bp,"\074\057\045\163\076\012", SXmlNode_getName(n,r)); } else BufPrint_write(o->bp, "\057\076\012", 3); } n = SXmlNode_next(n, r); } while(n && all); } typedef struct { SplayTreeNode super; SingleLink slink; unsigned int nsId; } NsTreeNode; #define NsTreeNode_link2Node(l) \ (NsTreeNode*)((U8*)l-offsetof(NsTreeNode,slink)) SerializeSXml* NsTree_createSerializer(NsTree* o, const char gpio27parents, BufPrint* bp) { size_t icachealiases = sizeof(SerializeSXml); SerializeSXml* sp = (SerializeSXml*)AllocatorIntf_malloc(o->alloc, &icachealiases); SlException_assertE(o->ex, sp, IOINTF_MEM); SerializeSXml_constructor2(sp, gpio27parents, bp, o); return sp; } static int asyncimport(SplayTreeNode* n, SplayTreeKey k) { return strcmp((const char*)n->key, (const char*)k); } void NsTree_constructor(NsTree* o, AllocatorIntf* unmapaliases, SlException* ex) { SplayTree_constructor((SplayTree*)o, asyncimport); SingleList_constructor(&o->nsTreeNodeList); o->ex=ex; o->alloc=unmapaliases; o->nextNsId=0; } void NsTree_destructor(NsTree* o) { SplayTreeNode* n; while( (n = SplayTree_getRoot((SplayTree*)o)) != 0) { SplayTree_remove((SplayTree*)o, n); AllocatorIntf_free(o->alloc, n); } } static void sleepnolock(NsTree* o, const char* ns) { char* ptr; size_t icachealiases = sizeof(NsTreeNode)+strlen(ns)+1; NsTreeNode* ntn = (NsTreeNode*)AllocatorIntf_malloc(o->alloc, &icachealiases); SlException_assertE(o->ex, ntn, IOINTF_MEM); ptr = (char*)(ntn+1); strcpy(ptr, ns); SplayTreeNode_constructor((SplayTreeNode*)ntn, ptr); SplayTree_insert((SplayTree*)o,(SplayTreeNode*)ntn); SingleLink_constructor(&ntn->slink); SingleList_insertLast(&o->nsTreeNodeList, &ntn->slink); ntn->nsId=++o->nextNsId; } void NsTree_addAllNs(NsTree* o, SXmlNode* n, SXmlRoot* r) { while(n) { const char* ns = SXmlNode_getNs(n, r); if(*ns && ! SplayTree_find((SplayTree*)o, ns) ) { sleepnolock(o, ns); } if(n->firstChild) NsTree_addNs(o, SXmlNode_firstChild(n,r), r); n = SXmlNode_next(n, r); } } void NsTree_addNs(NsTree* o, SXmlNode* n, SXmlRoot* r) { if(n) { const char* ns = SXmlNode_getNs(n, r); if(*ns && ! SplayTree_find((SplayTree*)o, ns) ) { sleepnolock(o, ns); } if(n->firstChild) NsTree_addNs(o, SXmlNode_firstChild(n,r), r); } } unsigned int NsTree_getNsId(NsTree* o, const char* ns) { NsTreeNode* ntn = (NsTreeNode*)SplayTree_find((SplayTree*)o, ns); return ntn ? ntn->nsId : 0; } void NsTree_printNsAttrList(NsTree* o, const char gpio27parents, BufPrint* out) { SingleLink* link; SingleListEnumerator instructioncounter; SingleListEnumerator_constructor(&instructioncounter, &o->nsTreeNodeList); for(link = SingleListEnumerator_getElement(&instructioncounter) ; link ; link = SingleListEnumerator_nextElement(&instructioncounter)) { NsTreeNode* ntn = NsTreeNode_link2Node(link); BufPrint_printf(out, "\040\170\155\154\156\163\072\045\143\045\170\075\042\045\163\042", gpio27parents, ntn->nsId, ((SplayTreeNode*)ntn)->key); } } #ifndef BA_LIB #define BA_LIB #endif #include "SharkSslASN1.h" #include "SharkSslCrypto.h" #if SHARKSSL_USE_ECC #endif #include #ifndef EXT_SHARK_LIB #define sharkStrstr strstr #endif #define SHARKSSL_DIM_ARR(a) (sizeof(a)/sizeof(a[0])) #if SHARKSSL_USE_ECC #if SHARKSSL_ECC_USE_SECP521R1 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_SECP521R1_POINTLEN #elif SHARKSSL_ECC_USE_BRAINPOOLP512R1 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_BRAINPOOLP512R1_POINTLEN #elif SHARKSSL_ECC_USE_CURVE448 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_CURVE448_POINTLEN #elif SHARKSSL_ECC_USE_SECP384R1 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_SECP384R1_POINTLEN #elif SHARKSSL_ECC_USE_BRAINPOOLP384R1 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_BRAINPOOLP384R1_POINTLEN #elif SHARKSSL_ECC_USE_SECP256R1 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_SECP256R1_POINTLEN #elif SHARKSSL_ECC_USE_BRAINPOOLP256R1 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_BRAINPOOLP256R1_POINTLEN #elif SHARKSSL_ECC_USE_CURVE25519 #define SHARKSSL_MAX_ECC_POINTLEN SHARKSSL_CURVE25519_POINTLEN #else #define SHARKSSL_MAX_ECC_POINTLEN 0 #endif #endif #if (((SHARKSSL_SSL_CLIENT_CODE || SHARKSSL_SSL_SERVER_CODE) && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || \ (SHARKSSL_ENABLE_CERTSTORE_API) || (SHARKSSL_ENABLE_PEM_API)) #define ALGO_ID_UNKNOWN processsdccr #define ALGO_ID_SHA512 batterythread #define ALGO_ID_SHA384 probewrite #define ALGO_ID_SHA256 domainnumber #define ALGO_ID_SHA1 presentpages #define ALGO_ID_MD5 skciphercreate #define ALGO_ID_MD2 0x0F #define ALGO_ID_PKCS5_PBES2 0x9A #define ALGO_ID_PKCS5_PBKDF2 0x9B #define ALGO_ID_RSA_ENCRYPTION entryearly #define ALGO_ID_ECDSA accessactive #define ALGO_ID_HMAC 0x08 #define ALGO_ID_SHA512_WITH_RSA_ENCRYPTION ((ALGO_ID_RSA_ENCRYPTION << 4) | ALGO_ID_SHA512) #define ALGO_ID_SHA384_WITH_RSA_ENCRYPTION ((ALGO_ID_RSA_ENCRYPTION << 4) | ALGO_ID_SHA384) #define ALGO_ID_SHA256_WITH_RSA_ENCRYPTION ((ALGO_ID_RSA_ENCRYPTION << 4) | ALGO_ID_SHA256) #define ALGO_ID_SHA1_WITH_RSA_ENCRYPTION ((ALGO_ID_RSA_ENCRYPTION << 4) | ALGO_ID_SHA1) #define ALGO_ID_MD5_WITH_RSA_ENCRYPTION ((ALGO_ID_RSA_ENCRYPTION << 4) | ALGO_ID_MD5) #define ALGO_ID_MD2_WITH_RSA_ENCRYPTION ((ALGO_ID_RSA_ENCRYPTION << 4) | ALGO_ID_MD2) #define ALGO_ID_ECDSA_WITH_SHA512 ((ALGO_ID_ECDSA << 4) | ALGO_ID_SHA512) #define ALGO_ID_ECDSA_WITH_SHA384 ((ALGO_ID_ECDSA << 4) | ALGO_ID_SHA384) #define ALGO_ID_ECDSA_WITH_SHA256 ((ALGO_ID_ECDSA << 4) | ALGO_ID_SHA256) #define ALGO_ID_ECDSA_WITH_SHA1 ((ALGO_ID_ECDSA << 4) | ALGO_ID_SHA1) #define ALGO_ID_HMAC_WITH_SHA256 ((ALGO_ID_HMAC << 4) | ALGO_ID_SHA256) #define GET_ALGO_HASH_ID(id) (id & 0x0F) #define GET_ALGO_SIGNATURE_ID(id) ((id & 0xF0) >> 4) #define ALGO_ID_AES_128_CBC 0xE1 #define ALGO_ID_AES_256_CBC 0xE2 #define ALGO_ID_CHACHA20 0xE4 U8 SharkSslParseASN1_getAlgoID(const SharkSslParseASN1 *o) { switch (o->datalen) { case 9: #if SHARKSSL_ENABLE_RSA if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_rsaEncryption, SHARKSSL_DIM_ARR(sharkssl_oid_rsaEncryption))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_rsaEncryption)); return ALGO_ID_RSA_ENCRYPTION; } if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_md2withRSAEncryption, SHARKSSL_DIM_ARR(sharkssl_oid_md2withRSAEncryption))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_md2withRSAEncryption)); return ALGO_ID_MD2_WITH_RSA_ENCRYPTION; } #if SHARKSSL_USE_MD5 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_md5withRSAEncryption, SHARKSSL_DIM_ARR(sharkssl_oid_md5withRSAEncryption))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_md5withRSAEncryption)); return ALGO_ID_MD5_WITH_RSA_ENCRYPTION; } #endif if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha1withRSAEncryption, SHARKSSL_DIM_ARR(sharkssl_oid_sha1withRSAEncryption))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_sha1withRSAEncryption)); return ALGO_ID_SHA1_WITH_RSA_ENCRYPTION; } #if SHARKSSL_USE_SHA_256 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha256withRSAEncryption, SHARKSSL_DIM_ARR(sharkssl_oid_sha256withRSAEncryption))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_sha256withRSAEncryption)); return ALGO_ID_SHA256_WITH_RSA_ENCRYPTION; } #endif #if SHARKSSL_USE_SHA_384 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha384withRSAEncryption, SHARKSSL_DIM_ARR(sharkssl_oid_sha384withRSAEncryption))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_sha384withRSAEncryption)); return ALGO_ID_SHA384_WITH_RSA_ENCRYPTION; } #endif #if SHARKSSL_USE_SHA_512 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha512withRSAEncryption, SHARKSSL_DIM_ARR(sharkssl_oid_sha512withRSAEncryption))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_sha512withRSAEncryption)); return ALGO_ID_SHA512_WITH_RSA_ENCRYPTION; } #endif #endif #if SHARKSSL_USE_SHA_256 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha256, SHARKSSL_DIM_ARR(sharkssl_oid_sha256))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_sha256)); return ALGO_ID_SHA256; } #endif #if SHARKSSL_USE_SHA_384 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha384, SHARKSSL_DIM_ARR(sharkssl_oid_sha384))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_sha384)); return ALGO_ID_SHA384; } #endif #if SHARKSSL_USE_SHA_512 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha512, SHARKSSL_DIM_ARR(sharkssl_oid_sha512))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_sha512)); return ALGO_ID_SHA512; } #endif #if SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_pkcs5PBES2, SHARKSSL_DIM_ARR(sharkssl_oid_pkcs5PBES2))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_pkcs5PBES2)); return ALGO_ID_PKCS5_PBES2; } if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_pkcs5PBKDF2, SHARKSSL_DIM_ARR(sharkssl_oid_pkcs5PBKDF2))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_pkcs5PBKDF2)); return ALGO_ID_PKCS5_PBKDF2; } #if (SHARKSSL_USE_AES_128 && SHARKSSL_ENABLE_AES_CBC) if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_aes128cbc, SHARKSSL_DIM_ARR(sharkssl_oid_aes128cbc))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_aes128cbc)); return ALGO_ID_AES_128_CBC; } #endif #if (SHARKSSL_USE_AES_256 && SHARKSSL_ENABLE_AES_CBC) if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_aes256cbc, SHARKSSL_DIM_ARR(sharkssl_oid_aes256cbc))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_aes256cbc)); return ALGO_ID_AES_256_CBC; } #endif #endif break; case 8: #if SHARKSSL_USE_MD5 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_md5, SHARKSSL_DIM_ARR(sharkssl_oid_md5))) { baAssert(8 == SHARKSSL_DIM_ARR(sharkssl_oid_md5)); return ALGO_ID_MD5; } #endif #if SHARKSSL_ENABLE_ECDSA #if SHARKSSL_USE_SHA_256 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_ecdsaWithSHA256, SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA256))) { baAssert(8 == SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA256)); return ALGO_ID_ECDSA_WITH_SHA256; } #endif #if SHARKSSL_USE_SHA_384 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_ecdsaWithSHA384, SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA384))) { baAssert(8 == SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA384)); return ALGO_ID_ECDSA_WITH_SHA384; } #endif #if SHARKSSL_USE_SHA_512 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_ecdsaWithSHA512, SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA512))) { baAssert(8 == SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA512)); return ALGO_ID_ECDSA_WITH_SHA512; } #endif #endif #if SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT #if SHARKSSL_USE_SHA_256 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_HMACWithSHA256, SHARKSSL_DIM_ARR(sharkssl_oid_HMACWithSHA256))) { baAssert(8 == SHARKSSL_DIM_ARR(sharkssl_oid_HMACWithSHA256)); return ALGO_ID_HMAC_WITH_SHA256; } #endif #endif break; #if SHARKSSL_USE_ECC case 7: if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_ecPublicKey, SHARKSSL_DIM_ARR(sharkssl_oid_ecPublicKey))) { baAssert(7 == SHARKSSL_DIM_ARR(sharkssl_oid_ecPublicKey)); return ALGO_OID_EC_PUBLIC_KEY; } #if SHARKSSL_ENABLE_ECDSA #if SHARKSSL_USE_SHA1 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_ecdsaWithSHA1, SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA1))) { baAssert(7 == SHARKSSL_DIM_ARR(sharkssl_oid_ecdsaWithSHA1)); return ALGO_ID_ECDSA_WITH_SHA1; } #endif #endif break; #endif #if SHARKSSL_USE_SHA1 case 5: if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_sha1, SHARKSSL_DIM_ARR(sharkssl_oid_sha1))) { baAssert(5 == SHARKSSL_DIM_ARR(sharkssl_oid_sha1)); return ALGO_ID_SHA1; } break; #endif default: break; } return ALGO_ID_UNKNOWN; } #if SHARKSSL_USE_ECC U8 controllerregister(U16 defaultsdhci1) { switch (defaultsdhci1) { #if SHARKSSL_ECC_USE_SECP256R1 case SHARKSSL_EC_CURVE_ID_SECP256R1: return SHARKSSL_SECP256R1_POINTLEN; #endif #if SHARKSSL_ECC_USE_SECP384R1 case SHARKSSL_EC_CURVE_ID_SECP384R1: return SHARKSSL_SECP384R1_POINTLEN; #endif #if SHARKSSL_ECC_USE_SECP521R1 case SHARKSSL_EC_CURVE_ID_SECP521R1: return SHARKSSL_SECP521R1_POINTLEN; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP256R1: return SHARKSSL_BRAINPOOLP256R1_POINTLEN; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP384R1: return SHARKSSL_BRAINPOOLP384R1_POINTLEN; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP512R1: return SHARKSSL_BRAINPOOLP512R1_POINTLEN; #endif #if SHARKSSL_ECC_USE_CURVE25519 case SHARKSSL_EC_CURVE_ID_CURVE25519: return SHARKSSL_CURVE25519_POINTLEN; #endif #if SHARKSSL_ECC_USE_CURVE448 case SHARKSSL_EC_CURVE_ID_CURVE448: return SHARKSSL_CURVE448_POINTLEN; #endif default: break; } return 0; } U8 SharkSslParseASN1_getCurveID(const SharkSslParseASN1 *o) { switch (o->datalen) { case 5: #if SHARKSSL_ECC_USE_SECP384R1 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_secp384r1, SHARKSSL_DIM_ARR(sharkssl_oid_secp384r1))) { baAssert(5 == SHARKSSL_DIM_ARR(sharkssl_oid_secp384r1)); return SHARKSSL_EC_CURVE_ID_SECP384R1; } #endif #if SHARKSSL_ECC_USE_SECP521R1 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_secp521r1, SHARKSSL_DIM_ARR(sharkssl_oid_secp521r1))) { baAssert(5 == SHARKSSL_DIM_ARR(sharkssl_oid_secp521r1)); return SHARKSSL_EC_CURVE_ID_SECP521R1; } #endif break; case 8: #if SHARKSSL_ECC_USE_SECP256R1 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_prime256v1, SHARKSSL_DIM_ARR(sharkssl_oid_prime256v1))) { baAssert(8 == SHARKSSL_DIM_ARR(sharkssl_oid_prime256v1)); return SHARKSSL_EC_CURVE_ID_SECP256R1; } #endif break; case 9: #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_brainpoolP256r1, SHARKSSL_DIM_ARR(sharkssl_oid_brainpoolP256r1))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_brainpoolP256r1)); return SHARKSSL_EC_CURVE_ID_BRAINPOOLP256R1; } #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_brainpoolP384r1, SHARKSSL_DIM_ARR(sharkssl_oid_brainpoolP384r1))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_brainpoolP384r1)); return SHARKSSL_EC_CURVE_ID_BRAINPOOLP384R1; } #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 if (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_brainpoolP512r1, SHARKSSL_DIM_ARR(sharkssl_oid_brainpoolP512r1))) { baAssert(9 == SHARKSSL_DIM_ARR(sharkssl_oid_brainpoolP512r1)); return SHARKSSL_EC_CURVE_ID_BRAINPOOLP512R1; } #endif break; default: break; } return SHARKSSL_EC_CURVE_ID_UNKNOWN; } #endif #endif #if (((SHARKSSL_SSL_CLIENT_CODE || SHARKSSL_SSL_SERVER_CODE) && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || \ (SHARKSSL_ENABLE_CERTSTORE_API)) static int sha256final(SharkSslParseASN1 *o) { if (o->len < 1) { return -1; } o->datalen = 0; if (*(o->ptr) != 0xA0) { return 0; } o->ptr++; o->len--; if (SharkSslParseASN1_getLength(o) < 0) { return -1; } if ((SharkSslParseASN1_getInt(o) < 0) || (o->datalen > 4)) { return -1; } return 0; } static int deltacamera(SharkSslParseASN1 *o, SharkSslCertDN *dn) { U8 *end, attrib, rightsvalid; int l; if ((l = SharkSslParseASN1_getSequence(o)) < 0) { return -1; } end = o->ptr + l; memset(dn, 0, sizeof(SharkSslCertDN)); while (o->ptr < end) { SharkSslParseASN1_getSet(o); if ((SharkSslParseASN1_getSequence(o) < 0) || (o->ptr >= end) || (*(o->ptr++) != SHARKSSL_ASN1_OID) || ((l = SharkSslParseASN1_getLength(o)) < 0) || (o->len < 2)) { return -1; } o->len--; attrib = 0; if (*(o->ptr) != SHARKSSL_OID_JIIT_DS) { attrib = 1; if (*(o->ptr) == sharkssl_oid_emailAddress[0]) { attrib++; } } o->ptr++; o->len--; if (0 == attrib) { if (*(o->ptr++) != SHARKSSL_OID_JIIT_DS_ATTRTYPE) { attrib = 1; } o->len--; } if (attrib) { attrib = (U8)sharkssl_kmemcmp(o->ptr, &sharkssl_oid_emailAddress[1], (int)(SHARKSSL_DIM_ARR(sharkssl_oid_emailAddress) - 1)); o->ptr += (U32)l; o->len -= (U32)l; if ((l = SharkSslParseASN1_getLength(o)) < 0) { return -1; } if (0 == attrib) { dn->emailAddress = o->ptr; dn->emailAddressLen = (U8)l; } o->ptr += (U32)l; o->len -= (U32)l; continue; } if (l != 3) { return -1; } attrib = *(o->ptr++); rightsvalid = *(o->ptr++); o->len -= 2; if ((l = SharkSslParseASN1_getLength(o)) < 0) { return -1; } if (l > 0xFF) { return -1; } if ((rightsvalid == SHARKSSL_ASN1_UTF8_STRING) || (rightsvalid == SHARKSSL_ASN1_PRINTABLE_STRING) || (rightsvalid == SHARKSSL_ASN1_T61_STRING) || (rightsvalid == SHARKSSL_ASN1_IA5_STRING) || (rightsvalid == SHARKSSL_ASN1_BMP_STRING)) { switch (attrib) { case SHARKSSL_OID_JIIT_DS_ATTRTYPE_CN: dn->commonName = o->ptr; dn->commonNameLen = (U8)l; break; case SHARKSSL_OID_JIIT_DS_ATTRTYPE_COUNTRY: dn->countryName = o->ptr; dn->countryNameLen = (U8)l; break; case SHARKSSL_OID_JIIT_DS_ATTRTYPE_LOCALITY: dn->locality = o->ptr; dn->localityLen = (U8)l; break; case SHARKSSL_OID_JIIT_DS_ATTRTYPE_PROVINCE: dn->province = o->ptr; dn->provinceLen = (U8)l; break; case SHARKSSL_OID_JIIT_DS_ATTRTYPE_ORGANIZATION: dn->organization = o->ptr; dn->organizationLen = (U8)l; break; case SHARKSSL_OID_JIIT_DS_ATTRTYPE_UNIT: dn->unit = o->ptr; dn->unitLen = (U8)l; break; default: break; } } o->ptr += (U32)l; o->len -= (U32)l; } return 0; } #endif #if ((SHARKSSL_SSL_CLIENT_CODE && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || \ (SHARKSSL_SSL_SERVER_CODE) || (SHARKSSL_ENABLE_CSR_SIGNING) || (SHARKSSL_SSL_TOOLS_CODE)) int spromregister(SharkSslCertParam *o, const U8 *p, U32 len, U8 *doublefnmul) { SharkSslParseASN1 parseCert, parseBitString; U8 *pTemp, tag; U32 probealchemy = 0; int l, v; baAssert((doublefnmul == NULL) || ((U32)-1 == len) || ((U32)-2 == len) || ((U32)-3 == len) || ((U32)-4 == len) || ((U32)-5 == len)); parseCert.ptr = (U8*)p; #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 == len) { parseCert.len = *(U32*)doublefnmul; } else #endif { parseCert.len = len; } if ((l = SharkSslParseASN1_getSequence(&parseCert)) < 0) { return -1; } pTemp = parseCert.ptr; if ((l = SharkSslParseASN1_getSequence(&parseCert)) < 0) { return -1; } parseBitString.len = parseCert.len - (U32)l; parseBitString.ptr = parseCert.ptr + (U32)l; if (SharkSslParseASN1_getSequence(&parseBitString) < 0) { return -1; } if (SharkSslParseASN1_getOID(&parseBitString) < 0) { return -1; } tag = SharkSslParseASN1_getAlgoID(&parseBitString); if ((doublefnmul == NULL) && ((U32)-1 == len)) { return ((U16)(GET_ALGO_HASH_ID(tag)) << 8) + GET_ALGO_SIGNATURE_ID(tag); } #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) if ((doublefnmul != NULL) && ((U32)-3 == len)) { *(int*)doublefnmul = ((U16)(GET_ALGO_HASH_ID(tag)) << 8) + GET_ALGO_SIGNATURE_ID(tag); goto SharkSslCertParam_parseCert_1; } #endif #if (SHARKSSL_ENABLE_CLIENT_AUTH || SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-2 == len) { goto SharkSslCertParam_parseCert_1; } #endif o->signature.hashAlgo = GET_ALGO_HASH_ID(tag); o->signature.signatureAlgo = GET_ALGO_SIGNATURE_ID(tag); if (tag == ALGO_ID_MD2_WITH_RSA_ENCRYPTION) { memset(o->signature.hash, 0, 20); } #if (!SHARKSSL_USE_SHA1) else if (tag == ALGO_ID_SHA1_WITH_RSA_ENCRYPTION) { memset(o->signature.hash, 0, 20); } #endif else if (sharkssl_hash(o->signature.hash, pTemp, (U16)(l + (U16)(parseCert.ptr - pTemp)), o->signature.hashAlgo) < 0) { return -1; } probealchemy = parseBitString.len; pTemp = parseBitString.ptr; #if (SHARKSSL_ENABLE_CLIENT_AUTH || (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) || SHARKSSL_ENABLE_CSR_SIGNING) SharkSslCertParam_parseCert_1: #endif parseCert.len = (U32)l; #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 != len) #endif { if (sha256final(&parseCert) < 0) { return -1; } #if (SHARKSSL_ENABLE_CLIENT_AUTH || (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) || SHARKSSL_ENABLE_CSR_SIGNING) if (((U32)-2 != len) && ((U32)-3 != len)) #endif { if (parseCert.datalen == 1) { o->certInfo.version = *(parseCert.dataptr); } else { o->certInfo.version = 0; } } } if (SharkSslParseASN1_getInt(&parseCert) < 0) { return -1; } #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 != len) #endif { #if (SHARKSSL_ENABLE_CLIENT_AUTH || (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) || SHARKSSL_ENABLE_CSR_SIGNING) if (((U32)-2 != len) && ((U32)-3 != len)) #endif { o->certInfo.sn = parseCert.dataptr; o->certInfo.snLen = (U16)parseCert.datalen; } if (SharkSslParseASN1_getSequence(&parseCert) < 0) { return -1; } if (SharkSslParseASN1_getOID(&parseCert) < 0) { return -1; } if (SharkSslParseASN1_getAlgoID(&parseCert) != tag) { return -1; } #if (SHARKSSL_ENABLE_CLIENT_AUTH || SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-2 == len) { if (doublefnmul) { parseBitString.ptr = parseCert.ptr; parseBitString.len = parseCert.len; if ((l = SharkSslParseASN1_getSequence(&parseBitString)) < 0) { return -1; } l += (int)(parseBitString.ptr - parseCert.ptr); if (((U32)l > parseCert.len) || ((U32)l > 0xFFFF)) { return -1; } *(U16*)doublefnmul = (U16)l; } return (int)(parseCert.ptr - p); } #endif if (deltacamera(&parseCert, &(o->certInfo.issuer)) < 0) { return -1; } if (SharkSslParseASN1_getSequence(&parseCert) < 0) { return -1; } if (!SharkSslParseASN1_getUTCTime(&parseCert)) { if ((parseCert.datalen != 13) || (parseCert.dataptr[12] != '\132')) { return -1; } } else if (!SharkSslParseASN1_getGenTime(&parseCert)) { if ((parseCert.datalen < 13) || (parseCert.dataptr[parseCert.datalen - 1] != '\132') || (parseCert.datalen > 0xFF)) { return -1; } } else { return -1; } o->certInfo.timeFrom = parseCert.dataptr; o->certInfo.timeFromLen = (U8)parseCert.datalen; if (!SharkSslParseASN1_getUTCTime(&parseCert)) { if ((parseCert.datalen != 13) || (parseCert.dataptr[12] != '\132')) { return -1; } } else if (!SharkSslParseASN1_getGenTime(&parseCert)) { if ((parseCert.datalen < 13) || (parseCert.dataptr[parseCert.datalen - 1] != '\132') || (parseCert.datalen > 0xFF)) { return -1; } } else { return -1; } o->certInfo.timeTo = parseCert.dataptr; o->certInfo.timeToLen = (U8)parseCert.datalen; } #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 == len) { *(U16*)&(o->certInfo.issuer.countryNameLen) = (U16)parseCert.len; } #endif if (deltacamera(&parseCert, &(o->certInfo.subject)) < 0) { return -1; } #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 == len) { *(U16*)&(o->certInfo.issuer.countryNameLen) -= (U16)parseCert.len; } #endif if (SharkSslParseASN1_getSequence(&parseCert) < 0) { return -1; } if (SharkSslParseASN1_getSequence(&parseCert) < 0) { return -1; } if (SharkSslParseASN1_getOID(&parseCert) < 0) { return -1; } switch (SharkSslParseASN1_getAlgoID(&parseCert)) { #if SHARKSSL_USE_ECC case ALGO_OID_EC_PUBLIC_KEY: if (SharkSslParseASN1_getOID(&parseCert) < 0) { return -1; } l = SharkSslParseASN1_getCurveID(&parseCert); baAssert(l < 0x0100); if ((l == SHARKSSL_EC_CURVE_ID_UNKNOWN) || (SharkSslParseASN1_getBitString(&parseCert) < 0)) { return -1; } #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) if ((U32)-3 == len) { goto SharkSslCertParam_parseCert_2; } #endif parseBitString.len = parseCert.datalen; parseBitString.ptr = parseCert.dataptr; while ((0 == *parseBitString.ptr) && (parseBitString.len)) { parseBitString.ptr++; parseBitString.len--; } if (0 == parseBitString.len) { return -1; } parseBitString.len--; if (*parseBitString.ptr++ != SHARKSSL_EC_POINT_UNCOMPRESSED) { return -1; } baAssert(parseBitString.len < 0x0100); o->certKey.mod = parseBitString.ptr; o->certKey.modLen = (U16)parseBitString.len >> 1; if ((parseBitString.len & 0x1) || (o->certKey.modLen != (U16)controllerregister((U16)l))) { return -1; } baAssert((U8)l); nomsrnoirq(o->certKey.modLen, (U16)l); o->certKey.exp = (U8*)0; o->certKey.expLen = 0; deltaticks(o->certKey.expLen); baAssert(loaderbinfmt(o->certKey.modLen,o->certKey.expLen) == ((U16)parseBitString.len >> 1)); baAssert(targetoracle(o->certKey.modLen,o->certKey.expLen) == (U8)l); baAssert(mousethresh(o->certKey.expLen) == 0); baAssert(monadiccheck(o->certKey.expLen) == 0); baAssert(coupledexynos(o->certKey.expLen)); baAssert(machinereboot(o->certKey.expLen)); parseBitString.ptr += parseBitString.len; break; #endif #if SHARKSSL_ENABLE_RSA case ALGO_ID_RSA_ENCRYPTION: if (SharkSslParseASN1_getBitString(&parseCert) < 0) { return -1; } #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) if ((U32)-3 == len) { goto SharkSslCertParam_parseCert_2; } #endif parseBitString.len = parseCert.datalen; parseBitString.ptr = parseCert.dataptr; if ((parseBitString.len < 1) || (*(parseBitString.ptr++) != 0x00)) { return -1; } parseBitString.len--; if (SharkSslParseASN1_getSequence(&parseBitString) < 0) { return -1; } if (SharkSslParseASN1_getInt(&parseBitString) < 0) { return -1; } o->certKey.mod = parseBitString.dataptr; o->certKey.modLen = (U16)parseBitString.datalen; baAssert(supportedvector(o->certKey.modLen) == (U16)parseBitString.datalen); while (supportedvector(o->certKey.modLen) & 0x1F) { o->certKey.modLen--; if (*(o->certKey.mod++) != 0x00) { return -1; } } if ((SharkSslParseASN1_getInt(&parseBitString) < 0) || (parseBitString.len)) { return -1; } o->certKey.exp = parseBitString.dataptr; o->certKey.expLen = (U16)parseBitString.datalen; specialmapping(o->certKey.expLen); baAssert(mousethresh(o->certKey.expLen) == (U16)parseBitString.datalen); baAssert(monadiccheck(o->certKey.expLen) == 0); baAssert(coupledexynos(o->certKey.expLen)); baAssert(machinekexec(o->certKey.expLen)); break; #endif default: return -1; } if (parseCert.ptr != parseBitString.ptr) { return -1; } #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) SharkSslCertParam_parseCert_2: #endif #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 == len) { l = SharkSslParseASN1_getCSRAttributes(&parseCert); *(U32*)doublefnmul = 0; } else #endif { SharkSslParseASN1_getIssuerUniqueID(&parseCert); SharkSslParseASN1_getSubjectUniqueID(&parseCert); l = SharkSslParseASN1_getExtensions(&parseCert); } if (parseCert.len != 0) { return -1; } o->certInfo.CAflag = 0; o->certInfo.subjectAltNamesPtr = 0; o->certInfo.subjectAltNamesLen = 0; if (l == 0) { parseCert.ptr = parseCert.dataptr; parseCert.len = parseCert.datalen; if (((v = SharkSslParseASN1_getSequence(&parseCert)) > 0) && ((U32)v < parseCert.datalen)) { #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 == len) { if (SharkSslParseASN1_getOID(&parseCert) < 0) { return -1; } if ((parseCert.datalen != SHARKSSL_DIM_ARR(sharkssl_oid_csr_ext_req)) || (sharkssl_kmemcmp(parseCert.dataptr, sharkssl_oid_csr_ext_req, SHARKSSL_DIM_ARR(sharkssl_oid_csr_ext_req)))) { return -1; } if ((v = SharkSslParseASN1_getSet(&parseCert)) <= 0) { return -1; } if ((v = SharkSslParseASN1_getSequence(&parseCert)) < 0) { return -1; } *(U16*)&(o->certInfo.issuer.commonNameLen) = (U16)(int)(parseCert.ptr - p); *(U32*)doublefnmul = (U16)v; } else #endif while (parseCert.len) { if ((l = SharkSslParseASN1_getSequence(&parseCert)) < 0) { break; } parseBitString.ptr = parseCert.ptr; parseBitString.len = (U32)l; parseCert.ptr += (U32)l; parseCert.len -= (U32)l; if (SharkSslParseASN1_getOID(&parseBitString) < 0) { continue; } if ((parseBitString.datalen == 3) && (parseBitString.dataptr[1] == SHARKSSL_OID_JIIT_DS_CERTEXT) && (parseBitString.dataptr[0] == SHARKSSL_OID_JIIT_DS)) { if (parseBitString.dataptr[2] == SHARKSSL_OID_JIIT_DS_CERTEXT_BASICCONSTRAINTS) { SharkSslParseASN1_getBool(&parseBitString); if ((SharkSslParseASN1_getOctetString(&parseBitString) == 0) && (parseBitString.len == 0)) { parseBitString.ptr = parseBitString.dataptr; parseBitString.len = parseBitString.datalen; if (SharkSslParseASN1_getSequence(&parseBitString) > 0) { if ((SharkSslParseASN1_getBool(&parseBitString) == 0) && (parseBitString.datalen == 1) && (parseBitString.dataptr[0] != 0)) { o->certInfo.CAflag++; break; } } } } #if SHARKSSL_ENABLE_CERT_KEYUSAGE else if (parseBitString.dataptr[2] == SHARKSSL_OID_JIIT_DS_CERTEXT_KEYUSAGE) { if (SharkSslParseASN1_getBool(&parseBitString) == 0) { if ((parseBitString.datalen == 1) && *(parseBitString.dataptr)) { o->certInfo.keyUsagePurposes |= SHARKSSL_CERT_KEYUSAGE_CRITICAL; } } #if (SHARKSSL_CERT_KEYUSAGE_DIGITALSIGNATURE != 0x00000001) || \ (SHARKSSL_CERT_KEYUSAGE_NONREPUDIATION != 0x00000002) || \ (SHARKSSL_CERT_KEYUSAGE_KEYENCIPHERMENT != 0x00000004) || \ (SHARKSSL_CERT_KEYUSAGE_DATAENCIPHERMENT != 0x00000008) || \ (SHARKSSL_CERT_KEYUSAGE_KEYAGREEMENT != 0x00000010) || \ (SHARKSSL_CERT_KEYUSAGE_KEYCERTSIGN != 0x00000020) || \ (SHARKSSL_CERT_KEYUSAGE_CRLSIGN != 0x00000040) || \ (SHARKSSL_CERT_KEYUSAGE_ENCIPHERONLY != 0x00000080) || \ (SHARKSSL_CERT_KEYUSAGE_DECIPHERONLY != 0x00000100) #error wrong SHARKSSL_CERT_KEYUSAGE_ values #endif if (SharkSslParseASN1_getOctetString(&parseBitString) == 0) { parseBitString.ptr = parseBitString.dataptr; parseBitString.len = parseBitString.datalen; if (SharkSslParseASN1_getBitString(&parseBitString) == 0) { U8 a, *pb = parseBitString.dataptr; l = parseBitString.datalen; if ((parseBitString.len == 0) && (l >= 2)) { l--; v = l * 8; if (v >= *pb) { v -= *pb; pb++; if (v > 8) { v = 8; if ((l > 1) && (pb[1] & 0x80)) { o->certInfo.keyUsagePurposes |= 0x100; } } a = *pb; for (l = 0x1; v > 0; v--, l <<= 1, a <<= 1) { if (a & 0x80) { o->certInfo.keyUsagePurposes |= (U8)l; } } o->certInfo.keyUsagePurposes |= SHARKSSL_CERT_KEYUSAGE_PRESENT; } } } } } #endif else if ((parseBitString.dataptr[2] == SHARKSSL_OID_JIIT_DS_CERTEXT_SUBJALTNAMES) && (!o->certInfo.CAflag)) { if ((SharkSslParseASN1_getOctetString(&parseBitString) == 0) && (parseBitString.len == 0)) { parseBitString.ptr = parseBitString.dataptr; parseBitString.len = parseBitString.datalen; if (SharkSslParseASN1_getSequence(&parseBitString) > 0) { baAssert(parseBitString.len <= 0xFFFF); o->certInfo.subjectAltNamesPtr = parseBitString.ptr; o->certInfo.subjectAltNamesLen = (U16)parseBitString.len; } } } } else if ((parseBitString.datalen == SHARKSSL_DIM_ARR(sharkssl_oid_ns_cert_type)) && (0 == sharkssl_kmemcmp(parseBitString.dataptr, sharkssl_oid_ns_cert_type, SHARKSSL_DIM_ARR(sharkssl_oid_ns_cert_type)))) { if ((SharkSslParseASN1_getOctetString(&parseBitString) == 0) && (parseBitString.len == 0)) { parseBitString.ptr = parseBitString.dataptr; parseBitString.len = parseBitString.datalen; if (SharkSslParseASN1_getBitString(&parseBitString) == 0) { if ((parseBitString.datalen) && (parseBitString.dataptr[parseBitString.datalen - 1] & 0x04)) { o->certInfo.CAflag++; break; } } } } } } } #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) if ((U32)-3 == len) { return 0; } #endif parseBitString.ptr = pTemp; parseBitString.len = probealchemy; if (SharkSslParseASN1_getBitString(&parseBitString) < 0) { return -1; } o->signature.signature = parseBitString.dataptr; o->signature.signLen = (U16)parseBitString.datalen; #if SHARKSSL_ENABLE_ECDSA if (o->signature.signatureAlgo == ALGO_ID_ECDSA) { while ((o->signature.signLen) && (0 == *(o->signature.signature))) { o->signature.signLen--; o->signature.signature++; } } #if SHARKSSL_ENABLE_RSA else #endif #endif #if SHARKSSL_ENABLE_RSA if (o->signature.signatureAlgo == ALGO_ID_RSA_ENCRYPTION) { while (o->signature.signLen & 0x1F) { o->signature.signLen--; if (*(o->signature.signature++) != 0x00) { return -1; } } } #endif #if (SHARKSSL_ENABLE_CSR_SIGNING) if ((U32)-4 == len) { *(U32*)doublefnmul |= ((U32)(*(U16*)&(o->certInfo.issuer.countryNameLen)) << 16); return (int)*(U16*)&(o->certInfo.issuer.commonNameLen); } #endif return 0; } SharkSslCert removerecursive(SharkSslCertEnum *o) { #if SHARKSSL_ENABLE_CERT_CHAIN if (o->cert != NULL) { if (o->priv_notFirstCertFlag) { if (o->priv_chainLen) { o->priv_chainLen--; o->cert += o->certLen; } else { o->cert = NULL; } } else { U16 setpropinplace, chargeerror; o->priv_notFirstCertFlag++; o->cert += o->certLen; while (0xFF == *o->cert) { o->cert++; } setpropinplace = (U16)(*(o->cert++)) << 8; setpropinplace += *(o->cert++); o->priv_chainLen = monadiccheck(setpropinplace); if (o->priv_chainLen) { o->priv_chainLen--; chargeerror = (U16)(*(o->cert++)) << 8; chargeerror += *(o->cert++); o->cert += mousethresh(setpropinplace); #if SHARKSSL_ENABLE_RSA if (machinekexec(setpropinplace)) { #if 0 baAssert(chargeerror == supportedvector(chargeerror)); baAssert((chargeerror <= 0x3FFF) && (0 == (chargeerror & 0x01))); #else if ((chargeerror > 0x3FFF) || (chargeerror & 0x01)) { o->cert = NULL; } #endif { o->cert += (U16)(chargeerror << 2); o->cert -= (U16)(chargeerror >> 1); } } #if SHARKSSL_USE_ECC else #endif #endif #if SHARKSSL_USE_ECC if (machinereboot(setpropinplace)) { chargeerror = attachdevice(chargeerror); #if 0 baAssert((chargeerror < 0x00FF) && (0 == (chargeerror & 0x01))); #else if ((chargeerror >= 0x00FF) || (chargeerror & 0x01)) { o->cert = NULL; } else #endif { o->cert += (U16)(chargeerror << 1); } } #endif else { o->cert = NULL; } } else { o->cert = NULL; } } } #else o->cert = NULL; #endif o->certLen = SharkSslCert_len(o->cert); return o->cert; } #if SHARKSSL_ENABLE_RSASSA_PSS static int resetquirks(U8 *singleunpack, U8 *resourceaddress64, U16 pxacameraplatform, U8 configwrite) { U8 chargerplatform[SHARKSSL_MAX_HASH_LEN], save[4]; U16 usb11device, ftraceupdate, j; int offsetarray = 0; baAssert(resourceaddress64); ftraceupdate = sharkssl_getHashLen(configwrite); if (0 == ftraceupdate) { return -1; } memcpy(&save[0], singleunpack + ftraceupdate, 4); *(U32*)(singleunpack + ftraceupdate) = 0x00000000; for (;;) { if (sharkssl_hash(&chargerplatform[0], singleunpack, ftraceupdate + 4, configwrite)) { offsetarray = -1; break; } usb11device = (pxacameraplatform >= ftraceupdate) ? ftraceupdate : pxacameraplatform; for (j = 0; j < usb11device; j++) { *resourceaddress64++ ^= chargerplatform[j]; } pxacameraplatform -= usb11device; if (pxacameraplatform > 0) { (*(singleunpack + ftraceupdate + 3))++; } else { break; } } memcpy(singleunpack + ftraceupdate, &save[0], 4); return offsetarray; } #endif int systemcapabilities(const SharkSslSignParam *o) { #if SHARKSSL_ENABLE_ECDSA U8 kexecprepare[claimresource(SHARKSSL_MAX_ECC_POINTLEN)]; U8 stackoverflow[claimresource(SHARKSSL_MAX_ECC_POINTLEN)]; SharkSslECDSAParam ecdsaParam; #endif SharkSslParseASN1 parseSgn; U8 *s; int len; s = o->signature.signature; switch (o->signature.signatureAlgo) { #if SHARKSSL_ENABLE_RSA #if (SHARKSSL_TLS_1_2 || SHARKSSL_ENABLE_RSA_PKCS1) case entryearly: #endif #if SHARKSSL_ENABLE_RSASSA_PSS case SHARKSSL_SIGNATUREALGORITHM_RSA_PSS: #endif if (!(machinekexec(o->pCertKey->expLen)) || (o->signature.signLen != supportedvector(o->pCertKey->modLen))) { return -1; } len = (int)handleguest(o->pCertKey, o->signature.signLen, s, s, #if SHARKSSL_ENABLE_RSASSA_PSS (o->signature.signatureAlgo == SHARKSSL_SIGNATUREALGORITHM_RSA_PSS) ? SHARKSSL_RSA_NO_PADDING : #endif SHARKSSL_RSA_PKCS1_PADDING); if (len < 0) { return -1; } #if SHARKSSL_ENABLE_RSASSA_PSS if (o->signature.signatureAlgo == SHARKSSL_SIGNATUREALGORITHM_RSA_PSS) { U32 sgnWord, lzbMask; U16 locationnotifier; len = supportedvector(o->pCertKey->modLen) - 1; if (*(s + len) != 0xBC) { return -1; } locationnotifier = sharkssl_getHashLen(o->signature.hashAlgo); len -= locationnotifier; read64uint32(lzbMask, s, 0); if (0 == lzbMask) { return -1; } lzbMask |= (lzbMask >> 1); lzbMask |= (lzbMask >> 2); lzbMask |= (lzbMask >> 4); lzbMask |= (lzbMask >> 8); lzbMask |= (lzbMask >> 16); if (resetquirks(s + (U16)len, s, (U16)len, o->signature.hashAlgo)) { return -1; } read64uint32(sgnWord, s, 0); sgnWord &= lzbMask; inputlevel(sgnWord, s, 0); len -= locationnotifier; len--; if (len < 0) { return -1; } while (len >= 4) { read64uint32(sgnWord, s, 0); if (sgnWord) { return -1; } s += 4; len -= 4; } while ((len > 0) && (0 == *s++)) { len--; } if ((len > 0) || (*s++ != 0x01)) { return -1; } s -= locationnotifier; memcpy(s, o->signature.hash, locationnotifier); len = 8 + (locationnotifier << 1); if (sharkssl_hash(s, s - 8, (U16)len, o->signature.hashAlgo)) { return -1; } len -= 8; if (sharkssl_kmemcmp(s, s + len, locationnotifier)) { return -1; } break; } else #endif { if (o->signature.hashAlgo == defaultspectre) { if (sharkssl_kmemcmp(o->signature.hash, s, (U16)len)) { return -1; } } #if SHARKSSL_TLS_1_2 else { parseSgn.ptr = s; parseSgn.len = (U16)len; if ((len = SharkSslParseASN1_getSequence(&parseSgn)) < 0) { return -1; } if (((U32)len != parseSgn.len) || (SharkSslParseASN1_getSequence(&parseSgn) < 0) || (SharkSslParseASN1_getOID(&parseSgn) < 0)) { return -1; } if (SharkSslParseASN1_getAlgoID(&parseSgn) != o->signature.hashAlgo) { return -1; } if ((SharkSslParseASN1_getOctetString(&parseSgn)) || (parseSgn.len)) { return -1; } if (parseSgn.datalen != sharkssl_getHashLen(o->signature.hashAlgo)) { return -1; } if (sharkssl_kmemcmp(o->signature.hash, parseSgn.dataptr, parseSgn.datalen)) { return -1; } } #endif } break; #endif #if SHARKSSL_ENABLE_ECDSA case accessactive: if (!(machinereboot(o->pCertKey->expLen))) { return -1; } parseSgn.ptr = s; parseSgn.len = o->signature.signLen; if (((len = SharkSslParseASN1_getSequence(&parseSgn)) < 0) || (SharkSslParseASN1_getInt(&parseSgn) < 0) || ((U32)len < parseSgn.datalen)) { return -1; } ecdsaParam.keyLen = attachdevice(o->pCertKey->modLen); if ((U16)parseSgn.datalen > ecdsaParam.keyLen) { return -1; } #if 1 len = (ecdsaParam.keyLen - parseSgn.datalen); if (len) { memset(kexecprepare, 0, len); memcpy(&kexecprepare[len], parseSgn.dataptr, parseSgn.datalen); ecdsaParam.R = kexecprepare; } else { ecdsaParam.R = parseSgn.dataptr; } if (SharkSslParseASN1_getInt(&parseSgn) < 0) { return -1; } len = (ecdsaParam.keyLen - parseSgn.datalen); if (len) { memset(stackoverflow, 0, len); memcpy(&stackoverflow[len], parseSgn.dataptr, parseSgn.datalen); ecdsaParam.S = stackoverflow; } else { ecdsaParam.S = parseSgn.dataptr; } #else ecdsaParam.R = parseSgn.dataptr; if (parseSgn.datalen < ecdsaParam.keyLen) { *(--(ecdsaParam.R)) = 0x00; parseSgn.datalen++; if (parseSgn.datalen < ecdsaParam.keyLen) { *(--(ecdsaParam.R)) = 0x00; parseSgn.datalen++; if (parseSgn.datalen < ecdsaParam.keyLen) { return -1; } } } if (SharkSslParseASN1_getInt(&parseSgn) < 0) { return -1; } ecdsaParam.S = parseSgn.dataptr; if (parseSgn.datalen < ecdsaParam.keyLen) { *(--(ecdsaParam.S)) = 0x00; parseSgn.datalen++; if (parseSgn.datalen < ecdsaParam.keyLen) { *(--(ecdsaParam.S)) = 0x00; parseSgn.datalen++; if (parseSgn.datalen < ecdsaParam.keyLen) { return -1; } } } #endif ecdsaParam.key = o->pCertKey->mod; ecdsaParam.curveType = wakeupenable(o->pCertKey->modLen); ecdsaParam.hash = (U8*)o->signature.hash; ecdsaParam.hashLen = sharkssl_getHashLen(o->signature.hashAlgo); if (SharkSslECDSAParam_ECDSA(&ecdsaParam, fixupdevices)) { return -1; } break; #endif default: return -1; } return 0; } static int systemconfiguration(const U8 *s1, const U8 *s2, const U32 disablechannel, const U32 modifymisccr) { if (s1 == NULL) { if (s2 == NULL) { return (disablechannel + modifymisccr); } } else if ((s2) && (disablechannel == modifymisccr)) { return sharkssl_kmemcmp((const char*)s1, (const char*)s2, disablechannel); } return 1; } U8 SharkSslCertDN_equal(const SharkSslCertDN *o1, const SharkSslCertDN *o2) { if ( systemconfiguration(o1->organization, o2->organization, o1->organizationLen, o2->organizationLen) || systemconfiguration(o1->unit, o2->unit, o1->unitLen, o2->unitLen) || systemconfiguration(o1->commonName, o2->commonName, o1->commonNameLen, o2->commonNameLen) || systemconfiguration(o1->countryName, o2->countryName, o1->countryNameLen, o2->countryNameLen) || systemconfiguration(o1->locality, o2->locality, o1->localityLen, o2->localityLen) || systemconfiguration(o1->province, o2->province, o1->provinceLen, o2->provinceLen) ) { return 0; } return 1; } #endif #if SHARKSSL_ENABLE_ECDSA static sharkssl_ECDSA_RetVal registerboard(SharkSslECDSAParam *audioshutdown, U8 *sig, U16 *platformconfig) { SharkSslASN1Create wasn1; U8 kexecprepare[claimresource(SHARKSSL_MAX_ECC_POINTLEN)]; U8 stackoverflow[claimresource(SHARKSSL_MAX_ECC_POINTLEN)]; int ret; baAssert(0 == SHARKSSL_ECDSA_OK); audioshutdown->R = kexecprepare; audioshutdown->S = stackoverflow; ret = SharkSslECDSAParam_ECDSA(audioshutdown, iommupdata); if (ret) { if ((int)SharkSslCon_AllocationError == ret) { return SHARKSSL_ECDSA_ALLOCATION_ERROR; } return SHARKSSL_ECDSA_INTERNAL_ERROR; } if (0 == *platformconfig) { return SHARKSSL_ECDSA_SIGLEN_TOO_SMALL; } SharkSslASN1Create_constructor(&wasn1, sig, *platformconfig); *platformconfig = 0; if (SharkSslASN1Create_int(&wasn1, audioshutdown->S, audioshutdown->keyLen) < 0) { return SHARKSSL_ECDSA_INTERNAL_ERROR; } if (SharkSslASN1Create_int(&wasn1, audioshutdown->R, audioshutdown->keyLen) < 0) { return SHARKSSL_ECDSA_INTERNAL_ERROR; } if (SharkSslASN1Create_length(&wasn1, SharkSslASN1Create_getLen(&wasn1)) < 0) { return SHARKSSL_ECDSA_SIGLEN_TOO_SMALL; } if (SharkSslASN1Create_sequence(&wasn1) < 0) { return SHARKSSL_ECDSA_INTERNAL_ERROR; } *platformconfig = (U16)SharkSslASN1Create_getLen(&wasn1); memmove(sig, SharkSslASN1Create_getData(&wasn1), *platformconfig); return SHARKSSL_ECDSA_OK; } #endif #if (((SHARKSSL_SSL_CLIENT_CODE && SHARKSSL_ENABLE_CLIENT_AUTH) || (SHARKSSL_SSL_SERVER_CODE) || (SHARKSSL_SSL_TOOLS_CODE) || \ (SHARKSSL_ENABLE_CSR_SIGNING) || (SHARKSSL_ENABLE_CSR_CREATION)) && \ (SHARKSSL_ENABLE_DHE_RSA || SHARKSSL_ENABLE_ECDHE_RSA || SHARKSSL_ENABLE_ECDHE_ECDSA)) int checkactions(SharkSslSignParam *o) { #if SHARKSSL_ENABLE_RSA int len; #if SHARKSSL_ENABLE_RSASSA_PSS int kernelirqfd; U32 sgnWord, lzbMask; #endif #endif U8 *pciercxcfg448; U16 ftraceupdate; #if SHARKSSL_ENABLE_RSA const U8 *oid; U8 fieldvalue; #endif #if SHARKSSL_ENABLE_ECDSA SharkSslECDSAParam audioshutdown; #endif pciercxcfg448 = o->signature.signature; o->signature.signLen = 0; ftraceupdate = sharkssl_getHashLen(o->signature.hashAlgo); switch (o->signature.signatureAlgo) { #if SHARKSSL_ENABLE_RSA #if (SHARKSSL_TLS_1_2 || SHARKSSL_ENABLE_RSA_PKCS1) case entryearly: if (!(machinekexec(o->pCertKey->expLen))) { return -1; } switch (o->signature.hashAlgo) { #if SHARKSSL_USE_SHA_512 case batterythread: oid = sharkssl_oid_sha512; fieldvalue = SHARKSSL_DIM_ARR(sharkssl_oid_sha512); goto _sharkssl_cs_common_1_2; #endif #if SHARKSSL_USE_SHA_384 case probewrite: oid = sharkssl_oid_sha384; fieldvalue = SHARKSSL_DIM_ARR(sharkssl_oid_sha384); goto _sharkssl_cs_common_1_2; #endif #if SHARKSSL_USE_SHA_256 case domainnumber: oid = sharkssl_oid_sha256; fieldvalue = SHARKSSL_DIM_ARR(sharkssl_oid_sha256); goto _sharkssl_cs_common_1_2; #endif #if SHARKSSL_USE_SHA1 case presentpages: oid = sharkssl_oid_sha1; fieldvalue = SHARKSSL_DIM_ARR(sharkssl_oid_sha1); #endif _sharkssl_cs_common_1_2: len = (fieldvalue + ftraceupdate + 10); baAssert(len < 0x80); *pciercxcfg448++ = 0x30; *pciercxcfg448++ = (U8)(len - 2); *pciercxcfg448++ = 0x30; *pciercxcfg448++ = (fieldvalue + 4); *pciercxcfg448++ = 0x06; *pciercxcfg448++ = fieldvalue; memcpy(pciercxcfg448, oid, fieldvalue); pciercxcfg448 += fieldvalue; *pciercxcfg448++ = 0x05; *pciercxcfg448++ = 0x00; *pciercxcfg448++ = 0x04; *pciercxcfg448++ = (U8)ftraceupdate; break; default: return -1; } memcpy(pciercxcfg448, o->signature.hash, ftraceupdate); len = (int)clockaccess(o->pCertKey, (U16)len, o->signature.signature, o->signature.signature, SHARKSSL_RSA_PKCS1_PADDING); if ((len < 0) || ((U16)len != supportedvector(o->pCertKey->modLen))) { return -1; } o->signature.signLen = (U16)len; break; #endif #if SHARKSSL_ENABLE_RSASSA_PSS case SHARKSSL_SIGNATUREALGORITHM_RSA_PSS: if (!(machinekexec(o->pCertKey->expLen))) { return -1; } len = supportedvector(o->pCertKey->modLen); if (len < ((int)2048/8)) { return -1; } len--; *(U8*)(pciercxcfg448 + len) = 0xBC; len--; kernelirqfd = (int)(ftraceupdate << 1); if (len < kernelirqfd) { return -1; } memset(pciercxcfg448, 0, 8); memcpy(pciercxcfg448 + 8, o->signature.hash, ftraceupdate); sharkssl_rng(pciercxcfg448 + 8 + ftraceupdate, ftraceupdate); len++; len -= ftraceupdate; sharkssl_hash(pciercxcfg448 + len, pciercxcfg448, 8 + (U16)kernelirqfd, o->signature.hashAlgo); len -= ftraceupdate; memmove(pciercxcfg448 + len, pciercxcfg448 + 8 + ftraceupdate, ftraceupdate); len--; memset(pciercxcfg448, 0, len); *(U8*)(pciercxcfg448 + len) = 0x01; len++; len += ftraceupdate; if (resetquirks(pciercxcfg448 + (U16)len, pciercxcfg448, (U16)len, o->signature.hashAlgo)) { return -1; } read64uint32(lzbMask, o->pCertKey->mod, 0); if (0 == lzbMask) { return -1; } lzbMask |= (lzbMask >> 1); lzbMask |= (lzbMask >> 2); lzbMask |= (lzbMask >> 4); lzbMask |= (lzbMask >> 8); lzbMask |= (lzbMask >> 16); lzbMask >>= 1; read64uint32(sgnWord, pciercxcfg448, 0); sgnWord &= lzbMask; inputlevel(sgnWord, pciercxcfg448, 0); len = (int)clockaccess(o->pCertKey, supportedvector(o->pCertKey->modLen), pciercxcfg448, pciercxcfg448, SHARKSSL_RSA_NO_PADDING); if ((len < 0) || ((U16)len != supportedvector(o->pCertKey->modLen))) { return -1; } o->signature.signLen = (U16)len; break; #endif #endif #if SHARKSSL_ENABLE_ECDSA case accessactive: if (!(machinereboot(o->pCertKey->expLen)) || coupledexynos(o->pCertKey->expLen)) { return -1; } audioshutdown.curveType = wakeupenable(o->pCertKey->modLen); audioshutdown.hash = o->signature.hash; audioshutdown.hashLen = ftraceupdate; audioshutdown.key = o->pCertKey->exp; audioshutdown.keyLen = mousethresh(o->pCertKey->expLen); if ((audioshutdown.key == NULL) || (audioshutdown.keyLen == 0)) { return -1; } o->signature.signLen = relocationchain(o->pCertKey); if (registerboard(&audioshutdown, pciercxcfg448, &(o->signature.signLen)) < 0) { return -1; } break; #endif default: return -1; } return 0; } #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) SHARKSSL_API U16 SharkSslCert_len(SharkSslCert kernelvaddr) { if ((kernelvaddr != NULL) && (0x30 == kernelvaddr[0]) && (0x82 == kernelvaddr[1])) { return (U16)(((U16)(kernelvaddr[2]) * 256) + kernelvaddr[3] + 4); } return (U16)-1; } U16 interrupthandler(SharkSslCertKey *disableclock, SharkSslCert kernelvaddr) { U16 ret, len; if (kernelvaddr) { ret = SharkSslCert_len(kernelvaddr); if (ret != (U16)-1) { ret += 0x03; ret &= ~0x03; kernelvaddr += ret; disableclock->expLen = (U16)((U16)(kernelvaddr[0]) * 256 + kernelvaddr[1]); len = mousethresh(disableclock->expLen); kernelvaddr += 2; disableclock->modLen = (U16)((U16)(kernelvaddr[0]) * 256 + kernelvaddr[1]); kernelvaddr += 2; disableclock->exp = len ? (U8*)kernelvaddr : (U8*)0; kernelvaddr += len; disableclock->mod = (U8*)kernelvaddr; return ret; } } memset(disableclock, 0, sizeof(SharkSslCertKey)); return 0; } #if SHARKSSL_ENABLE_ECDSA SHARKSSL_API U16 SharkSslKey_vectSize(const SharkSslKey sourcerouting) { return SharkSslKey_vectSize_keyInfo(sourcerouting, (U8*)0, (U8*)0, (U8**)0, (U16*)0, (U8**)0, (U16*)0); } SHARKSSL_API U16 SharkSslKey_vectSize_keyInfo(const SharkSslKey sourcerouting, U8 *earlyconsole, U8 *isKeyPrivate, U8 **d1, U16 *d1Len, U8 **d2, U16 *d2Len) { SharkSslCertKey disableclock; U16 icachealiases; #if SHARKSSL_ENABLE_CERT_CHAIN U16 nc0; #endif icachealiases = interrupthandler(&disableclock, (SharkSslCert)sourcerouting); if (icachealiases) { #if SHARKSSL_ENABLE_CERT_CHAIN nc0 = monadiccheck(disableclock.expLen); #endif if (isKeyPrivate) { *isKeyPrivate = coupledexynos(disableclock.expLen) ? 0 : 1; } if (d1) { *d1 = disableclock.mod; } icachealiases += 4 + mousethresh(disableclock.expLen); if (machinekexec(disableclock.expLen)) { if (earlyconsole) { *earlyconsole = SHARKSSL_KEYTYPE_RSA; } if (d1Len) { *d1Len = supportedvector(disableclock.modLen); } if (d2Len) { *d2Len = mousethresh(disableclock.expLen); } if (d2) { *d2 = disableclock.exp; } icachealiases += supportedvector(disableclock.modLen); if (!coupledexynos(disableclock.expLen)) { icachealiases += (U16)((supportedvector(disableclock.modLen) / 2) * 5); } } else if (machinereboot(disableclock.expLen)) { icachealiases += (U16)(2 * attachdevice(disableclock.modLen)); if (earlyconsole) { *earlyconsole = SHARKSSL_KEYTYPE_EC; } if (d1Len) { *d1Len = attachdevice(disableclock.modLen); } if (d2Len) { *d2Len = attachdevice(disableclock.modLen); } if (d2) { *d2 = disableclock.mod + attachdevice(disableclock.modLen); } } else { icachealiases = 0; } #if SHARKSSL_ENABLE_CERT_CHAIN if (icachealiases && nc0) { U8 *postcoreinitcall = (U8*)(&sourcerouting[icachealiases]); while (nc0--) { U16 ebasecpunum = SharkSslCert_len((SharkSslCert)postcoreinitcall); if ((U16)-1 == ebasecpunum) { icachealiases = nc0 = 0; } else { postcoreinitcall += ebasecpunum; icachealiases += ebasecpunum; } } } #endif } return icachealiases; } #endif #if ((SHARKSSL_SSL_CLIENT_CODE && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || \ (SHARKSSL_SSL_SERVER_CODE)) U8 fixupresources(SharkSslCert kernelvaddr, U16 len, U8 *ptr) { SharkSslCertEnum cEnum; baAssert(len >= 3); baAssert(ptr); len -= 3; *ptr++ = 0x00; *ptr++ = (U8)(len >> 8); *ptr++ = (U8)(len & 0xFF); registerautodeps(&cEnum, kernelvaddr); kernelvaddr = updatesctlr(&cEnum); while (kernelvaddr != NULL) { U16 pxafbmodes = SharkSslCertEnum_getCertLength(&cEnum); *ptr++ = 0x00; *ptr++ = (U8)(pxafbmodes >> 8); *ptr++ = (U8)(pxafbmodes & 0xFF); memcpy(ptr, kernelvaddr, pxafbmodes); ptr += pxafbmodes; len -= 3; len -= pxafbmodes; kernelvaddr = removerecursive(&cEnum); } return (U8)((len >> 8) | (len & 0xFF)); } U16 setupboard(SharkSslCert kernelvaddr) { SharkSslCertEnum cEnum; U16 len = 3; registerautodeps(&cEnum, kernelvaddr); kernelvaddr = updatesctlr(&cEnum); while (kernelvaddr != NULL) { U16 driverunregister = SharkSslCertEnum_getCertLength(&cEnum); if (driverunregister == (U16)-1) { len = 0; break; } len += 3 + driverunregister; kernelvaddr = removerecursive(&cEnum); } return len; } #endif #if SHARKSSL_ENABLE_CLIENT_AUTH U8 domainassociate(SharkSslCert kernelvaddr, U8 *dn, U16 installidmap) { SharkSslCertEnum cEnum; registerautodeps(&cEnum, kernelvaddr); kernelvaddr = updatesctlr(&cEnum); while (kernelvaddr != NULL) { U16 certLen, dnCLen; int registerinterrupts; certLen = SharkSslCertEnum_getCertLength(&cEnum); registerinterrupts = spromregister(0, (U8*)kernelvaddr, (U32)-2, (U8*)&dnCLen); if ((registerinterrupts > 0) && ((U32)registerinterrupts < certLen) && (installidmap == dnCLen)) { if (0 == sharkssl_kmemcmp(((U8*)kernelvaddr + registerinterrupts), dn, installidmap)) { return 1; } } kernelvaddr = removerecursive(&cEnum); } return 0; } #endif #endif #if ((SHARKSSL_ENABLE_PEM_API) || (SHARKSSL_ENABLE_CERTSTORE_API)) static const U8 sysrqreboot[128] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 62,0xFF,0xFF,0xFF, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,0xFF,0xFF,0xFF,0xFF,0xFF }; SHARKSSL_API U32 sharkssl_B64Decode( U8 *disableevent, U32 queryinput, const char *joystickmonitor, const char *requestpending) { U32 len; U8 phase, d, prev_d, c; len = 0; prev_d = phase = 0; for (; joystickmonitor != requestpending; joystickmonitor++) { if (((U8)(*joystickmonitor)) & 0x80) { continue; } d = sysrqreboot[(U8)*joystickmonitor]; if (d != 0xFF) { switch (phase & 0x03) { case 0: phase++; break; case 1: c = (U8)((prev_d << 2) | ((d & 0x30) >> 4)); goto _sharkssl_outstr_c; case 2: c = (U8)(((prev_d & 0xf) << 4) | ((d & 0x3c) >> 2)); goto _sharkssl_outstr_c; case 3: c = (U8)(((prev_d & 0x03) << 6) | d); _sharkssl_outstr_c: if (len < queryinput) { disableevent[len++] = c; } phase++; break; } prev_d = d; } } return len; } #endif #if (SHARKSSL_ENABLE_PEM_API) typedef enum { mmcsd0device = 0, branchinstruction = 1, devicecamera, beforeprobe, unmapdomain } key_enc_type; #define setupfixed 4 #define disablehazard (4 + setupfixed) #define pwrdmclear 4 static U32 clockgettime64(U8 **sourcerouting, const char *statesuspended, U32 pernodememory) { if (pernodememory) { *sourcerouting = (U8*)baMalloc(((U32)(pernodememory * 3) >> 2) + disablehazard); if (*sourcerouting) { #if (4 == setupfixed) *(*sourcerouting+0) = 0x30; *(*sourcerouting+1) = 0x82; #if (disablehazard > setupfixed) memset(*sourcerouting + 2, 0, disablehazard - 2); #else (*sourcerouting)[2] = 0x00; (*sourcerouting)[3] = 0x00; #endif #elif (disablehazard > 0) memset(*sourcerouting, 0, disablehazard); #endif return sharkssl_B64Decode(*sourcerouting + disablehazard, pernodememory, statesuspended, statesuspended+pernodememory); } } return 0; } static sharkssl_PEM_RetVal tcpudpnofold(SharkSslCertKey *disableclock, U8 *sourcerouting, U32 signaldefined) { U16 expLen, modLen; baAssert(signaldefined <= 0xFF); expLen = mousethresh(disableclock->expLen); if (signaldefined) { baAssert((U16)signaldefined >= expLen); gpiolibbanka(disableclock->expLen, signaldefined); signaldefined -= expLen; } *sourcerouting++ = (U8)(disableclock->expLen >> 8); *sourcerouting++ = (U8)disableclock->expLen; *sourcerouting++ = (U8)(disableclock->modLen >> 8); *sourcerouting++ = (U8)disableclock->modLen; memset(sourcerouting, 0, signaldefined); sourcerouting += signaldefined; memmove(sourcerouting, disableclock->exp, expLen); sourcerouting += expLen; modLen = loaderbinfmt(disableclock->modLen, disableclock->expLen); #if SHARKSSL_USE_ECC if (machinereboot(disableclock->expLen)) { memmove(sourcerouting, disableclock->mod, modLen << 1); } else #endif { memmove(sourcerouting, disableclock->mod, modLen); } return SHARKSSL_PEM_OK; } int sharkssl_PEM_getSeqVersion(SharkSslParseASN1 *sharkrestart, U32 len) { int l = SharkSslParseASN1_getSequence(sharkrestart); if ((l < 0) || ((U32)l > len)) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } l = SharkSslParseASN1_getInt(sharkrestart); if ((l < 0) || (sharkrestart->datalen != 1)) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } return *sharkrestart->dataptr; } #if SHARKSSL_USE_ECC static sharkssl_PEM_RetVal mmcsd1device(SharkSslParseASN1 *sharkrestart, SharkSslCertKey *disableclock) { int l; if (SharkSslParseASN1_getOID(sharkrestart) < 0) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } l = SharkSslParseASN1_getCurveID(sharkrestart); baAssert(l <= 0xFF); if (SHARKSSL_EC_CURVE_ID_UNKNOWN == (U8)l) { return SHARKSSL_PEM_KEY_UNSUPPORTED_FORMAT; } disableclock->modLen = 0; nomsrnoirq(disableclock->modLen, (U8)l); return SHARKSSL_PEM_OK; } static sharkssl_PEM_RetVal countslave(SharkSslParseASN1 *sharkrestart, SharkSslCertKey *disableclock) { U32 softirqclear; if (!coupledexynos(disableclock->expLen)) { if (SharkSslParseASN1_getECPublicKey(sharkrestart) < 0) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } } if (SharkSslParseASN1_getBitString(sharkrestart) < 0) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } while ((0 == *(sharkrestart->dataptr)) && (sharkrestart->datalen)) { sharkrestart->dataptr++; sharkrestart->datalen--; } if (0 == sharkrestart->datalen) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } sharkrestart->datalen--; if (SHARKSSL_EC_POINT_UNCOMPRESSED != *sharkrestart->dataptr++) { return SHARKSSL_PEM_KEY_UNSUPPORTED_FORMAT; } disableclock->mod = sharkrestart->dataptr; softirqclear = sharkrestart->datalen >> 1; if ((sharkrestart->datalen & 1) || (softirqclear != (U16)controllerregister(wakeupenable(disableclock->modLen)))) { return SHARKSSL_PEM_KEY_WRONG_LENGTH; } baAssert(softirqclear <= 0xFF); dcdc1consumers(disableclock->modLen, (U8)softirqclear); return SHARKSSL_PEM_OK; } #endif #if SHARKSSL_ENABLE_RSA static sharkssl_PEM_RetVal signalinject(SharkSslParseASN1 *sharkrestart, SharkSslCertKey *disableclock) { if (SharkSslParseASN1_getInt(sharkrestart) < 0) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } disableclock->mod = sharkrestart->dataptr; disableclock->modLen = (U16)sharkrestart->datalen; if (disableclock->modLen & 0x1F) { return SHARKSSL_PEM_KEY_UNSUPPORTED_FORMAT; } if ((disableclock->modLen < 0x040) || (disableclock->modLen > 0x200)) { return SHARKSSL_PEM_KEY_UNSUPPORTED_MODULUS_LENGTH; } if (SharkSslParseASN1_getInt(sharkrestart) < 0) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } disableclock->exp = sharkrestart->dataptr; disableclock->expLen = (U16)sharkrestart->datalen; if (disableclock->expLen > 0xF0) { return SHARKSSL_PEM_KEY_UNSUPPORTED_EXPONENT_LENGTH; } return SHARKSSL_PEM_OK; } #endif #if (SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT || (SHARKSSL_USE_MD5 && (SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256))) static sharkssl_PEM_RetVal pwrdmdisable(U8 *out, U8 *in, U32 len, U8 *pcmciascoop, U8 *iv, U32 loongson3priority, key_enc_type debugpreserved) { #if ((SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256) && SHARKSSL_ENABLE_AES_CBC) union { SharkSslAesCtx aesCtx; } decCtx; if ((devicecamera == debugpreserved) || (beforeprobe == debugpreserved)) { if (len & 0xF) { return SHARKSSL_PEM_KEY_WRONG_LENGTH; } if (loongson3priority != 16) { return SHARKSSL_PEM_KEY_WRONG_IV; } SharkSslAesCtx_constructor(&(decCtx.aesCtx), SharkSslAesCtx_Decrypt, pcmciascoop, ((debugpreserved == devicecamera) ? 16 : 32)); SharkSslAesCtx_cbc_decrypt(&(decCtx.aesCtx), iv, in, in, (U16)len); SharkSslAesCtx_destructor(&(decCtx.aesCtx)); } else { return SHARKSSL_PEM_KEY_UNSUPPORTED_ENCRYPTION_TYPE; } if (out != in) { memmove(out, in, len); } return SHARKSSL_PEM_OK; #else (void)out; (void)in; (void)len; (void)pcmciascoop; (void)iv; (void)loongson3priority; (void)debugpreserved; return SHARKSSL_PEM_KEY_UNSUPPORTED_ENCRYPTION_TYPE; #endif } #endif #if (SHARKSSL_USE_MD5 && (SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256)) static U8 pxa270baseboard(U8 c) { return (U8)((c >= '\101') ? (0xA + c - '\101') : (c - '\060')); } #endif static sharkssl_PEM_RetVal debugmonitors(const char *pxa270flash, key_enc_type debugpreserved, U8 *ptr, U32 len, const char *registerguest, U8 fixupbridge) { #if (SHARKSSL_USE_MD5 && (SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256)) SharkSslMd5Ctx md5Ctx; U8 softresetcomplete[16], pcmciascoop[32], i; fixupbridge >>= 1; if (fixupbridge > SHARKSSL_DIM_ARR(softresetcomplete)) { return SHARKSSL_PEM_KEY_WRONG_LENGTH; } for (i = 0; i < fixupbridge; i++) { softresetcomplete[i] = pxa270baseboard(*registerguest++); softresetcomplete[i] <<= 4; softresetcomplete[i] |= pxa270baseboard(*registerguest++); } SharkSslMd5Ctx_constructor(&md5Ctx); SharkSslMd5Ctx_append(&md5Ctx, (const U8*)pxa270flash, (U32)strlen(pxa270flash)); SharkSslMd5Ctx_append(&md5Ctx, (const U8*)softresetcomplete, 8 ); SharkSslMd5Ctx_finish(&md5Ctx, &pcmciascoop[0]); SharkSslMd5Ctx_constructor(&md5Ctx); SharkSslMd5Ctx_append(&md5Ctx, &pcmciascoop[0], SHARKSSL_MD5_HASH_LEN); SharkSslMd5Ctx_append(&md5Ctx, (const U8*)pxa270flash, (U32)strlen(pxa270flash)); SharkSslMd5Ctx_append(&md5Ctx, (const U8*)softresetcomplete, 8 ); SharkSslMd5Ctx_finish(&md5Ctx, &pcmciascoop[SHARKSSL_MD5_HASH_LEN]); return pwrdmdisable(ptr, ptr, len, pcmciascoop, softresetcomplete, fixupbridge, debugpreserved); #else (void)pxa270flash; (void)debugpreserved; (void)ptr; (void)len; (void)registerguest; (void)fixupbridge; return SHARKSSL_PEM_KEY_UNSUPPORTED_ENCRYPTION_TYPE; #endif } #if SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT SHARKSSL_API int sharkssl_PEM_PBKDF2(U8 *dk, const char *pxa270flash, const char *softresetcomplete, U32 singleftoui, U32 syskeyunlock, U16 registerioapic, U8 configwrite) { SharkSslHMACCtx registermcasp; U8 handledomain[4], chargerplatform[SHARKSSL_MAX_HASH_LEN]; U32 i; U16 usb11device, ftraceupdate, j; baAssert(pxa270flash); ftraceupdate = sharkssl_getHashLen(configwrite); if (0 == ftraceupdate) { return -1; } handledomain[0] = 0; handledomain[1] = 0; handledomain[2] = 0; handledomain[3] = 1; for (;;) { SharkSslHMACCtx_constructor(®istermcasp, configwrite, (const U8*)pxa270flash, (U16)strlen(pxa270flash)); SharkSslHMACCtx_append(®istermcasp, (const U8*)softresetcomplete, singleftoui); SharkSslHMACCtx_append(®istermcasp, handledomain, 4); SharkSslHMACCtx_finish(®istermcasp, chargerplatform); usb11device = (ftraceupdate >= registerioapic) ? ftraceupdate : registerioapic; memcpy(dk, chargerplatform, usb11device); for (i = 1; i < syskeyunlock; i++) { SharkSslHMACCtx_constructor(®istermcasp, configwrite, (const U8*)pxa270flash, (U16)strlen(pxa270flash)); SharkSslHMACCtx_append(®istermcasp, chargerplatform, ftraceupdate); SharkSslHMACCtx_finish(®istermcasp, chargerplatform); for (j = 0; j < usb11device; j++) { dk[j] ^= chargerplatform[j]; } } if (registerioapic > ftraceupdate) { registerioapic -= ftraceupdate; dk += ftraceupdate; if (0 == ++handledomain[3]) { if (0 == ++handledomain[2]) { if (0 == ++handledomain[1]) { handledomain[0]++; } } } } else { break; } } return 0; } #endif static sharkssl_PEM_RetVal clusterpower(const char *logicpwrst, const char *pxa270flash, SharkSslCert *psizecompute) { SharkSslParseASN1 sharkrestart; SharkSslCertKey disableclock; const char *statesuspended, *requestresources, *vectoraddress, *kaux, *kenc; int l; U32 pernodememory; U8 *sourcerouting; int loongson3priority = 0; key_enc_type debugpreserved = mmcsd0device; baAssert(NULL == (void*)0); *psizecompute = 0; if (logicpwrst == NULL) { return SHARKSSL_PEM_KEY_REQUIRED; } statesuspended = sharkStrstr(logicpwrst, "\055\055\055\055\055\102\105\107\111\116\040"); if (NULL != statesuspended) { statesuspended += 11; vectoraddress = sharkStrstr(statesuspended, "\040\113\105\131\055\055\055\055\055"); if (NULL != vectoraddress) { vectoraddress += 9; while (('\015' == *vectoraddress) || ('\012' == *vectoraddress)) { vectoraddress++; } requestresources = sharkStrstr(vectoraddress, "\055\055\055\055\055\105\116\104\040"); if ((NULL != requestresources) && (vectoraddress < requestresources)) { kaux = sharkStrstr(statesuspended, "\120\122\111\126\101\124\105"); if (NULL == kaux) { if (NULL == sharkStrstr(statesuspended, "\120\125\102\114\111\103")) { return SHARKSSL_PEM_KEY_UNRECOGNIZED_FORMAT; } pernodememory = clockgettime64(&sourcerouting, vectoraddress, (U32)(requestresources - vectoraddress)); if (0 == pernodememory) { return SHARKSSL_PEM_ALLOCATION_ERROR; } sharkrestart.len = pernodememory; sharkrestart.ptr = sourcerouting + disablehazard; #if SHARKSSL_ENABLE_RSA if (NULL != sharkStrstr(statesuspended, "\122\123\101\040\120\125\102\114\111\103")) { goto _key_parse_RSA_pub; } #endif l = SharkSslParseASN1_getSequence(&sharkrestart); if ((l < 0) || ((U32)l > pernodememory)) { _key_parse_error: baFree(sourcerouting); return SHARKSSL_PEM_KEY_PARSE_ERROR; } if ((SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getOID(&sharkrestart) < 0)) { goto _key_parse_error; } l = SharkSslParseASN1_getAlgoID(&sharkrestart); #if SHARKSSL_ENABLE_RSA if (ALGO_ID_RSA_ENCRYPTION == l) { if (SharkSslParseASN1_getBitString(&sharkrestart) < 0) { goto _key_parse_error; } sharkrestart.ptr = sharkrestart.dataptr; sharkrestart.len = sharkrestart.datalen; if ((0 == *(sharkrestart.ptr)) && (sharkrestart.len > 0)) { sharkrestart.ptr++; sharkrestart.len--; } _key_parse_RSA_pub: if (SharkSslParseASN1_getSequence(&sharkrestart) < 0) { goto _key_parse_error; } l = signalinject(&sharkrestart, &disableclock); if (SHARKSSL_PEM_OK != l) { baFree(sourcerouting); return (sharkssl_PEM_RetVal)l; } specialmapping(disableclock.expLen); pernodememory = claimresource(mousethresh(disableclock.expLen)); } else #endif #if SHARKSSL_USE_ECC if (ALGO_OID_EC_PUBLIC_KEY == l) { disableclock.expLen = 0; disableclock.exp = NULL; deltaticks(disableclock.expLen); l = mmcsd1device(&sharkrestart, &disableclock); if (SHARKSSL_PEM_OK == l) { l = countslave(&sharkrestart, &disableclock); } if (SHARKSSL_PEM_OK != l) { baFree(sourcerouting); return (sharkssl_PEM_RetVal)l; } pernodememory = 0; } else #endif { goto _key_parse_error; } l = tcpudpnofold(&disableclock, sourcerouting + setupfixed, pernodememory); if (SHARKSSL_PEM_OK != l) { baFree(sourcerouting); return (sharkssl_PEM_RetVal)l; } *psizecompute = (SharkSslCert)sourcerouting; return SHARKSSL_PEM_OK_PUBLIC; } if (kaux < vectoraddress) { kenc = strstr(statesuspended, "\105\116\103\122\131\120\124\105\104"); if ((NULL == kenc) || (kenc > vectoraddress)) { if (NULL != kenc) { if (NULL == pxa270flash) { return SHARKSSL_PEM_KEY_PASSPHRASE_REQUIRED; } #if ((SHARKSSL_USE_AES_256 || SHARKSSL_USE_AES_128) && SHARKSSL_ENABLE_AES_CBC) kenc += 9; #endif #if (SHARKSSL_USE_AES_256 && SHARKSSL_ENABLE_AES_CBC) kaux = sharkStrstr(kenc, "\101\105\123\055\062\065\066\055\103\102\103"); if (kaux) { kaux += 11; debugpreserved = beforeprobe; } else #endif { #if (SHARKSSL_USE_AES_128 && SHARKSSL_ENABLE_AES_CBC) kaux = sharkStrstr(kenc, "\101\105\123\055\061\062\070\055\103\102\103"); if (kaux) { kaux += 11; debugpreserved = devicecamera; } else #endif { #if 0 kaux = sharkStrstr(kenc, "\103\150\141\103\150\141\062\060"); if (kaux) { kaux += 8; debugpreserved = unmapdomain; } else #endif { return SHARKSSL_PEM_KEY_UNSUPPORTED_ENCRYPTION_TYPE; } } } #if ((SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256) && SHARKSSL_ENABLE_AES_CBC) if ('\054' != *kaux++) { return SHARKSSL_PEM_KEY_UNRECOGNIZED_FORMAT; } vectoraddress = kaux; while (('\015' != *vectoraddress) && ('\012' != *vectoraddress)) { if (((*vectoraddress < '\101') || (*vectoraddress > '\106')) && ((*vectoraddress < '\060') || (*vectoraddress > '\071'))) { return SHARKSSL_PEM_KEY_WRONG_IV; } vectoraddress++; } loongson3priority = (int)(vectoraddress - kaux); if (0 || #if (SHARKSSL_USE_AES_128 || SHARKSSL_USE_AES_256) ((loongson3priority != 0x20) && ((devicecamera == debugpreserved) || (beforeprobe == debugpreserved))) || #endif 0) { return SHARKSSL_PEM_KEY_WRONG_IV; } while (('\015' == *vectoraddress) || ('\012' == *vectoraddress)) { vectoraddress++; } #endif } pernodememory = clockgettime64(&sourcerouting, vectoraddress, (U32)(requestresources - vectoraddress)); if (0 == pernodememory) { return SHARKSSL_PEM_ALLOCATION_ERROR; } sharkrestart.len = pernodememory; sharkrestart.ptr = sourcerouting + disablehazard; #if SHARKSSL_ENABLE_RSA if (statesuspended == sharkStrstr(statesuspended, "\122\123\101\040\120\122\111\126\101\124\105")) { if (NULL != kenc) { l = debugmonitors(pxa270flash, debugpreserved, sharkrestart.ptr, sharkrestart.len, kaux, (U8)loongson3priority); if (SHARKSSL_PEM_OK != l) { goto _RSA_RetVal_not_OK; } } _key_parse_RSA_priv: if (sharkssl_PEM_getSeqVersion(&sharkrestart, pernodememory) < 0) { goto _key_parse_error; } l = signalinject(&sharkrestart, &disableclock); if (SHARKSSL_PEM_OK != l) { _RSA_RetVal_not_OK: baFree(sourcerouting); return (sharkssl_PEM_RetVal)l; } if (SharkSslParseASN1_getInt(&sharkrestart) < 0) { goto _key_parse_error; } cryptoresources(disableclock.expLen); pernodememory = claimresource(mousethresh(disableclock.expLen)); l = tcpudpnofold(&disableclock, sourcerouting + setupfixed, pernodememory); if (SHARKSSL_PEM_OK != l) { goto _RSA_RetVal_not_OK; } pernodememory = supportedvector(disableclock.modLen); kaux = (char*)(sourcerouting + setupfixed + pwrdmclear + mousethresh(disableclock.expLen) + pernodememory); baAssert((U8*)kaux <= sharkrestart.ptr); pernodememory >>= 1; for (l = 5; l > 0; l--) { if ((SharkSslParseASN1_getInt(&sharkrestart) < 0) || (sharkrestart.datalen > pernodememory)) { goto _key_parse_error; } if (sharkrestart.datalen < pernodememory) { memset((U8*)kaux, 0, (U16)(pernodememory - sharkrestart.datalen)); kaux += (U16)(pernodememory - sharkrestart.datalen); } memmove((U8*)kaux, sharkrestart.dataptr, sharkrestart.datalen); kaux += sharkrestart.datalen; } *psizecompute = (SharkSslCert)sourcerouting; return SHARKSSL_PEM_OK; } else #endif #if SHARKSSL_USE_ECC if (statesuspended == sharkStrstr(statesuspended, "\105\103\040\120\101\122\101\115\105\124\105\122\123")) { statesuspended = sharkStrstr(statesuspended, "\105\103\040\120\122\111\126\101\124\105"); if (NULL == statesuspended) { l = SHARKSSL_PEM_KEY_UNRECOGNIZED_FORMAT; goto _EC_RetVal_not_OK; } } if (statesuspended == sharkStrstr(statesuspended, "\105\103\040\120\122\111\126\101\124\105")) { if (NULL != kenc) { l = debugmonitors(pxa270flash, debugpreserved, sharkrestart.ptr, sharkrestart.len, kaux, (U8)loongson3priority); if (SHARKSSL_PEM_OK != l) { goto _EC_RetVal_not_OK; } } kaux = NULL; _key_parse_EC_priv: if (sharkssl_PEM_getSeqVersion(&sharkrestart, pernodememory) != 1) { baFree(sourcerouting); return SHARKSSL_PEM_KEY_UNSUPPORTED_VERSION; } if (SharkSslParseASN1_getOctetString(&sharkrestart) < 0) { goto _key_parse_error; } disableclock.exp = sharkrestart.dataptr; disableclock.expLen = (U8)sharkrestart.datalen; baAssert(disableclock.expLen <= 0xFF); hsspidevice(disableclock.expLen); if (NULL == kaux) { if (SharkSslParseASN1_getECParameters(&sharkrestart) < 0) { goto _key_parse_error; } l = mmcsd1device(&sharkrestart, &disableclock); if (SHARKSSL_PEM_OK != l) { _EC_RetVal_not_OK: baFree(sourcerouting); return (sharkssl_PEM_RetVal)l; } } l = countslave(&sharkrestart, &disableclock); if (SHARKSSL_PEM_OK != l) { goto _EC_RetVal_not_OK; } l = tcpudpnofold(&disableclock, sourcerouting + setupfixed, 0); if (SHARKSSL_PEM_OK != l) { goto _EC_RetVal_not_OK; } *psizecompute = (SharkSslCert)sourcerouting; return SHARKSSL_PEM_OK; } else #endif if (NULL == kenc) { if (statesuspended == kaux) { #if (SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT && SHARKSSL_ENABLE_AES_CBC) _plain_PKCS8_parsing: #endif if (sharkssl_PEM_getSeqVersion(&sharkrestart, pernodememory) < 0) { goto _key_parse_error; } if ((SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getOID(&sharkrestart) < 0)) { goto _key_parse_error; } l = SharkSslParseASN1_getAlgoID(&sharkrestart); #if SHARKSSL_ENABLE_RSA if (ALGO_ID_RSA_ENCRYPTION == l) { if (SharkSslParseASN1_getOctetString(&sharkrestart) < 0) { goto _key_parse_error; } sharkrestart.ptr = sharkrestart.dataptr; sharkrestart.len = sharkrestart.datalen; goto _key_parse_RSA_priv; } else #endif #if SHARKSSL_USE_ECC if (ALGO_OID_EC_PUBLIC_KEY == l) { if (SharkSslParseASN1_getOID(&sharkrestart) < 0) { return SHARKSSL_PEM_KEY_PARSE_ERROR; } l = SharkSslParseASN1_getCurveID(&sharkrestart); baAssert(l <= 0xFF); if (SHARKSSL_EC_CURVE_ID_UNKNOWN == (U8)l) { return SHARKSSL_PEM_KEY_UNSUPPORTED_FORMAT; } if (SharkSslParseASN1_getOctetString(&sharkrestart) < 0) { goto _key_parse_error; } disableclock.modLen = 0; nomsrnoirq(disableclock.modLen, (U8)l); sharkrestart.ptr = sharkrestart.dataptr; sharkrestart.len = sharkrestart.datalen; baAssert(kaux); goto _key_parse_EC_priv; } else #endif goto _key_parse_error; } } } else if (kenc == statesuspended) { #if SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT #if ((!SHARKSSL_USE_SHA_256) || (!SHARKSSL_ENABLE_AES_CBC)) #error SHARKSSL_ENABLE_ENCRYPTED_PKCS8_SUPPORT requires SHARKSSL_USE_SHA_256 and SHARKSSL_ENABLE_AES_CBC #endif if (NULL == pxa270flash) { return SHARKSSL_PEM_KEY_PASSPHRASE_REQUIRED; } pernodememory = clockgettime64(&sourcerouting, vectoraddress, (U32)(requestresources - vectoraddress)); if (0 == pernodememory) { return SHARKSSL_PEM_ALLOCATION_ERROR; } sharkrestart.len = pernodememory; sharkrestart.ptr = sourcerouting + disablehazard; l = SharkSslParseASN1_getSequence(&sharkrestart); if ((l < 0) || ((U32)l > pernodememory)) { goto _key_parse_error; } if ((SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getOID(&sharkrestart) < 0)) { goto _key_parse_error; } if (ALGO_ID_PKCS5_PBES2 != SharkSslParseASN1_getAlgoID(&sharkrestart)) { _key_unsupported_enctype: baFree(sourcerouting); return SHARKSSL_PEM_KEY_UNSUPPORTED_ENCRYPTION_TYPE; } if ((SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getOID(&sharkrestart) < 0)) { goto _key_parse_error; } if (ALGO_ID_PKCS5_PBKDF2 != SharkSslParseASN1_getAlgoID(&sharkrestart)) { goto _key_unsupported_enctype; } if ((SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getOctetString(&sharkrestart) < 0)) { goto _key_parse_error; } loongson3priority = sharkrestart.datalen; kaux = (const char*)sharkrestart.dataptr; if (loongson3priority > 16) { _key_unsupported_format: baFree(sourcerouting); return SHARKSSL_PEM_KEY_UNSUPPORTED_FORMAT; } if (SharkSslParseASN1_getInt(&sharkrestart) < 0) { goto _key_parse_error; } if (sharkrestart.datalen > 4) { goto _key_unsupported_format; } pernodememory = 0; while (sharkrestart.datalen--) { pernodememory <<= 8; pernodememory |= *sharkrestart.dataptr++; } if ((SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getOID(&sharkrestart) < 0)) { goto _key_parse_error; } l = SharkSslParseASN1_getAlgoID(&sharkrestart); #if SHARKSSL_USE_SHA_256 if (ALGO_ID_HMAC_WITH_SHA256 != l) #endif { goto _key_unsupported_enctype; } if (sharkssl_PEM_PBKDF2(sourcerouting + disablehazard, pxa270flash, kaux, loongson3priority, pernodememory, 32, GET_ALGO_HASH_ID(l))) { baFree(sourcerouting); return SHARKSSL_PEM_INTERNAL_ERROR; } if ((SharkSslParseASN1_getSequence(&sharkrestart) < 0) || (SharkSslParseASN1_getOID(&sharkrestart) < 0)) { goto _key_parse_error; } l = SharkSslParseASN1_getAlgoID(&sharkrestart); #if SHARKSSL_ENABLE_AES_CBC #if SHARKSSL_USE_AES_128 if (ALGO_ID_AES_128_CBC == l) { debugpreserved = devicecamera; } else #endif #if SHARKSSL_USE_AES_256 if (ALGO_ID_AES_256_CBC == l) { debugpreserved = beforeprobe; } else #endif #endif { goto _key_unsupported_enctype; } #if SHARKSSL_ENABLE_AES_CBC if (SharkSslParseASN1_getOctetString(&sharkrestart) < 0) { goto _key_parse_error; } loongson3priority = sharkrestart.datalen; kaux = (const char*)sharkrestart.dataptr; if (SharkSslParseASN1_getOctetString(&sharkrestart) < 0) { goto _key_parse_error; } sharkrestart.ptr = sourcerouting + disablehazard; sharkrestart.len = sharkrestart.datalen; l = pwrdmdisable(sharkrestart.ptr, sharkrestart.dataptr, sharkrestart.datalen, sourcerouting + disablehazard, (U8*)kaux, loongson3priority, debugpreserved); if (SHARKSSL_PEM_OK != l) { baFree(sourcerouting); return (sharkssl_PEM_RetVal)l; } goto _plain_PKCS8_parsing; #endif #else return SHARKSSL_PEM_KEY_UNSUPPORTED_FORMAT; #endif } } } } } return SHARKSSL_PEM_KEY_UNRECOGNIZED_FORMAT; } static sharkssl_PEM_RetVal cpuidledevice(const char **begin, const char **end) { *begin = sharkStrstr(*begin, "\055\055\055\055\055\102\105\107\111\116"); if (*begin) { *begin = sharkStrstr(*begin, "\103\105\122\124\111\106\111\103\101\124\105\055\055\055\055\055"); if (NULL == *begin) { return SHARKSSL_PEM_CERT_UNRECOGNIZED_FORMAT; } *begin += 16; while (('\015' == **begin) || ('\012' == **begin)) { (*begin)++; } *end = sharkStrstr(*begin, "\055\055\055\055\055\105\116\104"); if (NULL == *end) { return SHARKSSL_PEM_CERT_UNRECOGNIZED_FORMAT; } } return SHARKSSL_PEM_OK; } SHARKSSL_API sharkssl_PEM_RetVal sharkssl_PEM(const char *allowresize, const char *logicpwrst, const char *pxa270flash, SharkSslCert *psizecompute) { U8 *ptr; const char *cbeg, *cend; sharkssl_PEM_RetVal ret = clusterpower(logicpwrst, pxa270flash, psizecompute); U32 pernodememory = 0; U32 pxafbmodes; U8 rdlo12rdhi16rn0rm8rwflags; #if SHARKSSL_ENABLE_CERT_CHAIN U8 devicerelease; #endif if ((SHARKSSL_PEM_OK_PUBLIC == ret) && (allowresize)) { return SHARKSSL_PEM_KEY_PRIVATE_KEY_REQUIRED; } if (ret >= 0) { pernodememory = SharkSslKey_vectSize((SharkSslKey)*psizecompute); } if ((SHARKSSL_PEM_OK != ret) || (!allowresize)) { if (ret >= 0) { void *devicehandle = baRealloc((void*)*psizecompute, pernodememory); if (devicehandle) { *psizecompute = (SharkSslCert)devicehandle; } } return ret; } cbeg = allowresize; pxafbmodes = 0; #if SHARKSSL_ENABLE_CERT_CHAIN devicerelease = 0; _sharkssl_PEM_scan_next_cert: #endif ret = cpuidledevice(&cbeg, &cend); if (SHARKSSL_PEM_OK != ret) { _sharkssl_PEM_free_ret: baFree((void*)*psizecompute); return ret; } if (cbeg) { if (((U32)(cend - cbeg)) > 0xFFFF) { ret = SHARKSSL_PEM_CERT_UNSUPPORTED_TYPE; goto _sharkssl_PEM_free_ret; } pxafbmodes += (U32)(cend - cbeg); #if SHARKSSL_ENABLE_CERT_CHAIN devicerelease++; cbeg = cend; goto _sharkssl_PEM_scan_next_cert; #endif } else { #if SHARKSSL_ENABLE_CERT_CHAIN if (devicerelease) { devicerelease--; } else #endif { ret = SHARKSSL_PEM_CERT_UNRECOGNIZED_FORMAT; goto _sharkssl_PEM_free_ret; } } ptr = (U8*)baMalloc(((pxafbmodes * 3) >> 2) + pernodememory + SHARKSSL_ALIGNMENT - setupfixed); if (NULL == ptr) { ret = SHARKSSL_PEM_ALLOCATION_ERROR; goto _sharkssl_PEM_free_ret; } cbeg = allowresize; cpuidledevice(&cbeg, &cend); pxafbmodes = sharkssl_B64Decode(ptr, (U32)(cend - cbeg), cbeg, cend); if (pxafbmodes != SharkSslCert_len((SharkSslCert)ptr)) { ret = SHARKSSL_PEM_CERT_UNSUPPORTED_TYPE; baFree(ptr); goto _sharkssl_PEM_free_ret; } rdlo12rdhi16rn0rm8rwflags = (((U8)(~pxafbmodes & 0x3)) + 1) & 0x3; memset(ptr + pxafbmodes, 0xFF, rdlo12rdhi16rn0rm8rwflags); memcpy(ptr + pxafbmodes + rdlo12rdhi16rn0rm8rwflags, *psizecompute + setupfixed, pernodememory - setupfixed); baFree((void*)*psizecompute); *psizecompute = ptr; #if SHARKSSL_ENABLE_CERT_CHAIN if (devicerelease) { ptr = (U8*)*psizecompute + pxafbmodes + rdlo12rdhi16rn0rm8rwflags; *ptr = (*ptr & 0x0F) | ((U8)devicerelease << 4); ptr += pernodememory - setupfixed; while (devicerelease--) { cbeg = cend; cpuidledevice(&cbeg, &cend); pxafbmodes = sharkssl_B64Decode(ptr, (U32)(cend - cbeg), cbeg, cend); if (pxafbmodes != SharkSslCert_len((SharkSslCert)ptr)) { ret = SHARKSSL_PEM_CERT_UNSUPPORTED_TYPE; goto _sharkssl_PEM_free_ret; } ptr += pxafbmodes; } } #endif return SHARKSSL_PEM_OK; } #if ((SHARKSSL_ENABLE_RSA_API || SHARKSSL_ENABLE_ECDSA_API) && \ ((SHARKSSL_SSL_CLIENT_CODE && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) || \ (SHARKSSL_SSL_SERVER_CODE))) SHARKSSL_API SharkSslKey sharkssl_PEM_extractPublicKey_ext(const char *allowresize, U8 *earlyconsole) { SharkSslCertParam certParam; char *cbeg, *cend; U8 *aemifresources, *buttontable; U16 kco, kcoa, pxafbmodes; if (allowresize) { buttontable = NULL; pxafbmodes = (U16)sharkssl_PEM(NULL, allowresize, NULL, (SharkSslCert*)&buttontable); if ((SHARKSSL_PEM_OK == pxafbmodes) || (SHARKSSL_PEM_OK_PUBLIC == pxafbmodes)) { *earlyconsole = (buttontable[4] & mutantchannel); return buttontable; } cbeg = (char*)sharkStrstr(allowresize, "\055\055\055\055\055\102\105\107\111\116"); if (cbeg) { cbeg = sharkStrstr(cbeg, "\103\105\122\124\111\106\111\103\101\124\105\055\055\055\055\055"); } if (cbeg == NULL) { return NULL; } cbeg += 16; while ((*cbeg == '\015') || (*cbeg == '\012')) { cbeg++; } cend = (char*)sharkStrstr(cbeg, "\055\055\055\055\055\105\116\104"); if (cend == NULL) { return NULL; } if (((U32)(cend - cbeg)) > 0xFFFF) { return NULL; } pxafbmodes = (U16)(cend - cbeg); kco = ((U16)(pxafbmodes * 3)) >> 2; } else { return NULL; } aemifresources = (U8*)baMalloc(4 + kco); if (aemifresources == NULL) { return NULL; } kco = (U16)sharkssl_B64Decode(aemifresources, pxafbmodes, cbeg, cend); if ((kco != SharkSslCert_len((SharkSslCert)aemifresources)) || (spromregister(&certParam, aemifresources, kco, 0) < 0)) { sharkssl_PEM_extractPublicKey_1: baFree(aemifresources); return NULL; } kco = kcoa = mousethresh(certParam.certKey.expLen); pxafbmodes = loaderbinfmt(certParam.certKey.modLen, certParam.certKey.expLen); *earlyconsole = allocatoralloc(certParam.certKey.expLen); if (rewindsingle == *earlyconsole) { kcoa = claimresource(kco); certParam.certKey.expLen = (certParam.certKey.expLen & 0xFF00) + kcoa; } #if SHARKSSL_USE_ECC else { baAssert(0 == kco); pxafbmodes *= 2; } #endif kcoa -= kco; buttontable = (U8*)baMalloc(8 + mousethresh(certParam.certKey.expLen) + pxafbmodes); if (buttontable == NULL) { goto sharkssl_PEM_extractPublicKey_1; } cbeg = (char*)buttontable; *cbeg++ = (char)0x30; *cbeg++ = (unsigned char)0x82; *cbeg++ = (char)0x00; *cbeg++ = (char)0x00; *cbeg++ = (char)(certParam.certKey.expLen >> 8); *cbeg++ = (char)(certParam.certKey.expLen & 0xFF); *cbeg++ = (char)(certParam.certKey.modLen >> 8); *cbeg++ = (char)(certParam.certKey.modLen & 0xFF); while (kcoa--) { *cbeg++ = 0; } memcpy(cbeg, certParam.certKey.exp, kco); cbeg += kco; memcpy(cbeg, certParam.certKey.mod, pxafbmodes); baFree(aemifresources); return (SharkSslKey)buttontable; } SHARKSSL_API SharkSslKey sharkssl_PEM_extractPublicKey(const char *allowresize) { U8 earlyconsole; return sharkssl_PEM_extractPublicKey_ext(allowresize, &earlyconsole); } #endif #endif #if SHARKSSL_ENABLE_RSA int omap3430common(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe) { U16 creategroup; baAssert(NULL == (void*)0); baAssert((seepromprobe == SHARKSSL_RSA_NO_PADDING) || (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING)); if ((in == NULL) || (out == NULL) || (disableclock == NULL) || (!(machinekexec(disableclock->expLen)))) { return (int)SHARKSSL_RSA_WRONG_PARAMETERS; } creategroup = supportedvector(disableclock->modLen); #if (SHARKSSL_ENABLE_RSA_PKCS1 || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_SSL_CLIENT_CODE) if (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING) { U16 kl; if (creategroup < 11) { return (int)SHARKSSL_RSA_WRONG_KEY_LENGTH; } if (len > (creategroup - 11)) { return (int)SHARKSSL_RSA_INPUT_DATA_LENGTH_TOO_BIG; } kl = creategroup - len; memmove(out + kl, in, len); in = out; *in++ = 0x00; *in++ = 0x02; kl -= 3; len = (kl & 0x0003); kl &= 0xFFFC; if (sharkssl_rng(in, kl) < 0) { return (int)SHARKSSL_RSA_INTERNAL_ERROR; } in += kl; if (len) { in -= (4 - len); if (sharkssl_rng(in, 4) < 0) { return (int)SHARKSSL_RSA_INTERNAL_ERROR; } in += 4; } *in-- = 0x00; while (in != out) { if (0x00 == *in) { *in = 0x55; } in--; } } else #endif { if (len != creategroup) { return (int)SHARKSSL_RSA_INPUT_DATA_LENGTH_AND_KEY_LENGTH_MISMATCH; } memmove(out, in, len); } if (async3clksrc(disableclock, hsmmcplatform, out)) { return (int)SHARKSSL_RSA_ALLOCATION_ERROR; } return creategroup; } int writemessage(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe) { U16 creategroup; baAssert(NULL == (void*)0); baAssert((seepromprobe == SHARKSSL_RSA_NO_PADDING) || (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING)); if ((in == NULL) || (out == NULL) || (disableclock == NULL) || (!(machinekexec(disableclock->expLen)))) { return (int)SHARKSSL_RSA_WRONG_PARAMETERS; } creategroup = supportedvector(disableclock->modLen); if (0 == creategroup) { return (int)SHARKSSL_RSA_WRONG_KEY_LENGTH; } if (len != creategroup) { return (int)SHARKSSL_RSA_INPUT_DATA_LENGTH_AND_KEY_LENGTH_MISMATCH; } if (async3clksrc(disableclock, sleepstore, in)) { return (int)SHARKSSL_RSA_ALLOCATION_ERROR; } #if (SHARKSSL_ENABLE_RSA_PKCS1 || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_SSL_CLIENT_CODE) if (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING) { if ((*in++ != 0x00) || (*in++ != 0x02)) { return (int)SHARKSSL_RSA_PKCS1_PADDING_ERROR; } creategroup -= 2; while ((--creategroup) && (*in++ != 0x00)) { } if (0 == creategroup) { return (int)SHARKSSL_RSA_PKCS1_PADDING_ERROR; } } #endif memmove(out, in, creategroup); return creategroup; } int clockaccess(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe) { U16 creategroup; baAssert(NULL == (void*)0); baAssert((seepromprobe == SHARKSSL_RSA_NO_PADDING) || (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING)); if ((in == NULL) || (out == NULL) || (disableclock == NULL) || (!(machinekexec(disableclock->expLen)))) { return (int)SHARKSSL_RSA_WRONG_PARAMETERS; } creategroup = supportedvector(disableclock->modLen); #if (SHARKSSL_ENABLE_RSA_PKCS1 || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_SSL_CLIENT_CODE) if (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING) { U16 kl; if (creategroup < 11) { return (int)SHARKSSL_RSA_WRONG_KEY_LENGTH; } if (len >= (creategroup - 11)) { return (int)SHARKSSL_RSA_INPUT_DATA_LENGTH_TOO_BIG; } kl = creategroup - len; memmove(out + kl, in, len); in = out; *in++ = 0x00; *in++ = 0x01; kl -= 3; memset(in, 0xFF, kl); *(in + kl) = 0x00; } else #endif { if (len != creategroup) { return (int)SHARKSSL_RSA_INPUT_DATA_LENGTH_AND_KEY_LENGTH_MISMATCH; } memmove(out, in, len); } if (async3clksrc(disableclock, sleepstore, out)) { return (int)SHARKSSL_RSA_ALLOCATION_ERROR; } return creategroup; } int handleguest(const SharkSslCertKey *disableclock, U16 len, U8 *in, U8 *out, U8 seepromprobe) { U16 creategroup; baAssert(NULL == (void*)0); baAssert((seepromprobe == SHARKSSL_RSA_NO_PADDING) || (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING)); if ((in == NULL) || (out == NULL) || (disableclock == NULL) || (!(machinekexec(disableclock->expLen)))) { return (int)SHARKSSL_RSA_WRONG_PARAMETERS; } creategroup = supportedvector(disableclock->modLen); if (0 == creategroup) { return (int)SHARKSSL_RSA_WRONG_KEY_LENGTH; } if (len != creategroup) { return (int)SHARKSSL_RSA_INPUT_DATA_LENGTH_AND_KEY_LENGTH_MISMATCH; } if (async3clksrc(disableclock, hsmmcplatform, in)) { return (int)SHARKSSL_RSA_ALLOCATION_ERROR; } #if (SHARKSSL_ENABLE_RSA_PKCS1 || SHARKSSL_SSL_SERVER_CODE || SHARKSSL_SSL_CLIENT_CODE) if (seepromprobe == SHARKSSL_RSA_PKCS1_PADDING) { if ((*in++ != 0x00) || (*in++ != 0x01)) { return (int)SHARKSSL_RSA_PKCS1_PADDING_ERROR; } creategroup -= 2; while (--creategroup) { U8 c = *in++; if (c == 0) { break; } else if (c != 0xFF) { return (int)SHARKSSL_RSA_PKCS1_PADDING_ERROR; } } if (0 == creategroup) { return (int)SHARKSSL_RSA_PKCS1_PADDING_ERROR; } } #endif memmove(out, in, creategroup); return creategroup; } #if (SHARKSSL_ENABLE_RSA_API) #if (SHARKSSL_ENABLE_PEM_API) SHARKSSL_API SharkSslRSAKey sharkssl_PEM_to_RSAKey(const char *clearnopref, const char *pxa270flash) { SharkSslCert kernelvaddr; baAssert(NULL == (void*)0); if ((clearnopref == NULL) || (sharkssl_PEM(NULL, clearnopref, pxa270flash, &kernelvaddr) < 0)) { return NULL; } return (SharkSslRSAKey)kernelvaddr; } SHARKSSL_API void SharkSslRSAKey_free(SharkSslRSAKey hsspiregister) { if (hsspiregister) { baFree((void*)hsspiregister); } } #endif SHARKSSL_API U16 SharkSslRSAKey_size(SharkSslRSAKey sourcerouting) { SharkSslCertKey disableclock; baAssert(NULL == (void*)0); if (interrupthandler(&disableclock, (SharkSslCert)sourcerouting)) { if (machinekexec(disableclock.expLen)) { return disableclock.modLen; } } return 0; } typedef int (*SharkSslCertKey_RSA_func)(const SharkSslCertKey*, U16, U8*, U8*, U8); static sharkssl_RSA_RetVal switchcompletion(SharkSslCertKey_RSA_func orderarray, SharkSslRSAKey sourcerouting, int len, const U8 *in, U8 *out, int seepromprobe) { SharkSslCertKey disableclock; if ((in == NULL) || (out == NULL) || (sourcerouting == NULL)) { return SHARKSSL_RSA_WRONG_PARAMETERS; } if (0 == interrupthandler(&disableclock, sourcerouting)) { return SHARKSSL_RSA_WRONG_KEY_FORMAT; } return (sharkssl_RSA_RetVal)orderarray(&disableclock, (U16)len, (U8*)in, out, (U8)seepromprobe); } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_public_encrypt(SharkSslRSAKey setupreset, const U8 *in, int len, U8 *out, int seepromprobe) { return switchcompletion(omap3430common, setupreset, len, in, out, seepromprobe); } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_private_decrypt(SharkSslRSAKey resumeenabler, const U8 *in, int len, U8 *out, int seepromprobe) { return switchcompletion(writemessage, resumeenabler, len, in, out, seepromprobe); } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_private_encrypt(SharkSslRSAKey resumeenabler, const U8 *in, int len, U8 *out, int seepromprobe) { return switchcompletion(clockaccess, resumeenabler, len, in, out, seepromprobe); } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_public_decrypt(SharkSslRSAKey setupreset, const U8 *in, int len, U8 *out, int seepromprobe) { return switchcompletion(handleguest, setupreset, len, in, out, seepromprobe); } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_PKCS1V1_5_sign_hash(SharkSslRSAKey resumeenabler, U8 *sig, U16 *platformconfig, const U8 *chargerplatform, U8 configwrite) { SharkSslSignParam sgp; SharkSslCertKey disableclock; int ret; U16 ftraceupdate = sharkssl_getHashLen(configwrite); if ((0 == ftraceupdate) || (NULL == sig) || (NULL == chargerplatform) || (NULL == platformconfig)) { return SHARKSSL_RSA_WRONG_PARAMETERS; } if ((0 == interrupthandler(&disableclock, resumeenabler)) || !(machinekexec(disableclock.expLen))) { return SHARKSSL_RSA_WRONG_KEY_FORMAT; } if (coupledexynos(disableclock.expLen)) { return SHARKSSL_RSA_KEY_NOT_PRIVATE; } sgp.pCertKey = &disableclock; memcpy(sgp.signature.hash, chargerplatform, ftraceupdate); sgp.signature.hashAlgo = configwrite; sgp.signature.signature = sig; sgp.signature.signatureAlgo = entryearly; ret = checkactions(&sgp); *platformconfig = sgp.signature.signLen; if (0 != ret) { return SHARKSSL_RSA_WRONG_SIGNATURE; } return SHARKSSL_RSA_OK; } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_PKCS1V1_5_verify_hash(SharkSslRSAKey setupreset, U8 *sig, U16 platformconfig, const U8 *chargerplatform, U8 configwrite) { SharkSslSignParam sgp; SharkSslCertKey disableclock; U16 ftraceupdate = sharkssl_getHashLen(configwrite); if ((0 == ftraceupdate) || (NULL == sig) || (NULL == chargerplatform) || (0 == platformconfig)) { return SHARKSSL_RSA_WRONG_PARAMETERS; } if ((0 == interrupthandler(&disableclock, setupreset)) || !(machinekexec(disableclock.expLen))) { return SHARKSSL_RSA_WRONG_KEY_FORMAT; } sgp.pCertKey = &disableclock; memcpy(sgp.signature.hash, chargerplatform, ftraceupdate); sgp.signature.hashAlgo = configwrite; sgp.signature.signature = sig; sgp.signature.signatureAlgo = entryearly; sgp.signature.signLen = platformconfig; if (0 != systemcapabilities(&sgp)) { return SHARKSSL_RSA_VERIFICATION_FAIL; } return SHARKSSL_RSA_OK; } #if SHARKSSL_ENABLE_RSA_OAEP static void aliasstart(U8 *pciercxcfg448, U16 allocskcipher, U8 *src, U16 consolewrite, U8 configwrite) { if (allocskcipher) { U8 *ptr, *dptr, *buf; U16 ftraceupdate, i; ftraceupdate = sharkssl_getHashLen(configwrite); buf = baMalloc(ftraceupdate + consolewrite + 4); if (buf) { dptr = buf + ftraceupdate; memcpy(dptr, src, consolewrite); ptr = dptr + consolewrite; hsotgpdata(0, ptr, 0); consolewrite += 4; for (;;) { sharkssl_hash(buf, dptr, consolewrite, configwrite); if (allocskcipher < ftraceupdate) { ftraceupdate = (U8)allocskcipher; } for (i = 0; i < ftraceupdate; i++) { *pciercxcfg448++ ^= buf[i]; } allocskcipher -= ftraceupdate; if (allocskcipher) { U32 requestflags; read64uint32(requestflags, ptr, 0); requestflags++; inputlevel(requestflags, ptr, 0); } else { break; } } memset(buf, 0, ftraceupdate + consolewrite); baFree(buf); } } } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_private_decrypt_OAEP(SharkSslRSAKey resumeenabler, U8 *in, int len, U8 configwrite, U8 *out, const char *clkdmoperations, U16 auxdatalookup) { int ret; U16 ftraceupdate, i; ftraceupdate = sharkssl_getHashLen(configwrite); if ((U32)len > 0x0000FFFF) { return SHARKSSL_RSA_INPUT_DATA_LENGTH_TOO_BIG; } ret = (int)switchcompletion(writemessage, resumeenabler, (U16)len, in, in, SHARKSSL_RSA_NO_PADDING); if (ftraceupdate == 0) { ret = SHARKSSL_RSA_WRONG_PARAMETERS; } else if (ret < (2 * ftraceupdate + 2)) { ret = SHARKSSL_RSA_WRONG_KEY_LENGTH; } else { int PSLen, buttonsbuffalo; U8 logicstate[SHARKSSL_MAX_HASH_LEN], *ptr, sum, flg; aliasstart(&in[1], ftraceupdate, &in[1 + ftraceupdate], (U16)ret - ftraceupdate - 1, configwrite); aliasstart(&in[ftraceupdate + 1], (U16)ret - ftraceupdate - 1, &in[1], ftraceupdate, configwrite); if (0 != sharkssl_hash(logicstate, (U8*)clkdmoperations, auxdatalookup, configwrite)) { return SHARKSSL_RSA_WRONG_LABEL_LENGTH; } ptr = in; sum = *ptr++; ret--; ptr += ftraceupdate; ret -= (ftraceupdate << 1); for (i = 0; ftraceupdate--; i++) { sum |= *ptr++ ^ logicstate[i]; } buttonsbuffalo = ret; flg = 0; in = ptr; PSLen = 0; while (--buttonsbuffalo) { flg |= *in++; PSLen += (~flg) & 0x01; } if (PSLen >= ret) { return SHARKSSL_RSA_PKCS1_PADDING_ERROR; } ret -= PSLen; ptr += PSLen; sum |= *ptr++ ^ 0x01; if ((0 == ret) || (sum)) { return SHARKSSL_RSA_PKCS1_PADDING_ERROR; } ret--; memcpy(out, ptr, ret); memset(logicstate, 0, SHARKSSL_DIM_ARR(logicstate)); } return (sharkssl_RSA_RetVal)ret; } SHARKSSL_API sharkssl_RSA_RetVal sharkssl_RSA_public_encrypt_OAEP(SharkSslRSAKey setupreset, const U8 *in, int len, U8 configwrite, U8 *out, const char *clkdmoperations, U16 auxdatalookup) { int ret; U16 ftraceupdate, h2Len; ftraceupdate = sharkssl_getHashLen(configwrite); h2Len = (ftraceupdate * 2) + 2; ret = SharkSslRSAKey_size(setupreset); if (ftraceupdate == 0) { ret = SHARKSSL_RSA_WRONG_PARAMETERS; } else if (ret == 0) { ret = SHARKSSL_RSA_WRONG_KEY_FORMAT; } else if (ret < h2Len) { ret = SHARKSSL_RSA_WRONG_KEY_LENGTH; } else if (((U32)len > 0x0000FFFF) || ((U16)len > (ret - h2Len))) { ret = SHARKSSL_RSA_INPUT_DATA_LENGTH_TOO_BIG; } else { U8 *ptr = out; *ptr++ = 0x00; sharkssl_rng(ptr, ftraceupdate); ptr += ftraceupdate; if (0 != sharkssl_hash(ptr, (U8*)clkdmoperations, auxdatalookup, configwrite)) { return SHARKSSL_RSA_WRONG_LABEL_LENGTH; } ptr += ftraceupdate; h2Len = (U16)ret - h2Len - (U16)len; memset(ptr, 0, h2Len); ptr += h2Len; *ptr++ = 0x01; memcpy(ptr, in, len); aliasstart(&out[ftraceupdate + 1], (U16)ret - ftraceupdate - 1, &out[1], ftraceupdate, configwrite); aliasstart(&out[1], ftraceupdate, &out[1 + ftraceupdate], (U16)ret - ftraceupdate - 1, configwrite); ret = (int)switchcompletion(omap3430common, setupreset, (U16)ret, out, out, SHARKSSL_RSA_NO_PADDING); } return (sharkssl_RSA_RetVal)ret; } #endif #endif #endif #if SHARKSSL_USE_ECC #if (SHARKSSL_ENABLE_PEM_API) SHARKSSL_API SharkSslECCKey sharkssl_PEM_to_ECCKey(const char *clearnopref, const char *pxa270flash) { SharkSslCert kernelvaddr; baAssert(NULL == (void*)0); if ((clearnopref == NULL) || (sharkssl_PEM(NULL, clearnopref, pxa270flash, &kernelvaddr) < 0)) { return NULL; } return (SharkSslECCKey)kernelvaddr; } #endif #if (SHARKSSL_ENABLE_PEM_API || SHARKSSL_ENABLE_ECCKEY_CREATE) SHARKSSL_API void SharkSslECCKey_free(SharkSslECCKey dividetable) { if (dividetable) { baFree((void*)dividetable); } } #endif #if (SHARKSSL_ENABLE_ECDSA && SHARKSSL_ENABLE_ECDSA_API) #if (!SHARKSSL_ECDSA_ONLY_VERIFY) U16 relocationchain(SharkSslCertKey *disableclock) { U16 len = mousethresh(disableclock->expLen); if (len && (len < 0x70)) { len <<= 1; len += 8; #if SHARKSSL_ECC_USE_SECP521R1 if (len >= 0x80) { len++; } #endif return len; } return 0; } SHARKSSL_API U16 sharkssl_ECDSA_siglen(SharkSslECCKey resumeenabler) { SharkSslCertKey disableclock; if ((interrupthandler(&disableclock, resumeenabler)) && (machinereboot(disableclock.expLen)) && !(coupledexynos(disableclock.expLen))) { return relocationchain(&disableclock); } return 0; } SHARKSSL_API sharkssl_ECDSA_RetVal sharkssl_ECDSA_sign_hash(SharkSslECCKey resumeenabler, U8 *sig, U16 *platformconfig, const U8 *chargerplatform, U8 configwrite) #if 0 { SharkSslCertKey disableclock; SharkSslECDSAParam audioshutdown; sharkssl_ECDSA_RetVal ret; if ((NULL == sig) || (NULL == chargerplatform) || (NULL == platformconfig)) { return SHARKSSL_ECDSA_WRONG_PARAMETERS; } if ((0 == interrupthandler(&disableclock, resumeenabler)) || !(machinereboot(disableclock.expLen))) { return SHARKSSL_ECDSA_WRONG_KEY_FORMAT; } if (coupledexynos(disableclock.expLen)) { return SHARKSSL_ECDSA_KEY_NOT_PRIVATE; } audioshutdown.hashLen = sharkssl_getHashLen(configwrite); if (0 == audioshutdown.hashLen) { return SHARKSSL_ECDSA_WRONG_PARAMETERS; } audioshutdown.curveType = wakeupenable(disableclock.modLen); audioshutdown.hash = (U8*)chargerplatform; audioshutdown.key = disableclock.exp; audioshutdown.keyLen = mousethresh(disableclock.expLen); ret = registerboard(&audioshutdown, sig, platformconfig); if (ret < 0) { return ret; } return SHARKSSL_ECDSA_OK; } #else { SharkSslSignParam sgp; SharkSslCertKey disableclock; int ret; U16 ftraceupdate = sharkssl_getHashLen(configwrite); if ((0 == ftraceupdate) || (NULL == sig) || (NULL == chargerplatform) || (NULL == platformconfig)) { return SHARKSSL_ECDSA_WRONG_PARAMETERS; } if ((0 == interrupthandler(&disableclock, resumeenabler)) || !(machinereboot(disableclock.expLen))) { return SHARKSSL_ECDSA_WRONG_KEY_FORMAT; } if (coupledexynos(disableclock.expLen)) { return SHARKSSL_ECDSA_KEY_NOT_PRIVATE; } sgp.pCertKey = &disableclock; memcpy(sgp.signature.hash, chargerplatform, ftraceupdate); sgp.signature.hashAlgo = configwrite; sgp.signature.signature = sig; sgp.signature.signatureAlgo = accessactive; ret = checkactions(&sgp); *platformconfig = sgp.signature.signLen; if (0 != ret) { return SHARKSSL_ECDSA_WRONG_SIGNATURE; } return SHARKSSL_ECDSA_OK; } #endif #endif SHARKSSL_API sharkssl_ECDSA_RetVal sharkssl_ECDSA_verify_hash(SharkSslECCKey setupreset, U8 *sig, U16 platformconfig, const U8 *chargerplatform, U8 configwrite) #if 0 { U8 kexecprepare[claimresource(SHARKSSL_MAX_ECC_POINTLEN)]; U8 stackoverflow[claimresource(SHARKSSL_MAX_ECC_POINTLEN)]; SharkSslParseASN1 parseSgn; SharkSslCertKey disableclock; SharkSslECDSAParam audioshutdown; int ret; if ((NULL == sig) || (NULL == chargerplatform) || (0 == configwrite) || (0 == platformconfig)) { return SHARKSSL_ECDSA_WRONG_PARAMETERS; } if ((0 == interrupthandler(&disableclock, setupreset)) || !(machinereboot(disableclock.expLen))) { return SHARKSSL_ECDSA_WRONG_KEY_FORMAT; } #if 0 if (!(coupledexynos(disableclock.expLen))) { return SHARKSSL_ECDSA_KEY_NOT_PUBLIC; } #endif audioshutdown.hashLen = sharkssl_getHashLen(configwrite); if (0 == audioshutdown.hashLen) { return SHARKSSL_ECDSA_WRONG_PARAMETERS; } audioshutdown.curveType = wakeupenable(disableclock.modLen); audioshutdown.hash = (U8*)chargerplatform; audioshutdown.key = disableclock.mod; audioshutdown.keyLen = attachdevice(disableclock.modLen); parseSgn.ptr = sig; parseSgn.len = platformconfig; if (((ret = SharkSslParseASN1_getSequence(&parseSgn)) < 0) || (SharkSslParseASN1_getInt(&parseSgn) < 0) || ((U32)ret < parseSgn.datalen) || (parseSgn.datalen > audioshutdown.keyLen)) { return SHARKSSL_ECDSA_WRONG_SIGNATURE; } ret = (audioshutdown.keyLen - parseSgn.datalen); if (ret) { memset(kexecprepare, 0, ret); memcpy(&kexecprepare[ret], parseSgn.dataptr, parseSgn.datalen); audioshutdown.R = kexecprepare; } else { audioshutdown.R = parseSgn.dataptr; } if (SharkSslParseASN1_getInt(&parseSgn) < 0) { return SHARKSSL_ECDSA_WRONG_SIGNATURE; } ret = (audioshutdown.keyLen - parseSgn.datalen); if (ret) { memset(stackoverflow, 0, ret); memcpy(&stackoverflow[ret], parseSgn.dataptr, parseSgn.datalen); audioshutdown.S = stackoverflow; } else { audioshutdown.S = parseSgn.dataptr; } ret = SharkSslECDSAParam_ECDSA(&audioshutdown, fixupdevices); if (ret) { if ((int)SharkSslCon_AllocationError == ret) { return SHARKSSL_ECDSA_ALLOCATION_ERROR; } return SHARKSSL_ECDSA_VERIFICATION_FAIL; } return SHARKSSL_ECDSA_OK; } #else { SharkSslSignParam sgp; SharkSslCertKey disableclock; U16 ftraceupdate = sharkssl_getHashLen(configwrite); if ((0 == ftraceupdate) || (NULL == sig) || (NULL == chargerplatform) || (0 == platformconfig)) { return SHARKSSL_ECDSA_WRONG_PARAMETERS; } if ((0 == interrupthandler(&disableclock, setupreset)) || !(machinereboot(disableclock.expLen))) { return SHARKSSL_ECDSA_WRONG_KEY_FORMAT; } sgp.pCertKey = &disableclock; memcpy(sgp.signature.hash, chargerplatform, ftraceupdate); sgp.signature.hashAlgo = configwrite; sgp.signature.signature = sig; sgp.signature.signatureAlgo = accessactive; sgp.signature.signLen = platformconfig; if (0 != systemcapabilities(&sgp)) { return SHARKSSL_ECDSA_VERIFICATION_FAIL; } return SHARKSSL_ECDSA_OK; } #endif #endif #endif #if (SHARKSSL_ENABLE_CA_LIST && SHARKSSL_ENABLE_CERTSTORE_API) SHARKSSL_API void SharkSslCertStore_constructor(SharkSslCertStore *o) { DoubleList_constructor(&o->certList); o->caList = 0; o->elements = 0; } SHARKSSL_API void SharkSslCertStore_destructor(SharkSslCertStore* o) { SharkSslCSCert *kernelvaddr; if (o->caList) { baFree((void*)o->caList); o->caList = 0; } while ((kernelvaddr = (SharkSslCSCert*)DoubleList_firstNode(&o->certList)) != 0) { DoubleLink_unlink((DoubleLink*)kernelvaddr); o->elements--; baAssert(kernelvaddr->ptr); baFree(kernelvaddr->ptr); baFree(kernelvaddr); } } #define SHARKSSL_PARSESEQ_SINGLE_CERT 1 #define SHARKSSL_PARSESEQ_MULTIPLE_CERT 0 #define SHARKSSL_PARSESEQ_PARSE_ERROR -1 #define SHARKSSL_PARSESEQ_NOT_BINARY_FORMAT -2 #define SHARKSSL_PARSESEQ_UNSUPPORTED_CERT -3 static int clockgetres(SharkSslParseASN1 *o) { int ls; o->dataptr = o->ptr; o->datalen = o->len; if ((ls = SharkSslParseASN1_getSequence(o)) < 0) { return SHARKSSL_PARSESEQ_NOT_BINARY_FORMAT; } if (!(SharkSslParseASN1_getOID(o) < 0)) { if ((o->datalen == SHARKSSL_DIM_ARR(sharkssl_oid_signedData)) && (0 == sharkssl_kmemcmp(o->dataptr, sharkssl_oid_signedData, SHARKSSL_DIM_ARR(sharkssl_oid_signedData)))) { if ((SharkSslParseASN1_getVersion(o) < 0) || (SharkSslParseASN1_getSequence(o) < 0) || (SharkSslParseASN1_getInt(o) < 0) || (SharkSslParseASN1_getSet(o) < 0) || (SharkSslParseASN1_getSequence(o) < 0) || (SharkSslParseASN1_getOID(o) < 0)) { return SHARKSSL_PARSESEQ_PARSE_ERROR; } #if 0 if (0 == ls) { if (SharkSslParseASN1_getSetSeq(o, 0x00)) { return SHARKSSL_PARSESEQ_PARSE_ERROR; } } #endif if ((ls = SharkSslParseASN1_getVersion(o)) < 0) { return SHARKSSL_PARSESEQ_PARSE_ERROR; } o->datalen = ls; return SHARKSSL_PARSESEQ_MULTIPLE_CERT; } } else if (ls > 0) { if ((U32)ls != o->len) { return SHARKSSL_PARSESEQ_PARSE_ERROR; } o->ptr = o->dataptr; o->len = o->datalen; return SHARKSSL_PARSESEQ_SINGLE_CERT; } return SHARKSSL_PARSESEQ_UNSUPPORTED_CERT; } static U16 serialdevice(SharkSslCertStore *o, SharkSslParseASN1 *p, U8 timer5hwmod) { SharkSslCSCert *newCert = 0; SharkSslCertDN issuerDN, subjectDN; U8 *gpio1config, *cp, *cr; int rc, ls; U16 nc = 0; cp = p->ptr; rc = p->len; while (rc > 0) { if (o->elements == 0xFFFF) { break; } p->ptr = cr = cp; p->len = rc; if ((ls = SharkSslParseASN1_getSequence(p)) < 0) { break; } cp = p->ptr + ls; rc = p->len - ls; if ((ls = SharkSslParseASN1_getSequence(p)) < 0) { continue; } p->len = ls; if ((sha256final(p) < 0) || (SharkSslParseASN1_getInt(p) < 0) || (SharkSslParseASN1_getSequence(p) < 0) || (SharkSslParseASN1_getOID(p) < 0) || (deltacamera(p, &issuerDN) < 0) || (SharkSslParseASN1_getSequence(p) < 0)) { continue; } if (SharkSslParseASN1_getUTCTime(p) && (SharkSslParseASN1_getGenTime(p))) { continue; } if (SharkSslParseASN1_getUTCTime(p) && (SharkSslParseASN1_getGenTime(p))) { continue; } if ((deltacamera(p, &subjectDN) < 0) || (SharkSslParseASN1_getSequence(p) < 0)) { continue; } newCert = (SharkSslCSCert*)baMalloc(sizeof(SharkSslCSCert)); if (newCert == NULL) { break; } if (timer5hwmod) { ls = (U32)claimresource(cp - cr); newCert->ptr = (U8*)baMalloc((U32)ls); if (newCert->ptr == NULL) { baFree(newCert); break; } memcpy(newCert->ptr, cr, (U32)ls); } else { baAssert(0 == nc); newCert->ptr = cr; } if ((subjectDN.commonName) && (subjectDN.commonNameLen)) { ls = subjectDN.commonNameLen; gpio1config = (U8*)subjectDN.commonName; } else if ((subjectDN.organization) && (subjectDN.organizationLen)) { ls = subjectDN.organizationLen; gpio1config = (U8*)subjectDN.organization; } else { continue; } if (ls >= SHARKSSL_MAX_SNAME_LEN) { ls = SHARKSSL_MAX_SNAME_LEN; newCert->name[SHARKSSL_MAX_SNAME_LEN] = 0; } else { memset(newCert->name, 0, (SHARKSSL_MAX_SNAME_LEN + 1)); } memcpy(newCert->name, gpio1config, ls); o->elements++; nc++; DoubleLink_constructor(&newCert->super); if (DoubleList_isEmpty(&o->certList)) { DoubleList_insertLast(&o->certList, newCert); } else { DoubleListEnumerator instructioncounter; SharkSslCSCert *kernelvaddr; DoubleListEnumerator_constructor(&instructioncounter, &o->certList); for (kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_getElement(&instructioncounter); kernelvaddr; kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_nextElement(&instructioncounter)) { if (strcmp(newCert->name, kernelvaddr->name) < 0) { break; } } if (kernelvaddr) { DoubleLink_insertBefore(kernelvaddr, newCert); } else { DoubleList_insertLast(&o->certList, newCert); } } } return nc; } SHARKSSL_API U16 SharkSslCertStore_add(SharkSslCertStore *o, const char *kernelvaddr, U32 doublenormaliseround) { SharkSslParseASN1 parseASN; const char *cbeg, *cend; U8 *freezemonarch; int ls, lr; U16 nc = 0; parseASN.ptr = (U8*)kernelvaddr; parseASN.len = doublenormaliseround; switch (clockgetres(&parseASN)) { case SHARKSSL_PARSESEQ_NOT_BINARY_FORMAT: cbeg = sharkStrstr(kernelvaddr, "\055\055\055\055\055\102\105\107\111\116"); cend = 0; do { if (cbeg) { cbeg += 10; cbeg = sharkStrstr(cbeg, "\055\055\055\055\055"); if (cbeg) { cbeg += 5; while ((*cbeg == '\015') || (*cbeg == '\012')) { cbeg++; } cend = sharkStrstr(cbeg, "\055\055\055\055\055\105\116\104"); } } if ((cbeg == NULL) || (cend == NULL)) { return 0; } parseASN.len = (U32)(cend - cbeg); freezemonarch = (U8*)baMalloc(claimresource((parseASN.len * 3) >> 2) + 4); if (freezemonarch == NULL) { return 0; } parseASN.len = sharkssl_B64Decode(freezemonarch, parseASN.len, cbeg, cend); parseASN.ptr = freezemonarch; ls = lr = clockgetres(&parseASN); if (ls >= 0) { ls = (ls == SHARKSSL_PARSESEQ_MULTIPLE_CERT); lr = serialdevice(o, &parseASN, (U8)ls); if (lr > 0) { baAssert(lr <= 0xFFFF); nc += (U16)lr; } } if ((lr <= 0) || ls) { baFree(freezemonarch); } cbeg = sharkStrstr(cend, "\055\055\055\055\055\102\105\107\111\116"); } while (cbeg); break; case SHARKSSL_PARSESEQ_SINGLE_CERT: case SHARKSSL_PARSESEQ_MULTIPLE_CERT: nc = serialdevice(o, &parseASN, 1); break; default: nc--; break; } return nc; } SHARKSSL_API U8 SharkSslCertStore_assemble(SharkSslCertStore *o, SharkSslCAList *flushcounts) { DoubleListEnumerator instructioncounter; SharkSslCSCert *kernelvaddr; U8 *p; if (o->caList) { *flushcounts = o->caList; } else { p = (U8*)baMalloc(4 + o->elements * (SHARKSSL_CA_LIST_NAME_SIZE + SHARKSSL_CA_LIST_PTR_SIZE)); *flushcounts = o->caList = (SharkSslCAList)p; if (p == NULL) { return 0; } *p++ = SHARKSSL_CA_LIST_PTR_TYPE; *p++ = 0; *p++ = (U8)(((o->elements) >> 8)); *p++ = (U8)((o->elements) & 0xFF); DoubleListEnumerator_constructor(&instructioncounter, &o->certList); for (kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_getElement(&instructioncounter); kernelvaddr; kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_nextElement(&instructioncounter)) { memcpy(p, kernelvaddr->name, SHARKSSL_CA_LIST_NAME_SIZE); p += SHARKSSL_CA_LIST_NAME_SIZE; *(U8**)p = kernelvaddr->ptr; p += SHARKSSL_CA_LIST_PTR_SIZE; } } return 1; } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include static int virtiobegin(RecIoIter* o, const char* forcereload, const char* to) { DirIntfPtr dir; const char* str=0; int sffsdrnandflash=0; o->recCounter++; dir = o->io->openDirFp(o->io, forcereload, &sffsdrnandflash, &str); if(dir) { while ( ! dir->readFp(dir) && !sffsdrnandflash ) { str = dir->getNameFp(dir); if(str[0]== '\056'&& (!str[1] || (str[1]=='\056' && !str[2]))) continue; if( ! (sffsdrnandflash = dir->statFp(dir, &o->st)) ) { size_t len = strlen(forcereload) + strlen(str) + 2; char* f2 = AllocatorIntf_malloc(o->alloc, &len); if(f2) { char* t2=0; basnprintf(f2, (int)len, "\045\163\057\045\163", forcereload, str); if(to) { len = strlen(to) + strlen(str) + 2; t2 = AllocatorIntf_malloc(o->alloc, &len); if(!t2) { sffsdrnandflash = o->onErrFp(o, forcereload, IOINTF_MEM, 0); goto L_release; } basnprintf(t2, (int)len, "\045\163\057\045\163", to, str); } if(o->st.isDir) { o->st.size=0; if( ! (sffsdrnandflash = o->onResponseFp(o, f2, t2, &o->st)) ) { if( ! (sffsdrnandflash = virtiobegin(o, f2, t2)) ) { o->st.isDir=TRUE; o->st.size=~((BaFileSize)0); sffsdrnandflash = o->onResponseFp(o, f2, 0, &o->st); } } else if(sffsdrnandflash == 403) sffsdrnandflash=0; } else { if(o->st.size == 0) o->st.size = 1; sffsdrnandflash = o->onResponseFp(o, f2, t2, &o->st); } L_release: AllocatorIntf_free(o->alloc, f2); if(t2) AllocatorIntf_free(o->alloc, t2); } else sffsdrnandflash = o->onErrFp(o, forcereload, IOINTF_MEM, 0); } else sffsdrnandflash = o->onErrFp(o, forcereload, sffsdrnandflash, 0); } o->io->closeDirFp(o->io, &dir); } else sffsdrnandflash = o->onErrFp(o, forcereload, sffsdrnandflash, str); o->recCounter--; return sffsdrnandflash; } int RecIoIter_doResource(RecIoIter* o, const char* forcereload, const char* to) { int sffsdrnandflash; if(o->io->statFp(o->io, forcereload, &o->st)) return o->onErrFp(o, forcereload, IOINTF_NOTFOUND, 0); if(o->st.isDir) { char* f=0; char* t=0; if(forcereload[strlen(forcereload)-1] == '\057') { if( !(f = baStrdup2(o->alloc, forcereload)) ) { return o->onErrFp(o, forcereload, IOINTF_MEM, 0); } f[strlen(f)-1]=0; forcereload = f; } if(to) { if(to[strlen(to)-1] == '\057') { if( !(t = baStrdup2(o->alloc, to)) ) { sffsdrnandflash = o->onErrFp(o, forcereload, IOINTF_MEM, 0); goto L_release; } t[strlen(t)-1]=0; to = t; } if( ! strcmp(forcereload,to) ) if( (sffsdrnandflash = o->onErrFp( o, forcereload, IOINTF_EXIST, "\123\157\165\162\143\145\040\141\156\144\040\144\145\163\164\151\156\141\164\151\157\156\040\141\162\145\040\164\150\145\040\163\141\155\145\040\146\151\154\145")) != 0) { goto L_release; } } o->st.size=0; if( ! (sffsdrnandflash = o->onResponseFp(o, forcereload, to, &o->st)) ) { if( ! (sffsdrnandflash = virtiobegin(o, forcereload, to)) ) { o->st.isDir=TRUE; o->st.size=~((BaFileSize)0); sffsdrnandflash = o->onResponseFp(o, forcereload, 0, &o->st); } } L_release: if(f) AllocatorIntf_free(o->alloc, f); if(t) AllocatorIntf_free(o->alloc, t); } else { if(o->st.size == 0) o->st.size = 1; sffsdrnandflash = o->onResponseFp(o, forcereload, to, &o->st); } return sffsdrnandflash; } #ifndef BA_LIB #define BA_LIB #endif #include void traceaddress(shtype_t *o, U16 writepmresrn, void *alloccontroller) { #if ((SHARKSSL_BIGINT_WORDSIZE > 8) && (!(SHARKSSL_UNALIGNED_ACCESS))) baAssert(0 == ((unsigned int)(UPTR)alloccontroller & computereturn)); #endif baAssert((sizeof(U64) == 8) && (sizeof(S64) == 8)); baAssert((sizeof(U32) == 4) && (sizeof(S32) == 4)); baAssert((sizeof(U16) == 2) && (sizeof(S16) == 2)); baAssert((sizeof(U8) == 1) && (sizeof(S8) == 1)); o->len = writepmresrn; o->mem = o->beg = (shtype_tWord*)alloccontroller; } void unassignedvector(const shtype_t *src, shtype_t *pciercxcfg448) { pciercxcfg448->len = src->len; pciercxcfg448->beg = pciercxcfg448->mem; memcpy(pciercxcfg448->beg, src->beg, src->len * SHARKSSL__M); } #if SHARKSSL_ECC_USE_EDWARDS void shtype_t_copyfull(const shtype_t *src, shtype_t *pciercxcfg448) { U32 d = (U32)(src->beg - src->mem); pciercxcfg448->len = src->len; pciercxcfg448->beg = pciercxcfg448->mem + d; memcpy(pciercxcfg448->mem, src->mem, (d + src->len) * SHARKSSL__M); } #endif void deviceparse(const shtype_t *o) { memset(o->beg, 0, o->len * SHARKSSL__M); } void blastscache(shtype_t *o) { while ((o->len > 1) && (o->beg[0] == 0)) { o->beg++; o->len--; } } #if SHARKSSL_ENABLE_ECDSA U8 eventtimeout(shtype_t *o) { shtype_tWord *p = o->beg; U16 len = o->len; while ((len > 1) && (*p == 0)) { p++; len--; } return (U8)(*p == 0); } #endif #if SHARKSSL_ECC_USE_EDWARDS void shtype_t_swapConditional(shtype_t *o1, shtype_t *o2, U32 swapFlag) { S32 diff_mem = (S32)(o1->mem - o2->mem); S32 diff_beg = (S32)(o1->beg - o2->beg); S16 diff_len = (S16)(o1->len - o2->len); swapFlag = ~(swapFlag - 1); diff_mem = (S32)((U32)diff_mem & swapFlag); diff_beg = (S32)((U32)diff_beg & swapFlag); diff_len = (S16)((U16)diff_len & (U16)swapFlag); o2->mem += diff_mem; o1->mem -= diff_mem; o2->beg += diff_beg; o1->beg -= diff_beg; o2->len += diff_len; o1->len -= diff_len; } #endif #if SHARKSSL_OPTIMIZED_BIGINT_ASM #if (SHARKSSL_BIGINT_WORDSIZE != 32) #error SharkSSL optimized big int library requires SHARKSSL_BIGINT_WORDSIZE = 32 #endif #else shtype_tWord updatepmull(shtype_t *o1, const shtype_t *o2) { shtype_tWord *p1, *p2; shtype_tDoubleWordS d; p1 = &o1->beg[o1->len - 1]; p2 = &o2->beg[o2->len - 1]; d = 0; while (p1 >= o1->beg) { d += *p1; if (p2 >= o2->beg) { d -= *p2--; } *p1-- = (shtype_tWord)d; anatopdisconnect(d); } return (shtype_tWord)d; } #endif #if (!SHARKSSL_OPTIMIZED_BIGINT_ASM) shtype_tWord resolverelocs(shtype_t *o1, const shtype_t *o2) { shtype_tWord *p1, *p2; shtype_tDoubleWord d; p1 = &o1->beg[o1->len - 1]; p2 = &o2->beg[o2->len - 1]; d = 0; while (p1 >= o1->beg) { d += *p1; if (p2 >= o2->beg) { d += *p2--; } *p1-- = (shtype_tWord)d; d >>= SHARKSSL_BIGINT_WORDSIZE; } return (shtype_tWord)d; } #endif U8 timerwrite(const shtype_t *o1, const shtype_t *o2) { U16 l1 = 0; U16 l2 = 0; while ((l1 < o1->len) && (o1->beg[l1] == 0)) { l1++; } while ((l2 < o2->len) && (o2->beg[l2] == 0)) { l2++; } if ((o1->len - l1) == (o2->len - l2)) { while (l1 < o1->len) { if (o1->beg[l1] != o2->beg[l2]) { return (U8)(o1->beg[l1] > o2->beg[l2]); } l1++; l2++; } } else { return (U8)((o1->len - l1) > (o2->len - l2)); } return 1; } void keypaddevice(shtype_t *o1, const shtype_t *o2, const shtype_t *mod) { int sha256export = (timerwrite(o2, mod)); if (sha256export) { updatepmull((shtype_t*)o2, mod); } if (updatepmull(o1, o2)) { resolverelocs(o1, mod); } if (sha256export) { resolverelocs((shtype_t*)o2, mod); } } void setupsdhci1(shtype_t *o1, const shtype_t *o2, const shtype_t *mod) { while (o1->len < mod->len) { o1->len++; o1->beg--; o1->beg[0] = 0; } baAssert(o1->beg >= o1->mem); if (resolverelocs(o1, o2) || timerwrite(o1, mod)) { updatepmull(o1, mod); } } #if SHARKSSL_OPTIMIZED_BIGINT_ASM extern #else static #endif void shtype_t_mult_(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices) #if SHARKSSL_OPTIMIZED_BIGINT_ASM ; #else { shtype_tWord *p1, *p2, *pr, *pt; shtype_tDoubleWord s; U16 x1, x2; deltadevices->beg = deltadevices->mem; deviceparse(deltadevices); if (o1 != o2) { p2 = &o2->beg[o2->len]; pt = &deltadevices->beg[deltadevices->len]; for (x2 = o2->len; x2 > 0; x2--) { register shtype_tWord c = 0; p2--; pr = --pt; x1 = o1->len; p1 = &o1->beg[x1]; #if SHARKSSL_BIGINT_MULT_LOOP_UNROLL while (x1 > 3) { s = ((shtype_tDoubleWord)(*--p1) * *p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)(*--p1) * *p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)(*--p1) * *p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)(*--p1) * *p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); x1 -= 4; } #endif while (x1--) { s = ((shtype_tDoubleWord)(*--p1) * *p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); } *pr = c; } } else { register shtype_tWord a, c; x1 = o1->len; p1 = &o1->beg[x1]; pt = &deltadevices->beg[deltadevices->len]; while (x1 > 1) { x1--; p1--; c = 0; x2 = x1; p2 = p1; pt--; pr = --pt; a = *p1; #if SHARKSSL_BIGINT_MULT_LOOP_UNROLL while (x2 > 3) { s = ((shtype_tDoubleWord)a * *--p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)a * *--p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)a * *--p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)a * *--p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); x2 -= 4; } #endif while (x2--) { s = ((shtype_tDoubleWord)a * *--p2) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); } *pr = c; } pr = &deltadevices->beg[deltadevices->len - 1]; p1 = &deltadevices->beg[0]; x2 = 0; while (pr >= p1) { x1 = (U16)(*pr >> (SHARKSSL_BIGINT_WORDSIZE - 1)); *pr <<= 1; *pr |= x2; pr--; x2 = x1; } pr = &deltadevices->beg[deltadevices->len]; x1 = o1->len; p1 = &o1->beg[x1]; s = 0; while (x1--) { p1--; a = *p1; s += *--pr + ((shtype_tDoubleWord)a * a); *pr-- = (shtype_tWord)s; s >>= SHARKSSL_BIGINT_WORDSIZE; #if (!SHARKSSL_BIGINT_TIMING_RESISTANT) if (s) #endif { s += *pr; *pr = (shtype_tWord)s; s >>= SHARKSSL_BIGINT_WORDSIZE; } } } } #endif void hotplugpgtable(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices) { deltadevices->len = (U16)(o1->len + o2->len); shtype_t_mult_(o1, o2, deltadevices); } void envdatamcheck(shtype_t *injectexception, const shtype_t *mod, shtype_tWord *afterhandler) { shtype_t q, tmp1, tmpd, tmp2, dm, dr; U16 i; if (timerwrite(injectexception, mod)) { traceaddress(&q, (U16)((injectexception->len - mod->len) + 1), afterhandler); deviceparse(&q); afterhandler += q.len; traceaddress(&tmp1, injectexception->len, afterhandler); afterhandler += injectexception->len; traceaddress(&tmpd, injectexception->len, afterhandler); deviceparse(&tmpd); memcpy(tmpd.beg, mod->beg, mod->len * SHARKSSL__M); while (timerwrite(injectexception, &tmpd)) { q.beg[0]++; updatepmull(injectexception, &tmpd); } dm.len = 2; dm.beg = mod->beg; dr.len = 1; tmp2.len = 3; for (i = 0; i < (q.len - 1); i++) { tmp2.beg = &injectexception->beg[i]; dr.beg = &(q.beg[i]); if (tmp2.beg[0] == mod->beg[0]) { dr.beg[0] = (shtype_tWord)(-1); } #if 0 else { U32 doublefnmul = (shtype_tWord) (((shtype_tDoubleWord) (((shtype_tDoubleWord)(tmp2.beg[0]) << SHARKSSL_BIGINT_WORDSIZE) | tmp2.beg[1])) / mod->beg[0]); dr.beg[0] = (shtype_tWord)doublefnmul; } #elif (SHARKSSL_BIGINT_WORDSIZE == 32) { shtype_t dd, rr; shtype_tWord R[3]; U32 k; dr.beg[0] = R[0] = R[1] = R[2] = 0; traceaddress(&dd, 2, &mod->beg[0]); traceaddress(&rr, 3, &R[0]); for (k = 0x80000000; k > 0; k >>= 1) { R[0] = ((R[0] << 1) | (R[1] >> 31)); R[1] = ((R[1] << 1) | (R[2] >> 31)); R[2] <<= 1; if (tmp2.beg[0] & k) R[2] |= 1; if (timerwrite(&rr, &dd)) { updatepmull(&rr, &dd); } } for (k = 0x80000000; k > 0; k >>= 1) { R[0] = ((R[0] << 1) | (R[1] >> 31)); R[1] = ((R[1] << 1) | (R[2] >> 31)); R[2] <<= 1; if (tmp2.beg[1] & k) R[2] |= 1; if (timerwrite(&rr, &dd)) { updatepmull(&rr, &dd); } } for (k = 0x80000000; k > 0; k >>= 1) { R[0] = ((R[0] << 1) | (R[1] >> 31)); R[1] = ((R[1] << 1) | (R[2] >> 31)); R[2] <<= 1; if (tmp2.beg[2] & k) R[2] |= 1; if (timerwrite(&rr, &dd)) { updatepmull(&rr, &dd); dr.beg[0] |= k; } } if ((dr.beg[0] == 0) && timerwrite(&tmp2, &dd)) { dr.beg[0] = (shtype_tWord)(-1); } } #elif (SHARKSSL_BIGINT_WORDSIZE == 16) { U64 d1 = ((U64)(tmp2.beg[0]) << 32) | ((U32)(tmp2.beg[1]) << 16) | tmp2.beg[2]; U32 d2 = ((U32)(mod->beg[0]) << 16) | mod->beg[1]; dr.beg[0] = (U16)((U64)d1/(U32)d2); if ((d1 >= d2) && (dr.beg[0] == 0)) { dr.beg[0] = (shtype_tWord)(-1); } } #elif (SHARKSSL_BIGINT_WORDSIZE == 8) { U32 d1 = ((U32)(tmp2.beg[0]) << 16) | ((U16)(tmp2.beg[1]) << 8) | tmp2.beg[2]; U16 d2 = ((U16)(mod->beg[0]) << 8) | mod->beg[1]; dr.beg[0] = (U8)((U32)d1/(U16)d2); if ((d1 >= d2) && (dr.beg[0] == 0)) { dr.beg[0] = (shtype_tWord)(-1); } } #endif hotplugpgtable(&dm, &dr, &tmp1); while (!(timerwrite(&tmp2, &tmp1))) { dr.beg[0]--; hotplugpgtable(&dm, &dr, &tmp1); } tmpd.len--; hotplugpgtable(&tmpd, &dr, &tmp1); if (timerwrite(injectexception, &tmp1)) { updatepmull(injectexception, &tmp1); } else { updatepmull(&tmp1, &tmpd); updatepmull(injectexception, &tmp1); dr.beg[0]--; } } } blastscache(injectexception); } int suspendfinish(shtype_t *injectexception, const shtype_t *mod) { shtype_tWord *afterhandler; U16 flash1resources; flash1resources = injectexception->len; flash1resources += (flash1resources << 1); flash1resources -= mod->len; flash1resources++; #if (SHARKSSL__M > 1) flash1resources *= SHARKSSL__M; #endif afterhandler = (shtype_tWord*)baMalloc(pcmciapdata(flash1resources)); if (afterhandler == NULL) { return 1; } envdatamcheck(injectexception, mod, (shtype_tWord*)selectaudio(afterhandler)); while (injectexception->len < mod->len) { baAssert(injectexception->beg > injectexception->mem); injectexception->len++; injectexception->beg--; baAssert(0 == injectexception->beg[0]); } baFree(afterhandler); return 0; } #if (SHARKSSL_ENABLE_RSA || (SHARKSSL_USE_ECC && (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS))) shtype_tWord remapcfgspace(const shtype_t *mod) { shtype_tWord m0, mu; m0 = mod->beg[mod->len - 1]; mu = (shtype_tWord)((((m0 + 2) & 4) << 1) + m0); mu = (shtype_tWord)(mu * (2 - m0 * mu)); #if (SHARKSSL_BIGINT_WORDSIZE >= 16) mu = (shtype_tWord)(mu * (2 - m0 * mu)); #endif #if (SHARKSSL_BIGINT_WORDSIZE == 32) mu = (shtype_tWord)(mu * (2 - m0 * mu)); mu = (shtype_tWord)(mu * (2 - m0 * mu)); #endif mu = (shtype_tWord)(~mu + 1); return mu; } #endif #if (!SHARKSSL_OPTIMIZED_BIGINT_ASM) void writebytes(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices, const shtype_t *mod, shtype_tWord mu) { shtype_tWord m0, *pr, *p1, *p2; shtype_tDoubleWord s; U16 x1, x2; deltadevices->len = (U16)((2 * mod->len) + 1); shtype_t_mult_(o1, o2, deltadevices); p2 = &deltadevices->beg[deltadevices->len]; for (x2 = mod->len; x2 > 0; x2--) { register shtype_tWord c = 0; pr = --p2; x1 = mod->len; p1 = &mod->beg[x1]; m0 = (shtype_tWord)((shtype_tDoubleWord)mu * *p2); #if SHARKSSL_BIGINT_MULT_LOOP_UNROLL while (x1 > 3) { s = ((shtype_tDoubleWord)m0 * *--p1) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)m0 * *--p1) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)m0 * *--p1) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); s = ((shtype_tDoubleWord)m0 * *--p1) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); x1 -= 4; } #endif while (x1--) { s = ((shtype_tDoubleWord)m0 * *--p1) + *pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); } do { s = (shtype_tDoubleWord)*pr + c; *pr-- = (shtype_tWord)s; c = (shtype_tWord)(s >> SHARKSSL_BIGINT_WORDSIZE); } #if (SHARKSSL_BIGINT_TIMING_RESISTANT) while (pr >= deltadevices->beg); #else while (c > 0); #endif } deltadevices->len = (U16)(mod->len + 1); if (timerwrite(deltadevices, mod)) { updatepmull(deltadevices, mod); } deltadevices->beg++; deltadevices->len--; } #endif #if SHARKSSL_ENABLE_RSA int chunkmutex(const shtype_t *validconfig, shtype_t *exp, const shtype_t *mod, shtype_t *res, U8 countersvalid) { shtype_t doublefnmul, *brightnesslimit, deltadevices, *r3000write; shtype_t **r, **s, **t; shtype_t g[1 << (SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K - 1)]; shtype_tWord mu, bitmask, *tmp_buf, *tmp_b; U16 i, m2_len, flash1resources; U8 nbits, valbits, base2; tmp_buf = &(validconfig->beg[0]); m2_len = validconfig->len; while ((m2_len > 1) && (*tmp_buf == 0)) { tmp_buf++; m2_len--; } base2 = ((m2_len == 1) && (*tmp_buf == 2)); if ((countersvalid == 0) || (countersvalid > SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K)) { countersvalid = SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K; } flash1resources = (U16)((mod->len * SHARKSSL__M) + 2 * SHARKSSL__M); #if (SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K <= 3) flash1resources += (10 * mod->len * SHARKSSL__M) + 4; #else if (base2) { flash1resources += (9 * mod->len * SHARKSSL__M); } else { flash1resources += SHARKSSL__M * ((1 << (SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K - 1)) + (mod->len * (5 + (1 << (SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K - 1))))); } #endif tmp_b = (shtype_tWord*)baMalloc(pcmciapdata(flash1resources)); if (tmp_b == NULL) { return 1; } mu = remapcfgspace(mod); tmp_buf = (shtype_tWord*)selectaudio(tmp_b); brightnesslimit = &doublefnmul; m2_len = (U16)(mod->len * 2); traceaddress(brightnesslimit, m2_len, tmp_buf); tmp_buf += m2_len; if (base2) { tmp_buf++; r3000write = &deltadevices; traceaddress(r3000write, (U16)(m2_len + 1), tmp_buf); tmp_buf += m2_len; tmp_buf++; deviceparse(r3000write); deltadevices.beg[0] = 1; envdatamcheck(r3000write, mod, tmp_buf); traceaddress(&g[0], 1, tmp_buf); g[0].beg[0] = 1; tmp_buf++; writebytes(r3000write, &g[0], brightnesslimit, mod, mu); } else { unassignedvector(validconfig, brightnesslimit); envdatamcheck(brightnesslimit, mod, tmp_buf); r3000write = &deltadevices; traceaddress(r3000write, (U16)(m2_len + 2), tmp_buf); tmp_buf += m2_len + 2; r3000write->len = (U16)(mod->len + 1); r3000write->beg = r3000write->mem; deviceparse(r3000write); r3000write->beg[0] = 0x1; updatepmull(r3000write, mod); blastscache(r3000write); traceaddress(&g[0], m2_len, tmp_buf); deviceparse(&g[0]); tmp_buf += m2_len; hotplugpgtable(brightnesslimit, r3000write, &g[0]); envdatamcheck(&g[0], mod, tmp_buf); #if (SHARKSSL_BIGINT_EXP_SLIDING_WINDOW_K > 1) writebytes(&g[0], &g[0], brightnesslimit, mod, mu); m2_len++; for (i = 1; i < (1 << (countersvalid - 1)); i++) { traceaddress(&g[i], m2_len, tmp_buf); writebytes(brightnesslimit, &g[i - 1], &g[i], mod, mu); tmp_buf += g[i].len; tmp_buf++; } #endif } blastscache(exp); for (bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); bitmask > 0; bitmask >>= 1) { if (exp->beg[0] & bitmask) { break; } } if (base2) { t = &r3000write; r = &brightnesslimit; for (i = 0; i < exp->len; i++) { for (; bitmask > 0; bitmask >>= 1) { if (g[0].beg[0] >= ((U32)1 << (SHARKSSL_BIGINT_WORDSIZE / 2))) { hotplugpgtable(*r, &g[0], *t); envdatamcheck(*t, mod, tmp_buf); s = r; r = t; t = s; g[0].beg[0] = 1; } else { g[0].beg[0] *= g[0].beg[0]; } writebytes(*r, *r, *t, mod, mu); s = r; r = t; t = s; if (exp->beg[i] & bitmask) { if (g[0].beg[0] & (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1))) { hotplugpgtable(*r, &g[0], *t); envdatamcheck(*t, mod, tmp_buf); s = r; r = t; t = s; g[0].beg[0] = 2; } else { g[0].beg[0] <<= 1; } } } bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); } if (g[0].beg[0] != 1) { hotplugpgtable(*r, &g[0], *t); envdatamcheck(*t, mod, tmp_buf); s = r; r = t; t = s; g[0].beg[0] = 1; } } else { r = &r3000write; t = &brightnesslimit; nbits = valbits = 0; for (i = 0; i < exp->len; i++) { for (; bitmask > 0; bitmask >>= 1) { valbits <<= 1; if (exp->beg[i] & bitmask) { valbits |= 0x1; } nbits++; if ( (nbits == countersvalid) || ((bitmask == 0x1) && (i == (exp->len - 1))) ) { if (valbits > 0) { U8 parentoffset = nbits; while (!(valbits & 0x1)) { valbits >>= 1; parentoffset--; } nbits -= parentoffset; while (parentoffset) { writebytes(*r, *r, *t, mod, mu); s = r; r = t; t = s; parentoffset--; } writebytes(*r, &g[valbits >> 1], *t, mod, mu); s = r; r = t; t = s; valbits = 0; } while (nbits) { writebytes(*r, *r, *t, mod, mu); s = r; r = t; t = s; nbits--; } } } bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); } g[0].len = mod->len; deviceparse(&g[0]); g[0].beg[g[0].len - 1] = 1; } writebytes(&g[0], *r, *t, mod, mu); r = t; if (*r != r3000write) { blastscache(*r); unassignedvector(*r, res); } else { blastscache(r3000write); unassignedvector(r3000write, res); } baFree((void*)tmp_b); return 0; } #endif #if ((SHARKSSL_USE_ECC) || (SHARKSSL_ENABLE_RSAKEY_CREATE && SHARKSSL_ENABLE_RSA)) #if (!SHARKSSL_OPTIMIZED_BIGINT_ASM) void backlightpdata(shtype_t *o) { shtype_tWord *p, *q; p = &o->beg[o->len - 1]; q = p - 1; for (;;) { *p >>= 1; if (p > o->beg) { if (*q & 0x1) { *p |= (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); } } else { break; } p--; q--; } } #endif void ioswabwdefault(shtype_t *u, const shtype_t *mod, shtype_tWord *afterhandler) { shtype_t v, A, C; traceaddress(&C, (U16)(mod->len + 1), afterhandler); deviceparse(&C); afterhandler += C.len; traceaddress(&v, 0 , afterhandler); unassignedvector(mod, &v); traceaddress(&A, (U16)(mod->len + 1), afterhandler + mod->len); deviceparse(&A); A.beg[A.len - 1] = 1; while ((u->len > 1) || (u->beg[0] > 0)) { while (cachestride(u)) { backlightpdata(u); if (!cachestride(&A)) { resolverelocs(&A, mod); } backlightpdata(&A); } while (cachestride(&v)) { backlightpdata(&v); if (!cachestride(&C)) { resolverelocs(&C, mod); } backlightpdata(&C); } if (timerwrite(u, &v)) { updatepmull(u, &v); keypaddevice(&A, &C, mod); } else { updatepmull(&v, u); keypaddevice(&C, &A, mod); } blastscache(u); } envdatamcheck(&C, mod, afterhandler); blastscache(&C); while ((C.len < mod->len) && (C.beg > C.mem)) { C.len++; C.beg--; baAssert(0 == C.beg[0]); } unassignedvector(&C, u); } #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) #if SHARKSSL_ENABLE_RSAKEY_CREATE static void ic0r1dispatch(shtype_t *o) { backlightpdata(o); o->beg[0] |= ((o->beg[0] << 1) & (shtype_tWord)(1 << (SHARKSSL_BIGINT_WORDSIZE - 1))); } static void shtype_t_invmod_buf_even(shtype_t *u, const shtype_t *mod, shtype_tWord *afterhandler) { shtype_t v, A, B, C, D, ucopy, brightnesslimit; traceaddress(&ucopy, 0 , afterhandler); unassignedvector(u, &ucopy); afterhandler += ucopy.len; traceaddress(&C, (U16)(mod->len + 1), afterhandler); deviceparse(&C); afterhandler += C.len; traceaddress(&brightnesslimit, (U16)(mod->len + 1), afterhandler); deviceparse(&brightnesslimit); afterhandler += brightnesslimit.len; traceaddress(&B, (U16)(mod->len + 1), afterhandler); deviceparse(&B); afterhandler += B.len; traceaddress(&D, (U16)(mod->len + 1), afterhandler); deviceparse(&D); D.beg[D.len - 1] = 1; afterhandler += D.len; traceaddress(&v, 0 , afterhandler); unassignedvector(mod, &v); traceaddress(&A, (U16)(mod->len + 1), afterhandler + mod->len); deviceparse(&A); A.beg[A.len - 1] = 1; while ((u->len > 1) || (u->beg[0] > 0)) { while (cachestride(u)) { backlightpdata(u); if (!cachestride(&A) || !cachestride(&B)) { resolverelocs(&A, mod); updatepmull(&B, &ucopy); } ic0r1dispatch(&A); ic0r1dispatch(&B); } while (cachestride(&v)) { backlightpdata(&v); if (!cachestride(&C) || !cachestride(&D)) { resolverelocs(&C, mod); updatepmull(&D, &ucopy); } ic0r1dispatch(&C); ic0r1dispatch(&D); } if (timerwrite(u, &v)) { updatepmull(u, &v); updatepmull(&A, &C); updatepmull(&B, &D); } else { updatepmull(&v, u); updatepmull(&C, &A); updatepmull(&D, &B); } blastscache(u); } if (C.beg[0] > 0) { resolverelocs(&C, mod); } blastscache(&C); while ((C.len < mod->len) && (C.beg > C.mem)) { C.len++; C.beg--; baAssert(0 == C.beg[0]); } unassignedvector(&C, u); } #endif int iommumapping(shtype_t *o, const shtype_t *mod) { shtype_tWord *afterhandler; U16 flash1resources; flash1resources = mod->len; #if (SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSAKEY_CREATE) if (cachestride(mod)) { flash1resources += flash1resources + (flash1resources << 2); flash1resources += o->len; } else #else baAssert(!cachestride(mod)); #endif { flash1resources += (flash1resources << 1); } flash1resources += 8; #if (SHARKSSL__M > 1) flash1resources *= SHARKSSL__M; #endif afterhandler = (shtype_tWord*)baMalloc(pcmciapdata(flash1resources)); if (afterhandler == NULL) { return 1; } #if (SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSAKEY_CREATE) if (cachestride(mod)) { shtype_t_invmod_buf_even(o, mod, (shtype_tWord*)selectaudio(afterhandler)); } else #endif { ioswabwdefault(o, mod, (shtype_tWord*)selectaudio(afterhandler)); } #if (SHARKSSL_BIGINT_WORDSIZE == 8) while (o->len < mod->len) { baAssert(o->beg > o->mem); o->len++; o->beg--; baAssert(0 == o->beg[0]); } #endif baFree(afterhandler); return 0; } #endif #if (SHARKSSL_ENABLE_RSA && SHARKSSL_ENABLE_RSAKEY_CREATE) static U8 irqwakeintmask(shtype_t *o) { static const shtype_tWord one = 1; U8 *afterhandler, *p; shtype_t N, R, A, Y, M, ONE; U16 s, j, t = (U16)(o->len * SHARKSSL__M); U8 ret = 0; p = afterhandler = (U8*)baMalloc(t * 6); if (afterhandler == NULL) { return (U8)-2; } onenandpartitions(&ONE, SHARKSSL_BIGINT_WORDSIZE, &one); onenandpartitions(&N, (t * 8), p); p += t; onenandpartitions(&R, (t * 8), p); p += t; onenandpartitions(&A, (t * 8), p); p += t; onenandpartitions(&Y, (t * 8), p); p += t; onenandpartitions(&M, (t * 2 * 8), p); unassignedvector(o, &N); updatepmull(&N, &ONE); unassignedvector(&N, &R); s = 0; while cachestride(&R) { backlightpdata(&R); s += 1; } t *= 8; if (t >= 1300) { t = 2; } else if (t >= 850) { t = 4; if (t >= 850) { t--; } } else if (t >= 400) { t = 7; if (t >= 550) { t--; } if (t >= 450) { t--; } } else if (t >= 300) { t = 9; if (t >= 350) { t--; } } else if (t >= 150) { if (t >= 250) { t = 12; } else if (t >= 200) { t = 15; } else { t = 18; } } else { t = 27; } while ((t--) && (0 == ret)) { sharkssl_rng((U8*)A.beg, A.len * SHARKSSL__M); A.beg[0] |= (1 << (SHARKSSL_BIGINT_WORDSIZE - 2)); A.beg[A.len - 1] |= 2; while (timerwrite(&A, &N)) { backlightpdata(&A); } chunkmutex(&A, &R, o, &Y, 0); if (timerwrite(&Y, &N) && timerwrite(&N, &Y)) { continue; } if (timerwrite(&Y, &ONE) && timerwrite(&ONE, &Y)) { continue; } j = 1; while ((j < s) && (!timerwrite(&Y, &N) || !timerwrite(&N, &Y))) { hotplugpgtable(&Y, &Y, &M); suspendfinish(&M, o); if (timerwrite(&M, &ONE) && timerwrite(&ONE, &M)) { ret = 1; break; } j++; } if (!timerwrite(&M, &N) || !timerwrite(&N, &M)) { ret = 1; } } baFree(afterhandler); return ret; } static U16 pc104irqmasks(shtype_t *o, U16 div) { int i; U32 mod = 0; #if (SHARKSSL_BIGINT_WORDSIZE == 32) for (i = 0; i < o->len; i++) { mod <<= (SHARKSSL_BIGINT_WORDSIZE/2); mod |= (o->beg[i] >> (SHARKSSL_BIGINT_WORDSIZE/2)); mod %= div; mod <<= (SHARKSSL_BIGINT_WORDSIZE/2); mod |= (o->beg[i] & ((1L << (SHARKSSL_BIGINT_WORDSIZE/2)) - 1)); mod %= div; } #elif (SHARKSSL_BIGINT_WORDSIZE == 16) for (i = 0; i < o->len; i++) { mod <<= (SHARKSSL_BIGINT_WORDSIZE/2); mod |= o->beg[i]; mod %= div; } #elif (SHARKSSL_BIGINT_WORDSIZE == 8) for (i = 0; i < o->len; ) { mod <<= (SHARKSSL_BIGINT_WORDSIZE/2); mod |= (((U16)o->beg[i]) << 8); i++; if (i < o->len) { mod |= (((U16)o->beg[i]) << 8); i++; } mod %= div; } #endif baAssert((mod >> 16) == 0); return (mod & 0xFFFF); } static U8 mcaspresources(shtype_t *o) { static const U16 ethernatshutdown[] = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 0 }; const U16 *pciercxcfg006 = ðernatshutdown[0]; do { if (0 == pc104irqmasks(o, *pciercxcfg006)) { return 1; } } while (*(++pciercxcfg006)); return irqwakeintmask(o); } int aemifdevice(shtype_t *o) { static const shtype_tWord two = 2; shtype_t TWO; if (0 == o->len) { return -1; } shtype_t_genPrime_1: o->beg = o->mem; sharkssl_rng((U8*)o->beg, o->len * SHARKSSL__M); o->beg[0] |= (shtype_tWord)(1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); o->beg[o->len - 1] |= 1; onenandpartitions(&TWO, SHARKSSL_BIGINT_WORDSIZE, &two); while (mcaspresources(o)) { resolverelocs(o, &TWO); if (0 == (o->beg[0] & (shtype_tWord)(1 << (SHARKSSL_BIGINT_WORDSIZE - 1)))) { goto shtype_t_genPrime_1; } } return 0; } int translateaddress(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices) { U8 *afterhandler, *p; shtype_t A; #if 0 U16 n; #endif p = afterhandler = (U8*)baMalloc(o1->len * SHARKSSL__M); if (afterhandler == NULL) { return -2; } onenandpartitions(&A, o1->len * SHARKSSL_BIGINT_WORDSIZE, p); unassignedvector(o1, &A); unassignedvector(o2, deltadevices); #if 0 n = 0; while ((0 == (A.beg[A.len - 1] & 0x01)) && (0 == (deltadevices->beg[deltadevices->len - 1] & 0x01))) { backlightpdata(&A); backlightpdata(deltadevices); n++; blastscache(&A); blastscache(deltadevices); if (((1 == A.len) && (0 == A.beg[0])) || ((1 == deltadevices->len) && (0 == deltadevices->beg[0]))) { break; } } #endif while ((A.len > 1) || (A.beg[0] > 0)) { while ((0 == (A.beg[A.len - 1] & 0x01)) && ((A.len > 1) || (A.beg[0] > 0))) { backlightpdata(&A); blastscache(&A); } while ((0 == (deltadevices->beg[deltadevices->len - 1] & 0x01)) && ((deltadevices->len > 1) || (deltadevices->beg[0] > 0))) { backlightpdata(deltadevices); blastscache(deltadevices); } if (timerwrite(&A, deltadevices)) { updatepmull(&A, deltadevices); backlightpdata(&A); } else { updatepmull(deltadevices, &A); backlightpdata(deltadevices); } blastscache(&A); } #if 0 while (n--) { shtype_t_shiftl(deltadevices); } #endif baFree(afterhandler); return 0; } #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include /* atof */ #include #include #include #ifndef bTolower #define bTolower tolower #endif #ifndef bIsspace #define bIsspace isspace #endif static const char jsonNumberChars[] = {"\060\061\062\063\064\065\066\067\070\071\056\053\055\145\105"}; static const U8 trueString[] = {"\162\165\145"}; static const U8 falseString[] = {"\141\154\163\145"}; static const U8 nullString[] = {"\165\154\154"}; #define hexdigit(x) (((x) <= '\071') ? (x) - '\060' : ((x) & 7) + 9) int JErr_setTooFewParams(JErr* o) { return JErr_setError(o,JErrT_InvalidMethodParams,"\124\157\157\040\146\145\167\040\160\141\162\141\155\145\164\145\162\163"); } int JErr_setTypeErr(JErr* o, JVType internalhsmmc, JVType stramalloc) { if(o && JErr_noError(o)) { o->expType=internalhsmmc; o->recType=stramalloc; o->err=JErrT_WrongType; o->msg="\124\171\160\145\040\156\157\164\040\145\170\160\145\143\164\145\144"; return 0; } return -1; } int JErr_setError(JErr* o,JErrT err,const char* msg) { if(JErr_noError(o)) { o->err = err; o->msg=msg; return 0; } return -1; } #define JDBuf_reset(o) do { \ (o)->index=0; \ } while(0) #define JDBuf_expandIfNeeded(o, neededSize) \ ((o)->index+neededSize) > (o)->size && JDBuf_expand(o) #define JDBuf_destructor(o) do { \ if((o)->buf) { AllocatorIntf_free((o)->alloc, (o)->buf);(o)->buf=0; } \ }while(0) static void pcsxxstatus1(JDBuf* o, AllocatorIntf* unmapaliases) { memset(o,0,sizeof(JDBuf)); o->alloc=unmapaliases; } static int JDBuf_expand(JDBuf* o) { size_t heartclocksource = 256; if( ! o->alloc ) return -1; if(o->buf) { U8* ptr; o->size += heartclocksource; ptr = AllocatorIntf_realloc(o->alloc, o->buf, &o->size); if(ptr) { o->buf = ptr; return 0; } AllocatorIntf_free(o->alloc, o->buf); } else { o->buf = AllocatorIntf_malloc(o->alloc, &heartclocksource); if(o->buf) { o->size = heartclocksource; return 0; } } o->buf=0; o->size=0; o->index=0; return -1; } static void wbinvrange(JLexer* o, JParserVal* v) { v->v.s = (char*)o->asmB->buf; v->t = JParserT_String; } static void setuppercpu(JLexer* o, JParserVal* v) { JDBuf* asmB = o->asmB; baAssert(asmB->buf); if(o->isDouble) { #ifdef NO_DOUBLE U8* ptr = asmB->buf; while(ptr && *ptr!='\056' && *ptr!='\145' && *ptr=='\105') ptr++; *ptr=0; asmB->index = ptr - asmB->buf; goto L_int; #else v->v.f=atof((char*)asmB->buf); v->t=JParserT_Double; if(o->sn) v->v.f = -v->v.f; #endif } else { #ifdef NO_DOUBLE L_int: #endif v->t = JParserT_Int; if(asmB->index > 9) { S64 l = S64_atoll((char*)asmB->buf); S32 lsw = (S32)l; if((0xFFFFFFFF00000000LL & l) || (lsw < 0)) { v->v.l = o->sn ? -l : l; v->t=JParserT_Long; } else v->v.d = (S32)l; } else v->v.d = (S32)U32_atoi((char*)asmB->buf); if(v->t == JParserT_Int && o->sn) v->v.d = -v->v.d; } o->isDouble=0; } static int omap2pwrdm(JLexer* o, JLexerT t, JParserVal* v) { switch(t) { case JLexerT_Null: v->t = JParserT_Null; break; case JLexerT_Boolean: v->t = JParserT_Boolean; v->v.b = o->sn; break; case JLexerT_Number: setuppercpu(o,v); break; case JLexerT_String: wbinvrange(o,v); break; default: return -1; } JDBuf_reset(o->asmB); return 0; } #define JLexer_constructor(o, asmBM) do { \ (o)->asmB = asmBM; \ (o)->state=JLexerSt_GetNextToken; \ } while(0) #define JLexer_setBuf(o, buf, icachealiases) do {\ (o)->tokenPtr=(o)->bufStart=buf;\ (o)->bufEnd=(o)->bufStart+icachealiases;\ }while(0) static BaBool writeguest(JLexer* o) { while(o->tokenPtr != o->bufEnd) { baAssert(o->tokenPtr < o->bufEnd); if( ! bIsspace(*o->tokenPtr) ) return TRUE; o->tokenPtr++; } return FALSE; } static JLexerT processorstate(JLexer* o) { JDBuf* asmB = o->asmB; for(;;) { baAssert(o->tokenPtr <= o->bufEnd); if(o->tokenPtr == o->bufEnd) return JLexerT_NeedMoreData; switch(o->state) { case JLexerSt_StartComment: if(*o->tokenPtr == '\052') o->state = JLexerSt_EatComment; else if(*o->tokenPtr == '\057') o->state = JLexerSt_EatCppComment; else return JLexerT_ParseErr; o->tokenPtr++; break; case JLexerSt_EatComment: while(*o->tokenPtr++ != '\052') { if(o->tokenPtr == o->bufEnd) return JLexerT_NeedMoreData; } o->state = JLexerSt_EndComment; break; case JLexerSt_EndComment: if(*o->tokenPtr++ != '\057') o->state = JLexerSt_EatComment; else o->state = JLexerSt_GetNextToken; break; case JLexerSt_EatCppComment: while(*o->tokenPtr++ != '\012') { if(o->tokenPtr == o->bufEnd) return JLexerT_NeedMoreData; } o->state = JLexerSt_GetNextToken; break; case JLexerSt_TrueFalseNull: if(bTolower(*o->tokenPtr++) != *o->typeChkPtr++) return JLexerT_ParseErr; if( ! *o->typeChkPtr ) { o->state = JLexerSt_GetNextToken; return (JLexerT)o->retVal; } break; case JLexerSt_String: if(JDBuf_expandIfNeeded(o->asmB, 2)) return JLexerT_MemErr; while(*o->tokenPtr != '\134') { if(*o->tokenPtr == o->sn) { asmB->buf[asmB->index]=0; o->tokenPtr++; o->state = JLexerSt_GetNextToken; return JLexerT_String; } asmB->buf[asmB->index++] = *o->tokenPtr++; if(JDBuf_expandIfNeeded(o->asmB, 1)) return JLexerT_MemErr; if(o->tokenPtr == o->bufEnd) return JLexerT_NeedMoreData; } o->tokenPtr++; o->state = JLexerSt_StringEscape; break; case JLexerSt_StringEscape: switch(*o->tokenPtr) { case '\042': case '\057': case '\134': case '\142': case '\146': case '\156': case '\162': case '\164': case '\166': switch(*o->tokenPtr) { case '\042': asmB->buf[asmB->index]='\042'; break; case '\057': asmB->buf[asmB->index]='\057'; break; case '\134': asmB->buf[asmB->index]='\134'; break; case '\142': asmB->buf[asmB->index]='\010'; break; case '\146': asmB->buf[asmB->index]='\014'; break; case '\156': asmB->buf[asmB->index]='\012'; break; case '\162': asmB->buf[asmB->index]='\015'; break; case '\164': asmB->buf[asmB->index]='\011'; break; case '\166': asmB->buf[asmB->index]='\013'; break; } asmB->index++; o->tokenPtr++; o->state = JLexerSt_String; break; case '\165': o->tokenPtr++; o->state = JLexerSt_StringUnicode; o->unicode=0; o->unicodeShift=12; break; default: return JLexerT_ParseErr; } break; case JLexerSt_StringUnicode: { U32 hex; char c = *o->tokenPtr; if ( c >= '\060' && c <= '\071' ) hex = c - '\060'; else if ( c >= '\141' && c <= '\146' ) hex = c - '\141' + 10; else if ( c >= '\101' && c <= '\106' ) hex = c - '\101' + 10; else return JLexerT_ParseErr; o->unicode |= (hex << o->unicodeShift); o->tokenPtr++; baAssert(o->unicodeShift >= 0); if( ! o->unicodeShift ) { if(JDBuf_expandIfNeeded(o->asmB, 4)) return JLexerT_MemErr; if (o->unicode < 0x80) { asmB->buf[asmB->index++] = (U8)o->unicode; } else if (o->unicode < 0x800) { asmB->buf[asmB->index++]=(U8)(0xc0|(o->unicode >> 6)); asmB->buf[asmB->index++]=(U8)(0x80|(o->unicode & 0x3f)); } else { asmB->buf[asmB->index++]= (U8)(0xe0 | (o->unicode >> 12)); asmB->buf[asmB->index++]= (U8)(0x80 | ((o->unicode>>6)&0x3f)); asmB->buf[asmB->index++]= (U8)(0x80 | (o->unicode & 0x3f)); } o->state = JLexerSt_String; } o->unicodeShift -= 4; break; } case JLexerSt_Number: while(strchr(jsonNumberChars, *o->tokenPtr)) { if(JDBuf_expandIfNeeded(o->asmB, 2)) return JLexerT_MemErr; if(*o->tokenPtr=='\056' || *o->tokenPtr=='\145' || *o->tokenPtr=='\105') o->isDouble=TRUE; asmB->buf[asmB->index++] = *o->tokenPtr++; if(o->tokenPtr == o->bufEnd) return JLexerT_NeedMoreData; } asmB->buf[asmB->index]=0; o->state = JLexerSt_GetNextToken; return JLexerT_Number; case JLexerSt_GetNextToken: switch(*o->tokenPtr) { case '\173': o->tokenPtr++; return JLexerT_BeginObject; case '\175': o->tokenPtr++; return JLexerT_EndObject; case '\133': o->tokenPtr++; return JLexerT_BeginArray; case '\135': o->tokenPtr++; return JLexerT_EndArray; case '\054': o->tokenPtr++; return JLexerT_Comma; case '\072': o->tokenPtr++; return JLexerT_MemberSep; case '\164': case '\124': case '\146': case '\106': o->state = JLexerSt_TrueFalseNull; o->retVal = JLexerT_Boolean; if(*o->tokenPtr == '\146' || *o->tokenPtr == '\124') { o->typeChkPtr = falseString; o->sn = FALSE; } else { o->typeChkPtr = trueString; o->sn = TRUE; } o->tokenPtr++; break; case '\156': case '\116': o->tokenPtr++; o->typeChkPtr = nullString; o->retVal = JLexerT_Null; o->state = JLexerSt_TrueFalseNull; break; case '\042': case '\047': baAssert(asmB->index==0); if(JDBuf_expandIfNeeded(o->asmB, 2)) return JLexerT_MemErr; o->sn = *o->tokenPtr++; o->state = JLexerSt_String; break; case '\040': case '\011': case '\012': case '\015': o->tokenPtr++; break; case '\055': o->tokenPtr++; o->sn = 255; o->state = JLexerSt_Number; baAssert(asmB->index==0); if(JDBuf_expandIfNeeded(o->asmB, 256)) return JLexerT_MemErr; break; case '\057': o->tokenPtr++; o->state = JLexerSt_StartComment; break; default: baAssert(asmB->index==0); if(isdigit(*o->tokenPtr)) { o->sn = 0; o->state = JLexerSt_Number; if(JDBuf_expandIfNeeded(o->asmB, 256)) return JLexerT_MemErr; break; } else return JLexerT_ParseErr; } } } } static int aintcconfig(JParser* o, JParsStat s, int handlersetup) { o->status = (U8)s; if(handlersetup) { o->stackIx=0; o->state = JParserSt_StartObj; } return handlersetup; } static int pinnedasids(JParser* o) { int handlersetup = JParserIntf_serviceCB(o->intf, &o->val, o->stackIx); if(handlersetup) aintcconfig(o, JParsStat_IntfErr, -1); o->val.memberName[0]=0; return handlersetup; } void JParser_constructor(JParser* o, JParserIntf* apecsmachine, char* pointertables, int simulatetable, AllocatorIntf* unmapaliases, int hotplugrange) { memset(o, 0, sizeof(JParser)); pcsxxstatus1(&o->mnameB, 0); o->val.memberName = pointertables; o->mnameB.buf = (U8*)pointertables; pointertables[0]=0; o->mnameB.size = (size_t)simulatetable; pcsxxstatus1(&o->asmB, unmapaliases); JLexer_constructor(&o->lexer,&o->asmB); o->intf = apecsmachine; o->status = JParsStat_DoneEOS; o->state = JParserSt_StartObj; o->stackIx = 0; o->stackSize = (U16)(JPARSER_STACK_LEN + hotplugrange); } void JParser_destructor(JParser* o) { JDBuf_destructor(&o->asmB); } int JParser_parse(JParser* o, const U8* buf, U32 icachealiases) { JLexerT lexerT; if(o->status == JParsStat_DoneEOS || o->status == JParsStat_NeedMoreData) JLexer_setBuf(&o->lexer,buf,icachealiases); else if(o->status != JParsStat_Done) { baAssert(o->status == JParsStat_ParseErr || o->status == JParsStat_MemErr || o->status == JParsStat_IntfErr); return -1; } for(;;) { lexerT = processorstate(&o->lexer); if(lexerT == JLexerT_NeedMoreData) return aintcconfig(o, JParsStat_NeedMoreData, 0); if(lexerT == JLexerT_ParseErr) return aintcconfig(o, JParsStat_ParseErr, -1); if(lexerT == JLexerT_MemErr) return aintcconfig(o, JParsStat_MemErr, -1); switch(o->state) { case JParserSt_StartObj: L_startObj: if( (o->stackIx + 1) >= o->stackSize) return aintcconfig(o, JParsStat_StackOverflow, -1); o->stack[o->stackIx] = (U8)lexerT; if(lexerT == JLexerT_BeginObject) { o->val.t = JParserT_BeginObject; o->lexer.asmB = &o->mnameB; o->state = JParserSt_MemberName; } else if(lexerT == JLexerT_BeginArray) { o->val.t = JParserT_BeginArray; o->state = JParserSt_BeginArray; } else return aintcconfig(o, JParsStat_ParseErr, -1); if(pinnedasids(o)) return -1; o->stackIx++; break; case JParserSt_BeginArray: if(lexerT == JLexerT_EndArray) goto L_endArray; else goto L_value; case JParserSt_MemberName: JDBuf_reset(&o->mnameB); o->lexer.asmB = &o->asmB; if(lexerT == JLexerT_EndObject) goto L_endObj; if(lexerT != JLexerT_String) return aintcconfig(o, JParsStat_ParseErr, -1); o->state = JParserSt_MemberSep; break; case JParserSt_MemberSep: if(lexerT != JLexerT_MemberSep) return aintcconfig(o, JParsStat_ParseErr, -1); o->state = JParserSt_Value; break; case JParserSt_Value: L_value: if(lexerT == JLexerT_BeginObject || lexerT == JLexerT_BeginArray) { goto L_startObj; } if(omap2pwrdm(&o->lexer, lexerT, &o->val)) return aintcconfig(o, JParsStat_ParseErr, -1); if(pinnedasids(o)) return -1; o->state = JParserSt_Comma; break; case JParserSt_Comma: if(o->stack[o->stackIx-1] == JLexerT_BeginObject) { if(lexerT == JLexerT_Comma) { o->lexer.asmB = &o->mnameB; o->state = JParserSt_MemberName; } else if(lexerT == JLexerT_EndObject) { L_endObj: if(o->stack[o->stackIx-1] != JLexerT_BeginObject) return aintcconfig(o, JParsStat_ParseErr, -1); o->val.t = JParserT_EndObject; o->stackIx--; if(pinnedasids(o)) return -1; if(o->stackIx == 0) { L_endParse: return aintcconfig( o, writeguest(&o->lexer) ? JParsStat_Done : JParsStat_DoneEOS, 1); } o->state = JParserSt_Comma; } else return aintcconfig(o, JParsStat_ParseErr, -1); } else { baAssert(o->stack[o->stackIx-1] == JLexerT_BeginArray); if(lexerT == JLexerT_Comma) o->state = JParserSt_Value; else if(lexerT == JLexerT_EndArray) { L_endArray: if(o->stack[o->stackIx-1] != JLexerT_BeginArray) return aintcconfig(o, JParsStat_ParseErr, -1); o->val.t = JParserT_EndArray; o->stackIx--; if(pinnedasids(o)) return -1; if(o->stackIx == 0) goto L_endParse; o->state = JParserSt_Comma; } else return aintcconfig(o, JParsStat_ParseErr, -1); } break; default: baAssert(0); } } } #ifndef BA_LIB #define BA_LIB #endif #include #include #include #ifndef EXT_SHARK_LIB #define sharkStrchr strchr #endif #include "SharkSslASN1.h" void SubjectAltNameEnumerator_constructor( SubjectAltNameEnumerator *o, U8 *ptr, U16 len) { baAssert(o); baAssert(ptr); o->ptr = ptr; o->len = len; } void SubjectAltNameEnumerator_getElement( SubjectAltNameEnumerator *o, SubjectAltName *s) { if ((o->len) && (SharkSslParseASN1_getContextSpecific( (SharkSslParseASN1*)o, &(s->tag)) == 0)) { baAssert(o->datalen < 0xFFFF); s->ptr = o->dataptr; s->len = (U16)o->datalen; } else { s->ptr = NULL; } } int sharkStrCaseCmp(const char *a, int enableblock, const char *b, int timerinterrupt) { if(enableblock == timerinterrupt) { register int n=-1; while((enableblock) && ((n = tolower((unsigned char)*a) - tolower((unsigned char)*b)) == 0)) { enableblock--; a++, b++; } return n; } return enableblock - timerinterrupt; } static int memblockregions(const char* cn, int cnl, const char* gpio1config, int alignresource) { if((cn[0] == '\052') && (cn[1] == '\056') && (cnl > 2)) { char* writereg16; if( ! sharkStrCaseCmp(cn+2,(cnl-2),gpio1config, alignresource) ) return 0; writereg16=sharkStrchr(gpio1config, '\056'); if(writereg16) { if( ! sharkStrCaseCmp(cn+2,(cnl-2),writereg16+1,alignresource - (int)(writereg16 - gpio1config) -1) ) return 0; } } return -1; } int sharkSubjectSubjectAltCmp(const char *cn, U16 registermmcsd1, U8 *programattributes, U16 smemcresume, const char* gpio1config, U16 alignresource) { if(cn && registermmcsd1) { if( ! sharkStrCaseCmp(cn, registermmcsd1, gpio1config, alignresource) || ! memblockregions(cn, registermmcsd1, gpio1config, alignresource)) { return 0; } } if (programattributes && smemcresume) { SubjectAltNameEnumerator se; SubjectAltName s; SubjectAltNameEnumerator_constructor(&se, programattributes, smemcresume); for (SubjectAltNameEnumerator_getElement(&se, &s); SubjectAltName_isValid(&s); SubjectAltNameEnumerator_nextElement(&se, &s)) { if (SUBJECTALTNAME_DNSNAME == SubjectAltName_getTag(&s)) { if( ! sharkStrCaseCmp((const char*)SubjectAltName_getPtr(&s), SubjectAltName_getLen(&s),gpio1config,alignresource) || ! memblockregions((const char*)SubjectAltName_getPtr(&s), SubjectAltName_getLen(&s),gpio1config, alignresource) ) { return 0; } } } } return -1; } #if SHARKSSL_CHECK_DATE BaTime sharkParseCertTime(const U8 *utc, U8 len) { int i; int dt[7]; if(len > 15) return 0; for (i = 0; i < (len >> 1); utc += 2, i++) { if (!isdigit(*utc)) break; dt[i] = 10 * (utc[0] - '\060') + (utc[1] - '\060'); } if(utc[0] == '\132' && (len == 13 || len == 15)) { #ifdef ThreadLib_hpp struct BaTm ts; BaTimeEx tex; memset(&ts,0,sizeof(ts)); if (len == 13) { ts.tm_sec = dt[5]; ts.tm_min = dt[4]; ts.tm_hour = dt[3]; ts.tm_mday = dt[2]; ts.tm_mon = dt[1]-1; ts.tm_year = dt[0]+2000; } else { ts.tm_sec = dt[6]; ts.tm_min = dt[5]; ts.tm_hour = dt[4]; ts.tm_mday = dt[3]; ts.tm_mon = dt[2] - 1; ts.tm_year = dt[1] + dt[0] * 100; } if(baTm2TimeEx(&ts, FALSE, &tex)) return 0; return tex.sec; #else struct tm ts; memset(&ts,0,sizeof(ts)); if (len == 13) { ts.tm_sec = dt[5]; ts.tm_min = dt[4]; ts.tm_hour = dt[3]; ts.tm_mday = dt[2]; ts.tm_mon = dt[1] - 1; ts.tm_year = dt[0] + 100; } else { ts.tm_sec = dt[6]; ts.tm_min = dt[5]; ts.tm_hour = dt[4]; ts.tm_mday = dt[3]; ts.tm_mon = dt[2] - 1; ts.tm_year = (dt[1] + dt[0] * 100) - 1900; } return (BaTime)mktime(&ts); #endif } return 0; } static SharkSslConTrust dbdmastart(SharkSslCertInfo* ci) { SharkSslCertInfo* instructioncounter; for(instructioncounter = ci ; instructioncounter ; instructioncounter = instructioncounter->parent) { if(instructioncounter->parent || instructioncounter == ci) { BaTime forcereload = sharkParseCertTime(instructioncounter->timeFrom, instructioncounter->timeFromLen); BaTime now = baGetUnixTime(); BaTime to = sharkParseCertTime(instructioncounter->timeTo, instructioncounter->timeToLen); if(forcereload == 0 || to == 0 || forcereload > (now+86400) || to < now) return SharkSslConTrust_CertCn; } } return SharkSslConTrust_CertCnDate; } #else #define dbdmastart(ci) SharkSslConTrust_CertCn #endif SHARKSSL_API SharkSslConTrust SharkSslCon_trusted(SharkSslCon *o, const char *gpio1config, SharkSslCertInfo **cPtr) { if(o) { SharkSslCertInfo* ci = SharkSslCon_getCertInfo(o); if(cPtr) { *cPtr = ci; } if(ci) { int usbsshwmod = SharkSslCon_trustedCA(o); if( !gpio1config ) { return usbsshwmod ? SharkSslConTrust_CertCn : SharkSslConTrust_None; } if (!sharkSubjectSubjectAltCmp((const char*)ci->subject.commonName, ci->subject.commonNameLen, ci->subjectAltNamesPtr, ci->subjectAltNamesLen, gpio1config, (U16)strlen(gpio1config))) { return usbsshwmod ? dbdmastart(ci) : SharkSslConTrust_Cn; } return usbsshwmod ? SharkSslConTrust_Cert : SharkSslConTrust_None; } return SharkSslConTrust_None; } if(cPtr) { *cPtr = 0; } return SharkSslConTrust_NotSSL; } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include #define JEncoder_isObject(o) \ ((o)->objectStack.data[((o)->objectStack.level/8)] & \ (1 << ((o)->objectStack.level%8))) #define JEncoder_setObject(o) \ (o)->objectStack.data[((o)->objectStack.level/8)] |= \ (1 << ((o)->objectStack.level%8)); #define JEncoder_clearObject(o) \ (o)->objectStack.data[((o)->objectStack.level/8)] &= \ ~(1 << ((o)->objectStack.level%8)); static int permissionfault(JEncoder* o) { JErr_setError(o->err, JErrT_IOErr, "\103\141\156\156\157\164\040\167\162\151\164\145"); return -1; } static int timerdispatch(JEncoder* o) { if(o->startNewObj) o->startNewObj = FALSE; else { if(BufPrint_printf(o->out,"\054")<0) { permissionfault(o); return -1; } } return 0; } static BaBool fixupdevice(JEncoder* o, BaBool registernorflash) { const char* mcbsppdata=0; if(JErr_isError(o->err)) return FALSE; if(JEncoder_isObject(o)) { if(registernorflash) { if(timerdispatch(o)) return FALSE; if(o->objectMember) mcbsppdata = "\104\165\160\154\151\143\141\164\145\040\143\141\154\154\040\164\157\040\156\141\155\145"; else o->objectMember=1; } else if(o->objectMember) o->objectMember = 0; else mcbsppdata = "\111\156\166\141\154\151\144\040\146\155\164\056\040\115\151\163\163\151\156\147\040\157\142\152\145\143\164\040\155\145\155\142\145\162\040\156\141\155\145"; } else { if(timerdispatch(o)) return FALSE; if(registernorflash) mcbsppdata="\111\156\166\141\154\151\144\040\146\155\164\040\151\156\040\156\141\155\145\056\040\116\157\164\040\141\156\040\157\142\152\145\143\164"; } if(mcbsppdata) { JErr_setError(o->err, JErrT_FmtValErr, mcbsppdata); return FALSE; } return TRUE; } void JEncoder_constructor(JEncoder* o, JErr* err, BufPrint* out) { memset(o, 0, sizeof(JEncoder)); o->err = err; o->out = out; o->startNewObj=TRUE; } int JEncoder_flush(JEncoder* o) { if(JErr_noError(o->err)) return BufPrint_flush(o->out); return -1; } int JEncoder_commit(JEncoder* o) { o->startNewObj=TRUE; return JEncoder_flush(o); } int JEncoder_setInt(JEncoder* o, S32 val) { if(fixupdevice(o, FALSE)) { if(BufPrint_printf(o->out, "\045\144", val)<0) return permissionfault(o); return 0; } return -1; } int JEncoder_setLong(JEncoder* o, S64 val) { if(fixupdevice(o, FALSE)) { if(BufPrint_printf(o->out, "\045\154\154\144", val)<0) return permissionfault(o); return 0; } return -1; } #ifndef NO_DOUBLE int JEncoder_setDouble(JEncoder* o, double val) { if(fixupdevice(o, FALSE)) { if(BufPrint_printf(o->out,"\045\146",val)<0) return permissionfault(o); return 0; } return -1; } #endif int JEncoder_setString(JEncoder* o, const char* val) { if(fixupdevice(o, FALSE)) { if(val) { if(BufPrint_jsonString(o->out,val)<0) return permissionfault(o); } else { if(BufPrint_write(o->out,"\156\165\154\154", -1)<0) return permissionfault(o); } return 0; } return -1; } int JEncoder_b64enc(JEncoder* o, const void* panicblock, S32 allockuser) { if(fixupdevice(o, FALSE)) { if(BufPrint_putc(o->out,'\042') || BufPrint_b64Encode(o->out,panicblock, allockuser)<0 || BufPrint_putc(o->out,'\042')) { return permissionfault(o); } } return -1; } int JEncoder_vFmtString(JEncoder* o, const char* fmt,va_list breakpointthread) { if(fixupdevice(o, FALSE)) { if(fmt) { if(BufPrint_putc(o->out,'\042') || BufPrint_vprintf(o->out,fmt,breakpointthread)<0 || BufPrint_putc(o->out,'\042')) { return permissionfault(o); } } else { if(BufPrint_write(o->out,"\156\165\154\154", -1)<0) return permissionfault(o); } return 0; } return -1; } int JEncoder_setBoolean(JEncoder* o, BaBool val) { if(fixupdevice(o, FALSE)) { if(BufPrint_printf(o->out,"\045\163",val?"\164\162\165\145":"\146\141\154\163\145")<0) return permissionfault(o); return 0; } return -1; } int JEncoder_setNull(JEncoder* o) { if(fixupdevice(o, FALSE)) { if(BufPrint_write(o->out, "\156\165\154\154", -1)<0) return permissionfault(o); return 0; } return -1; } #ifdef NO_JVAL_DEPENDENCY #define JEncoder_setJV(o,val,x) \ JErr_setError(o->err, JErrT_FmtValErr, "\106\145\141\164\165\162\145\040\047\112\047\040\104\151\163\141\142\154\145\144");return -1 #else int JEncoder_setJV(JEncoder* o, JVal* val, BaBool kaslroffset) { for(; val && JErr_noError(o->err); val=JVal_getNextElem(val)) { if( JVal_isObjectMember(val) && ! o->objectMember ) { JEncoder_setName(o, JVal_getName(val)); } switch(JVal_getType(val)) { case JVType_Null: JEncoder_setNull(o); break; case JVType_Boolean: JEncoder_setBoolean(o,JVal_getBoolean(val,o->err)); break; case JVType_Double: #ifdef NO_DOUBLE baAssert(0); #else JEncoder_setDouble(o, JVal_getDouble(val, o->err)); #endif break; case JVType_Int: JEncoder_setInt(o, JVal_getInt(val, o->err)); break; case JVType_Long: JEncoder_setLong(o, JVal_getLong(val, o->err)); break; case JVType_String: JEncoder_setString(o, JVal_getString(val, o->err)); break; case JVType_Object: JEncoder_beginObject(o); JEncoder_setJV(o, JVal_getObject(val, o->err),TRUE); JEncoder_endObject(o); break; case JVType_Array: JEncoder_beginArray(o); JEncoder_setJV(o, JVal_getArray(val, o->err), TRUE); JEncoder_endArray(o); break; default: baAssert(0); } if( !kaslroffset ) break; } return JErr_noError(o->err) ? 0 : -1; } #endif int JEncoder_setName(JEncoder* o, const char* gpio1config) { if(fixupdevice(o, TRUE)) { if(BufPrint_printf(o->out, "\042\045\163\042\072", gpio1config)<0) return permissionfault(o); return 0; } return -1; } int JEncoder_beginObject(JEncoder* o) { if(fixupdevice(o, FALSE)) { if(o->objectStack.level < (S32)(sizeof(o->objectStack.data)*8-1)) { o->objectStack.level++; JEncoder_setObject(o); if(BufPrint_write(o->out, "\173", -1)<0) return permissionfault(o); o->startNewObj=TRUE; return 0; } JErr_setError(o->err, JErrT_FmtValErr, "\117\142\152\145\143\164\040\156\145\163\164\145\144\040\164\157\157\040\144\145\145\160"); } return -1; } int JEncoder_endObject(JEncoder* o) { if(JErr_noError(o->err)) { if(o->objectStack.level > 0) { if(JEncoder_isObject(o)) { if(BufPrint_printf(o->out, "\175", -1)<0) return permissionfault(o); JEncoder_clearObject(o); o->objectStack.level--; o->startNewObj=FALSE; return 0; } JErr_setError(o->err, JErrT_FmtValErr, "\145\156\144\117\142\152\145\143\164\072\040\116\157\164\040\141\156\040\157\142\152\145\143\164"); } else JErr_setError(o->err, JErrT_FmtValErr, "\145\156\144\117\142\152\145\143\164\072\040\125\156\162\157\154\154\145\144\040\164\157\157\040\155\141\156\171\040\164\151\155\145\163"); } return -1; } int JEncoder_beginArray(JEncoder* o) { if(fixupdevice(o, FALSE)) { if(o->objectStack.level < (S32)(sizeof(o->objectStack.data)*8)) { o->objectStack.level++; if(BufPrint_printf(o->out, "\133", -1)<0) return permissionfault(o); o->startNewObj=TRUE; return 0; } JErr_setError(o->err, JErrT_FmtValErr, "\101\162\162\141\171\040\156\145\163\164\145\144\040\164\157\157\040\144\145\145\160"); } return -1; } int JEncoder_endArray(JEncoder* o) { if(JErr_noError(o->err)) { if(o->objectStack.level > 0) { if( ! JEncoder_isObject(o) ) { if(BufPrint_printf(o->out, "\135", -1)<0) return permissionfault(o); o->objectStack.level--; o->startNewObj=FALSE; return 0; } JErr_setError(o->err, JErrT_FmtValErr, "\145\156\144\101\162\162\141\171\072\040\111\163\040\157\142\152\145\143\164"); } else JErr_setError(o->err, JErrT_FmtValErr, "\145\156\144\101\162\162\141\171\072\040\125\156\162\157\154\154\145\144\040\164\157\157\040\155\141\156\171\040\164\151\155\145\163"); } return -1; } static int icacheflush(JEncoder* o, const char sha256export, void* lcdspigpiod, int len) { int i; JEncoder_beginArray(o); for(i = 0 ; i < len ; i++) { if(JErr_isError(o->err)) return -1; switch(sha256export) { case '\142': JEncoder_setBoolean(o, ((BaBool*)lcdspigpiod)[i]); break; case '\144': JEncoder_setInt(o, ((S32*)lcdspigpiod)[i]); break; case '\146': JEncoder_setDouble(o, ((double*)lcdspigpiod)[i]); break; case '\163': JEncoder_setString(o, ((const char**)lcdspigpiod)[i]); break; case '\112': JEncoder_setJV(o, ((JVal**)lcdspigpiod)[i], FALSE); break; default: JErr_setError( o->err, JErrT_FmtValErr, "\125\156\153\156\157\167\156\040\157\162\040\151\154\154\145\147\141\154\040\146\157\162\155\141\164\040\146\154\141\147\040\151\156\040\141\162\162\141\171\040\146\154\141\147\040\047\101\047"); } } JEncoder_endArray(o); return 0; } int JEncoder_vSetJV(JEncoder* o, const char** fmt, va_list* breakpointthread) { union { const void* p; int len; } u; for( ; **fmt ; (*fmt)++) { if(JErr_isError(o->err)) return -1; if(**fmt == '\175' || **fmt == '\135') { if(o->objectStack.level == 0) { JErr_setError(o->err, JErrT_FmtValErr, "\112\105\156\143\157\144\145\162\072\072\163\145\164\040\115\151\163\155\141\164\143\150\145\144\040\047\135\047\040\157\162\040\047\175\047"); return -1; } return 0; } if(JEncoder_isObject(o)) JEncoder_setName(o,va_arg(*breakpointthread, char*)); switch(**fmt) { case '\142': JEncoder_setBoolean(o, (BaBool)va_arg(*breakpointthread, int)); break; case '\144': JEncoder_setInt(o, va_arg(*breakpointthread, S32)); break; case '\154': JEncoder_setLong(o, va_arg(*breakpointthread, S64)); break; case '\146': JEncoder_setDouble(o, va_arg(*breakpointthread, double)); break; case '\163': JEncoder_setString(o, va_arg(*breakpointthread, char*)); break; case '\156': JEncoder_setNull(o); break; case '\112': JEncoder_setJV(o, va_arg(*breakpointthread, JVal*), FALSE); break; case '\101': u.len = va_arg(*breakpointthread, int); icacheflush( o,*++(*fmt),va_arg(*breakpointthread,void*),u.len); break; case '\133': (*fmt)++; JEncoder_beginArray(o); JEncoder_vSetJV(o, fmt, breakpointthread); JEncoder_endArray(o); if(**fmt != '\135') { JErr_setError( o->err, JErrT_FmtValErr, "\112\105\156\143\157\144\145\162\072\072\163\145\164\040\105\156\144\040\157\146\040\141\162\162\141\171\040\146\154\141\147\040\047\135\047\040\156\157\164\040\146\157\165\156\144"); return -1; } break; case '\173': (*fmt)++; JEncoder_beginObject(o); JEncoder_vSetJV(o, fmt, breakpointthread); JEncoder_endObject(o); if(**fmt != '\175') { JErr_setError( o->err, JErrT_FmtValErr, "\112\105\156\143\157\144\145\162\072\072\163\145\164\040\105\156\144\040\157\146\040\157\142\152\145\143\164\040\146\154\141\147\040\047\175\047\040\156\157\164\040\146\157\165\156\144"); return -1; } break; default: JErr_setError(o->err, JErrT_FmtValErr, "\112\105\156\143\157\144\145\162\072\072\163\145\164\040\125\156\153\156\157\167\156\040\146\157\162\155\141\164\040\146\154\141\147"); } } return JErr_noError(o->err) ? 0 : -1; } int JEncoder_set(JEncoder* o, const char* fmt, ...) { int handlersetup; va_list demuxregids; va_start(demuxregids, fmt); handlersetup = JEncoder_vSetJV(o, &fmt, &demuxregids); if(handlersetup) JErr_setError(o->err, JErrT_FmtValErr, "\077"); va_end(demuxregids); return handlersetup; } #ifndef BA_LIB #define BA_LIB #endif #define _SHARKSSL_C_ #undef _SHARKSSL_C_ #include #if (SHARKSSL_SSL_SERVER_CODE || SHARKSSL_SSL_CLIENT_CODE) SHARKSSL_API void SharkSsl_constructor( SharkSsl *o, SharkSsl_Role startkernel, U16 detectbootwidth, U16 inBufStartSize, U16 outBufSize ) { baAssert(o); baAssert(NULL == (void*)0); #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_SSL_CLIENT_CODE) baAssert((startkernel == SharkSsl_Server) || (startkernel == SharkSsl_Client)); o->role = startkernel; #else #if SHARKSSL_SSL_SERVER_CODE baAssert(startkernel == SharkSsl_Server); #elif SHARKSSL_SSL_CLIENT_CODE baAssert(startkernel == SharkSsl_Client); #endif (void)startkernel; #endif o->inBufStartSize = inBufStartSize; o->outBufSize = outBufSize; o->nCon = 0; #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) SingleList_constructor(&o->certList); #if SHARKSSL_ENABLE_CA_LIST o->caList = 0; #endif #endif #if SHARKSSL_ENABLE_SESSION_CACHE counter1clocksource(&o->sessionCache, detectbootwidth); o->intf = 0; #else (void)detectbootwidth; #endif } SHARKSSL_API void SharkSsl_destructor(SharkSsl *o) { #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) SharkSslCertList *link; while((link = (SharkSslCertList*)SingleList_removeFirst(&o->certList)) != 0) { baFree(link); } #endif baAssert(o); baAssert(o->nCon == 0); #if SHARKSSL_ENABLE_SESSION_CACHE if (o->intf) { o->intf->terminate(o->intf, o); } defaultsdhci0(&o->sessionCache); #endif memset(o, 0, sizeof(SharkSsl)); } SharkSslCon *SharkSsl_createCon(SharkSsl *o) { SharkSslCon *s; baAssert(o); s = (SharkSslCon*)baMalloc(pcmciapdata(sizeof(SharkSslCon))); if (s != NULL) { #if SHARKSSL_UNALIGNED_MALLOC SharkSslCon *su = s; s = (SharkSslCon*)selectaudio(s); conditionvalid(s, o); s->mem = su; #else conditionvalid(s, o); #endif o->nCon++; } return s; } void SharkSsl_terminateCon(const SharkSsl *o, SharkSslCon *emulaterd8rn16) { #if SHARKSSL_UNALIGNED_MALLOC SharkSslCon *sslConMem = emulaterd8rn16->mem; baAssert(sslConMem); #endif baAssert(emulaterd8rn16); baAssert((!o) || (o == emulaterd8rn16->sharkSsl)); baAssert(emulaterd8rn16->sharkSsl->nCon); (void)o; emulaterd8rn16->sharkSsl->nCon--; localenable(emulaterd8rn16); #if SHARKSSL_UNALIGNED_MALLOC baFree(sslConMem); #else baFree(emulaterd8rn16); #endif } #if SHARKSSL_ENABLE_SESSION_CACHE U16 SharkSsl_getCacheSize(SharkSsl *o) { baAssert(o); return (o->sessionCache.cacheSize); } #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) SHARKSSL_API U8 SharkSsl_addCertificate(SharkSsl *o, SharkSslCert kernelvaddr) { SharkSslCertList *c; SharkSslCertKey sourcerouting; int modulesemaphore; baAssert(o); if (0 == o->nCon) { c = (SharkSslCertList*)baMalloc(sizeof(SharkSslCertList)); if (c) { #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) SharkSslCertInfo cp; #endif if ((c->certP.msgLen = setupboard(kernelvaddr)) == 0) { goto _SharkSsl_addCertificate_exit; } #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) if (spromregister((SharkSslCertParam*)&cp, (U8*)kernelvaddr, (U32)-3, (U8*)&modulesemaphore) < 0) { goto _SharkSsl_addCertificate_exit; } #else modulesemaphore = spromregister(0, (U8*)kernelvaddr, (U32)-1, 0); if (modulesemaphore < 0) { goto _SharkSsl_addCertificate_exit; } #endif if (0 == interrupthandler(&sourcerouting, kernelvaddr)) { goto _SharkSsl_addCertificate_exit; } if (machinekexec(sourcerouting.expLen)) { c->certP.keyType = ahashchild; c->certP.keyOID = camerareset(sourcerouting.modLen); } else if (machinereboot(sourcerouting.expLen)) { c->certP.keyType = compatrestart; c->certP.keyOID = wakeupenable(sourcerouting.modLen); } else { _SharkSsl_addCertificate_exit: baFree(c); return 0; } c->certP.cert = kernelvaddr; c->certP.signatureAlgo = (modulesemaphore & 0xFF); c->certP.hashAlgo = ((modulesemaphore >> 8) & 0xFF); #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SNI) c->certP.commonName = cp.subject.commonName; c->certP.commonNameLen = cp.subject.commonNameLen; c->certP.subjectAltNamesPtr = cp.subjectAltNamesPtr; c->certP.subjectAltNamesLen = cp.subjectAltNamesLen; #endif SingleLink_constructor((SingleLink*)c); SingleList_insertLast(&o->certList, (SingleList*)c); return 1; } } return 0; } #if SHARKSSL_ENABLE_CA_LIST SHARKSSL_API U8 SharkSsl_setCAList(SharkSsl *o, SharkSslCAList displaysetup) { baAssert(o); if (0 == o->nCon) { o->caList = displaysetup; return 1; } return 0; } #endif #endif #endif #ifndef BA_LIB #define BA_LIB 1 #endif #include #include static void fpsimdbegin( JVal* o,JErr* err,const char sha256export,void* lcdspigpiod,int len); static void JVal_extractObject( JVal* o,JErr* err,const char** fmt,va_list* breakpointthread); static JVal* JVal_extract( JVal* o,JErr* err,const char** fmt, va_list* breakpointthread); static int pcimtsetup(JVal* o, JVal* checkstack, JParserVal* pv, AllocatorIntf* threadcleanup) { memset(o, 0, sizeof(JVal)); if(*pv->memberName) { o->memberName = baStrdup2(threadcleanup, pv->memberName); if( ! o->memberName ) return -1; } switch(pv->t) { case JParserT_String: o->type = JVType_String; o->v.s = (U8*)baStrdup2(threadcleanup, (char*)pv->v.s); if( ! o->v.s ) { if(o->memberName) AllocatorIntf_free(threadcleanup, o->memberName); return -1; } break; case JParserT_Double: #ifdef NO_DOUBLE baAssert(0); #else o->v.f=pv->v.f; #endif o->type = JVType_Double; break; case JParserT_Int: o->v.d=pv->v.d; o->type = JVType_Int; break; case JParserT_Long: o->v.l=pv->v.l; o->type = JVType_Long; break; case JParserT_Boolean: o->v.b=pv->v.b; o->type = JVType_Boolean; break; case JParserT_Null: o->type = JVType_Null; break; case JParserT_BeginObject: o->type = JVType_Object; break; case JParserT_BeginArray: o->type = JVType_Array; break; default: baAssert(0); } if(checkstack) { if(checkstack->v.firstChild) { JVal* instructioncounter = checkstack->v.firstChild; while(instructioncounter->next) instructioncounter = instructioncounter->next; instructioncounter->next = o; } else checkstack->v.firstChild = o; } return 0; } static int JVal_extractValue(JVal* o, JErr* err, const char** fmt, va_list* breakpointthread) { union { BaBool* b; S32* d; S64* l; double* f; const char** s; void* p; JVal** j; } u; switch(**fmt) { case '\142': u.b = va_arg(*breakpointthread, BaBool*); *u.b = JVal_getBoolean(o, err); return 0; case '\144': u.d = va_arg(*breakpointthread, S32*); *u.d = JVal_getInt(o, err); return 0; case '\154': u.l = va_arg(*breakpointthread, S64*); *u.l = JVal_getLong(o, err); return 0; #ifndef NO_DOUBLE case '\146': u.f = va_arg(*breakpointthread, double*); *u.f = JVal_getDouble(o, err); return 0; #endif case '\163': u.s = va_arg(*breakpointthread, const char**); *u.s = JVal_getString(o, err); return 0; case '\112': u.j = va_arg(*breakpointthread, JVal**); *u.j = o; return 0; case '\101': u.p = va_arg(*breakpointthread, void*); fpsimdbegin(JVal_getArray(o,err), err, *++(*fmt), u.p, va_arg(*breakpointthread, int)); return 0; case '\133': (*fmt)++; JVal_extract(JVal_getArray(o,err),err,fmt,breakpointthread); if(**fmt != '\135') { JErr_setError(err, JErrT_FmtValErr, "\105\156\144\040\157\146\040\141\162\162\141\171\040\146\154\141\147\040\047\135\047\040\156\157\164\040\146\157\165\156\144"); return 1; } return 0; case '\135': return 1; case '\173': (*fmt)++; JVal_extractObject( JVal_getObject(o,err),err,fmt,breakpointthread); return 0; case '\175': return 1; default: JErr_setError(err, JErrT_FmtValErr, "\125\156\153\156\157\167\156\040\146\157\162\155\141\164\040\146\154\141\147"); } return -1; } static void fpsimdbegin(JVal* o, JErr* err, const char sha256export, void* lcdspigpiod, int len) { int i; if(!o) return; for(i = 0 ; i < len ; i++) { if(!o) JErr_setTooFewParams(err); if(JErr_isError(err)) return; switch(sha256export) { case '\142': ((BaBool*)lcdspigpiod)[i] = JVal_getBoolean(o, err); break; case '\144': ((S32*)lcdspigpiod)[i] = JVal_getInt(o, err); break; case '\154': ((S64*)lcdspigpiod)[i] = JVal_getLong(o, err); break; #ifndef NO_DOUBLE case '\146': ((double*)lcdspigpiod)[i] = JVal_getDouble(o, err); break; #endif case '\163': ((const char**)lcdspigpiod)[i] = JVal_getString(o, err); break; case '\112': ((JVal**)lcdspigpiod)[i] = o; break; default: JErr_setError( err, JErrT_FmtValErr, "\125\156\153\156\157\167\156\040\157\162\040\151\154\154\145\147\141\154\040\146\157\162\155\141\164\040\146\154\141\147\040\151\156\040\141\162\162\141\171\040\146\154\141\147\040\047\101\047"); } o = JVal_getNextElem(o); } } static void JVal_extractObject(JVal* o,JErr* err,const char** fmt,va_list* breakpointthread) { if(!o) return; for( ; **fmt && **fmt != '\175' && JErr_noError(err) ; (*fmt)++) { const char* n; const char* gpio1config = va_arg(*breakpointthread, const char*); JVal* instructioncounter = o; while(instructioncounter && (n = JVal_getName(instructioncounter))!=0 && strcmp(gpio1config,n) ) instructioncounter = JVal_getNextElem(instructioncounter); if(!instructioncounter) { JErr_setError(err, JErrT_InvalidMethodParams, "\115\145\155\142\145\162\040\156\141\155\145\040\156\157\164\040\146\157\165\156\144\040\151\156\040\157\142\152\145\143\164"); return; } if(JVal_extractValue(instructioncounter, err, fmt, breakpointthread)) { JErr_setError( err, JErrT_FmtValErr, "\104\145\164\145\143\164\145\144\040\155\151\163\155\141\164\143\150\145\144\040\157\142\152\145\143\164\040\141\156\144\040\141\162\162\141\171\040\146\157\162\155\141\164\040\146\154\141\147\163"); return; } } if(**fmt != '\175') { JErr_setError( err, JErrT_FmtValErr, "\106\157\162\155\141\164\040\145\162\162\157\162\072\040\105\156\144\040\157\146\040\157\142\152\145\143\164\040\047\175\047\040\156\157\164\040\146\157\165\156\144"); } } static JVal* JVal_extract(JVal* o,JErr* err,const char** fmt, va_list* breakpointthread) { for( ; **fmt ; (*fmt)++) { if(JErr_isError(err)) return 0; if(JVal_extractValue(o, err, fmt, breakpointthread)) break; if(!o) { JErr_setTooFewParams(err); return 0; } o = JVal_getNextElem(o); } return o; } JVal* JVal_vget(JVal* o,JErr* err,const char** fmt, va_list* breakpointthread) { o = JVal_extract(o,err,fmt,breakpointthread); if(**fmt) { JErr_setTooFewParams(err); return 0; } return o; } JVal* JVal_get(JVal* o, JErr* err, const char* fmt, ...) { JVal* handlersetup; va_list demuxregids; va_start(demuxregids, fmt); handlersetup = JVal_vget(o, err, &fmt, &demuxregids); va_end(demuxregids); return handlersetup; } S32 JVal_getInt(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Int) return o->v.d; #ifndef NO_DOUBLE if(o->type == JVType_Double) return (S32)o->v.f; #endif if(o->type == JVType_Long) return (S32)o->v.l; else if(o->type == JVType_Boolean) return (S32)o->v.b; else if(o->type == JVType_Null) return 0; JErr_setTypeErr(e, JVType_Int, o->type); } else JErr_setTooFewParams(e); return 0; } S64 JVal_getLong(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Long) return o->v.l; #ifndef NO_DOUBLE if(o->type == JVType_Double) return (S64)o->v.f; #endif if(o->type == JVType_Int) return (S64)o->v.d; else if(o->type == JVType_Boolean) return (S64)o->v.b; else if(o->type == JVType_Null) return 0; JErr_setTypeErr(e, JVType_Long, o->type); } else JErr_setTooFewParams(e); return 0; } #ifndef NO_DOUBLE double JVal_getDouble(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Double) return o->v.f; if(o->type == JVType_Int) return (double)o->v.d; if(o->type == JVType_Long) return (double)o->v.l; else if(o->type == JVType_Boolean) return (double)o->v.b; else if(o->type == JVType_Null) return 0; JErr_setTypeErr(e, JVType_Double, o->type); } else JErr_setTooFewParams(e); return 0; } #endif BaBool JVal_getBoolean(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Boolean) return o->v.b; else if(o->type == JVType_Null) return FALSE; JErr_setTypeErr(e, JVType_Boolean, o->type); } else JErr_setTooFewParams(e); return FALSE; } const char* JVal_getString(JVal* o, JErr* e) { if(o) { if(o->type == JVType_String) return (char*)o->v.s; else if(o->type == JVType_Null) return 0; JErr_setTypeErr(e, JVType_String, o->type); } else JErr_setTooFewParams(e); return 0; } char* JVal_manageString(JVal* o, JErr* e) { if(o) { if(o->type == JVType_String) { char* ptr = (char*)o->v.s; o->v.s=0; return ptr; } JErr_setTypeErr(e, JVType_String, o->type); } else JErr_setTooFewParams(e); return 0; } const char* JVal_getName(JVal* o) { return o ? o->memberName : 0; } char* JVal_manageName(JVal* o) { if(o) { char* ptr = o->memberName; o->memberName=0; return ptr; } return 0; } JVal* JVal_getObject(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Object) return o->v.firstChild; JErr_setTypeErr(e, JVType_Object, o->type); } else JErr_setTooFewParams(e); return 0; } JVal* JVal_getArray(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Array) return o->v.firstChild; JErr_setTypeErr(e, JVType_Array, o->type); } else JErr_setTooFewParams(e); return 0; } JVal* JVal_getJ(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Array || o->type == JVType_Object) return o->v.firstChild; JErr_setTypeErr(e, JVType_Object, o->type); } else JErr_setTooFewParams(e); return 0; } JVal* JVal_manageJ(JVal* o, JErr* e) { if(o) { if(o->type == JVType_Array || o->type == JVType_Object) { JVal* handlersetup = o->v.firstChild; o->v.firstChild=0; return handlersetup; } JErr_setTypeErr(e, JVType_Object, o->type); } else JErr_setTooFewParams(e); return 0; } S32 JVal_getLength(struct JVal* o, JErr* e) { o = JVal_getJ(o, e); if(o) { S32 len=1; while( (o = JVal_getNextElem(o)) != 0) len++; return len; } return 0; } void JVal_setX(JVal* o, JErr* e, JVType t, void* v) { if(o->type == JVType_Array || o->type == JVType_Object) { JErr_setTypeErr(e, o->type, t); return; } if(o->type == JVType_String && o->v.s) { JErr_setError(e,JErrT_MemErr, "\112\126\141\154\072\072\163\145\164\130\040\163\164\162\151\156\147\040\155\165\163\164\040\142\145\040\155\141\156\141\147\145\144"); return; } o->type = t; switch(t) { case JVType_String: o->v.s=(U8*)v; break; case JVType_Double: #ifdef NO_DOUBLE o->v.l=*((S64*)v); #else o->v.f=*((double*)v); #endif break; case JVType_Int: o->v.d=*((S32*)v); break; case JVType_Long: o->v.l=*((S64*)v); break; case JVType_Boolean: o->v.b = *((BaBool*)v) ? TRUE : FALSE; break; case JVType_Null: break; default: baAssert(0); } } int JVal_unlink(JVal* o, JVal* writeretired) { if( (o->type == JVType_Object || o->type == JVType_Array) && o->v.firstChild ) { JVal* instructioncounter; if(writeretired == o->v.firstChild) { o->v.firstChild = writeretired->next; writeretired->next=0; return 0; } instructioncounter = o->v.firstChild; while(instructioncounter->next && instructioncounter->next != writeretired) instructioncounter = instructioncounter->next; if(instructioncounter->next) { instructioncounter->next = writeretired->next; writeretired->next=0; return 0; } } return -1; } static int segmentnumber(JVal* o, JVal* writeretired) { if(writeretired->next) return -1; writeretired->next=o->v.firstChild; o->v.firstChild=writeretired; return 0; } int JVal_addMember(JVal* o, JErr* e, const char* resetcontrol, JVal* writeretired, AllocatorIntf* threadcleanup) { if(JErr_noError(e)) { if(o->type == JVType_Object) { if( ! writeretired->memberName ) { writeretired->memberName = threadcleanup ? baStrdup2(threadcleanup, resetcontrol) : (char*)resetcontrol; } if(writeretired->memberName) return segmentnumber(o, writeretired); JErr_setError(e,JErrT_MemErr,0); } else JErr_setTypeErr(e, JVType_Int, o->type); } return -1; } int JVal_add(JVal* o, JErr* e, JVal* writeretired) { if(JErr_noError(e)) { if(o->type == JVType_Array) return segmentnumber(o, writeretired); JErr_setTypeErr(e, JVType_Int, o->type); } return -1; } void JVal_terminate(JVal* o, AllocatorIntf* scacherange, AllocatorIntf* threadcleanup) { while(o) { JVal* prctlenable = o->next; if(o->type == JVType_Object || o->type == JVType_Array) JVal_terminate(o->v.firstChild, scacherange, threadcleanup); else if(o->type == JVType_String) AllocatorIntf_free(threadcleanup, o->v.s); if(o->memberName) AllocatorIntf_free(threadcleanup, o->memberName); AllocatorIntf_free(scacherange, o); o = prctlenable; } } static int platformcreate(JParserValFact* o) { size_t indexnospec = (o->vStackSize + 32) * sizeof(void*); JVal** v = o->vStack ? AllocatorIntf_realloc(o->dAlloc, o->vStack, &indexnospec) : AllocatorIntf_malloc(o->dAlloc, &indexnospec); if(v) { o->vStack = v; o->vStackSize=(int)(indexnospec/sizeof(void*)); return 0; } o->status=JParserValFactStat_DMemErr; return -1; } static int devicecfcon(JParserIntf* fdc37m81xconfig, JParserVal* pv, int classifysyscall) { JVal* v; size_t jValSize = sizeof(JVal); JParserValFact* o = (JParserValFact*)fdc37m81xconfig; if(pv->t == JParserT_EndObject || pv->t == JParserT_EndArray) return 0; if(++o->nodeCounter >= o->maxNodes) { o->status=JParserValFactStat_MaxNodes; return -1; } if(classifysyscall >= o->vStackSize && platformcreate(o)) return -1; if( (v = AllocatorIntf_malloc(o->vAlloc, &jValSize)) == 0 ) { o->status=JParserValFactStat_VMemErr; return -1; } if(pcimtsetup(v, classifysyscall ? o->vStack[classifysyscall-1] : 0, pv, o->dAlloc)) { o->status=JParserValFactStat_VMemErr; AllocatorIntf_free(o->vAlloc, v); return -1; } if(pv->t == JParserT_BeginObject || pv->t == JParserT_BeginArray) o->vStack[classifysyscall] = v; return 0; } void JParserValFact_constructor( JParserValFact* o, AllocatorIntf* scacherange, AllocatorIntf* threadcleanup) { memset(o, 0, sizeof(JParserValFact)); o->vAlloc=scacherange; o->dAlloc=threadcleanup; JParserIntf_constructor((JParserIntf*)o, devicecfcon); o->maxNodes=~(U32)0; } JVal* JParserValFact_manageFirstVal(JParserValFact* o) { if(o->vStack && *o->vStack) { JVal* v = *o->vStack; *o->vStack = 0; o->nodeCounter=0; return v; } return 0; } void JParserValFact_termFirstVal(JParserValFact* o) { if(o->vStack) { if(o->vStack) { JVal_terminate(*o->vStack, o->vAlloc, o->dAlloc); *o->vStack=0; o->nodeCounter=0; } AllocatorIntf_free(o->dAlloc, o->vStack); o->vStack=0; o->vStackSize=0; } } void JParserValFact_destructor(JParserValFact* o) { JParserValFact_termFirstVal(o); } void JValFact_constructor(JValFact* o, AllocatorIntf* scacherange, AllocatorIntf* threadcleanup) { memset(o, 0, sizeof(JValFact)); o->vAlloc=scacherange; o->dAlloc=threadcleanup; } JVal* JValFact_mkVal(JValFact* o, JVType t, const void* uv) { size_t icachealiases=sizeof(JVal); JVal* v = (JVal*)AllocatorIntf_malloc(o->vAlloc,&icachealiases); if(v) { memset(v,0,sizeof(JVal)); v->type = t; switch(t) { case JVType_String: v->v.s=(U8*)baStrdup2(o->dAlloc, (const char*)uv); if(!v->v.s) t = JVType_InvalidType; break; case JVType_Double: #ifdef NO_DOUBLE v->v.l=*((S64*)uv); #else v->v.f=*((double*)uv); #endif break; case JVType_Int: v->v.d=*((S32*)uv); break; case JVType_Long: v->v.l=*((S64*)uv); break; case JVType_Boolean: v->v.b = *((BaBool*)uv) ? TRUE : FALSE; break; case JVType_Null: case JVType_Object: case JVType_Array: break; default: baAssert(0); t = JVType_InvalidType; } if(t != JVType_InvalidType) return v; AllocatorIntf_free(o->vAlloc, v); } return 0; } #ifndef BA_LIB #define BA_LIB #endif #define MAX_SHARK_BUF_SIZE 0xFFFF #include #include #include #if SHARKSSL_ENABLE_SESSION_CACHE #include #endif typedef struct { SharkSslCon super; DoubleLink link; SoDispCon* con; /* Owner of BaSharkSslCon */ char* host; U16 port; } BaSharkSslCon; #ifdef HTTP_TRACE static void gpio6resources(int reservevmcore, SoDispCon* con) { char removestate[60]; HttpSockaddr serialports; SoDispCon_getPeerName(con,&serialports,0); SoDispCon_addr2String(con, &serialports, removestate, sizeof(removestate)); removestate[59]=0; HttpTrace_write(reservevmcore,removestate, -1); } #endif BA_API int SoDispCon_getSharkAlert(SoDispCon* o, U8* disableerrgen, U8* local1irqdispatch) { if(o->sslData) { SharkSslCon *s = (SharkSslCon*)o->sslData; *disableerrgen=SharkSslCon_getAlertLevel(s); *local1irqdispatch=SharkSslCon_getAlertDescription(s); return 0; } return -1; } static int tsx09parse(SoDispCon* con, int handlersetup) { int x,desc; SharkSslCon *s = (SharkSslCon*)con->sslData; switch (handlersetup) { case SharkSslCon_AlertSend: { BaBool queueevent=FALSE; ThreadMutex* m=0; #ifdef HTTP_TRACE gpio6resources(12, con); HttpTrace_printf( 11, "\040\123\150\141\162\153\123\123\114\040\072\040\123\145\156\164\040\141\154\145\162\164\040\155\145\163\163\141\147\145\054\040\154\145\166\145\154\040\045\144\054\040\144\145\163\143\162\151\160\164\151\157\156\040\045\144\012", SharkSslCon_getAlertLevel(s), SharkSslCon_getAlertDescription(s)); #endif x = SharkSslCon_getAlertDataLen(s); baAssert(x); HttpSocket_send(&con->httpSocket, m, &queueevent, SharkSslCon_getAlertData(s), x, &x); (void)queueevent; return E_SOCKET_WRITE_FAILED; } case SharkSslCon_AlertRecv: x=SharkSslCon_getAlertLevel(s); desc=SharkSslCon_getAlertDescription(s); if(x == 1 && desc == 0) return E_TLS_CLOSE_NOTIFY; #ifdef HTTP_TRACE gpio6resources(12, con); HttpTrace_printf( 11, "\040\123\150\141\162\153\123\123\114\040\072\040\122\145\143\145\151\166\145\144\040\141\154\145\162\164\054\040\154\145\166\145\154\040\045\144\054\040\144\145\163\143\162\151\160\164\151\157\156\040\045\144\012", x, desc); #endif return E_SHARK_ALERT_RECV; case SharkSslCon_Error: #ifdef HTTP_TRACE gpio6resources(12, con); HttpTrace_printf( 11,"\040\123\150\141\162\153\123\123\114\072\040\103\162\171\160\164\157\040\146\141\151\154\165\162\145\040\144\165\162\151\156\147\040\145\156\143\162\171\160\164\057\144\145\143\162\171\160\164\040\157\160\145\162\141\164\151\157\156\040" "\050\045\144\051\012", debugdestroy(s)); #endif return E_TLS_CRYPTOERR; case SharkSslCon_AllocationError: #ifdef HTTP_TRACE HttpTrace_printf( 0,"\123\150\141\162\153\123\123\114\072\040\101\154\154\157\143\040\145\162\162\157\162\040\144\165\162\151\156\147\040\145\156\143\162\171\160\164\057\144\145\143\162\171\160\164\040\157\160\145\162\141\164\151\157\156\012"); #endif return E_MALLOC; case SharkSslCon_HandshakeNotComplete: #ifdef HTTP_TRACE gpio6resources(5, con); HttpTrace_printf(5,"\040\123\150\141\162\153\123\123\114\040\072\040\110\141\156\144\163\150\141\153\145\040\156\157\164\040\143\157\155\160\154\145\164\145\012"); #endif return E_TLS_HANDSHAKE; default: baAssert(0); return -1; } } static int belowstart(SoDispCon* con, ThreadMutex* m, void* buf, int masterclock) { int sockLen, nb, handlersetup; SharkSslCon *s = (SharkSslCon*)con->sslData; BaBool queueevent=FALSE; sockLen=0; for (;;) { switch (handlersetup = SharkSslCon_decrypt(s, (U16)sockLen)) { case SharkSslCon_NeedMoreData: if(con->recTermPtr) return E_SOCKET_READ_FAILED; if( ! SoDispCon_socketHasNonBlockData(con) ) { SoDispCon_clearHasMoreData(con); if( ! SoDispCon_isNonBlocking(con) ) return 0; } con->recTermPtr=&queueevent; sockLen=SoDispCon_platReadData(con,m,&queueevent, SharkSslCon_getBuf(s), SharkSslCon_getBufLen(s)); if(queueevent) return E_SOCKET_READ_FAILED; con->recTermPtr=0; if (sockLen <= 0) { SoDispCon_clearHasMoreData(con); return sockLen; } break; case SharkSslCon_Decrypted: if( ! buf ) return TRUE; sockLen = SharkSslCon_copyDecData(s, buf, (U16)masterclock); if (SharkSslCon_decryptMore(s)) { if ((sockLen == 0) && (masterclock > 0)) { break; } } return sockLen; case SharkSslCon_Handshake: if ((nb = SharkSslCon_getHandshakeDataLen(s)) != 0) { const U8* alloccontroller = SharkSslCon_getHandshakeData(s); HttpSocket_send(&con->httpSocket, m, &queueevent, alloccontroller, nb, &sockLen); if (nb != sockLen) { if ((sockLen < 0) || queueevent || (!SoDispCon_isNonBlocking(con))) { return E_SOCKET_WRITE_FAILED; } baAssert(sockLen < nb); SoDispCon_setBlocking(con); nb -= sockLen; alloccontroller += sockLen; HttpSocket_send(&con->httpSocket, m, &queueevent, alloccontroller, nb, &sockLen); if ((sockLen < 0) || queueevent) { return E_SOCKET_WRITE_FAILED; } SoDispCon_setNonblocking(con); } } nb = SharkSslCon_isHandshakeComplete(s); if (nb) { if (!buf) { sockLen = 0; if (nb > 1) { continue; } } if ((!buf) || (!masterclock)) { return 0; } } sockLen = 0; break; default: return tsx09parse(con, handlersetup); } } } static int handlerfixup(SoDispCon* con,ThreadMutex* m,void* buf,int masterclock) { int bytes, nb, handlersetup; SharkSslCon *s = (SharkSslCon*)con->sslData; if(con->sendTermPtr) return E_SOCKET_WRITE_FAILED; for (;;) { switch (handlersetup = SharkSslCon_encrypt(s, buf, (U16)masterclock)) { case SharkSslCon_Encrypted: { U8* buf = SharkSslCon_getEncData(s); BaBool queueevent=FALSE; nb = SharkSslCon_getEncDataLen(s); con->sendTermPtr=&queueevent; HttpSocket_send(&con->httpSocket,m,&queueevent,buf,nb,&bytes); if(queueevent) return E_SOCKET_WRITE_FAILED; con->sendTermPtr=0; if(bytes != nb) { return E_SOCKET_WRITE_FAILED; } if (SharkSslCon_encryptMore(s)) { break; } return masterclock; } default: return tsx09parse(con, handlersetup); } } } static int timerretrigger(SoDispCon* con, int len) { int rebootnotifier, handlersetup; U16* enablelevel; BaBool queueevent=FALSE; ThreadMutex* m=0; if( ! SoDispCon_isValid(con) ) return -1; baAssert(len <= SharkSslCon_getEncBufSize(con->sslData)); rebootnotifier = SharkSslCon_getEncDataLen(con->sslData); if ( ! rebootnotifier ) { if (len == 0) return 1; handlersetup = SharkSslCon_encrypt(con->sslData, 0, (U16)len); if (handlersetup != SharkSslCon_Encrypted) return tsx09parse(con, handlersetup); rebootnotifier = SharkSslCon_getEncDataLen(con->sslData); } enablelevel = &((SharkSslCon*)con->sslData)->outBuf.temp; len = rebootnotifier - *enablelevel; HttpSocket_send(&con->httpSocket, m, &queueevent, SharkSslCon_getEncData(con->sslData)+*enablelevel, len, &len); (void)queueevent; if (len < 0 || !SoDispCon_isValid(con)) return E_SOCKET_WRITE_FAILED; *enablelevel += (U16)len; baAssert(*enablelevel <= rebootnotifier); if (*enablelevel == rebootnotifier) { *enablelevel = ((SharkSslCon*)con->sslData)->outBuf.dataLen = 0; return 1; } return 0; } static int registersubpacket( SoDispCon* con,ThreadMutex* m,SoDispCon_ExType s,void* alloccontroller,int len) { if( ! con->sslData ) { if(s == SoDispCon_GetSharkSslCon) { if(alloccontroller) { *((SharkSslCon**)alloccontroller) = 0; return FALSE; } return TRUE; } if(s == SoDispCon_ExTypeMoveCon) goto L_ExTypeMoveCon; return -1; } switch(s) { case SoDispCon_ExTypeRead: return belowstart(con, m, alloccontroller, len); case SoDispCon_ExTypeWrite: if(len > MAX_SHARK_BUF_SIZE) { U8* ptr=(U8*)alloccontroller; int ix=len; while(ix) { int devicelcdspi = ix > MAX_SHARK_BUF_SIZE ? MAX_SHARK_BUF_SIZE : ix; int rsp=handlerfixup(con, m, ptr, devicelcdspi); if(rsp < 0) return rsp; ptr += devicelcdspi; ix -= devicelcdspi; } return len; } return handlerfixup(con, m, alloccontroller, len); case SoDispCon_ExTypeIdle: ((SharkSslCon*)con->sslData)->outBuf.dataLen = 0; return FALSE; case SoDispCon_GetSharkSslCon: if(alloccontroller) { *((SharkSslCon**)alloccontroller) = (SharkSslCon*)con->sslData; } return TRUE; case SoDispCon_ExTypeClose: { BaSharkSslCon* bs; baAssert(con->sslData); bs=(BaSharkSslCon*)con->sslData; if( con->sendTermPtr ) { *con->sendTermPtr=TRUE; con->sendTermPtr=0; } if( con->recTermPtr ) { *con->recTermPtr=TRUE; con->recTermPtr=0; } con->sslData=0; if(bs->host) { SharkSslSCMgr* scMgr = (SharkSslSCMgr*)SharkSsl_getIntf(((SharkSslCon*)bs)->sharkSsl); if(scMgr && SharkSslCon_isHandshakeComplete((SharkSslCon*)bs)) { if( ! SharkSslSCMgr_get( scMgr, (SharkSslCon*)bs, bs->host, bs->port) ) { SharkSslSCMgr_save(scMgr,(SharkSslCon*)bs,bs->host,bs->port); } } baFree(bs->host); bs->host=0; } DoubleLink_destructor(&bs->link); SharkSslCon_terminate((SharkSslCon*)bs); return 0; } case SoDispCon_ExTypeMoveCon: L_ExTypeMoveCon: ((SoDispCon*)alloccontroller)->exec = registersubpacket; ((SoDispCon*)alloccontroller)->sslData = con->sslData; if(con->sslData) ((BaSharkSslCon*)(con->sslData))->con = (SoDispCon*)alloccontroller; con->sslData=0; return 0; case SoDispCon_ExTypeAllocAsynchBuf: ((AllocAsynchBufArgs*)alloccontroller)->retVal = SharkSslCon_getEncBufPtr(con->sslData); ((AllocAsynchBufArgs*)alloccontroller)->size = (SharkSslCon_getEncBufSize(con->sslData)); ((SharkSslCon*)con->sslData)->outBuf.dataLen = 0; return 0; case SoDispCon_ExTypeAsyncReady: return timerretrigger(con, len); default: baAssert(0); } return 0; } #ifndef NO_BA_SERVER static void erratumworkaround(HttpSharkSslServCon* o) { int sffsdrnandflash; SoDispCon* fdc37m81xconfig = (SoDispCon*)o; HttpServer* uarchbuild = HttpConnection_getServer((HttpConnection*)fdc37m81xconfig); SoDispCon* boardmanufacturer = (SoDispCon*)HttpServer_getFreeCon(uarchbuild); if(boardmanufacturer) { L_tryAgain: HttpSocket_accept(&fdc37m81xconfig->httpSocket, &boardmanufacturer->httpSocket, &sffsdrnandflash); if( ! sffsdrnandflash ) { BaSharkSslCon* bs = (BaSharkSslCon*)baMalloc(sizeof(BaSharkSslCon)); if (bs) { memset(bs, 0, sizeof(BaSharkSslCon)); SharkSsl_createCon2(o->sharkSsl,(SharkSslCon*)bs); if(o->favorRSA) SharkSslCon_favorRSA((SharkSslCon*)bs, TRUE); DoubleLink_constructor(&bs->link); DoubleList_insertLast(&o->sharkSslConList, &bs->link); boardmanufacturer->sslData = bs; bs->con=boardmanufacturer; if(SoDispCon_isIP6(fdc37m81xconfig)) SoDispCon_setIP6(boardmanufacturer); boardmanufacturer->exec = registersubpacket; HttpConnection_setTCPNoDelay(boardmanufacturer,TRUE); HttpServer_installNewCon(uarchbuild, (HttpConnection*)boardmanufacturer); SoDispCon_newConnectionIsReady(boardmanufacturer); return; } SoDispCon_destructor(boardmanufacturer); HttpServer_returnFreeCon(uarchbuild, (HttpConnection*)boardmanufacturer); return; } #ifdef HTTP_TRACE SoDispCon_printSockErr(fdc37m81xconfig, "\101\143\143\145\160\164", &fdc37m81xconfig->httpSocket, sffsdrnandflash); #endif if( ! HttpServer_termOldestIdleCon(uarchbuild) ) goto L_tryAgain; HttpServer_returnFreeCon(uarchbuild, (HttpConnection*)boardmanufacturer); } else { SoDispCon con; memset(&con, 0, sizeof(SoDispCon)); SoDispCon_constructor(&con,0,0); HttpSocket_accept(&fdc37m81xconfig->httpSocket, &con.httpSocket, &sffsdrnandflash); SoDispCon_destructor(&con); TRPR(("\123\145\162\166\145\162\040\143\157\156\156\145\143\164\151\157\156\163\040\145\170\150\141\165\163\164\145\144\012")); } TRPR(("\110\164\164\160\123\145\162\166\103\157\156\072\072\167\145\142\123\145\162\166\145\162\101\143\143\145\160\164\105\166\040\146\141\151\154\145\144\072\045\163\040\045\144\012", boardmanufacturer?"":"\040\163\145\162\166\145\162\040\143\157\156\040\145\170\150\141\165\163\164\145\144",sffsdrnandflash)); } #endif static void rangeparser(HttpSharkSslServCon* o) { HttpConnection boardmanufacturer; SoDispCon* newSoCon = (SoDispCon*)&boardmanufacturer; int sffsdrnandflash; HttpConnection* hCon = (HttpConnection*)o; SoDispCon* soCon = (SoDispCon*)o; #ifndef NO_BA_SERVER L_tryAgain: #endif memset(&boardmanufacturer, 0, sizeof(HttpConnection)); HttpSocket_accept(&soCon->httpSocket, &newSoCon->httpSocket, &sffsdrnandflash); if( ! sffsdrnandflash ) { BaSharkSslCon* bs = (BaSharkSslCon*)baMalloc(sizeof(BaSharkSslCon)); if (bs) { memset(bs, 0, sizeof(BaSharkSslCon)); SharkSsl_createCon2(o->sharkSsl,(SharkSslCon*)bs); if(o->favorRSA) SharkSslCon_favorRSA((SharkSslCon*)bs, TRUE); DoubleLink_constructor(&bs->link); DoubleList_insertLast(&o->sharkSslConList, &bs->link); if(SoDispCon_isIP6(soCon)) SoDispCon_setIP6(newSoCon); newSoCon->sslData = bs; bs->con=newSoCon; boardmanufacturer.server = hCon->server; newSoCon->exec = registersubpacket; newSoCon->dispatcher=soCon->dispatcher; ((HttpServCon*)o)->userDefinedAccept((HttpServCon*)o, &boardmanufacturer); if( ! HttpSocket_isValid(&newSoCon->httpSocket) ) { return; } #ifdef HTTP_TRACE HttpTrace_printf(0,"\111\156\166\141\154\151\144\040\155\157\166\145\103\157\156\012"); #endif DoubleLink_unlink(&bs->link); SharkSsl_terminateCon(o->sharkSsl, (SharkSslCon*)bs); } HttpSocket_close(&newSoCon->httpSocket); } #ifndef NO_BA_SERVER else { HttpServer* uarchbuild = HttpConnection_getServer(hCon); if( uarchbuild && ! HttpServer_termOldestIdleCon(uarchbuild) ) goto L_tryAgain; } #endif } int HttpSharkSslServCon_bindExec( SoDispCon* con, SharkSsl* ssl, const char* disableswapping, const char* writereg16, int hwmoddeassert) { int rsp; ThreadMutex* m=0; SharkSslCon* mmcsd0resources; if(con->sslData) mmcsd0resources = con->sslData; else { baAssert(con->exec != registersubpacket ); mmcsd0resources = (SharkSslCon*)baMalloc(sizeof(BaSharkSslCon)); if(!mmcsd0resources) return E_MALLOC; memset(mmcsd0resources, 0, sizeof(BaSharkSslCon)); SharkSsl_createCon2(ssl, mmcsd0resources); DoubleLink_constructor(&((BaSharkSslCon*)mmcsd0resources)->link); con->sslData = mmcsd0resources; con->exec=registersubpacket; m = con->dispatcher ? SoDisp_getMutex(con->dispatcher) : 0; } #if SHARKSSL_ENABLE_SESSION_CACHE if(writereg16) { #if SHARKSSL_ENABLE_SNI U8 aLvl, aDsc; #endif SharkSslSCMgrNode* scn; SharkSslSCMgr* scMgr = (SharkSslSCMgr*)SharkSsl_getIntf(ssl); if( ! scMgr ) { scMgr = baMalloc(sizeof(SharkSslSCMgr)); if( ! scMgr ) return E_MALLOC; SharkSslSCMgr_constructor(scMgr,ssl,60*60); SharkSsl_setIntf(ssl,(SharkSslIntf*)scMgr); } scn = SharkSslSCMgr_get(scMgr, mmcsd0resources, writereg16, (U16)hwmoddeassert); #if SHARKSSL_ENABLE_SNI SharkSslCon_setSNI(mmcsd0resources, writereg16, (U16)strlen(writereg16)); _skipWarning112: #endif if(disableswapping) SharkSslCon_setALPNProtocols(mmcsd0resources, disableswapping); if( SoDispCon_isNonBlocking(con) ) { do { SoDispCon_clearSocketHasNonBlockData(con); rsp=belowstart(con, 0, 0, 0); } while( ! rsp && SoDispCon_hasMoreData(con) ); } else { do { SoDispCon_setDispHasRecData(con); rsp=belowstart(con, m, 0, 0); } while( ! rsp && ! SharkSslCon_isHandshakeComplete(mmcsd0resources) ); } #if SHARKSSL_ENABLE_SNI if ((rsp == E_SHARK_ALERT_RECV) && (0 == SoDispCon_getSharkAlert(con, &aLvl, &aDsc)) && ((SHARKSSL_ALERT_LEVEL_WARNING == aLvl) && (SHARKSSL_ALERT_UNRECOGNIZED_NAME == aDsc))) { goto _skipWarning112; } #endif if(SharkSslCon_isHandshakeComplete(mmcsd0resources)) { if(!scn && SharkSslSCMgr_save(scMgr, mmcsd0resources, writereg16, (U16)hwmoddeassert)) { ((BaSharkSslCon*)mmcsd0resources)->host = baMalloc(strlen(writereg16)+1); strcpy(((BaSharkSslCon*)mmcsd0resources)->host, writereg16); ((BaSharkSslCon*)mmcsd0resources)->port=(U16)hwmoddeassert; } return 1; } return rsp; } #endif if( SoDispCon_isNonBlocking(con) ) { do { SoDispCon_clearSocketHasNonBlockData(con); rsp=belowstart(con, 0, 0, 0); } while( ! rsp && SoDispCon_hasMoreData(con) ); } else { do { SoDispCon_setDispHasRecData(con); rsp=belowstart(con, m, 0, 0); } while( ! rsp && ! SharkSslCon_isHandshakeComplete(mmcsd0resources) ); } if(rsp == 0 && SharkSslCon_isHandshakeComplete(mmcsd0resources)) return 1; return rsp; } SHARKSSL_API void HttpSharkSslServCon_constructor(HttpSharkSslServCon* o, SharkSsl* resetcounters, struct HttpServer* uarchbuild, struct SoDisp* sha256start, U16 hwmoddeassert, BaBool timercontext, const void* sanitiseouter, HttpServCon_AcceptNewCon emulateeffective) { baAssert(resetcounters->role == SharkSsl_Server); if(resetcounters->role != SharkSsl_Server) return; #ifdef NO_BA_SERVER if(!emulateeffective) baFatalE(FE_INCORRECT_USE,0); HttpConnection_constructor((HttpConnection*)o,uarchbuild,sha256start, (SoDispCon_DispRecEv)rangeparser); #else HttpConnection_constructor( (HttpConnection*)o,uarchbuild,sha256start, (SoDispCon_DispRecEv) (emulateeffective ? rangeparser : erratumworkaround) ); #endif o->sharkSsl=resetcounters; o->favorRSA=o->requestClientCert=FALSE; DoubleList_constructor(&o->sharkSslConList); ((SoDispCon*)o)->exec=registersubpacket; ((HttpServCon*)o)->userDefinedAccept=emulateeffective; if(!hwmoddeassert || HttpServCon_init((HttpServCon*)o, uarchbuild, hwmoddeassert, timercontext, sanitiseouter)) { return; } SoDisp_addConnection(sha256start, (SoDispCon*)o); SoDisp_activateRec(sha256start, (SoDispCon*)o); } SHARKSSL_API int HttpSharkSslServCon_setPort(HttpSharkSslServCon* o, U16 setuppcierr, BaBool sama5d2config, const void* sanitiseouter) { HttpSharkSslServCon boardmanufacturer; HttpServer* uarchbuild = HttpConnection_getServer((HttpConnection*)o); HttpSharkSslServCon_constructor(&boardmanufacturer, o->sharkSsl, uarchbuild, uarchbuild->dispatcher, setuppcierr, sama5d2config, sanitiseouter, 0); if(HttpSharkSslServCon_isValid(&boardmanufacturer)) { SoDispCon_closeCon((SoDispCon*)o); SoDispCon_moveCon((SoDispCon*)&boardmanufacturer, (SoDispCon*)o); SoDisp_addConnection(uarchbuild->dispatcher, (SoDispCon*)o); SoDisp_activateRec(uarchbuild->dispatcher, (SoDispCon*)o); return 0; } return -1; } SHARKSSL_API void HttpSharkSslServCon_destructor(HttpSharkSslServCon* o) { DoubleLink* l; while( (l=DoubleList_firstNode(&o->sharkSslConList)) != 0) { BaSharkSslCon* bs=(BaSharkSslCon*)((U8*)l-offsetof(BaSharkSslCon,link)); SoDispCon_closeCon(bs->con); } if(HttpServCon_isValid(o)) HttpConnection_destructor((HttpConnection*)o); } #ifndef BA_LIB #define BA_LIB #endif #include #if ((SHARKSSL_USE_AES_256 || SHARKSSL_USE_AES_128) && (SHARKSSL_ENABLE_AES_GCM)) int offsetkernel(SharkSslCon *o, U8 op, U8 *stackchecker, U16 len) { SharkSslAesGcmCtx *registermcasp; #if SHARKSSL_TLS_1_3 int ret; #endif baAssert(o); baAssert(o->minor >= 2); registermcasp = (SharkSslAesGcmCtx*)((op & populatebasepages) ? o->rCtx : o->wCtx); if (op & bcm1x80bcm1x55) { if (op & boardcompat) { if ((o->rCtx) && (op & populatebasepages)) { SharkSslAesGcmCtx_destructor((SharkSslAesGcmCtx*)selectaudio(o->rCtx)); baFree(o->rCtx); o->rCtx = 0; } else if ((o->wCtx) && (op & ptraceregsets)) { SharkSslAesGcmCtx_destructor((SharkSslAesGcmCtx*)selectaudio(o->wCtx)); baFree(o->wCtx); o->wCtx = 0; } return 0; } else { baAssert(!registermcasp); registermcasp = (SharkSslAesGcmCtx*)baMalloc(pcmciapdata(sizeof(SharkSslAesGcmCtx))); if (registermcasp == NULL) { return -1; } if (op & populatebasepages) { SharkSslAesGcmCtx_constructor((SharkSslAesGcmCtx*)selectaudio(registermcasp), o->rKey, o->rCipherSuite->keyLen); o->rCtx = registermcasp; } else { SharkSslAesGcmCtx_constructor((SharkSslAesGcmCtx*)selectaudio(registermcasp), o->wKey, o->wCipherSuite->keyLen); o->wCtx = registermcasp; } if (op & SHARKSSL_OP_CONSTRUCTOR_FLAG) { return 0; } } } #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { if (op & populatebasepages) { *(U32*)&o->rIV[4] ^= *(U32*)&o->rSeqNum[0]; *(U32*)&o->rIV[8] ^= *(U32*)&o->rSeqNum[4]; baAssert(16 == o->rCipherSuite->digestLen); baAssert(len >= 16); len -= 16; ret = SharkSslAesGcmCtx_decrypt((SharkSslAesGcmCtx*)selectaudio(registermcasp), o->rIV, &stackchecker[len], stackchecker - clkctrlmanaged, clkctrlmanaged, stackchecker, stackchecker, len); *(U32*)&o->rIV[4] ^= *(U32*)&o->rSeqNum[0]; *(U32*)&o->rIV[8] ^= *(U32*)&o->rSeqNum[4]; while ((len > 0) && (stackchecker[--len] == 0)); templateentry(o, stackchecker[len], stackchecker - clkctrlmanaged, len); return ret; } *(U32*)&o->wIV[4] ^= *(U32*)&o->wSeqNum[0]; *(U32*)&o->wIV[8] ^= *(U32*)&o->wSeqNum[4]; baAssert(16 == o->wCipherSuite->digestLen); stackchecker[len++] = stackchecker[-clkctrlmanaged]; #if ((SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH > 0) && (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH <= 0x100)) baAssert(0 == (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH & (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH - 1))); baAssert((sizeof(ret) == 4) || (sizeof(ret) == 8)); sharkssl_rng((U8*)&ret, sizeof(ret)); ret = (U16)ret & (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH - 1); while (ret--) { stackchecker[len++] = 0; } #endif templateentry(o, polledbutton, stackchecker - clkctrlmanaged, len + 16); ret = SharkSslAesGcmCtx_encrypt((SharkSslAesGcmCtx*)selectaudio(registermcasp), o->wIV, &stackchecker[len], stackchecker - clkctrlmanaged, clkctrlmanaged, stackchecker, stackchecker, len); *(U32*)&o->wIV[4] ^= *(U32*)&o->wSeqNum[0]; *(U32*)&o->wIV[8] ^= *(U32*)&o->wSeqNum[4]; return ret; } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { if (op & populatebasepages) { U8 *branchtarget = func3fixup(&o->inBuf); memcpy(&o->rIV[4], stackchecker, SHARKSSL_AES_GCM_EXPLICIT_IV_LEN); stackchecker += SHARKSSL_AES_GCM_EXPLICIT_IV_LEN ; baAssert(16 == o->rCipherSuite->digestLen); baAssert(len >= 24); len -= (SHARKSSL_AES_GCM_EXPLICIT_IV_LEN + 16); templateentry(o, o->inBuf.data[0], branchtarget, len); *(U32*)&branchtarget[-8] = *(U32*)&o->rSeqNum[0]; *(U32*)&branchtarget[-4] = *(U32*)&o->rSeqNum[4]; return SharkSslAesGcmCtx_decrypt((SharkSslAesGcmCtx*)selectaudio(registermcasp), o->rIV, &stackchecker[len], branchtarget - SHARKSSL_AES_GCM_EXPLICIT_IV_LEN, SHARKSSL_AES_GCM_EXPLICIT_IV_LEN + clkctrlmanaged, stackchecker, stackchecker, len); } return SharkSslAesGcmCtx_encrypt((SharkSslAesGcmCtx*)selectaudio(registermcasp), o->wIV, &stackchecker[len], stackchecker - (SHARKSSL_AES_GCM_EXPLICIT_IV_LEN + clkctrlmanaged), SHARKSSL_AES_GCM_EXPLICIT_IV_LEN + clkctrlmanaged, stackchecker, stackchecker, len); } #endif } #endif #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) int updatecontext(SharkSslCon *o, U8 op, U8 *stackchecker, U16 len) { SharkSslPoly1305Ctx timer8hwmod; SharkSslChaChaCtx *registermcasp; U8 unalignedwarning[32]; baAssert(o); baAssert(o->minor >= 2); registermcasp = (SharkSslChaChaCtx*)((op & populatebasepages) ? o->rCtx : o->wCtx); if (op & bcm1x80bcm1x55) { if (op & boardcompat) { if ((o->rCtx) && (op & populatebasepages)) { SharkSslChaChaCtx_destructor((SharkSslChaChaCtx*)selectaudio(o->rCtx)); baFree(o->rCtx); o->rCtx = 0; } else if ((o->wCtx) && (op & ptraceregsets)) { SharkSslChaChaCtx_destructor((SharkSslChaChaCtx*)selectaudio(o->wCtx)); baFree(o->wCtx); o->wCtx = 0; } return 0; } else { baAssert(!registermcasp); registermcasp = (SharkSslChaChaCtx*)baMalloc(pcmciapdata(sizeof(SharkSslChaChaCtx))); if (registermcasp == NULL) { return -1; } if (op & populatebasepages) { SharkSslChaChaCtx_constructor((SharkSslChaChaCtx*)selectaudio(registermcasp), o->rKey, o->rCipherSuite->keyLen); o->rCtx = registermcasp; } else { SharkSslChaChaCtx_constructor((SharkSslChaChaCtx*)selectaudio(registermcasp), o->wKey, o->wCipherSuite->keyLen); o->wCtx = registermcasp; } if (op & SHARKSSL_OP_CONSTRUCTOR_FLAG) { return 0; } } } if (op & populatebasepages) { baAssert(16 == o->rCipherSuite->digestLen); baAssert(len >= 16); len -= 16; *(U32*)&unalignedwarning[0] = *(U32*)&(o->rIV[0]); *(U32*)&unalignedwarning[4] = *(U32*)&(o->rIV[4]) ^ *(U32*)&o->rSeqNum[0]; *(U32*)&unalignedwarning[8] = *(U32*)&(o->rIV[8]) ^ *(U32*)&o->rSeqNum[4]; } else { baAssert(16 == o->wCipherSuite->digestLen); *(U32*)&unalignedwarning[0] = *(U32*)&(o->wIV[0]); *(U32*)&unalignedwarning[4] = *(U32*)&(o->wIV[4]) ^ *(U32*)&o->wSeqNum[0]; *(U32*)&unalignedwarning[8] = *(U32*)&(o->wIV[8]) ^ *(U32*)&o->wSeqNum[4]; } SharkSslChaChaCtx_setIV((SharkSslChaChaCtx*)selectaudio(registermcasp), (const U8*)unalignedwarning); *(U32*)&unalignedwarning[0] = 0; *(U32*)&unalignedwarning[4] = 0; *(U32*)&unalignedwarning[8] = 0; *(U32*)&unalignedwarning[12] = 0; *(U32*)&unalignedwarning[16] = 0; *(U32*)&unalignedwarning[20] = 0; *(U32*)&unalignedwarning[24] = 0; *(U32*)&unalignedwarning[28] = 0; SharkSslChaChaCtx_crypt((SharkSslChaChaCtx*)selectaudio(registermcasp), unalignedwarning, unalignedwarning, 32); SharkSslPoly1305Ctx_constructor(&timer8hwmod, unalignedwarning); *(U32*)&unalignedwarning[0] = 0; *(U32*)&unalignedwarning[4] = 0; *(U32*)&unalignedwarning[8] = 0; *(U32*)&unalignedwarning[12] = 0; #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { if (op & ptraceregsets) { U32 ret; stackchecker[len++] = stackchecker[-clkctrlmanaged]; #if ((SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH > 0) && (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH < 0x100)) baAssert(0 == (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH & (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH - 1))); sharkssl_rng((U8*)&ret, sizeof(ret)); ret &= (SHARKSSL_TLS_1_3_PADDING_MAX_LENGTH - 1); while (ret--) { stackchecker[len++] = 0; } #endif templateentry(o, polledbutton, stackchecker - clkctrlmanaged, len + 16); } SharkSslPoly1305Ctx_append(&timer8hwmod, stackchecker - clkctrlmanaged, clkctrlmanaged); SharkSslPoly1305Ctx_append(&timer8hwmod, unalignedwarning, SHARKSSL_POLY1305_HASH_LEN - clkctrlmanaged); } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { if (op & populatebasepages) { templateentry(o, o->inBuf.data[0], func3fixup(&o->inBuf), len); SharkSslPoly1305Ctx_append(&timer8hwmod, o->rSeqNum, SHARKSSL_SEQ_NUM_LEN); SharkSslPoly1305Ctx_append(&timer8hwmod, func3fixup(&o->inBuf), clkctrlmanaged); } else { baAssert(serial2platform(&o->outBuf)); SharkSslPoly1305Ctx_append(&timer8hwmod, o->wSeqNum, SHARKSSL_SEQ_NUM_LEN); SharkSslPoly1305Ctx_append(&timer8hwmod, func3fixup(&o->outBuf), clkctrlmanaged); } SharkSslPoly1305Ctx_append(&timer8hwmod, unalignedwarning, SHARKSSL_POLY1305_HASH_LEN - SHARKSSL_SEQ_NUM_LEN - clkctrlmanaged); } #endif if (op & ptraceregsets) { SharkSslChaChaCtx_crypt((SharkSslChaChaCtx*)selectaudio(registermcasp), stackchecker, stackchecker, len); } SharkSslPoly1305Ctx_append(&timer8hwmod, stackchecker, len); baAssert(0 == (SHARKSSL_POLY1305_HASH_LEN & (SHARKSSL_POLY1305_HASH_LEN - 1))); SharkSslPoly1305Ctx_append(&timer8hwmod, unalignedwarning, (U8)-((U8)len) & (SHARKSSL_POLY1305_HASH_LEN - 1)); #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { unalignedwarning[0] = clkctrlmanaged; } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { unalignedwarning[0] = 13; } #endif SharkSslPoly1305Ctx_append(&timer8hwmod, &unalignedwarning[0], 8); unalignedwarning[0] = (U8)(len & 0xFF); unalignedwarning[1] = (U8)(len >> 8); SharkSslPoly1305Ctx_append(&timer8hwmod, &unalignedwarning[0], 8); if (op & populatebasepages) { SharkSslPoly1305Ctx_finish(&timer8hwmod, &unalignedwarning[0]); SharkSslPoly1305Ctx_destructor(&timer8hwmod); if (sharkssl_kmemcmp(&stackchecker[len], &unalignedwarning[0], 16)) { return 1; } SharkSslChaChaCtx_crypt((SharkSslChaChaCtx*)selectaudio(registermcasp), stackchecker, stackchecker, len); #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { while ((len > 0) && (stackchecker[--len] == 0)); templateentry(o, stackchecker[len], stackchecker - clkctrlmanaged, len); } #endif } else { SharkSslPoly1305Ctx_finish(&timer8hwmod, &stackchecker[len]); SharkSslPoly1305Ctx_destructor(&timer8hwmod); } return 0; } #endif #ifndef BA_LIB #define BA_LIB #endif #include #if SHARKSSL_ENABLE_SESSION_CACHE void counter1clocksource(SharkSslSessionCache *commoncontiguous, U16 detectbootwidth) { U32 flash1resources = detectbootwidth * sizeof(SharkSslSession); baAssert(commoncontiguous); memset(commoncontiguous, 0, sizeof(SharkSslSessionCache)); ThreadMutex_constructor(&(commoncontiguous->cacheMutex)); if (detectbootwidth != 0) { commoncontiguous->cache = (SharkSslSession*)baMalloc(pcmciapdata(flash1resources)); if (commoncontiguous->cache != NULL) { commoncontiguous->cacheSize = detectbootwidth; memset(selectaudio(commoncontiguous->cache), 0, flash1resources); } } } void defaultsdhci0(SharkSslSessionCache *commoncontiguous) { baAssert(commoncontiguous); if (commoncontiguous->cacheSize != 0) { #if SHARKSSL_SSL_SERVER_CODE U32 uart2hwmod; SharkSslSession *func2fixup = (SharkSslSession*)selectaudio(commoncontiguous->cache); for (uart2hwmod = commoncontiguous->cacheSize; uart2hwmod > 0; uart2hwmod--, func2fixup++) { SHARKDBG_PRINTF(("\106\162\145\145\151\156\147\040\163\145\163\163\151\157\156\040\045\060\070\130\057\163\145\163\163\151\157\156\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\040\045\060\070\130\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)func2fixup, (U32)func2fixup->clonedCertInfo, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\103\141\143\150\145\137\144\145\163\164\162\165\143\164\157\162")); if (func2fixup->clonedCertInfo) { SHARKDBG_PRINTF(("\163\145\163\163\151\157\156\050\045\060\070\130\051\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\050\045\060\070\130\051\055\076\162\145\146\143\156\164\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)func2fixup, (U32)func2fixup->clonedCertInfo, func2fixup->clonedCertInfo->refcnt, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\103\141\143\150\145\137\144\145\163\164\162\165\143\164\157\162")); #if (!SHARKSSL_ENABLE_CLIENT_AUTH) baAssert(0 == (func2fixup->clonedCertInfo->refcnt)); #endif baFree((void*)func2fixup->clonedCertInfo); } if (SharkSslSession_isProtocol(func2fixup, SHARKSSL_PROTOCOL_TLS_1_3) && (func2fixup->prot.tls13.ticket)) { baFree((void*)func2fixup->prot.tls13.ticket); } } #endif memset(selectaudio(commoncontiguous->cache), 0, commoncontiguous->cacheSize * sizeof(SharkSslSession)); baFree(commoncontiguous->cache); } ThreadMutex_destructor(&commoncontiguous->cacheMutex); memset(commoncontiguous, 0, sizeof(SharkSslSessionCache)); } SharkSslSession *sa1111device(SharkSslSessionCache *commoncontiguous, SharkSslCon *o, U8 *id, U16 setupinterface) { SharkSslSession *func2fixup = 0; baAssert(o); if (commoncontiguous->cacheSize) { SharkSslSession *oldestSession = 0; U32 t, uart2hwmod, now; now = (U32)baGetUnixTime(); t = 0xFFFFFFFF; func2fixup = (SharkSslSession*)selectaudio(commoncontiguous->cache); filtermatch(commoncontiguous); for (uart2hwmod = commoncontiguous->cacheSize; uart2hwmod > 0; uart2hwmod--, func2fixup++) { if (func2fixup->cipherSuite == 0) { baAssert(func2fixup->nUse == 0); break; } #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (SharkSslSession_isProtocol(func2fixup, SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if ((func2fixup->prot.tls12.latestAccess < t) && (func2fixup->nUse == 0)) { t = func2fixup->prot.tls12.latestAccess; oldestSession = func2fixup; } } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 { if ((func2fixup->prot.tls13.expiration < t) && (func2fixup->nUse == 0)) { t = func2fixup->prot.tls13.expiration; oldestSession = func2fixup; } } #endif } if (uart2hwmod == 0) { func2fixup = oldestSession; } if (func2fixup) { uart2hwmod = (U32)(func2fixup - (SharkSslSession*)selectaudio(commoncontiguous->cache)); if (uart2hwmod < commoncontiguous->cacheSize) { #if SHARKSSL_SSL_CLIENT_CODE #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isClient(o->sharkSsl)) #endif { baAssert(id); baAssert(setupinterface); baAssert((SharkSslClonedCertInfo*)0 == func2fixup->clonedCertInfo); #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if (setupinterface < SHARKSSL_MAX_SESSION_ID_LEN) { memset(func2fixup->prot.tls12.id, 0, SHARKSSL_MAX_SESSION_ID_LEN); } memcpy(func2fixup->prot.tls12.id, id, setupinterface); } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 { if (setupinterface > SHARKSSL_MAX_SESSION_TICKET_LEN) { func2fixup = 0; } else { baAssert((hardirqsenabled(func2fixup) != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) || (NULL == func2fixup->prot.tls13.ticket)); func2fixup->prot.tls13.ticket = baMalloc(setupinterface); if (NULL == func2fixup->prot.tls13.ticket) { func2fixup = 0; } else { memcpy(func2fixup->prot.tls13.ticket, id, setupinterface); func2fixup->prot.tls13.ticketLen = setupinterface; } } } #endif } #if SHARKSSL_SSL_SERVER_CODE else #endif #endif #if SHARKSSL_SSL_SERVER_CODE { baAssert(0 == id); baAssert(0 == setupinterface); SHARKDBG_PRINTF(("\123\145\163\163\151\157\156\040\151\156\144\145\170\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", uart2hwmod, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\103\141\143\150\145\137\156\145\167\123\145\163\163\151\157\156")); uart2hwmod++; uart2hwmod = ~uart2hwmod; func2fixup->prot.tls12.id[0] = (U8)(uart2hwmod >> 24); func2fixup->prot.tls12.id[1] = (U8)(uart2hwmod >> 16); func2fixup->prot.tls12.id[2] = (U8)(uart2hwmod >> 8); func2fixup->prot.tls12.id[3] = (U8)(uart2hwmod & 0xFF); func2fixup->prot.tls12.id[4] = (U8)(now >> 24); func2fixup->prot.tls12.id[5] = (U8)(now >> 16); func2fixup->prot.tls12.id[6] = (U8)(now >> 8); func2fixup->prot.tls12.id[7] = (U8)(now & 0xFF); if (func2fixup->clonedCertInfo) { func2fixup->clonedCertInfo->refcnt--; SHARKDBG_PRINTF(("\163\145\163\163\151\157\156\050\045\060\070\130\051\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\050\045\060\070\130\051\055\076\162\145\146\143\156\164\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)func2fixup, (U32)func2fixup->clonedCertInfo, func2fixup->clonedCertInfo->refcnt, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\103\141\143\150\145\137\156\145\167\123\145\163\163\151\157\156")); if (0 == func2fixup->clonedCertInfo->refcnt) { SHARKDBG_PRINTF(("\163\145\163\163\151\157\156\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\040\162\145\154\145\141\163\145\144\054\040\045\163\072\040\045\144\012", __FILE__, __LINE__)); baFree((void*)func2fixup->clonedCertInfo); } func2fixup->clonedCertInfo = (SharkSslClonedCertInfo*)0; } if (sharkssl_rng(&func2fixup->prot.tls12.id[8], SHARKSSL_MAX_SESSION_ID_LEN - 8) < 0) { func2fixup = 0; } } #endif if (func2fixup) { func2fixup->nUse = 1; func2fixup->flags = 0; func2fixup->firstAccess = now; sha224final(func2fixup, o->major, o->minor); #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (SharkSslSession_isProtocol(func2fixup, SHARKSSL_PROTOCOL_TLS_1_2)) #endif { func2fixup->cipherSuite = hsParam(o)->cipherSuite; func2fixup->prot.tls12.latestAccess = now; } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 { func2fixup->cipherSuite = o->rCipherSuite; func2fixup->prot.tls13.expiration = now; } #endif } } else { func2fixup = 0; } } else { SHARKDBG_PRINTF(("\101\154\154\040\163\145\163\163\151\157\156\163\040\151\156\040\165\163\145\054\040\045\163\072\040\045\144\040\050\045\163\051\012", __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\103\141\143\150\145\137\156\145\167\123\145\163\163\151\157\156")); } helperglobal(commoncontiguous); } return func2fixup; } SharkSslSession *latchgpiochip(SharkSslSessionCache *commoncontiguous, SharkSslCon *o, U8 *id, U16 setupinterface) { SharkSslSession *func2fixup = 0; baAssert(id); baAssert(setupinterface); baAssert(commoncontiguous); if (commoncontiguous->cacheSize) { U32 now, uart2hwmod; now = (U32)baGetUnixTime(); filtermatch(commoncontiguous); if (SharkSsl_isClient(o->sharkSsl)) { func2fixup = (SharkSslSession*)selectaudio(commoncontiguous->cache); uart2hwmod = commoncontiguous->cacheSize - 1; } #if SHARKSSL_TLS_1_2 else { uart2hwmod = (~(((U32)id[0] << 24) | ((U32)id[1] << 16) | ((U16)id[2] << 8) | id[3])) - 1; SHARKDBG_PRINTF(("\123\145\163\163\151\157\156\040\151\156\144\145\170\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", uart2hwmod, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\103\141\143\150\145\137\146\151\156\144\123\145\163\163\151\157\156")); if (uart2hwmod < commoncontiguous->cacheSize) { func2fixup = (SharkSslSession*)((U8*)selectaudio(commoncontiguous->cache) + (uart2hwmod * sizeof(SharkSslSession))); } } #else uart2hwmod = 0; #endif for (;;) { #if SHARKSSL_TLS_1_2 if ((func2fixup) && (func2fixup->cipherSuite) && (restarthandler(func2fixup, o->major, o->minor)) && (SharkSslSession_isProtocol(func2fixup, SHARKSSL_PROTOCOL_TLS_1_2)) && (0 == sharkssl_kmemcmp(func2fixup->prot.tls12.id, id, setupinterface)) && ((U32)(now - func2fixup->firstAccess) < 21600L ) && (func2fixup->nUse < 0xFFFF)) { func2fixup->nUse++; func2fixup->prot.tls12.latestAccess = now; #if SHARKSSL_ENABLE_CA_LIST if (func2fixup->flags & ecoffaouthdr) { o->flags |= switcheractivation; } #endif break; } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 if ((func2fixup) && (restarthandler(func2fixup, o->major, o->minor)) && (SharkSslSession_isProtocol(func2fixup, SHARKSSL_PROTOCOL_TLS_1_3)) && (func2fixup->prot.tls13.ticket) && (0 == sharkssl_kmemcmp(func2fixup->prot.tls13.ticket, id, setupinterface)) && (now < func2fixup->prot.tls13.expiration) && (func2fixup->nUse < 0xFFFF)) { func2fixup->nUse++; #if SHARKSSL_ENABLE_CA_LIST if (func2fixup->flags & ecoffaouthdr) { o->flags |= switcheractivation; } #endif break; } #endif else { if ((SharkSsl_isServer(o->sharkSsl)) || (0 == uart2hwmod)) { func2fixup = 0; break; } else { uart2hwmod--; func2fixup++; } } } helperglobal(commoncontiguous); } return func2fixup; } #endif void atomiccmpxchg(SharkSslBuf *o, U16 icachealiases) { U16 mcasp0device = icachealiases + gpio5config; baAssert(o); memset(o, 0, sizeof(SharkSslBuf)); #if SHARKSSL_UNALIGNED_MALLOC o->mem = (U8*)baMalloc(pcmciapdata(mcasp0device)); if (o->mem != NULL) { o->buf = (U8*)selectaudio(o->mem); #else baAssert(pcmciapdata(0) == 0); o->buf = (U8*)baMalloc(mcasp0device); if (o->buf != NULL) { #endif registerfixed(o); o->size = icachealiases; } } void guestconfig5(SharkSslBuf *o) { baAssert(o); if (o->buf) { #if SHARKSSL_UNALIGNED_MALLOC memset(o->mem, 0, pcmciapdata(o->size) + gpio5config); baFree(o->mem); #else memset(o->buf, 0, o->size + gpio5config); baFree(o->buf); #endif } memset(o, 0, sizeof(SharkSslBuf)); } void binaryheader(SharkSslBuf *o) { U8 *doublefnmul = o->data; registerfixed(o); memmove(o->data, doublefnmul, o->dataLen); } #if (!SHARKSSL_DISABLE_INBUF_EXPANSION) U8 *othersegments(SharkSslBuf *o, U16 kprobehandler) { #if (SHARKSSL_UNALIGNED_MALLOC) U8 *percpuclockdev; #endif U8 *anatopenable; U16 mcasp0device; if (kprobehandler) { baAssert(o->size < kprobehandler); mcasp0device = ((kprobehandler + cachewback - 1) / cachewback) * cachewback; baAssert(mcasp0device >= kprobehandler); } else { mcasp0device = o->size + cachewback; } mcasp0device += gpio5config; #if (SHARKSSL_UNALIGNED_MALLOC) percpuclockdev = o->mem; anatopenable = (U8*)baMalloc(pcmciapdata(mcasp0device)); if (anatopenable != NULL) { o->mem = anatopenable; anatopenable = (U8*)selectaudio(anatopenable); memcpy(anatopenable, o->buf, gpio5config + o->size); } baFree(percpuclockdev); #else anatopenable = (U8*)baRealloc(o->buf, mcasp0device); if (anatopenable == NULL) { anatopenable = (U8*)baMalloc(mcasp0device); if (anatopenable != NULL) { memcpy(anatopenable, o->buf, gpio5config + o->size); } baFree(o->buf); } #endif o->buf = anatopenable; if (anatopenable) { registerfixed(o); o->size = (U16)mcasp0device - gpio5config; } return anatopenable; } #endif void breakpointhandler(SharkSslHSParam *o) { baAssert(o); memset(o, 0, sizeof(SharkSslHSParam)); SharkSslSha256Ctx_constructor(&o->sha256Ctx); #if SHARKSSL_USE_SHA_384 SharkSslSha384Ctx_constructor(&o->sha384Ctx); #endif #if (SHARKSSL_USE_SHA_512 && SHARKSSL_TLS_1_2) SharkSslSha512Ctx_constructor(&o->prot.tls12.sha512Ctx); #endif } void alignmentldmstm(SharkSslHSParam *o) { baAssert(o); memset(o, 0, sizeof(SharkSslHSParam)); } void ioremapresource(SharkSslHSParam *o, U8 *alloccontroller, U16 len) { baAssert(o); baAssert(alloccontroller); baAssert(len); #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if ((o->cipherSuite) && (o->cipherSuite->flags & SHARKSSL_CS_TLS13)) #else if (o->cipherSuite) #endif { switch (o->cipherSuite->hashID) { #if SHARKSSL_USE_SHA_256 case domainnumber: SharkSslSha256Ctx_append(&o->sha256Ctx, alloccontroller, len); break; #endif #if SHARKSSL_USE_SHA_384 case probewrite: SharkSslSha384Ctx_append(&o->sha384Ctx, alloccontroller, len); break; #endif default: baAssert(0); break; } } else #endif { SharkSslSha256Ctx_append(&o->sha256Ctx, alloccontroller, len); #if SHARKSSL_USE_SHA_384 SharkSslSha384Ctx_append(&o->sha384Ctx, alloccontroller, len); #endif #if (SHARKSSL_USE_SHA_512 && SHARKSSL_TLS_1_2) SharkSslSha512Ctx_append(&o->prot.tls12.sha512Ctx, alloccontroller, len); #endif } } int wakeupvector(SharkSslHSParam *o, U8 *chargerplatform, U8 configwrite) { void *buf; baAssert(o); baAssert(chargerplatform); switch (configwrite) { #if (SHARKSSL_USE_SHA_512 && SHARKSSL_TLS_1_2) case batterythread: buf = baMalloc(sizeof(SharkSslSha512Ctx)); if (!buf) { return -1; } memcpy(buf, &o->prot.tls12.sha512Ctx, sizeof(SharkSslSha512Ctx)); SharkSslSha512Ctx_finish((SharkSslSha512Ctx*)buf, chargerplatform); break; #endif #if SHARKSSL_USE_SHA_384 case probewrite: buf = baMalloc(sizeof(SharkSslSha384Ctx)); if (!buf) { return -1; } memcpy(buf, &o->sha384Ctx, sizeof(SharkSslSha384Ctx)); SharkSslSha384Ctx_finish((SharkSslSha384Ctx*)buf, chargerplatform); break; #endif #if SHARKSSL_USE_SHA_256 case domainnumber: buf = baMalloc(sizeof(SharkSslSha256Ctx)); if (!buf) { return -1; } memcpy(buf, &o->sha256Ctx, sizeof(SharkSslSha256Ctx)); SharkSslSha256Ctx_finish((SharkSslSha256Ctx*)buf, chargerplatform); break; #endif default: return -1; } baFree(buf); return 0; } static void disablelevel(U8 *commonalloc) { memset(commonalloc, 0, SHARKSSL_SEQ_NUM_LEN); } static void clusterpowerdown(U8 *commonalloc) { #if 0 U8 n = SHARKSSL_SEQ_NUM_LEN - 1; while ((0 == ++commonalloc[n]) && (n > 0)) { n--; } #else U32 seq; baAssert(8 == SHARKSSL_SEQ_NUM_LEN); read64uint32(seq, commonalloc, 4); seq++; inputlevel(seq, commonalloc, 4); if (0 == seq) { read64uint32(seq, commonalloc, 0); seq++; inputlevel(seq, commonalloc, 0); } #endif } void conditionvalid(SharkSslCon *o, SharkSsl *resetcounters) { baAssert(o); memset(o, 0, sizeof(SharkSslCon)); o->sharkSsl = resetcounters; if (SharkSsl_isClient(resetcounters)) { o->flags |= probedaddress; } else { baAssert(SharkSsl_isServer(resetcounters)); o->state = pciercxcfg070; } } static void singleftosi(SharkSslCon *o) { if (o->clonedCertInfo) { #if SHARKSSL_ENABLE_SESSION_CACHE filtermatch(&o->sharkSsl->sessionCache); o->clonedCertInfo->refcnt--; SHARKDBG_PRINTF(("\157\050\045\060\070\130\051\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\050\045\060\070\130\051\055\076\162\145\146\143\156\164\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)o, (U32)o->clonedCertInfo, o->clonedCertInfo->refcnt, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\103\157\156\137\146\162\145\145\103\154\157\156\145\144\103\145\162\164\111\156\146\157")); if (0 == o->clonedCertInfo->refcnt) #endif { SHARKDBG_PRINTF(("\157\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\040\162\145\154\145\141\163\145\144\054\040\045\163\072\040\045\144\012", __FILE__, __LINE__)); baFree((void*)o->clonedCertInfo); } #if SHARKSSL_ENABLE_SESSION_CACHE helperglobal(&o->sharkSsl->sessionCache); #endif } } void localenable(SharkSslCon *o) { baAssert(o); guestconfig5(&o->inBuf); guestconfig5(&o->outBuf); #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION guestconfig5(&o->tmpBuf); #endif if (o->rCipherSuite) { o->rCipherSuite->cipherFunc(o, chargerworker | populatebasepages, (U8*)0, 0); } if (o->wCipherSuite) { o->wCipherSuite->cipherFunc(o, chargerworker | ptraceregsets, (U8*)0, 0); } #if SHARKSSL_ENABLE_SESSION_CACHE if (o->session) { SharkSslSession *s = o->session; o->session = 0; if ((SharkSsl_isServer(o->sharkSsl)) || (o->flags & gpiolibmbank)) { SharkSslSession_release(s, o->sharkSsl); } } #endif singleftosi(o); memset(o, 0, sizeof(SharkSslCon)); } static int breakpointcontrol(U8 regsetcopyin) { return ((regsetcopyin == rangealigned) || (regsetcopyin == firstentry) || (regsetcopyin == controllegacy) || (regsetcopyin == polledbutton)); } SharkSslCon_RetVal SharkSslCon_decrypt(SharkSslCon *o, U16 pmattrstore) { U8 *registeredevent; SharkSslCon_RetVal ret; U16 backuppdata, recLenDec, atagsprocfs, consumedBytes; U8 regsetcopyin, tvp5146pdata, minor; baAssert(o); if (o->flags & firstcomponent) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } if (o->flags & SHARKSSL_FLAG_PARTIAL_HS_SEND) { o->flags &= ~SHARKSSL_FLAG_PARTIAL_HS_SEND; return SharkSslCon_Handshake; } #if SHARKSSL_SSL_CLIENT_CODE #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isClient(o->sharkSsl)) #endif { if (o->flags & probedaddress) { return configdword(o, 0, 0); } baAssert(!microresources(&o->inBuf)); } #if SHARKSSL_SSL_SERVER_CODE else #endif #endif #if SHARKSSL_SSL_SERVER_CODE { if (microresources(&o->inBuf)) { #if (SHARKSSL_ENABLE_RSA || (SHARKSSL_ENABLE_ECDSA)) SingleListEnumerator e; SingleLink *link; SingleListEnumerator_constructor(&e, (SingleList*)&o->sharkSsl->certList); recLenDec = 0; for (link = SingleListEnumerator_getElement(&e); link; link = SingleListEnumerator_nextElement(&e)) { if (((SharkSslCertList*)link)->certP.msgLen > recLenDec) { recLenDec = ((SharkSslCertList*)link)->certP.msgLen; } } if (0 == recLenDec) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_CertificateError; } #else recLenDec = 0; #endif baAssert(!(o->flags & clockgettime32)); baAssert(!SharkSslCon_isHandshakeComplete(o)); backuppdata = o->sharkSsl->inBufStartSize; recLenDec += 128 + SHARKSSL_MAX_SESSION_ID_LEN + SHARKSSL_MAX_BLOCK_LEN + SHARKSSL_MAX_DIGEST_LEN + prefetchwrite; #if SHARKSSL_ENABLE_DHE_RSA recLenDec += 1024 + 14; #elif SHARKSSL_ENABLE_ECDHE_RSA recLenDec += 256; #endif recLenDec = claimresource(recLenDec); if (backuppdata < recLenDec) { backuppdata = recLenDec; } atomiccmpxchg(&o->inBuf, backuppdata); if (microresources(&o->inBuf)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } if (microresources(&o->outBuf)) { backuppdata = o->sharkSsl->outBufSize; baAssert(backuppdata >= (128 + sizeof(SharkSslHSParam))); atomiccmpxchg(&o->outBuf, backuppdata); if (microresources(&o->outBuf)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } } } } #endif registeredevent = o->inBuf.data; if (o->flags & SHARKSSL_FLAG_FRAGMENTED_HS_RECORD) { if (o->inBuf.temp > 0) { registeredevent += o->inBuf.temp; backuppdata = ((U16)(*registeredevent++)) << 8; backuppdata += *registeredevent++; o->inBuf.dataLen = backuppdata; backuppdata = ((U16)(*registeredevent++)) << 8; backuppdata += *registeredevent++ - 4; registeredevent += backuppdata; } else { o->flags &= ~SHARKSSL_FLAG_FRAGMENTED_HS_RECORD; } } else if (o->flags & clockgettime32) { if (o->inBuf.temp) { return SharkSslCon_Decrypted; } else { o->flags &= ~clockgettime32; } } o->inBuf.dataLen += pmattrstore; atagsprocfs = o->inBuf.dataLen; backuppdata = 0; _sharkssl_process_another_record: if (atagsprocfs < clkctrlmanaged) { #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SECURE_RENEGOTIATION) if (o->flags & registerbuses #if SHARKSSL_SSL_CLIENT_CODE && (SharkSsl_isServer(o->sharkSsl)) #endif ) { o->flags &= ~registerbuses; o->flags |= skciphersetkey; return SharkSslCon_Handshake; } #endif _sharkssl_need_more_data: baAssert(o->inBuf.size >= o->inBuf.dataLen); backuppdata += clkctrlmanaged; if (!(o->flags & SHARKSSL_FLAG_FRAGMENTED_HS_RECORD)) { if (!(serial2platform(&o->inBuf))) { binaryheader(&o->inBuf); } if (o->inBuf.size < backuppdata) { #if (!SHARKSSL_DISABLE_INBUF_EXPANSION) if (!othersegments(&o->inBuf, backuppdata)) #endif { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } } } else { consumedBytes = (U16)(registeredevent - o->inBuf.data); if (backuppdata > (o->inBuf.size - consumedBytes)) { #if (!SHARKSSL_DISABLE_INBUF_EXPANSION) if (!othersegments(&o->inBuf, o->inBuf.size + backuppdata)) #endif { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } } registeredevent = o->inBuf.data + o->inBuf.temp; *registeredevent++ = (U8)(o->inBuf.dataLen >> 8); *registeredevent++ = (U8)(o->inBuf.dataLen & 0xFF); consumedBytes -= clkctrlmanaged; o->inBuf.dataLen += consumedBytes; consumedBytes -= o->inBuf.temp; *registeredevent++ = (U8)(consumedBytes >> 8); *registeredevent++ = (U8)(consumedBytes & 0xFF); } return SharkSslCon_NeedMoreData; } if ((o->major) || (0 == (*registeredevent & 0x80)) || SharkSsl_isClient(o->sharkSsl)) { regsetcopyin = *registeredevent++; tvp5146pdata = *registeredevent++; minor = *registeredevent++; backuppdata = (U16)(*registeredevent++) << 8; backuppdata += *registeredevent++; atagsprocfs -= clkctrlmanaged; } else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_alert_unexpected_message; } if (!breakpointcontrol(regsetcopyin)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); _sharkssl_alert_unexpected_message: return savedconfig(o, SHARKSSL_ALERT_UNEXPECTED_MESSAGE); } if ( (backuppdata == 0) || (backuppdata > gpio2enable) || ((o->state != trampolinehandler) && (o->state != pciercxcfg070) && ((o->major != tvp5146pdata) || (minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2))) ) ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); _sharkssl_alert_illegal_parameter: return savedconfig(o, SHARKSSL_ALERT_ILLEGAL_PARAMETER); } if (atagsprocfs < backuppdata) { goto _sharkssl_need_more_data; } recLenDec = backuppdata; #if SHARKSSL_TLS_1_3 if (o->state == SHARKSSL_HANDSHAKETYPE_ENCRYPTED_EXTENSIONS) { if ((regsetcopyin != rangealigned) && (!(o->rCipherSuite))) { SharkSslCon_calcHandshakeTrafficSecret(o); } } #endif if (o->rCipherSuite) { if (backuppdata < o->rCipherSuite->digestLen) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); _sharkssl_alert_bad_record_mac: return savedconfig(o, SHARKSSL_ALERT_BAD_RECORD_MAC); } #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if (0 #if SHARKSSL_ENABLE_AES_GCM || ((o->rCipherSuite->flags & framekernel) && (backuppdata < (SHARKSSL_AES_GCM_EXPLICIT_IV_LEN + o->rCipherSuite->digestLen ))) #endif #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) || ((o->rCipherSuite->flags & suspendenter) && (backuppdata < o->rCipherSuite->digestLen)) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_alert_bad_record_mac; } } #endif if (o->rCipherSuite->cipherFunc(o, populatebasepages, registeredevent, backuppdata)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_alert_bad_record_mac; #if 0 resvdexits(o); return SharkSslCon_Error; #endif } #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { regsetcopyin = registeredevent[0 - clkctrlmanaged]; if (!breakpointcontrol(regsetcopyin)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_alert_unexpected_message; } recLenDec = (U16)(registeredevent[3 - clkctrlmanaged]) << 8; recLenDec += registeredevent[4 - clkctrlmanaged]; } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { #if SHARKSSL_ENABLE_AES_GCM if (o->rCipherSuite->flags & framekernel) { recLenDec -= (SHARKSSL_AES_GCM_EXPLICIT_IV_LEN + o->rCipherSuite->digestLen ); registeredevent += SHARKSSL_AES_GCM_EXPLICIT_IV_LEN; } #endif #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) #if SHARKSSL_ENABLE_AES_GCM if (o->rCipherSuite->flags & suspendenter) #endif { recLenDec -= o->rCipherSuite->digestLen; } #endif } #endif clusterpowerdown(o->rSeqNum); #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { o->padLen = (backuppdata - recLenDec); } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { o->padLen = 0; } #endif } consumedBytes = 0; switch (regsetcopyin) { case controllegacy: if (o->flags & SHARKSSL_FLAG_FRAGMENTED_HS_RECORD) { baAssert(o->inBuf.temp); memmove(o->inBuf.data + o->inBuf.temp, registeredevent, recLenDec); o->flags &= ~SHARKSSL_FLAG_FRAGMENTED_HS_RECORD; o->inBuf.temp += recLenDec; ret = configdword(o, o->inBuf.data, o->inBuf.temp); } else { ret = configdword(o, registeredevent, recLenDec); if (o->flags & SHARKSSL_FLAG_FRAGMENTED_HS_RECORD) { if (!(serial2platform(&o->inBuf))) { o->inBuf.data -= clkctrlmanaged; if (!(serial2platform(&o->inBuf))) { o->inBuf.dataLen += clkctrlmanaged; binaryheader(&o->inBuf); o->inBuf.dataLen -= clkctrlmanaged; } o->inBuf.data += clkctrlmanaged; registeredevent = o->inBuf.data; } consumedBytes = (U16)(atagsprocfs - o->inBuf.dataLen); o->inBuf.temp = recLenDec - consumedBytes; } } _sharkssl_check_if_another_record: if (ret == SharkSslCon_Handshake) { atagsprocfs -= backuppdata; o->inBuf.dataLen = atagsprocfs; if (atagsprocfs) { registeredevent += backuppdata - consumedBytes; #if ((SHARKSSL_ENABLE_AES_GCM || (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305)) && SHARKSSL_TLS_1_2) #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if ((o->flags & devicedriver) && (o->rCipherSuite->flags & framekernel)) { registeredevent -= SHARKSSL_AES_GCM_EXPLICIT_IV_LEN; } } #endif if (!(o->flags & SHARKSSL_FLAG_FRAGMENTED_HS_RECORD)) { o->inBuf.data = registeredevent; } if ((o->state != loongson3notifier) #if SHARKSSL_TLS_1_3 || ((o->flags & devicedriver) #if SHARKSSL_TLS_1_2 && (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif ) #endif ) { goto _sharkssl_process_another_record; } } else { if (o->flags & SHARKSSL_FLAG_FRAGMENTED_HS_RECORD) { o->inBuf.data -= clkctrlmanaged; o->inBuf.dataLen = o->inBuf.temp + clkctrlmanaged; o->inBuf.temp = 0; ret = SharkSslCon_NeedMoreData; } else { registerfixed(&o->inBuf); } } #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { o->flags &= ~devicedriver; } #endif } break; case rangealigned: ret = kexecprotect(o, registeredevent, recLenDec); goto _sharkssl_check_if_another_record; case polledbutton: if (!SharkSslCon_isHandshakeComplete(o)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_alert_unexpected_message; } if (recLenDec == 0) { if (o->flags & stealenabled) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_alert_unexpected_message; } o->flags |= stealenabled; } else { o->flags &= ~stealenabled; } o->flags |= clockgettime32; atagsprocfs -= backuppdata; o->inBuf.dataLen = atagsprocfs; o->inBuf.data = registeredevent; o->inBuf.temp = recLenDec; ret = SharkSslCon_Decrypted; break; default: case firstentry: if ((recLenDec < 2) || ((*registeredevent != SHARKSSL_ALERT_LEVEL_WARNING) && (*registeredevent != SHARKSSL_ALERT_LEVEL_FATAL))) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); goto _sharkssl_alert_illegal_parameter; } if (*registeredevent != SHARKSSL_ALERT_LEVEL_WARNING) { fpemureturn(o); } o->flags |= switcherregister; o->alertLevel = *registeredevent++; o->alertDescr = *registeredevent++; atagsprocfs -= backuppdata; o->inBuf.dataLen = atagsprocfs; o->inBuf.data = registeredevent; ret = SharkSslCon_AlertRecv; break; } return ret; } #if SHARKSSL_TLS_1_3 #if SHARKSSL_ENABLE_SESSION_CACHE #define bgezllabel(s,b,c,o,l,h) brespdisable(s,b,c,o,l,0,h) static int brespdisable(U8 *spi4000check, char *clkdmoperations, U8 *context, U8 *out, U16 cachemumbojumbo, U8 ptrauthdisable, U8 configwrite) #else static int bgezllabel(U8 *spi4000check, char *clkdmoperations, U8 *context, U8 *out, U16 cachemumbojumbo, U8 configwrite) #endif { #define HKDF_LABEL_MAX_LENGTH 12 U8 memblocksteal[SHARKSSL_MAX_HASH_LEN + 2 + 1 + 6 + HKDF_LABEL_MAX_LENGTH + 1 + SHARKSSL_MAX_HASH_LEN + 1]; U16 ftraceupdate = sharkssl_getHashLen(configwrite); U16 loops, HLen; HLen = (U16)strlen(clkdmoperations); baAssert(HLen <= HKDF_LABEL_MAX_LENGTH); memblocksteal[SHARKSSL_MAX_HASH_LEN + 0] = (U8)(cachemumbojumbo >> 8); memblocksteal[SHARKSSL_MAX_HASH_LEN + 1] = (U8)(cachemumbojumbo & 0xFF); memblocksteal[SHARKSSL_MAX_HASH_LEN + 2] = (U8)(HLen + 6); memblocksteal[SHARKSSL_MAX_HASH_LEN + 3] = '\164'; memblocksteal[SHARKSSL_MAX_HASH_LEN + 4] = '\154'; memblocksteal[SHARKSSL_MAX_HASH_LEN + 5] = '\163'; memblocksteal[SHARKSSL_MAX_HASH_LEN + 6] = '\061'; memblocksteal[SHARKSSL_MAX_HASH_LEN + 7] = '\063'; memblocksteal[SHARKSSL_MAX_HASH_LEN + 8] = '\040'; memcpy(&memblocksteal[SHARKSSL_MAX_HASH_LEN + 9], clkdmoperations, HLen); baAssert(ftraceupdate <= 0xFF); if (NULL == context) { memblocksteal[SHARKSSL_MAX_HASH_LEN + 9 + HLen] = 0; } else { #if SHARKSSL_ENABLE_SESSION_CACHE U8 driverunregister = (ptrauthdisable > 0) ? ptrauthdisable : (U8)ftraceupdate; #else #define driverunregister ftraceupdate #endif memblocksteal[SHARKSSL_MAX_HASH_LEN + 9 + HLen] = (U8)driverunregister; memcpy(&memblocksteal[SHARKSSL_MAX_HASH_LEN + 10 + HLen], context, driverunregister); HLen += driverunregister; #ifdef driverunregister #undef driverunregister #endif } HLen += 11; loops = (cachemumbojumbo + ftraceupdate - 1)/ftraceupdate; memblocksteal[SHARKSSL_MAX_HASH_LEN + HLen - 1] = 0x01; sharkssl_HMAC(configwrite, &memblocksteal[SHARKSSL_MAX_HASH_LEN], HLen, spi4000check, ftraceupdate, &memblocksteal[SHARKSSL_MAX_HASH_LEN - ftraceupdate]); memcpy(out, &memblocksteal[SHARKSSL_MAX_HASH_LEN - ftraceupdate], cachemumbojumbo); #if 1 while (--loops) { out += ftraceupdate; cachemumbojumbo -= ftraceupdate; memblocksteal[SHARKSSL_MAX_HASH_LEN + HLen - 1]++; sharkssl_HMAC(configwrite, &memblocksteal[SHARKSSL_MAX_HASH_LEN - ftraceupdate], ftraceupdate + HLen, spi4000check, ftraceupdate, &memblocksteal[SHARKSSL_MAX_HASH_LEN - ftraceupdate]); memcpy(out, &memblocksteal[SHARKSSL_MAX_HASH_LEN - ftraceupdate], (loops == 1) ? cachemumbojumbo : ftraceupdate); } #endif return 0; } #if SHARKSSL_ENABLE_SESSION_CACHE int SharkSslCon_calcResumptionSecret(SharkSslCon *o, U8 *chargerplatform) { baAssert(SharkSsl_isClient(o->sharkSsl)); bgezllabel(o->masterSecret, "\162\145\163\040\155\141\163\164\145\162", chargerplatform, o->resumptionMasterSecret, sharkssl_getHashLen(o->rCipherSuite->hashID), o->rCipherSuite->hashID); return 0; } int SharkSslCon_calcTicketPSK(SharkSslCon *o, U8 *PSK, U8 *broadcastenter, U8 unmapunlock) { baAssert(SharkSsl_isClient(o->sharkSsl)); if (0 == unmapunlock) { broadcastenter = NULL; } brespdisable(o->resumptionMasterSecret, "\162\145\163\165\155\160\164\151\157\156", broadcastenter, PSK, sharkssl_getHashLen(o->rCipherSuite->hashID), unmapunlock, o->rCipherSuite->hashID); return 0; } int SharkSslCon_calcEarlySecret(SharkSslCon *o, U8 *PSK, U8 configwrite) { SharkSslHSParam* sharkSslHSParam = hsParam(o); U8 t1[SHARKSSL_MAX_HASH_LEN]; U16 ftraceupdate; baAssert(SharkSsl_isClient(o->sharkSsl)); ftraceupdate = sharkssl_getHashLen(configwrite); t1[0] = 0; sharkssl_HMAC(configwrite, PSK, ftraceupdate, t1, 1, o->masterSecret); sharkssl_hash(t1, t1, 0, configwrite); bgezllabel(o->masterSecret, "\162\145\163\040\142\151\156\144\145\162", t1, t1, ftraceupdate, configwrite); bgezllabel(t1, "\146\151\156\151\163\150\145\144", NULL, sharkSslHSParam->prot.tls13.HSSecret, ftraceupdate, configwrite); return 0; } #endif int SharkSslCon_calcAppTrafficSecret(SharkSslCon *o, U8 *chargerplatform) { SharkSslHSParam* sharkSslHSParam = hsParam(o); U8 t1[SHARKSSL_MAX_HASH_LEN], t2[SHARKSSL_MAX_HASH_LEN]; U16 ftraceupdate; baAssert(SharkSsl_isClient(o->sharkSsl)); o->rCipherSuite->cipherFunc(o, chargerworker | populatebasepages, (U8*)0, 0); o->wCipherSuite->cipherFunc(o, chargerworker | ptraceregsets, (U8*)0, 0); memset(t2, 0, ftraceupdate = sharkssl_getHashLen(o->rCipherSuite->hashID)); sharkssl_hash(t1, t1, 0, o->rCipherSuite->hashID); bgezllabel(sharkSslHSParam->prot.tls13.HSSecret, "\144\145\162\151\166\145\144", t1, t1, ftraceupdate, o->rCipherSuite->hashID); sharkssl_HMAC(o->rCipherSuite->hashID, t2, ftraceupdate, t1, ftraceupdate, o->masterSecret); bgezllabel(o->masterSecret, "\163\040\141\160\040\164\162\141\146\146\151\143", chargerplatform, t1, ftraceupdate, o->rCipherSuite->hashID); bgezllabel(o->masterSecret, "\143\040\141\160\040\164\162\141\146\146\151\143", chargerplatform, t2, ftraceupdate, o->wCipherSuite->hashID); bgezllabel(t1, "\153\145\171", NULL, o->rKey, o->rCipherSuite->keyLen, o->rCipherSuite->hashID); bgezllabel(t2, "\153\145\171", NULL, o->wKey, o->wCipherSuite->keyLen, o->wCipherSuite->hashID); bgezllabel(t1, "\151\166", NULL, o->rIV, 12, o->rCipherSuite->hashID); bgezllabel(t2, "\151\166", NULL, o->wIV, 12, o->wCipherSuite->hashID); o->rCipherSuite->cipherFunc(o, SHARKSSL_OP_CONSTRUCTOR | populatebasepages, (U8*)0, 0); o->wCipherSuite->cipherFunc(o, SHARKSSL_OP_CONSTRUCTOR | ptraceregsets, (U8*)0, 0); disablelevel(o->rSeqNum); disablelevel(o->wSeqNum); return 0; } int SharkSslCon_calcHandshakeTrafficSecret(SharkSslCon *o) { SharkSslHSParam* sharkSslHSParam = hsParam(o); U8 chargerplatform[SHARKSSL_MAX_HASH_LEN]; U8 t1[SHARKSSL_MAX_HASH_LEN], t2[SHARKSSL_MAX_HASH_LEN]; U16 ftraceupdate; baAssert(SharkSsl_isClient(o->sharkSsl)); o->rCipherSuite = o->wCipherSuite = sharkSslHSParam->cipherSuite; wakeupvector(sharkSslHSParam, &chargerplatform[0], o->rCipherSuite->hashID); memset(t1, 0, ftraceupdate = sharkssl_getHashLen(o->rCipherSuite->hashID)); #if SHARKSSL_ENABLE_SESSION_CACHE if (o->flags & startqueue) { memcpy(t2, o->masterSecret, ftraceupdate); } else #endif { sharkssl_HMAC(o->rCipherSuite->hashID, t1, ftraceupdate, t1, 1, t2); } sharkssl_hash(t1, t1, 0, o->rCipherSuite->hashID); bgezllabel(t2, "\144\145\162\151\166\145\144", t1, t2, ftraceupdate, o->rCipherSuite->hashID); sharkssl_HMAC(o->rCipherSuite->hashID, sharkSslHSParam->ecdhParam.k, sharkSslHSParam->ecdhParam.xLen, t2, ftraceupdate, sharkSslHSParam->prot.tls13.HSSecret); bgezllabel(sharkSslHSParam->prot.tls13.HSSecret, "\163\040\150\163\040\164\162\141\146\146\151\143", chargerplatform, sharkSslHSParam->prot.tls13.srvHSTraffic, ftraceupdate, o->rCipherSuite->hashID); bgezllabel(sharkSslHSParam->prot.tls13.HSSecret, "\143\040\150\163\040\164\162\141\146\146\151\143", chargerplatform, sharkSslHSParam->prot.tls13.cliHSTraffic, ftraceupdate, o->rCipherSuite->hashID); bgezllabel(sharkSslHSParam->prot.tls13.srvHSTraffic, "\153\145\171", NULL, o->rKey, o->rCipherSuite->keyLen, o->rCipherSuite->hashID); bgezllabel(sharkSslHSParam->prot.tls13.cliHSTraffic, "\153\145\171", NULL, o->wKey, o->wCipherSuite->keyLen, o->wCipherSuite->hashID); bgezllabel(sharkSslHSParam->prot.tls13.srvHSTraffic, "\151\166", NULL, o->rIV, 12, o->rCipherSuite->hashID); bgezllabel(sharkSslHSParam->prot.tls13.cliHSTraffic, "\151\166", NULL, o->wIV, 12, o->wCipherSuite->hashID); o->rCipherSuite->cipherFunc(o, SHARKSSL_OP_CONSTRUCTOR | populatebasepages, (U8*)0, 0); o->wCipherSuite->cipherFunc(o, SHARKSSL_OP_CONSTRUCTOR | ptraceregsets, (U8*)0, 0); disablelevel(o->rSeqNum); disablelevel(o->wSeqNum); return 0; } #endif SharkSslCon_RetVal kexecprotect(SharkSslCon *o, U8 *registeredevent, U16 atagsprocfs) { #if SHARKSSL_TLS_1_2 SharkSslHSParam *sharkSslHSParam = hsParam(o); #endif if ( #if SHARKSSL_TLS_1_3 ( #if SHARKSSL_TLS_1_2 (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) && #endif (o->state != SHARKSSL_HANDSHAKETYPE_ENCRYPTED_EXTENSIONS) ) #if SHARKSSL_TLS_1_2 || #endif #endif #if SHARKSSL_TLS_1_2 ( #if SHARKSSL_TLS_1_3 (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) && #endif (o->state != switcherdevice) ) #endif ) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_UNEXPECTED_MESSAGE); } if ((atagsprocfs != 1) || (*registeredevent != 1)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_ILLEGAL_PARAMETER); } o->flags |= cachematch; #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->rCipherSuite) { baAssert(o->flags & platformdevice); o->rCipherSuite->cipherFunc(o, chargerworker | populatebasepages, (U8*)0, 0); } #endif o->rCipherSuite = sharkSslHSParam->cipherSuite; #if SHARKSSL_ENABLE_AES_GCM if (o->rCipherSuite->flags & framekernel) { baAssert(SHARKSSL_MAX_KEY_LEN); memcpy(o->rKey, sharkSslHSParam->prot.tls12.sharedSecret + (SharkSsl_isClient(o->sharkSsl) ? o->rCipherSuite->keyLen : 0), o->rCipherSuite->keyLen); memcpy(o->rIV, sharkSslHSParam->prot.tls12.sharedSecret + (2 * o->rCipherSuite->keyLen) + (SharkSsl_isClient(o->sharkSsl) ? 4 : 0), 4); memset(&(o->rIV[4]), 0, 8); } #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) else #endif #endif #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) #if SHARKSSL_ENABLE_AES_GCM if (o->rCipherSuite->flags & suspendenter) #endif { baAssert(SHARKSSL_MAX_KEY_LEN); memcpy(o->rKey, sharkSslHSParam->prot.tls12.sharedSecret + (SharkSsl_isClient(o->sharkSsl) ? o->rCipherSuite->keyLen : 0), o->rCipherSuite->keyLen); memcpy(o->rIV, sharkSslHSParam->prot.tls12.sharedSecret + (2 * o->rCipherSuite->keyLen) + (SharkSsl_isClient(o->sharkSsl) ? 12 : 0), 12); } #if SHARKSSL_ENABLE_AES_GCM else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } #endif #endif o->rCipherSuite->cipherFunc(o, SHARKSSL_OP_CONSTRUCTOR | populatebasepages, (U8*)0, 0); disablelevel(o->rSeqNum); } #endif o->inBuf.temp = 0; return SharkSslCon_Handshake; } #if SHARKSSL_TLS_1_2 int sanitisependbaser(SharkSslCon *o, SharkSslCon_SendersRole fixupcy82c693, U8 *pciercxcfg448) { U8 *tp, i; SharkSslHSParam *sharkSslHSParam = hsParam(o); baAssert(serial2platform(&o->outBuf)); #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->wCipherSuite) { baAssert(o->flags & platformdevice); tp = templateentry(o, rangealigned, o->outBuf.data, 1); *tp++ = 1; if (SharkSslCon_calcMACAndEncrypt(o) < 0) { return -1; } if (pciercxcfg448 == NULL) { pciercxcfg448 = func3fixup(&o->inBuf); o->inBuf.temp = 0; } memcpy(pciercxcfg448, o->outBuf.data, o->outBuf.dataLen); registerfixed(&o->outBuf); o->inBuf.temp += o->outBuf.dataLen; pciercxcfg448 += o->outBuf.dataLen; o->wCipherSuite->cipherFunc(o, chargerworker | ptraceregsets, (U8*)0, 0); } #endif o->wCipherSuite = sharkSslHSParam->cipherSuite; #if SHARKSSL_ENABLE_AES_GCM if (o->wCipherSuite->flags & framekernel) { baAssert(o->minor >= 3); baAssert(SHARKSSL_MAX_KEY_LEN); memcpy(o->wKey, sharkSslHSParam->prot.tls12.sharedSecret + (SharkSsl_isServer(o->sharkSsl) ? o->wCipherSuite->keyLen : 0), o->wCipherSuite->keyLen); memcpy(o->wIV, sharkSslHSParam->prot.tls12.sharedSecret + (2 * o->wCipherSuite->keyLen) + (SharkSsl_isServer(o->sharkSsl) ? 4 : 0), 4); memset(&o->wIV[4], 0, 8); } #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) else #endif #endif #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) #if SHARKSSL_ENABLE_AES_GCM if (o->wCipherSuite->flags & suspendenter) #endif { baAssert(SHARKSSL_MAX_KEY_LEN); memcpy(o->wKey, sharkSslHSParam->prot.tls12.sharedSecret + (SharkSsl_isServer(o->sharkSsl) ? o->wCipherSuite->keyLen : 0), o->wCipherSuite->keyLen); memcpy(o->wIV, sharkSslHSParam->prot.tls12.sharedSecret + (2 * o->wCipherSuite->keyLen) + (SharkSsl_isServer(o->sharkSsl) ? 12 : 0), 12); disablelevel(o->wSeqNum); } #if SHARKSSL_ENABLE_AES_GCM else { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return savedconfig(o, SHARKSSL_ALERT_INTERNAL_ERROR); } #endif #endif o->wCipherSuite->cipherFunc(o, SHARKSSL_OP_CONSTRUCTOR | ptraceregsets, (U8*)0, 0); tp = o->outBuf.data; i = SHARKSSL_FINISHED_MSG_LEN_TLS_1_2; tp = templateentry(o, controllegacy, tp, i + traceentry); *tp++ = switcherdevice; *tp++ = 0x00; *tp++ = 0x00; *tp++ = i; if (printsilicon(o, fixupcy82c693, tp) < 0) { return -1; } #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION memcpy(SharkSsl_isServer(o->sharkSsl) ? o->serverVerifyData : o->clientVerifyData, tp, i); #endif if (((fixupcy82c693 == rodatastart) && (o->flags & startqueue)) || ((fixupcy82c693 == tvp5146routes) && (!(o->flags & startqueue)))) { ioremapresource(sharkSslHSParam, tp - traceentry, i + traceentry); } if (SharkSslCon_calcMACAndEncrypt(o) < 0) { return -1; } if (pciercxcfg448 == NULL) { baAssert(!(o->flags & createmappings)); o->flags |= createmappings; pciercxcfg448 = o->outBuf.data; } o->inBuf.temp += o->outBuf.dataLen; #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & platformdevice) { memcpy(pciercxcfg448, o->outBuf.data, o->outBuf.dataLen); } else #endif { { memmove(pciercxcfg448 + clkctrlmanaged + 1, o->outBuf.data, o->outBuf.dataLen); tp = templateentry(o, rangealigned, pciercxcfg448, 1); *tp++ = 1; baAssert((clkctrlmanaged + 1) == (U16)(tp - pciercxcfg448)); o->inBuf.temp += (clkctrlmanaged + 1); } } return 0; } #endif SharkSslCon_RetVal savedconfig(SharkSslCon *o, U8 local1irqdispatch) { fpemureturn(o); return securememblock(o, SHARKSSL_ALERT_LEVEL_FATAL, local1irqdispatch); } SharkSslCon_RetVal securememblock(SharkSslCon *o, U8 disableerrgen, U8 local1irqdispatch) { U8 *tp; baAssert(o); baAssert((disableerrgen == SHARKSSL_ALERT_LEVEL_WARNING) || (disableerrgen == SHARKSSL_ALERT_LEVEL_FATAL)); baAssert( (local1irqdispatch <= SHARKSSL_ALERT_UNRECOGNIZED_NAME)); if (microresources(&o->outBuf)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } o->inBuf.dataLen = o->inBuf.temp = 0; registerfixed(&o->inBuf); registerfixed(&o->outBuf); tp = templateentry(o, firstentry, o->outBuf.data, 2); o->flags |= switcherregister; *tp++ = o->alertLevel = disableerrgen; *tp++ = o->alertDescr = local1irqdispatch; o->outBuf.dataLen = (U16)(tp - o->outBuf.data); if (o->wCipherSuite) { if (SharkSslCon_calcMACAndEncrypt(o) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } } return SharkSslCon_AlertSend; } U8 *templateentry(SharkSslCon *o, U8 defaultattrs, U8 *ptr, U16 backuppdata) { *ptr++ = defaultattrs; *ptr++ = o->major; *ptr++ = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); *ptr++ = (U8)(backuppdata >> 8); *ptr++ = (U8)(backuppdata & 0xFF); return ptr; } void fpemureturn(SharkSslCon *o) { baAssert(o); baAssert(!(o->flags & firstcomponent)); o->flags |= firstcomponent; } #if SHARKSSL_TLS_1_2 U16 disableclean(SharkSslCipherSuite* c) { U16 hwcapfixup; hwcapfixup = c->keyLen; #if SHARKSSL_ENABLE_AES_GCM if (c->flags & framekernel) { hwcapfixup += 4; } else #endif { #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) if (c->flags & suspendenter) { hwcapfixup += 12; } #endif } baAssert(hwcapfixup < (U16)0x8000); return ((U16)(hwcapfixup << 1)); } int allocalloc(SharkSslCon *o, U8 *pciercxcfg448, U16 len, U8 *s, U16 sLen, U8 r1[32], U8 r2[32]) { #if SHARKSSL_CRYPTO_USE_HEAP U8 *buf; #else U8 buf[claimresource(SHARKSSL_MAX_DIGEST_LEN + 13 + 32 + 32)]; #endif U8 *p; int offsetarray = -1; U16 ftraceupdate; U8 configwrite, n; baAssert(o && pciercxcfg448 && len && sLen && s && r1 && r2); baAssert(pcmciaplatform(pciercxcfg448)); baAssert((len & 0x03) == 0); #if SHARKSSL_CRYPTO_USE_HEAP buf = (U8*)baMalloc(claimresource(SHARKSSL_MAX_DIGEST_LEN + 13 + 32 + 32)); baAssert(buf); if (!buf) { return offsetarray; } #endif configwrite = hsParam(o)->cipherSuite->hashID; ftraceupdate = sharkssl_getHashLen(configwrite); n = (U8)((len + (ftraceupdate - 1)) / ftraceupdate); baAssert(n > 0); p = &buf[ftraceupdate]; memcpy(p, (pciercxcfg448 == hsParam(o)->prot.tls12.masterSecret) ? "\155\141\163\164\145\162\040\163\145\143\162\145\164" : "\153\145\171\040\145\170\160\141\156\163\151\157\156", 13); memcpy(p + 13, r1, 32); memcpy(p + 13 + 32, r2, 32); if (sharkssl_HMAC(configwrite, p, 13 + 32 + 32, s, sLen, buf) < 0) { goto _SharkSslCon_calcCryptoParam_exit; } for (; ; pciercxcfg448 += ftraceupdate) { if (sharkssl_HMAC(configwrite, buf, ftraceupdate + 13 + 32 + 32, s, sLen, pciercxcfg448) < 0) { goto _SharkSslCon_calcCryptoParam_exit; } if (--n == 0) { break; } if (sharkssl_HMAC(configwrite, buf, ftraceupdate, s, sLen, buf) < 0) { goto _SharkSslCon_calcCryptoParam_exit; } } offsetarray = 0; _SharkSslCon_calcCryptoParam_exit: #if SHARKSSL_CRYPTO_USE_HEAP baFree(buf); #endif return offsetarray; } #endif int printsilicon(SharkSslCon *o, SharkSslCon_SendersRole fixupcy82c693, U8 *chargerplatform) { #if SHARKSSL_TLS_1_2 int offsetarray = -1; #endif U16 ftraceupdate; U8 configwrite; configwrite = hsParam(o)->cipherSuite->hashID; ftraceupdate = sharkssl_getHashLen(configwrite); #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { U8 buf[SHARKSSL_MAX_HASH_LEN]; bgezllabel((fixupcy82c693 == tvp5146routes) ? hsParam(o)->prot.tls13.cliHSTraffic : hsParam(o)->prot.tls13.srvHSTraffic, "\146\151\156\151\163\150\145\144", NULL, buf, ftraceupdate, configwrite); wakeupvector(hsParam(o), chargerplatform, configwrite); if (sharkssl_HMAC(configwrite, chargerplatform, ftraceupdate, buf, ftraceupdate, chargerplatform) < 0) { return -1; } return 0; } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { U8 *buf; buf = (U8*)baMalloc((ftraceupdate << 1) + 16 ); if (buf) { memcpy(&buf[ftraceupdate], (fixupcy82c693 == tvp5146routes) ? "\143\154\151\145\156\164\040\146\151\156\151\163\150\145\144" : "\163\145\162\166\145\162\040\146\151\156\151\163\150\145\144", 15); wakeupvector(hsParam(o), &buf[ftraceupdate + 15], configwrite); if (sharkssl_HMAC(configwrite, &buf[ftraceupdate], 15 + ftraceupdate, hsParam(o)->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, buf) < 0) { goto _SharkSslCon_calcFinishedHash_exit; } if (sharkssl_HMAC(configwrite, buf, (U16)(ftraceupdate << 1) + 15 , hsParam(o)->prot.tls12.masterSecret, SHARKSSL_MASTER_SECRET_LEN, buf) < 0) { goto _SharkSslCon_calcFinishedHash_exit; } memcpy(chargerplatform, buf, 12); offsetarray = 0; _SharkSslCon_calcFinishedHash_exit: baFree(buf); } } return offsetarray; #endif } #if SHARKSSL_TLS_1_3 int SharkSslCon_calcMACAndEncryptHS(SharkSslCon *o) { U8 *p; U16 fastforwardsingle; baAssert(o->rCipherSuite); baAssert(o->rCipherSuite->flags & (framekernel | suspendenter)); p = o->inBuf.data; fastforwardsingle = (U16)(((U16)(*(p + 3)) << 8) + *(p + 4)); p += clkctrlmanaged; if (o->wCipherSuite->cipherFunc(o, ptraceregsets, p, fastforwardsingle)) { return -1; } fastforwardsingle = (U16)(((U16)(*(p - 2)) << 8) + *(p - 1)); o->inBuf.temp = clkctrlmanaged + fastforwardsingle; baAssert(o->inBuf.size >= o->inBuf.temp); return 0; } #endif int SharkSslCon_calcMACAndEncrypt(SharkSslCon *o) { U8 *p; U16 fastforwardsingle; #if (SHARKSSL_TLS_1_2 && SHARKSSL_ENABLE_AES_GCM) U8 guestconfig4 = *(o->outBuf.data); #endif baAssert(SHARKSSL_ENABLE_AES_GCM || (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305)); baAssert(serial2platform(&o->outBuf)); baAssert(o->wCipherSuite); baAssert(o->wCipherSuite->flags & (framekernel | suspendenter)); p = o->outBuf.data; fastforwardsingle = (U16)(((U16)(*(p + 3)) << 8) + *(p + 4)); #if (SHARKSSL_TLS_1_2 && SHARKSSL_ENABLE_AES_GCM) #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { if (o->wCipherSuite->flags & framekernel) { memcpy(p - SHARKSSL_AES_GCM_EXPLICIT_IV_LEN, &o->wIV[4], SHARKSSL_AES_GCM_EXPLICIT_IV_LEN); } } #endif p += clkctrlmanaged; if (o->wCipherSuite->cipherFunc(o, ptraceregsets, p, fastforwardsingle)) { return -1; } #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif { clusterpowerdown(o->wSeqNum); fastforwardsingle = (U16)(((U16)(*(p - 2)) << 8) + *(p - 1)); } #if SHARKSSL_TLS_1_2 else #endif #endif #if SHARKSSL_TLS_1_2 { #if (SHARKSSL_USE_CHACHA20 && SHARKSSL_USE_POLY1305) if (o->wCipherSuite->flags & suspendenter) { baAssert(16 == o->wCipherSuite->digestLen); clusterpowerdown(o->wSeqNum); fastforwardsingle += 16; *(p + 3 - clkctrlmanaged) = (U8)(fastforwardsingle >> 8); *(p + 4 - clkctrlmanaged) = (U8)(fastforwardsingle & 0xFF); } #if SHARKSSL_ENABLE_AES_GCM else #endif #endif #if SHARKSSL_ENABLE_AES_GCM if (o->wCipherSuite->flags & framekernel) { memcpy(p - SHARKSSL_AES_GCM_EXPLICIT_IV_LEN, &o->wIV[4], SHARKSSL_AES_GCM_EXPLICIT_IV_LEN); clusterpowerdown(&o->wIV[4]); fastforwardsingle += o->wCipherSuite->digestLen + SHARKSSL_AES_GCM_EXPLICIT_IV_LEN; o->outBuf.data = (p - clkctrlmanaged - SHARKSSL_AES_GCM_EXPLICIT_IV_LEN); templateentry(o, guestconfig4, o->outBuf.data, fastforwardsingle); } #endif } #endif o->outBuf.dataLen = clkctrlmanaged + fastforwardsingle; baAssert(o->outBuf.size >= o->outBuf.dataLen); return 0; } SHARKSSL_API U16 SharkSslCon_getDecData(SharkSslCon *o, U8 **ptregdefines) { U16 guestdebug; baAssert(o); baAssert(ptregdefines); baAssert(!(o->flags & firstcomponent)); *ptregdefines = o->inBuf.data; guestdebug = o->inBuf.temp; o->inBuf.data += guestdebug; o->inBuf.temp = 0; if (o->inBuf.dataLen) { o->inBuf.data += o->padLen; #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { o->inBuf.data += o->rCipherSuite->digestLen; } #endif o->padLen = 0; } else { o->flags &= ~clockgettime32; registerfixed(&o->inBuf); } return guestdebug; } U16 SharkSslCon_copyDecData(SharkSslCon *o, U8 *buf, U16 masterclock) { baAssert(o); baAssert(buf); baAssert(!(o->flags & firstcomponent)); if (o->inBuf.temp < masterclock) { masterclock = o->inBuf.temp; } memcpy(buf, o->inBuf.data, masterclock); o->inBuf.data += masterclock; o->inBuf.temp -= masterclock; if (0 == o->inBuf.temp) { if (o->inBuf.dataLen) { o->inBuf.data += o->padLen; #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif { o->inBuf.data += o->rCipherSuite->digestLen; } #endif o->padLen = 0; } else { o->flags &= ~clockgettime32; registerfixed(&o->inBuf); } } return masterclock; } U8 *SharkSslCon_getBuf(SharkSslCon *o) { baAssert(o); baAssert(o->inBuf.data); return (o->inBuf.data + o->inBuf.dataLen); } U16 SharkSslCon_getBufLen(SharkSslCon *o) { baAssert(o); return (o->inBuf.size - o->inBuf.dataLen); } U8 SharkSslCon_decryptMore(SharkSslCon *o) { baAssert(o); return ((o->flags & clockgettime32) ? 1 : 0); } U8 SharkSslCon_encryptMore(SharkSslCon *o) { baAssert(o); return ((o->flags & audiosuspend) ? 1 : 0); } U16 SharkSslCon_getHandshakeDataLen(SharkSslCon *o) { baAssert(o); return (o->inBuf.temp); } U16 SharkSslCon_setHandshakeDataSent(SharkSslCon *o, U16 traceleave) { U16 res = 0; baAssert(o); if (traceleave <= (o->inBuf.temp)) { res = o->inBuf.temp; if (traceleave > 0) { res -= traceleave; if (res > 0) { memmove(func3fixup(&o->inBuf), func3fixup(&o->inBuf) + traceleave, res); o->flags |= SHARKSSL_FLAG_PARTIAL_HS_SEND; } o->inBuf.temp = res; } } return res; } U8 *SharkSslCon_getHandshakeData(SharkSslCon *o) { if (SharkSslCon_getHandshakeDataLen(o)) { #if SHARKSSL_TLS_1_2 if (o->flags & createmappings) { baAssert(o->outBuf.data); o->flags &= ~createmappings; return (o->outBuf.data); } #endif baAssert(o->inBuf.buf); return (func3fixup(&o->inBuf)); } return NULL; } U8 SharkSslCon_isHandshakeComplete(SharkSslCon *o) { baAssert(o); if (!(o->flags & SHARKSSL_FLAG_PARTIAL_HS_SEND)) { if ((o->state == loongson3notifier) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION && (!(o->flags & skciphersetkey)) #endif ) { #if SHARKSSL_TLS_1_3 if (SharkSsl_isClient(o->sharkSsl) && (o->inBuf.dataLen) #if SHARKSSL_TLS_1_2 && (o->minor == SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3)) #endif ) { return 2; } #endif return 1; } } return 0; } U8 SharkSslCon_getAlertLevel(SharkSslCon *o) { baAssert(o); return (o->alertLevel); } U8 SharkSslCon_getAlertDescription(SharkSslCon *o) { baAssert(o); return (o->alertDescr); } SharkSslCon_RetVal SharkSslCon_encrypt(SharkSslCon *o, U8 *buf, U16 masterclock) { U8 *tp, iotimingdebugfs; U16 brightnesslimit; SharkSslBuf *oBuf; baAssert(o); if (o->flags & firstcomponent) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION if (o->flags & (registerbuses | skciphersetkey)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } #endif if (!SharkSslCon_isHandshakeComplete(o)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_HandshakeNotComplete; } baAssert(!microresources(&o->outBuf)); oBuf = &o->outBuf; registerfixed(oBuf); brightnesslimit = oBuf->temp; masterclock -= brightnesslimit; if ((!buf) && (brightnesslimit)) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } iotimingdebugfs = r3000tlbchange(o); baAssert(oBuf->size > iotimingdebugfs); if (masterclock <= (oBuf->size - iotimingdebugfs)) { o->flags &= ~audiosuspend; oBuf->temp = 0; } else { if (!buf) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); return SharkSslCon_AllocationError; } o->flags |= audiosuspend; masterclock = (oBuf->size - iotimingdebugfs); oBuf->temp += masterclock; } tp = templateentry(o, polledbutton, oBuf->data, masterclock); if (buf) { memcpy(tp, buf + brightnesslimit, (oBuf->dataLen = masterclock)); } if (SharkSslCon_calcMACAndEncrypt(o) < 0) { SHARKDBG_PRINTF(("\045\163\072\040\045\144\012", __FILE__, __LINE__)); resvdexits(o); return SharkSslCon_Error; } return SharkSslCon_Encrypted; } U8 *SharkSslCon_getEncBufPtr(SharkSslCon *o) { baAssert(o); if (o->outBuf.data) { return (func3fixup(&(o->outBuf)) + clkctrlmanaged); } return (U8*)0; } U16 SharkSslCon_getEncBufSize(SharkSslCon *o) { baAssert(o); if (o->outBuf.data) { return (o->outBuf.size - r3000tlbchange(o)); } return 0; } U8 *SharkSslCon_getEncData(SharkSslCon *o) { baAssert(o); baAssert(o->outBuf.data); return (o->outBuf.data); } U16 SharkSslCon_getEncDataLen(SharkSslCon *o) { baAssert(o); return (o->outBuf.dataLen); } #if SHARKSSL_ENABLE_INFO_API SHARKSSL_API U16 SharkSslCon_getCiphersuite(SharkSslCon *o) { baAssert(o); if (SharkSslCon_isHandshakeComplete(o) && (o->rCipherSuite)) { baAssert(o->rCipherSuite == o->wCipherSuite); return o->rCipherSuite->id; } return 0; } #if (SHARKSSL_TLS_1_3 && SHARKSSL_TLS_1_2) SHARKSSL_API U8 SharkSslCon_getProtocol(SharkSslCon *o) { baAssert(o); baAssert(SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_2) == SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_3)); if ((o->major == SHARKSSL_PROTOCOL_MAJOR(SHARKSSL_PROTOCOL_TLS_1_3)) && (o->minor >= SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) && (o->minor <= SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3))) { return ((o->major << 4) | (o->minor)); } return SHARKSSL_PROTOCOL_UNKNOWN; } #endif #endif #if (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA) SHARKSSL_API SharkSslCertInfo *SharkSslCon_getCertInfo(SharkSslCon *o) { if (o) { #if SHARKSSL_ENABLE_SESSION_CACHE if ((o->session) && (o->session->clonedCertInfo)) { return &(o->session->clonedCertInfo->ci); } #endif if (o->clonedCertInfo) { return &(o->clonedCertInfo->ci); } } return (SharkSslCertInfo*)0; } U8 realnummemory(SharkSslCon *o, SharkSslClonedCertInfo **outCertInfoPtr) { baAssert(outCertInfoPtr); #if SHARKSSL_SSL_SERVER_CODE if (!(o->flags & serialreset)) #endif { U32 stringlookup; SharkSslCertInfo *ci; SharkSslClonedCertInfo *cci; ci = &(hsParam(o)->certParam.certInfo); baAssert(ci); stringlookup = 0; while (ci) { #if SHARKSSL_ENABLE_SESSION_CACHE if (stringlookup == 0) { stringlookup += sizeof(SharkSslClonedCertInfo); } else #endif { stringlookup += sizeof(SharkSslCertInfo); } stringlookup += SHARKSSL_ALIGNMENT; stringlookup += ci->snLen + ci->timeFromLen + ci->timeToLen + ci->issuer.commonNameLen + ci->issuer.countryNameLen + ci->issuer.localityLen + ci->issuer.organizationLen + ci->issuer.provinceLen + ci->issuer.unitLen + ci->subject.commonNameLen + ci->subject.countryNameLen + ci->subject.localityLen + ci->subject.organizationLen + ci->subject.provinceLen + ci->subject.unitLen + ci->subjectAltNamesLen; ci = ci->parent; } cci = (SharkSslClonedCertInfo*)baMalloc(claimresource(stringlookup)); if (cci != NULL) { U8 *p = (U8*)0; SharkSslCertInfo *di = &cci->ci; ci = &(hsParam(o)->certParam.certInfo); *outCertInfoPtr = cci; #if SHARKSSL_ENABLE_SESSION_CACHE cci->refcnt = 1; #endif for (;;) { if (p) { p = (U8*)((SharkSslCertInfo*)(di + 1)); } else { p = (U8*)((SharkSslClonedCertInfo*)(cci + 1)); } memcpy(di, ci, sizeof(SharkSslCertInfo)); memcpy(p, ci->sn, ci->snLen); di->sn = p; p += ci->snLen; memcpy(p, ci->timeFrom, ci->timeFromLen); di->timeFrom = p; p += ci->timeFromLen; memcpy(p, ci->timeTo, ci->timeToLen); di->timeTo = p; p += ci->timeToLen; if (ci->subjectAltNamesPtr) { baAssert(ci->subjectAltNamesLen > 0); memcpy(p, ci->subjectAltNamesPtr, ci->subjectAltNamesLen); di->subjectAltNamesPtr = p; di->subjectAltNamesLen = ci->subjectAltNamesLen; p += ci->subjectAltNamesLen; } if (ci->issuer.commonName) { memcpy(p, ci->issuer.commonName, ci->issuer.commonNameLen); di->issuer.commonName = p; p += ci->issuer.commonNameLen; } if (ci->issuer.countryName) { memcpy(p, ci->issuer.countryName, ci->issuer.countryNameLen); di->issuer.countryName = p; p += ci->issuer.countryNameLen; } if (ci->issuer.locality) { memcpy(p, ci->issuer.locality, ci->issuer.localityLen); di->issuer.locality = p; p += ci->issuer.localityLen; } if (ci->issuer.organization) { memcpy(p, ci->issuer.organization, ci->issuer.organizationLen); di->issuer.organization = p; p += ci->issuer.organizationLen; } if (ci->issuer.province) { memcpy(p, ci->issuer.province, ci->issuer.provinceLen); di->issuer.province = p; p += ci->issuer.provinceLen; } if (ci->issuer.unit) { memcpy(p, ci->issuer.unit, ci->issuer.unitLen); di->issuer.unit = p; p += ci->issuer.unitLen; } if (ci->subject.commonName) { memcpy(p, ci->subject.commonName, ci->subject.commonNameLen); di->subject.commonName = p; p += ci->subject.commonNameLen; } if (ci->subject.countryName) { memcpy(p, ci->subject.countryName, ci->subject.countryNameLen); di->subject.countryName = p; p += ci->subject.countryNameLen; } if (ci->subject.locality) { memcpy(p, ci->subject.locality, ci->subject.localityLen); di->subject.locality = p; p += ci->subject.localityLen; } if (ci->subject.organization) { memcpy(p, ci->subject.organization, ci->subject.organizationLen); di->subject.organization = p; p += ci->subject.organizationLen; } if (ci->subject.province) { memcpy(p, ci->subject.province, ci->subject.provinceLen); di->subject.province = p; p += ci->subject.provinceLen; } if (ci->subject.unit) { memcpy(p, ci->subject.unit, ci->subject.unitLen); di->subject.unit = p; p += ci->subject.unitLen; } p = (U8*)regulatorconsumer(p); ci = ci->parent; if (ci) { di->parent = (SharkSslCertInfo*)p; di = (SharkSslCertInfo*)p; } else { di->parent = (SharkSslCertInfo*)0; break; } } return 1; } } return 0; } #if (SHARKSSL_SSL_CLIENT_CODE && SHARKSSL_ENABLE_CLIENT_AUTH) U8 SharkSslCon_certificateRequested(SharkSslCon *o) { baAssert(o); return (o->flags & nresetconsumers) ? 1 : 0; } #endif #if SHARKSSL_ENABLE_CA_LIST SHARKSSL_API U8 SharkSslCon_trustedCA(SharkSslCon *o) { baAssert(o); return (o->flags & switcheractivation) ? 1 : 0; } U8 SharkSslCon_isCAListEmpty(SharkSslCon *o) { baAssert(o); baAssert(o->sharkSsl); baAssert(NULL == (void*)0); return (NULL == o->sharkSsl->caList); } #endif #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_RSA) U8 SharkSslCon_favorRSA(SharkSslCon *o, U8 sha256export) { if (o && ((!(SharkSslCon_isHandshakeComplete(o))) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION || (o->flags & registerbuses) #endif ) #if SHARKSSL_SSL_CLIENT_CODE && (SharkSsl_isServer(o->sharkSsl)) #endif ) { if (sha256export) { o->flags |= uprobeabort; } else { o->flags &= ~uprobeabort; } return 1; } return 0; } #endif #endif #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_CLIENT_AUTH && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) U8 SharkSslCon_requestClientCert(SharkSslCon *o, const void *displaysetup) { if (o && ((!(SharkSslCon_isHandshakeComplete(o))) #if SHARKSSL_ENABLE_SECURE_RENEGOTIATION || (o->flags & registerbuses) #endif ) #if SHARKSSL_SSL_CLIENT_CODE && (SharkSsl_isServer(o->sharkSsl)) #endif ) { o->flags |= unregistershash; #if SHARKSSL_ENABLE_CA_LIST o->caListCertReq = (SharkSslCAList)displaysetup; #else (void)displaysetup; #endif return 1; } return 0; } #endif #if (SHARKSSL_TLS_1_3 && SHARKSSL_SSL_CLIENT_CODE && SHARKSSL_ENABLE_CA_EXTENSION && (SHARKSSL_ENABLE_RSA || SHARKSSL_ENABLE_ECDSA)) U8 SharkSslCon_setCertificateAuthorities(SharkSslCon *o, const void *displaysetup) { if ((o) && (SharkSsl_isClient(o->sharkSsl)) && (o->state <= pciercxcfg070) #if SHARKSSL_TLS_1_2 && (o->minor != SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2)) #endif ) { #if SHARKSSL_ENABLE_CA_LIST o->flags |= SHARKSSL_FLAG_CA_EXTENSION_REQUEST; o->caListCertReq = (SharkSslCAList)displaysetup; return 1; #else (void)displaysetup; #endif } return 0; } #endif #if (SHARKSSL_SSL_SERVER_CODE && SHARKSSL_ENABLE_SECURE_RENEGOTIATION) U8 SharkSslCon_renegotiate(SharkSslCon *o) { if (o && (SharkSslCon_isHandshakeComplete(o) && (!(o->flags & (registerbuses | skciphersetkey)))) #if SHARKSSL_SSL_CLIENT_CODE && (SharkSsl_isServer(o->sharkSsl)) #endif ) { U8 *tp; #if SHARKSSL_ENABLE_ALPN_EXTENSION o->rALPN = NULL; #endif registerfixed(&o->outBuf); tp = templateentry(o, controllegacy, o->outBuf.data, 4); *tp++ = switchessetup; *tp++ = 0; *tp++ = 0; *tp++ = 0; if (SharkSslCon_calcMACAndEncrypt(o) >= 0) { o->inBuf.temp = o->outBuf.dataLen; o->flags |= registerbuses; o->flags |= createmappings; singleftosi(o); o->clonedCertInfo = (SharkSslClonedCertInfo*)0; return 1; } } return 0; } #endif #if SHARKSSL_SSL_CLIENT_CODE U8 SharkSslCon_selectProtocol(SharkSslCon *o, U8 ejtagsetup) { baAssert((ejtagsetup == SHARKSSL_PROTOCOL_TLS_1_2) || (ejtagsetup == SHARKSSL_PROTOCOL_TLS_1_3)); if ((!o) || (o->state >= pciercxcfg070) #if SHARKSSL_ENABLE_SESSION_CACHE || (o->session) #endif #if SHARKSSL_SSL_SERVER_CODE || (!(SharkSsl_isClient(o->sharkSsl))) #endif ) { return 0; } switch (ejtagsetup) { case SHARKSSL_PROTOCOL_TLS_1_2: #if SHARKSSL_TLS_1_2 o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_2); #endif break; case SHARKSSL_PROTOCOL_TLS_1_3: #if SHARKSSL_TLS_1_3 o->minor = SHARKSSL_PROTOCOL_MINOR(SHARKSSL_PROTOCOL_TLS_1_3); #endif break; default: break; } if (o->minor) { #if SHARKSSL_ENABLE_SELECT_CIPHERSUITE if (o->cipherSelCtr) { U8 i = 0; while (i < o->cipherSelCtr) { if (sharkssl_protocol_ciphersuite(ejtagsetup, o->cipherSelection[i])) { i++; } else { U8 j = i + 1; while (j < o->cipherSelCtr) { o->cipherSelection[j - 1] = o->cipherSelection[j]; j++; } o->cipherSelCtr--; o->cipherSelection[o->cipherSelCtr] = 0; } } } #endif return 1; } return 0; } #if SHARKSSL_ENABLE_SNI U8 SharkSslCon_setSNI(SharkSslCon *o, const char *gpio1config, U16 traceleave) { baAssert(o); baAssert(gpio1config || !traceleave); #if SHARKSSL_SSL_SERVER_CODE if (SharkSsl_isClient(o->sharkSsl)) #endif { if ((o->state == 0) && (traceleave <= 64)) { baAssert(traceleave < 0x100); o->padLen = traceleave; o->rCtx = (void*)gpio1config; return 1; } } return 0; } #endif #endif #if SHARKSSL_ENABLE_SESSION_CACHE #if SHARKSSL_ENABLE_INFO_API U8 SharkSslCon_isResumed(SharkSslCon *o) { baAssert(startqueue == 0x200); return (U8)((U32)(o->flags & startqueue) >> 9); } #endif U8 SharkSslSession_release(SharkSslSession *o, SharkSsl *s) { baAssert(s); if (o) { filtermatch(&s->sessionCache); baAssert(o->nUse); if (o->nUse) { o->nUse--; SHARKDBG_PRINTF(("\157\050\045\060\070\130\051\055\076\156\125\163\145\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)o, (U32)o->nUse, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\137\162\145\154\145\141\163\145")); #if SHARKSSL_SSL_CLIENT_CODE if ((SharkSsl_isClient(s)) && (0 == o->nUse)) { #if SHARKSSL_ENABLE_CA_LIST o->flags &= ~ecoffaouthdr; #endif if (o->clonedCertInfo) { o->clonedCertInfo->refcnt--; SHARKDBG_PRINTF(("\157\050\045\060\070\130\051\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\050\045\060\070\130\051\055\076\162\145\146\143\156\164\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)o, (U32)o->clonedCertInfo, o->clonedCertInfo->refcnt, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\137\162\145\154\145\141\163\145")); if (0 == o->clonedCertInfo->refcnt) { SHARKDBG_PRINTF(("\157\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\040\162\145\154\145\141\163\145\144\054\040\045\163\072\040\045\144\012", __FILE__, __LINE__)); baFree((void*)o->clonedCertInfo); } o->clonedCertInfo = (SharkSslClonedCertInfo*)0; } if (SharkSslSession_isProtocol(o, SHARKSSL_PROTOCOL_TLS_1_3) && (o->prot.tls13.ticket)) { baFree((void*)o->prot.tls13.ticket); o->prot.tls13.ticket = (U8*)0; } } #endif } helperglobal(&s->sessionCache); return 1; } return 0; } void SharkSslSession_copyClonedCertInfo(SharkSslSession *func2fixup, SharkSslCon *o) { baAssert((SharkSslClonedCertInfo*)0 == func2fixup->clonedCertInfo); func2fixup->clonedCertInfo = o->clonedCertInfo; o->clonedCertInfo->refcnt++; SHARKDBG_PRINTF(("\157\050\045\060\070\130\051\055\076\143\154\157\156\145\144\103\145\162\164\111\156\146\157\050\045\060\070\130\051\055\076\162\145\146\143\156\164\072\040\045\144\054\040\045\163\072\040\045\144\040\050\045\163\051\012", (U32)o, (U32)o->clonedCertInfo, o->clonedCertInfo->refcnt, __FILE__, __LINE__, "\123\150\141\162\153\123\163\154\123\145\163\163\151\157\156\137\143\157\160\171\103\154\157\156\145\144\103\145\162\164\111\156\146\157")); #if SHARKSSL_ENABLE_CA_LIST if (o->flags & switcheractivation) { func2fixup->flags |= ecoffaouthdr; } #endif } #if SHARKSSL_SSL_SERVER_CODE U8 SharkSslCon_releaseSession(SharkSslCon *o) { baAssert(o); if ((SharkSsl_isServer(o->sharkSsl)) && (SharkSslCon_isHandshakeComplete(o)) && (o->session)) { SharkSslSession *s = o->session; o->session = NULL; return SharkSslSession_release(s, o->sharkSsl); } return 0; } #endif #if SHARKSSL_SSL_CLIENT_CODE SharkSslSession *SharkSslCon_acquireSession(SharkSslCon *o) { baAssert(o); if ((SharkSsl_isClient(o->sharkSsl)) && (SharkSslCon_isHandshakeComplete(o)) && (o->sharkSsl->sessionCache.cache) && (o->session)) { baAssert(o->minor == hardirqsenabled(o->session)); #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (SharkSslSession_isProtocol(o->session, SHARKSSL_PROTOCOL_TLS_1_2)) #endif { return latchgpiochip(&(o->sharkSsl->sessionCache), o, o->session->prot.tls12.id, SHARKSSL_MAX_SESSION_ID_LEN); } #if SHARKSSL_TLS_1_3 else #endif #endif #if SHARKSSL_TLS_1_3 { return latchgpiochip(&(o->sharkSsl->sessionCache), o, o->session->prot.tls13.ticket, o->session->prot.tls13.ticketLen); } #endif } return 0; } U8 SharkSslCon_resumeSession(SharkSslCon *o, SharkSslSession *s) { baAssert(o); if ((SharkSsl_isClient(o->sharkSsl)) && (o->session == 0) && (s) && (o->state <= pciercxcfg070)) { U32 uart2hwmod = o->sharkSsl->sessionCache.cacheSize; if (uart2hwmod) { SharkSslSession *sv = o->sharkSsl->sessionCache.cache; do { if (s == sv) { baAssert(s->cipherSuite); o->session = s; #if SHARKSSL_ENABLE_SELECT_CIPHERSUITE o->cipherSelCtr = 0; #endif #if SHARKSSL_TLS_1_2 && SHARKSSL_TLS_1_3 o->minor = hardirqsenabled(s); #endif return 1; } uart2hwmod--; sv++; } while (uart2hwmod > 0); baAssert(0); } } return 0; } U32 SharkSslSession_getLatestAccessTime(SharkSslSession *o) { if (o) { #if SHARKSSL_TLS_1_2 #if SHARKSSL_TLS_1_3 if (SharkSslSession_isProtocol(o, SHARKSSL_PROTOCOL_TLS_1_2)) #endif { return (o->prot.tls12.latestAccess); } #endif #if SHARKSSL_TLS_1_3 #if SHARKSSL_TLS_1_2 else #endif { U32 now = (U32)baGetUnixTime(); baAssert(SharkSslSession_isProtocol(o, SHARKSSL_PROTOCOL_TLS_1_3)); if (now < o->prot.tls13.expiration) { return now; } } #endif } return 0; } #endif #endif #ifndef BA_LIB #define BA_LIB #endif #include #if SHARKSSL_USE_ECC #define fpscroffset(o, vect) \ traceaddress(o, sizeof(vect)/sizeof(vect[0]), (void*)vect) #if (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) #define SharkSslECCurve_constructor1_(c, i, gpio1config) do { \ c->bits = i; \ fpscroffset(&c->prime, gpio1config##_prime); \ fpscroffset(&c->order, gpio1config##_order); \ fpscroffset(&c->G.x, gpio1config##_Gx); \ fpscroffset(&c->G.y, gpio1config##_Gy); \ fpscroffset(&c->a, gpio1config##_a); \ } while (0) #else #define SharkSslECCurve_constructor1_(c, i, gpio1config) do { \ c->bits = i; \ fpscroffset(&c->prime, gpio1config##_prime); \ fpscroffset(&c->order, gpio1config##_order); \ fpscroffset(&c->G.x, gpio1config##_Gx); \ fpscroffset(&c->G.y, gpio1config##_Gy); \ } while (0) #endif #if SHARKSSL_ECC_VERIFY_POINT #define SharkSslECCurve_constructor_(c, i, gpio1config) do { \ SharkSslECCurve_constructor1_(c, i, gpio1config); \ fpscroffset(&c->b, gpio1config##_b); \ } while (0) #else #define SharkSslECCurve_constructor_(c, i, gpio1config) \ SharkSslECCurve_constructor1_(c, i, gpio1config); #endif #if SHARKSSL_ECC_USE_NIST static void availableasids(shtype_t *o, shtype_t *mod) { #if SHARKSSL_ECC_USE_SECP521R1 shtype_t checkcontext; #endif #if (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1) shtype_tDoubleWordS d; #endif #if (SHARKSSL_BIGINT_WORDSIZE == 32) baAssert(o->len == (mod->len * 2)); switch (mod->len) { #if SHARKSSL_ECC_USE_SECP256R1 case 8: d = (shtype_tDoubleWordS)o->beg[15] + o->beg[7] + o->beg[6] - o->beg[4] - o->beg[3] - o->beg[2] - o->beg[1]; o->beg[15] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[14] + o->beg[6] + o->beg[5] - o->beg[3] - o->beg[2] - o->beg[1] - o->beg[0]; o->beg[14] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[13] + o->beg[5] + o->beg[4] - o->beg[2] - o->beg[1] - o->beg[0]; o->beg[13] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[12] + o->beg[4] + o->beg[4] + o->beg[3] + o->beg[3] + o->beg[2] - o->beg[0] - o->beg[7] - o->beg[6]; o->beg[12] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[11] + o->beg[3] + o->beg[3] + o->beg[2] + o->beg[2] + o->beg[1] - o->beg[6] - o->beg[5]; o->beg[11] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[10] + o->beg[2] + o->beg[2] + o->beg[1] + o->beg[1] + o->beg[0] - o->beg[5] - o->beg[4]; o->beg[10] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[9] + o->beg[1] + o->beg[1] + o->beg[1] + o->beg[0] + o->beg[0] + o->beg[2] - o->beg[7] - o->beg[6]; o->beg[9] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[8] + o->beg[0] + o->beg[0] + o->beg[0] + o->beg[7] - o->beg[5] - o->beg[4] - o->beg[3] - o->beg[2]; o->beg[8] = (shtype_tWord)d; anatopdisconnect(d); break; #endif #if SHARKSSL_ECC_USE_SECP384R1 case 12: d = (shtype_tDoubleWordS)o->beg[23] + o->beg[11] + o->beg[3] + o->beg[2] - o->beg[0]; o->beg[23] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[22] + o->beg[10] + o->beg[1] + o->beg[0] - o->beg[11] - o->beg[3]; o->beg[22] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[21] + o->beg[9] + o->beg[0] - o->beg[10] - o->beg[2]; o->beg[21] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[20] + o->beg[11] + o->beg[8] + o->beg[3] + o->beg[2] - o->beg[9] - o->beg[1] - o->beg[0]; o->beg[20] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[19] + o->beg[2] + o->beg[2] + o->beg[7] + o->beg[10] + o->beg[11] + o->beg[3] + o->beg[1] - o->beg[8] - o->beg[0] - o->beg[0]; o->beg[19] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[18] + o->beg[1] + o->beg[1] + o->beg[6] + o->beg[9] + o->beg[10] + o->beg[2] + o->beg[0] - o->beg[7]; o->beg[18] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[17] + o->beg[0] + o->beg[0] + o->beg[5] + o->beg[8] + o->beg[9] + o->beg[1] - o->beg[6]; o->beg[17] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[16] + o->beg[4] + o->beg[7] + o->beg[8] + o->beg[0] - o->beg[5]; o->beg[16] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[15] + o->beg[3] + o->beg[6] + o->beg[7] - o->beg[4]; o->beg[15] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[14] + o->beg[2] + o->beg[5] + o->beg[6] - o->beg[3]; o->beg[14] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[13] + o->beg[1] + o->beg[4] + o->beg[5] - o->beg[2]; o->beg[13] = (shtype_tWord)d; anatopdisconnect(d); d += (shtype_tDoubleWordS)o->beg[12] + o->beg[0] + o->beg[3] + o->beg[4] - o->beg[1]; o->beg[12] = (shtype_tWord)d; anatopdisconnect(d); break; #endif #if SHARKSSL_ECC_USE_SECP521R1 case 17: o->len = 17; traceaddress(&checkcontext, 17, &o->beg[17]); memmove(&o->beg[0], &o->beg[1], 17 * SHARKSSL__M); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); checkcontext.beg[0] &= 0x1FF; setupsdhci1(o, &checkcontext, mod); return; #endif default: return; } #elif (SHARKSSL_BIGINT_WORDSIZE == 16) #if (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1) shtype_tWord *r, *s1, *s2, *s3; shtype_tWord *s4; shtype_tWord *s5, *s6; #endif #if SHARKSSL_ECC_USE_SECP521R1 shtype_tWord d0; #endif U16 i = mod->len; #if (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1) d = 0; r = &o->beg[i * 2 - 1]; #endif baAssert(o->len == (i * 2)); switch (i) { #if SHARKSSL_ECC_USE_SECP256R1 case 16: s1 = &o->beg[13]; s2 = NULL; s3 = NULL; s4 = &o->beg[9]; s5 = &o->beg[5]; s6 = &o->beg[3]; while (i--) { d += (shtype_tDoubleWordS)*r; d += *(r - 16); d += *s1--; d -= *s4--; d -= *(s4 - 1); if (s2) { d += *s2; d += *s2--; } if (s3) { d += *s3; d += *s3--; } if (s5) { d -= *s5--; } if (s6) { d -= *s6--; } *r-- = (shtype_tWord)d; anatopdisconnect(d); if (i & 1) { continue; } if ((i == 12) || (i == 8)) { s6 = NULL; } else if (i == 10) { s1 = &o->beg[9]; s2 = &o->beg[7]; s3 = s5 = &o->beg[5]; s4 = &o->beg[15]; s6 = &o->beg[1]; } else if (i == 4) { s1 = &o->beg[5]; s2 = &o->beg[3]; s3 = &o->beg[1]; s4 = &o->beg[15]; s5 = NULL; } else if (i == 2) { s1 = &o->beg[15]; s3 = NULL; s4 = &o->beg[11]; s5 = &o->beg[7]; s6 = &o->beg[5]; } } break; #endif #if SHARKSSL_ECC_USE_SECP384R1 case 24: s1 = &o->beg[7]; s2 = &o->beg[1]; s3 = NULL; s4 = NULL; s5 = NULL; s6 = &o->beg[25]; while (i--) { d += (shtype_tDoubleWordS)*r; d += *(r - 24); d -= *(r - 22); d += *s1--; d += *(s1 - 1); if (s2) { d -= *s2--; } if (s3) { d -= *s3--; } if (s4) { d += *s4--; } if (s5) { d += *s5; d += *s5--; } if (s6) { d += *s6--; } *r-- = (shtype_tWord)d; anatopdisconnect(d); if ((i & 1) || (i <= 6)) { continue; } if (i == 22) { s1 = &o->beg[3]; s2 = &o->beg[7]; s6 = NULL; } else if (i == 20) { s1 = s3 = &o->beg[3]; } else if (i == 18) { s1 = &o->beg[7]; s6 = &o->beg[23]; } else if (i == 16) { s1 = &o->beg[23]; s3 = &o->beg[1]; s4 = &o->beg[7]; s5 = &o->beg[5]; s6 = &o->beg[3]; } else if (i == 14) { s2 = s3 = NULL; } else if (i == 12) { s6 = NULL; } else if (i == 10) { s5 = NULL; } else if (i == 8) { s4 = NULL; } } break; #endif #if SHARKSSL_ECC_USE_SECP521R1 case 33: o->len = 33; traceaddress(&checkcontext, 33, &o->beg[33]); d0 = (o->beg[0] & 0x3) << 7; memmove(&o->beg[0], &o->beg[1], 33 * SHARKSSL__M); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); backlightpdata(o); o->beg[0] |= d0; checkcontext.beg[0] &= 0x1FF; setupsdhci1(o, &checkcontext, mod); return; #endif default: return; } #elif (SHARKSSL_BIGINT_WORDSIZE == 8) #if (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1) shtype_tWord *r, *s1, *s2, *s3; shtype_tWord *s4; shtype_tWord *s5, *s6; #endif U16 i = mod->len; #if (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1) d = 0; r = &o->beg[i * 2 - 1]; #endif baAssert(o->len == (i * 2)); switch (i) { #if SHARKSSL_ECC_USE_SECP256R1 case 32: s1 = &o->beg[27]; s2 = NULL; s3 = NULL; s4 = &o->beg[19]; s5 = &o->beg[11]; s6 = &o->beg[7]; while (i--) { d += (shtype_tDoubleWordS)*r; d += *(r - 32); d += *s1--; d -= *s4--; d -= *(s4 - 3); if (s2) { d += *s2; d += *s2--; } if (s3) { d += *s3; d += *s3--; } if (s5) { d -= *s5--; } if (s6) { d -= *s6--; } *r-- = (shtype_tWord)d; anatopdisconnect(d); if (i & 1) { continue; } if ((i == 24) || (i == 16)) { s6 = NULL; } else if (i == 20) { s1 = &o->beg[19]; s2 = &o->beg[15]; s3 = s5 = &o->beg[11]; s4 = &o->beg[31]; s6 = &o->beg[3]; } else if (i == 8) { s1 = &o->beg[11]; s2 = &o->beg[7]; s3 = &o->beg[3]; s4 = &o->beg[31]; s5 = NULL; } else if (i == 4) { s1 = &o->beg[31]; s3 = NULL; s4 = &o->beg[23]; s5 = &o->beg[15]; s6 = &o->beg[11]; } } break; #endif #if SHARKSSL_ECC_USE_SECP384R1 case 48: s1 = &o->beg[15]; s2 = &o->beg[3]; s3 = NULL; s4 = NULL; s5 = NULL; s6 = &o->beg[51]; while (i--) { d += (shtype_tDoubleWordS)*r; d += *(r - 48); d -= *(r - 44); d += *s1--; d += *(s1 - 3); if (s2) { d -= *s2--; } if (s3) { d -= *s3--; } if (s4) { d += *s4--; } if (s5) { d += *s5; d += *s5--; } if (s6) { d += *s6--; } *r-- = (shtype_tWord)d; anatopdisconnect(d); if ((i & 1) || (i <= 14)) { continue; } if (i == 44) { s1 = &o->beg[7]; s2 = &o->beg[15]; s6 = NULL; } else if (i == 40) { s1 = s3 = &o->beg[7]; } else if (i == 36) { s1 = &o->beg[15]; s6 = &o->beg[47]; } else if (i == 32) { s1 = &o->beg[47]; s3 = &o->beg[3]; s4 = &o->beg[15]; s5 = &o->beg[11]; s6 = &o->beg[7]; } else if (i == 28) { s2 = s3 = NULL; } else if (i == 24) { s6 = NULL; } else if (i == 20) { s5 = NULL; } else if (i == 16) { s4 = NULL; } } break; #endif #if SHARKSSL_ECC_USE_SECP521R1 case 66: o->len = 66; traceaddress(&checkcontext, 66, &o->beg[66]); memmove(&o->beg[0], &o->beg[1], 66 * SHARKSSL__M); backlightpdata(o); checkcontext.beg[0] &= 0x1; setupsdhci1(o, &checkcontext, mod); return; #endif default: return; } #else #error unsupported SHARKSSL_BIGINT_WORDSIZE #endif #if (SHARKSSL_ECC_USE_SECP256R1 || SHARKSSL_ECC_USE_SECP384R1) o->len >>= 1; o->beg += o->len; while (d != 0) { if (d < 0) { d += (shtype_tWordS)resolverelocs(o, mod); } else { d += (shtype_tWordS)updatepmull(o, mod); } } if (timerwrite(o, mod)) { updatepmull(o, mod); } #endif } #endif void clearerrors(SharkSslECCurve *o, U16 rightsvalid) { #if SHARKSSL_ECC_USE_SECP256R1 static const shtype_tWord SECP256R1_prime[] = {HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(00,00,00,01), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF)}; static const shtype_tWord SECP256R1_order[] = {HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(BC,E6,FA,AD), HEX4_TO_WORDSIZE(A7,17,9E,84), HEX4_TO_WORDSIZE(F3,B9,CA,C2), HEX4_TO_WORDSIZE(FC,63,25,51)}; static const shtype_tWord SECP256R1_Gx[] = {HEX4_TO_WORDSIZE(6B,17,D1,F2), HEX4_TO_WORDSIZE(E1,2C,42,47), HEX4_TO_WORDSIZE(F8,BC,E6,E5), HEX4_TO_WORDSIZE(63,A4,40,F2), HEX4_TO_WORDSIZE(77,03,7D,81), HEX4_TO_WORDSIZE(2D,EB,33,A0), HEX4_TO_WORDSIZE(F4,A1,39,45), HEX4_TO_WORDSIZE(D8,98,C2,96)}; static const shtype_tWord SECP256R1_Gy[] = {HEX4_TO_WORDSIZE(4F,E3,42,E2), HEX4_TO_WORDSIZE(FE,1A,7F,9B), HEX4_TO_WORDSIZE(8E,E7,EB,4A), HEX4_TO_WORDSIZE(7C,0F,9E,16), HEX4_TO_WORDSIZE(2B,CE,33,57), HEX4_TO_WORDSIZE(6B,31,5E,CE), HEX4_TO_WORDSIZE(CB,B6,40,68), HEX4_TO_WORDSIZE(37,BF,51,F5)}; #if (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) static const shtype_tWord SECP256R1_a[] = {(shtype_tWord)-3}; #endif #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord SECP256R1_b[] = {HEX4_TO_WORDSIZE(5A,C6,35,D8), HEX4_TO_WORDSIZE(AA,3A,93,E7), HEX4_TO_WORDSIZE(B3,EB,BD,55), HEX4_TO_WORDSIZE(76,98,86,BC), HEX4_TO_WORDSIZE(65,1D,06,B0), HEX4_TO_WORDSIZE(CC,53,B0,F6), HEX4_TO_WORDSIZE(3B,CE,3C,3E), HEX4_TO_WORDSIZE(27,D2,60,4B)}; #endif #endif #if SHARKSSL_ECC_USE_SECP384R1 static const shtype_tWord SECP384R1_prime[] = {HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FE), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(FF,FF,FF,FF)}; static const shtype_tWord SECP384R1_order[] = {HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(C7,63,4D,81), HEX4_TO_WORDSIZE(F4,37,2D,DF), HEX4_TO_WORDSIZE(58,1A,0D,B2), HEX4_TO_WORDSIZE(48,B0,A7,7A), HEX4_TO_WORDSIZE(EC,EC,19,6A), HEX4_TO_WORDSIZE(CC,C5,29,73)}; static const shtype_tWord SECP384R1_Gx[] = {HEX4_TO_WORDSIZE(AA,87,CA,22), HEX4_TO_WORDSIZE(BE,8B,05,37), HEX4_TO_WORDSIZE(8E,B1,C7,1E), HEX4_TO_WORDSIZE(F3,20,AD,74), HEX4_TO_WORDSIZE(6E,1D,3B,62), HEX4_TO_WORDSIZE(8B,A7,9B,98), HEX4_TO_WORDSIZE(59,F7,41,E0), HEX4_TO_WORDSIZE(82,54,2A,38), HEX4_TO_WORDSIZE(55,02,F2,5D), HEX4_TO_WORDSIZE(BF,55,29,6C), HEX4_TO_WORDSIZE(3A,54,5E,38), HEX4_TO_WORDSIZE(72,76,0A,B7)}; static const shtype_tWord SECP384R1_Gy[] = {HEX4_TO_WORDSIZE(36,17,DE,4A), HEX4_TO_WORDSIZE(96,26,2C,6F), HEX4_TO_WORDSIZE(5D,9E,98,BF), HEX4_TO_WORDSIZE(92,92,DC,29), HEX4_TO_WORDSIZE(F8,F4,1D,BD), HEX4_TO_WORDSIZE(28,9A,14,7C), HEX4_TO_WORDSIZE(E9,DA,31,13), HEX4_TO_WORDSIZE(B5,F0,B8,C0), HEX4_TO_WORDSIZE(0A,60,B1,CE), HEX4_TO_WORDSIZE(1D,7E,81,9D), HEX4_TO_WORDSIZE(7A,43,1D,7C), HEX4_TO_WORDSIZE(90,EA,0E,5F)}; #if (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) static const shtype_tWord SECP384R1_a[] = {(shtype_tWord)-3}; #endif #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord SECP384R1_b[] = {HEX4_TO_WORDSIZE(B3,31,2F,A7), HEX4_TO_WORDSIZE(E2,3E,E7,E4), HEX4_TO_WORDSIZE(98,8E,05,6B), HEX4_TO_WORDSIZE(E3,F8,2D,19), HEX4_TO_WORDSIZE(18,1D,9C,6E), HEX4_TO_WORDSIZE(FE,81,41,12), HEX4_TO_WORDSIZE(03,14,08,8F), HEX4_TO_WORDSIZE(50,13,87,5A), HEX4_TO_WORDSIZE(C6,56,39,8D), HEX4_TO_WORDSIZE(8A,2E,D1,9D), HEX4_TO_WORDSIZE(2A,85,C8,ED), HEX4_TO_WORDSIZE(D3,EC,2A,EF)}; #endif #endif #if SHARKSSL_ECC_USE_SECP521R1 static const shtype_tWord SECP521R1_prime[] = {HEX2_TO_WORDSIZE(01,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF)}; static const shtype_tWord SECP521R1_order[] = {HEX2_TO_WORDSIZE(01,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FA), HEX4_TO_WORDSIZE(51,86,87,83), HEX4_TO_WORDSIZE(BF,2F,96,6B), HEX4_TO_WORDSIZE(7F,CC,01,48), HEX4_TO_WORDSIZE(F7,09,A5,D0), HEX4_TO_WORDSIZE(3B,B5,C9,B8), HEX4_TO_WORDSIZE(89,9C,47,AE), HEX4_TO_WORDSIZE(BB,6F,B7,1E), HEX4_TO_WORDSIZE(91,38,64,09)}; static const shtype_tWord SECP521R1_Gx[] = {HEX2_TO_WORDSIZE(00,C6), HEX4_TO_WORDSIZE(85,8E,06,B7), HEX4_TO_WORDSIZE(04,04,E9,CD), HEX4_TO_WORDSIZE(9E,3E,CB,66), HEX4_TO_WORDSIZE(23,95,B4,42), HEX4_TO_WORDSIZE(9C,64,81,39), HEX4_TO_WORDSIZE(05,3F,B5,21), HEX4_TO_WORDSIZE(F8,28,AF,60), HEX4_TO_WORDSIZE(6B,4D,3D,BA), HEX4_TO_WORDSIZE(A1,4B,5E,77), HEX4_TO_WORDSIZE(EF,E7,59,28), HEX4_TO_WORDSIZE(FE,1D,C1,27), HEX4_TO_WORDSIZE(A2,FF,A8,DE), HEX4_TO_WORDSIZE(33,48,B3,C1), HEX4_TO_WORDSIZE(85,6A,42,9B), HEX4_TO_WORDSIZE(F9,7E,7E,31), HEX4_TO_WORDSIZE(C2,E5,BD,66)}; static const shtype_tWord SECP521R1_Gy[] = {HEX2_TO_WORDSIZE(01,18), HEX4_TO_WORDSIZE(39,29,6A,78), HEX4_TO_WORDSIZE(9A,3B,C0,04), HEX4_TO_WORDSIZE(5C,8A,5F,B4), HEX4_TO_WORDSIZE(2C,7D,1B,D9), HEX4_TO_WORDSIZE(98,F5,44,49), HEX4_TO_WORDSIZE(57,9B,44,68), HEX4_TO_WORDSIZE(17,AF,BD,17), HEX4_TO_WORDSIZE(27,3E,66,2C), HEX4_TO_WORDSIZE(97,EE,72,99), HEX4_TO_WORDSIZE(5E,F4,26,40), HEX4_TO_WORDSIZE(C5,50,B9,01), HEX4_TO_WORDSIZE(3F,AD,07,61), HEX4_TO_WORDSIZE(35,3C,70,86), HEX4_TO_WORDSIZE(A2,72,C2,40), HEX4_TO_WORDSIZE(88,BE,94,76), HEX4_TO_WORDSIZE(9F,D1,66,50)}; #if (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) static const shtype_tWord SECP521R1_a[] = {(shtype_tWord)-3}; #endif #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord SECP521R1_b[] = {HEX2_TO_WORDSIZE(00,51), HEX4_TO_WORDSIZE(95,3E,B9,61), HEX4_TO_WORDSIZE(8E,1C,9A,1F), HEX4_TO_WORDSIZE(92,9A,21,A0), HEX4_TO_WORDSIZE(B6,85,40,EE), HEX4_TO_WORDSIZE(A2,DA,72,5B), HEX4_TO_WORDSIZE(99,B3,15,F3), HEX4_TO_WORDSIZE(B8,B4,89,91), HEX4_TO_WORDSIZE(8E,F1,09,E1), HEX4_TO_WORDSIZE(56,19,39,51), HEX4_TO_WORDSIZE(EC,7E,93,7B), HEX4_TO_WORDSIZE(16,52,C0,BD), HEX4_TO_WORDSIZE(3B,B1,BF,07), HEX4_TO_WORDSIZE(35,73,DF,88), HEX4_TO_WORDSIZE(3D,2C,34,F1), HEX4_TO_WORDSIZE(EF,45,1F,D4), HEX4_TO_WORDSIZE(6B,50,3F,00)}; #endif #endif #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 static const shtype_tWord brainpoolP256R1_prime[] = {HEX4_TO_WORDSIZE(A9,FB,57,DB), HEX4_TO_WORDSIZE(A1,EE,A9,BC), HEX4_TO_WORDSIZE(3E,66,0A,90), HEX4_TO_WORDSIZE(9D,83,8D,72), HEX4_TO_WORDSIZE(6E,3B,F6,23), HEX4_TO_WORDSIZE(D5,26,20,28), HEX4_TO_WORDSIZE(20,13,48,1D), HEX4_TO_WORDSIZE(1F,6E,53,77)}; static const shtype_tWord brainpoolP256R1_order[] = {HEX4_TO_WORDSIZE(A9,FB,57,DB), HEX4_TO_WORDSIZE(A1,EE,A9,BC), HEX4_TO_WORDSIZE(3E,66,0A,90), HEX4_TO_WORDSIZE(9D,83,8D,71), HEX4_TO_WORDSIZE(8C,39,7A,A3), HEX4_TO_WORDSIZE(B5,61,A6,F7), HEX4_TO_WORDSIZE(90,1E,0E,82), HEX4_TO_WORDSIZE(97,48,56,A7)}; static const shtype_tWord brainpoolP256R1_Gx[] = {HEX4_TO_WORDSIZE(8E,1F,76,7A), HEX4_TO_WORDSIZE(9E,11,9B,DF), HEX4_TO_WORDSIZE(70,4C,31,1D), HEX4_TO_WORDSIZE(6B,89,2A,D3), HEX4_TO_WORDSIZE(80,DE,4D,9A), HEX4_TO_WORDSIZE(B9,7C,F3,0A), HEX4_TO_WORDSIZE(27,C0,D9,2D), HEX4_TO_WORDSIZE(35,1F,D1,0C)}; static const shtype_tWord brainpoolP256R1_Gy[] = {HEX4_TO_WORDSIZE(14,EB,78,C6), HEX4_TO_WORDSIZE(02,6E,B0,A2), HEX4_TO_WORDSIZE(16,FD,F6,E8), HEX4_TO_WORDSIZE(DF,BD,8B,03), HEX4_TO_WORDSIZE(A6,18,F2,59), HEX4_TO_WORDSIZE(CD,95,01,62), HEX4_TO_WORDSIZE(9A,4F,E9,48), HEX4_TO_WORDSIZE(A0,91,7A,17)}; static const shtype_tWord brainpoolP256R1_a[] = {HEX4_TO_WORDSIZE(1E,46,76,AB), HEX4_TO_WORDSIZE(D6,66,BC,17), HEX4_TO_WORDSIZE(95,EC,1E,5E), HEX4_TO_WORDSIZE(63,98,55,6E), HEX4_TO_WORDSIZE(A6,81,23,F1), HEX4_TO_WORDSIZE(C1,D2,0C,64), HEX4_TO_WORDSIZE(D5,D1,8E,DF), HEX4_TO_WORDSIZE(69,69,62,61)}; #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord brainpoolP256R1_b[] = {HEX4_TO_WORDSIZE(26,DC,5C,6C), HEX4_TO_WORDSIZE(E9,4A,4B,44), HEX4_TO_WORDSIZE(F3,30,B5,D9), HEX4_TO_WORDSIZE(BB,D7,7C,BF), HEX4_TO_WORDSIZE(95,84,16,29), HEX4_TO_WORDSIZE(5C,F7,E1,CE), HEX4_TO_WORDSIZE(6B,CC,DC,18), HEX4_TO_WORDSIZE(FF,8C,07,B6)}; #endif #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 static const shtype_tWord brainpoolP384R1_prime[] = {HEX4_TO_WORDSIZE(8C,B9,1E,82), HEX4_TO_WORDSIZE(A3,38,6D,28), HEX4_TO_WORDSIZE(0F,5D,6F,7E), HEX4_TO_WORDSIZE(50,E6,41,DF), HEX4_TO_WORDSIZE(15,2F,71,09), HEX4_TO_WORDSIZE(ED,54,56,B4), HEX4_TO_WORDSIZE(12,B1,DA,19), HEX4_TO_WORDSIZE(7F,B7,11,23), HEX4_TO_WORDSIZE(AC,D3,A7,29), HEX4_TO_WORDSIZE(90,1D,1A,71), HEX4_TO_WORDSIZE(87,47,00,13), HEX4_TO_WORDSIZE(31,07,EC,53)}; static const shtype_tWord brainpoolP384R1_order[] = {HEX4_TO_WORDSIZE(8C,B9,1E,82), HEX4_TO_WORDSIZE(A3,38,6D,28), HEX4_TO_WORDSIZE(0F,5D,6F,7E), HEX4_TO_WORDSIZE(50,E6,41,DF), HEX4_TO_WORDSIZE(15,2F,71,09), HEX4_TO_WORDSIZE(ED,54,56,B3), HEX4_TO_WORDSIZE(1F,16,6E,6C), HEX4_TO_WORDSIZE(AC,04,25,A7), HEX4_TO_WORDSIZE(CF,3A,B6,AF), HEX4_TO_WORDSIZE(6B,7F,C3,10), HEX4_TO_WORDSIZE(3B,88,32,02), HEX4_TO_WORDSIZE(E9,04,65,65)}; static const shtype_tWord brainpoolP384R1_Gx[] = {HEX4_TO_WORDSIZE(85,00,75,33), HEX4_TO_WORDSIZE(88,F5,3F,C1), HEX4_TO_WORDSIZE(9C,DD,0D,CF), HEX4_TO_WORDSIZE(BA,CD,00,99), HEX4_TO_WORDSIZE(06,8B,26,4E), HEX4_TO_WORDSIZE(F9,5C,21,64), HEX4_TO_WORDSIZE(94,C3,78,E9), HEX4_TO_WORDSIZE(9D,20,2F,23), HEX4_TO_WORDSIZE(66,FC,80,E8), HEX4_TO_WORDSIZE(D5,A8,86,BF), HEX4_TO_WORDSIZE(A1,89,DE,EB), HEX4_TO_WORDSIZE(D4,38,FB,C1)}; static const shtype_tWord brainpoolP384R1_Gy[] = {HEX4_TO_WORDSIZE(2C,F4,A0,62), HEX4_TO_WORDSIZE(45,89,68,B5), HEX4_TO_WORDSIZE(C6,16,25,66), HEX4_TO_WORDSIZE(4F,21,DD,B6), HEX4_TO_WORDSIZE(A1,80,AC,D4), HEX4_TO_WORDSIZE(D5,71,92,17), HEX4_TO_WORDSIZE(F8,83,09,A3), HEX4_TO_WORDSIZE(8F,07,37,FC), HEX4_TO_WORDSIZE(F5,E0,D2,46), HEX4_TO_WORDSIZE(C7,99,6F,55), HEX4_TO_WORDSIZE(E7,38,B3,31), HEX4_TO_WORDSIZE(0D,E1,40,A5)}; static const shtype_tWord brainpoolP384R1_a[] = {HEX4_TO_WORDSIZE(7C,33,80,21), HEX4_TO_WORDSIZE(A2,E8,C0,D1), HEX4_TO_WORDSIZE(40,0A,8F,DF), HEX4_TO_WORDSIZE(42,B0,0C,60), HEX4_TO_WORDSIZE(E7,FF,E9,E5), HEX4_TO_WORDSIZE(35,52,93,74), HEX4_TO_WORDSIZE(93,67,71,B9), HEX4_TO_WORDSIZE(D7,F1,0D,B4), HEX4_TO_WORDSIZE(75,D7,F3,FE), HEX4_TO_WORDSIZE(F1,57,B0,7B), HEX4_TO_WORDSIZE(DB,26,B8,95), HEX4_TO_WORDSIZE(46,6C,3C,99)}; #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord brainpoolP384R1_b[] = {HEX4_TO_WORDSIZE(04,A8,C7,DD), HEX4_TO_WORDSIZE(22,CE,28,26), HEX4_TO_WORDSIZE(8B,39,B5,54), HEX4_TO_WORDSIZE(16,F0,44,7C), HEX4_TO_WORDSIZE(2F,B7,7D,E1), HEX4_TO_WORDSIZE(07,DC,D2,A6), HEX4_TO_WORDSIZE(2E,88,0E,A5), HEX4_TO_WORDSIZE(3E,EB,62,D5), HEX4_TO_WORDSIZE(7C,B4,39,02), HEX4_TO_WORDSIZE(95,DB,C9,94), HEX4_TO_WORDSIZE(3A,B7,86,96), HEX4_TO_WORDSIZE(FA,50,4C,11)}; #endif #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 static const shtype_tWord brainpoolP512R1_prime[] = {HEX4_TO_WORDSIZE(AA,DD,9D,B8), HEX4_TO_WORDSIZE(DB,E9,C4,8B), HEX4_TO_WORDSIZE(3F,D4,E6,AE), HEX4_TO_WORDSIZE(33,C9,FC,07), HEX4_TO_WORDSIZE(CB,30,8D,B3), HEX4_TO_WORDSIZE(B3,C9,D2,0E), HEX4_TO_WORDSIZE(D6,63,9C,CA), HEX4_TO_WORDSIZE(70,33,08,71), HEX4_TO_WORDSIZE(7D,4D,9B,00), HEX4_TO_WORDSIZE(9B,C6,68,42), HEX4_TO_WORDSIZE(AE,CD,A1,2A), HEX4_TO_WORDSIZE(E6,A3,80,E6), HEX4_TO_WORDSIZE(28,81,FF,2F), HEX4_TO_WORDSIZE(2D,82,C6,85), HEX4_TO_WORDSIZE(28,AA,60,56), HEX4_TO_WORDSIZE(58,3A,48,F3)}; static const shtype_tWord brainpoolP512R1_order[] = {HEX4_TO_WORDSIZE(AA,DD,9D,B8), HEX4_TO_WORDSIZE(DB,E9,C4,8B), HEX4_TO_WORDSIZE(3F,D4,E6,AE), HEX4_TO_WORDSIZE(33,C9,FC,07), HEX4_TO_WORDSIZE(CB,30,8D,B3), HEX4_TO_WORDSIZE(B3,C9,D2,0E), HEX4_TO_WORDSIZE(D6,63,9C,CA), HEX4_TO_WORDSIZE(70,33,08,70), HEX4_TO_WORDSIZE(55,3E,5C,41), HEX4_TO_WORDSIZE(4C,A9,26,19), HEX4_TO_WORDSIZE(41,86,61,19), HEX4_TO_WORDSIZE(7F,AC,10,47), HEX4_TO_WORDSIZE(1D,B1,D3,81), HEX4_TO_WORDSIZE(08,5D,DA,DD), HEX4_TO_WORDSIZE(B5,87,96,82), HEX4_TO_WORDSIZE(9C,A9,00,69)}; static const shtype_tWord brainpoolP512R1_Gx[] = {HEX4_TO_WORDSIZE(5A,2B,A1,4C), HEX4_TO_WORDSIZE(09,94,E9,81), HEX4_TO_WORDSIZE(87,1C,B5,CA), HEX4_TO_WORDSIZE(00,6D,45,73), HEX4_TO_WORDSIZE(B2,B6,EA,37), HEX4_TO_WORDSIZE(F3,6D,3C,F7), HEX4_TO_WORDSIZE(24,33,D7,6F), HEX4_TO_WORDSIZE(90,5C,87,37), HEX4_TO_WORDSIZE(85,50,53,95), HEX4_TO_WORDSIZE(14,C0,1F,C8), HEX4_TO_WORDSIZE(34,AB,04,14), HEX4_TO_WORDSIZE(6D,F5,5E,8F), HEX4_TO_WORDSIZE(68,3E,4D,64), HEX4_TO_WORDSIZE(27,2C,02,A4), HEX4_TO_WORDSIZE(C4,CE,96,09), HEX4_TO_WORDSIZE(51,61,D9,D3)}; static const shtype_tWord brainpoolP512R1_Gy[] = {HEX4_TO_WORDSIZE(8C,50,C9,D1), HEX4_TO_WORDSIZE(2A,CB,72,81), HEX4_TO_WORDSIZE(9A,5E,D7,DA), HEX4_TO_WORDSIZE(87,0F,3F,9B), HEX4_TO_WORDSIZE(58,5D,2B,77), HEX4_TO_WORDSIZE(CD,9D,3F,8C), HEX4_TO_WORDSIZE(7C,17,0B,88), HEX4_TO_WORDSIZE(8F,E6,2F,DC), HEX4_TO_WORDSIZE(36,0E,C7,75), HEX4_TO_WORDSIZE(59,8E,CC,3E), HEX4_TO_WORDSIZE(BF,84,55,53), HEX4_TO_WORDSIZE(4C,85,94,90), HEX4_TO_WORDSIZE(75,18,DF,6F), HEX4_TO_WORDSIZE(47,42,F3,25), HEX4_TO_WORDSIZE(2F,90,66,29), HEX4_TO_WORDSIZE(25,04,2A,6D)}; static const shtype_tWord brainpoolP512R1_a[] = {HEX4_TO_WORDSIZE(5E,C4,F1,87), HEX4_TO_WORDSIZE(22,7D,2A,83), HEX4_TO_WORDSIZE(B8,3B,84,FA), HEX4_TO_WORDSIZE(E2,D0,85,0C), HEX4_TO_WORDSIZE(18,2D,0F,59), HEX4_TO_WORDSIZE(F4,1E,87,78), HEX4_TO_WORDSIZE(A5,EC,30,C8), HEX4_TO_WORDSIZE(3F,80,D1,C7), HEX4_TO_WORDSIZE(CF,8F,01,11), HEX4_TO_WORDSIZE(9E,6E,87,FF), HEX4_TO_WORDSIZE(40,B0,4B,72), HEX4_TO_WORDSIZE(46,75,BB,AB), HEX4_TO_WORDSIZE(14,E4,95,7D), HEX4_TO_WORDSIZE(AF,A7,D2,83), HEX4_TO_WORDSIZE(DA,1F,8A,34), HEX4_TO_WORDSIZE(EA,10,C4,46)}; #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord brainpoolP512R1_b[] = {HEX4_TO_WORDSIZE(3D,F9,16,10), HEX4_TO_WORDSIZE(A8,34,41,CA), HEX4_TO_WORDSIZE(EA,98,63,BC), HEX4_TO_WORDSIZE(2D,ED,5D,5A), HEX4_TO_WORDSIZE(A8,25,3A,A1), HEX4_TO_WORDSIZE(0A,2E,F1,C9), HEX4_TO_WORDSIZE(8B,9A,C8,B5), HEX4_TO_WORDSIZE(7F,11,17,A7), HEX4_TO_WORDSIZE(2B,F2,C7,B9), HEX4_TO_WORDSIZE(E7,C1,AC,4D), HEX4_TO_WORDSIZE(77,FC,94,CA), HEX4_TO_WORDSIZE(DC,08,3E,67), HEX4_TO_WORDSIZE(98,40,50,B7), HEX4_TO_WORDSIZE(5E,BA,E5,DD), HEX4_TO_WORDSIZE(28,09,BD,63), HEX4_TO_WORDSIZE(80,16,F7,23)}; #endif #endif #if SHARKSSL_ECC_USE_CURVE25519 static const shtype_tWord curve25519_prime[] = {HEX4_TO_WORDSIZE(7F,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,ED)}; static const shtype_tWord curve25519_order[] = {HEX4_TO_WORDSIZE(10,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(14,DE,F9,DE), HEX4_TO_WORDSIZE(A2,F7,9C,D6), HEX4_TO_WORDSIZE(58,12,63,1A), HEX4_TO_WORDSIZE(5C,F5,D3,ED)}; static const shtype_tWord curve25519_Gx[] = {HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,09)}; static const shtype_tWord curve25519_Gy[] = {HEX4_TO_WORDSIZE(20,AE,19,A1), HEX4_TO_WORDSIZE(B8,A0,86,B4), HEX4_TO_WORDSIZE(E0,1E,DD,2C), HEX4_TO_WORDSIZE(77,48,D1,4C), HEX4_TO_WORDSIZE(92,3D,4D,7E), HEX4_TO_WORDSIZE(6D,7C,61,B2), HEX4_TO_WORDSIZE(29,E9,C5,A2), HEX4_TO_WORDSIZE(7E,CE,D3,D9)}; static const shtype_tWord curve25519_a[] = {HEX4_TO_WORDSIZE(00,46,8B,A6)}; #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord curve25519_b[] = {(shtype_tWord)0}; #endif #endif #if SHARKSSL_ECC_USE_CURVE448 static const shtype_tWord curve448_prime[] = {HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FE), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF)}; static const shtype_tWord curve448_order[] = {HEX4_TO_WORDSIZE(3F,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(FF,FF,FF,FF), HEX4_TO_WORDSIZE(7C,CA,23,E9), HEX4_TO_WORDSIZE(C4,4E,DB,49), HEX4_TO_WORDSIZE(AE,D6,36,90), HEX4_TO_WORDSIZE(21,6C,C2,72), HEX4_TO_WORDSIZE(8D,C5,8F,55), HEX4_TO_WORDSIZE(23,78,C2,92), HEX4_TO_WORDSIZE(AB,58,44,F3)}; static const shtype_tWord curve448_Gx[] = {HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,05)}; static const shtype_tWord curve448_Gy[] = {HEX4_TO_WORDSIZE(7D,23,5D,12), HEX4_TO_WORDSIZE(95,F5,B1,F6), HEX4_TO_WORDSIZE(6C,98,AB,6E), HEX4_TO_WORDSIZE(58,32,6F,CE), HEX4_TO_WORDSIZE(CB,AE,5D,34), HEX4_TO_WORDSIZE(F5,55,45,D0), HEX4_TO_WORDSIZE(60,F7,5D,C2), HEX4_TO_WORDSIZE(8D,F3,F6,ED), HEX4_TO_WORDSIZE(B8,02,7E,23), HEX4_TO_WORDSIZE(46,43,0D,21), HEX4_TO_WORDSIZE(13,12,C4,B1), HEX4_TO_WORDSIZE(50,67,7A,F7), HEX4_TO_WORDSIZE(6F,D7,22,3D), HEX4_TO_WORDSIZE(45,7B,5B,1A)}; static const shtype_tWord curve448_a[] = {HEX4_TO_WORDSIZE(00,00,98,A9), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,00,00), HEX4_TO_WORDSIZE(00,00,98,A9)}; #if SHARKSSL_ECC_VERIFY_POINT static const shtype_tWord curve448_b[] = {(shtype_tWord)0}; #endif #endif baAssert(o); baAssert((rightsvalid >= SHARKSSL_EC_CURVE_ID_SECP256R1) || (rightsvalid <= SHARKSSL_EC_CURVE_ID_CURVE448)); #if SHARKSSL_ECC_USE_EDWARDS if (rightsvalid < SHARKSSL_EC_CURVE_ID_CURVE25519) { o->setPoint = SharkSslECCurve_setPoint_NB; o->multiply = SharkSslECCurve_multiply_NB; } else { o->setPoint = SharkSslECCurve_setPoint_ED; o->multiply = SharkSslECCurve_multiply_ED; } #endif switch (rightsvalid) { #if SHARKSSL_ECC_USE_SECP256R1 case SHARKSSL_EC_CURVE_ID_SECP256R1: SharkSslECCurve_constructor_(o, 256, SECP256R1); break; #endif #if SHARKSSL_ECC_USE_SECP384R1 case SHARKSSL_EC_CURVE_ID_SECP384R1: SharkSslECCurve_constructor_(o, 384, SECP384R1); break; #endif #if SHARKSSL_ECC_USE_SECP521R1 case SHARKSSL_EC_CURVE_ID_SECP521R1: SharkSslECCurve_constructor_(o, 521, SECP521R1); break; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP256R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP256R1: SharkSslECCurve_constructor_(o, 256, brainpoolP256R1); break; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP384R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP384R1: SharkSslECCurve_constructor_(o, 384, brainpoolP384R1); break; #endif #if SHARKSSL_ECC_USE_BRAINPOOLP512R1 case SHARKSSL_EC_CURVE_ID_BRAINPOOLP512R1: SharkSslECCurve_constructor_(o, 512, brainpoolP512R1); break; #endif #if SHARKSSL_ECC_USE_CURVE25519 case SHARKSSL_EC_CURVE_ID_CURVE25519: SharkSslECCurve_constructor_(o, 256, curve25519); break; #endif #if SHARKSSL_ECC_USE_CURVE448 case SHARKSSL_EC_CURVE_ID_CURVE448: SharkSslECCurve_constructor_(o, 448, curve448); break; #endif default: memset(o, 0, sizeof(SharkSslECCurve)); } return; } typedef void (*func_mulmod)(const shtype_t*, const shtype_t*, shtype_t*, shtype_t*, shtype_tWord*); typedef void (*func_fmulmod)(const shtype_t*, const shtype_t*, shtype_t*, shtype_t*, shtype_tWord); typedef struct { shtype_t A, B, C, D, E, F; #if SHARKSSL_ECC_USE_EDWARDS shtype_t G; #endif #if (SHARKSSL_ECC_USE_NIST && (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS)) func_mulmod mulmod; func_fmulmod fmulmod; #endif #if (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) shtype_t *factor_a; shtype_tWord mu; #endif } SharkSslEC_temp; #if (SHARKSSL_ECC_USE_NIST && (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS)) #define probehandler(x,y,z) brightnesslimit->fmulmod(x, y, z, mod, brightnesslimit->mu); #define traceguest(x,y,z) brightnesslimit->mulmod(x, y, z, mod, &brightnesslimit->D.mem[0]); #define temp_fmulmod brightnesslimit.fmulmod #define temp_mulmod brightnesslimit.mulmod static void registernotifier(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices, shtype_t *cpuidfeature, shtype_tWord *afterhandler) { hotplugpgtable(o1, o2, deltadevices); envdatamcheck(deltadevices, cpuidfeature, afterhandler); } static void branchlikely(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices, shtype_t *cpuidfeature, shtype_tWord mu) { writebytes(o1, o2, deltadevices, cpuidfeature, mu); } static void helpersetup(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices, shtype_t *cpuidfeature, shtype_tWord *afterhandler) { (void)afterhandler; hotplugpgtable(o1, o2, deltadevices); availableasids(deltadevices, cpuidfeature); } static void softlockupwatchdog(const shtype_t *o1, const shtype_t *o2, shtype_t *deltadevices, shtype_t *cpuidfeature, shtype_tWord mu) { helpersetup(o1, o2, deltadevices, cpuidfeature, &mu); } #elif SHARKSSL_ECC_USE_NIST #define probehandler(x,y,z) hotplugpgtable(x, y, z); availableasids(z, mod) #define traceguest(x,y,z) hotplugpgtable(x, y, z); availableasids(z, mod) #elif (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) #define probehandler(x,y,z) writebytes(x, y, z, mod, brightnesslimit->mu) #define traceguest(x,y,z) hotplugpgtable(x, y, z); envdatamcheck(z, mod, &brightnesslimit->D.mem[0]) #define temp_fmulmod(x,y,z,mod,mu) writebytes(x, y, z, mod, mu) #define temp_mulmod(x,y,z,mod,afterhandler) hotplugpgtable(x, y, z); envdatamcheck(z, mod, afterhandler) #else #endif #if (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS) void SharkSslEC_temp_setmulmod(SharkSslEC_temp *brightnesslimit, SharkSslECCurve *o) { if (((shtype_tWord)-3) == o->a.beg[0]) { #if (SHARKSSL_ECC_USE_NIST && (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS)) brightnesslimit->mulmod = helpersetup; brightnesslimit->fmulmod = softlockupwatchdog; #endif brightnesslimit->factor_a = NULL; brightnesslimit->mu = 0; } else { #if (SHARKSSL_ECC_USE_NIST && (SHARKSSL_ECC_USE_BRAINPOOL || SHARKSSL_ECC_USE_EDWARDS)) brightnesslimit->mulmod = registernotifier; brightnesslimit->fmulmod = branchlikely; #endif brightnesslimit->factor_a = &(o->a); brightnesslimit->mu = remapcfgspace(&o->prime); } return; } #else #define SharkSslEC_temp_setmulmod(t,o) #endif int SharkSslECCurve_setPoint_NB(SharkSslECCurve *o, SharkSslECPoint *p) { if ((void*)p != (void*)NULL) { if ((p->x.len <= o->G.x.len) && (p->y.len <= o->G.y.len)) { #if SHARKSSL_ECC_VERIFY_POINT SharkSslEC_temp doublefnmul, *brightnesslimit; shtype_t *mod; shtype_tWord *tmp_b, *tmp_buf; U16 i; mod = &o->prime; brightnesslimit = &doublefnmul; if ((timerwrite(&p->x, mod)) || (timerwrite(&p->y, mod))) { return 2; } i = (o->prime.len << 1) + 1; tmp_b = (shtype_tWord*)baMalloc(pcmciapdata(i * SHARKSSL__M * 6)); if (tmp_b == NULL) { return 3; } tmp_buf = (shtype_tWord*)selectaudio(tmp_b); traceaddress(&doublefnmul.A, i, tmp_buf); tmp_buf += i; traceaddress(&doublefnmul.B, i, tmp_buf); tmp_buf += i; traceaddress(&doublefnmul.C, i, tmp_buf); tmp_buf += i; traceaddress(&doublefnmul.D, i, tmp_buf); tmp_buf += i; traceaddress(&doublefnmul.E, i, tmp_buf); tmp_buf += i; traceaddress(&doublefnmul.F, i, tmp_buf); SharkSslEC_temp_setmulmod(&doublefnmul, o); traceguest(&p->x, &p->x, &doublefnmul.A); traceguest(&p->x, &doublefnmul.A, &doublefnmul.B); setupsdhci1(&doublefnmul.B, &o->b, mod); #if (SHARKSSL_ECC_USE_NIST && SHARKSSL_ECC_USE_BRAINPOOL) if (NULL == doublefnmul.factor_a) #endif #if SHARKSSL_ECC_USE_NIST { keypaddevice(&doublefnmul.B, &p->x, mod); keypaddevice(&doublefnmul.B, &p->x, mod); keypaddevice(&doublefnmul.B, &p->x, mod); } #if SHARKSSL_ECC_USE_BRAINPOOL else #endif #endif #if SHARKSSL_ECC_USE_BRAINPOOL { doublefnmul.D.len = 1; doublefnmul.D.beg[0] = 1; writebytes(&doublefnmul.D, &o->a, &doublefnmul.C, &o->prime, doublefnmul.mu); traceguest(&doublefnmul.C, &p->x, &doublefnmul.A); setupsdhci1(&doublefnmul.B, &doublefnmul.A, mod); o->bits |= SharkSslECCurve_bits_Montgomery_flag; } #endif traceguest(&p->y, &p->y, &doublefnmul.A); keypaddevice(&doublefnmul.A, &doublefnmul.B, mod); blastscache(&doublefnmul.A); i = (U16)(doublefnmul.A.len - 1) | (U16)(doublefnmul.A.beg[0] & 0xFFFF); #if (SHARKSSL_BIGINT_WORDSIZE == 32) i |= (doublefnmul.A.beg[0] >> 16); #endif baFree((void*)tmp_b); if (i) { return 1; } #elif SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (((shtype_tWord)-3) != o->a.beg[0]) #endif { o->bits |= SharkSslECCurve_bits_Montgomery_flag; } #endif o->G.x = p->x; o->G.y = p->y; } else { memset(o, 0, sizeof(SharkSslECCurve)); return 4; } } return 0; } #if SHARKSSL_ECC_USE_EDWARDS int SharkSslECCurve_setPoint_ED(SharkSslECCurve *o, SharkSslECPoint *p) { if ((void*)p != (void*)NULL) { if (p->x.len <= o->G.x.len) { o->G.x = p->x; o->G.y = p->y; } else { memset(o, 0, sizeof(SharkSslECCurve)); return 4; } } return 0; } #endif typedef struct { shtype_t x, y, z; } SharkSslECPointJ; #define SharkSslECPointJ_copy(s,d) \ unassignedvector(&((s)->x), &((d)->x)); unassignedvector(&((s)->y), &((d)->y)); unassignedvector(&((s)->z), &((d)->z)) static void timerconfig(SharkSslECPointJ *p, shtype_t *mod, SharkSslEC_temp *brightnesslimit) { probehandler(&p->y, &p->z, &brightnesslimit->A); setupsdhci1(&brightnesslimit->A, &brightnesslimit->A, mod); probehandler(&p->y, &p->y, &brightnesslimit->B); probehandler(&p->z, &p->z, &brightnesslimit->C); unassignedvector(&brightnesslimit->A, &p->z); probehandler(&p->x, &brightnesslimit->B, &brightnesslimit->A); setupsdhci1(&brightnesslimit->A, &brightnesslimit->A, mod); setupsdhci1(&brightnesslimit->A, &brightnesslimit->A, mod); probehandler(&brightnesslimit->B, &brightnesslimit->B, &brightnesslimit->D); unassignedvector(&brightnesslimit->D, &brightnesslimit->B); setupsdhci1(&brightnesslimit->B, &brightnesslimit->B, mod); setupsdhci1(&brightnesslimit->B, &brightnesslimit->B, mod); setupsdhci1(&brightnesslimit->B, &brightnesslimit->B, mod); #if SHARKSSL_ECC_USE_BRAINPOOL if (brightnesslimit->factor_a != NULL) { probehandler(&p->x, &p->x, &brightnesslimit->D); unassignedvector(&brightnesslimit->D, &brightnesslimit->F); setupsdhci1(&brightnesslimit->D, &brightnesslimit->D, mod); setupsdhci1(&brightnesslimit->D, &brightnesslimit->F, mod); probehandler(&brightnesslimit->C, &brightnesslimit->C, &brightnesslimit->F); probehandler(brightnesslimit->factor_a, &brightnesslimit->F, &brightnesslimit->E); setupsdhci1(&brightnesslimit->D, &brightnesslimit->E, mod); } #if SHARKSSL_ECC_USE_NIST else #endif #endif #if SHARKSSL_ECC_USE_NIST { unassignedvector(&p->x, &brightnesslimit->E); keypaddevice(&brightnesslimit->E, &brightnesslimit->C, mod); setupsdhci1(&brightnesslimit->C, &p->x, mod); probehandler(&brightnesslimit->E, &brightnesslimit->C, &brightnesslimit->D); unassignedvector(&brightnesslimit->D, &brightnesslimit->E); setupsdhci1(&brightnesslimit->E, &brightnesslimit->E, mod); setupsdhci1(&brightnesslimit->D, &brightnesslimit->E, mod); } #endif probehandler(&brightnesslimit->D, &brightnesslimit->D, &brightnesslimit->F); keypaddevice(&brightnesslimit->F, &brightnesslimit->A, mod); keypaddevice(&brightnesslimit->F, &brightnesslimit->A, mod); unassignedvector(&brightnesslimit->F, &p->x); keypaddevice(&brightnesslimit->A, &brightnesslimit->F, mod); probehandler(&brightnesslimit->D, &brightnesslimit->A, &brightnesslimit->F); keypaddevice(&brightnesslimit->F, &brightnesslimit->B, mod); unassignedvector(&brightnesslimit->F, &p->y); } #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) static void threadflush(SharkSslECPointJ *p, SharkSslECPointJ *g, shtype_t *mod, SharkSslEC_temp *brightnesslimit) { probehandler(&p->z, &p->z, &brightnesslimit->A); probehandler(&brightnesslimit->A, &g->x, &brightnesslimit->C); probehandler(&g->z, &g->z, &brightnesslimit->B); probehandler(&brightnesslimit->B, &p->x, &brightnesslimit->D); probehandler(&brightnesslimit->B, &g->z, &brightnesslimit->E); probehandler(&brightnesslimit->E, &p->y, &brightnesslimit->B); probehandler(&brightnesslimit->A, &p->z, &brightnesslimit->E); probehandler(&brightnesslimit->E, &g->y, &brightnesslimit->A); keypaddevice(&brightnesslimit->C, &brightnesslimit->D, mod); keypaddevice(&brightnesslimit->A, &brightnesslimit->B, mod); if (eventtimeout(&brightnesslimit->C)) { if (eventtimeout(&brightnesslimit->A)) { timerconfig(p, mod, brightnesslimit); } else { baAssert(0); } } else { probehandler(&brightnesslimit->C, &p->z, &brightnesslimit->E); probehandler(&brightnesslimit->E, &g->z, &brightnesslimit->F); unassignedvector(&brightnesslimit->F, &p->z); probehandler(&brightnesslimit->C, &brightnesslimit->C, &brightnesslimit->E); probehandler(&brightnesslimit->D, &brightnesslimit->E, &brightnesslimit->F); probehandler(&brightnesslimit->C, &brightnesslimit->E, &brightnesslimit->D); probehandler(&brightnesslimit->A, &brightnesslimit->A, &brightnesslimit->C); keypaddevice(&brightnesslimit->C, &brightnesslimit->D, mod); keypaddevice(&brightnesslimit->C, &brightnesslimit->F, mod); keypaddevice(&brightnesslimit->C, &brightnesslimit->F, mod); unassignedvector(&brightnesslimit->C, &p->x); keypaddevice(&brightnesslimit->F, &brightnesslimit->C, mod); probehandler(&brightnesslimit->B, &brightnesslimit->D, &brightnesslimit->E); probehandler(&brightnesslimit->A, &brightnesslimit->F, &brightnesslimit->B); keypaddevice(&brightnesslimit->B, &brightnesslimit->E, mod); unassignedvector(&brightnesslimit->B, &p->y); } } #endif static void deviceu2ootg(SharkSslECPointJ *p, SharkSslECPoint *g, shtype_t *mod, SharkSslEC_temp *brightnesslimit) { probehandler(&p->z, &p->z, &brightnesslimit->A); probehandler(&brightnesslimit->A, &g->x, &brightnesslimit->C); keypaddevice(&brightnesslimit->C, &p->x, mod); probehandler(&brightnesslimit->A, &p->z, &brightnesslimit->D); probehandler(&brightnesslimit->D, &g->y, &brightnesslimit->A); keypaddevice(&brightnesslimit->A, &p->y, mod); probehandler(&brightnesslimit->C, &p->z, &brightnesslimit->B); unassignedvector(&brightnesslimit->B, &p->z); probehandler(&brightnesslimit->C, &brightnesslimit->C, &brightnesslimit->B); probehandler(&brightnesslimit->B, &brightnesslimit->C, &brightnesslimit->F); unassignedvector(&p->x, &brightnesslimit->C); setupsdhci1(&brightnesslimit->C, &p->x, mod); probehandler(&brightnesslimit->C, &brightnesslimit->B, &brightnesslimit->D); setupsdhci1(&brightnesslimit->D, &brightnesslimit->F, mod); probehandler(&brightnesslimit->A, &brightnesslimit->A, &brightnesslimit->E); keypaddevice(&brightnesslimit->E, &brightnesslimit->D, mod); probehandler(&brightnesslimit->F, &p->y, &brightnesslimit->D); probehandler(&brightnesslimit->B, &p->x, &brightnesslimit->F); unassignedvector(&brightnesslimit->E, &p->x); keypaddevice(&brightnesslimit->F, &p->x, mod); probehandler(&brightnesslimit->F, &brightnesslimit->A, &brightnesslimit->E); keypaddevice(&brightnesslimit->E, &brightnesslimit->D, mod); unassignedvector(&brightnesslimit->E, &p->y); } static void panicblink(SharkSslECPointJ *j, SharkSslECPoint *p, shtype_t *mod, SharkSslEC_temp *brightnesslimit) { ioswabwdefault(&j->z, mod, &brightnesslimit->A.mem[0]); traceguest(&j->z, &j->z, &brightnesslimit->A); traceguest(&j->z, &brightnesslimit->A, &brightnesslimit->B); traceguest(&j->x, &brightnesslimit->A, &brightnesslimit->C); unassignedvector(&brightnesslimit->C, &p->x); traceguest(&j->y, &brightnesslimit->B, &brightnesslimit->C); unassignedvector(&brightnesslimit->C, &p->y); } #undef probehandler #undef traceguest #if (!SHARKSSL_ECDSA_ONLY_VERIFY) int SharkSslECCurve_multiply_NB(SharkSslECCurve *o, shtype_t *k, SharkSslECPoint *deltadevices) { SharkSslEC_temp brightnesslimit; shtype_tWord *tmp_b, *tmp_buf, bitmask; #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 4) #error SHARKSSL_ECC_MULT_SLIDING_WINDOW_K must be between 1 and 4 #elif ((SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) && (SHARKSSL_ECC_TIMING_RESISTANT)) #error SHARKSSL_ECC_MULT_SLIDING_WINDOW_K must be 0 when SHARKSSL_ECC_TIMING_RESISTANT is enabled #endif #if (SHARKSSL_ECC_TIMING_RESISTANT) shtype_tWord m0; SharkSslECPointJ point[2]; #else SharkSslECPointJ point[1]; #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) SharkSslECPointJ countshift[1 << (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K - 1)]; #endif #endif U16 i, flash1resources; #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) shtype_tWord sha256export; U8 bitcounter, accvalue; #endif i = o->prime.len; baAssert((deltadevices->x.len == i) && (deltadevices->y.len == i)); #if SHARKSSL_ECC_TIMING_RESISTANT flash1resources = (i * SHARKSSL__M) * (3 + 3 + 12); #else flash1resources = (i * SHARKSSL__M) * (3 + 12); #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) flash1resources += (i * SHARKSSL__M) * (3 * (1 << (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K - 1))); #endif #endif SharkSslEC_temp_setmulmod(&brightnesslimit, o); #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { flash1resources += (6 * SHARKSSL__M); } #endif tmp_b = (shtype_tWord*)baMalloc(pcmciapdata(flash1resources)); if (tmp_b == NULL) { return 1; } tmp_buf = (shtype_tWord*)selectaudio(tmp_b); #if SHARKSSL_ECC_TIMING_RESISTANT m0 = 0; #endif #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { if (o->bits & SharkSslECCurve_bits_Montgomery_flag) { o->bits &= ~SharkSslECCurve_bits_Montgomery_flag; brightnesslimit.A.beg = brightnesslimit.A.mem = tmp_buf; brightnesslimit.A.len = o->prime.len + 1; deviceparse(&brightnesslimit.A); brightnesslimit.B.beg = brightnesslimit.B.mem = tmp_buf + brightnesslimit.A.len; brightnesslimit.A.beg[0] = 1; temp_mulmod(&brightnesslimit.A, &o->G.x, &brightnesslimit.B, &o->prime, tmp_buf + (i << 2)); unassignedvector(&brightnesslimit.B, &o->G.x); temp_mulmod(&brightnesslimit.A, &o->G.y, &brightnesslimit.B, &o->prime, tmp_buf + (i << 2)); unassignedvector(&brightnesslimit.B, &o->G.y); } } #endif traceaddress(&point[0].x, i, tmp_buf); tmp_buf += i; traceaddress(&point[0].y, i, tmp_buf); tmp_buf += i; traceaddress(&point[0].z, i, tmp_buf); tmp_buf += i; mipidplatform(&(o->G), &point[0]); deviceparse(&point[0].z); point[0].z.beg[i - 1] = 1; #if SHARKSSL_ECC_TIMING_RESISTANT traceaddress(&point[1].x, i, tmp_buf); tmp_buf += i; traceaddress(&point[1].y, i, tmp_buf); tmp_buf += i; traceaddress(&point[1].z, i, tmp_buf); tmp_buf += i; SharkSslECPointJ_copy(&point[0], &point[1]); #endif #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) for (flash1resources = 0; flash1resources < (1 << (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K - 1)); flash1resources++) { traceaddress(&countshift[flash1resources].x, i, tmp_buf); tmp_buf += i; traceaddress(&countshift[flash1resources].y, i, tmp_buf); tmp_buf += i; traceaddress(&countshift[flash1resources].z, i, tmp_buf); tmp_buf += i; } #endif i <<= 1; #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { i++; brightnesslimit.A.beg = brightnesslimit.A.mem = tmp_buf; brightnesslimit.A.len = o->prime.len + 1; deviceparse(&brightnesslimit.A); brightnesslimit.A.beg[0] = 1; updatepmull(&brightnesslimit.A, &o->prime); blastscache(&brightnesslimit.A); unassignedvector(&brightnesslimit.A, &point[0].z); } #endif traceaddress(&brightnesslimit.A, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.B, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.C, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.D, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.E, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.F, i, tmp_buf); #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) SharkSslECPointJ_copy(&point[0], &countshift[0]); timerconfig(&countshift[0], &o->prime, &brightnesslimit); #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 2) timerconfig(&countshift[0], &o->prime, &brightnesslimit); #endif #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 3) timerconfig(&countshift[0], &o->prime, &brightnesslimit); #endif for (i = 1; i < (1 << (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K - 1)); i++) { SharkSslECPointJ_copy(&countshift[i-1], &countshift[i]); deviceu2ootg(&countshift[i], &o->G, &o->prime, &brightnesslimit); } #endif blastscache(k); bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); #if SHARKSSL_ECC_TIMING_RESISTANT m0 = (SHARKSSL_BIGINT_WORDSIZE - 1); for (; bitmask > 0; bitmask >>= 1, m0--) #else for (; bitmask > 0; bitmask >>= 1) #endif { if (k->beg[0] & bitmask) { bitmask >>= 1; #if SHARKSSL_ECC_TIMING_RESISTANT m0--; #endif break; } } #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) sha256export = 0; bitcounter = accvalue = 0; #endif for (i = 0; i < k->len; i++) { #if SHARKSSL_ECC_TIMING_RESISTANT for (; bitmask > 0; bitmask >>= 1, m0--) #else for (; bitmask > 0; bitmask >>= 1) #endif { timerconfig(&point[0], &o->prime, &brightnesslimit); #if SHARKSSL_ECC_TIMING_RESISTANT deviceu2ootg(&point[((~(k->beg[i] & bitmask)) >> m0) & 0x1], &o->G, &o->prime, &brightnesslimit); #else #if (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K > 1) if (0 == sha256export) { sha256export = (k->beg[i] & bitmask); if (sha256export && (i == (k->len - 1)) && (bitmask < (1 << (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K - 1)))) { deviceu2ootg(&point[0], &o->G, &o->prime, &brightnesslimit); sha256export = 0; } } else { bitcounter++; accvalue <<= 1; if (k->beg[i] & bitmask) { accvalue |= 1; } if (bitcounter == (SHARKSSL_ECC_MULT_SLIDING_WINDOW_K - 1)) { threadflush(&point[0], &countshift[accvalue], &o->prime, &brightnesslimit); bitcounter = 0; accvalue = 0; sha256export = 0; } } #else if (k->beg[i] & bitmask) { deviceu2ootg(&point[0], &o->G, &o->prime, &brightnesslimit); } #endif #endif } bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); #if SHARKSSL_ECC_TIMING_RESISTANT m0 = (SHARKSSL_BIGINT_WORDSIZE - 1); #endif } #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { brightnesslimit.A.len = 1; brightnesslimit.A.beg[0] = 1; writebytes(&brightnesslimit.A, &point[0].x, &brightnesslimit.C, &o->prime, brightnesslimit.mu); writebytes(&brightnesslimit.A, &point[0].y, &brightnesslimit.D, &o->prime, brightnesslimit.mu); writebytes(&brightnesslimit.A, &point[0].z, &brightnesslimit.E, &o->prime, brightnesslimit.mu); unassignedvector(&brightnesslimit.C, &point[0].x); unassignedvector(&brightnesslimit.D, &point[0].y); unassignedvector(&brightnesslimit.E, &point[0].z); } #endif panicblink(&point[0], deltadevices, &o->prime, &brightnesslimit); baFree((void*)tmp_b); return 0; } #if SHARKSSL_ECC_USE_EDWARDS int SharkSslECCurve_multiply_ED(SharkSslECCurve *o, shtype_t *k, SharkSslECPoint *deltadevices) { SharkSslEC_temp brightnesslimit; shtype_t x; shtype_tWord *tmp_b, *tmp_buf, bitmask, bit; U16 i, flash1resources, bIndex; baAssert(o); baAssert(k); baAssert(deltadevices); i = o->prime.len; baAssert(deltadevices->x.len == i); i <<= 1; i++; SharkSslEC_temp_setmulmod(&brightnesslimit, o); flash1resources = (i * SHARKSSL__M) * 7 + (o->prime.len * SHARKSSL__M); tmp_b = (shtype_tWord*)baMalloc(pcmciapdata(flash1resources)); if (tmp_b == NULL) { return 1; } tmp_buf = (shtype_tWord*)selectaudio(tmp_b); traceaddress(&brightnesslimit.A, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.B, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.C, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.D, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.E, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.F, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.G, i, tmp_buf); tmp_buf += i; traceaddress(&x, o->prime.len, tmp_buf); brightnesslimit.A.len = o->prime.len + 1; deviceparse(&brightnesslimit.A); brightnesslimit.A.beg[0] = 1; unassignedvector(&o->G.x, &brightnesslimit.D); blastscache(&brightnesslimit.D); #if SHARKSSL_ECC_USE_CURVE25519 if ((brightnesslimit.D.len == 1) && (brightnesslimit.D.beg[0] == 9)) { #if (SHARKSSL_BIGINT_WORDSIZE == 8) brightnesslimit.D.len++; *(brightnesslimit.D.beg--) = 0x56; *(brightnesslimit.D.beg) = 0x01; #else brightnesslimit.D.beg[0] = 0x0156; #endif shtype_t_copyfull(&brightnesslimit.D, &brightnesslimit.B); } else #endif #if SHARKSSL_ECC_USE_CURVE448 if ((brightnesslimit.D.len == 1) && (brightnesslimit.D.beg[0] == 5)) { brightnesslimit.D.len = (8 * 32 / SHARKSSL_BIGINT_WORDSIZE) + 1 - (32 / SHARKSSL_BIGINT_WORDSIZE); brightnesslimit.D.beg -= brightnesslimit.D.len - 1; brightnesslimit.D.beg[0] = 0x05; shtype_t_copyfull(&brightnesslimit.D, &brightnesslimit.B); } else #endif { temp_mulmod(&brightnesslimit.A, &brightnesslimit.D, &brightnesslimit.B, &o->prime, &brightnesslimit.E.mem[0]); } unassignedvector(&brightnesslimit.B, &x); deviceparse(&brightnesslimit.C); blastscache(&brightnesslimit.C); updatepmull(&brightnesslimit.A, &o->prime); #if SHARKSSL_ECC_USE_CURVE25519 #if SHARKSSL_ECC_USE_CURVE448 if (o->bits == 256) #endif { updatepmull(&brightnesslimit.A, &o->prime); } #endif unassignedvector(&brightnesslimit.A, &brightnesslimit.D); blastscache(&brightnesslimit.A); blastscache(&brightnesslimit.D); blastscache(k); bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); for (bIndex = (SHARKSSL_BIGINT_WORDSIZE - 1); bitmask > 0; bitmask >>= 1, bIndex--) { if (k->beg[0] & bitmask) { break; } } bit = 0; for (i = 0; i < k->len; i++) { for (; bitmask > 0; bitmask >>= 1, bIndex--) { shtype_tWord kt = (k->beg[i] & bitmask) >> bIndex; bit ^= kt; shtype_t_swapConditional(&brightnesslimit.A, &brightnesslimit.B, (U32)bit); shtype_t_swapConditional(&brightnesslimit.C, &brightnesslimit.D, (U32)bit); bit = kt; shtype_t_copyfull(&brightnesslimit.A, &brightnesslimit.E); setupsdhci1(&brightnesslimit.E, &brightnesslimit.C, &o->prime); keypaddevice(&brightnesslimit.A, &brightnesslimit.C, &o->prime); shtype_t_copyfull(&brightnesslimit.B, &brightnesslimit.C); setupsdhci1(&brightnesslimit.C, &brightnesslimit.D, &o->prime); keypaddevice(&brightnesslimit.B, &brightnesslimit.D, &o->prime); temp_fmulmod(&brightnesslimit.E, &brightnesslimit.E, &brightnesslimit.D, &o->prime, brightnesslimit.mu); temp_fmulmod(&brightnesslimit.A, &brightnesslimit.A, &brightnesslimit.F, &o->prime, brightnesslimit.mu); temp_fmulmod(&brightnesslimit.C, &brightnesslimit.A, &brightnesslimit.G, &o->prime, brightnesslimit.mu); temp_fmulmod(&brightnesslimit.E, &brightnesslimit.B, &brightnesslimit.C, &o->prime, brightnesslimit.mu); shtype_t_copyfull(&brightnesslimit.G, &brightnesslimit.A); setupsdhci1(&brightnesslimit.G, &brightnesslimit.C, &o->prime); keypaddevice(&brightnesslimit.A, &brightnesslimit.C, &o->prime); temp_fmulmod(&brightnesslimit.A, &brightnesslimit.A, &brightnesslimit.B, &o->prime, brightnesslimit.mu); shtype_t_copyfull(&brightnesslimit.D, &brightnesslimit.C); keypaddevice(&brightnesslimit.C, &brightnesslimit.F, &o->prime); temp_fmulmod(&brightnesslimit.C, brightnesslimit.factor_a, &brightnesslimit.A, &o->prime, brightnesslimit.mu); setupsdhci1(&brightnesslimit.A, &brightnesslimit.D, &o->prime); temp_fmulmod(&brightnesslimit.A, &brightnesslimit.C, &brightnesslimit.E, &o->prime, brightnesslimit.mu); temp_fmulmod(&brightnesslimit.D, &brightnesslimit.F, &brightnesslimit.A, &o->prime, brightnesslimit.mu); temp_fmulmod(&x, &brightnesslimit.B, &brightnesslimit.D, &o->prime, brightnesslimit.mu); temp_fmulmod(&brightnesslimit.G, &brightnesslimit.G, &brightnesslimit.B, &o->prime, brightnesslimit.mu); shtype_t_copyfull(&brightnesslimit.E, &brightnesslimit.C); } bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); bIndex = (SHARKSSL_BIGINT_WORDSIZE - 1); } #if 0 #if (SHARKSSL_ECC_USE_CURVE25519 && SHARKSSL_ECC_USE_CURVE448) if (o->bits == 256) { i = 253; flash1resources = 4; bIndex = 2; } else { i = 446; flash1resources = 224; bIndex = 1; } #endif unassignedvector(&brightnesslimit.C, &brightnesslimit.D); #if (SHARKSSL_ECC_USE_CURVE25519 && SHARKSSL_ECC_USE_CURVE448) for (; i > 0; i--) #elif SHARKSSL_ECC_USE_CURVE25519 for (i = 253; i > 0; i--) #elif SHARKSSL_ECC_USE_CURVE448 for (i = 446; i > 0; i--) #else #error internal error in SharkSslECCurve_multiply_ED #endif { temp_fmulmod(&brightnesslimit.C, &brightnesslimit.C, &brightnesslimit.E, &o->prime, brightnesslimit.mu); #if (SHARKSSL_ECC_USE_CURVE25519 && SHARKSSL_ECC_USE_CURVE448) if ((i == flash1resources) || (i == bIndex)) #elif SHARKSSL_ECC_USE_CURVE25519 if ((i == 4) || (i == 2)) #else if ((i == 224) || (i == 1)) #endif { #if 0 unassignedvector(&brightnesslimit.E, &brightnesslimit.C); #else shtype_t_swapConditional(&brightnesslimit.C, &brightnesslimit.E, 1); #endif } else { temp_fmulmod(&brightnesslimit.E, &brightnesslimit.D, &brightnesslimit.C, &o->prime, brightnesslimit.mu); } } temp_fmulmod(&brightnesslimit.A, &brightnesslimit.C, &brightnesslimit.D, &o->prime, brightnesslimit.mu); brightnesslimit.A.len = 1; brightnesslimit.A.beg[0] = 1; temp_fmulmod(&brightnesslimit.A, &brightnesslimit.D, &brightnesslimit.E, &o->prime, brightnesslimit.mu); unassignedvector(&brightnesslimit.E, &deltadevices->x); #else brightnesslimit.B.len = 1; brightnesslimit.B.beg[0] = 1; temp_fmulmod(&brightnesslimit.B, &brightnesslimit.C, &brightnesslimit.D, &o->prime, brightnesslimit.mu); temp_fmulmod(&brightnesslimit.B, &brightnesslimit.A, &brightnesslimit.C, &o->prime, brightnesslimit.mu); iommumapping(&brightnesslimit.D, &o->prime); temp_mulmod(&brightnesslimit.C, &brightnesslimit.D, &brightnesslimit.B, &o->prime, &brightnesslimit.E.mem[0]); unassignedvector(&brightnesslimit.B, &deltadevices->x); #endif deltadevices->y.mem = NULL; deltadevices->y.beg = NULL; deltadevices->y.len = 0; baFree((void*)tmp_b); return 0; } #endif #endif #if SHARKSSL_ENABLE_EDDSA #if SHARKSSL_ECC_USE_CURVE25519 #endif #endif #if SHARKSSL_ENABLE_ECDSA int directalloc(SharkSslECCurve *S, shtype_t *d, SharkSslECCurve *T, shtype_t *e, SharkSslECPoint *deltadevices) { SharkSslEC_temp brightnesslimit; shtype_tWord *tmp_b, *tmp_buf, bitmask; SharkSslECPointJ point[1]; SharkSslECPoint sum; #if SHARKSSL_ECC_USE_BRAINPOOL SharkSslECPoint TG, *TGP; #endif U16 i, flash1resources; i = S->prime.len; #if SHARKSSL_ECC_USE_BRAINPOOL T->bits &= ~SharkSslECCurve_bits_Montgomery_flag; #endif if ((i != T->prime.len) || (S->bits != T->bits) || (d->len != e->len)) { return 1; } baAssert(T->prime.beg == S->prime.beg); baAssert((deltadevices->x.len == i) && (deltadevices->y.len == i)); flash1resources = (i * SHARKSSL__M) * (3 + 2 + 12); SharkSslEC_temp_setmulmod(&brightnesslimit, S); #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { flash1resources += (6 * SHARKSSL__M); flash1resources += (i * SHARKSSL__M) * 2; } #endif tmp_b = (shtype_tWord*)baMalloc(pcmciapdata(flash1resources)); if (tmp_b == NULL) { return 1; } tmp_buf = (shtype_tWord*)selectaudio(tmp_b); traceaddress(&point[0].x, i, tmp_buf); tmp_buf += i; traceaddress(&point[0].y, i, tmp_buf); tmp_buf += i; traceaddress(&point[0].z, i, tmp_buf); tmp_buf += i; deviceparse(&point[0].z); point[0].z.beg[i - 1] = 1; mipidplatform(&(S->G), &point[0]); receivebroadcast(&sum, i, tmp_buf, tmp_buf + i); tmp_buf += (i << 1); i <<= 1; #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { receivebroadcast(&TG, T->prime.len, tmp_buf, tmp_buf + T->prime.len); tmp_buf += i; i++; brightnesslimit.A.beg = brightnesslimit.A.mem = tmp_buf; brightnesslimit.A.len = T->prime.len + 1; deviceparse(&brightnesslimit.A); brightnesslimit.A.beg[0] = 1; updatepmull(&brightnesslimit.A, &T->prime); blastscache(&brightnesslimit.A); unassignedvector(&brightnesslimit.A, &point[0].z); hotplugpgtable(&T->G.x, &point[0].z, &brightnesslimit.A); envdatamcheck(&brightnesslimit.A, &T->prime, tmp_buf + i); unassignedvector(&brightnesslimit.A, &TG.x); hotplugpgtable(&T->G.y, &point[0].z, &brightnesslimit.A); envdatamcheck(&brightnesslimit.A, &T->prime, tmp_buf + i); unassignedvector(&brightnesslimit.A, &TG.y); } #endif traceaddress(&brightnesslimit.A, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.B, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.C, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.D, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.E, i, tmp_buf); tmp_buf += i; traceaddress(&brightnesslimit.F, i, tmp_buf); #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { deviceu2ootg(&point[0], &TG, &S->prime, &brightnesslimit); brightnesslimit.A.len = 1; brightnesslimit.A.beg[0] = 1; writebytes(&brightnesslimit.A, &point[0].x, &brightnesslimit.C, &T->prime, brightnesslimit.mu); writebytes(&brightnesslimit.A, &point[0].y, &brightnesslimit.D, &T->prime, brightnesslimit.mu); writebytes(&brightnesslimit.A, &point[0].z, &brightnesslimit.E, &T->prime, brightnesslimit.mu); unassignedvector(&brightnesslimit.C, &point[0].x); unassignedvector(&brightnesslimit.D, &point[0].y); unassignedvector(&brightnesslimit.E, &point[0].z); } #if SHARKSSL_ECC_USE_NIST else #endif #endif #if SHARKSSL_ECC_USE_NIST { deviceu2ootg(&point[0], &T->G, &S->prime, &brightnesslimit); } #endif panicblink(&point[0], &sum, &S->prime, &brightnesslimit); #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { brightnesslimit.A.len = T->prime.len + 1; deviceparse(&brightnesslimit.A); brightnesslimit.A.beg[0] = 1; updatepmull(&brightnesslimit.A, &T->prime); blastscache(&brightnesslimit.A); unassignedvector(&brightnesslimit.A, &point[0].z); hotplugpgtable(&sum.x, &point[0].z, &brightnesslimit.A); envdatamcheck(&brightnesslimit.A, &T->prime, &brightnesslimit.B.beg[0]); unassignedvector(&brightnesslimit.A, &sum.x); hotplugpgtable(&sum.y, &point[0].z, &brightnesslimit.A); envdatamcheck(&brightnesslimit.A, &T->prime, &brightnesslimit.B.beg[0]); unassignedvector(&brightnesslimit.A, &sum.y); TGP = &TG; } #if SHARKSSL_ECC_USE_NIST else #endif #endif #if SHARKSSL_ECC_USE_NIST { point[0].z.len = S->prime.len; deviceparse(&point[0].z); point[0].z.beg[S->prime.len - 1] = 1; #if SHARKSSL_ECC_USE_BRAINPOOL TGP = &T->G; #endif } #endif while ((e->beg[0] == 0) && (d->beg[0] == 0) && (e->len > 1) && (d->len > 1)) { e->beg++; e->len--; d->beg++; d->len--; } bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); for (; bitmask > 0; bitmask >>= 1) { if (e->beg[0] & bitmask) { if (d->beg[0] & bitmask) { mipidplatform(&sum, &point[0]); } else #if SHARKSSL_ECC_USE_BRAINPOOL { mipidplatform(TGP, &point[0]); } #else { mipidplatform(&(T->G), &point[0]); } #endif } else if (d->beg[0] & bitmask) { mipidplatform(&(S->G), &point[0]); } else { continue; } bitmask >>= 1; break; } for (i = 0; i < e->len; i++) { for (; bitmask > 0; bitmask >>= 1) { timerconfig(&point[0], &S->prime, &brightnesslimit); if (e->beg[i] & bitmask) { if (d->beg[i] & bitmask) { deviceu2ootg(&point[0], &sum, &S->prime, &brightnesslimit); } else #if SHARKSSL_ECC_USE_BRAINPOOL { deviceu2ootg(&point[0], TGP, &S->prime, &brightnesslimit); } #else { deviceu2ootg(&point[0], &T->G, &S->prime, &brightnesslimit); } #endif } else if (d->beg[i] & bitmask) { deviceu2ootg(&point[0], &S->G, &S->prime, &brightnesslimit); } } bitmask = (shtype_tWord)((shtype_tWord)1 << (SHARKSSL_BIGINT_WORDSIZE - 1)); } #if SHARKSSL_ECC_USE_BRAINPOOL #if SHARKSSL_ECC_USE_NIST if (brightnesslimit.factor_a != NULL) #endif { brightnesslimit.A.len = 1; brightnesslimit.A.beg[0] = 1; writebytes(&brightnesslimit.A, &point[0].x, &brightnesslimit.C, &T->prime, brightnesslimit.mu); writebytes(&brightnesslimit.A, &point[0].y, &brightnesslimit.D, &T->prime, brightnesslimit.mu); writebytes(&brightnesslimit.A, &point[0].z, &brightnesslimit.E, &T->prime, brightnesslimit.mu); unassignedvector(&brightnesslimit.C, &point[0].x); unassignedvector(&brightnesslimit.D, &point[0].y); unassignedvector(&brightnesslimit.E, &point[0].z); } #endif panicblink(&point[0], deltadevices, &S->prime, &brightnesslimit); baFree((void*)tmp_b); return 0; } #endif #if SHARKSSL_ENABLE_ECCKEY_CREATE extern U8 controllerregister(U16 defaultsdhci1); SHARKSSL_API int SharkSslECCKey_createEx(SharkSslECCKey *mcbspplatform, U16 defaultsdhci1, void* iospacestart, sharkssl_rngfunc smartflush) { static const shtype_tWord w_one = 0x1; SharkSslECCurve nandflashpartition; SharkSslECPoint Q; shtype_t one, d, order; U8 *buf; int buttonsbuffalo = 0; U8 allockuser, plen; *mcbspplatform = NULL; plen = controllerregister(defaultsdhci1); if (0 == plen) { return -1; } allockuser = (U8)((plen + 3) & ~3); buttonsbuffalo = (int)(((unsigned int)allockuser << 1) + allockuser + 8); *mcbspplatform = buf = (U8*)baMalloc(buttonsbuffalo); if (NULL == buf) { return -1; } if (smartflush ? smartflush(iospacestart, buf, allockuser + 8) : sharkssl_rng(buf, allockuser + 8)) { baFree(buf); return -2; } onenandpartitions(&one, sizeof(shtype_tWord) * 8, &w_one); onenandpartitions(&d, ((allockuser + 8) * 8), buf); clearerrors(&nandflashpartition, defaultsdhci1); #if SHARKSSL_ECC_USE_SECP521R1 if (allockuser > plen) { d.beg[0] &= nandflashpartition.prime.beg[0]; } #endif buf += allockuser + 8; onenandpartitions(&order, (nandflashpartition.prime.len * SHARKSSL_BIGINT_WORDSIZE), buf); unassignedvector(&(nandflashpartition.order), &order); updatepmull(&order, &one); suspendfinish(&d, &order); resolverelocs(&d, &one); updatefrequency(&Q, (nandflashpartition.prime.len * SHARKSSL_BIGINT_WORDSIZE), buf , buf + allockuser); unregisterskciphers(&nandflashpartition, &d, &Q); buf = *mcbspplatform; buf[0] = 0x30; buf[1] = 0x82; buf[2] = buf[3] = 0x00; buf[4] = 0x02; buf[5] = buf[7] = plen; buf[6] = (U8)defaultsdhci1; memmove_endianess(&buf[8], &buf[8], (allockuser << 1) + allockuser); #if SHARKSSL_ECC_USE_SECP521R1 if (allockuser > plen) { allockuser -= plen; memmove(&buf[8], &buf[8 + allockuser], plen); memmove(&buf[8 + plen], &buf[8 + plen + (allockuser * 2)], plen); memmove(&buf[8 + (plen * 2)], &buf[8 + (plen * 2) + (allockuser * 2) + allockuser], plen); } #endif return buttonsbuffalo; } #endif #endif #ifndef BA_LIB #define BA_LIB #endif #include #include #include #ifndef NO_SHARKSSL #include #endif #define BA_WKREFIX "\137\102\101\127\113\122\111\130" #define BA_WKREFTAB "\137\102\101\127\113" BA_API unsigned int baluai_makeseed(void) { unsigned int val; sharkssl_rng((U8*)&val, sizeof(val)); return val; } BA_API void* #ifdef BA_LEAK_CHECK baLMallocL(lua_State* L, size_t icachealiases,const char* debugsetup, int enabledisable) { void* ptr=baLeakDetectMalloc(icachealiases,debugsetup,enabledisable); #else baLMalloc(lua_State* L, size_t icachealiases) { void* ptr=baMalloc(icachealiases); #endif if(!ptr) { lua_gc(L,LUA_GCCOLLECT,0); ptr=baMalloc(icachealiases); } return ptr; } #if 0 BA_API void* #ifdef BA_LEAK_CHECK baLReallocL(lua_State* L, void* p, U32 icachealiases,const char* debugsetup, int enabledisable) { void* ptr=baLeakDetectRealloc(p, icachealiases,debugsetup,enabledisable); #else baLRealloc(lua_State* L, void* p, U32 icachealiases) { void* ptr=baRealloc(p, icachealiases); #endif if(!ptr) { lua_gc(L,LUA_GCCOLLECT,0); ptr=baRealloc(p, icachealiases); } return ptr; } #endif #ifndef NO_BA_SERVER static int unwindinner(lua_State* L, int ix, int timerunblocking, int pri) { int n = lua_gettop(L); const char *s; int i; lua_Debug ar; if(timerunblocking) { lua_getstack(L, 1, &ar); lua_getinfo(L, "\156\154", &ar); HttpTrace_printf( pri, "\045\163\040\045\144\072\040",ar.name ? ar.name : "", ar.currentline); } lua_getglobal(L, "\164\157\163\164\162\151\156\147"); for (i=ix; i<=n; i++) { size_t l; lua_pushvalue(L, -1); lua_pushvalue(L, i); lua_call(L, 1, 1); s = lua_tolstring(L, -1, &l); if (s == NULL) return luaL_error(L, "\047\164\157\163\164\162\151\156\147\047\040\155\165\163\164\040\162\145\164\165\162\156\040\141\040\163\164\162\151\156\147\040\164\157\040\047\160\162\151\156\164\047"); if (i>ix) { HttpTrace_write(pri, "\011", 1); } HttpTrace_write(pri, s, (int)l); lua_pop(L, 1); } HttpTrace_write(pri, "\012",1); return 0; } static int bgezlhazard(lua_State* L) { return unwindinner(L, 1, TRUE, 0); } static int maceisalevel(lua_State* L) { int pri; int ix=1; int timerunblocking=TRUE; if(lua_isboolean(L, 1)) { timerunblocking=lua_toboolean(L, 1); ix=2; } pri = (int)luaL_checkinteger(L,ix); return unwindinner(L,ix+1,timerunblocking,pri); } static const luaL_Reg baGLib[] = { {"\164\162\141\143\145", bgezlhazard}, {"\164\162\141\143\145\160", maceisalevel}, {NULL, NULL} }; #endif static int sleepenter(lua_State *L) { #ifndef NO_BA_SERVER BaLua_param* p = balua_getparam(L); #endif lua_createtable(L, 0, 30); luaopen_ba_misc(L); luaopen_ba_io(L); luaopen_ba_aes(L); #ifdef NO_BA_SERVER lua_newtable(L); lua_setfield(L, -2, "\143\162\145\141\164\145"); #else if(p->server) { luaopen_ba_create(L); lua_setfield(L, -2, "\143\162\145\141\164\145"); if(p->timer) luaopen_ba_timer(L); } #endif luaopen_ba_json(L); lua_setfield(L, -2, "\152\163\157\156"); luaopen_ba_xmlrpc(L); lua_setfield(L, -2, "\170\155\154\162\160\143"); luaopen_xparser(L); luaopen_ba_datetime(L); #ifndef NO_BA_SERVER lua_pushglobaltable(L); luaL_setfuncs(L,baGLib,0); lua_pop(L,1); #endif return 1; } BA_API void balua_getuservalue(lua_State* L, int doublefsito) { lua_getuservalue(L,doublefsito); if(lua_isnil(L,-1)) { lua_pop(L,1); lua_createtable(L, 0, 0); lua_pushvalue(L, -1); lua_setuservalue(L, doublefsito); } } BA_API int balua_wkRef(lua_State* L) { int ref=balua_wkRefIx(L, -1); lua_pop(L,1); return ref; } BA_API int balua_wkRefIx(lua_State* L, int uart2hwmod) { int wkRef; lua_getfield(L,LUA_REGISTRYINDEX,BA_WKREFIX); wkRef=(int)lua_tointeger(L, -1); lua_getfield(L,LUA_REGISTRYINDEX,BA_WKREFTAB); for(;;) { int isnil; lua_rawgeti(L, -1, wkRef); isnil=lua_isnil(L, -1); lua_pop(L,1); if(isnil) break; if (++wkRef == INT_MAX) wkRef = 1; } lua_pushvalue(L, uart2hwmod-2); lua_rawseti(L, -2, wkRef); lua_pushinteger(L, wkRef+1); lua_setfield(L, LUA_REGISTRYINDEX, BA_WKREFIX); lua_pop(L,2); return wkRef; } BA_API void balua_wkUnref(lua_State* L, int wkRef) { lua_getfield(L,LUA_REGISTRYINDEX,BA_WKREFTAB); lua_pushnil(L); lua_rawseti(L, -2, wkRef); lua_pop(L,1); } BA_API void balua_wkPush(lua_State* L, int ref) { lua_getfield(L,LUA_REGISTRYINDEX,BA_WKREFTAB); lua_rawgeti(L, -1, ref); lua_replace(L, -2); } BA_API lua_State* balua_getmainthread(lua_State* L) { lua_State* LM; lua_rawgeti(L,LUA_REGISTRYINDEX,LUA_RIDX_MAINTHREAD); LM=lua_tothread(L, -1); lua_pop(L,1); return LM; } BA_API int balua_typeerror(lua_State *L, int scoopsetup, const char *lowmembounds) { const char *msg = lua_pushfstring(L, "\045\163\040\145\170\160\145\143\164\145\144\054\040\147\157\164\040\045\163", lowmembounds, luaL_typename(L, scoopsetup)); return luaL_argerror(L, scoopsetup, msg); } BA_API int balua_checkboolean(lua_State *L, int scoopsetup) { if (!lua_isboolean(L, scoopsetup)) balua_typeerror(L, scoopsetup, lua_typename(L, LUA_TBOOLEAN)); return lua_toboolean(L, scoopsetup); } BA_API void balua_manageerr( lua_State* L, const char* registershash, const char* ethernatenable,HttpCommand* cmd) { BaLua_param* p = balua_getparam(L); if(p && p->errHndRef) { static const char setupsdhci0[] ={"\164\157\157\040\155\141\156\171\040\163\171\156\164\141\170\040\154\145\166\145\154\163"}; if(strstr(ethernatenable,setupsdhci0)) { #ifdef NO_BA_SERVER printf("\045\163\012",setupsdhci0); #else HttpTrace_printf(0,"\114\165\141\040\045\163",setupsdhci0); if(cmd) HttpTrace_printf(0,"\054\040\125\122\114\072\040\045\163", HttpRequest_getRequestURL(&cmd->request,FALSE)); HttpTrace_printf(0,"\012"); #endif } else { int sffsdrnandflash; int top = lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, p->errHndRef); if(registershash) lua_pushfstring(L, "\114\165\141\040\145\162\162\157\162\040\151\156\040\045\163\072\040\045\163",registershash,ethernatenable); else lua_pushfstring(L, "\114\165\141\040\145\162\162\157\162\072\040\045\163",ethernatenable); if(cmd && cmd->lcmd) { lua_rawgeti(L, LUA_REGISTRYINDEX, cmd->lcmd->envRef); sffsdrnandflash=lua_pcall(L, 2, 1, 0); } else sffsdrnandflash=lua_pcall(L, 1, 1, 0); if(sffsdrnandflash) { HttpTrace_printf(0, "\105\162\162\157\162\040\151\156\040\145\162\162\157\162\040\150\141\156\144\154\145\162\072\040\045\163", lua_isstring(L,-1) ? lua_tostring(L, -1) : "\077"); } lua_settop(L,top); } } HttpTrace_printf(0,"\012\012\055\055\055\055\055\055\055\055\040\114\165\141\040\145\162\162\157\162"); if(registershash) HttpTrace_printf(0, "\040\151\156\040\045\163\072\040\045\163\012\012",registershash,ethernatenable); else HttpTrace_printf(0, "\072\040\045\163\012\012",ethernatenable); } BA_API int balua_errorhandler(lua_State* L) { luaL_traceback(L,L,lua_tostring(L, -1), 1); balua_manageerr(L,0,lua_tostring(L, -1),0); return 1; } BA_API void balua_resumeerr(lua_State* L, const char* atomicbarrier) { luaL_traceback(L,L,lua_tostring(L, -1), 1); balua_manageerr(L,atomicbarrier,lua_tostring(L, -1),0); lua_pop(L, 1); } int balua_pushstatus(lua_State* L, int ret) { if (ret == 0) { lua_pushboolean(L,1); return 1; } lua_pushnil(L); lua_pushstring(L, baErr2Str(ret)); lua_pushinteger(L, ret); return 3; } static const char* balua_typestr(int predividetable) { switch (predividetable) { case BA_TDIR: return "\104\111\122"; case BA_TDIR_RSRDR: return "\123\122\104\122"; case BA_TDIR_DAV: return "\101\126"; case BA_TRESINTF: return "\122\105\123\111\116\124\106"; case BA_TIOINTF: return "\111\117\111\116\124\106"; case BA_TDIRITER: return "\104\111\122\111\124\105\122"; case BA_THTTPCMD: return "\110\124\124\120\103\115\104"; case BA_TCOOKIE: return "\103\117\117\113\111\105"; case BA_TSESSION: return "\123\105\123\123\111\117\116"; case BA_TSETRESPONSE: return "\123\105\124\122\105\123\120\117\116\123\105"; case BA_TAUTHORIZERINTF: return "\101\125\124\110\117\122\111\132\105\122\111\116\124\106"; case BA_TLUA_AUTHORIZER: return "\125\124\110\117\122\111\132\105\122"; case BA_TUSERINTF: return "\125\123\105\122\111\116\124\106"; case BA_TLUA_USER: return "\123\105\122"; case BA_TJAUTHORIZER: return "\112\101\125\124\110\117\122\111\132\105\122"; case BA_TJUSER: return "\112\125\123\105\122"; case BA_TAUTHENTICATORINTF: return "\101\125\124\110\105\116\124\111\103\101\124\117\122\111\116\124\106"; case BA_TAUTHENTICATOR: return "\101\125\124\110\105\116\124\111\103\101\124\117\122"; case BA_TTIMER: return "\124\111\115\105\122"; case BA_TUPLOAD: return "\125\120\114\117\101\104"; case BA_TASYNCRESP: return "\101\123\131\116\103\122\105\123\120"; } return "\165\156\153\156\157\167\156"; } BA_API int baluaENV_newmetatable(lua_State *L, int predividetable, int allocsigpage) { baluaENV_getmetatable(L,predividetable); if (!lua_isnil(L, -1)) return 0; lua_pop(L, 1); lua_newtable(L); lua_pushvalue(L, -1); lua_rawseti(L, BA_ENV_IX, predividetable); if(allocsigpage) { baluaENV_getmetatable(L,allocsigpage); baAssert(LUA_TTABLE == lua_type(L,-1)); lua_setmetatable(L, -2); } return 1; } BA_API void baluaENV_register(lua_State *L, int predividetable, int allocsigpage, const luaL_Reg* lib) { balua_check(baluaENV_newmetatable(L, predividetable, allocsigpage), 1); lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); lua_pushvalue(L,BA_ENV_IX); luaL_setfuncs(L, lib, 1); lua_pop(L, 1); } BA_API void* baluaENV_newuserdata(lua_State *L, int predividetable, size_t icachealiases) { void* o = lua_newuserdata(L, icachealiases); balua_check(baluaENV_newmetatable(L, predividetable, 0), 0); lua_setmetatable(L, -2); return o; } BA_API void* _baluaENV_isudtype(lua_State* L, int barrierreserve, int predividetable, int gpio2resources) { void *p = lua_touserdata(L, barrierreserve); if(p) { if(lua_getmetatable(L, barrierreserve)) { int flushremote = lua_gettop(L); int allocateresources = flushremote+1; baluaENV_getmetatable(L,predividetable); for(;;) { baAssert(LUA_TTABLE == lua_type(L,allocateresources)); if(lua_rawequal(L, allocateresources, flushremote)) { lua_settop(L, allocateresources-2); return p; } if( ! lua_getmetatable(L, flushremote) ) break; flushremote=-1; } } } if(gpio2resources) { luaL_argerror(L, barrierreserve, lua_pushfstring( L, "\045\163\040\145\170\160\145\143\164\145\144\054\040\147\157\164\040\045\163", balua_typestr(predividetable), luaL_typename(L, barrierreserve))); } return 0; } #ifndef NO_BA_SERVER BA_API HttpCommand* baluaENV_checkcmd(lua_State* L, int ix) { return LHttpCommand_check(L,ix)->cmd; } #endif BA_API BaLua_param* balua_getparam(lua_State* L) { BaLua_param* p; balua_pushbatab(L); lua_rawgeti(L, -1, BA_VMPTR); baAssert(LUA_TLIGHTUSERDATA == lua_type(L,-1)); p = (BaLua_param*)lua_touserdata(L, -1); lua_pop(L,2); return p; } BA_API BaLua_param* baluaENV_getparam(lua_State* L) { BaLua_param* p; lua_rawgeti(L, BA_ENV_IX, BA_VMPTR); baAssert(LUA_TLIGHTUSERDATA == lua_type(L,-1)); p = (BaLua_param*)lua_touserdata(L, -1); lua_pop(L,1); return p; } static const luaL_Reg balibs[] = { {"\142\141", sleepenter}, {NULL, NULL} }; static int ocelotpcb123(lua_State *L) { const luaL_Reg *lib; lua_Integer baWkRef=1; BaLua_param* p=baluaENV_getparam(L); lua_pushliteral(L, BA_TABLE); lua_pushvalue(L, BA_ENV_IX); lua_rawset(L, LUA_REGISTRYINDEX); lua_pushinteger(L, baWkRef); lua_setfield(L, LUA_REGISTRYINDEX, BA_WKREFIX); lua_createtable(L, 0, 0); lua_createtable(L, 0, 1); lua_pushliteral(L, "\166"); lua_setfield(L, -2, "\137\137\155\157\144\145"); lua_setmetatable(L, -2); lua_setfield(L, LUA_REGISTRYINDEX, BA_WKREFTAB); lua_createtable(L,0,1); lua_rawseti(L, BA_ENV_IX, BA_IOINTFTAB); baiolib_register(L); if(p->server) { #ifndef NO_BA_SERVER LHttpDir_register(L); #endif if(p->timer) LTimer_register(L); } ljsonlib_register(L); balua_iointf(L, "\166\155", p->vmio); for (lib = balibs; lib->func; lib++) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); } return 0; } static void* balua_alloc(void *ud, void *ptr, size_t hugetlbvalid, size_t ahashsetkey) { register void* mem; (void)ud; (void)hugetlbvalid; if (ahashsetkey == 0) { baFree(ptr); return 0; } else { mem = baRealloc(ptr, ahashsetkey); if (!mem) { luaC_fullgc(((BaLua_param *)ud)->L, 1); mem = baRealloc(ptr, ahashsetkey); if (!mem) baFatalE(FE_MALLOC, ahashsetkey); } return mem; } } static int write64uint16(lua_State *L) { HttpTrace_printf(0,"\120\101\116\111\103\072\040\165\156\160\162\157\164\145\143\164\145\144\040\145\162\162\157\162\040\151\156\040\143\141\154\154\040\164\157\040\114\165\141\040\101\120\111\040\050\045\163\051\012", lua_tostring(L, -1)); baFatalE(FE_BLUA_PANIC, 0); return 0; } static void balua_warn(void* ud, const char* msg, int tocont) { (void)ud; HttpTrace_printf(5, "\045\163\045\163", msg, tocont ? "" : "\012"); } BA_API lua_State* _balua_create(const BaLua_param* p, int dummywrite) { int sffsdrnandflash; lua_State *L; BaLua_param* pc; pc=(BaLua_param*)baMalloc(sizeof(BaLua_param)); pc->zipBinPwd = p->zipBinPwd; pc->zipBinPwdLen = p->zipBinPwdLen; pc->pwdRequired = p->pwdRequired; #ifdef NO_BA_SERVER L=p->L; baAssert(L); #else lSharkSSLFuncs=0; if(!p || dummywrite != BALUA_VERSION || p->L || !p->vmio) { HttpTrace_printf(0, "\102\141\114\165\141\137\160\141\162\141\155\072\040\167\162\157\156\147\040\166\145\162\163\151\157\156\040\157\162\040\151\156\143\157\162\162\145\143\164\040\160\141\162\141\155\163"); return 0; } sharkssl_entropy((U32)((uintptr_t)pc)); sharkssl_entropy((U32)(baGetMsClock() + baGetUnixTime())); sharkssl_rng((U8*)&sffsdrnandflash, sizeof(sffsdrnandflash)); if( !(L = lua_newstate(balua_alloc,pc, sffsdrnandflash)) ) { HttpTrace_printf(0,"\154\165\141\040\163\164\141\164\145\072\040\156\157\164\040\145\156\157\165\147\150\040\155\145\155\157\162\171"); return 0; } lua_atpanic(L, write64uint16); lua_setwarnf(L, balua_warn, 0); #endif luaL_openlibs(L); lua_gc(L, LUA_GCSTOP, 0); lua_createtable(L,20,0); lua_pushlightuserdata(L, pc); memcpy(pc, p, sizeof(BaLua_param)); pc->L=L; #ifdef NO_BA_SERVER pc->mutex=p->mutex; pc->server=p->server; #else pc->mutex= pc->server ? SoDisp_getMutex(HttpServer_getDispatcher(pc->server)) : 0; #endif lua_rawseti(L, -2, BA_VMPTR); lua_pushcclosure(L, ocelotpcb123, 1); sffsdrnandflash=lua_pcall(L,0,0,0); if(sffsdrnandflash) baFatalE(FE_BLUA_PANIC, sffsdrnandflash); lua_gc(L, LUA_GCRESTART, 0); return L; } BA_API void balua_close(lua_State* L) { BaLua_param* p = balua_getparam(L); lua_pushvalue(L, LUA_REGISTRYINDEX); lua_pushnil(L); while (lua_next(L, -2) != 0) { if(LUA_TNUMBER == lua_type(L, -2)) { int ix = (int)lua_tointeger(L, -2); switch (lua_type(L, -1)) { case LUA_TUSERDATA: case LUA_TTHREAD: luaL_unref(L, LUA_REGISTRYINDEX, ix); } } lua_pop(L, 1); } lua_gc(L, LUA_GCCOLLECT); lua_gc(L, LUA_GCCOLLECT); lua_close(L); baFree(p); } int balua_loadconfigExt( lua_State* L, struct IoIntf* io, const char* debugsetup, int hugepageadjust) { int sffsdrnandflash; static const char machinerestart[]={"\056\143\157\156\146\151\147"}; int top = lua_gettop(L); if(!debugsetup) debugsetup = machinerestart; sffsdrnandflash = balua_loadfile(L, debugsetup, io, 0); if(!sffsdrnandflash) { lua_pushstring(L, debugsetup); sffsdrnandflash = lua_pcall(L,1,hugepageadjust,0); } else if(sffsdrnandflash == LUA_ERRFILE && !debugsetup) { sffsdrnandflash = 0; } if(sffsdrnandflash) { if(!lua_tostring(L, -1)) lua_pushliteral(L, "\050\145\162\162\157\162\040\167\151\164\150\040\156\157\040\155\145\163\163\141\147\145\051"); } else if(hugepageadjust == 0) lua_settop(L,top); return sffsdrnandflash; } void successfulsyscall(lua_State *L, int idx, const U8 k[], size_t kz) { size_t i; luaL_Buffer B; char* str=luaL_buffinitsize(L, &B,kz+1); for(i = 0 ; i < kz ; i++) str[i]=k[i] ^ BALUA_XH; str[i]=0; lua_pushvalue(L, -2); lua_setfield(L,idx-2,str); lua_pop(L, 2); } void delaycycles( lua_State *L, lua_CFunction f, const U8 k[], size_t kz,int nup) { int i; for(i = 0; i < nup; i++) lua_pushvalue(L, -nup); lua_pushcclosure(L, f, nup); successfulsyscall(L, -(nup + 2), k, kz); } #ifndef BA_LIB #define BA_LIB #endif #include #include #include #include #include typedef struct { int isB64; /* iso8601 if false */ size_t len; char data[1]; } LXMLRPC; #define writeLiteral(bp, s) BufPrint_write(bp, s, sizeof(s)-1) static int threadrollback(lua_State* L) { DynBuffer db; BufPrint* bp=(BufPrint*)&db; LXMLRPC* lx = (LXMLRPC*)lua_touserdata (L, lua_upvalueindex(1)); DynBuffer_constructor( &db,(int)((lx->isB64 ? (lx->len*4)/3 : lx->len) + 100), 0, 0, 0); if(lx->isB64) { writeLiteral(bp, "\074\142\141\163\145\066\064\076"); BufPrint_b64Encode(bp, lx->data, (S32)lx->len); writeLiteral(bp, "\074\057\142\141\163\145\066\064\076"); } else { static const char iso[] = {"\144\141\164\145\124\151\155\145\056\151\163\157\070\066\060\061"}; BufPrint_printf(bp,"\074\045\163\076\045\163\074\057\045\163\076",iso,lx->data,iso); } if(DynBuffer_getECode(&db)) { DynBuffer_destructor(&db); luaL_error(L, "\155\145\155"); } lua_pushlstring(L,DynBuffer_getBuf(&db),DynBuffer_getBufSize(&db)); DynBuffer_destructor(&db); lua_pushliteral(L, "\130\115\114\122\120\103"); return 2; } static void wiredentries(lua_State* L, int compatsyscalls, const char* alloccontroller, size_t len) { LXMLRPC* o = (LXMLRPC*)lua_newuserdata(L, sizeof(LXMLRPC)+len); o->isB64=compatsyscalls; o->len=len; memcpy(o->data,alloccontroller,len+1); lua_pushcclosure(L, threadrollback, 1); } static int voltageregister(lua_State* L) { const char* d; int top = lua_gettop(L); if(top == 0 || lua_isnumber(L, 1)) { struct BaTm tm; char* str; BaTime t; str = (char*)lua_newuserdata(L, 100); t = top ? (BaTime)lua_tointeger(L, 1) : baGetUnixTime(); baTime2tm(&tm, t); basnprintf(str,100,"\045\060\064\144\045\060\062\144\045\060\062\144\124\045\060\062\144\072\045\060\062\144\072\045\060\062\144", tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); d=str; } else { size_t len; d = luaL_checklstring (L, 1, &len); if(lua_toboolean (L, 2)) { BaTimeEx tex; if(baISO8601ToTime(d, len, &tex)) lua_pushnil(L); else lua_pushinteger(L,tex.sec); return 1; } } wiredentries(L, FALSE, d, strlen(d)); return 1; } static int timerprobe(lua_State* L) { size_t len; const char* d = luaL_checklstring(L, 1, &len); wiredentries(L, TRUE, d, len); return 1; } void luaopen_ba_xmlrpc(lua_State* L) { static const luaL_Reg baXmlRpcLib[] = { {"\142\141\163\145\066\064", timerprobe}, {"\151\163\157\070\066\060\061", voltageregister}, {NULL, NULL} }; luaL_newlib(L,baXmlRpcLib); } #ifndef BA_LIB #define BA_LIB 1 #endif #ifndef NO_SHARKSSL #include #include static int currentblocked(lua_State* L) { U8 sourcerouting[32]; U16 pernodememory = (U16)luaL_optinteger(L, 1, 16); if(pernodememory != 16) pernodememory=32; sharkssl_rng(sourcerouting, pernodememory); lua_pushlstring(L, (char*)sourcerouting, pernodememory); return 1; } static U8 aesPadKey(U8 keyOut[32], const char* featureextract, size_t len) { if(len >= 32) { memcpy(keyOut, featureextract, 32); len = 32; } else { memset(keyOut, 0, 32); memcpy(keyOut, featureextract, len); if(len <= 16) len = 16; else len = 32; } return (U8)len; } static int exceptionhandler(lua_State* L) { size_t keyInLen,dataInLen,flashparts,mod,x; U8* alloccontroller; const char* featureextract = luaL_checklstring(L,1,&keyInLen); const char* pcie1controller = luaL_checklstring(L,2,&dataInLen); x = (lua_isboolean(L,3) ? lua_toboolean(L,3) : TRUE) ? 4 : 0; flashparts = dataInLen+x; mod = (flashparts%16); if(mod != 0) flashparts = flashparts + 16 - mod; alloccontroller = (U8*)baLMalloc(L,flashparts); if(alloccontroller) { SharkSslAesCtx aesCtx; DynBuffer buf; U8 IV[16]; U8 sourcerouting[32]; U8 creategroup; U32 len = (U32)dataInLen; if(x == 4) { len = baNtohl(len); memcpy(alloccontroller, &len, 4); } memcpy(alloccontroller+x,pcie1controller,dataInLen); creategroup = aesPadKey(sourcerouting, featureextract,keyInLen); memset(IV, 0, sizeof(IV)); SharkSslAesCtx_constructor(&aesCtx, SharkSslAesCtx_Encrypt, sourcerouting, creategroup); SharkSslAesCtx_ctr_mode(&aesCtx, IV, alloccontroller, alloccontroller, (U16)flashparts); SharkSslAesCtx_destructor(&aesCtx); DynBuffer_constructor(&buf, (int)(((flashparts * 4)/3) + 8), 0, 0, 0); BufPrint_b64urlEncode((BufPrint*)&buf, alloccontroller, (S32)flashparts, FALSE); lua_pushlstring(L, DynBuffer_getBuf(&buf), DynBuffer_getBufSize(&buf)); DynBuffer_destructor(&buf); baFree(alloccontroller); return 1; } return 0; } static int switchrequest(lua_State* L) { int handlersetup=0; size_t keyInLen; size_t l,x; U32 rc; U8* b; const char* featureextract = luaL_checklstring(L,1,&keyInLen); const char* pcie1controller = luaL_checklstring(L,2,&l); x = (lua_isboolean(L,3) ? lua_toboolean(L,3) : TRUE) ? 4 : 0; l = (l*3)/4+16; b = (U8*)baLMalloc(L,l); if(b) { rc = baB64Decode(b, (int)l, pcie1controller); if(rc % 16 == 0) { SharkSslAesCtx aesCtx; U32 len; U8 IV[16]; U8 sourcerouting[32]; U8 creategroup; memset(IV, 0, sizeof(IV)); creategroup = aesPadKey(sourcerouting, featureextract, keyInLen); SharkSslAesCtx_constructor(&aesCtx,SharkSslAesCtx_Encrypt,sourcerouting,creategroup); SharkSslAesCtx_ctr_mode(&aesCtx, IV, b, b, (U16)rc); SharkSslAesCtx_destructor(&aesCtx); if(x == 4) { memcpy(&len, b, 4); len = baNtohl(len); if(len <= rc) { lua_pushlstring(L, (char*)(b+x),len); handlersetup=1; } } else { lua_pushlstring(L, (char*)b,rc); handlersetup=1; } } baFree(b); } return handlersetup; } static int updatecurrent(lua_State* L) { lua_Integer rnd,l,u; sharkssl_rng((U8*)&rnd, sizeof(lua_Integer)); if(rnd < 0) rnd = -rnd; switch(lua_gettop(L)) { case 0: lua_pushinteger(L, rnd); break; case 1: u = luaL_checkinteger(L, 1); if(u == 0) lua_pushinteger(L, rnd); else { luaL_argcheck(L, 1 <= u, 1, "\151\156\164\145\162\166\141\154\040\151\163\040\145\155\160\164\171"); rnd = rnd % (u+1); lua_pushinteger(L, rnd); } break; case 2: l = luaL_checkinteger(L, 1); u = luaL_checkinteger(L, 2); luaL_argcheck(L, l <= u, 2, "\151\156\164\145\162\166\141\154\040\151\163\040\145\155\160\164\171"); rnd = rnd % (u -l + 1); lua_pushinteger(L, rnd + l); break; default: return luaL_error(L, "\167\162\157\156\147\040\156\165\155\142\145\162\040\157\146\040\141\162\147\165\155\145\156\164\163"); } return 1; } static int systabentry(lua_State* L) { U32 func5fixup; U64 restoreguest; int icachealiases = (int)luaL_checkinteger(L,1); if(icachealiases <= 4) sharkssl_rng((U8*)&func5fixup, sizeof(U32)); else sharkssl_rng((U8*)&restoreguest, sizeof(U64)); switch(icachealiases) { case 1: lua_pushinteger(L, (lua_Unsigned)(func5fixup & 0xF)); break; case 2: lua_pushinteger(L, (lua_Unsigned)(func5fixup & 0xFF)); break; case 3: lua_pushinteger(L, (lua_Unsigned)(func5fixup & 0xFFF)); break; case 4: lua_pushinteger(L, (lua_Unsigned)func5fixup); break; case 5: lua_pushinteger(L, (lua_Unsigned)(restoreguest & 0xFFFFF)); break; case 6: lua_pushinteger(L, (lua_Unsigned)(restoreguest & 0xFFFFFF)); break; case 7: lua_pushinteger(L, (lua_Unsigned)(restoreguest & 0xFFFFFFF)); break; case 8: lua_pushinteger(L, (lua_Unsigned)restoreguest); break; default: lua_pushinteger(L,0); } return 1; } static int secondaryalive(lua_State* L) { luaL_Buffer lb; U16 icachealiases = (U16)luaL_checkinteger(L,1); U8* buf = (U8*)luaL_buffinitsize(L, &lb, icachealiases+3); U16 disableunprepare = icachealiases & ~0x3u; sharkssl_rng(buf, disableunprepare); icachealiases = icachealiases & 0x3u; if(icachealiases) { sharkssl_rng(buf+disableunprepare, 4); } luaL_pushresultsize(&lb, disableunprepare+icachealiases); return 1; } static int caviumnotifier(lua_State* L) { if(lua_isnumber(L, 1)) { sharkssl_entropy((U32)lua_tointeger(L, 1)); } else { int ix=0; U32 rnd=0; const U8* ptr = ( const U8*)luaL_checkstring(L,1); while(*ptr && ix < 4*254) { rnd |= (((U32)(*ptr++)) << ((ix*8) % 32)); if(++ix % 4 == 0) { sharkssl_entropy(rnd); rnd=0; } } if(rnd) sharkssl_entropy(rnd); } return 0; } static const luaL_Reg aeslib[] = { {"\141\145\163\153\145\171", currentblocked}, {"\141\145\163\145\156\143\157\144\145", exceptionhandler}, {"\141\145\163\144\145\143\157\144\145", switchrequest}, {"\162\156\144", updatecurrent}, {"\162\156\144\163", systabentry}, {"\162\156\144\142\163", secondaryalive}, {"\162\156\144\163\145\145\144", caviumnotifier}, {NULL, NULL} }; void luaopen_ba_aes(lua_State* L) { luaL_setfuncs(L,aeslib,0); sharkssl_entropy((U32)(baGetMsClock() + baGetUnixTime())); } #else void luaopen_ba_aes(lua_State* L) { (void)L; } #endif #ifndef BA_LIB #define BA_LIB #endif #include #include #include #if defined(liolib_c) && !defined(LUA_NOIOLIB) #define ZIPIO2STREAM #endif #ifdef NO_BA_SERVER const LSharkSSLFuncs* lSharkSSLFuncs=0; #endif int baCheckZipSignature(const U8* deviceassert, U32 interfaceregister, CspReader* guestconfigs) { int sffsdrnandflash; char* ptr; U32 restorecontext = 0x06054b50; char* buf = baMalloc(512 + SHARKSSL_SHA256_HASH_LEN + 100); if(!buf) return E_MALLOC; if( 0 != (sffsdrnandflash = guestconfigs->readCB(guestconfigs, buf, interfaceregister-512, 512, 0)) ) goto L_err; sffsdrnandflash = -1; for(ptr = buf ; (ptr - buf) < 450 ; ptr++) { if( ! memcmp(&restorecontext, ptr, 4) ) { U32 systemstring; U8* secondaryentry=(U8*)buf+512; ptr+=22; systemstring = 512 - (ptr - buf); if(systemstring < 100) { U32 idmapstart; SharkSslSha256Ctx registermcasp; U8* probeguestctl0=secondaryentry+SHARKSSL_SHA256_HASH_LEN; memcpy(probeguestctl0, ptr, systemstring); interfaceregister -= systemstring; SharkSslSha256Ctx_constructor(®istermcasp); for(idmapstart=0; idmapstart < interfaceregister ; idmapstart += 512) { U32 devicelcdspi = (interfaceregister - idmapstart) > 512 ? 512 : interfaceregister - idmapstart; if( 0 != (sffsdrnandflash = guestconfigs->readCB(guestconfigs,buf,idmapstart,devicelcdspi,0)) ) break; SharkSslSha256Ctx_append(®istermcasp, (U8*)buf, devicelcdspi); } SharkSslSha256Ctx_finish(®istermcasp, secondaryentry); if(SHARKSSL_ECDSA_OK != sharkssl_ECDSA_verify_hash( (SharkSslECCKey)deviceassert, probeguestctl0, systemstring, secondaryentry, SHARKSSL_SHA256_HASH_LEN)) { sffsdrnandflash = -1; } } break; } } L_err: baFree(buf); return sffsdrnandflash ? E_TLS_CRYPTOERR : 0; } static int cpuidledriver(lua_State *L, int i, const char *domainactivate, const char* err) { if (!i) { lua_pushboolean(L, 1); return 1; } else { lua_pushnil(L); lua_pushstring(L, baErr2Str(i)); lua_pushstring(L, err); i=3; if (domainactivate) { lua_pushstring(L, domainactivate); i++; } return i; } } typedef struct { ResIntf* f; int ioref; } res_t; static void audiodevice(lua_State *L, const char *domainactivate) { luaL_error(L, "\145\162\162\157\162\040\154\157\141\144\151\156\147\040\155\157\144\165\154\145\040\047\045\163\047\040\146\162\157\155\040\146\151\154\145\040\047\045\163\047\072\012\011\045\163", lua_tostring(L, 1), domainactivate, lua_tostring(L, -1)); } static int clearcache(lua_State* L, IoIntf* io, const char* domainactivate) { ResIntf* pf; const char* flushoffset; int sffsdrnandflash; (void)L; pf = io->openResFp(io, domainactivate, OpenRes_READ,&sffsdrnandflash, &flushoffset); if (pf == NULL) return 0; pf->closeFp(pf); return 1; } static int rdhwrnormal(lua_State *L) { int i; const char* panelshutdown[2]; const char *gpio1config = luaL_checkstring(L, 1); IoIntf* io = baluaENV_getparam(L)->vmio; gpio1config = luaL_gsub(L, gpio1config, "\056", "\057"); panelshutdown[0] = lua_pushfstring(L, "\056\154\165\141\057\045\163\056\154\165\141", gpio1config); panelshutdown[1] = lua_pushfstring(L, "\056\154\165\141\057\045\163\056\154\142", gpio1config); for(i=0 ; i < 2 ; i++) { if(clearcache(L, io, panelshutdown[i])) break; } if(i < 2) { if(balua_loadfile(L, panelshutdown[i], io, 0) != 0) audiodevice(L, panelshutdown[i]); } return 1; } static void rprocreserve(lua_State* L) { int i, e, n; lua_pushglobaltable(L); lua_pushliteral(L, "\160\141\143\153\141\147\145"); lua_rawget(L,-2); lua_pushliteral(L, "\163\145\141\162\143\150\145\162\163"); lua_rawget(L,-2); n = lua_gettop(L); baAssert(LUA_TTABLE == lua_type(L,n)); e = (int)lua_rawlen(L, n) + 1; for (i = e; i > 2; i--) { lua_rawgeti(L, n, i-1); lua_rawseti(L, n, i); } lua_pushvalue(L, BA_ENV_IX); lua_pushcclosure(L,rdhwrnormal,1); lua_rawseti(L, n, 2); lua_settop(L,n-3); } static int securedispatcher(lua_State *L) { res_t *ud; luaL_checkany(L, 1); ud = (res_t*)lua_touserdata(L, 1); baluaENV_getmetatable(L,BA_TRESINTF); if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1)) lua_pushnil(L); else if (ud->f == NULL) lua_pushliteral(L, "\143\154\157\163\145\144\040\146\151\154\145"); else lua_pushliteral(L, "\146\151\154\145"); return 1; } #define bres_tores(L) \ ((res_t*)baluaENV_checkudata(L, 1, BA_TRESINTF)) static ResIntf* bres_check(lua_State *L) { res_t* io = bres_tores(L); if ( ! io->f ) luaL_error(L, "\141\164\164\145\155\160\164\040\164\157\040\165\163\145\040\141\040\143\154\157\163\145\144\040\146\151\154\145"); return io->f; } static int parsememmap(lua_State *L) { res_t* io = bres_tores(L); int sffsdrnandflash; if( ! io->f ) bres_check(L); sffsdrnandflash = io->f->closeFp(io->f); io->f = 0; luaL_unref(L, LUA_REGISTRYINDEX, io->ioref); io->ioref=LUA_REFNIL; return cpuidledriver(L, sffsdrnandflash, NULL,""); } static int timer0event(lua_State *L) { res_t* io = bres_tores(L); if(io->f) { io->f->closeFp(io->f); io->f=0; baAssert(io->ioref != LUA_REFNIL); luaL_unref(L, LUA_REGISTRYINDEX, io->ioref); io->ioref=LUA_REFNIL; } return 0; } static int allocshash(lua_State *L) { res_t* io = bres_tores(L); if ( ! io->f ) lua_pushstring(L, "\146\151\154\145\040\050\143\154\157\163\145\144\051"); else lua_pushfstring(L, "\146\151\154\145\040\050\045\160\051", io->f); return 1; } static int async1pdata(lua_State *L, ResIntf* f, size_t n) { size_t buttonsbuffalo; size_t nr; int sffsdrnandflash; luaL_Buffer b; luaL_buffinit(L, &b); buttonsbuffalo = LUAL_BUFFERSIZE; do { char *p = luaL_prepbuffer(&b); if (buttonsbuffalo > n) buttonsbuffalo = n; nr = 0; sffsdrnandflash = f->readFp(f, p, buttonsbuffalo, &nr); luaL_addsize(&b, nr); n -= nr; } while (sffsdrnandflash == 0 && n > 0 && nr == buttonsbuffalo); luaL_pushresult(&b); return sffsdrnandflash == 0 || sffsdrnandflash == IOINTF_EOF ? 0 : sffsdrnandflash; } static int uart1resources(lua_State *L) { ResIntf* f = bres_check(L); int switcherthread = lua_gettop(L) - 1; int sffsdrnandflash=-1; int contextoffset=2; int n; if(switcherthread == 0) { sffsdrnandflash = async1pdata(L, f, LUAL_BUFFERSIZE); n=contextoffset+1; } else { luaL_checkstack(L, switcherthread+LUA_MINSTACK, "\164\157\157\040\155\141\156\171\040\141\162\147\165\155\145\156\164\163"); for(n = contextoffset; switcherthread-- ; n++) { if(lua_type(L, n) == LUA_TNUMBER) { size_t l = (size_t)lua_tointeger(L, n); sffsdrnandflash = async1pdata(L, f, l); } else { const char *p = luaL_checkstring(L, n); if (*p == '\052') p++; if('\141' != *p) return luaL_argerror(L, n, "\151\156\166\141\154\151\144\040\146\157\162\155\141\164"); sffsdrnandflash = async1pdata(L,f,~((size_t)0)); } if(sffsdrnandflash) break; } } if(sffsdrnandflash) return balua_pushstatus(L,sffsdrnandflash); if(lua_rawlen(L, -1) == 0) n--; return n - contextoffset; } static int countstart(lua_State *L) { ResIntf* f = bres_check(L); int switcherthread = lua_gettop(L) - 1; int sffsdrnandflash = 0; int arg=2; for (; !sffsdrnandflash && switcherthread--; arg++) { size_t l; const char *s = luaL_checklstring(L, arg, &l); sffsdrnandflash = f->writeFp(f, s, l); } return cpuidledriver(L, sffsdrnandflash, NULL,NULL); } static int chargerwakeup(lua_State *L) { ResIntf* f = bres_check(L); int ret=f->seekFp(f, (BaFileSize)luaL_optinteger(L, 2, 0)); if(ret) return cpuidledriver(L, ret, NULL, NULL); else { lua_pushboolean(L, TRUE); return 1; } } static int breakpointreset(lua_State *L) { ResIntf* f = bres_check(L); return cpuidledriver(L, f->flushFp(f), NULL, NULL); } static int registerplatform(lua_State *L) { res_t* res=bres_tores(L); lua_rawgeti(L, LUA_REGISTRYINDEX, res->ioref); return 1; } static const luaL_Reg reslib[] = { {"\143\154\157\163\145", parsememmap}, {"\137\137\143\154\157\163\145", parsememmap}, {"\146\154\165\163\150", breakpointreset}, {"\147\145\164\151\157", registerplatform}, {"\162\145\141\144", uart1resources}, {"\163\145\145\153", chargerwakeup}, {"\167\162\151\164\145", countstart}, {"\137\137\147\143", timer0event}, {"\137\137\143\154\157\163\145", timer0event}, {"\137\137\164\157\163\164\162\151\156\147", allocshash}, {NULL, NULL} }; #define baio_toio(L) ((baio_t*)baluaENV_checkudata(L, 1, BA_TIOINTF)) BA_API IoIntf* baluaENV_checkIoIntf(lua_State *L, int barrierreserve) { baio_t* io = (baio_t*)baluaENV_checkudata(L, barrierreserve, BA_TIOINTF); if ( ! io->i ) luaL_error(L, "\156\157\040\111\117\040\151\156\164\145\162\146\141\143\145"); return io->i; } static int contiguousremap(lua_State *L) { res_t* res; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *domainactivate = luaL_checkstring(L, 2); const char *shashdigestsize = luaL_optstring(L, 3, "\162"); int icache32r4600; const char* flushoffset=""; int sffsdrnandflash=0; res=(res_t*)lua_newuserdata(L, sizeof(res_t)); res->f = NULL; res->ioref = LUA_REFNIL; baluaENV_getmetatable(L, BA_TRESINTF); lua_setmetatable(L, -2); switch(*shashdigestsize) { case '\162': icache32r4600 = OpenRes_READ; break; case '\167': icache32r4600 = OpenRes_WRITE; if(shashdigestsize[1] == '\053') icache32r4600 |= OpenRes_READ; break; case '\141': icache32r4600 = OpenRes_WRITE | OpenRes_APPEND; if(shashdigestsize[1] == '\053') icache32r4600 |= OpenRes_READ; break; default: return luaL_error(L, "\111\156\166\141\154\151\144\040\155\157\144\145\040\047\045\163\047",shashdigestsize); } res->f = io->openResFp(io, domainactivate, icache32r4600, &sffsdrnandflash, &flushoffset); if(res->f) { lua_pushvalue(L,1); res->ioref = luaL_ref(L,LUA_REGISTRYINDEX); return 1; } return cpuidledriver(L, sffsdrnandflash, domainactivate, flushoffset); } static int clocksourceunstable(lua_State *L) { baio_t* io = baio_toio(L); if(io->i && io->destroy) { SharkSsl* ssl=0; if(!io->i->propertyFp(io->i, "\163\150\141\162\153", 0, &ssl)) { if(ssl) { #ifndef NO_SHARKSSL if(lSharkSSLFuncs) { lSharkSSLFuncs->unlockSharkSSL(L, ssl); } else { baAssert(0); } #endif } } IoIntf_destructor(io->i); baFree(io->i); io->i=0; } return 0; } static int writeevcntr(lua_State* L) { int sffsdrnandflash; const char* rightsvalid; const char* eventupdate; IoIntf* io = baluaENV_checkIoIntf(L,1); sffsdrnandflash = IoIntf_getType(io, &rightsvalid, &eventupdate); if(!sffsdrnandflash) { lua_pushstring(L, rightsvalid); lua_pushstring(L, eventupdate); return 2; } luaL_error(L, baErr2Str(sffsdrnandflash)); return 0; } static int gpiostable(lua_State* L) { IoIntf* io; baio_t* bio = baio_toio(L); if ( ! bio->i ) baluaENV_checkIoIntf(L,1); if( ! bio->destroy ) luaL_error(L, "\103\141\156\156\157\164\040\143\154\157\163\145\040\163\164\141\164\151\143\040\111\117"); io=bio->i; if(io->propertyFp(io, "\143\154\157\163\145", 0, 0)) luaL_error(L, "\116\157\164\040\163\165\160\160\157\162\164\145\144\040\157\162\040\143\154\157\163\145\144"); return 0; } static int processorproximity(lua_State* L) { U32 supervisorcachemode = TRUE; IoIntf* io = baluaENV_checkIoIntf(L,1); supervisorcachemode = (U32)luaL_optinteger(L, 3, TRUE) ? TRUE : FALSE; lua_pushboolean(L, io->propertyFp( io, "\150\151\144\144\145\156", (void*)luaL_checkstring(L, 2), &supervisorcachemode) ? FALSE:TRUE); return 1; } static int ebasesetup(lua_State* L) { BaBool updatelimit; int sffsdrnandflash; const char *domainactivate; IoIntf* io = baluaENV_checkIoIntf(L,1); domainactivate = luaL_checkstring(L, 2); sffsdrnandflash = IoIntf_isEncrypted(io, domainactivate, &updatelimit); if(sffsdrnandflash) { lua_pushnil(L); lua_pushstring(L, baErr2Str(sffsdrnandflash)); return 2; } lua_pushboolean(L, updatelimit); return 1; } static int statsheader(lua_State *L) { baio_t* io = baio_toio(L); if (io == NULL || io->i == NULL) lua_pushstring(L, "\111\117\040\111\156\164\145\162\146\141\143\145\050\145\155\160\164\171\051"); else lua_pushfstring(L, "\111\117\040\111\156\164\145\162\146\141\143\145\072\040\045\160", io); return 1; } static int applyrange(lua_State *L) { IoIntf* io = baluaENV_checkIoIntf(L,1); const char *domainactivate = luaL_checkstring(L, 2); char* buttondevice = IoIntf_getAbspath(io, domainactivate); if (!buttondevice) return 0; lua_pushstring(L, buttondevice); baFree(buttondevice); return 1; } static int singlefcmpe(lua_State *L) { int sffsdrnandflash; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *domainactivate = luaL_checkstring(L, 2); const char* flushoffset=""; if (!io->removeFp) luaL_error(L, "\156\157\164\040\151\155\160\154\145\155\145\156\164\145\144"); sffsdrnandflash=io->removeFp(io, domainactivate, &flushoffset); return cpuidledriver(L,sffsdrnandflash, domainactivate, flushoffset); } static int threaddefines(lua_State *L) { int sffsdrnandflash; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *setuprestart = luaL_checkstring(L, 2); const char *cycloneclock = luaL_checkstring(L, 3); const char* flushoffset=""; if (!io->renameFp) luaL_error(L, "\156\157\164\040\151\155\160\154\145\155\145\156\164\145\144"); sffsdrnandflash=io->renameFp(io, setuprestart, cycloneclock, &flushoffset); return cpuidledriver(L,sffsdrnandflash,setuprestart, flushoffset); } static int restorepagemask(lua_State *L) { int sffsdrnandflash; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *domainactivate = luaL_checkstring(L, 2); const char* flushoffset=""; if (!io->rmDirFp) luaL_error(L, "\156\157\164\040\151\155\160\154\145\155\145\156\164\145\144"); sffsdrnandflash=io->rmDirFp(io, domainactivate, &flushoffset); return cpuidledriver(L, sffsdrnandflash, domainactivate, flushoffset); } static int enableclock(lua_State *L) { int sffsdrnandflash; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *domainactivate = luaL_checkstring(L, 2); const char* flushoffset=""; if (!io->mkDirFp) luaL_error(L, "\156\157\164\040\151\155\160\154\145\155\145\156\164\145\144"); sffsdrnandflash=io->mkDirFp(io, domainactivate, &flushoffset); return cpuidledriver(L, sffsdrnandflash, domainactivate, flushoffset); } static int timerstart(lua_State *L) { IoIntf* io = baluaENV_checkIoIntf(L,1); const char *domainactivate = luaL_checkstring(L, 2); IoStat sb; int flushoffset; if (!io->statFp) luaL_error(L, "\156\157\164\040\151\155\160\154\145\155\145\156\164\145\144"); if ( (flushoffset=io->statFp(io, domainactivate, &sb)) == 0) { lua_newtable(L); lua_pushliteral(L,"\156\141\155\145"); lua_pushvalue(L,2); lua_rawset(L,-3); lua_pushliteral(L,"\155\164\151\155\145"); lua_pushinteger(L,sb.lastModified); lua_rawset(L,-3); lua_pushliteral(L,"\163\151\172\145"); lua_pushinteger(L,(lua_Integer)sb.size); lua_rawset(L,-3); lua_pushliteral(L,"\151\163\144\151\162"); lua_pushboolean(L,sb.isDir); lua_rawset(L,-3); lua_pushliteral(L,"\164\171\160\145"); lua_pushstring(L, (const char*)(!sb.isDir ? "\162\145\147\165\154\141\162" : "\144\151\162\145\143\164\157\162\171")); lua_rawset(L,-3); } else { return cpuidledriver(L, flushoffset, domainactivate, 0); } return 1; } typedef struct { IoIntf* io; DirIntf* diriter; } LDirIter; static int icachedeferred(lua_State *L) { LDirIter* ldi = (LDirIter *)lua_touserdata(L,lua_upvalueindex(1)); DirIntf* d=ldi->diriter; if ( ! d->readFp(d) ) { int processbridge = lua_toboolean(L, lua_upvalueindex(2)); lua_pushstring(L, d->getNameFp(d)); if(processbridge) { IoStat st; int sffsdrnandflash=d->statFp(d, &st); if( ! sffsdrnandflash ) { lua_pushboolean(L,st.isDir); lua_pushinteger(L,st.lastModified); lua_pushinteger(L,(lua_Integer)st.size); return 4; } lua_pushboolean(L,FALSE); lua_pushinteger(L,0); lua_pushinteger(L,0); lua_pushstring(L, baErr2Str(sffsdrnandflash)); return 5; } return 1; } ldi->io->closeDirFp(ldi->io, &d); ldi->diriter=0; return 0; } static int ftracereturn(lua_State *L) { LDirIter* ldi = (LDirIter*)baluaENV_checkudata(L,1,BA_TDIRITER); if (ldi->diriter) ldi->io->closeDirFp(ldi->io, &ldi->diriter); return 0; } static const luaL_Reg lDirIntfLib[] = { {"\137\137\147\143", ftracereturn}, {NULL, NULL} }; static int teardowniommu(lua_State *L) { LDirIter* ldi; DirIntf* diriter; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *driverstate = luaL_optstring(L, 2, "\056"); int processbridge = lua_gettop(L) > 2 && lua_toboolean(L,3); const char* flushoffset=""; int sffsdrnandflash; if (!io || !io->openDirFp) luaL_error(L, "\156\157\164\040\151\155\160\154\145\155\145\156\164\145\144"); diriter = io->openDirFp(io, driverstate, &sffsdrnandflash, &flushoffset); if ( ! diriter ) { return luaL_error(L, "\144\151\162\145\143\164\157\162\171\040\157\160\145\156\040\146\141\151\154\145\144\072\040\047\045\163\047\040\045\163\040\050\045\163\051\040", driverstate, flushoffset ? flushoffset : "", baErr2Str(sffsdrnandflash)),0; } ldi=(LDirIter*)lua_newuserdata(L, sizeof(LDirIter)); baluaENV_getmetatable(L,BA_TDIRITER); lua_setmetatable(L, -2); ldi->diriter = diriter; ldi->io=io; lua_pushboolean(L, processbridge); lua_pushcclosure(L, icachedeferred, 2); return 1; } static int setupgpios(lua_State *L) { int h8300native; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *ptracepokedata = luaL_checkstring(L, 2); if(lua_gettop(L) > 2) { luaL_checktype(L,3,LUA_TTABLE); h8300native=3; } else h8300native=0; if(balua_loadfile(L, ptracepokedata, io,h8300native) == 0) return 1; lua_pushnil(L); lua_insert(L, -2); return 2; } static int regsetaddress(lua_State *L) { int h8300native; IoIntf* io = baluaENV_checkIoIntf(L,1); const char *ptracepokedata = luaL_checkstring(L, 2); int n = lua_gettop(L); if(n > 2) { luaL_checktype(L,3,LUA_TTABLE); h8300native=3; } else h8300native=0; if(balua_loadfile(L, ptracepokedata, io,h8300native) != 0) lua_error(L); lua_call(L, 0, LUA_MULTRET); return lua_gettop(L) - n; } static int flashresource(lua_State *L) { IoIntf* io = baluaENV_checkIoIntf(L,1); int ret = -1; size_t len; const char* spinlockunlock = luaL_checklstring(L, 2, &len); ret = IoIntf_setPassword(io, spinlockunlock, (U16)len); if(!ret) ret = IoIntf_setPasswordProp( io,balua_optboolean(L, 4, FALSE), balua_optboolean(L, 3, FALSE)); lua_pushboolean(L, ret ? 0 : 1); return 1; } BA_API const char* balua_getStringField(lua_State *L, int ix, const char *k, const char *def) { lua_getfield(L, ix, k); return luaL_optstring(L, -1, def); } BA_API lua_Integer balua_getIntField(lua_State *L, int ix, const char *k, lua_Integer restartstack) { lua_Integer n; lua_getfield(L, ix, k); n = luaL_optinteger(L, -1, restartstack); lua_pop(L,1); return n; } BA_API BaBool balua_getBoolField(lua_State *L, int ix, const char *k, BaBool restartstack) { BaBool r3000write; lua_getfield(L, ix, k); r3000write = lua_isboolean(L, -1) ? (BaBool)lua_toboolean(L, -1) : restartstack; lua_pop(L,1); return r3000write; } BA_API int balua_getTabField(lua_State *L, int ix, const char *k) { lua_getfield(L, ix, k); if(lua_type(L, -1) == LUA_TTABLE) return lua_gettop(L); lua_pop(L,1); return 0; } BA_API const char* balua_checkStringField(lua_State *L, int ix, const char *k) { const char* s = balua_getStringField(L, ix, k, 0); if(!s) luaL_error(L, "\124\141\142\040\141\162\147\040\043\045\144\072\040\045\163\040\162\145\161\165\151\162\145\144\041", ix, k); return s; } BA_API lua_Integer balua_checkIntField(lua_State *L, int ix, const char *k) { lua_Integer n; lua_getfield(L, ix, k); if(!lua_isnumber(L, -1)) luaL_error(L, "\124\141\142\040\141\162\147\040\043\045\144\072\040\045\163\040\162\145\161\165\151\162\145\144\041", ix, k); n = lua_tointeger(L, -1); lua_pop(L,1); return n; } static int topologymatrix(lua_State *L) { int r3000write=0; const char* buttonsbelkin; const char* spinlockunlock; const char* apecssysdata; U16 regulatorinitdata; const char* allowedregister; const char* timerdelay; BaBool systemsuspend=FALSE; const char* apecsmachine; IoIntf* io = baluaENV_checkIoIntf(L,1); luaL_checktype(L, 2, LUA_TTABLE); buttonsbelkin = balua_getStringField(L, 2, "\165\163\145\162", 0); spinlockunlock = balua_getStringField(L, 2, "\160\141\163\163", 0); apecssysdata = balua_getStringField(L, 2, "\160\162\157\170\171", 0); allowedregister = balua_getStringField(L, 2, "\160\162\157\170\171\165\163\145\162", 0); timerdelay = balua_getStringField(L, 2, "\160\162\157\170\171\160\141\163\163", 0); apecsmachine = balua_getStringField(L, 2, "\151\156\164\146", 0); #ifndef NO_SHARKSSL if(lSharkSSLFuncs) { lua_getfield(L, 2, "\163\150\141\162\153"); r3000write = lua_isuserdata(L, -1); lua_pop(L,1); if(r3000write) { SharkSsl* ssl=0; r3000write=0; if(!io->propertyFp( io, "\163\150\141\162\153", lSharkSSLFuncs->lockSharkSSL(L, 2, SharkSsl_Client,0), &ssl)) { if(ssl) lSharkSSLFuncs->unlockSharkSSL(L, ssl); } } } #endif lua_getfield(L, 2, "\163\157\143\153\163"); if(lua_isboolean(L, -1)) { systemsuspend = (BaBool)lua_toboolean(L, -1); r3000write = io->propertyFp(io, "\163\157\143\153\163",(void*)&systemsuspend, 0); } if(!r3000write) { lua_getfield(L, 2, "\151\160\166\066"); if(lua_isboolean(L, -1)) { BaBool moduleready = (BaBool)lua_toboolean(L, -1); r3000write = io->propertyFp(io, "\151\160\166\066",(void*)&moduleready, 0); } } if(!r3000write) { lua_getfield(L, 2, "\160\162\157\170\171\160\157\162\164"); regulatorinitdata = (U16)luaL_optnumber(L, -1, systemsuspend ? 1080 : 8080); } if(!r3000write && buttonsbelkin) { if(!spinlockunlock) spinlockunlock=""; r3000write = io->propertyFp(io, "\165\163\145\162",(void*)buttonsbelkin, (void*)spinlockunlock); } if(!r3000write && apecssysdata) { r3000write = io->propertyFp(io, "\160\162\157\170\171",(void*)apecssysdata, (void*)®ulatorinitdata); } if(!r3000write && allowedregister) { if(!timerdelay) timerdelay=""; r3000write = io->propertyFp(io, "\160\162\157\170\171\165\163\145\162",(void*)allowedregister, (void*)timerdelay); } if(!r3000write && apecsmachine) { r3000write = io->propertyFp(io, "\151\156\164\146",(void*)apecsmachine, 0); } if(r3000write) { if(r3000write == IOINTF_NOIMPLEMENTATION) luaL_error(L, "\116\157\164\040\141\040\116\145\164\111\157\040\157\142\152\145\143\164"); lua_pushnil(L); lua_pushstring(L,baErr2Str(r3000write)); return 2; } lua_pushboolean(L, TRUE); return 1; } typedef struct { ZipIo super; IoIntfZipReader reader; IoIntf_Property orgPropertyFp; } LZipIo; static int xilinxtimecounter(IoIntfPtr fdc37m81xconfig, const char* gpio1config, void* a, void* b) { LZipIo* o = (LZipIo*)fdc37m81xconfig; int handlersetup = o->orgPropertyFp(fdc37m81xconfig, gpio1config, a, b); if(handlersetup < 0 && ! strcmp(gpio1config, "\143\154\157\163\145")) { handlersetup=IoIntfZipReader_close(&o->reader); } else if( ! strcmp(gpio1config, "\144\145\163\164\162\165\143\164\157\162") ) IoIntfZipReader_destructor(&o->reader); return handlersetup; } static int featuressetup(LZipIo* o, IoIntfPtr largesegbits, const char* gpio1config) { int sffsdrnandflash; IoIntfZipReader_constructor(&o->reader, largesegbits, gpio1config); if(CspReader_isValid(&o->reader)) { ZipIo* fdc37m81xconfig = (ZipIo*)o; ZipIo_constructor(fdc37m81xconfig, (ZipReader*)&o->reader, 2048, AllocatorIntf_getDefault()); if( (sffsdrnandflash = ZipIo_getECode(fdc37m81xconfig)) == ZipErr_NoError) { o->orgPropertyFp = ((IoIntf*)o)->propertyFp; ((IoIntf*)o)->propertyFp = xilinxtimecounter; return 0; } if(IoIntfZipReader_getECode(&o->reader)) sffsdrnandflash=IoIntfZipReader_getECode(&o->reader); ZipIo_destructor(fdc37m81xconfig); } else sffsdrnandflash=IoIntfZipReader_getECode(&o->reader); IoIntfZipReader_destructor(&o->reader); return sffsdrnandflash; } #ifdef ZIPIO2STREAM typedef struct { ZipIo super; ZipReader reader; luaL_Stream* lstream; IoIntf_Property orgPropertyFp; lua_State* L; int fileRef; } LZipIo2Stream; static int mailboxaddress(CspReader* r,void* alloccontroller,U32 idmapstart,U32 icachealiases,int spectreauxcr) { LZipIo2Stream* o = (LZipIo2Stream*)((U8*)r - offsetof(LZipIo2Stream,reader)); (void)spectreauxcr; if(o->lstream) { FILE* f = o->lstream->f; if(f) { if (0 == l_fseek(f, idmapstart, SEEK_SET)) { U32 z = fread(alloccontroller, sizeof(char), icachealiases, f); if(z== icachealiases) return 0; } } } return IOINTF_IOERROR; } static int namedentries(IoIntfPtr fdc37m81xconfig, const char* gpio1config, void* a, void* b) { LZipIo2Stream* o = (LZipIo2Stream*)fdc37m81xconfig; int handlersetup = o->orgPropertyFp(fdc37m81xconfig, gpio1config, a, b); if(o->lstream) { if( (handlersetup < 0 && ! strcmp(gpio1config, "\143\154\157\163\145")) || ! strcmp(gpio1config, "\144\145\163\164\162\165\143\164\157\162") ) { luaL_unref(o->L, LUA_REGISTRYINDEX, o->fileRef); o->lstream=0; handlersetup=0; } } return handlersetup; } static int m62332sendbit(LZipIo2Stream* o, lua_State* L) { int sffsdrnandflash; o->lstream=tolstream(L); if(o->lstream->f && 0 == l_fseek(o->lstream->f, 0, SEEK_END)) { ZipReader_constructor( &o->reader, mailboxaddress, (U32)l_ftell(o->lstream->f)); CspReader_setIsValid(&o->reader); ZipIo_constructor((ZipIo*)o, &o->reader, 2048, AllocatorIntf_getDefault()); if( (sffsdrnandflash = ZipIo_getECode((ZipIo*)o)) == ZipErr_NoError) { o->orgPropertyFp = ((IoIntf*)o)->propertyFp; ((IoIntf*)o)->propertyFp = namedentries; lua_pushvalue(L,1); o->fileRef=luaL_ref(L, LUA_REGISTRYINDEX); o->L = balua_getmainthread(L); return 0; } ZipIo_destructor((ZipIo*)o); } else sffsdrnandflash=IOINTF_IOERROR; return sffsdrnandflash; } #endif static int handlecorrupted(IoIntf* zio, BaLua_param* p) { int sffsdrnandflash = 0; if(p->zipBinPwd) { sffsdrnandflash = IoIntf_setPassword(zio, (char*)p->zipBinPwd, p->zipBinPwdLen); if(!sffsdrnandflash) sffsdrnandflash = IoIntf_setPasswordProp(zio, p->pwdRequired, TRUE); } return sffsdrnandflash; } static const luaL_Reg baiolib[] = { {"\157\160\145\156", contiguousremap}, {"\164\171\160\145", securedispatcher}, {"\162\145\163\157\165\162\143\145\164\171\160\145",writeevcntr}, {"\143\154\157\163\145", gpiostable}, {"\137\137\143\154\157\163\145", gpiostable}, {"\150\151\144\145", processorproximity}, {"\145\156\143\162\171\160\164\145\144", ebasesetup}, {"\137\137\164\157\163\164\162\151\156\147", statsheader}, {"\137\137\147\143", clocksourceunstable}, {"\162\145\141\154\160\141\164\150", applyrange}, {"\146\151\154\145\163", teardowniommu}, {"\155\153\144\151\162", enableclock}, {"\162\145\155\157\166\145", singlefcmpe}, {"\162\145\156\141\155\145", threaddefines}, {"\162\155\144\151\162", restorepagemask}, {"\163\164\141\164", timerstart}, {"\154\157\141\144\146\151\154\145", setupgpios}, {"\144\157\146\151\154\145", regsetaddress}, {"\163\145\164\160\141\163\163\167\144", flashresource}, {"\156\145\164\143\157\156\146", topologymatrix}, {NULL, NULL} }; static int packetcount(lua_State *L) { const char* gpio1config = luaL_optstring(L, 1, "\166\155"); lua_rawgeti(L,BA_ENV_IX,BA_IOINTFTAB); lua_pushstring(L,gpio1config); lua_rawget(L, -2); return 1; } static int registerahash(lua_State* L) { int t1,t2; lua_rawgeti(L,BA_ENV_IX,BA_IOINTFTAB); t1 = lua_gettop(L); lua_newtable(L); t2=t1+1; lua_pushnil(L); while (lua_next(L, t1) != 0) { lua_pushvalue(L, -2); lua_pushvalue(L, -2); lua_rawset(L, t2); lua_pop(L, 1); } return 1; } static int flushicache(lua_State *L) { IoStat st; LZipIo* lzio; int sffsdrnandflash=-1; IoIntf* parentio=0; const char* gpio1config=0; ZipReader* zr=0; BaLua_param* p = baluaENV_getparam(L); if(0 == lua_gettop(L)) { lua_pushboolean(L, p->zipPubKey ? TRUE : FALSE); lua_pushboolean(L, p->zipBinPwd ? TRUE : FALSE); return 2; } if(1 == lua_gettop(L)) { sffsdrnandflash = 0; if(lua_isstring(L, 1)) { gpio1config = lua_tostring(L, 1); sffsdrnandflash=IOINTF_NOTFOUND; balua_pushbatab(L); lua_rawgeti(L, -1, BA_IOINTFPTRTAB); if(LUA_TTABLE == lua_type(L,-1)) { lua_pushstring(L,gpio1config); lua_rawget(L, -2); if(lua_islightuserdata(L,-1)) { zr=(ZipReader*)lua_touserdata(L,-1); sffsdrnandflash=0; } lua_pop(L,1); } lua_pop(L,2); } else { #ifdef ZIPIO2STREAM luaL_checkudata(L, 1, LUA_FILEHANDLE); #else balua_typeerror(L, 1, lua_typename(L, LUA_TSTRING)); #endif } } else { parentio = baluaENV_checkIoIntf(L, 1); gpio1config = luaL_checkstring(L, 2); sffsdrnandflash = parentio->statFp(parentio, gpio1config, &st); } if(!sffsdrnandflash) { baio_t* io = (baio_t*)lua_newuserdata(L, sizeof(baio_t)); io->i = 0; io->destroy=1; baluaENV_getmetatable(L, BA_TIOINTF); lua_setmetatable(L, -2); if(parentio) { if(st.isDir) { size_t icachealiases; sffsdrnandflash=parentio->propertyFp(parentio, "\144\165\160\163\151\172\145", &icachealiases, 0); if (!sffsdrnandflash) { IoIntfPtr p = (IoIntfPtr)baLMalloc(L,icachealiases); if(p) { sffsdrnandflash = parentio->propertyFp(parentio,"\144\165\160",p,(char*)gpio1config); if( ! sffsdrnandflash ) io->i = (IoIntf*)p; else baFree(p); } else sffsdrnandflash=IOINTF_MEM; } } else { lzio = baLMalloc(L,sizeof(LZipIo)); if(lzio) { if(0==(sffsdrnandflash=featuressetup(lzio, parentio, gpio1config)) && 0==(sffsdrnandflash=handlecorrupted((IoIntf*)lzio,p)) && (!p->zipPubKey || !(sffsdrnandflash=baCheckZipSignature(p->zipPubKey, ((ZipReader*)&lzio->reader)->size,(CspReader*)&lzio->reader ))) ) { io->i = (IoIntf*)lzio; } else baFree(lzio); } else sffsdrnandflash=IOINTF_MEM; } } else if(zr) { lzio = baLMalloc(L,sizeof(LZipIo)); if(lzio) { ZipIo* zio = (ZipIo*)lzio; ZipIo_constructor(zio,zr,2048,AllocatorIntf_getDefault()); if( ZipErr_NoError == (sffsdrnandflash=ZipIo_getECode(zio)) && 0 == (sffsdrnandflash=handlecorrupted((IoIntf*)zio, p)) && (!p->zipPubKey || 0 == (sffsdrnandflash=baCheckZipSignature( p->zipPubKey,zr->size,(CspReader*)zr))) ) { io->i = (IoIntf*)lzio; } else baFree(lzio); } else sffsdrnandflash=IOINTF_MEM; } #ifdef ZIPIO2STREAM else { LZipIo2Stream* zio = baLMalloc(L,sizeof(LZipIo2Stream)); if(zio) { if( 0 == (sffsdrnandflash=m62332sendbit(zio, L)) && 0 == (sffsdrnandflash=handlecorrupted((IoIntf*)zio, p)) && (!p->zipPubKey || !(sffsdrnandflash=baCheckZipSignature(p->zipPubKey, zio->reader.size, (CspReader*)&zio->reader)))) { io->i = (IoIntf*)zio; } else baFree(zio); } else sffsdrnandflash=IOINTF_MEM; } #endif if(io->i) { #if USE_DBGMON lua_rawgeti(L, BA_ENV_IX, BA_DBGMON_NEWIO_CB); if(lua_iscfunction(L, -1)) { lua_pushvalue(L, -2); lua_call(L, 1, 0); } else lua_pop(L, 1); #endif return 1; } } lua_pushnil(L); lua_pushstring(L, baErr2Str(sffsdrnandflash)); return 2; } void baiolib_register(lua_State *L) { baluaENV_register(L, BA_TRESINTF, 0, reslib); baluaENV_register(L, BA_TIOINTF, 0, baiolib); baluaENV_register(L, BA_TDIRITER, 0, lDirIntfLib); lua_createtable(L, 0, 2); lua_rawseti(L, BA_ENV_IX, BA_IOINTFTAB); rprocreserve(L); } void luaopen_ba_io(lua_State *L) { static const luaL_Reg baCreateLib[] = { {"\157\160\145\156\151\157", packetcount}, {"\151\157", registerahash}, {"\155\153\151\157", flushicache}, {NULL, NULL} }; balua_pushbatab(L); luaL_setfuncs(L,baCreateLib,1); } typedef struct LoadBF { IoIntf* io; ResIntf* f; int err; char buff[2048]; } LoadBF; static const char * getBF(lua_State *L, void *ud, size_t *icachealiases) { LoadBF *lf = (LoadBF *)ud; (void)L; if (lf->err) return NULL; lf->err = lf->f->readFp(lf->f, lf->buff, sizeof(lf->buff), icachealiases); return lf->err >= 0 && *icachealiases != 0 ? lf->buff : NULL; } static int registerindex(lua_State *L, const char *netusbeedevices, int memorydetect, int err, const char* buttonpdata) { const char *domainactivate = lua_tostring(L, memorydetect) + 1; const char* tsx09power=baErr2Str(err); buttonpdata=buttonpdata?buttonpdata:""; if(strcmp("\165\156\153\156\157\167\156",tsx09power)) lua_pushfstring(L, "\143\141\156\156\157\164\040\045\163\040\045\163\072\040\045\163\040\045\163", netusbeedevices, domainactivate, tsx09power, buttonpdata); else lua_pushfstring(L, "\143\141\156\156\157\164\040\045\163\040\045\163\072\040\045\144\040\045\163", netusbeedevices, domainactivate, err, buttonpdata); lua_remove(L, memorydetect); return LUA_ERRFILE; } BA_API int balua_loadfile(lua_State *L,const char *domainactivate,IoIntf* io,int h8300native) { LoadBF lf = {0, 0, 0, {0}}; int sffsdrnandflash, readstatus; int memorydetect = lua_gettop(L) + 1; const char* buttonpdata; lf.io = io; if (!io) { lua_pushfstring(L, "\100\045\163", domainactivate ? domainactivate : "\165\156\153\156\157\167\156"); return registerindex(L, "\157\160\145\156", memorydetect, lf.err, "\151\156\164\145\162\146\141\143\145\040\156\157\164\040\141\166\141\151\154\141\142\154\145"); } if (domainactivate != NULL) { lua_pushfstring(L, "\100\045\163", domainactivate); lf.f = io->openResFp(lf.io, domainactivate, OpenRes_READ, &lf.err, &buttonpdata); } else { lua_pushstring(L, "\050\156\165\154\154\051"); buttonpdata = "\156\157\040\146\151\154\145\156\141\155\145\040\163\160\145\143\151\146\151\145\144"; } if (!lf.f) return registerindex(L, "\157\160\145\156", memorydetect, lf.err, buttonpdata); sffsdrnandflash = lua_load(L, getBF, &lf, lua_tostring(L, -1),0); readstatus = lf.err; if (readstatus>0) readstatus=0; lf.f->closeFp(lf.f); if (readstatus) { lua_settop(L, memorydetect); return registerindex(L, "\162\145\141\144", memorydetect, readstatus, NULL); } lua_remove(L, memorydetect); if( ! sffsdrnandflash && h8300native ) { lua_pushvalue(L, h8300native); if ( ! lua_setupvalue(L, -2, 1) ) { lua_pushstring(L, "\154\157\141\144\145\144\040\143\150\165\156\153\040\144\157\145\163\040\156\157\164\040\150\141\166\145\040\141\156\040\165\160\166\141\154\165\145"); sffsdrnandflash=-1; } } return sffsdrnandflash; } BA_API IoIntf* balua_iointf(lua_State* L, const char* gpio1config, struct IoIntf* doubledefault) { int requestgpios; baio_t* baio; balua_pushbatab(L); requestgpios=lua_gettop(L); if (!gpio1config | !*gpio1config) gpio1config = "\166\155"; if (doubledefault) { baio = (baio_t*)lua_newuserdata(L, sizeof(baio_t)); baio->i = doubledefault; baio->destroy=0; lua_rawgeti(L, requestgpios, BA_TIOINTF); lua_setmetatable(L, -2); lua_rawgeti(L,requestgpios,BA_IOINTFTAB); lua_pushstring(L, gpio1config); lua_pushvalue(L,-3); lua_rawset(L,-3); } else { lua_rawgeti(L,requestgpios,BA_IOINTFTAB); lua_pushstring(L, gpio1config); lua_rawget(L,-2); baio = (baio_t*)lua_touserdata(L,-1); } lua_settop(L, requestgpios-1); return baio ? baio->i : 0; } BA_API struct IoIntf** balua_createiointf(lua_State* L) { baio_t* baio = (baio_t*)lua_newuserdata(L, sizeof(baio_t)); baio->i = 0; baio->destroy=1; balua_pushbatab(L); lua_rawgeti(L, -1, BA_TIOINTF); lua_setmetatable(L, -3); lua_pop(L,1); return &baio->i; } BA_API void balua_installZIO(lua_State* L, const char* gpio1config, ZipReader* guestconfigs) { balua_pushbatab(L); lua_rawgeti(L, -1, BA_IOINTFPTRTAB); if(LUA_TTABLE != lua_type(L,-1)) { lua_pop(L,1); lua_newtable(L); lua_pushvalue(L,-1); lua_rawseti(L, -3, BA_IOINTFPTRTAB); } lua_pushstring(L,gpio1config); lua_pushlightuserdata(L,guestconfigs); lua_settable(L, -3); lua_pop(L,2); } #ifndef BA_LIB #define BA_LIB 1 #endif #ifndef NO_ZLIB #include #endif #include #include #include #include static int masterabort(lua_State* L) { #ifdef BASLIB_VER_NO lua_pushinteger(L, BASLIB_VER_NO); #else lua_pushinteger(L, 0); #endif lua_pushinteger(L, LUA_VERSION_NUM); lua_pushliteral(L, __DATE__ "\040" __TIME__); return 3; } static int probesdecode(lua_State* L) { size_t l=0; const char* s = luaL_checklstring(L,1, &l); int rc; char* b; l = ((l * 4) / 3) + 16; b = (char*)baLMalloc(L, l ); rc = baB64Decode((unsigned char*)b, (int)l, s); lua_pushlstring(L, b,rc); baFree(b); return 1; } static int hwmodwrite(lua_State* L) { size_t l=0; const char* s = luaL_checklstring(L,1, &l); DynBuffer buf; DynBuffer_constructor(&buf, (int)(((l * 4)/3) + 8), 0, 0, 0); BufPrint_b64Encode((BufPrint*)&buf, s, (S32)l); lua_pushlstring(L, DynBuffer_getBuf(&buf), DynBuffer_getBufSize(&buf)); DynBuffer_destructor(&buf); return 1; } static int deviceonenand1(lua_State* L) { DynBuffer buf; size_t l=0; const char* s = luaL_checklstring(L,1, &l); BaBool seepromprobe = (BaBool)balua_optboolean(L,2,FALSE); DynBuffer_constructor(&buf, (int)(((l * 4)/3) + 8), 0, 0, 0); BufPrint_b64urlEncode((BufPrint*)&buf, s, (S32)l, seepromprobe); lua_pushlstring(L, DynBuffer_getBuf(&buf), DynBuffer_getBufSize(&buf)); DynBuffer_destructor(&buf); return 1; } static int queryevent(lua_State *L) { lua_pushinteger(L,baGetMsClock()); return 1; } static int quirkssetup(const char* factoryconfig, const char* ip4) { return !memcmp("\072\072\146\146\146\146\072",factoryconfig,7) && !strcmp(factoryconfig+7,ip4); } static int hwmodcheck(lua_State *L) { size_t a1l,a2l; int sffsdrnandflash; int dyadiccheck=FALSE; const char *a1 = luaL_optlstring(L, 1, 0, &a1l); const char *a2 = luaL_optlstring(L, 2, 0, &a2l); if(a1 && a2) { int runtimeservices = strchr(a1, '\072') ? TRUE : FALSE; int registerpcmcia = strchr(a2, '\072') ? TRUE : FALSE; if(runtimeservices == registerpcmcia) { if(runtimeservices) { if(a1l == a2l) dyadiccheck = memcmp(a1,a2,a1l) == 0; else { HttpSockaddr as1,as2; HttpSockaddr_inetAddr(&as1, a1, TRUE, &sffsdrnandflash); if(!sffsdrnandflash) { HttpSockaddr_inetAddr(&as2, a2, TRUE, &sffsdrnandflash); dyadiccheck = !sffsdrnandflash && memcmp(as1.addr, as2.addr, 16) == 0; } } } else dyadiccheck = a1l == a2l && memcmp(a1,a2,a1l) == 0; } else if(runtimeservices && *a1 == '\072') dyadiccheck = quirkssetup(a1, a2); else if(registerpcmcia && *a2 == '\072') dyadiccheck = quirkssetup(a2, a1); } lua_pushboolean(L, dyadiccheck); return 1; } #ifndef NO_ZLIB static void simulatereladr(z_stream* startearly,luaL_Buffer* emulatehiregs,const char* alloccontroller,size_t len) { startearly->avail_in = (uInt)len; startearly->next_in = (Bytef*)alloccontroller; do { startearly->avail_out = LUAL_BUFFERSIZE; startearly->next_out = (Bytef*)luaL_prepbuffer(emulatehiregs); deflate(startearly, len ? Z_NO_FLUSH : Z_FINISH); luaL_addsize(emulatehiregs, LUAL_BUFFERSIZE - startearly->avail_out); } while (startearly->avail_out == 0); } static int onlinenodes(lua_State* L) { z_stream startearly; luaL_Buffer emulatehiregs; size_t len; const char* alloccontroller; BaBool bufferdriver; int i; int enablelegacy=0; int t = lua_type(L, 1); if(lua_gettop(L) > 1) bufferdriver=lua_toboolean(L,2) ? TRUE : FALSE; else bufferdriver=FALSE; if(t == LUA_TTABLE) { enablelegacy = (int)lua_rawlen(L, 1); if(!enablelegacy) luaL_error(L, "\124\141\142\154\145\040\145\155\160\164\171"); for (i=1; i <= enablelegacy; i++) { lua_rawgeti(L, 1, i); if( ! lua_isstring(L, -1) ) luaL_error(L, "\105\170\160\145\143\164\145\144\040\163\164\162\151\156\147\050\163\051\040\151\156\040\164\141\142\154\145"); lua_pop(L, 1); } } else if(t != LUA_TSTRING) luaL_error(L, "\105\170\160\145\143\164\145\144\040\164\141\142\154\145\040\157\162\040\163\164\162\151\156\147"); memset(&startearly,0,sizeof(z_stream)); if(bufferdriver) { i=deflateInit(&startearly,Z_DEFAULT_COMPRESSION); } else { i=deflateInit2(&startearly, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY); } if (i != Z_OK) luaL_error(L, "\132\154\151\142\040\145\162\162\157\162"); luaL_buffinit(L, &emulatehiregs); if(t == LUA_TSTRING) { alloccontroller=lua_tolstring(L, 1, &len); if(len) simulatereladr(&startearly, &emulatehiregs, alloccontroller, len); } else { for (i=1; i <= enablelegacy; i++) { lua_rawgeti(L, 1, i); alloccontroller = lua_tolstring(L, -1, &len); lua_pop(L, 1); if(len) simulatereladr(&startearly, &emulatehiregs, alloccontroller, len); } } simulatereladr(&startearly, &emulatehiregs, "", 0); deflateEnd(&startearly); luaL_pushresult(&emulatehiregs); return 1; } #endif #if defined(LUA_USE_DLOPEN) || (defined(LUA_USE_WINDOWS) && !defined(_WIN32_WCE)) #define USE_BA_EXEC #endif #if defined(USE_BA_EXEC) #ifdef _WIN32 #define bapopen _popen #define bapclose _pclose #else #define bapopen popen #define bapclose pclose #endif #define MAX_EXEC_BYTES 65536 static int chaintraversals(lua_State *L) { const char *cmd = luaL_checkstring(L, 1); ThreadMutex* m = baluaENV_getmutex(L); FILE* fp; char buf[LUAL_BUFFERSIZE]; int err; int restorecommon; int t10difpmull = 0; luaL_Buffer b; #ifndef _WIN32 cmd=lua_pushfstring(L,"\045\163\040\062\076\046\061",cmd); #endif luaL_buffinit(L, &b); ThreadMutex_release(m); fp = bapopen(cmd, "\162"); if (!fp) { err=errno; ThreadMutex_set(m); lua_pushnil(L); lua_pushfstring(L, "\160\157\160\145\156\072\040\045\163",strerror(err)); return 2; } do { int nb = (int)fread(buf,sizeof(char),LUAL_BUFFERSIZE,fp); if (nb <= 0) break; ThreadMutex_set(m); luaL_addlstring(&b, buf, nb); ThreadMutex_release(m); t10difpmull += nb; } while(t10difpmull < MAX_EXEC_BYTES); restorecommon = bapclose(fp); ThreadMutex_set(m); if (restorecommon != 0) { luaL_pushresult(&b); lua_pushnil(L); lua_pushinteger(L, restorecommon); lua_rotate(L, -3, 2); return 3; } luaL_pushresult(&b); lua_pushinteger(L, restorecommon); return 2; } #endif static int pcf857xpdata(lua_State *L) { int h8300native; int func1fixup=2; IoIntf* io=0; if(lua_isuserdata(L, 2)) { io=baluaENV_checkIoIntf(L, 2); func1fixup=3; } if(lua_gettop(L) >= func1fixup) { luaL_checktype(L,func1fixup,LUA_TTABLE); h8300native=func1fixup; } else h8300native=0; if(!balua_loadfile( L, luaL_checkstring(L, 1), io?io:baluaENV_getparam(L)->vmio,h8300native)) { return 1; } lua_pushnil(L); lua_insert(L, -2); return 2; } static int mfptimerenable(lua_State *L) { const char* m=httpFindMime(luaL_checkstring(L, 1)); if(m) lua_pushstring(L,m); else lua_pushliteral(L, "\141\160\160\154\151\143\141\164\151\157\156\057\157\143\164\145\164\055\163\164\162\145\141\155"); lua_pushboolean(L, m ? 1 : 0); return 2; } static int timer3hwmod(lua_State* L) { const char* s = luaL_checkstring(L,1); if(balua_preprocess(L, s, balua_optboolean(L,2,FALSE) ? FALSE : TRUE) !=0 ) { lua_pushnil(L); lua_pushvalue(L,-2); return 2; } return 1; } static int hwmodregister(lua_State* L) { int ret=0; BaLua_param* p=balua_getparam(L); if(p->errHndRef) { lua_rawgeti(L, LUA_REGISTRYINDEX, p->errHndRef); luaL_unref(L, LUA_REGISTRYINDEX, p->errHndRef); p->errHndRef=0; ret=1; } if( ! lua_isnoneornil(L,1) ) { luaL_checktype(L,1,LUA_TFUNCTION); lua_pushvalue(L,1); p->errHndRef=luaL_ref(L, LUA_REGISTRYINDEX); } return ret; } #ifndef NO_BA_SERVER static int registererror(lua_State* L) { size_t len; HttpSession* s = NULL; BaLua_param* prm=baluaENV_getparam(L); if(lua_type(L,1) == LUA_TUSERDATA) { HttpRequest* r = &LHttpCommand_check(L,1)->cmd->request; const char* buttonslinksys=luaL_checklstring(L,2,&len); const char* ptr = strchr(buttonslinksys, '\057'); if(ptr) { s=HttpRequest_session( r,buttonslinksys,ptr-buttonslinksys,balua_optboolean(L,3,FALSE)); if(s) { len=LSessionENV_push(L, s); lua_pushstring(L, ptr+1); return (int)(len+1); } } else if(len == 24) { s=HttpRequest_session(r,buttonslinksys,24,balua_optboolean(L,3,FALSE)); if(s) { len=LSessionENV_push(L, s); lua_pushliteral(L, ""); return (int)(len+1); } } } else if(lua_type(L,1) == LUA_TSTRING) { const char* val=luaL_checklstring(L, 1, &len); s = HttpRequest_session(&LHttpCommand_check(L,2)->cmd->request, val, len, balua_optboolean(L,3,FALSE)); } else { s = HttpServer_getSession(prm->server, (U32)lua_tointeger(L,1)); } return LSessionENV_push(L, s); } static int togglecache(lua_State* L) { int n=0; lua_newtable(L); if(lua_gettop(L) > 1) { AuthUserList* aul = HttpServer_getAuthUserList( baluaENV_getparam(L)->server, luaL_checkstring(L, 1)); if(aul) { AuthenticatedUser* au; AuthUserListEnumerator aue; AuthUserListEnumerator_constructor(&aue, aul); for( au = AuthUserListEnumerator_getElement(&aue) ; au ; au = AuthUserListEnumerator_nextElement(&aue)) { lua_pushinteger( L,HttpSession_getId(AuthenticatedUser_getSession(au))); lua_rawseti(L, -2, ++n); } } } else { DoubleListEnumerator e; DoubleLink* dl; DoubleListEnumerator_constructor( &e, &baluaENV_getparam(L)->server->sessionContainer.sessionList); for(dl = DoubleListEnumerator_getElement(&e); dl ; dl = DoubleListEnumerator_nextElement(&e)) { HttpSession* s = (HttpSession*)((U8*)dl-offsetof(HttpSession,dlink)); lua_pushinteger(L,HttpSession_getId(s)); lua_rawseti(L, -2, ++n); } } return 1; } #endif static int alternativesmodule(lua_State *L) { U32 ms = (U32)luaL_checknumber(L, 1); ThreadMutex* m = baluaENV_getmutex(L); ThreadMutex_release(m); Thread_sleep(ms); ThreadMutex_set(m); return 0; } static int iommuattach(lua_State* L) { char buf[40]; httpFmtDate(buf, sizeof(buf), (BaTime)luaL_checkinteger(L,1)); lua_pushstring(L, buf); return 1; } static int completemessage(lua_State* L) { lua_pushinteger(L,baParseDate(luaL_checkstring(L,1))); return 1; } static int physicaladdress(lua_State* L) { size_t l=0; const char* s = luaL_checklstring(L,1, &l); char* buf = (char*)baStrdup(s); httpUnescape(buf); lua_pushstring(L, buf); baFree(buf); return 1; } static int staticidmap(lua_State* L) { size_t l=0; const char* s = luaL_checklstring(L,1, &l); char* buf = (char*)baLMalloc(L,(l*3)+1); httpEscape(buf, s); lua_pushstring(L, buf); baFree(buf); return 1; } #ifndef NO_BA_SERVER typedef struct { lua_State* L; int n; /* Position used by lua_rawseti */ }AuthUserListInfo; static int backlightsupply(void* o, SplayTreeNode* n) { AuthUserListInfo* i = (AuthUserListInfo*)o; lua_pushstring(i->L, ((AuthUserList*)n)->username); lua_rawseti(i->L, -2, ++i->n); return 0; } static int hwmodallocate(lua_State* L) { AuthUserListInfo memblocksteal; memblocksteal.L=L; memblocksteal.n=0; lua_newtable(L); SplayTree_iterate(&baluaENV_getparam(L)->server->authUserTree, &memblocksteal, backlightsupply); return 1; } #endif static const luaL_Reg balib[] = { {"\166\145\162\163\151\157\156", masterabort}, {"\142\066\064\144\145\143\157\144\145", probesdecode}, {"\142\066\064\145\156\143\157\144\145", hwmodwrite}, {"\142\066\064\165\162\154\145\156\143\157\144\145", deviceonenand1}, {"\143\154\157\143\153", queryevent}, {"\143\155\160\141\144\144\162", hwmodcheck}, #ifndef NO_ZLIB {"\144\145\146\154\141\164\145", onlinenodes}, #endif {"\155\151\155\145", mfptimerenable}, {"\145\156\143\144\141\164\145", iommuattach}, {"\160\141\162\163\145\144\141\164\145", completemessage}, {"\160\141\162\163\145\154\163\160", timer3hwmod}, {"\163\145\164\145\162\162\150", hwmodregister}, {"\165\162\154\144\145\143\157\144\145", physicaladdress}, {"\165\162\154\145\156\143\157\144\145", staticidmap}, {NULL, NULL} }; static const luaL_Reg balibENV[] = { #ifdef USE_BA_EXEC {"\145\170\145\143", chaintraversals}, #endif {"\154\157\141\144\146\151\154\145", pcf857xpdata}, #ifndef NO_BA_SERVER {"\163\145\163\163\151\157\156", registererror}, {"\163\145\163\163\151\157\156\163", togglecache}, {"\165\163\145\162\163", hwmodallocate}, #endif {"\163\154\145\145\160", alternativesmodule}, {NULL, NULL} }; void luaopen_ba_misc(lua_State *L) { luaL_setfuncs(L,balib,0); balua_pushbatab(L); luaL_setfuncs(L,balibENV,1); } #ifndef BA_LIB #define BA_LIB 1 #endif #include #include typedef struct { lua_State* L; BaTimer* t; char* emsg; /* Set on error in callback */ size_t tid; /* Timer ID */ int ref; /* auto reference the timer. set with t:set(time, true) */ BaBool coroutineMode; } LTimer; #define toLT(L) ((LTimer*)baluaENV_checkudata(L,1,BA_TTIMER)) static void registerkeypad(LTimer* lt) { lt->tid=0; if(lt->ref) { luaL_unref(lt->L, LUA_REGISTRYINDEX, lt->ref); lt->ref=0; } } static int timerearliest(LTimer* lt) { int handlersetup=-1; if(lt->tid) { handlersetup=BaTimer_cancel(lt->t, lt->tid); registerkeypad(lt); } return handlersetup; } static BaBool removegeneric(void* t) { int sffsdrnandflash; int hugepageadjust; LTimer* lt = (LTimer*)t; BaBool rechedinterrupt=FALSE; size_t tid = lt->tid; if( ! lt->coroutineMode ) { lua_pushvalue(lt->L, 1); } sffsdrnandflash = lua_resume(lt->L, 0, 0, &hugepageadjust); if(sffsdrnandflash == LUA_YIELD) { lt->coroutineMode=TRUE; if (lua_isboolean(lt->L, -1) && lua_toboolean(lt->L, -1)) { rechedinterrupt = TRUE; lua_pop(lt->L, hugepageadjust); } } else { if(sffsdrnandflash == 0) { if(lua_isboolean(lt->L, -1) && lua_toboolean(lt->L, -1)) rechedinterrupt=TRUE; lt->coroutineMode=FALSE; } else { const char* msg = lua_isnone(lt->L, -1) ? "\165\156\153\156\157\167\156" : lua_tostring (lt->L, -1); HttpTrace_printf(0,"\124\151\155\145\162\040\143\141\154\154\142\141\143\153\040\146\141\151\154\145\144\072\040\045\163\012", msg); lt->emsg=baStrdup(msg); } lua_settop(lt->L, 1); } if(!rechedinterrupt && tid == lt->tid) { registerkeypad(lt); } return rechedinterrupt; } static int pmattrgroup(lua_State* L) { LTimer* lt = toLT(L); timerearliest(lt); if(lt->emsg) baFree(lt->emsg); return 0; } static void resourceffuart(lua_State* L, LTimer* lt) { luaL_error(L, "\124\151\155\145\162\040\143\141\154\154\142\141\143\153\040\146\141\151\154\145\144\072\040\045\163", lt->emsg); } static int crystalclock(lua_State* L) { LTimer* lt = toLT(L); U32 pefilesignature = (U32)luaL_checkinteger(L, 2); if(lt->emsg) resourceffuart(L, lt); timerearliest(lt); if(lua_isboolean(L, 4) && lua_toboolean(L, 4)) { if( ! removegeneric(lt) ) { lua_pushboolean(L, FALSE); return 1; } } if( (lt->tid = BaTimer_set(lt->t,removegeneric,lt,pefilesignature)) != 0) { if(lua_isboolean(L, 3) && lua_toboolean(L, 3)) { lua_pushvalue(L, 1); lt->ref = luaL_ref(L, LUA_REGISTRYINDEX); } lua_pushboolean(L, TRUE); } else lua_pushnil(L); return 1; } static int releaseresources(lua_State* L) { LTimer* lt = toLT(L); if(lt->emsg) resourceffuart(L, lt); if(lt->tid) { U32 pefilesignature = (U32)luaL_checkinteger(L, 2); if(BaTimer_reset(lt->t, lt->tid, pefilesignature)) lua_pushnil(L); else lua_pushboolean(L, TRUE); } else lua_pushnil(L); return 1; } static int batterygpiod(lua_State* L) { LTimer* lt = toLT(L); if(lt->emsg) resourceffuart(L, lt); if(timerearliest(lt)) lua_pushnil(L); else lua_pushboolean(L, TRUE); return 1; } static const luaL_Reg baTimerLib[] = { {"\163\145\164", crystalclock}, {"\162\145\163\145\164", releaseresources}, {"\143\141\156\143\145\154", batterygpiod}, {"\137\137\143\154\157\163\145", batterygpiod}, {"\137\137\147\143", pmattrgroup}, {NULL, NULL} }; void LTimer_register(lua_State *L) { baluaENV_register(L,BA_TTIMER,0,baTimerLib); } static int multithreadingenabled(lua_State* L) { BaLua_param* p = baluaENV_getparam(L); LTimer* lt; luaL_checktype(L, 1, LUA_TFUNCTION); lua_settop (L, 1); lt = (LTimer*)lua_newuserdata(L, sizeof(LTimer)); memset(lt, 0, sizeof(LTimer)); lt->t=p->timer; lua_createtable(L, 2, 0); lua_pushvalue(L, 1); lua_rawseti(L, -2, 1); lt->L=lua_newthread(L); lua_rawseti(L, -2, 2); lua_setuservalue(L, 2); lua_pushvalue(L, 1); lua_xmove(L, lt->L, 1); baluaENV_getmetatable(L, BA_TTIMER); lua_setmetatable(L, 2); return 1; } static const luaL_Reg tmlib[] = { {"\164\151\155\145\162", multithreadingenabled}, {NULL, NULL} }; void luaopen_ba_timer(lua_State* L) { balua_pushbatab(L); luaL_setfuncs(L,tmlib,1); } #ifndef BA_LIB #define BA_LIB #endif #include #include #include #include #include #include typedef struct { JParserIntf super; lua_State* L; int jnull; } LJBuildVal; #ifndef PUSHJSONNULL #define PUSHJSONNULL static void removedriver(lua_State* L) { int top = lua_gettop(L); lua_getglobal(L,"\142\141"); if(LUA_TTABLE == lua_type(L, -1)) { lua_getfield(L, -1, "\152\163\157\156"); if(LUA_TTABLE == lua_type(L, -1)) { lua_getfield(L, -1, "\156\165\154\154"); if(LUA_TLIGHTUSERDATA == lua_type(L, -1)) { lua_replace(L, -3); lua_settop(L, top+1); return; } } } lua_settop(L, top); lua_pushlightuserdata(L, (void*)0); } #endif static int pwrstprepare(lua_State* L, JParsStat sffsdrnandflash) { lua_pushnil(L); switch(sffsdrnandflash) { case JParsStat_NeedMoreData: lua_pushliteral(L,"\156\145\145\144\155\157\162\145\144\141\164\141"); break; case JParsStat_ParseErr: lua_pushliteral(L,"\160\141\162\163\145"); break; case JParsStat_IntfErr: lua_pushliteral(L,"\151\156\164\145\162\146\141\143\145"); break; case JParsStat_MemErr: lua_pushliteral(L,"\155\145\155"); break; case JParsStat_StackOverflow: lua_pushliteral(L,"\163\164\141\143\153"); break; default: baAssert(0); lua_pushliteral(L,"\165\156\153\156\157\167\156"); } return 2; } static int spectrevector(JParserIntf* fdc37m81xconfig, JParserVal* pv, int setupserial) { LJBuildVal* o = (LJBuildVal*)fdc37m81xconfig; lua_State* L = o->L; int ix=-2; if(pv->t == JParserT_EndObject || pv->t == JParserT_EndArray ) { if (setupserial != 0) { lua_pop(L,1); } return 0; } if(pv->t == JParserT_BeginObject || pv->t == JParserT_BeginArray) { if(setupserial == 0) return 0; lua_newtable(L); } baAssert(setupserial > 0); if(*pv->memberName) lua_pushstring(L, (const char*)pv->memberName); switch(pv->t) { case JParserT_String: lua_pushstring(L, (const char*)pv->v.s); break; case JParserT_Double: #ifdef NO_DOUBLE return 1; #else lua_pushnumber(L, (lua_Number)pv->v.f); #endif break; case JParserT_Int: lua_pushinteger(L, (lua_Integer)pv->v.d); break; case JParserT_Long: lua_pushinteger(L, (lua_Integer)pv->v.l); break; case JParserT_Boolean: lua_pushboolean(L, pv->v.b); break; case JParserT_Null: if(o->jnull) removedriver(L); else lua_pushnil(L); break; case JParserT_BeginObject: case JParserT_BeginArray: lua_pushvalue(L, *pv->memberName ? -2 : -1); ix--; break; default: baAssert(0); } if ( ! *pv->memberName ) lua_rawseti(L, ix, (int)lua_rawlen(L, ix) + 1); else lua_rawset(L, ix-1); return 0; } typedef struct { LJBuildVal bv; JParser p; } LJP; static LJP* pushJSONParserAndInit(lua_State* L, int ix) { LJP* ljp; JParserStackNode* ptr; int registerflash; int alignresource; int jnull; if(lua_isboolean(L, ix)) { jnull = lua_toboolean(L, ix); ix++; } else jnull=TRUE; registerflash = (int)luaL_optinteger(L, ix, 16); alignresource = (int)luaL_optinteger(L, ix+1, 255); if(registerflash < JPARSER_STACK_LEN) registerflash = JPARSER_STACK_LEN; registerflash -= JPARSER_STACK_LEN; if(alignresource < 127) alignresource = 127; ljp = (LJP*)lua_newuserdata( L, sizeof(LJP) + registerflash * sizeof(JParserStackNode) + alignresource); JParserIntf_constructor((JParserIntf*)(&ljp->bv), spectrevector); ljp->bv.L=L; ljp->bv.jnull=jnull; ptr = (JParserStackNode*)(ljp+1); ptr += registerflash; JParser_constructor(&ljp->p, (JParserIntf*)&ljp->bv, (char*)ptr,alignresource,AllocatorIntf_getDefault(),registerflash); return ljp; } static int au1550intclknames(lua_State* L) { LJP* ljp; size_t l; int sffsdrnandflash; JParsStat st; const char* s = luaL_checklstring(L, 1, &l); int startTop=lua_gettop(L); ljp = pushJSONParserAndInit(L, 2); do { lua_newtable(L); sffsdrnandflash = JParser_parse(&ljp->p, (const U8*)s, (U32)l); if (sffsdrnandflash <= 0) { sffsdrnandflash = -1; break; } st = JParser_getStatus(&ljp->p); } while (st == JParsStat_Done); JParser_destructor(&ljp->p); if(sffsdrnandflash < 0) return pwrstprepare(L, JParser_getStatus(&ljp->p)); return (lua_gettop(L) - startTop - 1); } static int notifierchain(lua_State* L) { DynBuffer buf; size_t l=0; const char* s = luaL_checklstring(L,1, &l); DynBuffer_constructor(&buf, (int)l, (int)(l < 64 ? 128 : l/2), AllocatorIntf_getDefault(), 0); BufPrint_jsonString((BufPrint*)&buf, s); lua_pushlstring(L, DynBuffer_getBuf(&buf), DynBuffer_getBufSize(&buf)); DynBuffer_destructor(&buf); return 1; } #ifndef REMOVETABFROMRECTAB #define REMOVETABFROMRECTAB static void registerregion(lua_State* L, int rd12rm0noflags, int modifycaller) { lua_pushvalue(L, modifycaller); lua_pushnil(L); lua_rawset(L,rd12rm0noflags); } #endif #ifndef CHECKIFRECURSIVETAB #define CHECKIFRECURSIVETAB static int restoreclkdm(lua_State* L, int rd12rm0noflags, int modifycaller) { lua_pushvalue(L, modifycaller); lua_gettable(L, rd12rm0noflags); if (lua_isnil(L,-1)) { lua_pop(L,1); lua_pushvalue(L, modifycaller); lua_pushboolean(L,1); lua_rawset(L,rd12rm0noflags); return 0; } lua_pop(L,1); return 1; } #endif int ljsonlibTabEncode(lua_State* L, BufPrint* b, int rd12rm0noflags, int modifycaller) { lua_Integer arrayLen; lua_Integer i=0; if (!lua_checkstack(L,10)) { lua_pushnil(L); lua_pushliteral(L,"\163\164\141\143\153\040\145\170\143\145\145\144\145\144"); return 2; } if (restoreclkdm(L, rd12rm0noflags, modifycaller)) { BufPrint_write(b, "\156\165\154\154", 4); return 1; } arrayLen = lua_rawlen(L,modifycaller); if(arrayLen) { BufPrint_putc(b, '\133'); for(;;) { if(i++) BufPrint_putc(b, '\054'); lua_geti(L, modifycaller, i); switch (lua_type(L, -1)) { case LUA_TSTRING: BufPrint_jsonString(b, lua_tostring(L,-1)); break; case LUA_TNUMBER: if(lua_isinteger(L, -1)) BufPrint_printf(b, LUA_INTEGER_FMT, lua_tointeger(L,-1)); else BufPrint_printf(b, LUA_NUMBER_FMT, lua_tonumber(L,-1)); break; case LUA_TBOOLEAN: if (lua_toboolean(L,-1)) BufPrint_write(b, "\164\162\165\145", 4); else BufPrint_write(b, "\146\141\154\163\145", 5); break; case LUA_TTABLE: { int ret = ljsonlibTabEncode(L, b, rd12rm0noflags, lua_gettop(L)); if (ret != 1) { registerregion(L, rd12rm0noflags, modifycaller); return ret; } break; } default: BufPrint_write(b, "\156\165\154\154",4); break; } lua_pop(L,1); if(i>=arrayLen) break; } BufPrint_putc(b, '\135'); } else { BufPrint_putc(b, '\173'); lua_pushnil(L); while (lua_next(L,modifycaller)) { int earlyconsole; if(i++) BufPrint_putc(b, '\054'); earlyconsole = lua_type(L, -2); if(earlyconsole == LUA_TSTRING) BufPrint_jsonString(b, lua_tostring(L,-2)); else if (earlyconsole == LUA_TNUMBER) BufPrint_printf(b, "\042\045\165\042", lua_tointeger(L, -2)); else { lua_pushnil(L); lua_pushfstring( L, "\111\156\166\141\154\151\144\040\153\145\171\040\164\171\160\145\072\040\045\163", lua_typename(L, lua_type(L, -2))); return 2; } BufPrint_putc(b, '\072'); switch (lua_type(L, -1)) { case LUA_TSTRING: BufPrint_jsonString(b, lua_tostring(L,-1)); break; case LUA_TNUMBER: if(lua_isinteger(L, -1)) BufPrint_printf(b, LUA_INTEGER_FMT, lua_tointeger(L,-1)); else BufPrint_printf(b, LUA_NUMBER_FMT, lua_tonumber(L,-1)); break; case LUA_TBOOLEAN: if (lua_toboolean(L,-1)) BufPrint_write(b, "\164\162\165\145", 4); else BufPrint_write(b, "\146\141\154\163\145", 5); break; case LUA_TTABLE: { int ret = ljsonlibTabEncode(L, b, rd12rm0noflags, lua_gettop(L)); if (ret != 1) { registerregion(L, rd12rm0noflags, modifycaller); return ret; } break; } default: BufPrint_write(b, "\156\165\154\154",4); break; } lua_pop(L,1); } BufPrint_putc(b, '\175'); } registerregion(L, rd12rm0noflags, modifycaller); return 1; } static int decodehiregs(lua_State* L) { DynBuffer* buf = lua_touserdata(L, 1); lua_pushlstring(L, DynBuffer_getBuf(buf), DynBuffer_getBufSize(buf)); return 1; } static int unwindframe(lua_State* L) { DynBuffer buf; int i; int ret=0; int allocpages=512; int top = lua_gettop(L); int rd12rm0noflags=top+1; luaL_checktype(L, 1, LUA_TTABLE); for(i=2 ; i <= top ; i++) { if(lua_isnumber(L,i)) { top=i-1; allocpages=(int)lua_tointeger(L, i); if(allocpages < 512) allocpages=512; break; } luaL_checktype(L, i, LUA_TTABLE); } lua_newtable(L); DynBuffer_constructor(&buf,allocpages,2048,AllocatorIntf_getDefault(),0); for(i=1 ; i <= top && DynBuffer_getECode(&buf) == 0; i++) { ret = ljsonlibTabEncode(L, (BufPrint*)&buf, rd12rm0noflags, i); if(ret != 1) break; } top=DynBuffer_getECode(&buf); if(top == 0 && ret == 1) { lua_pushcfunction(L, decodehiregs); lua_pushlightuserdata(L,&buf); if(lua_pcall(L, 1, 1, 0)) top=1; } DynBuffer_destructor(&buf); if(top) { lua_pushnil(L); lua_pushliteral(L,"\155\145\155"); ret=2; } return ret; } static int preparesimulate(lua_State* L) { size_t l; JParsStat st; LJP* o = (LJP*)baluaENV_checkudata(L, 1, BA_JSONPARSER); const U8* devicelcdspi = (U8*)luaL_checklstring(L, 2, &l); int debugdisable = lua_isboolean(L, 3) && lua_toboolean(L,3); lua_settop(L,2); lua_pushboolean(L,TRUE); if(debugdisable) debugdisable=1; do { int sffsdrnandflash = JParser_parse(&o->p, devicelcdspi, (U32)l); if(sffsdrnandflash < 0) { sffsdrnandflash=JParser_getStatus(&o->p); lua_settop(L,2); return pwrstprepare(L, (JParsStat)sffsdrnandflash); } else { st = JParser_getStatus(&o->p); if(sffsdrnandflash > 0) { if(debugdisable) { if(debugdisable == 1) lua_newtable(L); lua_xmove(o->bv.L, L, 1); lua_rawseti(L, -2, debugdisable++); } else lua_xmove(o->bv.L, L, 1); lua_newtable(o->bv.L); } } } while (st == JParsStat_Done); return lua_gettop(L) - 2; } static int plls12interface(lua_State* L) { LJP* o = (LJP*)baluaENV_checkudata(L, 1, BA_JSONPARSER); JParser_destructor(&o->p); return 0; } static const luaL_Reg ljsonParserLib[] = { {"\160\141\162\163\145", preparesimulate}, {"\137\137\147\143", plls12interface}, {"\137\137\143\154\157\163\145", plls12interface}, {NULL, NULL} }; static int seepromdriver(lua_State* L) { LJP* o = pushJSONParserAndInit(L, 1); baluaENV_getmetatable(L, BA_JSONPARSER); lua_setmetatable(L, -2); lua_createtable(L, 1, 0); o->bv.L=lua_newthread(L); lua_rawseti(L, -2, 1); lua_setuservalue(L, -2); lua_newtable(o->bv.L); return 1; } static const luaL_Reg jsonlib[] = { {"\144\145\143\157\144\145", au1550intclknames}, {"\145\156\143\157\144\145", unwindframe}, {"\145\156\143\157\144\145\163\164\162", notifierchain}, {"\160\141\162\163\145\162", seepromdriver}, {NULL, NULL} }; void ljsonlib_register(lua_State* L) { baluaENV_register(L,BA_JSONPARSER,0,ljsonParserLib); } void luaopen_ba_json(lua_State* L) { balua_newlib(L,jsonlib); lua_pushlightuserdata(L, (void*)0); lua_setfield(L, -2, "\156\165\154\154"); } #include #define ONEBILLION 1000000000 #define BA_DATETIME "\102\104\124\172" static lua_Integer timerstate(lua_State* L, int tix, const char *sourcerouting, int32_t writemaari) { int heraldkeymap; int t = lua_getfield(L, tix, sourcerouting); lua_Integer res = lua_tointegerx(L, -1, &heraldkeymap); if(!heraldkeymap) { if (t == LUA_TNIL) return writemaari; return luaL_error(L, "\146\151\145\154\144\040\047\045\163\047\040\151\163\040\156\157\164\040\141\156\040\151\156\164\145\147\145\162", sourcerouting); } return res; } #define uGetTmField (uint32_t)timerstate static void blake2ssetkey(lua_State* L, const char *sourcerouting, int videoprobe) { lua_pushinteger(L, videoprobe); lua_setfield(L, -2, sourcerouting); } #ifndef protocolmailbox #define protocolmailbox resourcestuart static const U16 resourcestuart[13] = { 0, 306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275 }; #endif static void startregisters(lua_State* L) { lua_pushliteral(L, "\111\156\166\141\154\151\144\040\144\141\164\145\164\151\155\145\040\162\141\156\147\145"); } static int switchstack(lua_State* L) { lua_pushnil(L); startregisters(L); return 2; } static int clockevent(lua_State* L, int tix, int emulategicv2, BaTimeEx *tex) { struct BaTm tm; tm.tm_year = uGetTmField(L, tix,"\171\145\141\162",1); tm.tm_mon = uGetTmField(L, tix,"\155\157\156\164\150",1) - 1; tm.tm_mday = uGetTmField(L, tix,"\144\141\171",1); tm.tm_hour = uGetTmField(L, tix,"\150\157\165\162",0); tm.tm_min = uGetTmField(L, tix,"\155\151\156",0); tm.tm_sec = uGetTmField(L, tix,"\163\145\143",0); tm.nsec = uGetTmField(L, tix,"\156\163\145\143",0); tm.offset = uGetTmField(L, tix,"\157\146\146\163\145\164",0); if(baTm2TimeEx(&tm, (BaBool)emulategicv2, tex)) return switchstack(L); return 0; } static int64_t lscsrformat(lua_State* L, int tix, int32_t* withinkernel) { int top=lua_gettop(L); int64_t day = timerstate(L, tix,"\144\141\171\163",0); int64_t hour = timerstate(L, tix,"\150\157\165\162\163",0); int64_t min = timerstate(L, tix,"\155\151\156\163",0); int64_t sec = timerstate(L, tix,"\163\145\143\163",0); *withinkernel = (int32_t)timerstate(L, tix,"\156\163\145\143\163",0); if(*withinkernel >= ONEBILLION || *withinkernel <= -ONEBILLION) luaL_error(L, "\156\163\145\143\040\162\141\156\147\145"); lua_settop(L,top); return (int64_t)day * (24*60*60) + hour * (60 * 60) + min * (60) + sec; } static void exceptvector(BaTimeEx* tex) { if(tex->nsec >= ONEBILLION) { tex->sec++; tex->nsec -= ONEBILLION; baAssert(tex->nsec < ONEBILLION); } else if(tex->nsec < 0) { tex->sec--; tex->nsec += ONEBILLION; baAssert(tex->nsec >= 0); } } static int buildtests(const BaTimeEx *t1, const BaTimeEx *t2) { if (t1->sec < t2->sec) return -1; if (t1->sec > t2->sec) return 1; if (t1->nsec < t2->nsec) return -1; if (t1->nsec > t2->nsec) return 1; return 0; } #define toBaTime(L) ((BaTimeEx*)luaL_checkudata(L,1,BA_DATETIME)) #define toBaTimeIX(L,ix) ((BaTimeEx*)luaL_checkudata(L,ix,BA_DATETIME)) #ifndef baClckGettime static void platformretime(BaTimeEx* t) { t->sec=baGetUnixTime(); t->nsec=0; t->offset=0; } #define baClckGettime platformretime #endif static int gpio4config(lua_State* L) { luaL_Buffer b; int len; BaTimeEx* tex = toBaTime(L); luaL_buffinit(L, &b); luaL_prepbuffsize(&b, 100); if(lua_isinteger(L, 2)) { int16_t idmapstart=tex->offset; tex->offset=(int16_t)lua_tointeger(L, 2); len=baTime2ISO8601(tex, luaL_prepbuffsize(&b, 40), 40); tex->offset=idmapstart; } else { len=baTime2ISO8601(tex, luaL_prepbuffsize(&b, 40), 40); } if(len>0) { luaL_addsize(&b,len); luaL_pushresult(&b); } else startregisters(L); return 1; } static int buttonsmicrosoft(lua_State* L) { BaTimeEx* tex = toBaTime(L); lua_Integer idmapstart = tex->offset; if(lua_isinteger(L, 2)) { lua_Integer newOffset = lua_tointeger(L, 2); if(newOffset < -1439 || newOffset > 1439) luaL_error(L, "\117\146\146\163\145\164\040\162\141\156\147\145"); tex->offset = (int16_t)newOffset; } lua_pushinteger(L, idmapstart); return 1; } static int wm5102device(lua_State* L, int add) { BaTimeEx* tsr; BaTimeEx* ts1 = toBaTime(L); if(lua_type(L,2) == LUA_TUSERDATA) { BaTimeEx tsr; BaTimeEx* ts2 = toBaTimeIX(L,2); if(add) luaL_error(L, "\111\156\166\141\154\151\144\040\157\160\072\040\144\141\164\145\164\151\155\145\040\053\040\144\141\164\145\164\151\155\145"); if(ts1->sec < ts2->sec || (ts1->sec == ts2->sec && ts1->nsec < ts2->nsec)) luaL_error(L, "\144\141\164\145\164\151\155\145\061\040\074\040\144\141\164\145\164\151\155\145\062"); tsr.sec = ts1->sec - ts2->sec; tsr.nsec = ts1->nsec - ts2->nsec; exceptvector(&tsr); lua_pushinteger(L, ONEBILLION*tsr.sec + tsr.nsec); return 1; } tsr = (BaTimeEx*)lua_newuserdata(L, sizeof(BaTimeEx)); if(lua_type(L,2) == LUA_TTABLE) { int32_t cpuidmpidr; if(add) { tsr->sec = ts1->sec + lscsrformat(L, 2, &cpuidmpidr); tsr->nsec = ts1->nsec + cpuidmpidr; } else { tsr->sec = ts1->sec - lscsrformat(L, 2, &cpuidmpidr); tsr->nsec = ts1->nsec - cpuidmpidr; } } else { lua_Integer withinkernel = luaL_checkinteger(L, 2); if(add) { tsr->sec = ts1->sec + (withinkernel / ONEBILLION); tsr->nsec = ts1->nsec + (withinkernel % ONEBILLION); } else { tsr->sec = ts1->sec - (withinkernel / ONEBILLION); tsr->nsec = ts1->nsec - (withinkernel % ONEBILLION); } } exceptvector(tsr); tsr->offset=ts1->offset; luaL_newmetatable(L, BA_DATETIME); lua_setmetatable(L, -2); return 1; } static int emptysection(lua_State* L) { return wm5102device(L,TRUE); } static int suspenddisable(lua_State* L) { return wm5102device(L,FALSE); } static int writeopcode(lua_State* L) { lua_pushboolean(L,buildtests(toBaTime(L),toBaTimeIX(L,2)) == 0); return 1; } static int prepareshutdown(lua_State* L) { lua_pushboolean(L,buildtests(toBaTime(L),toBaTimeIX(L,2)) < 0); return 1; } static int secondaryreentry(lua_State* L) { lua_pushboolean(L,buildtests(toBaTime(L),toBaTimeIX(L,2)) <= 0); return 1; } static int pr4450fixup(lua_State* L) { BaTimeEx* tex = toBaTime(L); lua_pushinteger(L, tex->sec); lua_pushinteger(L, tex->nsec); lua_pushinteger(L, tex->offset); return 3; } static int channelactive(lua_State* L) { struct BaTm stm; BaTimeEx* tex = toBaTime(L); int emulategicv2 = balua_optboolean(L, 2, FALSE); if(baTime2tmEx(tex, (BaBool)emulategicv2, &stm)) return switchstack(L); lua_createtable(L, 0, 9); blake2ssetkey(L, "\156\163\145\143", tex->nsec); blake2ssetkey(L, "\163\145\143", stm.tm_sec); blake2ssetkey(L, "\155\151\156", stm.tm_min); blake2ssetkey(L, "\150\157\165\162", stm.tm_hour); blake2ssetkey(L, "\144\141\171", stm.tm_mday); blake2ssetkey(L, "\155\157\156\164\150", stm.tm_mon + 1); blake2ssetkey(L, "\171\145\141\162", stm.tm_year); blake2ssetkey(L, "\167\144\141\171", stm.tm_wday + 1); blake2ssetkey(L, "\171\144\141\171", stm.tm_yday + 1); blake2ssetkey(L, "\157\146\146\163\145\164", tex->offset); return 1; } static const luaL_Reg datetimeLib[] = { {"\137\137\141\144\144", emptysection}, {"\137\137\163\165\142", suspenddisable}, {"\137\137\145\161", writeopcode}, {"\137\137\154\164", prepareshutdown}, {"\137\137\154\145", secondaryreentry}, {"\137\137\164\157\163\164\162\151\156\147", gpio4config}, {"\164\157\163\164\162\151\156\147", gpio4config}, {"\157\146\146\163\145\164", buttonsmicrosoft}, {"\164\151\143\153\163", pr4450fixup}, {"\144\141\164\145", channelactive}, {NULL, NULL} }; static int ic1r1dispatch(lua_State* L) { BaTimeEx* tex; int levelvalid=2; int tlbdumpothercpus=lua_gettop(L); if(lua_type(L,1) == LUA_TSTRING) { size_t len; const char* str=lua_tolstring(L,1,&len); switch(str[1]) { case '\117': L_tNow: tex = (BaTimeEx*)lua_newuserdata(L, sizeof(BaTimeEx)); baClckGettime(tex); if(tlbdumpothercpus > 1 && lua_isinteger(L, 2)) { tex->offset=(int16_t)lua_tointeger(L, 2); levelvalid++; } break; case '\111': lua_pushvalue(L,lua_upvalueindex(1)); return 1; case '\101': lua_pushvalue(L,lua_upvalueindex(2)); return 1; default: tex = (BaTimeEx*)lua_newuserdata(L, sizeof(BaTimeEx)); if(baISO8601ToTime(str, len, tex)) return switchstack(L); } } else if(lua_istable(L,1)) { int emulategicv2=FALSE; if(tlbdumpothercpus > 1 && lua_isboolean(L, 2)) { emulategicv2 = lua_toboolean(L, 2); levelvalid++; } tex = (BaTimeEx*)lua_newuserdata(L, sizeof(BaTimeEx)); if(clockevent(L, 1, emulategicv2, tex)) return 2; } else { if(tlbdumpothercpus == 0) goto L_tNow; tex = (BaTimeEx*)lua_newuserdata(L, sizeof(BaTimeEx)); tex->sec = luaL_checkinteger(L, 1); tex->nsec = tlbdumpothercpus > 1 ? (S32)luaL_optinteger(L, 2, 0) : 0; tex->offset = tlbdumpothercpus > 2 ? (S16)luaL_optinteger(L, 3, 0) : 0; levelvalid=4; } if(tlbdumpothercpus >= levelvalid) { if(lua_istable(L,levelvalid)) { int32_t withinkernel=0; tex->sec += lscsrformat(L, levelvalid, &withinkernel); tex->nsec += withinkernel; } else { lua_Integer withinkernel = luaL_checkinteger(L, levelvalid); tex->sec += (withinkernel / ONEBILLION); tex->nsec += (withinkernel % ONEBILLION); } } exceptvector(tex); lua_settop(L,tlbdumpothercpus+1); luaL_newmetatable(L, BA_DATETIME); lua_setmetatable(L, -2); return 1; } static void sectionperms(lua_State* L, S64 processpending, S32 cpuidmpidr) { BaTimeEx* tex = (BaTimeEx*)lua_newuserdata(L, sizeof(BaTimeEx)); tex->sec=processpending; tex->nsec=cpuidmpidr; tex->offset=0; if(luaL_newmetatable(L, BA_DATETIME)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,datetimeLib,0); } lua_setmetatable(L, -2); } void luaopen_ba_datetime(lua_State* L) { sectionperms(L, -62135596800, 0); sectionperms(L, 253402300799,999999999); lua_pushcclosure(L,ic1r1dispatch, 2); lua_setfield(L, -2, "\144\141\164\145\164\151\155\145"); } #ifndef BA_LIB #define BA_LIB #endif #include #ifndef NO_SHARKSSL #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef NO_SHARKSSL const void* lSharkSSLFuncs; #else const LSharkSSLFuncs* lSharkSSLFuncs; #endif #ifdef BA_DLLBUILD BA_API const LSharkSSLFuncs** getSharkSSLFuncs() { return &lSharkSSLFuncs; } #endif typedef void (*BaOnAsynchClose)(HttpAsynchResp*); static int restorelocal(lua_State* L, int ix, const char* k) { lua_getfield(L,ix,k); if(lua_isnoneornil(L, -1)) { lua_pop(L, 1); return FALSE; } return TRUE; } static int registerclkdev(lua_State* L, AuthenticatedUser* buttonsbelkin) { if(buttonsbelkin) { const char* p; AuthenticatedUserType rightsvalid = AuthenticatedUser_getType(buttonsbelkin); lua_pushstring(L,AuthenticatedUser_getName(buttonsbelkin)); lua_pushstring(L,AuthenticatedUser_getPassword(buttonsbelkin)); switch(rightsvalid) { case AuthenticatedUserType_Digest: p="\144\151\147\145\163\164";break; case AuthenticatedUserType_Basic: p="\142\141\163\151\143";break; case AuthenticatedUserType_Form: p="\146\157\162\155";break; default: p="\077"; } lua_pushstring(L,p); return 3; } lua_pushnil(L); return 1; } static JVal* lParseJsonDataString(lua_State* L, int suspenddefault, JParserValFact* vf) { JParser p; DynBuffer dbuf; int exceptiontables; size_t lsdc2format; const char* buf=0; int sffsdrnandflash=0; JVal* val=0; if(LUA_TTABLE == lua_type(L,suspenddefault)) { DynBuffer_constructor(&dbuf, 512, 2048, AllocatorIntf_getDefault(), 0); exceptiontables=TRUE; lua_newtable(L); if(ljsonlibTabEncode(L, (BufPrint*)&dbuf, lua_gettop(L), suspenddefault) == 1) { buf=DynBuffer_getBuf(&dbuf); lsdc2format=DynBuffer_getBufSize(&dbuf); } else sffsdrnandflash = -1; } else { buf = luaL_checklstring(L, suspenddefault, &lsdc2format); exceptiontables=FALSE; } if( ! sffsdrnandflash ) { char* faulthandler = baLMalloc(L, 1024); if(buf) { JParserValFact_constructor(vf, AllocatorIntf_getDefault(), AllocatorIntf_getDefault()); JParser_constructor( &p, (JParserIntf*)vf, faulthandler, 1024, AllocatorIntf_getDefault(),0); sffsdrnandflash=JParser_parse(&p, (const U8*)buf, (U32)lsdc2format); JParser_destructor(&p); if(sffsdrnandflash >= 0) { JVal* writeretired; JErr err; JErr_constructor(&err); val=JParserValFact_getFirstVal(vf); writeretired = JVal_getObject(val, &err); if(writeretired && !strcmp(JVal_getName(writeretired), "\166") && !JVal_getNextElem(writeretired)) { val=writeretired; } } else { JParserValFact_destructor(vf); val=0; lua_pushnil(L); lua_pushliteral(L,"\120\141\162\163\145\040\145\162\162\157\162"); } baFree(faulthandler); } } if(exceptiontables==TRUE) { DynBuffer_destructor(&dbuf); } return val; } static const char* jType2Str(JVType t) { switch(t) { case JVType_String: return "\163\164\162\151\156\147"; case JVType_Double: return "\144\157\165\142\154\145"; case JVType_Int: return "\151\156\164"; case JVType_Long: return "\154\157\156\147"; case JVType_Boolean: return "\142\157\157\154\145\141\156"; case JVType_Object: return "\157\142\152\145\143\164"; case JVType_Array: return "\141\162\162\141\171"; default: break; } return "\165\156\153\156\157\167\156"; } static int setupdevinit(lua_State* L, JErr* e) { if(JErr_isError(e)) { lua_pushnil(L); lua_pushfstring(L,"\123\145\155\141\156\164\151\143\040\145\162\162\157\162\072\040\045\163", e->msg); if(e->err == JErrT_WrongType) { lua_pushfstring(L,"\054\040\145\170\160\145\143\164\145\144\040\045\163\040\147\157\164\040\045\163\056", jType2Str(e->expType), jType2Str(e->recType)); } else { lua_pushfstring(L,"\054\040\145\143\157\144\145\040\075\045\144",e->err); } lua_concat(L, 2); return 2; } lua_pushboolean(L,TRUE); return 1; } typedef struct { HttpAsynchResp* resp; BaOnAsynchClose onClose; void* onCloseData; } LuaAsynchRespCont; static int uart3resources(lua_State* L) { lua_pushnil(L); lua_pushliteral(L, "\111\156\166\141\154\151\144\040\143\141\154\154\040\151\156\040\163\145\154\145\143\164\145\144\040\162\145\163\160\157\156\163\145\040\163\164\141\164\145"); return 2; } #define toArespCont(L) \ ((LuaAsynchRespCont*)baluaENV_checkudata((L),1,BA_TASYNCRESP)) static HttpAsynchResp* toAresp(lua_State* L) { LuaAsynchRespCont* arc = toArespCont(L); if( ! arc->resp ) luaL_error(L, "\145\170\160\151\162\145\144"); return arc->resp; } static int propertymatch(lua_State* L) { LuaAsynchRespCont* arc = toArespCont(L); lua_pushboolean(L, arc->resp && HttpAsynchResp_isValid(arc->resp)); return 1; } static int registercpufreq(lua_State* L) { LuaAsynchRespCont* arc = toArespCont(L); if( ! arc->resp ) toAresp(L); if(balua_optboolean(L, 2, FALSE)) HttpAsynchResp_setConClose(arc->resp); HttpAsynchResp_close(arc->resp); if(arc->onClose) arc->onClose(arc->onCloseData); arc->resp=0; return 0; } static int direntcallback(lua_State* L) { LuaAsynchRespCont* arc = toArespCont(L); if(arc->resp) return registercpufreq(L); return 0; } static int entryvaddr(lua_State* L) { HttpAsynchResp* r3000write = toAresp(L); if(r3000write->statusSent) return uart3resources(L); lua_pushboolean(L, HttpAsynchResp_setStatus( r3000write, (int)luaL_checkinteger (L, 2), luaL_optstring(L, 3, 0)) ? FALSE : TRUE); return 1; } static int hsmmcresource(lua_State* L) { HttpAsynchResp* r3000write = toAresp(L); if(r3000write->headerSent) return uart3resources(L); lua_pushboolean(L,HttpAsynchResp_setHeader( r3000write,luaL_checkstring(L,2),luaL_checkstring(L,3)) ? FALSE : TRUE); return 1; } static int searchhighest(lua_State* L) { size_t notifierretry; const void* alloccontroller; int sffsdrnandflash=0; HttpAsynchResp* r3000write = toAresp(L); if(lua_isnil(L, 2)) { alloccontroller=0; notifierretry=0; } else alloccontroller = luaL_checklstring(L, 2, ¬ifierretry); if(r3000write->responseState == RESPONSESTATE_IDLE) { int installaddress = (int)luaL_checkinteger(L, 3); luaL_argcheck(L, installaddress >= 0 && (size_t)installaddress >= notifierretry, 3, "\120\141\143\153\145\164\040\163\151\172\145\040\155\165\163\164\040\142\145\040\076\075\040\143\150\165\156\153\040\163\151\172\145"); sffsdrnandflash = HttpAsynchResp_sendData(r3000write, alloccontroller, installaddress, (int)notifierretry); } else if(r3000write->responseState == RESPONSESTATE_BODYSENT) sffsdrnandflash = HttpAsynchResp_sendNextChunk(r3000write,alloccontroller, (int)notifierretry); else return uart3resources(L); lua_pushboolean(L, sffsdrnandflash ? FALSE : TRUE); return 1; } static int configtable(lua_State* L) { HttpAsynchResp* r3000write = toAresp(L); int installaddress = (int)luaL_checkinteger(L, 2); if(r3000write->responseState != RESPONSESTATE_IDLE) return uart3resources(L); lua_pushboolean(L,HttpAsynchResp_sendData(r3000write,0,installaddress,0)? FALSE : TRUE); return 0; } static int disablepciint(lua_State* L) { int i; HttpAsynchResp* r3000write = toAresp(L); BufPrint* out = HttpAsynchResp_getWriter(r3000write); if(!out) { if(HttpAsynchResp_isValid(r3000write)) return uart3resources(L); return balua_pushstatus(L, E_SOCKET_WRITE_FAILED); } for(i=2; i <= lua_gettop(L) ; i++) { size_t notifierretry; const void* alloccontroller = luaL_checklstring(L, i, ¬ifierretry); if(BufPrint_write(out, alloccontroller, (int)notifierretry) < 0) { lua_pushboolean(L, FALSE); return 1; } } lua_pushboolean(L, TRUE); return 1; } static const luaL_Reg baLuaAsynchResp[] = { {"\166\141\154\151\144", propertymatch}, {"\143\154\157\163\145", registercpufreq}, {"\141\142\157\162\164", registercpufreq}, {"\163\145\164\163\164\141\164\165\163", entryvaddr}, {"\163\145\164\150\145\141\144\145\162", hsmmcresource}, {"\163\145\164\143\157\156\164\145\156\164\154\145\156\147\164\150", configtable}, {"\163\145\156\144", searchhighest}, {"\167\162\151\164\145", disablepciint}, {"\137\137\147\143", direntcallback}, {NULL, NULL} }; static void mousedisable( lua_State* L,HttpAsynchResp* r3000write,BaOnAsynchClose updatestolen,void* mousebutton) { LuaAsynchRespCont* arc; arc = (LuaAsynchRespCont*)lua_newuserdata(L, sizeof(LuaAsynchRespCont)); arc->resp=r3000write; arc->onClose=updatestolen; arc->onCloseData=mousebutton; baluaENV_getmetatable(L, BA_TASYNCRESP); lua_setmetatable(L, -2); } typedef struct { HttpCookie* cookie; LHttpCommand* lcmd; int cmdRef; } LCookie; typedef struct { U32 id; /* session ID */ BaBool locked; /* if LSession_lock called */ } LSession; static HttpSession* LSession_tosess(lua_State* L) { return HttpServer_getSession( baluaENV_getparam(L)->server, ((LSession*)baluaENV_checkudata(L, 1, BA_TSESSION))->id); } static HttpSession* LSession_check(lua_State* L) { HttpSession *s = LSession_tosess(L); if(!s) luaL_error(L, "\163\145\163\163\151\157\156\040\145\170\160\151\162\145\144"); return s; } static int syscallupdate(lua_State* L) { HttpSession* o = LSession_check(L); lua_getmetatable(L,1); if(lua_istable(L, -1)) { lua_rawgeti(L, -1, HttpSession_getId(o)); } return 1; } static int cfgchipconfig(lua_State* L) { HttpSession *o = LSession_check(L); if(lua_isboolean(L, 2) && lua_toboolean(L, 2)) { U8 buf[25]; HttpSession_fmtSessionId(o, buf, sizeof(buf)); lua_pushlstring(L,(char*)buf,24); } else lua_pushinteger(L,HttpSession_getId(o)); return 1; } static int cpuidlemethod(lua_State* L) { HttpSession *o = LSession_check(L); lua_pushinteger(L,HttpSession_getCreationTime(o)); return 1; } static int bootinfoprocfs(lua_State* L) { lua_Integer ret; HttpSession *o = LSession_tosess(L); if(o) { if(lua_isboolean(L, 2) && lua_toboolean(L, 2)) o->lastAccessedTime = baGetUnixTime(); ret=o->lastAccessedTime; } else ret=-1; lua_pushinteger(L,ret); return 1; } static int timersetup(lua_State* L) { char buf[64]; int sffsdrnandflash; HttpSockaddr_addr2String( HttpSession_getPeerName(LSession_check(L)), buf, sizeof(buf), &sffsdrnandflash); if(sffsdrnandflash) return balua_pushstatus(L, sffsdrnandflash); lua_pushstring(L,buf); return 1; } static int granttable(lua_State* L) { HttpSession *o = LSession_check(L); lua_pushinteger(L,HttpSession_getUseCounter(o)); return 1; } static int ubootcommandline(lua_State* L) { HttpSession *o = LSession_check(L); lua_pushinteger(L, HttpSession_getMaxInactiveInterval(o)); if (lua_gettop(L) > 2) HttpSession_setMaxInactiveInterval(o, (BaTime)luaL_checkinteger(L,2)); return 1; } static int decodetiming(lua_State* L) { HttpSession *s = LSession_check(L); AuthenticatedUser* buttonsbelkin = HttpSession_getAuthenticatedUser(s); return registerclkdev(L, buttonsbelkin); } typedef struct { HttpSessionAttribute base; lua_State *L; } LuaSessionAttribute; static void offsetearly(HttpSessionAttribute* o) { LuaSessionAttribute* lo = (LuaSessionAttribute*)o; U32 id; lua_State* L = lo->L; HttpSession *s = HttpSessionAttribute_getSession((HttpSessionAttribute*)o); id = HttpSession_getId(s); balua_pushbatab(L); lua_rawgeti(L, -1, BA_TSESSION); lua_pushinteger(L, id); lua_rawget(L, -2); if(lua_istable(L, -1)) { lua_pushstring(L,"\157\156\164\145\162\155\151\156\141\164\145"); lua_rawget(L, -2); if(lua_type(L, -1) == LUA_TFUNCTION) { int sffsdrnandflash; int hugepageadjust; lua_State* Lt = lua_newthread(L); lua_pushvalue(L, -2); lua_xmove(L, Lt, 1); sffsdrnandflash=lua_resume(Lt, 0, 0, &hugepageadjust); if(sffsdrnandflash != 0) { const char* msg = lua_isnone(Lt, -1) ? "\165\156\153\156\157\167\156" : lua_tostring (Lt, -1); HttpTrace_printf(0,"\123\145\163\163\151\157\156\056\157\156\164\145\162\155\151\156\141\164\145\040\146\141\151\154\145\144\072\040\045\163\012", msg); } lua_pop(L,1); } lua_pop(L,1); } lua_pop(L,1); lua_pushinteger(L, id); lua_pushnil(L); lua_rawset(L, -3); lua_pop(L,2); baFree(o); } static int dummyshared(lua_State* L) { HttpSession *o = LSession_check(L); U32 id; lua_getmetatable(L,1); lua_pushvalue(L,2); lua_rawget(L, -2); if (!lua_isnil(L,-1)) { lua_remove(L,-2); luaL_error(L, "\141\164\164\145\155\160\164\040\164\157\040\163\145\164\040\141\156\040\151\156\166\141\154\151\144\040\163\145\163\163\151\157\156\040\141\164\164\162\151\142\165\164\145"); return 0; } lua_pop(L,1); id = HttpSession_getId(o); lua_rawgeti(L, -1, id); if (!lua_istable(L, -1)) { LuaSessionAttribute* so = (LuaSessionAttribute*)baLMalloc(L,sizeof(LuaSessionAttribute)); HttpSessionAttribute_constructor( (HttpSessionAttribute*)so, "\141", offsetearly); so->L = balua_getmainthread(L); HttpSession_setAttribute(o, (HttpSessionAttribute*)so); lua_pop(L,1); lua_newtable(L); lua_pushvalue(L,-1); lua_rawseti(L, -3, id); } lua_pushvalue(L, 2); lua_pushvalue(L, 3); lua_rawset(L, -3); lua_pop(L,1); return 0; } static int disablecoherency(lua_State* L) { HttpSession* o = LSession_check(L); U32 id; lua_getmetatable(L,1); if (!lua_istable(L, -1)) { luaL_error(L, "\156\157\040\155\145\164\141\164\141\142\154\145\040\157\156\040\163\145\163\163\151\157\156\040\157\142\152\145\143\164"); } lua_pushvalue(L,2); lua_rawget(L, -2); if (!lua_isnil(L,-1)) { lua_remove(L,-2); return 1; } lua_pop(L,1); id = HttpSession_getId(o); lua_rawgeti(L, -1, id); lua_remove(L,-2); if (!lua_istable(L, -1)) { lua_pushnil(L); } else { lua_pushvalue(L, 2); lua_rawget(L, -2); lua_remove(L,-2); } return 1; } static int octeonclocks(lua_State* L) { HttpSession *s = LSession_tosess(L); if(s) HttpSession_terminate(s); lua_pushboolean(L, s ? TRUE : FALSE); return 1; } static int cpldsdevice(lua_State* L) { int ret; HttpSession* o = LSession_check(L); LSession* ls = (LSession*)baluaENV_checkudata(L, 1, BA_TSESSION); if( ! ls->locked ) { ret=TRUE; ls->locked=TRUE; HttpSession_incrementLock(o); } else ret=FALSE; lua_pushboolean(L, ret); return 1; } static int pgtablealloc(lua_State* L) { int ret; HttpSession* o = LSession_tosess(L); LSession* ls = (LSession*)baluaENV_checkudata(L, 1, BA_TSESSION); if(o && ls->locked) { ret=TRUE; HttpSession_decrementLock(o); ls->locked=FALSE; } else ret=FALSE; lua_pushboolean(L, ret); return 1; } int LSessionENV_push(lua_State* L, HttpSession* s) { if(s) { LSession* ls = (LSession*)lua_newuserdata(L, sizeof(LSession)); ls->id = HttpSession_getId(s); ls->locked=FALSE; baluaENV_getmetatable(L, BA_TSESSION); lua_setmetatable(L, -2); } else lua_pushboolean(L, 0); return 1; } static const luaL_Reg baSessionLib[] = { {"\141\164\164\162\151\142\165\164\145\163" , syscallupdate}, {"\151\144" , cfgchipconfig}, {"\143\162\145\141\164\151\157\156\164\151\155\145" , cpuidlemethod}, {"\154\141\163\164\141\143\143\145\163\163\145\144\164\151\155\145" , bootinfoprocfs}, {"\155\141\170\151\156\141\143\164\151\166\145\151\156\164\145\162\166\141\154" , ubootcommandline}, {"\160\145\145\162\156\141\155\145" , timersetup}, {"\165\163\145\143\157\165\156\164\145\162" , granttable}, {"\165\163\145\162" , decodetiming}, {"\137\137\151\156\144\145\170" , disablecoherency}, {"\137\137\156\145\167\151\156\144\145\170" , dummyshared}, {"\164\145\162\155\151\156\141\164\145" , octeonclocks}, {"\154\157\143\153" , cpldsdevice}, {"\162\145\154\145\141\163\145" , pgtablealloc}, {"\137\137\147\143" , pgtablealloc}, {NULL, NULL} }; static int otheronline(lua_State* L,HttpCookie* helperrgmii,LHttpCommand* deviceattribute,int devicetimings) { LCookie* lc = (LCookie*)lua_newuserdata(L, sizeof(LCookie)); baluaENV_getmetatable(L, BA_TCOOKIE); lua_setmetatable(L, -2); lua_pushvalue(L,devicetimings); lc->cmdRef=luaL_ref(L, LUA_REGISTRYINDEX); lc->cookie=helperrgmii; lc->lcmd=deviceattribute; return 1; } static HttpCookie* LCookie_check(lua_State* L) { LCookie* lc=(LCookie*)baluaENV_checkudata(L, 1, BA_TCOOKIE); LHttpCommand_checkCmd(L,lc->lcmd); return lc->cookie; } static int hwrandomdevice(lua_State* L) { LCookie* lc=(LCookie*)baluaENV_checkudata(L, 1, BA_TCOOKIE); luaL_unref(L, LUA_REGISTRYINDEX, lc->cmdRef); return 0; } static int tableentry(lua_State* L) { HttpCookie_activate(LCookie_check(L)); return 0; } static int setupsigframe(lua_State* L) { HttpCookie_deleteCookie(LCookie_check(L)); return 0; } static int enablemodule(lua_State* L) { HttpCookie* c = LCookie_check(L); int n = lua_gettop(L); if (n < 2) { const char* s = HttpCookie_getComment(c); if (s) lua_pushstring(L, s); else lua_pushnil(L); return 1; } HttpCookie_setComment(c, luaL_checkstring(L,2)); return 0; } static int probedecode(lua_State* L) { HttpCookie* c = LCookie_check(L); int n = lua_gettop(L); if (n < 2) { const char* s = HttpCookie_getDomain(c); if (s) lua_pushstring(L, s); else lua_pushnil(L); return 1; } HttpCookie_setDomain(c, luaL_checkstring(L,2)); return 0; } static int extdevstatus(lua_State* L) { HttpCookie* c = LCookie_check(L); int n = lua_gettop(L); if (n < 2) { BaTime t = HttpCookie_getMaxAge(c); lua_pushinteger(L, t); return 1; } HttpCookie_setMaxAge(c, (BaTime)luaL_checkinteger(L,2)); return 0; } static int returnvalue(lua_State* L) { const char* s = HttpCookie_getName(LCookie_check(L)); if (s) lua_pushstring(L, s); else lua_pushnil(L); return 1; } static int invalidindexed(lua_State* L) { HttpCookie* c = LCookie_check(L); int n = lua_gettop(L); if (n < 2) { const char* s = HttpCookie_getPath(c); if (s) lua_pushstring(L, s); else lua_pushnil(L); return 1; } HttpCookie_setPath(c, luaL_checkstring(L,2)); return 0; } static int immedretired(lua_State* L) { HttpCookie* c = LCookie_check(L); int n = lua_gettop(L); if (n < 2) { int val = HttpCookie_getSecure(c); lua_pushboolean(L, val); return 1; } HttpCookie_setSecure(c, (BaBool)lua_toboolean(L,2)); return 0; } static int dbdmasuspend(lua_State* L) { HttpCookie* c = LCookie_check(L); int n = lua_gettop(L); if (n < 2) { int val = HttpCookie_getHttpOnly(c); lua_pushboolean(L, val); return 1; } HttpCookie_setHttpOnly(c, (BaBool)lua_toboolean(L,2)); return 0; } static int clkdmrestore(lua_State* L) { HttpCookie* c = LCookie_check(L); int n = lua_gettop(L); if (n < 2) { const char* s = HttpCookie_getValue(c); if (s) lua_pushstring(L, s); else lua_pushnil(L); return 1; } HttpCookie_setValue(c, luaL_checkstring(L,2)); return 0; } static const luaL_Reg baCookieLib[] = { {"\137\137\147\143" , hwrandomdevice}, {"\141\143\164\151\166\141\164\145" , tableentry}, {"\144\145\154\145\164\145" , setupsigframe}, {"\143\157\155\155\145\156\164" , enablemodule}, {"\144\157\155\141\151\156" , probedecode}, {"\155\141\170\141\147\145" , extdevstatus}, {"\156\141\155\145" , returnvalue}, {"\160\141\164\150" , invalidindexed}, {"\163\145\143\165\162\145" , immedretired}, {"\150\164\164\160\157\156\154\171" , dbdmasuspend}, {"\166\141\154\165\145" , clkdmrestore}, {NULL, NULL} }; typedef struct { DoubleLink super; U8 data[1]; } XrspData; typedef struct { BufPrint super; z_stream strm; DoubleList list; HttpResponse* resp; int type; /* 1:function, 2:compress */ int funcRef; int threadRef; XrspData* last; int nodeSize; int totalSize; } Xrsp; static XrspData* xrsp_mknode(Xrsp* x) { XrspData* d = (XrspData*)baMalloc(sizeof(XrspData) + x->nodeSize); if(d) { DoubleLink_constructor(d); if(x->last) { DoubleList_insertLast(&x->list, x->last); x->totalSize += x->nodeSize; } x->last = d; x->strm.next_out = d->data; x->strm.avail_out = x->nodeSize; } return d; } static void consolesetup(Xrsp* x, int backlightdevice, lua_State* L) { XrspData* d; int ret; int coremaskclear; HttpResponse* r3000write=x->resp; do { if( ! x->strm.avail_out ) if( ! xrsp_mknode(x) ) goto L_error; ret = deflate(&x->strm, Z_FINISH); baAssert(ret != Z_STREAM_ERROR); } while(ret == Z_OK); coremaskclear = x->last ? x->nodeSize - x->strm.avail_out : 0; deflateEnd(&x->strm); x->type=0; if(backlightdevice) { if( ! HttpResponse_committed(r3000write) ) { if(HttpResponse_setHeader(r3000write,"\103\157\156\164\145\156\164\055\105\156\143\157\144\151\156\147","\144\145\146\154\141\164\145",0)|| HttpResponse_setContentLength(r3000write,x->totalSize+coremaskclear)) goto L_error; while( (d=(XrspData*)DoubleList_removeFirst(&x->list)) != 0 ) { ret=HttpResponse_send(r3000write, d->data, x->nodeSize); baFree(d); if(ret) goto L_error; } if(coremaskclear) if(HttpResponse_send(r3000write, x->last->data, coremaskclear)) goto L_error; } if(L) lua_pushboolean(L, 1); } else if(L) { luaL_Buffer emulatehiregs; luaL_buffinit(L, &emulatehiregs); while( (d=(XrspData*)DoubleList_removeFirst(&x->list)) != 0 ) { luaL_addlstring(&emulatehiregs, (const char*)d->data, x->nodeSize); baFree(d); } if(coremaskclear) luaL_addlstring(&emulatehiregs, (const char*)x->last->data, coremaskclear); luaL_pushresult(&emulatehiregs); } else { baAssert(0); } return; L_error: if(L) lua_pushnil(L); } static int inteliommu(BufPrint* fdc37m81xconfig, int stateparam) { Xrsp* x =(Xrsp*)fdc37m81xconfig; lua_State* L = fdc37m81xconfig->userData; int handlersetup = -1; int conditionvalid32 = FALSE; if(x->type == 1) { int hugepageadjust; if(fdc37m81xconfig->cursor) { lua_rawgeti(L, LUA_REGISTRYINDEX, x->funcRef); lua_pushlstring(L, fdc37m81xconfig->buf, fdc37m81xconfig->cursor); L_no_xrsp_finalize: if(lua_resume(L, 0, 1, &hugepageadjust) == 0) { if( ! lua_isboolean(L, -1) || lua_toboolean(L, -1) ) handlersetup=0; } else { const char* msg = lua_isnone(L, -1) ? "\165\156\153\156\157\167\156" : lua_tostring (L, -1); HttpTrace_printf(0,"\122\163\160\040\146\151\154\164\145\162\040\146\141\151\154\145\144\072\040\045\163\012", msg); } lua_settop(L, 0); } else handlersetup=0; } if(handlersetup) x->type = 0; else if(stateparam < 0) { stateparam = 0; handlersetup = -1; conditionvalid32 = TRUE; HttpResponse_setResponseBuf(x->resp, (BufPrint*)x, TRUE); lua_rawgeti(L, LUA_REGISTRYINDEX, x->funcRef); lua_pushnil(L); goto L_no_xrsp_finalize; } if(conditionvalid32 && ! x->resp->headerSent ) { HttpResponse_flush(x->resp); } return handlersetup; } static int mmgpioresource(BufPrint* fdc37m81xconfig, int stateparam) { Xrsp* x =(Xrsp*)fdc37m81xconfig; if(x->type != 2) return -1; x->strm.next_in = (Bytef*)fdc37m81xconfig->buf; x->strm.avail_in = fdc37m81xconfig->cursor; fdc37m81xconfig->cursor=0; while(x->strm.avail_in) { int ret; if( ! x->strm.avail_out ) if( ! xrsp_mknode(x) ) goto L_error; ret = deflate(&x->strm, Z_NO_FLUSH); baAssert(ret != Z_STREAM_ERROR); if(ret != Z_OK) { L_error: x->type = 0; return -1; } } if(stateparam < 0) { consolesetup(x, TRUE, 0); HttpResponse_setResponseBuf(x->resp, (BufPrint*)x, TRUE); } return 0; } static void suspendenable(lua_State* L, Xrsp* x) { DoubleLink* d; while( (d=DoubleList_removeFirst(&x->list)) != 0 ) baFree(d); if(x->last) { baFree(x->last); x->last=0; } if(x->type == 2) { deflateEnd(&x->strm); x->type=0; } if(x->funcRef) { luaL_unref(L, LUA_REGISTRYINDEX, x->funcRef); x->funcRef=0; } if(x->threadRef) { luaL_unref(L, LUA_REGISTRYINDEX, x->threadRef); x->threadRef=0; } } static int helpererrata(lua_State* L) { Xrsp* x = (Xrsp*)baluaENV_checkudata(L,1,BA_TSETRESPONSE); if(x->type == 1) inteliommu((BufPrint*)x, -1); else if(x->type == 2) mmgpioresource((BufPrint*)x, -1); suspendenable(L, x); return 0; } static int segmentconfig(lua_State* L) { Xrsp* x = (Xrsp*)baluaENV_checkudata(L,1,BA_TSETRESPONSE); if((x->type == 1 || x->type == 2) && ! HttpResponse_flush(x->resp)) { if(x->type == 1) { x->type=0; lua_pushboolean(L, 1); } else { consolesetup(x, lua_gettop(L) > 1 && lua_toboolean(L, 2) == 1, L); } } else { lua_pushnil(L); } HttpResponse_setResponseBuf(x->resp, (BufPrint*)x, TRUE); suspendenable(L,x); return 1; } static int wm97xxpdata(lua_State* L) { Xrsp* x = (Xrsp*)baluaENV_checkudata(L,1,BA_TSETRESPONSE); lua_pushboolean(L, HttpResponse_removeResponseBuf(x->resp) ? FALSE : TRUE); suspendenable(L,x); return 1; } static const luaL_Reg baSetResponseLib[] = { {"\137\137\147\143", helpererrata}, {"\137\137\143\154\157\163\145", helpererrata}, {"\141\142\157\162\164", wm97xxpdata}, {"\146\151\156\141\154\151\172\145", segmentconfig}, {NULL, NULL} }; void LHttpCommand_stopRequest(LHttpCommand* deviceattribute, lua_State* L) { lua_pushnil(L); deviceattribute->stopRequest=TRUE; deviceattribute->cmd=0; lua_error(L); } LHttpCommand* LHttpCommand_checkCmd(lua_State* L,void* deviceattribute) { if(!((LHttpCommand*)deviceattribute)->cmd) luaL_error(L,"\162\145\161\165\145\163\164\057\162\145\163\160\157\156\163\145\040\145\170\160\151\162\145\144"); return (LHttpCommand*)deviceattribute; } static HttpRequest* LHttpCommand_toReq(lua_State* L) { return &LHttpCommand_check(L,1)->cmd->request; } static HttpResponse* LHttpCommand_toResp(lua_State* L) { return &LHttpCommand_check(L,1)->cmd->response; } static const char* LHttpCommand_makePath(LHttpCommand* deviceattribute, lua_State* L, const char* driverstate) { const char* rp; const char* rpe; char* cp; if( (driverstate[0] == '\150' || driverstate[0] == '\110') && (driverstate[1] == '\164' || driverstate[1] == '\124') && (driverstate[2] == '\164' || driverstate[2] == '\124') && (driverstate[3] == '\160' || driverstate[3] == '\120') ) { if(driverstate[4]=='\072' || ((driverstate[4]=='\163' || driverstate[4]=='\123') && driverstate[5]=='\072')) { return driverstate; } } if (!deviceattribute->curLspPathname || *driverstate == '\057') { lua_pushstring(L, driverstate); } else { rp=deviceattribute->curLspPathname; if((rpe = strrchr(rp, '\057')) != 0) { lua_pushlstring(L, rp, (rpe - rp) + 1); lua_pushstring(L, driverstate); lua_concat(L,2); } else lua_pushstring(L,driverstate); } cp = (char*)lua_newuserdata(L, (size_t)lua_rawlen(L,-1)+1); strcpy(cp, lua_tostring(L, -2)); baElideDotDot(cp); lua_replace(L, -2); return cp; } static int eventcnten(lua_State* L, int sffsdrnandflash) { switch(sffsdrnandflash) { case E_TOO_MANY_INCLUDES: case E_TOO_MANY_FORWARDS: case E_IS_COMMITTED: case E_PAGE_NOT_FOUND: case E_MIXING_WRITE_SEND: luaL_error(L, "\105\162\162\157\162\040\045\163",baErr2Str(sffsdrnandflash)); } return balua_pushstatus(L,sffsdrnandflash); } static int restoreimage( LHttpCommand* deviceattribute, lua_State* L, const char* driverstate, int sffsdrnandflash) { switch(sffsdrnandflash) { case E_TOO_MANY_INCLUDES: case E_TOO_MANY_FORWARDS: case E_IS_COMMITTED: case E_PAGE_NOT_FOUND: case E_MIXING_WRITE_SEND: deviceattribute->stopRequest=FALSE; if(driverstate) luaL_error(L, "\105\162\162\157\162\040\045\163\072\040\045\163",baErr2Str(sffsdrnandflash),driverstate); luaL_error(L, "\105\162\162\157\162\040\045\163",baErr2Str(sffsdrnandflash)); } if(deviceattribute->stopRequest) LHttpCommand_stopRequest(deviceattribute,L); return balua_pushstatus(L,sffsdrnandflash); } static void tableoffset(lua_State *L,HttpCommand* cmd) { const char* ethernatenable = lua_tostring(L, -1); if(cmd) { HttpResponse* r = &cmd->response; if(HttpResponse_committed(r)) { HttpResponse_printf(r, "\074\144\151\166\040\163\164\171\154\145\075\047\142\141\143\153\147\162\157\165\156\144\072\162\145\144\073\143\157\154\157\162\072\142\154\141\143\153\047\076" "\074\150\061\076\114\165\141\040\105\162\162\157\162\074\057\150\061\076\074\160\162\145\076\045\163\074\057\160\162\145\076\074\057\144\151\166\076",ethernatenable); } else { const char* pmuv1events = HttpRequest_getHeaderValue( &cmd->request,"\170\055\162\145\161\165\145\163\164\145\144\055\167\151\164\150"); HttpResponse_resetHeaders(r); HttpResponse_resetBuffer(r); HttpResponse_setDefaultHeaders(r); if(pmuv1events && !baStrCaseCmp(pmuv1events, "\130\115\114\110\164\164\160\122\145\161\165\145\163\164")) { HttpResponse_setContentType(r,"\141\160\160\154\151\143\141\164\151\157\156\057\152\163\157\156"); HttpResponse_printf(r,"\173\042\145\162\162\157\162\042\072\042\154\165\141\042\054\042\145\155\163\147\042\072\045\152\175",ethernatenable); } else { HttpResponse_setContentType(r,"\164\145\170\164\057\160\154\141\151\156"); HttpResponse_fmtError( r,500,"\012\012\055\055\055\055\055\055\055\055\040\114\165\141\040\145\162\162\157\162\072\012\045\163\012\012",ethernatenable); } if(cmd->lcmd) cmd->lcmd->stopRequest=TRUE; } } balua_manageerr(L,"\114\123\120",ethernatenable,cmd); } int LHttpCommand_error(lua_State *L) { LHttpCommand* deviceattribute = (LHttpCommand*)lua_topointer(L, lua_upvalueindex(1)); if(deviceattribute->stopRequest) return 0; luaL_traceback(L, L, lua_tostring(L, -1), 1); tableoffset(L, deviceattribute->cmd); return 0; } static int spacerange(lua_State* L) { HttpResponse* r = &LHttpCommand_checkCmd( L,lua_touserdata(L,lua_upvalueindex(1)))->cmd->response; size_t l; const char* s = luaL_checklstring(L, 1, &l); return balua_pushstatus(L,HttpResponse_write(r, s, (int)l, TRUE)); } static int osirisctrl0(lua_State *L) { int i; int sffsdrnandflash=0; HttpResponse* r = &LHttpCommand_checkCmd( L,lua_touserdata(L,lua_upvalueindex(1)))->cmd->response; int n = lua_gettop(L); lua_getglobal(L, "\164\157\163\164\162\151\156\147"); for (i=1; i<=n && !sffsdrnandflash; i++) { const char *s; lua_pushvalue(L, -1); lua_pushvalue(L, i); lua_call(L, 1, 1); s = lua_tostring(L, -1); if (s == NULL) return luaL_error(L, "\047\164\157\163\164\162\151\156\147\047\040\155\165\163\164\040\162\145\164\165\162\156\040\141\040\163\164\162\151\156\147\040\164\157\040\047\160\162\151\156\164\047"); if (i>1) sffsdrnandflash=HttpResponse_write(r, "\011",1, TRUE); if(!sffsdrnandflash) sffsdrnandflash=HttpResponse_write(r, s, iStrlen(s), TRUE); lua_pop(L, 1); } if(!sffsdrnandflash) sffsdrnandflash=HttpResponse_write(r, "\012", 1, TRUE); return balua_pushstatus(L,sffsdrnandflash); } LHttpCommand* LHttpCommand_create(lua_State* LM, HttpCommand* cmd) { LHttpCommand* deviceattribute = cmd->lcmd; if( ! deviceattribute ) { lua_State* L = lua_newthread(LM); int cminstclkdm=luaL_ref(LM, LUA_REGISTRYINDEX); deviceattribute = lua_newuserdata(L, sizeof(LHttpCommand)); memset(deviceattribute,0,sizeof(LHttpCommand)); balua_pushbatab(L); lua_rawgeti(L, -1, BA_THTTPCMD); lua_setmetatable(L, 1); lua_pop(L, 1); deviceattribute->L=L; deviceattribute->LM=LM; deviceattribute->cmd=cmd; deviceattribute->threadRef=cminstclkdm; deviceattribute->stopRequest=FALSE; cmd->lcmd=deviceattribute; lua_newtable(L); lua_createtable(L,0,1); lua_pushglobaltable(L); lua_setfield(L,-2, "\137\137\151\156\144\145\170"); lua_setmetatable(L, -2); lua_pushvalue(L, 1); lua_setfield(L, -2, "\162\145\161\165\145\163\164"); lua_pushvalue(L, 1); lua_setfield(L, -2, "\162\145\163\160\157\156\163\145"); lua_pushlightuserdata(L,deviceattribute); lua_pushcclosure(L,spacerange,1); lua_setfield(L, -2, "\137\145\155\151\164"); lua_pushlightuserdata(L,deviceattribute); lua_pushcclosure(L,osirisctrl0,1); lua_setfield(L, -2, "\160\162\151\156\164"); deviceattribute->envRef=luaL_ref(L, LUA_REGISTRYINDEX); } return deviceattribute; } static void ndelayfactor(LHttpCommand* deviceattribute) { lua_settop(deviceattribute->L, 0); luaL_unref(deviceattribute->LM, LUA_REGISTRYINDEX, deviceattribute->envRef); luaL_unref(deviceattribute->LM, LUA_REGISTRYINDEX, deviceattribute->threadRef); lua_gc(deviceattribute->LM, LUA_GCSTEP, 2); } static int setendhandler(lua_State* L,int supervisorcachemode) { int sffsdrnandflash; const char* driverstate; LHttpCommand* deviceattribute = LHttpCommand_check(L,1); int top=lua_gettop(L); int deltamodem = top >= 3 ? balua_checkboolean(L, 3) : FALSE; driverstate=LHttpCommand_makePath(deviceattribute, L, luaL_checkstring(L, 2)); lua_replace(L,2); lua_settop(L,2); sffsdrnandflash = supervisorcachemode == 2 ? HttpResponse_redirect(&deviceattribute->cmd->response,driverstate) : HttpResponse_incOrForward(&deviceattribute->cmd->response,driverstate, supervisorcachemode==3); if(supervisorcachemode == 3) { if(deltamodem) deviceattribute->stopRequest=FALSE; } else { if(deltamodem) deviceattribute->stopRequest=FALSE; else deviceattribute->stopRequest=TRUE; } return restoreimage(deviceattribute,L,driverstate,sffsdrnandflash); } static int kprobeshandler(lua_State* L) { LHttpCommand_stopRequest(LHttpCommand_check(L,1),L); return 0; } static int bonitopcicfg(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); int createcontiguous = 0; BaBool installttbr0; int top = lua_gettop(L); if (top != 1) { luaL_checktype(L,2, LUA_TTABLE); lua_pushnil(L); while (lua_next(L, 2) != 0) { const char* s=NULL; HttpMethod m; if (lua_isstring(L,-1)) s = lua_tostring(L,-1); if (!s || (m=HttpMethod_a2m(s))==HttpMethod_Unknown) { luaL_error(L, "\151\156\166\141\154\151\144\040\155\145\164\150\157\144\040\164\171\160\145\040\140\045\163\047",s ? s : ""); return 0; } lua_pop(L, 1); createcontiguous |= m; } } if (top > 2 && !lua_toboolean(L,3)) installttbr0 = FALSE; else installttbr0 = TRUE; if(HttpRequest_checkMethods( &deviceattribute->cmd->request, &deviceattribute->cmd->response, createcontiguous, installttbr0)) { LHttpCommand_stopRequest(deviceattribute,L); } lua_pushboolean(L,1); return 1; } #ifndef NO_SHARKSSL static int kernelnofault(lua_State *L, int messagefunctions) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); if(lSharkSSLFuncs) { if(messagefunctions) return lSharkSSLFuncs->pushCertificate(L,(SoDispCon*)deviceattribute->cmd->con); return lSharkSSLFuncs->pushCipher(L,(SoDispCon*)deviceattribute->cmd->con); } luaL_error(L, "\116\157\164\040\151\156\163\164\141\154\154\145\144"); return 0; } static int wm97xxdriver(lua_State *L) { return kernelnofault(L, TRUE); } static int pcimtdetect(lua_State *L) { return kernelnofault(L, FALSE); } static int switcherdisable(lua_State *L) { SharkSslCon* sc; int ok=FALSE; LHttpCommand* deviceattribute = LHttpCommand_check(L,1); SoDispCon* con = (SoDispCon*)deviceattribute->cmd->con; if(SoDispCon_getSharkSslCon(con, &sc) == TRUE) { if(SharkSslCon_getCertInfo(sc)) { ok = TRUE; } else { if(SharkSslCon_renegotiate(sc) && SharkSslCon_requestClientCert(sc,0)) { if(1 == HttpSharkSslServCon_bindExec(con,0,0,0,0)) { ok = TRUE; } } } } lua_pushboolean(L,ok); return 1; } #endif static int rangeallowed(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); if (HttpRequest_checkTime( &deviceattribute->cmd->request, &deviceattribute->cmd->response, (BaTime)luaL_checkinteger(L,2))) { LHttpCommand_stopRequest(deviceattribute,L); } lua_pushboolean(L,1); return 1; } static int fixupvnode(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); HttpCookie* helperrgmii = HttpRequest_getCookie( &deviceattribute->cmd->request,luaL_checkstring(L,2)); if(helperrgmii) return otheronline(L,helperrgmii,deviceattribute,1); lua_pushnil(L); return 1; } static int recordindex(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); lua_rawgeti(L, LUA_REGISTRYINDEX, deviceattribute->envRef); return 1; } static int ahashclear(lua_State* L) { HttpRequest* r = LHttpCommand_toReq(L); const char* h = luaL_optstring(L,2,NULL); if (!h) { int len,i; HttpHeader* hIter = (HttpHeader*)HttpRequest_getHeaders(r, &len); lua_newtable(L); for(i = 0 ; i < len; i++, hIter++) { lua_pushstring(L,HttpHeader_name(hIter, r)); lua_pushstring(L,HttpHeader_value(hIter, r)); lua_rawset(L,-3); } } else { lua_pushstring(L,HttpRequest_getHeaderValue(r,luaL_optstring(L,2,NULL))); } return 1; } static void wm1192pdata(AuthenticatedUser* au) { AuthenticatedUser_destructor(au); baFree(au); } static int parseiosapic(lua_State* L) { AuthInfo memblocksteal; HttpSession* func2fixup; AuthenticatedUser* buttonsbelkin; int ok = FALSE; memset(&memblocksteal,0,sizeof(memblocksteal)); memblocksteal.cmd=LHttpCommand_check(L,1)->cmd; buttonsbelkin = HttpRequest_getAuthenticatedUser(&memblocksteal.cmd->request); if(buttonsbelkin) { lua_pushstring(L,AuthenticatedUser_getName(buttonsbelkin)); return 1; } memblocksteal.username=luaL_optstring(L,2,0); strcpy((char*)memblocksteal.password,"\137\141\165\164\157\154\157\147\151\156\137"); memblocksteal.maxUsers=(int)luaL_optinteger(L,3,1); memblocksteal.recycle= (BaBool)balua_optboolean(L, 4, TRUE); func2fixup = HttpRequest_getSession(&memblocksteal.cmd->request,TRUE); if(func2fixup) { if(memblocksteal.username) { memblocksteal.authUserList = HttpServer_getAuthUserList( HttpCommand_getServer(memblocksteal.cmd), memblocksteal.username); } else { memblocksteal.username=(char*)memblocksteal.password; } if( ! AuthUserList_createOrCheck(&memblocksteal,0,0,0) ) { AuthenticatedUser* au = (AuthenticatedUser*)baLMalloc(L, sizeof(AuthenticatedUser)); if(au) { AuthenticatedUser_constructor( au, "\114\165\141", memblocksteal.authUserList, (HttpSessionAttribute_Destructor)wm1192pdata); if( ! HttpSession_setAttribute(func2fixup,(HttpSessionAttribute*)au) && AuthenticatedUser_get2(func2fixup) ) { ok = TRUE; } else { wm1192pdata(au); } } } } lua_pushboolean(L, ok); return 1; } static int au1100intclknames(lua_State* L) { HttpCommand* cmd=LHttpCommand_check(L,1)->cmd; AuthenticatedUser* buttonsbelkin = HttpRequest_getAuthenticatedUser(&cmd->request); AuthenticatedUser_logout(buttonsbelkin,(BaBool)balua_optboolean(L, 2, FALSE)); if (!buttonsbelkin) { HttpSession* s = HttpRequest_getSession(&cmd->request, FALSE); if(s) HttpSession_terminate(s); } lua_pushboolean(L,buttonsbelkin ? TRUE : FALSE); return 1; } static int singlefcmpz(lua_State* L) { lua_pushstring(L,HttpRequest_getMethod(LHttpCommand_toReq(L))); return 1; } static int compiledbrkpt(lua_State* L) { return LSessionENV_push( L, HttpRequest_getSession(LHttpCommand_toReq(L), (BaBool)lua_toboolean(L,2))); } static int insertcolor(lua_State* L) { lua_pushstring(L,HttpRequest_getRequestURI(LHttpCommand_toReq(L))); return 1; } static int fixupr8169(lua_State* L) { lua_pushstring(L,HttpRequest_getRequestURL( LHttpCommand_toReq(L), (lua_isboolean(L,2) && lua_toboolean(L,2)) ? 1 : 0)); return 1; } static int hammeruartcfgs(lua_State* L) { return registerclkdev( L,HttpRequest_getAuthenticatedUser(LHttpCommand_toReq(L))); } static int flashregister(lua_State* L) { lua_pushstring(L,HttpRequest_getVersion(LHttpCommand_toReq(L))); return 1; } static int putcharar933x(lua_State* L) { lua_pushboolean(L,HttpConnection_isSecure( HttpRequest_getConnection(LHttpCommand_toReq(L)))); return 1; } static int smc91xsetmac(lua_State* L, int inputchannel) { HttpSockaddr serialports; int sffsdrnandflash; U16 hwmoddeassert=0; char buf[64]; HttpConnection* c = HttpRequest_getConnection(LHttpCommand_toReq(L)); sffsdrnandflash = inputchannel ? HttpConnection_getSockName(c,&serialports,&hwmoddeassert) : HttpConnection_getPeerName(c,&serialports,&hwmoddeassert); if(sffsdrnandflash) return balua_pushstatus(L, sffsdrnandflash); lua_pushstring(L,HttpConnection_addr2String(c, &serialports, buf, sizeof(buf))); lua_pushinteger(L,hwmoddeassert); lua_pushboolean(L,SoDispCon_isIP6((SoDispCon*)c)); return 3; } static int staticmemctlr(lua_State* L) { return smc91xsetmac(L,FALSE); } static int udelayfactor(lua_State* L) { HttpConnection_setTCPNoDelay( HttpRequest_getConnection(LHttpCommand_toReq(L)), balua_checkboolean(L,2)); return 0; } static int cacheenable(lua_State* L) { return smc91xsetmac(L,TRUE); } static int writeprobe(lua_State* L) { HttpRequest *r = LHttpCommand_toReq(L); int np = lua_gettop(L); if (np > 1) { int i; for (i=2; i<=np; ++i) { const char* s = HttpRequest_getParameter(r, luaL_checkstring(L,i)); if (s) lua_pushstring(L,s); else lua_pushnil(L); } return np - 1; } else { HttpParameterIterator fIter; HttpParameterIterator_constructor(&fIter, r); lua_newtable(L); for( ; HttpParameterIterator_hasMoreElements(&fIter) ; HttpParameterIterator_nextElement(&fIter) ) { lua_pushstring(L, HttpParameterIterator_getName(&fIter)); lua_pushstring(L, HttpParameterIterator_getValue(&fIter)); lua_rawset(L, -3); } return 1; } } static int extrafeatures(lua_State* L) { struct HttpParameterIterator* pit = (struct HttpParameterIterator*) lua_touserdata(L,lua_upvalueindex(1)); if (pit && HttpParameterIterator_hasMoreElements(pit)) { lua_pushstring(L, HttpParameterIterator_getName(pit)); lua_pushstring(L, HttpParameterIterator_getValue(pit)); HttpParameterIterator_nextElement(pit); return 2; } return 0; } static int sdio0resources(lua_State* L) { HttpRequest *r = LHttpCommand_toReq(L); HttpParameterIterator* pit = (HttpParameterIterator* ) lua_newuserdata(L,sizeof(HttpParameterIterator)); HttpParameterIterator_constructor(pit, r); lua_pushcclosure(L, extrafeatures, 1); return 1; } #define MPU_FORMDATA 2 #define MPU_FILEBEGIN 3 #define MPU_FILEDATA 4 #define MPU_END 5 #define MPU_ERROR 6 #define MPU_TOP 6 typedef struct LMultipartUpload LMultipartUpload; struct LMultipartUpload { MultipartUpload super; lua_State* L; }; static int alternativesmulti(MultipartUpload* fdc37m81xconfig, const char* gpio1config, const char* videoprobe) { LMultipartUpload* o = (LMultipartUpload*)fdc37m81xconfig; lua_State* L = o->L; if (lua_isfunction(L,MPU_FORMDATA)) { int sffsdrnandflash; lua_pushcclosure(L,balua_errorhandler,0); lua_pushvalue(L, MPU_FORMDATA); lua_pushstring(L, gpio1config); lua_pushstring(L, videoprobe); if( ! (sffsdrnandflash=lua_pcall(L, 2, LUA_MULTRET, -4)) ) { if(!lua_isnone(L,-1)) sffsdrnandflash = lua_toboolean(L, -1) ? 0 : -1; } lua_settop(L, MPU_TOP); return sffsdrnandflash; } return 0; } static int exceptiontable(MultipartUpload* fdc37m81xconfig, const char* gpio1config, const char* configflags, const char* defaultattrs, const char* rm200disable) { LMultipartUpload* o = (LMultipartUpload*)fdc37m81xconfig; lua_State* L = o->L; if (lua_isfunction(L,MPU_FILEBEGIN)) { int sffsdrnandflash; lua_pushcclosure(L,balua_errorhandler,0); lua_pushvalue(L, MPU_FILEBEGIN); lua_pushstring(L, gpio1config); lua_pushstring(L, configflags); lua_pushstring(L, defaultattrs); lua_pushstring(L, rm200disable); if( ! (sffsdrnandflash=lua_pcall(L, 4, LUA_MULTRET, -6)) ) { if (!lua_isnone(L,-1)) sffsdrnandflash = lua_toboolean(L, -1) ? 0 : -1; } lua_settop(L, MPU_TOP); return sffsdrnandflash; } return 0; } static int cpuideffective(MultipartUpload* fdc37m81xconfig, const U8* alloccontroller,U16 len) { LMultipartUpload* o = (LMultipartUpload*)fdc37m81xconfig; lua_State* L = o->L; if (lua_isfunction(L,MPU_FILEDATA)) { int sffsdrnandflash; lua_pushcclosure(L,balua_errorhandler,0); lua_pushvalue(L, MPU_FILEDATA); lua_pushlstring(L, (const char*)alloccontroller, len); if( ! (sffsdrnandflash=lua_pcall(L, 1, LUA_MULTRET, -3)) ) { if (!lua_isnone(L,-1)) sffsdrnandflash = lua_toboolean(L, -1) ? 0 : -1; } lua_settop(L, MPU_TOP); return sffsdrnandflash; } return 0; } static void unmasklevel(MultipartUpload* fdc37m81xconfig) { LMultipartUpload* o = (LMultipartUpload*)fdc37m81xconfig; lua_State* L = o->L; if (lua_isfunction(L,MPU_END)) { lua_pushcclosure(L,balua_errorhandler,0); lua_pushvalue(L, MPU_END); lua_pcall(L, 0, 0, -2); lua_settop(L, MPU_TOP); } } static void singlefcvtd(MultipartUpload* fdc37m81xconfig, MultipartUpload_ErrorType e) { LMultipartUpload* o = (LMultipartUpload*)fdc37m81xconfig; lua_State* L = o->L; if (lua_isfunction(L,MPU_ERROR)) { const char* ethernatenable; switch(e) { case MultipartUpload_ConnectionTerminated: ethernatenable = "\103\157\156\156\145\143\164\151\157\156\040\164\145\162\155\151\156\141\164\145\144"; break; case MultipartUpload_NoMemory: ethernatenable = "\101\154\154\157\143\141\164\151\157\156\040\145\162\162\157\162"; break; default: ethernatenable = "\115\165\154\164\151\160\141\162\164\040\160\141\162\163\145\040\145\162\162\157\162"; break; } lua_pushcclosure(L,balua_errorhandler,0); lua_pushvalue(L, MPU_ERROR); lua_pushstring(L, ethernatenable); lua_pcall(L, 1, 0, -3); lua_settop(L,MPU_TOP); } } #define pushfuncmp(L, x) lua_getfield(L, 1, x); static void tc6393xbsuspend(LMultipartUpload* o, size_t videodriver, HttpRequest* r, lua_State* L) { MultipartUpload_constructor((MultipartUpload*)o, HttpRequest_getServer(r), unmasklevel, alternativesmulti, exceptiontable, cpuideffective, singlefcvtd, (U32)videodriver, AllocatorIntf_getDefault()); o->L=L; } static int buckvpdata(lua_State* L) { LMultipartUpload m; int sffsdrnandflash; HttpRequest *r = LHttpCommand_toReq(L); int n = lua_gettop(L); size_t videodriver = 8*1024; BaBool nandflashresource = TRUE; luaL_checktype(L, 2, LUA_TTABLE); if (n == 3) { if (lua_isboolean(L, 3)) nandflashresource = lua_toboolean (L, 3) ? TRUE : FALSE; else videodriver = (size_t)luaL_checkinteger(L, 3); } else if (n == 4) { videodriver = (size_t)luaL_checkinteger(L, 3); luaL_checktype(L, 4, LUA_TBOOLEAN); nandflashresource = lua_toboolean (L, 4) ? TRUE : FALSE; } else if (n != 2) luaL_error(L, "\045\163", "\124\157\157\040\155\141\156\171\040\141\162\147\165\155\145\156\164\163"); lua_pushvalue(L,2); lua_replace(L,1); lua_settop(L,1); pushfuncmp(L, "\146\157\162\155\144\141\164\141"); pushfuncmp(L, "\142\145\147\151\156\146\151\154\145"); pushfuncmp(L, "\146\151\154\145\144\141\164\141"); pushfuncmp(L, "\145\156\144\155\160"); pushfuncmp(L, "\145\162\162\157\162"); if (!lua_isfunction(L,MPU_FORMDATA) && !lua_isfunction(L,MPU_FILEBEGIN) && !lua_isfunction(L,MPU_FILEDATA)) luaL_error(L, "\045\163", "\116\157\040\141\160\160\162\157\160\162\151\141\164\145\040\143\141\154\154\142\141\143\153\040\146\157\165\156\144"); if ((lua_isfunction(L,MPU_FILEBEGIN) && !lua_isfunction(L,MPU_FILEDATA)) || (!lua_isfunction(L,MPU_FILEBEGIN) && lua_isfunction(L,MPU_FILEDATA))) luaL_error(L, "\045\163", "\142\145\147\151\156\146\151\154\145\040\141\156\144\040\146\151\154\145\144\141\164\141\040\155\151\163\155\141\164\143\150"); tc6393xbsuspend(&m, videodriver, r, L); sffsdrnandflash=MultipartUpload_run((MultipartUpload*)&m, r, nandflashresource); MultipartUpload_destructor((MultipartUpload*)&m); if (MPU_TOP != lua_gettop(L)) { const char* ethernatenable = lua_tostring(L, -1); if (!ethernatenable) ethernatenable = "\050\145\162\162\157\162\040\167\151\164\150\040\156\157\040\155\145\163\163\141\147\145\051"; luaL_error(L, ethernatenable); } switch (sffsdrnandflash) { case 0: break; case -1: luaL_error(L, "\122\145\163\160\157\156\163\145\040\143\157\155\155\151\164\164\145\144"); case -3: luaL_error(L, "\116\157\164\040\155\165\154\164\151\160\141\162\164"); case -5: luaL_error(L, "\101\154\154\157\143\141\164\151\157\156\040\145\162\162\157\162"); default: lua_pushnil(L); lua_pushstring(L, "\117\160\145\162\141\164\151\157\156\040\146\141\151\154\145\144"); lua_pushinteger(L, sffsdrnandflash); return 3; } lua_pushboolean(L,1); return 1; } #undef MPU_FORMDATA #undef MPU_FILEBEGIN #undef MPU_FILEDATA #undef MPU_END #undef MPU_ERROR #undef MPU_TOP #if 0 static int kexeccleanup(lua_State* L) { HttpRecData* rd = (HttpRecData*)lua_touserdata(L,lua_upvalueindex(2)); int localflush = (int)lua_tointeger(L, lua_upvalueindex(3)); int hwmodclocks=localflush; int red; int n = 0; char buf[LUAL_BUFFERSIZE]; lua_settop(L,0); if (!rd || localflush <= 0) { lua_pushnil(L); lua_replace(L, lua_upvalueindex(2)); lua_pushnil(L); return 1; } while (hwmodclocks > 0) { S32 len = (S32)(hwmodclocks <= LUAL_BUFFERSIZE ? hwmodclocks : LUAL_BUFFERSIZE); red = (int)HttpRecData_read(rd, buf, len); if (red > 0) { lua_pushlstring(L, buf, red); hwmodclocks -= red; n++; } else break; } if (n > 1) lua_concat(L, n); else if (n == 0) { lua_pushnil(L); lua_replace(L, lua_upvalueindex(2)); lua_pushnil(L); } return 1; } #endif static int kexeccleanup(lua_State* L) { luaL_Buffer b; HttpRecData* rd = (HttpRecData*)lua_touserdata(L,lua_upvalueindex(2)); size_t maxz = (int)lua_tointeger(L, lua_upvalueindex(3)); size_t zleft; char* buf; luaL_buffinit(L, &b); buf=luaL_prepbuffsize(&b, maxz); for(zleft = maxz ; zleft != 0 ; ) { S32 rec = HttpRecData_read(rd, buf, zleft); if(rec <= 0) break; luaL_addsize(&b, rec); buf+=rec; zleft-=rec; } if(zleft == maxz) { lua_pushnil(L); lua_replace(L, lua_upvalueindex(2)); lua_pushnil(L); } else { luaL_pushresult(&b); } return 1; } static int debugexception(lua_State* L) { HttpRecData* rd; SBaFileSize sffsdrnandflash; HttpRequest *r = LHttpCommand_toReq(L); lua_Integer icachealiases = luaL_optinteger(L, 2, LUAL_BUFFERSIZE); lua_pushlightuserdata(L, r); if ( (sffsdrnandflash = HttpRecData_valid(r)) >= 0) { rd=(HttpRecData*)lua_newuserdata(L,sizeof(HttpRecData)); HttpRecData_constructor(rd, r); } else { switch(sffsdrnandflash) { case -1: lua_pushstring(L, "\115\151\163\163\151\156\147\040\143\157\156\164\145\156\164\055\154\145\156\147\164\150\040\141\156\144\040\156\157\164\040\143\150\165\156\153\040\145\156\143\157\144\151\156\147"); break; case -2: lua_pushstring(L, "\125\122\114\040\145\156\143\157\144\145\144\040\144\141\164\141"); break; default: lua_pushstring(L, "\155\165\154\164\151\160\141\162\164\057\146\157\162\155\055\144\141\164\141"); } lua_error(L); return 1; } lua_pushinteger(L, icachealiases); lua_pushcclosure(L, kexeccleanup, 3); return 1; } static int ltm022a97amodes(lua_State* L) { const char* sanitiseinner = HttpStdHeaders_getDomain( HttpRequest_getStdHeaders(LHttpCommand_toReq(L))); if (sanitiseinner) { lua_pushstring(L, sanitiseinner); return 1; } return staticmemctlr(L); } static int genericruntime(lua_State* L) { lua_pushinteger(L, HttpResponse_byteCount(LHttpCommand_toResp(L))); return 1; } static int sa1111enable(lua_State* L) { HttpConnection_clearKeepAlive(LHttpCommand_check(L,1)->cmd->con); return 0; } static int radioconfig(lua_State* L) { lua_pushboolean(L,HttpResponse_committed(LHttpCommand_toResp(L))); return 1; } static int clone3wrapper(lua_State* L) { const char* s = HttpResponse_containsHeader( LHttpCommand_toResp(L),luaL_checkstring(L,2)); if(s) lua_pushstring(L, s); else lua_pushboolean(L,0); return 1; } static int after2probe(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); HttpCookie* helperrgmii = HttpResponse_createCookie( &deviceattribute->cmd->response,luaL_checkstring(L,2)); return otheronline(L,helperrgmii,deviceattribute,1); } static int sysconmatch(lua_State* L) { HttpResponse_downgrade(LHttpCommand_toResp(L)); return 0; } static int tablebegin(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); const char* driverstate=luaL_checkstring(L, 2); HttpResponse *r = &deviceattribute->cmd->response; if (lua_gettop(L) > 2 && lua_toboolean(L,3) ) { BaBool flashcommon=lua_gettop(L)>3 && lua_toboolean(L,4) ? TRUE : FALSE; lua_pushstring(L, HttpResponse_encodeRedirectURLWithParamOrSessionURL( r,driverstate,flashcommon)); } else lua_pushstring(L,HttpResponse_encodeRedirectURL(r, driverstate)); return 1; } static int mdmctl1names(lua_State* L) { lua_pushstring(L, HttpResponse_encodeUrl( LHttpCommand_toResp(L),luaL_checkstring(L,2))); return 1; } static int cmpxchgfixup(lua_State* L) { lua_pushboolean(L, HttpResponse_flush(LHttpCommand_toResp(L)) == 0 ? 1 : 0); return 1; } static int pcmciareadl(lua_State* L) { return setendhandler(L, 1); } static int cmpxchgacquire(lua_State* L) { int len; const char* d = HttpResponse_getRespData(LHttpCommand_toResp(L), &len); if(d) lua_pushlstring(L,d,len); else lua_pushnil(L); return 1; } static int stacktrace(lua_State* L) { lua_pushinteger(L, HttpResponse_getStatus(LHttpCommand_toResp(L))); return 1; } static int closeconsole(lua_State* L) { return setendhandler(L, 3); } static int clusterstate(lua_State* L) { lua_pushboolean(L,HttpResponse_initial(LHttpCommand_toResp(L))); return 1; } static int bootargscmdline(lua_State* L) { HttpResponse *r = LHttpCommand_toResp(L); lua_pushboolean(L,HttpResponse_isForward(r)); lua_pushinteger(L,r->forwardCounter); return 2; } static int disableunlocked(lua_State* L) { HttpResponse *r = LHttpCommand_toResp(L); lua_pushboolean(L,HttpResponse_isInclude(r)); lua_pushinteger(L,r->includeCounter); return 2; } static int kernelunmapped(lua_State* L) { return setendhandler(L, 2); } static int setupsdhci2(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); HttpResponse* r = &deviceattribute->cmd->response; int sffsdrnandflash = HttpResponse_redirect2TLS(r); if(sffsdrnandflash == 0) { lua_pushboolean(L, FALSE); } else if(sffsdrnandflash > 0) { int blake2bsetkey = balua_optboolean(L,2,FALSE); if(blake2bsetkey) { lua_pushboolean(L, TRUE); deviceattribute->cmd=0; } else LHttpCommand_stopRequest(deviceattribute,L); } else { return balua_pushstatus(L,sffsdrnandflash); } return 1; } static int offsetvalid(lua_State* L) { static const char *const localcounters[] = {"\141\154\154", "\150\145\141\144\145\162\163", "\142\165\146\146\145\162",NULL}; int ret; HttpResponse *r = LHttpCommand_toResp(L); int hdq1wreset = luaL_checkoption(L, 2, "\141\154\154", localcounters); switch (hdq1wreset) { case 1: ret = HttpResponse_resetHeaders(r); break; case 2: ret = HttpResponse_resetBuffer(r); break; case 0: default: if( ! (ret = HttpResponse_resetHeaders(r)) ) ret = HttpResponse_resetBuffer(r); break; } return eventcnten(L,ret); } static int supportsaddress(lua_State* L) { size_t l; HttpResponse* r = LHttpCommand_toResp(L); const char* s = lua_tolstring(L,2,&l); return eventcnten(L,HttpResponse_send(r,s, (int)l)); } static int removekprobe(lua_State* L) { int sffsdrnandflash; HttpResponse* r3000write=LHttpCommand_toResp(L); const char* s = luaL_optstring(L,3, NULL); int n = (int)luaL_checkinteger(L,2); if (!s || !*s) sffsdrnandflash=HttpResponse_sendError1(r3000write, n); else sffsdrnandflash=HttpResponse_sendError2(r3000write, n, s); return eventcnten(L, sffsdrnandflash); } static int setupucontext(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_check(L,1); HttpResponse* r = &deviceattribute->cmd->response; const char* url = luaL_checkstring(L,2); int eventfilter = balua_optboolean(L,3,FALSE); int blake2bsetkey = balua_optboolean(L,4,FALSE); int sffsdrnandflash=HttpResponse_sendRedirectI( r,url,eventfilter?301:302); if( ! sffsdrnandflash ) { if(blake2bsetkey) deviceattribute->cmd=0; else LHttpCommand_stopRequest(deviceattribute,L); } return restoreimage(deviceattribute,L, url, sffsdrnandflash); } static int titanannotations(lua_State* L) { return eventcnten( L,HttpResponse_setContentLength( LHttpCommand_toResp(L), (BaFileSize)luaL_checkinteger(L,2))); } static int videoremove(lua_State* L) { HttpResponse* r = &(LHttpCommand_check(L,1)->cmd->response); if( (lua_isnone(L, 3) || lua_toboolean(L, 3)) || !HttpResponse_containsHeader(r, "\103\157\156\164\145\156\164\055\124\171\160\145") ) { return eventcnten( L,HttpResponse_setContentType(r,luaL_checkstring(L,2))); } lua_pushboolean(L, FALSE); return 1; } static int memmapspace(lua_State* L) { return eventcnten(L, HttpResponse_setDateHeader( LHttpCommand_toResp(L), luaL_checkstring(L,2), (BaTime)luaL_checkinteger(L,3))); } static int eventneeds(lua_State* L) { return eventcnten(L, HttpResponse_setDefaultHeaders(LHttpCommand_toResp(L))); } static int instructionpointer(lua_State* L) { return eventcnten( L, HttpResponse_setHeader(LHttpCommand_toResp(L), luaL_checkstring(L,2), luaL_optstring(L,3, NULL), 1)); } static int kernelbreak(lua_State* L) { return eventcnten( L, HttpResponse_setMaxAge( LHttpCommand_toResp(L), (int)luaL_checkinteger(L,2))); } static int singledefault(lua_State* L) { Xrsp* x; HttpResponse* r3000write = LHttpCommand_toResp(L); int top=lua_gettop(L); if(HttpResponse_committed(r3000write)) eventcnten(L,E_IS_COMMITTED); x = (Xrsp*)lua_newuserdata(L, sizeof(Xrsp)); memset(x, 0 , sizeof(Xrsp)); x->resp=r3000write; DoubleList_constructor(&x->list); if(top > 1 && lua_type(L, 2) == LUA_TFUNCTION) { lua_State* Lt; x->type=1; Lt=lua_newthread(L); x->threadRef=luaL_ref(L, LUA_REGISTRYINDEX); lua_pushvalue(L, 2); x->funcRef=luaL_ref(L, LUA_REGISTRYINDEX); BufPrint_constructor((BufPrint*)x, (void*)Lt, inteliommu); } else { int ret; int bufferdriver = top > 1 && lua_toboolean(L, 2) == 1; if(bufferdriver) { ret=deflateInit(&x->strm,Z_DEFAULT_COMPRESSION); } else { ret=deflateInit2(&x->strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY); } if (ret != Z_OK) luaL_error(L, "\132\154\151\142\040\145\162\162\157\162\040\045\144",ret); BufPrint_constructor((BufPrint*)x, 0,mmgpioresource); x->type=2; x->nodeSize = r3000write->defaultBodyPrint.bufSize; } baluaENV_getmetatable(L, BA_TSETRESPONSE); lua_setmetatable(L, -2); if(HttpResponse_setResponseBuf(r3000write, (BufPrint*)x, TRUE)) lua_pushnil(L); else HttpResponse_resetHeaders(r3000write); return 1; } static int stage2range(lua_State* L) { int sffsdrnandflash = (int)luaL_checkinteger(L,2); return eventcnten( L,HttpResponse_setStatus(LHttpCommand_toResp(L),sffsdrnandflash)); } static int debugfault(lua_State* L) { LHttpCommand* deviceattribute = LHttpCommand_toCmd(L, 1); lua_pushboolean(L, deviceattribute->cmd ? TRUE : FALSE); return 1; } static int removeoptimized(lua_State* L) { int i,ret; const char* s; size_t tot=0; size_t l=0; HttpResponse *r = LHttpCommand_toResp(L); int n = lua_gettop(L); if (!lua_checkstack(L, 8)) luaL_error(L, "\163\164\141\143\153\040\163\151\172\145\040\145\170\143\145\145\144\145\144"); for (i=2; i<=n ; i++) { s = lua_tolstring(L, i, &l); tot+=l; if ((ret=HttpResponse_write(r, s, (int)l, TRUE))!=0) return balua_pushstatus(L, ret); } lua_pushinteger(L,tot); return 1; } static int callchaintrace(lua_State* L) { DynBuffer buf; int i; int rd12rm0noflags; int blake2bsetkey; int ret=0; int top = lua_gettop(L); LHttpCommand* deviceattribute = LHttpCommand_check(L,1); HttpResponse* r = &deviceattribute->cmd->response; luaL_checktype(L, 2, LUA_TTABLE); if(HttpResponse_committed(r)) eventcnten(L, E_IS_COMMITTED); if(lua_isboolean(L, -1)) { blake2bsetkey=lua_toboolean(L,-1); lua_settop(L,--top); } else blake2bsetkey=FALSE; rd12rm0noflags=top+1; for(i=3 ; i <= top ; i++) luaL_checktype(L, i, LUA_TTABLE); lua_newtable(L); DynBuffer_constructor(&buf, 512, 2048, AllocatorIntf_getDefault(), 0); if(top > 2) BufPrint_putc((BufPrint*)&buf, '\133'); for(i=2 ; i <= top ; i++) { if(top > 2 && i > 2) BufPrint_putc((BufPrint*)&buf, '\054'); ret = ljsonlibTabEncode(L, (BufPrint*)&buf, rd12rm0noflags, i); if(ret != 1) break; } if(ret == 1) { size_t lsdc2format; if(top > 2) BufPrint_putc((BufPrint*)&buf, '\135'); HttpResponse_resetHeaders(r); HttpResponse_resetBuffer(r); lsdc2format=DynBuffer_getBufSize(&buf); HttpResponse_setContentLength(r,lsdc2format); HttpResponse_setContentType(r, "\141\160\160\154\151\143\141\164\151\157\156\057\152\163\157\156"); HttpResponse_setHeader( r,"\103\141\143\150\145\055\103\157\156\164\162\157\154","\156\157\055\163\164\157\162\145\054\040\156\157\055\143\141\143\150\145\054\040\155\165\163\164\055\162\145\166\141\154\151\144\141\164\145\054\040\155\141\170\055\141\147\145\075\060", TRUE); HttpResponse_send(r,DynBuffer_getBuf(&buf), (int)lsdc2format); } DynBuffer_destructor(&buf); if(ret != 1) { luaL_error(L, "\112\123\117\116\040\145\156\143\157\144\151\156\147\040\146\141\151\154\145\144\072\040\045\163", lua_isstring(L,-1) ? lua_tostring(L,-1) : ""); } if(blake2bsetkey) deviceattribute->cmd=0; else LHttpCommand_stopRequest(deviceattribute,L); return 1; } static int cpufreqnotifier(lua_State* L) { lua_pushinteger(L,BufPrint_getBufSize( HttpResponse_getWriter(LHttpCommand_toResp(L)))); return 1; } static int sysconswlocked(lua_State* L) { HttpResponse* r = LHttpCommand_toResp(L); if(HttpResponse_committed(r)) eventcnten(L, E_IS_COMMITTED); BasicAuthenticator_setAutHeader(luaL_checkstring(L,2),r); return 0; } static int asyncdigest(lua_State* L) { HttpResponse* r = LHttpCommand_toResp(L); if(HttpResponse_committed(r)) eventcnten(L, E_IS_COMMITTED); DigestAuthenticator_setAutHeader(luaL_checkstring(L,2),r); return 0; } #define DEF_RESP_BUF_SIZE 2048 typedef struct { HttpAsynchResp super; char buf[DEF_RESP_BUF_SIZE]; } DeferredResp; static int disableunused(lua_State* L) { LuaAsynchRespCont* arc; DeferredResp* dr; HttpResponse* r = LHttpCommand_toResp(L); if(HttpResponse_committed(r)) luaL_error(L, "\122\145\163\160\157\156\163\145\040\143\157\155\155\151\164\164\145\144"); arc = (LuaAsynchRespCont*)lua_newuserdata( L, sizeof(LuaAsynchRespCont)+sizeof(DeferredResp)); dr = (DeferredResp*)(arc+1); arc->resp=&dr->super; arc->onClose=0; arc->onCloseData=0; HttpAsynchResp_constructor( &dr->super, dr->buf, DEF_RESP_BUF_SIZE, HttpResponse_getRequest(r)); baluaENV_getmetatable(L, BA_TASYNCRESP); lua_setmetatable(L, -2); return 1; } static const luaL_Reg baHttpCmdLib[] = { {"\141\142\157\162\164" , kprobeshandler}, {"\141\154\154\157\167" , bonitopcicfg}, #ifndef NO_SHARKSSL {"\143\145\162\164\151\146\151\143\141\164\145" , wm97xxdriver}, {"\143\151\160\150\145\162" , pcimtdetect}, {"\143\154\151\145\156\164\143\145\162\164" , switcherdisable}, #endif {"\143\150\145\143\153\164\151\155\145" , rangeallowed}, {"\143\157\157\153\151\145" , fixupvnode}, {"\144\157\155\141\151\156" , ltm022a97amodes}, {"\145\156\166" , recordindex}, {"\150\145\141\144\145\162" , ahashclear}, {"\154\157\147\151\156" , parseiosapic}, {"\154\157\147\157\165\164" , au1100intclknames}, {"\155\145\164\150\157\144" , singlefcmpz}, {"\163\145\163\163\151\157\156" , compiledbrkpt}, {"\165\162\151" , insertcolor}, {"\165\162\154" , fixupr8169}, {"\165\163\145\162" , hammeruartcfgs}, {"\166\145\162\163\151\157\156" , flashregister}, {"\151\163\163\145\143\165\162\145" , putcharar933x}, {"\160\145\145\162\156\141\155\145" , staticmemctlr}, {"\163\145\164\156\157\144\145\154\141\171" , udelayfactor}, {"\163\157\143\153\156\141\155\145" , cacheenable}, {"\144\141\164\141" , writeprobe}, {"\144\141\164\141\160\141\151\162\163" , sdio0resources}, {"\155\165\154\164\151\160\141\162\164" , buckvpdata}, {"\162\141\167\162\144\162" , debugexception}, {"\142\171\164\145\143\157\165\156\164", genericruntime}, {"\143\154\145\141\162\153\145\145\160\141\154\151\166\145", sa1111enable}, {"\143\157\155\155\151\164\164\145\144", radioconfig}, {"\143\157\156\164\141\151\156\163\150\145\141\144\145\162", clone3wrapper}, {"\143\162\145\141\164\145\143\157\157\153\151\145", after2probe}, {"\144\157\167\156\147\162\141\144\145", sysconmatch}, {"\145\156\143\157\144\145\162\145\144\151\162\145\143\164\165\162\154", tablebegin}, {"\145\156\143\157\144\145\165\162\154", mdmctl1names}, {"\146\154\165\163\150", cmpxchgfixup}, {"\146\157\162\167\141\162\144", pcmciareadl}, {"\147\145\164\144\141\164\141", cmpxchgacquire}, {"\147\145\164\163\164\141\164\165\163", stacktrace}, {"\151\156\143\154\165\144\145", closeconsole}, {"\151\156\151\164\151\141\154", clusterstate}, {"\151\163\146\157\162\167\141\162\144", bootargscmdline}, {"\151\163\151\156\143\154\165\144\145", disableunlocked}, {"\162\145\144\151\162\145\143\164", kernelunmapped}, {"\162\145\144\151\162\145\143\164\062\164\154\163", setupsdhci2}, {"\162\145\163\145\164", offsetvalid}, {"\163\145\156\144", supportsaddress}, {"\163\145\156\144\145\162\162\157\162", removekprobe}, {"\163\145\156\144\162\145\144\151\162\145\143\164", setupucontext}, {"\163\145\164\143\157\156\164\145\156\164\154\145\156\147\164\150", titanannotations}, {"\163\145\164\143\157\156\164\145\156\164\164\171\160\145", videoremove}, {"\163\145\164\144\141\164\145\150\145\141\144\145\162", memmapspace}, {"\163\145\164\144\145\146\141\165\154\164\150\145\141\144\145\162\163", eventneeds}, {"\163\145\164\150\145\141\144\145\162", instructionpointer}, {"\163\145\164\155\141\170\141\147\145", kernelbreak}, {"\163\145\164\162\145\163\160\157\156\163\145", singledefault}, {"\163\145\164\163\164\141\164\165\163", stage2range}, {"\166\141\154\151\144", debugfault}, {"\167\162\151\164\145", removeoptimized}, {"\167\162\151\164\145\163\151\172\145", cpufreqnotifier}, {"\152\163\157\156", callchaintrace}, {"\163\145\164\142\141\163\151\143", sysconswlocked}, {"\163\145\164\144\151\147\145\163\164", asyncdigest}, {"\144\145\146\145\162\162\145\144", disableunused}, {NULL, NULL} }; typedef struct { struct HttpUploadNode* node; } LUploadNode; static LUploadNode* LUploadNode_check(lua_State* L, int ix) { LUploadNode* o=(LUploadNode*)baluaENV_checkudata(L, ix, BA_TUPLOAD); if( ! o->node ) luaL_error(L,"\145\170\160\151\162\145\144"); return o; } static int shashexport(lua_State* L) { lua_pushstring(L,HttpUploadNode_getUrl(LUploadNode_check(L,1)->node)); return 1; } static int scoopconfig(lua_State* L) { lua_pushstring(L,HttpUploadNode_getName(LUploadNode_check(L,1)->node)); return 1; } static int externalhandler(lua_State* L) { lua_pushboolean( L, HttpUploadNode_isMultipartUpload(LUploadNode_check(L,1)->node)); return 1; } static int memoryproximity(lua_State* L) { return LSessionENV_push( L, HttpUploadNode_getSession(LUploadNode_check(L,1)->node)); } static void gpiocfgbanka(HttpAsynchResp* fdc37m81xconfig) { HttpUploadNode_decrRef((struct HttpUploadNode*)fdc37m81xconfig); } static int reportpci1clk(lua_State* L) { struct HttpUploadNode* un = LUploadNode_check(L,1)->node; if(HttpUploadNode_isResponseMode(un)) luaL_error(L, "\045\163", "\101\154\162\145\141\144\171\040\151\156\040\165\160\154\157\141\144\040\155\157\144\145"); HttpUploadNode_incRef(un); mousedisable(L, HttpUploadNode_getResponse(un), gpiocfgbanka, un); return 1; } static const luaL_Reg baLUploadNodeLib[] = { { "\165\162\154", shashexport}, { "\156\141\155\145", scoopconfig}, { "\155\165\154\164\151\160\141\162\164", externalhandler}, { "\163\145\163\163\151\157\156", memoryproximity}, { "\162\145\163\160\157\156\163\145", reportpci1clk}, {NULL, NULL} }; typedef struct { HttpUploadCbIntf super; HttpUpload upload; lua_State* LM; } LUpload; static lua_State* LUpload_tothread(LUpload* o, struct HttpUploadNode* smartreflexhwmod) { lua_State* L; lua_rawgeti(o->LM, LUA_REGISTRYINDEX, (lua_Integer)((ptrdiff_t)HttpUploadNode_getdata(smartreflexhwmod))); L=lua_tothread(o->LM, -1); lua_pop(o->LM,1); return L; } static void registeralways(LUpload* o, struct HttpUploadNode* smartreflexhwmod, const char* ethernatenable) { lua_State* L = LUpload_tothread(o, smartreflexhwmod); LUploadNode* lup=lua_touserdata(L, 5); lup->node=0; if( ! HttpUploadNode_isResponseMode(smartreflexhwmod) ) { int setpropinplace; HttpAsynchResp* r3000write = HttpUploadNode_getResponse(smartreflexhwmod); if(!ethernatenable) ethernatenable = "\116\157\040\162\145\163\160\157\156\163\145\040\151\156\040\114\165\141\040\143\141\154\154\142\141\143\153\163"; HttpAsynchResp_setStatus(r3000write,500,0); setpropinplace = iStrlen(ethernatenable); HttpAsynchResp_sendData(r3000write,ethernatenable,setpropinplace,setpropinplace); HttpAsynchResp_close(r3000write); } if(ethernatenable) TRPR(("\105\162\162\040\114\165\141\040\165\160\154\157\141\144\072\040\045\163\012", ethernatenable)); luaL_unref(o->LM, LUA_REGISTRYINDEX, (int)((size_t)HttpUploadNode_getdata(smartreflexhwmod))); } static const char* LUpload_pcall(lua_State* L, int switcherthread) { if(lua_pcall(L,switcherthread,1,-(switcherthread+2))) { const char* ethernatenable; ethernatenable = lua_isstring(L,-1) ? lua_tostring(L,-1) : "\114\165\141\040\143\141\154\154\142\141\143\153\040\146\141\151\154\145\144"; return ethernatenable; } return 0; } static void kernelsegment( HttpUploadCbIntf* fdc37m81xconfig, struct HttpUploadNode* smartreflexhwmod, BaBool requestvector) { const char* ethernatenable; LUpload* o=(LUpload*)fdc37m81xconfig; lua_State* L = LUpload_tothread(o, smartreflexhwmod); LUploadNode* lup=lua_touserdata(L, 5); lup->node=smartreflexhwmod; lua_pushcclosure(L,balua_errorhandler,0); lua_pushvalue(L, requestvector ? 2 : 1); lua_pushvalue(L, 4); lua_pushvalue(L, 5); ethernatenable = LUpload_pcall(L,2); if(ethernatenable || requestvector || HttpUploadNode_isResponseMode(smartreflexhwmod)) registeralways(o, smartreflexhwmod, ethernatenable); else lua_pop(L,1); } static void switcherunregister( HttpUploadCbIntf* fdc37m81xconfig,struct HttpUploadNode* smartreflexhwmod, int flushoffset,const char* heartcounter) { const char* ethernatenable; const char* initrdstart; LUpload* o=(LUpload*)fdc37m81xconfig; lua_State* L = LUpload_tothread(o, smartreflexhwmod); LUploadNode* lup=lua_touserdata(L, 5); lup->node=smartreflexhwmod; lua_pushcclosure(L,balua_errorhandler,0); lua_pushvalue(L, 3); lua_pushvalue(L, 4); lua_pushvalue(L, 5); ethernatenable=baErr2Str(flushoffset); lua_pushstring(L,ethernatenable); if(heartcounter) lua_pushstring(L,heartcounter); initrdstart = LUpload_pcall(L, heartcounter ? 4 : 3); if(initrdstart) { lua_pushfstring(L,"\045\163\072\040\045\163",ethernatenable,initrdstart); ethernatenable = lua_tostring(L,-1); } else ethernatenable=0; registeralways(o, smartreflexhwmod, ethernatenable); } static int platformpopulate(lua_State* L) { int cminstclkdm; lua_State* LT; LUpload* o = (LUpload*)lua_touserdata(L,lua_upvalueindex(3)); LHttpCommand* deviceattribute=LHttpCommand_check(L,1); const char* writeconfig=luaL_checkstring(L, 2); int blake2bsetkey = FALSE; luaL_checktype(L,3,LUA_TFUNCTION); luaL_checktype(L,4,LUA_TFUNCTION); luaL_checktype(L,5,LUA_TFUNCTION); if(lua_gettop(L) > 5) { luaL_checktype(L,6, LUA_TTABLE); blake2bsetkey = balua_optboolean(L,7,FALSE); lua_settop(L,6); } else lua_newtable(L); lua_createtable(L,0,1); lua_pushglobaltable(L); lua_setfield(L,-2, "\137\137\151\156\144\145\170"); lua_setmetatable(L, -2); if(HttpResponse_isInclude(&deviceattribute->cmd->response)) luaL_error(L, "\125\160\154\157\141\144\040\167\151\164\150\151\156\040\151\156\143\154\165\144\145"); LT=lua_newthread(L); cminstclkdm=luaL_ref(L,LUA_REGISTRYINDEX); lua_xmove(L, LT, 4); lua_newuserdata(LT, sizeof(LUploadNode)); baluaENV_getmetatable(L, BA_TUPLOAD); lua_xmove(L, LT, 1); lua_setmetatable(LT, -2); if(HttpUpload_service(&o->upload,writeconfig,deviceattribute->cmd,(void*)((size_t)cminstclkdm))) { luaL_unref(L, LUA_REGISTRYINDEX, cminstclkdm); luaL_error(L, "\111\156\166\141\154\151\144\040\120\125\124\040\157\162\040\155\165\154\164\151\160\141\162\164\040\120\117\123\124"); } if(blake2bsetkey) deviceattribute->cmd=0; else LHttpCommand_stopRequest(deviceattribute,L); return 0; } static int hotplugdisable(lua_State* L) { LUpload* o; IoIntf* io = baluaENV_checkIoIntf(L, 1); int isideindependent = (int)luaL_optinteger(L,2,0xFFFF); lua_settop(L, 1); lua_pushvalue(L,1); balua_pushbatab(L); lua_replace(L,1); o = (LUpload*)lua_newuserdata(L,sizeof(LUpload)); o->LM = balua_getmainthread(L); HttpUploadCbIntf_constructor((HttpUploadCbIntf*)o, kernelsegment, switcherunregister); HttpUpload_constructor(&o->upload, io, AllocatorIntf_getDefault(), (HttpUploadCbIntf*)o, isideindependent); lua_pushcclosure(L, platformpopulate, 3); return 1; } static int singlefcmpez(lua_State* L) { AuthenticatedUser* buttonsbelkin=0; AuthorizerIntf* o = LAuthorizerIntf_check(L, 1); if(baluaENV_isudtype(L, 2, BA_THTTPCMD)) { buttonsbelkin = HttpRequest_getAuthenticatedUser( &LHttpCommand_check(L,2)->cmd->request); } else { HttpSession* s=HttpUploadNode_getSession(LUploadNode_check(L,2)->node); if(s) buttonsbelkin=AuthenticatedUser_get2(s); } lua_pushboolean( L, buttonsbelkin && o->authorizeFP( o,buttonsbelkin,HttpMethod_a2m(luaL_checkstring(L,3)),luaL_checkstring(L,4))); return 1; } static const luaL_Reg baAuthorizerIntfLib[] = { {"\141\165\164\150\157\162\151\172\145", singlefcmpez}, {NULL, NULL} }; typedef struct { AuthorizerIntf super; lua_State* LM; int funcRef; } LuaAuthorizer; static BaBool boardsetup(AuthorizerIntf* fdc37m81xconfig, AuthenticatedUser* buttonsbelkin, HttpMethod averagevalue, const char* driverstate) { BaBool cachelsize=FALSE; const char* gpio1config = AuthenticatedUser_getName(buttonsbelkin); if(gpio1config) { HttpSession* s; LSession* ls; LuaAuthorizer* o = (LuaAuthorizer*)fdc37m81xconfig; lua_State* L = lua_newthread(o->LM); int spiflashparts=luaL_ref(o->LM, LUA_REGISTRYINDEX); lua_pushcclosure(L,balua_errorhandler,0); lua_rawgeti(L, LUA_REGISTRYINDEX, o->funcRef); lua_pushstring(L,gpio1config); lua_pushstring(L,HttpRequest_getMethod2(averagevalue)); lua_pushstring(L,driverstate); s = AuthenticatedUser_getSession(buttonsbelkin); ls = (LSession*)lua_newuserdata(L, sizeof(LSession)); ls->id = HttpSession_getId(s); ls->locked=FALSE; balua_pushbatab(L); lua_rawgeti(L, -1, BA_TSESSION); lua_setmetatable(L, -3); lua_pop(L,1); if( ! lua_pcall(L,4,1,-6) ) { cachelsize = (lua_isboolean(L, -1) && lua_toboolean(L, -1)) ? TRUE : FALSE; } luaL_unref(o->LM, LUA_REGISTRYINDEX, spiflashparts); } return cachelsize; } static int platformoemdata(lua_State* L) { LuaAuthorizer* o; lua_settop(L, 1); luaL_checktype(L,1,LUA_TFUNCTION); o = (LuaAuthorizer*)lua_newuserdata(L, sizeof(LuaAuthorizer)); AuthorizerIntf_constructor((AuthorizerIntf*)o, boardsetup); baluaENV_getmetatable(L, BA_TLUA_AUTHORIZER); lua_setmetatable(L, -2); lua_pushvalue(L,1); o->funcRef=luaL_ref(L, LUA_REGISTRYINDEX); o->LM=balua_getmainthread(L); return 1; } static int buildlabel(lua_State* L) { LuaAuthorizer* o = (LuaAuthorizer*)baluaENV_checkudata(L,1,BA_TLUA_AUTHORIZER); luaL_unref(L, LUA_REGISTRYINDEX, o->funcRef); return 0; } static const luaL_Reg baLAuthorizerLib[] = { {"\137\137\147\143", buildlabel}, {NULL, NULL} }; typedef struct { JConstrCont super; int ljuserRef; /* reference to LJUser */ } LJAuthorizer; #define LJAuthorizer_check(L) \ (LJAuthorizer*)baluaENV_checkudata(L,1,BA_TJAUTHORIZER) static int sead3begin(lua_State* L, JUserCont* uc, int cpucfgemulation) { LJAuthorizer* o; o = (LJAuthorizer*)lua_newuserdata(L, sizeof(LJAuthorizer)); JConstrCont_constructor((JConstrCont*)o, uc, 0); baluaENV_getmetatable(L, BA_TJAUTHORIZER); lua_setmetatable(L, -2); lua_pushvalue(L,cpucfgemulation); o->ljuserRef=luaL_ref(L, LUA_REGISTRYINDEX); return 1; } static int forbiddenoffset(lua_State* L) { JParserValFact vf; int ret=2; LJAuthorizer* o = LJAuthorizer_check(L); JVal* val = lParseJsonDataString(L, 2, &vf); if(val) { JErr err; JErr_constructor(&err); JConstrCont_setConstraints((JConstrCont*)o, val, &err); ret=setupdevinit(L,&err); JParserValFact_destructor(&vf); } return ret; } static int blasticache32(lua_State* L) { LJAuthorizer* o = LJAuthorizer_check(L); lua_pushboolean(L, ((JConstrCont*)o)->caseSensensitive); ((JConstrCont*)o)->caseSensensitive=(BaBool)balua_optboolean(L,2,FALSE); return 1; } static int spillsprel(lua_State* L) { LJAuthorizer* o = LJAuthorizer_check(L); luaL_unref(L, LUA_REGISTRYINDEX, o->ljuserRef); JConstrCont_destructor((JConstrCont*)o); return 0; } static const luaL_Reg baLJAuthorizerLib[] = { {"\137\137\147\143", spillsprel}, {"\143\141\163\145\163\145\156\163\151\164\151\166\145", blasticache32}, {"\163\145\164", forbiddenoffset}, {NULL, NULL} }; static int uart1hwmod(lua_State* L) { AuthInfo memblocksteal; UserIntf* o = (UserIntf*)baluaENV_checkudata(L, 1, BA_TUSERINTF); AuthInfo_constructor(&memblocksteal, 0, 0, AuthenticatedUserType_Unknown); memblocksteal.username=luaL_checkstring(L, 2); o->getPwdFp(o,&memblocksteal); if((memblocksteal.ct == AuthInfoCT_Password || memblocksteal.ct == AuthInfoCT_HA1) && *memblocksteal.password) { if(memblocksteal.ct == AuthInfoCT_HA1) lua_pushlstring(L,(char*)memblocksteal.password,32); else lua_pushstring(L,(char*)memblocksteal.password); lua_pushinteger(L,memblocksteal.maxUsers); lua_pushboolean(L,memblocksteal.recycle); lua_pushinteger(L,memblocksteal.maxInactiveInterval); return 4; } lua_pushnil(L); return 1; } static const luaL_Reg baUserIntfLib[] = { {"\147\145\164\160\167\144", uart1hwmod}, {NULL, NULL} }; typedef JUserCont LJUser; #define LJUser_check(L,ix) ((LJUser*)baluaENV_checkudata(L,ix,BA_TJUSER)) static int cpumaskcluster(lua_State* L) { LJUser* o; o = (LJUser*)lua_newuserdata(L, sizeof(LJUser)); JUserCont_constructor((JUserCont*)o,0); baluaENV_getmetatable(L, BA_TJUSER); lua_setmetatable(L, -2); return 1; } static int handlerbhhook(lua_State* L) { return sead3begin(L,LJUser_check(L,1),1); } static int masterstandbymode(lua_State* L) { JParserValFact vf; int ret=2; LJUser* o = LJUser_check(L,1); JVal* val = lParseJsonDataString(L, 2, &vf); if(val) { JErr err; JErr_constructor(&err); JUserCont_setUserDb(o, val, &err); ret=setupdevinit(L,&err); JParserValFact_destructor(&vf); } return ret; } static int iommudetach(lua_State* L) { JUserCont_destructor(LJUser_check(L,1)); return 0; } static const luaL_Reg baLJUserLib[] = { {"\137\137\147\143", iommudetach}, {"\141\165\164\150\157\162\151\172\145\162", handlerbhhook}, {"\163\145\164", masterstandbymode}, {NULL, NULL} }; typedef struct { UserIntf super; lua_State* LM; int funcRef; } LuaUser; static void graphtracing(UserIntf* fdc37m81xconfig, AuthInfo* ai) { lua_State* L; LuaUser* o = (LuaUser*)fdc37m81xconfig; LHttpCommand* deviceattribute = LHttpCommand_create(o->LM, ai->cmd); const char* lowmemredirect=deviceattribute->curLspPathname; deviceattribute->curLspPathname=0; L=deviceattribute->L; ai->ct = AuthInfoCT_Invalid; lua_pushlightuserdata(L,deviceattribute); lua_pushcclosure(L,LHttpCommand_error,1); baAssert(o->funcRef); lua_rawgeti(L, LUA_REGISTRYINDEX, o->funcRef); lua_pushstring(L,ai->username); lua_pushstring(L,ai->upwd); lua_rawgeti(L, LUA_REGISTRYINDEX, deviceattribute->envRef); if( ! lua_pcall(L,3,4,-5) ) { size_t s; const char* p; int rightsvalid=lua_type(L, -4); switch(rightsvalid) { case LUA_TSTRING: p=lua_tolstring(L, -4, &s); if(s+1 < sizeof(ai->password)) { memcpy(ai->password,p,s+1); ai->ct = AuthInfoCT_Password; } break; case LUA_TTABLE: lua_rawgeti(L, -4, 1); if(lua_isstring(L, -1)) { p=lua_tolstring(L, -1, &s); if(s==32) { memcpy(ai->password,p,32); ai->ct = AuthInfoCT_HA1; } } lua_pop(L, 1); break; case LUA_TBOOLEAN: if(lua_toboolean(L, -4)) ai->ct = AuthInfoCT_Valid; } if(ai->ct != AuthInfoCT_Invalid) { if(lua_isnumber(L, -3)) { ai->maxUsers=(int)lua_tointeger(L,-3); if(lua_isboolean(L, -2)) { ai->recycle=(BaBool)lua_toboolean(L,-2); if(lua_isnumber(L, -1)) ai->maxInactiveInterval=(int)lua_tointeger(L,-1); } } } } deviceattribute->curLspPathname=lowmemredirect; LHttpCommand_release(deviceattribute); } static int timer0shutdown(lua_State* L) { LuaUser* o; lua_settop(L, 1); luaL_checktype(L,1,LUA_TFUNCTION); o = (LuaUser*)lua_newuserdata(L, sizeof(LuaUser)); UserIntf_constructor((UserIntf*)o, graphtracing); baluaENV_getmetatable(L, BA_TLUA_USER); lua_setmetatable(L, -2); lua_pushvalue(L,1); o->funcRef=luaL_ref(L, LUA_REGISTRYINDEX); o->LM=balua_getmainthread(L); return 1; } static int transparenthugepage(lua_State* L) { LuaUser* o = (LuaUser*)baluaENV_checkudata(L,1,BA_TLUA_USER); luaL_unref(L, LUA_REGISTRYINDEX, o->funcRef); return 0; } static const luaL_Reg baLuaUserLib[] = { {"\137\137\147\143", transparenthugepage}, {NULL, NULL} }; typedef AuthenticatorIntf LAuthenticatorIntf; #define LAuthenticatorIntf_check(L,ix) \ (LAuthenticatorIntf*)baluaENV_checkudata(L,ix,BA_TAUTHENTICATORINTF) static int pgtablechange(lua_State* L) { AuthenticatedUser* buttonsbelkin= AuthenticatorIntf_authenticate(LAuthenticatorIntf_check(L, 1), luaL_checkstring(L, 3), LHttpCommand_check(L,2)->cmd); if(buttonsbelkin) return registerclkdev(L,buttonsbelkin); lua_pushnil(L); return 1; } static const luaL_Reg baLAuthenticatorIntfLib[] = { {"\141\165\164\150\145\156\164\151\143\141\164\145", pgtablechange}, {NULL, NULL} }; typedef struct { AuthenticatorIntf super; LoginRespIntf loginResp; lua_State *LM; int authType; int userRef; /* Reference to a BA_TUSERINTF instance, if any */ int respFuncRef; /* Optional ref to Lua response callback */ } LAuthenticator; static AuthenticatedUser* LAuthenticator_wrapper( AuthenticatorIntf* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { AuthenticatorIntf* ai = (AuthenticatorIntf*)(((LAuthenticator*)fdc37m81xconfig) + 1); return AuthenticatorIntf_authenticate(ai,driverregister,cmd); } static void thumb32compose(LoginRespIntf* apecsmachine, AuthInfo* memblocksteal) { HttpResponse* r=&memblocksteal->cmd->response; (void)apecsmachine; HttpResponse_setDefaultHeaders(r); HttpResponse_write(r, "\074\150\164\155\154\076\074\142\157\144\171\040\163\164\171\154\145\075\047\142\141\143\153\147\162\157\165\156\144\072\162\145\144\047\076" "\074\150\061\076\111\156\143\157\162\162\145\143\164\040\143\162\145\144\145\156\164\151\141\154\163\074\057\150\061\076\074\057\142\157\144\171\076\074\057\150\164\155\154\076", -1,TRUE); } static void decodegroup(LoginRespIntf* apecsmachine, AuthInfo* ai) { static const char *inframatch[] = {"\144\151\147\145\163\164","\142\141\163\151\143","\146\157\162\155"}; const char* rightsvalid; lua_State* L; LAuthenticator* o=(LAuthenticator*) ((U8*)apecsmachine-offsetof(LAuthenticator,loginResp)); LHttpCommand* deviceattribute = LHttpCommand_create(o->LM, ai->cmd); const char* lowmemredirect=deviceattribute->curLspPathname; deviceattribute->curLspPathname=0; L=deviceattribute->L; lua_pushlightuserdata(L,deviceattribute); lua_pushcclosure(L,LHttpCommand_error,1); baAssert(o->respFuncRef); lua_rawgeti(L, LUA_REGISTRYINDEX, o->respFuncRef); lua_rawgeti(L, LUA_REGISTRYINDEX, deviceattribute->envRef); if(ai->username) { lua_createtable(L,0,11); lua_pushstring(L, ai->username); lua_setfield(L, -2, "\165\163\145\162\156\141\155\145"); lua_pushstring(L, (char*)ai->password); lua_setfield(L, -2, "\160\141\163\163\167\157\162\144"); lua_pushstring(L, ai->upwd); lua_setfield(L, -2, "\165\160\167\144"); lua_pushboolean(L, ai->recycle); lua_setfield(L, -2, "\162\145\143\171\143\154\145"); lua_pushinteger(L, ai->maxUsers); lua_setfield(L, -2, "\155\141\170\165\163\145\162\163"); lua_pushinteger(L, ai->maxInactiveInterval); lua_setfield(L, -2, "\151\156\141\143\164\151\166\145"); } else lua_createtable(L,0,5); if(ai->seed) { lua_pushfstring(L, "\045\144",ai->seed); lua_setfield(L, -2, "\163\145\145\144"); lua_pushfstring(L, "\045\144",ai->seedKey); lua_setfield(L, -2, "\163\145\145\144\153\145\171"); } lua_pushinteger(L, ai->loginAttempts); lua_setfield(L, -2, "\154\157\147\151\156\141\164\164\145\155\160\164\163"); lua_pushboolean(L, ai->denied); lua_setfield(L, -2, "\144\145\156\151\145\144"); switch(ai->type) { case AuthenticatedUserType_Digest: rightsvalid = inframatch[0]; break; case AuthenticatedUserType_Basic: rightsvalid = inframatch[1]; break; case AuthenticatedUserType_Form: rightsvalid = inframatch[2]; break; default: baAssert(0); rightsvalid=0; } lua_pushstring(L, rightsvalid); lua_setfield(L, -2, "\164\171\160\145"); lua_pcall(L,2,1,-4); deviceattribute->curLspPathname=lowmemredirect; LHttpCommand_release(deviceattribute); } static int siblingsmasks(lua_State* L) { static const int processlogout[]={ sizeof(Authenticator), sizeof(DigestAuthenticator), sizeof(BasicAuthenticator), sizeof(FormAuthenticator), sizeof(FormAuthenticator), sizeof(DavAuth) }; LAuthenticator* o; void* deviceinterrupt; int helpersgmii=FALSE; int assignunassigned=1; int switcherrestore=0; const char* mappingprotection="\102\141\162\162\141\143\165\144\141\040\123\145\162\166\145\162"; UserIntf* ui=LUserIntf_check(L, 1); BaLua_param* p=baluaENV_getparam(L); if(LUA_TTABLE == lua_type(L,2)) { static const char *const lboardclass[] = { "\141\165\164\150", "\144\151\147\145\163\164", "\142\141\163\151\143", "\146\157\162\155", "\163\146\157\162\155", "\144\141\166", NULL }; if(restorelocal(L, 2, "\164\171\160\145")) assignunassigned=luaL_checkoption(L, -1, 0, lboardclass); if(restorelocal(L, 2, "\162\145\141\154\155")) mappingprotection=luaL_checkstring(L,-1); if(restorelocal(L, 2, "\162\145\163\160\157\156\163\145")) { switcherrestore = lua_gettop(L); luaL_checktype(L,switcherrestore,LUA_TFUNCTION); } else if(assignunassigned == 3 || assignunassigned == 4) luaL_error(L, "\117\160\164\151\157\156\040\047\162\145\163\160\157\156\163\145\047\040\162\145\161\165\151\162\145\144\040\167\151\164\150\040\146\157\162\155\040\141\165\164\150"); if(restorelocal(L, 2, "\164\162\141\143\153\145\162")) { helpersgmii=lua_toboolean(L,-1); if(helpersgmii && !p->tracker) luaL_error(L, "\124\162\141\143\153\145\162\040\156\157\164\040\151\156\163\164\141\154\154\145\144"); } } o=(LAuthenticator*)lua_newuserdata( L,sizeof(LAuthenticator)+processlogout[assignunassigned]); memset(o,0,sizeof(LAuthenticator)); AuthenticatorIntf_constructor((AuthenticatorIntf*)o,LAuthenticator_wrapper); LoginRespIntf_constructor( &o->loginResp, switcherrestore ? decodegroup : thumb32compose); o->LM=balua_getmainthread(L); baluaENV_getmetatable(L, BA_TAUTHENTICATOR); lua_setmetatable(L, -2); lua_pushvalue(L,1); o->userRef=luaL_ref(L,LUA_REGISTRYINDEX); if(switcherrestore) { lua_pushvalue(L,switcherrestore); o->respFuncRef=luaL_ref(L,LUA_REGISTRYINDEX); } o->authType=assignunassigned; deviceinterrupt=o+1; switch(assignunassigned) { case 0: Authenticator_constructor( (Authenticator*)deviceinterrupt,ui,mappingprotection,&o->loginResp); if(helpersgmii) Authenticator_setLoginTracker((Authenticator*)deviceinterrupt,p->tracker); break; case 1: DigestAuthenticator_constructor( (DigestAuthenticator*)deviceinterrupt,ui,mappingprotection,&o->loginResp); if(helpersgmii) DigestAuthenticator_setLoginTracker( (DigestAuthenticator*)deviceinterrupt,p->tracker); break; case 2: BasicAuthenticator_constructor( (BasicAuthenticator*)deviceinterrupt,ui,mappingprotection,&o->loginResp); if(helpersgmii) BasicAuthenticator_setLoginTracker( (BasicAuthenticator*)deviceinterrupt,p->tracker); break; case 3: case 4: FormAuthenticator_constructor( (FormAuthenticator*)deviceinterrupt,ui,mappingprotection,&o->loginResp); if(assignunassigned == 4) FormAuthenticator_setSecure((FormAuthenticator*)deviceinterrupt); if(helpersgmii) FormAuthenticator_setLoginTracker( (FormAuthenticator*)deviceinterrupt,p->tracker); break; case 5: DavAuth_constructor((DavAuth*)deviceinterrupt, ui, mappingprotection); if(helpersgmii) DavAuth_setLoginTracker((DavAuth*)deviceinterrupt,p->tracker); } return 1; } static int printprefix(lua_State* L) { LAuthenticator* o = (LAuthenticator*)baluaENV_checkudata(L,1,BA_TAUTHENTICATOR); void* deviceinterrupt=o+1; luaL_unref(L, LUA_REGISTRYINDEX, o->userRef); if(o->respFuncRef) luaL_unref(L, LUA_REGISTRYINDEX, o->respFuncRef); switch(o->authType) { case 0: Authenticator_destructor((Authenticator*)deviceinterrupt); break; #ifndef NO_SHARKSSL case 1: DigestAuthenticator_destructor((DigestAuthenticator*)deviceinterrupt); break; #endif case 2: BasicAuthenticator_destructor((BasicAuthenticator*)deviceinterrupt); break; case 3: case 4: FormAuthenticator_destructor((FormAuthenticator*)deviceinterrupt); break; #ifndef NO_SHARKSSL case 5: DavAuth_destructor((DavAuth*)deviceinterrupt); break; #endif default: baAssert(0); } return 0; } static const luaL_Reg baLAuthenticatorLib[] = { {"\137\137\147\143", printprefix}, {NULL, NULL} }; static LHttpDir* LHttpDir_checkLDir(lua_State* L,int ix) { if(LUA_TTABLE == lua_type(L, ix)) { lua_getfield(L, ix, "\144\151\162"); if(lua_isuserdata(L, -1)) lua_replace(L, ix); else lua_pop(L, -1); } return (LHttpDir*)baluaENV_checkudata(L,ix,BA_TDIR); } #define LHttpDir_toDirM(L,ix) (HttpDir*)(LHttpDir_checkLDir(L,ix) + 1) #define LHttpDir_toBase(httpdir) (((LHttpDir*)httpdir)-1) BA_API HttpDir* baluaENV_toDir(lua_State* L, int ix) { return LHttpDir_toDirM(L,ix); } BA_API HttpDir* baluaENV_createDir(lua_State* L,int cpuidtcmstatus,size_t poly1305blocks) { LHttpDir* debughandler=(LHttpDir*)lua_newuserdata(L, sizeof(LHttpDir)+poly1305blocks); memset(debughandler,0,sizeof(LHttpDir)); baluaENV_getmetatable(L, cpuidtcmstatus); lua_setmetatable(L, -2); lua_newtable(L); lua_pushvalue(L, -1); lua_setuservalue(L,-3); debughandler->utabRef = balua_wkRef(L); debughandler->LM=balua_getmainthread(L); return (HttpDir*)(debughandler+1); } static void doublepacked(LHttpDir* o, lua_State* L, int ref) { balua_wkPush(L, o->utabRef); lua_rawgeti(L, -1, ref); lua_replace(L, -2); } static int eventmutex(LHttpDir* o, lua_State* L) { int ref; balua_wkPush(L, o->utabRef); lua_pushvalue(L, -2); ref=luaL_ref(L, -2); lua_pop(L,2); return ref; } static void handleexception(LHttpDir* o, lua_State* L, int ref) { balua_wkPush(L, o->utabRef); #ifndef NDEBUG lua_rawgeti(L, -1, ref); baAssert( ! lua_isnil(L, -1) ); lua_pop(L,1); #endif luaL_unref(L, -1, ref); lua_pop(L,1); } static void pcibioswrite(LHttpDir* debughandler) { HttpDir* dir = (HttpDir*)(debughandler+1); if(debughandler->orgServiceFunc) { HttpDir_setService(dir, debughandler->orgServiceFunc); debughandler->orgServiceFunc=0; } } static int pmuv1event(HttpDir* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { int sffsdrnandflash; lua_State* L; LHttpCommand* deviceattribute; LHttpDir* debughandler = ((LHttpDir*)fdc37m81xconfig) - 1; if(cmd) { const char* lowmemredirect; HttpDir* savedDir; baAssert(debughandler->funcRef); deviceattribute = LHttpCommand_create(debughandler->LM, cmd); L=deviceattribute->L; lua_pushlightuserdata(L,deviceattribute); lua_pushcclosure(L,LHttpCommand_error,1); doublepacked(debughandler, L, debughandler->funcRef); lua_rawgeti(L, LUA_REGISTRYINDEX, deviceattribute->envRef); lua_pushstring(L, driverregister); lowmemredirect=deviceattribute->curLspPathname; deviceattribute->curLspPathname=0; savedDir=deviceattribute->curDir; deviceattribute->curDir=fdc37m81xconfig; if(lua_pcall(L,2,1,-4) == LUA_OK && lua_type(L, -1) == LUA_TBOOLEAN && lua_toboolean(L, -1) == FALSE && deviceattribute->stopRequest == FALSE) { sffsdrnandflash = debughandler->orgServiceFunc ? (*debughandler->orgServiceFunc)(fdc37m81xconfig, driverregister, cmd) : 0; } else sffsdrnandflash=0; deviceattribute->curLspPathname=lowmemredirect; deviceattribute->curDir=savedDir; LHttpCommand_release(deviceattribute); return sffsdrnandflash; } pcibioswrite(debughandler); return (*fdc37m81xconfig->service)(fdc37m81xconfig, 0, 0); } static void clearfixmap(lua_State* L) { LHttpDir* o=LHttpDir_checkLDir(L,1); pcibioswrite(o); balua_wkUnref(L,o->utabRef); o->utabRef=0; } static int dummyiospace(lua_State* L) { if(LUA_TTABLE == lua_type(L, 1)) { return 0; } clearfixmap(L); HttpDir_destructor(LHttpDir_toDirM(L,1)); return 0; } static int breakpointexceptions(lua_State* L) { size_t l; HttpDir* dir=LHttpDir_toDirM(L,1); char* edma1resources=HttpDir_makeAbsPath(dir,NULL,0); if (!edma1resources) return 0; lua_pushstring(L, edma1resources); l = (size_t)lua_rawlen(L,-1); if(l == 0 || (edma1resources[l-1] != '\057')) { lua_pushliteral(L, "\057"); lua_concat(L,2); } baFree(edma1resources); return 1; } static void hwmodenable(lua_State* L) { luaL_error(L,"\104\151\162\145\143\164\157\162\171\040\141\154\162\145\141\144\171\040\151\156\163\145\162\164\145\144"); } static int singleftosiz(lua_State* L) { HttpDir* dir=LHttpDir_toDirM(L,1); if( ! lua_isnoneornil(L,2) ) { int sffsdrnandflash; HttpDir* writeretired=LHttpDir_toDirM(L,2); if(HttpDir_isLinked(writeretired) || dir == writeretired) hwmodenable(L); sffsdrnandflash=HttpDir_insertDir(dir, writeretired); if( ! sffsdrnandflash ) { LHttpDir* lparent=LHttpDir_toBase(dir); LHttpDir* lchild=LHttpDir_toBase(writeretired); if(balua_optboolean(L, 3, FALSE)) { lua_pushvalue(L,2); lchild->parentRef=eventmutex(lparent,L); } lchild->parent=lparent; } return balua_pushstatus(L,sffsdrnandflash); } if(HttpDir_isLinked(dir)) hwmodenable(L); return balua_pushstatus( L, HttpServer_insertDir(baluaENV_getparam(L)->server, luaL_optstring(L,2,0), dir)); } static int removemapping(lua_State* L) { LHttpDir* o=LHttpDir_checkLDir(L,1); HttpDir* dir = (HttpDir*)(o+1); LHttpCommand* deviceattribute = LHttpCommand_check(L,2); const char* driverregister=luaL_checkstring(L, 3); int reporthardware = balua_optboolean(L,4,FALSE); HttpDir_Service serviceFunc; if(deviceattribute->curDir == dir) { baAssert(o->funcRef && o->orgServiceFunc); serviceFunc=o->orgServiceFunc; } else serviceFunc=dir->service; if(reporthardware) { deviceattribute->cmd->response.forwardCounter++; lua_pushboolean(L,(*serviceFunc)(dir,driverregister,deviceattribute->cmd) ? FALSE : TRUE); deviceattribute->cmd->response.forwardCounter--; } else lua_pushboolean(L,(*serviceFunc)(dir,driverregister,deviceattribute->cmd) ? FALSE : TRUE); return 1; } static int enableunlocked(lua_State* L) { HttpDir* dir=LHttpDir_toDirM(L,1); lua_pushstring(L,dir->name); return 1; } static int selectaffinity(lua_State* L) { HttpDir_p403(LHttpDir_toDirM(L,1), luaL_checkstring(L,2)); return 0; } static int matchtable(lua_State* L) { AuthenticatorIntf* authenticator=0; AuthorizerIntf* authorizer=0; LHttpDir* o = LHttpDir_checkLDir(L,1); HttpDir* dir = (HttpDir*)(o+1); if( ! lua_isnone(L, 2) ) { if( ! lua_isnil(L, 2) ) authenticator = LAuthenticatorIntf_check(L, 2); if( ! lua_isnoneornil(L, 3) ) authorizer = LAuthorizerIntf_check(L, 3); } if(o->authenticatorRef) handleexception(o,L,o->authenticatorRef); if(o->authorizerRef) handleexception(o,L,o->authorizerRef); o->authenticatorRef=0; o->authorizerRef=0; if(authenticator) { lua_pushvalue(L,2); o->authenticatorRef=eventmutex(o,L); } if(authorizer) { lua_pushvalue(L,3); o->authorizerRef=eventmutex(o,L); } HttpDir_setAuthenticator(dir,authenticator,authorizer); return 0; } static int setupfirst(lua_State* L) { LHttpDir* o=LHttpDir_checkLDir(L,1); HttpDir* dir = (HttpDir*)(o+1); if( ! lua_isnoneornil(L, 2) ) luaL_checktype(L, 2, LUA_TFUNCTION); if(o->orgServiceFunc) { HttpDir_setService(dir, o->orgServiceFunc); o->orgServiceFunc=0; } if(o->funcRef) { handleexception(o, L, o->funcRef); o->funcRef=0; } if( ! lua_isnoneornil(L, 2) ) { lua_settop(L, 2); o->funcRef=eventmutex(o, L); o->orgServiceFunc = HttpDir_setService(dir, pmuv1event); } lua_pushboolean(L,TRUE); return 1; } static int matrixkeymap(HttpDir* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { LHttpDir* debughandler = ((LHttpDir*)fdc37m81xconfig) - 1; int sffsdrnandflash = HttpResponse_redirect2TLS(&cmd->response); return sffsdrnandflash ? 0 : (*debughandler->orgServiceFunc)(fdc37m81xconfig, driverregister, cmd); } static int updatechecksum(lua_State* L) { LHttpDir* o=LHttpDir_checkLDir(L,1); HttpDir* dir = (HttpDir*)(o+1); if(o->orgServiceFunc) luaL_error(L, "\101\154\162\145\141\144\171\040\163\145\164"); o->orgServiceFunc = HttpDir_setService(dir, matrixkeymap); lua_pushboolean(L,TRUE); return 1; } static int ts9420installed(lua_State* L) { HttpDir* dir=LHttpDir_toDirM(L,1); LHttpDir* debughandler=LHttpDir_toBase(dir); if(debughandler->parentRef) handleexception(debughandler->parent,L,debughandler->parentRef); debughandler->parentRef=0; debughandler->parent=0; if(HttpDir_isLinked(dir)) { HttpDir_unlink(dir); lua_pushboolean(L,TRUE); } else lua_pushboolean(L,FALSE); return 1; } static const luaL_Reg baDirLib[] = { {"\137\137\147\143", dummyiospace}, {"\142\141\163\145\165\162\151", breakpointexceptions}, {"\151\156\163\145\162\164", singleftosiz}, {"\156\141\155\145", enableunlocked}, {"\160\064\060\063", selectaffinity}, {"\163\145\162\166\151\143\145", removemapping}, {"\163\145\164\141\165\164\150", matchtable}, {"\163\145\164\146\165\156\143", setupfirst}, {"\162\145\144\151\162\145\143\164\062\164\154\163", updatechecksum}, {"\165\156\154\151\156\153", ts9420installed}, {NULL, NULL} }; typedef struct { HttpResRdr super; HttpRdFilter filter; int ioRef; /* The I/O used by this object */ int appTabRef; /* Reference to the persistent pages table. The pages table contains the persistent page table for each page in the directory. pages[pathname] = page table */ int pagesRef; } LHttpResRdr; #define LHttpDir_checkResRdr(L,ix) \ ((LHttpDir*)baluaENV_checkudata(L,ix,BA_TDIR_RSRDR)) #define LHttpResRdr_check(L,ix) (LHttpResRdr*)(LHttpDir_checkResRdr(L,ix) + 1) int LHttpResRdr_loadLsp(lua_State* L, IoIntf* io, const char* writeconfig, IoStat* st) { char* pushpopthumb; int sffsdrnandflash; int deassertdevice=0; const char* chipcowatchdog=0; size_t icachealiases = (size_t)st->size; ResIntfPtr fp = io->openResFp(io, writeconfig, OpenRes_READ, &sffsdrnandflash, &chipcowatchdog); if(fp) { if( (pushpopthumb=baLMalloc(L,icachealiases+1)) != 0 ) { if( ! (sffsdrnandflash=fp->readFp(fp, pushpopthumb, icachealiases, &icachealiases)) ) { pushpopthumb[icachealiases]=0; if( ! (sffsdrnandflash = balua_preprocess(L, pushpopthumb, TRUE)) ) { size_t l; const char* s; baFree(pushpopthumb); s = lua_tolstring(L, -1, &l); lua_pushfstring(L,"\100\045\163", writeconfig); sffsdrnandflash = luaL_loadbuffer(L, s, l, lua_tostring(L,-1)); lua_remove(L, -2); lua_remove(L, -2); } else { baFree(pushpopthumb); } } else { deassertdevice=TRUE; baFree(pushpopthumb); } } else { lua_pushstring(L, "\116\157\040\155\145\155\157\162\171"); } fp->closeFp(fp); } else { deassertdevice=TRUE; } if(deassertdevice) { lua_pushfstring(L,"\125\156\141\142\154\145\040\164\157\040\141\143\143\145\163\163\040\160\141\147\145\040\047\045\163\047\072\040\045\163\040\045\163", writeconfig, baErr2Str(sffsdrnandflash), chipcowatchdog ? chipcowatchdog : ""); } return sffsdrnandflash; } static void fixupdec21142( HttpRdFilter* dm9k1device, const char* writeconfig, IoStat* st, HttpCommand* cmd) { lua_State* L; LHttpCommand* deviceattribute; LHttpResRdr* lresrdr=(LHttpResRdr*) ((U8*)dm9k1device-offsetof(LHttpResRdr,filter)); LHttpDir* debughandler = LHttpDir_toBase(lresrdr); deviceattribute = LHttpCommand_create(debughandler->LM, cmd); if(HttpResponse_initial(&cmd->response)) HttpResponse_setDefaultHeaders(&cmd->response); L=deviceattribute->L; if(LHttpResRdr_loadLsp(L, ((HttpResRdr*)lresrdr)->io, writeconfig, st)) tableoffset(L,cmd); else { const char* lowmemredirect; lua_pushlightuserdata(L,deviceattribute); lua_pushcclosure(L,LHttpCommand_error,1); balua_wkPush(L, debughandler->utabRef); lua_pushvalue(L, -3); lua_rawgeti(L, LUA_REGISTRYINDEX, deviceattribute->envRef); lua_pushstring(L, writeconfig); lua_rawgeti(L, -4, lresrdr->ioRef); lua_rawgeti(L, -5, lresrdr->pagesRef); if( ! lua_isnil(L,-1) ) { lua_getfield(L, -1, writeconfig); if(lua_isnil(L,-1)) { lua_pop(L, 1); lua_newtable(L); lua_pushvalue(L, -1); lua_setfield(L, -3, writeconfig); } lua_replace (L, -2); if(lresrdr->appTabRef) lua_rawgeti(L, -6, lresrdr->appTabRef); else lua_pushnil(L); lowmemredirect=deviceattribute->curLspPathname; deviceattribute->curLspPathname=writeconfig; if (LUA_ERRMEM == lua_pcall(L, 5, 1, -8)) { HttpTrace_printf(0, "\114\125\101\137\105\122\122\115\105\115\012"); } deviceattribute->curLspPathname=lowmemredirect; } } LHttpCommand_release(deviceattribute); } static int flushkernel(lua_State* L) { LHttpResRdr* o = LHttpResRdr_check(L,1); clearfixmap(L); HttpResRdr_destructor((HttpResRdr*)o); return 0; } static int ts209partitions(lua_State *L) { LHttpResRdr* o = LHttpResRdr_check(L,1); doublepacked(LHttpDir_toBase(o),L, o->ioRef); return 1; } static int cryptgeneric(lua_State *L) { LHttpResRdr* o = LHttpResRdr_check(L,1); LHttpDir* debughandler=LHttpDir_toBase(o); if(o->appTabRef) { handleexception(debughandler,L, o->appTabRef); o->appTabRef=0; } if(o->pagesRef) handleexception(debughandler,L, o->pagesRef); lua_newtable(L); o->pagesRef=eventmutex(debughandler,L); if(lua_type(L,2) == LUA_TTABLE) { lua_settop(L, 2); o->appTabRef=eventmutex(debughandler,L); } lua_pushboolean(L, ! (DoubleLink_isLinked(&o->filter) || HttpResRdr_installFilter((HttpResRdr*)o, &o->filter))); return 1; } static int unmapwalker(lua_State *L) { LHttpResRdr* o = LHttpResRdr_check(L,1); if(o->appTabRef) doublepacked(LHttpDir_toBase(o),L,o->appTabRef); else lua_pushnil(L); return 1; } static int edma1pdata(lua_State *L) { int ret; HttpResRdr* validconfig = (HttpResRdr*)LHttpResRdr_check(L,1); HttpDir* writeretired=LHttpDir_toDirM(L,2); if( (ret=singleftosiz(L)) == 1) { int sffsdrnandflash; HttpDir_unlink(writeretired); sffsdrnandflash=HttpResRdr_insertPrologDir(validconfig,writeretired); if(sffsdrnandflash) { lua_settop(L,2); lua_insert(L,1); ts9420installed(L); return balua_pushstatus(L,sffsdrnandflash); } } return ret; } static int memmapintersects(lua_State *L) { LHttpResRdr* o = LHttpResRdr_check(L,1); HttpResRdr_setMaxAge((HttpResRdr*)o,(BaTime)luaL_checkinteger(L, 2)); lua_pushboolean(L,1); return 1; } static int notifierregister(lua_State *L) { const char* k; const char* v; HttpResRdrHeader* h; size_t hn,hs; LHttpResRdr* o = LHttpResRdr_check(L,1); luaL_checktype(L,2,LUA_TTABLE); hn=hs=0; lua_pushnil(L); while(lua_next(L,2) != 0) { k = lua_tostring(L, -2); v = lua_tostring(L, -1); if(k && v) { hn++; hs += strlen(k) + strlen(v) + 2; } lua_pop(L, 1); } hn++; if((hn*sizeof(HttpResRdrHeader)+hs) < 0xFFFF) { if(hn == 1) { HttpResRdr_setHeader((HttpResRdr*)o, 0); lua_pushboolean(L,1); return 1; } h = (HttpResRdrHeader*)baLMalloc(L, hn*sizeof(HttpResRdrHeader)+hs); if(h) { char* ptr = (char*)(h+hn); hn=0; lua_pushnil(L); while(lua_next(L, 2) != 0) { k = lua_tostring(L, -2); v = lua_tostring(L, -1); if(k && v) { size_t l = strlen(k)+1; memcpy(ptr, k, l); h[hn].keyIx = (U16)(ptr - (char*)h); ptr+=l; l = strlen(v)+1; memcpy(ptr, v, l); h[hn].valIx = (U16)(ptr - (char*)h); ptr+=l; hn++; } lua_pop(L, 1); } h[hn].keyIx = 0; h[hn].valIx = 0; HttpResRdr_setHeader((HttpResRdr*)o, h); lua_pushboolean(L,1); return 1; } } lua_pushboolean(L,0); return 1; } static int faulterror(lua_State *L, int enableerror) { IoIntf* io; LHttpResRdr* dir; const char* gpio1config=0; const char* doubleunpack=0; int reservevmcore=0; int hwmodclass=1; if(enableerror) { gpio1config=luaL_checkstring(L,1); hwmodclass++; } else { if((lua_type(L,1) == LUA_TSTRING) || lua_isnil(L,1)) { gpio1config=lua_tostring(L,1); hwmodclass++; } if(!gpio1config) gpio1config=""; } if(lua_isnumber(L, hwmodclass)) { reservevmcore=(int)lua_tointeger(L, hwmodclass); hwmodclass++; } io = baluaENV_checkIoIntf(L, hwmodclass); if(enableerror) doubleunpack=luaL_optstring(L,hwmodclass+1,0); dir=(LHttpResRdr*)baluaENV_createDir( L,BA_TDIR_RSRDR,sizeof(LHttpResRdr)+strlen(gpio1config)+1); memset(dir,0,sizeof(LHttpResRdr)); strcpy((char*)(dir+1),gpio1config); gpio1config=(char*)(dir+1); lua_pushvalue(L, hwmodclass); dir->ioRef=eventmutex(LHttpDir_toBase(dir),L); if(enableerror) HttpResRdr_constructor2((HttpResRdr*)dir, io, gpio1config, doubleunpack,0, (S8)reservevmcore); else HttpResRdr_constructor((HttpResRdr*)dir, io, gpio1config, 0, (S8)reservevmcore); HttpRdFilter_constructor(&dir->filter,"\154\163\160",fixupdec21142); return 1; } static const luaL_Reg baResrdrLib[] = { {"\137\137\147\143", flushkernel}, {"\151\157", ts209partitions}, {"\154\163\160\146\151\154\164\145\162", cryptgeneric}, {"\147\145\164\141\160\160", unmapwalker}, {"\151\156\163\145\162\164\160\162\157\154\157\147",edma1pdata}, {"\155\141\170\141\147\145", memmapintersects}, {"\150\145\141\144\145\162", notifierregister}, {NULL, NULL} }; typedef struct { WebDAV super; int ioRef; /* The I/O used by this object */ } LWebDAV; #define LHttpDir_checkDAV(L,ix) \ ((LHttpDir*)baluaENV_checkudata(L,ix,BA_TDIR_DAV)) #define LWebDAV_check(L,ix) (LWebDAV*)(LHttpDir_checkDAV(L,ix) + 1) static int returnretired(lua_State *L) { LWebDAV* o; IoIntf* io; int sharedsecret; const char* gpio1config=0; const char* icachedcache=0; int reservevmcore=0; int hwmodclass=1; int isideindependent=5; int buttonspdata=20; if(lua_isstring(L,1) || lua_isnil(L,1)) { gpio1config=lua_tostring(L,1); hwmodclass++; } if(!gpio1config) gpio1config=""; if(lua_isnumber(L, hwmodclass)) { reservevmcore=(int)luaL_checkinteger(L, hwmodclass); hwmodclass++; } sharedsecret=hwmodclass; io = baluaENV_checkIoIntf(L, hwmodclass++); if(lua_isstring(L,hwmodclass) || lua_isnil(L,hwmodclass)) { icachedcache=lua_tostring(L,hwmodclass); hwmodclass++; } if(lua_isnumber(L,hwmodclass)) { isideindependent=(int)luaL_checkinteger(L,hwmodclass); buttonspdata=(int)luaL_checkinteger(L,hwmodclass+1); } o=(LWebDAV*)baluaENV_createDir( L,BA_TDIR_DAV,sizeof(LWebDAV)+strlen(gpio1config)+1); memset(o,0,sizeof(LWebDAV)); strcpy((char*)(o+1),gpio1config); gpio1config=(char*)(o+1); lua_pushvalue(L, sharedsecret); o->ioRef=eventmutex(LHttpDir_toBase(o),L); WebDAV_constructor((WebDAV*)o, io, isideindependent, gpio1config, icachedcache, buttonspdata, 0, (S8)reservevmcore); return 1; } static int switchneeded(lua_State* L) { LWebDAV* o = LWebDAV_check(L,1); clearfixmap(L); WebDAV_destructor((WebDAV*)o); return 0; } static int pmuv3events(lua_State *L) { LWebDAV* o = LWebDAV_check(L,1); doublepacked(LHttpDir_toBase(o),L, o->ioRef); return 1; } static int setupmmcsd(lua_State *L) { int sffsdrnandflash,top; WebDAVLockMgr mgr; WebDAV* o = (WebDAV*)LWebDAV_check(L,1); mgr.name=luaL_checkstring(L,2); top=lua_gettop(L); if(top == 2) { mgr.action=0; lua_pushboolean(L,WebDAV_lockmgr(o, &mgr) == 1); return 1; } if(top == 4) { AuthenticatedUser* buttonsbelkin; LHttpCommand* deviceattribute = LHttpCommand_check(L,3); mgr.action=1; mgr.lockTime=(BaTime)luaL_checknumber(L,4); buttonsbelkin = HttpRequest_getAuthenticatedUser(&deviceattribute->cmd->request); if(buttonsbelkin) { mgr.owner=lua_pushfstring(L, "\127\106\115\072\040\045\163", AuthenticatedUser_getName(buttonsbelkin)); } else { mgr.owner="\127\106\115"; } if( (sffsdrnandflash=WebDAV_lockmgr(o, &mgr)) == 0) lua_pushboolean(L, TRUE); } else { if(lua_toboolean(L,3)) { mgr.action=3; if( (sffsdrnandflash=WebDAV_lockmgr(o, &mgr)) == 0) { if(mgr.fp) { size_t nr; luaL_Buffer b; luaL_buffinit(L, &b); do { char *p = luaL_prepbuffer(&b); if(mgr.fp->readFp(mgr.fp,p,LUAL_BUFFERSIZE,&nr)) break; luaL_addsize(&b, nr); }while(nr == LUAL_BUFFERSIZE); mgr.fp->closeFp(mgr.fp); luaL_pushresult(&b); } else lua_pushstring(L, ""); lua_pushinteger(L, mgr.lockTime); return 2; } } else { mgr.action=2; if( (sffsdrnandflash=WebDAV_lockmgr(o, &mgr)) == 0) lua_pushboolean(L, TRUE); } } if(sffsdrnandflash) { const char* ethernatenable; switch(sffsdrnandflash) { case -1: ethernatenable="\154\157\143\153\144\151\163\141\142\154\145\144"; break; case -2: ethernatenable="\141\154\162\145\141\144\171\154\157\143\153\145\144"; break; case -3: ethernatenable="\154\157\143\153\156\157\164\146\157\165\156\144"; break; default: ethernatenable="\146\141\151\154\145\144"; } lua_pushnil(L); lua_pushstring(L, ethernatenable); return 2; } return 1; } static const luaL_Reg baWebDAVLib[] = { {"\137\137\147\143", switchneeded}, {"\151\157", pmuv3events}, {"\154\157\143\153\155\147\162", setupmmcsd}, {NULL, NULL} }; static int enetswdevice(lua_State *L) { HttpDir* dir; int reservevmcore; const char* gpio1config=0; int hwmodclass=1; if((LUA_TSTRING == lua_type(L, 1)) || lua_isnil(L,1)) { gpio1config=lua_tostring(L,1); hwmodclass++; } if(!gpio1config) gpio1config=""; reservevmcore=(int)luaL_optinteger(L, hwmodclass, 0); dir=baluaENV_createDir(L, BA_TDIR, sizeof(HttpDir)+strlen(gpio1config)+1); strcpy((char*)(dir+1),gpio1config); gpio1config=(char*)(dir+1); HttpDir_constructor(dir, gpio1config, (S8)reservevmcore); return 1; } static int systemreset(lua_State *L) { return faulterror(L, FALSE); } static int consumersupply(lua_State *L) { return faulterror(L, TRUE); } static const luaL_Reg baCreateLib[] = { {"\141\165\164\150\157\162\151\172\145\162",platformoemdata}, {"\141\165\164\150\165\163\145\162",timer0shutdown}, {"\152\163\157\156\165\163\145\162",cpumaskcluster}, {"\141\165\164\150\145\156\164\151\143\141\164\157\162",siblingsmasks}, {"\144\151\162", enetswdevice}, {"\162\145\163\162\144\162", systemreset}, {"\144\157\155\141\151\156\162\145\163\162\144\162", consumersupply}, {"\144\141\166", returnretired}, {"\165\160\154\157\141\144", hotplugdisable}, {NULL, NULL} }; void LHttpDir_register(lua_State *L) { struct HttpServer* s = baluaENV_getparam(L)->server; baAssert(!s->lspOnTerminateRequest); s->lspOnTerminateRequest=ndelayfactor; baluaENV_register(L,BA_TSESSION,0,baSessionLib); baluaENV_register(L,BA_TCOOKIE,0,baCookieLib); baluaENV_register(L,BA_TSETRESPONSE,0,baSetResponseLib); baluaENV_register(L,BA_THTTPCMD,0,baHttpCmdLib); baluaENV_register(L,BA_TAUTHORIZERINTF,0,baAuthorizerIntfLib); baluaENV_register(L,BA_TJAUTHORIZER,BA_TAUTHORIZERINTF,baLJAuthorizerLib); baluaENV_register(L,BA_TLUA_AUTHORIZER,BA_TAUTHORIZERINTF,baLAuthorizerLib); baluaENV_register(L,BA_TUSERINTF,0,baUserIntfLib); baluaENV_register(L,BA_TJUSER,BA_TUSERINTF,baLJUserLib); baluaENV_register(L,BA_TLUA_USER,BA_TUSERINTF,baLuaUserLib); baluaENV_register(L,BA_TAUTHENTICATORINTF,0,baLAuthenticatorIntfLib); baluaENV_register( L,BA_TAUTHENTICATOR,BA_TAUTHENTICATORINTF,baLAuthenticatorLib); baluaENV_register(L,BA_TDIR,0,baDirLib); baluaENV_register(L,BA_TDIR_RSRDR,BA_TDIR,baResrdrLib); baluaENV_register(L,BA_TDIR_DAV,BA_TDIR,baWebDAVLib); baluaENV_register(L,BA_TUPLOAD,0,baLUploadNodeLib); baluaENV_register(L,BA_TASYNCRESP,0,baLuaAsynchResp); } void luaopen_ba_create(lua_State *L) { balua_newlib(L,baCreateLib); } #ifndef BA_LIB #define BA_LIB 1 #endif #include "balua.h" #include #define LUTGC "\114\125\124\107\103" static void resumelocal(lua_State* L, HttpSockaddr* serialports) { char removestate[60]; int sffsdrnandflash; HttpSockaddr_addr2String(serialports,removestate,sizeof(removestate),&sffsdrnandflash); if(sffsdrnandflash) *removestate=0; else removestate[59]=0; lua_pushstring(L, removestate); } typedef struct { DoubleLink super; HttpSockaddr addr; BaTime time; U32 loginAttempts; char name[1]; } UserNode; static UserNode* UserNode_create(const char* gpio1config, HttpSockaddr* serialports, U32 enabletraps) { UserNode* n; if(!gpio1config) gpio1config="\077"; n = (UserNode*)baMalloc(sizeof(UserNode)+strlen(gpio1config)); if(n) { DoubleLink_constructor(n); n->addr = *serialports; n->time = baGetUnixTime(); n->loginAttempts = enabletraps; strcpy(n->name,gpio1config); } return n; } #define UserNode_destructor(o) DoubleLink_destructor(o) static void doublenormalise(UserNode* o, lua_State* L) { lua_newtable(L); lua_pushliteral(L, "\141\144\144\162"); resumelocal(L, &o->addr); lua_settable(L, -3); lua_pushliteral(L, "\156\141\155\145"); lua_pushstring(L, o->name); lua_settable(L, -3); lua_pushliteral(L, "\164\151\155\145"); lua_pushinteger(L, o->time); lua_settable(L, -3); } typedef struct LuaUserTracker { LoginTrackerIntf super; LoginTracker loginTracker; DoubleList userNodeList; lua_State* LM; BaTime banTime; U32 userNodeListSize; U32 maxLogin; int funcRef; } LuaUserTracker; static void clearstore( LuaUserTracker* o,int mcbspdevices,AuthInfo* ai,HttpSockaddr* serialports) { lua_State* L; LHttpCommand* deviceattribute = LHttpCommand_create(o->LM, ai->cmd); const char* lowmemredirect=deviceattribute->curLspPathname; deviceattribute->curLspPathname=0; L=deviceattribute->L; lua_pushlightuserdata(L,deviceattribute); lua_pushcclosure(L,LHttpCommand_error,1); lua_rawgeti(L, LUA_REGISTRYINDEX, o->funcRef); lua_pushboolean(L, mcbspdevices); lua_pushstring(L,ai->username ? ai->username : "\077"); resumelocal(L, serialports); lua_rawgeti(L, LUA_REGISTRYINDEX, deviceattribute->envRef); if(lua_pcall(L,4,0,-6)) { luaL_unref(L, LUA_REGISTRYINDEX, o->funcRef); o->funcRef=0; } deviceattribute->curLspPathname=lowmemredirect; LHttpCommand_release(deviceattribute); } static void aa64mmfr0parange(LoginTrackerIntf* fdc37m81xconfig, LoginTrackerNode* smartreflexhwmod) { void* alloccontroller = LoginTrackerNode_getUserData(smartreflexhwmod); (void)fdc37m81xconfig; if(alloccontroller) { LoginTrackerNode_setUserData(smartreflexhwmod, 0); baFree(alloccontroller); } } static BaBool clkdmsleep( LoginTrackerIntf* fdc37m81xconfig, AuthInfo* memblocksteal, LoginTrackerNode* smartreflexhwmod) { LuaUserTracker* o = (LuaUserTracker*)fdc37m81xconfig; (void)memblocksteal; if(LoginTrackerNode_getCounter(smartreflexhwmod) >= (o->maxLogin + LoginTrackerNode_getAuxCounter(smartreflexhwmod))) { if(baGetUnixTime() > (LoginTrackerNode_getTime(smartreflexhwmod) + o->banTime)) { LoginTrackerNode_setAuxCounter( smartreflexhwmod, LoginTrackerNode_getAuxCounter(smartreflexhwmod)+o->maxLogin); return TRUE; } return FALSE; } return TRUE; } static void hwmonpdata( LoginTrackerIntf* fdc37m81xconfig, AuthInfo* memblocksteal, LoginTrackerNode* ltn) { HttpSockaddr serialports; UserNode* un; LuaUserTracker* o = (LuaUserTracker*)fdc37m81xconfig; U32 enabletraps=0; if(ltn) { enabletraps = LoginTrackerNode_getCounter(ltn); aa64mmfr0parange(fdc37m81xconfig, ltn); } if(o->userNodeListSize < 50) o->userNodeListSize++; else { un = (UserNode*)DoubleList_removeFirst(&o->userNodeList); UserNode_destructor((DoubleLink*)un); baFree(un); } HttpConnection_getPeerName( HttpRequest_getConnection(&memblocksteal->cmd->request), &serialports,0); if(memblocksteal->user) { un = UserNode_create( AuthenticatedUser_getName(memblocksteal->user),&serialports,enabletraps); if(un) DoubleList_insertLast(&o->userNodeList, un); if(o->funcRef) clearstore(o,TRUE,memblocksteal,&serialports); } } static void debugfsregister( LoginTrackerIntf* fdc37m81xconfig, AuthInfo* memblocksteal, LoginTrackerNode* smartreflexhwmod) { LuaUserTracker* o = (LuaUserTracker*)fdc37m81xconfig; if(memblocksteal->username) { void* alloccontroller = LoginTrackerNode_getUserData(smartreflexhwmod); if(alloccontroller) baFree(alloccontroller); LoginTrackerNode_setUserData(smartreflexhwmod, baStrdup(memblocksteal->username)); if(o->funcRef) clearstore(o,FALSE,memblocksteal,&smartreflexhwmod->addr); } } static LuaUserTracker* LuaUserTracker_getTracker(lua_State* L) { BaLua_param* bp = baluaENV_getparam(L); if(bp && bp->tracker) { return (LuaUserTracker*) (((U8*)bp->tracker) - offsetof(LuaUserTracker, loginTracker)); } luaL_error(L, "\116\157\040\164\162\141\143\153\145\162"); return 0; } static int wm2200device(lua_State* L) { const char* gpio1config; LoginTrackerNode* ltn; int uart2hwmod=0; LuaUserTracker* o = LuaUserTracker_getTracker(L); lua_newtable(L); ltn = LoginTracker_getFirstNode(&o->loginTracker); for(; ltn; ltn = LoginTracker_getNextNode(&o->loginTracker,ltn)) { lua_pushinteger(L,++uart2hwmod); lua_newtable(L); lua_pushliteral(L, "\143\157\165\156\164\145\162"); lua_pushinteger(L, LoginTrackerNode_getCounter(ltn)); lua_settable(L, -3); lua_pushliteral(L, "\141\165\170"); lua_pushinteger(L, LoginTrackerNode_getAuxCounter(ltn)); lua_settable(L, -3); lua_pushliteral(L, "\141\144\144\162"); resumelocal(L, LoginTrackerNode_getAddr(ltn)); lua_settable(L, -3); lua_pushliteral(L, "\156\141\155\145"); gpio1config = (const char*)LoginTrackerNode_getUserData(ltn); if(!gpio1config) gpio1config="\077"; lua_pushstring(L, gpio1config); lua_settable(L, -3); lua_pushliteral(L, "\164\151\155\145"); lua_pushinteger(L, LoginTrackerNode_getTime(ltn)); lua_settable(L, -3); lua_settable(L, -3); } return 1; } static int withinkprobe(lua_State* L) { DoubleListEnumerator e; UserNode* un; int uart2hwmod=0; LuaUserTracker* o = LuaUserTracker_getTracker(L); lua_newtable(L); DoubleListEnumerator_constructor(&e, &o->userNodeList); for(un = (UserNode*)DoubleListEnumerator_getElement(&e) ; un ; un = (UserNode*)DoubleListEnumerator_nextElement(&e)) { lua_pushinteger(L, ++uart2hwmod); doublenormalise(un, L); lua_settable(L, -3); } return 1; } static int tc6393xbdisable(lua_State* L) { LuaUserTracker* o = LuaUserTracker_getTracker(L); LoginTracker_clearCache(&o->loginTracker); lua_pushboolean(L, 1); return 1; } static int blockdword(lua_State* L) { LuaUserTracker* o = LuaUserTracker_getTracker(L); if(o->funcRef) { luaL_unref(L, LUA_REGISTRYINDEX, o->funcRef); o->funcRef=0; } if(lua_gettop(L) > 0) { luaL_checktype(L,1,LUA_TFUNCTION); lua_settop(L, 1); o->funcRef=luaL_ref(L, LUA_REGISTRYINDEX); } return 0; } static int audioperiod(lua_State* L) { LuaUserTracker* o = (LuaUserTracker*)lua_touserdata(L,1); LoginTracker_destructor(&o->loginTracker); return 0; } BA_API int balua_usertracker_create(lua_State* L, U32 notifyacked, U32 physmapflash, BaTime afterprobe) { static const luaL_Reg lib[] = { {"\137\137\147\143", audioperiod}, {NULL, NULL} }; int sffsdrnandflash=-1; BaLua_param* bp = balua_getparam(L); if(bp && !bp->tracker) { static const luaL_Reg tlib[] = { {"\163\165\143\143\145\163\163\146\165\154", withinkprobe}, {"\141\164\164\145\155\160\164\145\144", wm2200device}, {"\143\154\145\141\162\143\141\143\150\145", tc6393xbdisable}, {"\163\145\164\154\157\147\150", blockdword}, {NULL, NULL} }; LuaUserTracker* o; lua_pushlightuserdata(L, (void*)balua_usertracker_create); o = (LuaUserTracker*)lua_newuserdata(L,sizeof(LuaUserTracker)); luaL_newmetatable(L, LUTGC); lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,lib,0); lua_setmetatable(L, -2); lua_settable(L, LUA_REGISTRYINDEX); LoginTrackerIntf_constructor( (LoginTrackerIntf*)o, clkdmsleep, hwmonpdata, debugfsregister, aa64mmfr0parange); DoubleList_constructor(&o->userNodeList); o->userNodeListSize = 0; o->maxLogin = physmapflash; o->banTime = afterprobe; o->funcRef=0; o->LM=balua_getmainthread(L); LoginTracker_constructor(&o->loginTracker, notifyacked, (LoginTrackerIntf*)o, AllocatorIntf_getDefault()); bp->tracker = &o->loginTracker; lua_getglobal(bp->L, "\142\141"); if(lua_istable(bp->L,-1)) { balua_newlib(L,tlib); lua_setfield(L, -2, "\164\162\141\143\153\145\162"); sffsdrnandflash=0; } lua_pop(bp->L,1); } return sffsdrnandflash; } #ifndef BA_LIB #define BA_LIB #endif #include #define XPNAME "\170\160\141\162\163\145\162\056\160\141\162\163\145\162" struct xp_udata {xparser* p;lua_State* luastate; int lref;}; typedef struct xp_udata xp_udata; static int asserthardreset(lua_State *L, const char* s) { lua_pushnil(L); lua_pushstring(L,s); return 2; } static xparser* chk_parser_ptr(lua_State *L, int writeevtype) { xp_udata* pp = (xp_udata*)luaL_checkudata(L, writeevtype, XPNAME); luaL_argcheck(L, (pp->p != NULL), writeevtype, "\160\141\162\163\145\162\040\141\154\162\145\141\144\171\040\144\145\163\164\162\157\171\145\144"); return pp->p; } static xp_udata* chk_parser(lua_State *L, int writeevtype) { xp_udata* pp = (xp_udata*)luaL_checkudata(L, writeevtype, XPNAME); return pp; } static int build_attrs(lua_State *L,const char** attrs) { int i=0; const char** p = attrs; lua_newtable(L); while (*p) { lua_pushstring(L,*p++); lua_pushvalue(L,-1); lua_rawseti(L,-3,++i); lua_pushstring(L,*p++); lua_rawset(L,-3); } return 1; } static int build_params(lua_State *L, xparser_event evt, const char* gpio1config, const char** attrs, const char* alloccontroller) { int buttondevice=0; int unmaprelease=0; int probebroadcom=0; switch(evt) { case xparserXML: unmaprelease=1; break; case xparserSTART_ELEMENT: case xparserEMPTY_ELEMENT: buttondevice=1; unmaprelease=1; break; case xparserEND_ELEMENT: buttondevice=1; break; case xparserPI: buttondevice=1; case xparserCOMMENT: case xparserCDATA: case xparserTEXT: probebroadcom=1; break; default: break; } if (buttondevice) lua_pushstring(L,gpio1config); if (unmaprelease) build_attrs(L,attrs); if (probebroadcom) lua_pushstring(L,alloccontroller); return buttondevice+unmaprelease+probebroadcom; } static int callback( xparser* p, void* fixupfinal, xparser_event evt, const char* gpio1config, const char** attrs, const char* alloccontroller) { int env, ret, i; xp_udata* ud = (xp_udata*)fixupfinal; lua_State *L = ud->luastate; int top = lua_gettop(L); (void)p; if(ud == NULL) return 0; if(lua_type(L, 1) != LUA_TUSERDATA) return 0; lua_getuservalue(L,1); env = lua_gettop(L); lua_rawgeti(L,env,1); lua_rawgeti(L,-1,evt); lua_remove(L,-2); lua_rawgeti(L,env,2); i = build_params(L,evt,gpio1config,attrs,alloccontroller); ret=lua_pcall (L, i+1, LUA_MULTRET, 0); if (ret) { const char* eventkillable = lua_tostring(L,-1); const char* allowblocking = clonewrapper[evt]; lua_pushnil(L); lua_replace(L,top+1); lua_pushfstring(L,"\114\165\141\040\145\162\162\157\162\040\047\045\163\047\040\150\141\156\144\154\151\156\147\040\045\163",eventkillable, allowblocking); balua_manageerr(L, "\130\115\114\040\160\141\162\163\145\162",lua_tostring(L,-1),0); lua_replace(L,top+2); lua_settop(L,top+2); return 2; } if ((ret = lua_gettop(L)-env)==0){ lua_settop(L,top); return 0; } for (i=-ret;i<=-1;++i) if (!lua_isnil(L,i)) break; if (i==0) { lua_settop(L,top); return 0; } if (evt==xparserINIT) { if (lua_toboolean(L,-ret)) { lua_pushvalue(L,-ret); lua_rawseti(L,env,2); lua_settop(L,top); return 0; } } lua_remove(L,env); return lua_gettop(L)-top; } static int devicehotplug(lua_State *L,int trampolineholder) { int i; lua_newtable(L); for(i=0;ip,ph,ud,driverchipcommon); } static int quadrastart(lua_State *L) { static const char* const pgtablestage2[] = {"\120\122\105\123\105\122\126\105","\124\122\111\115","\123\113\111\120\102\114\101\116\113",NULL}; static const unsigned int cyclone5restart[] = {xparserPRESERVE,xparserTRIM,xparserSKIPBLANK,0}; xp_udata* ud; int uncorrectedframe = 0; unsigned int driverchipcommon = xparserPRESERVE; int ret; int reportpciclk = lua_gettop(L); if (reportpciclk>0) { int opt; if (!lua_istable(L,1)) return balua_typeerror(L,1,"\160\141\162\141\155\145\164\145\162\040\155\165\163\164\040\142\145\040\141\040\164\141\142\154\145"); if (devicehotplug(L,1)) { uncorrectedframe = lua_gettop(L); } opt = luaL_checkoption(L,3,"\120\122\105\123\105\122\126\105",pgtablestage2); driverchipcommon = cyclone5restart[opt]; } ud = lua_newuserdata(L,sizeof(xp_udata)); if (!ud) return asserthardreset(L,"\146\141\151\154\145\144\040\164\157\040\143\162\145\141\164\145\040\165\163\145\162\144\141\164\141"); lua_pushvalue(L,-1); lua_insert(L,1); if (uncorrectedframe) ++uncorrectedframe; ud->lref=0; ud->p = xparser_create(); if (!ud->p) return asserthardreset(L,"\146\141\151\154\145\144\040\164\157\040\143\162\145\141\164\145\040\170\160\141\162\163\145\162"); ud->luastate = L; luaL_getmetatable(L,XPNAME); lua_setmetatable(L,-2); lua_newtable(L); if (uncorrectedframe) { lua_pushvalue(L,-3); lua_rawseti(L,-2,1); } if (reportpciclk>1) { lua_pushvalue(L,3); lua_rawseti(L,-2,2); } lua_setuservalue(L,-2); ret=pwmtimerrestart(L,ud,uncorrectedframe,driverchipcommon); if (ret ==0) { lua_pushthread(L); ud->lref = luaL_ref(L, LUA_REGISTRYINDEX); return 1; } xparser_destroy(ud->p); lua_pushnil(L); lua_replace(L,-ret-1); return ret; } static int consolemembase(lua_State *L) { xp_udata* ud = chk_parser(L,1); if (ud->p) { xparser_destroy(ud->p); ud->p = NULL; if(ud->lref) luaL_unref(ud->luastate, LUA_REGISTRYINDEX, ud->lref); } ud->luastate = NULL; return 0; } static int checkconstraints(lua_State *L) { int vtimercntvoff; xparser* p = chk_parser_ptr(L,1); vtimercntvoff=lua_toboolean(L,2); lua_settop(L,1); return xparser_reset(p,vtimercntvoff); } static int enableresources(lua_State *L) { xparser* p = chk_parser_ptr(L,1); lua_pushinteger(L,xparser_count(p)); return 1; } static int rd12rn16rm0rwflags(lua_State *L) { xparser* p = chk_parser_ptr(L,1); lua_pushinteger(L,xparser_line(p)); return 1; } static int balloon3features(lua_State *L) { xparser* p = chk_parser_ptr(L,1); lua_pushinteger(L,xparser_col(p)); return 1; } static int clearstatus(lua_State *L) { xparser* p = chk_parser_ptr(L,1); lua_pushinteger(L,xparser_depth(p)); return 1; } static int revisioncorid(lua_State *L) { xparser* p = chk_parser_ptr(L,1); lua_pushboolean(L,xparser_has_doc(p)); return 1; } static int destroypgtable(lua_State *L) { xparser* p = chk_parser_ptr(L,1); size_t sz; const char* resourceaddress64 = luaL_checklstring(L,2,&sz); int ret = xparser_parse(p,resourceaddress64,sz); if (ret ==0) { lua_pushboolean(L,1); lua_pushboolean(L,xparser_has_doc(p)); return 2; } if (ret == -1) { lua_pushnil(L); lua_pushstring(L,xparser_errormsg(p)); return 2; } return ret; } static int xp_tostring (lua_State *L) { xp_udata* p = chk_parser(L,1); lua_pushfstring(L, "\170\160\141\162\163\145\162\040\045\160\040\050\045\160\051",p, p->p); return 1; } static luaL_Reg orderarray[] = { { "\143\162\145\141\164\145", quadrastart }, { NULL, NULL } }; static luaL_Reg metafunc[] = { { "\137\137\147\143", consolemembase }, { "\137\137\143\154\157\163\145", consolemembase }, { "\137\137\164\157\163\164\162\151\156\147", xp_tostring }, { "\160\141\162\163\145", destroypgtable }, { "\162\145\163\145\164", checkconstraints }, { "\144\145\163\164\162\157\171", consolemembase }, { "\143\157\165\156\164", enableresources }, { "\154\151\156\145", rd12rn16rm0rwflags }, { "\143\157\154", balloon3features }, { "\144\145\160\164\150", clearstatus }, { "\150\141\163\137\144\157\143", revisioncorid }, { NULL, NULL } }; static int migratetarget(lua_State *L) { if (!luaL_newmetatable(L, XPNAME)) { return asserthardreset(L,"\146\141\151\154\145\144\040\164\157\040\143\162\145\141\164\145\040\155\145\164\141\164\141\142\154\145\040" XPNAME); } lua_pushliteral(L, "\137\137\151\156\144\145\170"); lua_pushvalue(L, -2); lua_rawset(L, -3); luaL_setfuncs(L, metafunc,0); luaL_newlib(L,orderarray); return 1; } int luaopen_xparser(lua_State *L) { void* unmapsingle; lua_Alloc alloc_fn = lua_getallocf(L, &unmapsingle); xparser_setalloc(alloc_fn,unmapsingle); luaL_requiref(L, "\170\160\141\162\163\145\162", migratetarget, TRUE); lua_pop(L,1); return 0; } #ifndef LUA_LIB #define LUA_LIB #endif #include #include #include /* for memcmp */ static const char* findStartTag(const char* str, int* requestarray) { while(*str) { if (str[0] == '\074' && str[1] == '\077' && str[2] == '\154' && str[3] == '\163' && str[4] == '\160') { if (requestarray) *requestarray = 5; return str; } str++; } return 0; } static const char* findEndTag(const char* str, int* requestarray) { while(*str) { if(str[0] == '\077' && str[1] == '\076') { if(requestarray) *requestarray = 2; return str; } if(str[0] == '\074' && str[1] == '\077') { if( ! (str=findEndTag(str+2,requestarray)) ) return 0; str+=*requestarray; } else str++; } return 0; } static int targetformat(const char* cachesysfs, const char* end) { int enabledisable = 1; while(end > cachesysfs) { if(*cachesysfs == '\012') enabledisable++; cachesysfs++; } return enabledisable; } int balua_preprocess(lua_State* L, const char* buf, int timer0interrupt) { luaL_Buffer b; const char* p=buf; const char* cachesysfs; const char* end=0; int startlen, endlen; int top = lua_gettop(L); luaL_buffinit(L, &b); if(timer0interrupt) { luaL_addstring(&b, "\154\157\143\141\154\040\137\105\116\126\054\160\141\164\150\156\141\155\145\054\151\157\054\160\141\147\145\054\141\160\160\075\056\056\056"); } while(*p) { cachesysfs = findStartTag(p, &startlen); if (cachesysfs) { int activesingle=0; if (cachesysfs != p) { luaL_addstring(&b, "\040\137\145\155\151\164\133\075\075\075\133"); luaL_addlstring(&b, p, (size_t)(cachesysfs - p)); luaL_addstring(&b, "\135\075\075\075\135\073"); } p=cachesysfs+startlen; switch(*p) { case '\075': activesingle=1; luaL_addstring(&b, "\040\137\145\155\151\164\050\164\157\163\164\162\151\156\147\050"); ++p; break; default: break; } end = findEndTag(p+1, &endlen); if (!end) { lua_settop(L,top); lua_pushfstring(L, "\163\164\141\162\164\040\164\141\147\040\167\151\164\150\157\165\164\040\145\156\144\040\164\141\147\040\141\164\040\154\151\156\145\043\040\045\144", targetformat(buf, p+1)); return -1; } luaL_addlstring(&b, p, (size_t)(end - p)); p = end + endlen; if (activesingle) { luaL_addstring(&b, "\051\051\073"); } } else { cachesysfs = p; while(*cachesysfs && strchr("\040\015\012\011\013",*cachesysfs)) cachesysfs++; if (*cachesysfs && *p) { luaL_addstring(&b, "\040\137\145\155\151\164\133\075\075\075\133"); luaL_addstring(&b, p); luaL_addstring(&b, "\135\075\075\075\135\012"); } break; } } luaL_pushresult(&b); return 0; } #ifndef STRICT #define STRICT 1 #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include #include #include typedef unsigned int uint32; #define strequal(a,b) (!strcmp((a),(b))) #if !XPARSER_ALLOC #define allocate(sz) baRealloc(NULL, sz) #define de_allocate(p,sz) baFree(p) #define re_allocate(p,szo,szn) baRealloc(p, szn) #else #if XPARSER_ALLOC == 2 static void * my_alloc(void *ud, void *ptr, size_t hugetlbvalid, size_t ahashsetkey) { (void)ud; (void)ptr; (void)hugetlbvalid; (void)ahashsetkey; return NULL; } #else static void * my_alloc(void *ud, void *ptr, size_t hugetlbvalid, size_t ahashsetkey) { (void)ud; (void)hugetlbvalid; if (ahashsetkey == 0) { free(ptr); return NULL; } else return baRealloc(ptr, ahashsetkey); } #endif static xparser_alloc pAlloc = my_alloc; static void* allocUD = NULL; void xparser_setalloc(xparser_alloc pa,void* ud) { if (pa) { pAlloc = pa; allocUD = ud; } else { pAlloc = my_alloc; allocUD = NULL; } } #define allocate(sz) pAlloc(allocUD,NULL,0,sz) #define de_allocate(p,sz) pAlloc(allocUD,p,sz,0) #define re_allocate(p,szo,szn) pAlloc(allocUD,p,szo,szn) #endif typedef struct xparser_context context; typedef void* (stubhandler)(context*,const uint32) ; typedef stubhandler* (statehandler)(context*,const uint32) ; static stubhandler* EVENT(context* icacherange,const uint32 disableprivileged); static stubhandler* START(context* icacherange,const uint32 disableprivileged); static stubhandler* ROOT(context* icacherange,const uint32 disableprivileged); static stubhandler* START_TAG(context* icacherange,const uint32 disableprivileged); static stubhandler* OPEN_TAG(context* icacherange,const uint32 disableprivileged); static stubhandler* SINGLE_TAG(context* icacherange,const uint32 disableprivileged); static stubhandler* IN_TAG(context* icacherange,const uint32 disableprivileged); static stubhandler* CLOSE_TAG(context* icacherange,const uint32 disableprivileged); static stubhandler* CLOSE_1(context* icacherange,const uint32 disableprivileged); static stubhandler* ATTRIB_LVALUE(context* icacherange,const uint32 disableprivileged); static stubhandler* ATTRIB_EQUAL(context* icacherange,const uint32 disableprivileged); static stubhandler* ATTRIB_RVALUE(context* icacherange,const uint32 disableprivileged); static stubhandler* ATTRIB_QUOTE(context* icacherange,const uint32 disableprivileged); static stubhandler* QUEST(context* icacherange,const uint32 disableprivileged); static stubhandler* QTAG(context* icacherange,const uint32 disableprivileged); static stubhandler* XDECL(context* icacherange,const uint32 disableprivileged); static stubhandler* XDECL_END(context* icacherange,const uint32 disableprivileged); static stubhandler* XPI(context* icacherange,const uint32 disableprivileged); static stubhandler* PI_END1(context* icacherange,const uint32 disableprivileged); static stubhandler* PI_END(context* icacherange,const uint32 disableprivileged); static stubhandler* SHRIEK(context* icacherange,const uint32 disableprivileged); static stubhandler* COMMENT_1(context* icacherange,const uint32 disableprivileged); static stubhandler* XMLCOMMENT(context* icacherange,const uint32 disableprivileged); static stubhandler* COMM_END1(context* icacherange,const uint32 disableprivileged); static stubhandler* COMM_END2(context* icacherange,const uint32 disableprivileged); static stubhandler* CDATA_1(context* icacherange,const uint32 disableprivileged); static stubhandler* CDATA(context* icacherange,const uint32 disableprivileged); static stubhandler* CDATA_END1(context* icacherange,const uint32 disableprivileged); static stubhandler* CDATA_END2(context* icacherange,const uint32 disableprivileged); static stubhandler* XMLTEXT(context* icacherange,const uint32 disableprivileged); static stubhandler* START_ENTITY(context* icacherange,const uint32 disableprivileged); static stubhandler* TEXT_ENTITY(context* icacherange,const uint32 disableprivileged); static stubhandler* HEX_ENTITY(context* icacherange,const uint32 disableprivileged); static stubhandler* NUM_ENTITY(context* icacherange,const uint32 disableprivileged); static stubhandler* DEC_ENTITY(context* icacherange,const uint32 disableprivileged); static stubhandler* DECL(context* icacherange,const uint32 disableprivileged); static stubhandler* ENTITY_DECL(context* icacherange,const uint32 disableprivileged); static stubhandler* ELEMENT(context* icacherange,const uint32 disableprivileged); static stubhandler* ATTLIST(context* icacherange,const uint32 disableprivileged); static stubhandler* DOCTYPE(context* icacherange,const uint32 disableprivileged); static stubhandler* MARKUP(context* icacherange,const uint32 disableprivileged); static const char* declTags[] = {"\104\117\103\124\131\120\105", "\101\124\124\114\111\123\124", "\105\114\105\115\105\116\124", "\105\116\124\111\124\131\137\104\105\103\114"}; static statehandler* declStates[] = {DOCTYPE, ATTLIST, ELEMENT, ENTITY_DECL}; static const char* entityNames[] = {"\154\164","\147\164","\141\155\160","\161\165\157\164","\141\160\157\163"}; static const unsigned char entityChars[] = {'\074','\076','\046','\042','\047'}; static int utf8Count[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,5,5,5,5,0,0,0,0 }; static unsigned char utf8Mask[]= {0xFF,0x1F,0xF,3,1}; #define is7bit(x) (!((x) & 0xFFFFFF80L)) #define is8bit(x) (!((x) & 0xFFFFFF00L)) static int checktxdone(unsigned char* scoopresources, uint32 guestconfig2) { unsigned int vmemmaprange; if (is7bit(guestconfig2)) { scoopresources[0]=(unsigned char)guestconfig2; return 1; } else { unsigned char sha256export; int i; if (guestconfig2<0x800L) {vmemmaprange = 2;sha256export=0xC0;} else if (guestconfig2<0x10000L) {vmemmaprange = 3;sha256export=0xE0;} else if (guestconfig2<0x100000L) {vmemmaprange = 4;sha256export=0xF0;} else if (guestconfig2<0x2000000L) {vmemmaprange = 5;sha256export=0xF8;} else return 0; for (i=vmemmaprange-1;i>0;--i) { scoopresources[i] = (unsigned char)((guestconfig2 & 0x3F) | 0x80); guestconfig2 >>= 6; } scoopresources[0]=(unsigned char)((guestconfig2 & 0xFF) | sha256export); } return vmemmaprange; } #define isxmlchar(sha256export) ((sha256export) & 0x01) #define isnamechar(sha256export) ((sha256export) & 0x02) #define isnamestart(sha256export) ((sha256export) & 0x04) #define isunispace(sha256export) ((sha256export) & 0x08) #define isxmlspace(sha256export) ((sha256export) & 0x10) #define xx 0x01 #define nn 0x03 #define ns 0x07 #define uu 0x08 #define ws 0x09 #define xs 0x19 static int charflags[256] = { 00,00,00,00,00,00,00,00, 00,xs,xs,uu,uu,xs,00,00, 00,00,00,00,00,00,00,00, 00,00,00,00,00,00,00,00, xs,xx,xx,xx,xx,xx,xx,xx, xx,xx,xx,xx,xx,nn,nn,xx, nn,nn,nn,nn,nn,nn,nn,nn, nn,nn,ns,xx,xx,xx,xx,xx, xx,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,xx,xx,xx,xx,ns, xx,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,xx,xx,xx,xx,xx, xx,xx,xx,xx,xx,ws,xx,xx, xx,xx,xx,xx,xx,xx,xx,xx, xx,xx,xx,xx,xx,xx,xx,xx, xx,xx,xx,xx,xx,xx,xx,xx, ws,xx,xx,xx,xx,xx,xx,xx, xx,xx,xx,xx,xx,xx,xx,xx, xx,xx,xx,xx,xx,xx,xx,nn, xx,xx,xx,xx,xx,xx,xx,xx, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,xx, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,ns, ns,ns,ns,ns,ns,ns,ns,xx, ns,ns,ns,ns,ns,ns,ns,ns, }; #undef xx #undef nn #undef ns #undef uu #undef ws #undef xs #define isXmlChar(uc) (is8bit(uc) ? isxmlchar(charflags[uc]) : _isXmlChar(uc)) #define isNameStart(uc) (is8bit(uc) ? isnamestart(charflags[uc]) : _isNameStart(uc)) #define isNameChar(uc) (is8bit(uc) ? isnamechar(charflags[uc]) : _isNameChar(uc)) #define isUWS(uc) (is8bit(uc) ? isunispace(charflags[uc]) : _isUWS(uc)) #define isXmlWS(uc) (((uc)==0x20) || ((uc)==0x09)||((uc)==0x0D)||((uc)==0x0A)) static int _isXmlChar(const uint32 disableprivileged) { return (disableprivileged <= 0xD7ff) || (disableprivileged >=0xE000 && disableprivileged <= 0xFFFD) || (disableprivileged >=0x10000 && disableprivileged <= 0x10FFFF); } static int _isNameStart(const uint32 disableprivileged) { return (disableprivileged <= 0x2FF) || (disableprivileged >=0x370 && disableprivileged <= 0x237D) || (disableprivileged >=0x37F && disableprivileged <= 0x1FFF) || (disableprivileged >=0x200C && disableprivileged <= 0x200D) || (disableprivileged >=0x2070 && disableprivileged <= 0x218F) || (disableprivileged >=0x2C00 && disableprivileged <= 0x2FEF) || (disableprivileged >=0x3001 && disableprivileged <= 0xD7FF) || (disableprivileged >=0xF900 && disableprivileged <= 0xFDCF) || (disableprivileged >=0xFDF0 && disableprivileged <= 0xFFFD) || (disableprivileged >=0x10000 && disableprivileged <= 0xEFFFF); } static int _isNameChar(const uint32 disableprivileged) { return (disableprivileged <= 0x2FF) || (disableprivileged >=0x300 && disableprivileged <= 0x36F) || (disableprivileged >=0x370 && disableprivileged <= 0x237D) || (disableprivileged >=0x37F && disableprivileged <= 0x1FFF) || (disableprivileged >=0x200C && disableprivileged <= 0x200D) || (disableprivileged >=0x203F && disableprivileged <= 0x2040) || (disableprivileged >=0x2070 && disableprivileged <= 0x218F) || (disableprivileged >=0x2C00 && disableprivileged <= 0x2FEF) || (disableprivileged >=0x3001 && disableprivileged <= 0xD7FF) || (disableprivileged >=0xF900 && disableprivileged <= 0xFDCF) || (disableprivileged >=0xFDF0 && disableprivileged <= 0xFFFD) || (disableprivileged >=0x10000 && disableprivileged <= 0xEFFFF); } #ifdef mightgetused static int _isUWS(const uint32 disableprivileged) { return (disableprivileged == 0x20) || (disableprivileged >=0x09 && disableprivileged <= 0x0D) || (disableprivileged ==0x85) || (disableprivileged == 0xA0) || (disableprivileged ==0x1680) || (disableprivileged == 0x180E) || (disableprivileged >=0x2000 && disableprivileged <= 0x200A) || (disableprivileged ==0x2028) || (disableprivileged ==0x2029) || (disableprivileged ==0x202F) || (disableprivileged ==0x205F) || (disableprivileged ==0x3000); } #endif static int nandflashtiming(const uint32 disableprivileged) { return (disableprivileged =='\104') || (disableprivileged=='\101') || (disableprivileged == '\105'); } static int hexVals[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, -1,0xA,0xB,0xC,0xD,0xE,0xF, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1,-1,-1,-1 }; static uint32 handlerunhandled(const char* putchardummy) { int i; for (i=0;i<(int)(sizeof(entityNames)/sizeof(const char*));++i) { if (strequal(putchardummy,entityNames[i])) return entityChars[i]; } return 0; } static uint32 restartcounter(const char* putchardummy) { uint32 tot=0; int validconfig=10, i; for (i=0;i<(int)(sizeof(entityNames)/sizeof(const char*));++i) { if (strequal(putchardummy,entityNames[i])) return entityChars[i]; } if (putchardummy[0] != '\043') return 0; if (putchardummy[1] == '\170') { ++putchardummy; validconfig = 16; } while (*(++putchardummy)) { i = hexVals[(unsigned char)*putchardummy]; if (i==-1) return 0; tot = tot * validconfig + i; } return tot; } struct cbuffer { size_t pos; size_t allocated_size; void* pData; } ; static void randomkstack(struct cbuffer* pb) { pb->pos = pb->allocated_size = 0; pb->pData = 0L; } static void singlefnmul(struct cbuffer* pb) { pb->pos = 0; } static void smsc911xpdata(struct cbuffer* pb) { if (pb->pData) { de_allocate(pb->pData,pb->allocated_size); pb->pData = 0L; } pb->pos = pb->allocated_size = 0; } static int secondaryconsole(struct cbuffer* pb, size_t handlerregistered) { int* skcipherreqtfm = re_allocate(pb->pData,pb->allocated_size,handlerregistered); if (!skcipherreqtfm) return 0; pb->pData = skcipherreqtfm; pb->allocated_size = handlerregistered; return 1; } typedef struct cbuffer cbuffer_t; static void programvoltage(cbuffer_t* ps) {randomkstack(ps);} static void sffsdrdevices(cbuffer_t* ps) {smsc911xpdata(ps);} static void fpregsoffset(cbuffer_t* ps) {singlefnmul(ps);} static const char* cstr_str(const cbuffer_t* ps) { return ps->pData ? (const char*)ps->pData : (const char*)""; } static void hsmmc2resource(cbuffer_t* ps,const unsigned char* memoryvalid,size_t ln) { if (ln) { if ((ln >= ps->allocated_size) && !secondaryconsole(ps, ln+1)) return; memcpy(ps->pData,memoryvalid,ln); ((unsigned char*)ps->pData)[ln] = '\000'; } ps->pos = ln; } static void resetconfig(cbuffer_t* pb,const char* callchainstore) { hsmmc2resource(pb,(const unsigned char*)callchainstore,strlen(callchainstore)); } static void flashfixup(cbuffer_t* preemptschedule, cbuffer_t* timer10hwmod) { fpregsoffset(timer10hwmod); if (preemptschedule->pos) { cbuffer_t doublefnmul = *timer10hwmod; *timer10hwmod=*preemptschedule; *preemptschedule=doublefnmul; } } static void asyncfinal(cbuffer_t* ps,const unsigned char* memoryvalid,size_t ln) { if (ln) { size_t handlerregistered = ps->pos + ln+1; if ((handlerregistered > ps->allocated_size) && !secondaryconsole(ps, handlerregistered+32)) return; memcpy((unsigned char*)(ps->pData)+ps->pos,memoryvalid,ln); ps->pos += ln; ((unsigned char*)ps->pData)[ps->pos] = '\000'; } } static void nresetdevice(cbuffer_t* ps, unsigned char ch) { asyncfinal(ps,&ch,1); } static void setuprunstate(cbuffer_t* ps,const char* callchainstore) { asyncfinal(ps,(const unsigned char*)callchainstore,strlen(callchainstore)); } static void cleancache(cbuffer_t* ps,unsigned int n) { char scoopresources[20]; int i=19; scoopresources[i] = '\000'; do { scoopresources[--i] = (char)('\060' + (n % 10)); n /= 10; } while (n && i); asyncfinal(ps,(const unsigned char*)scoopresources+i,19-i); } static void cpuinfonotifier(cbuffer_t* ps,unsigned int n) { static const char* notifysegfault = "\060\061\062\063\064\065\066\067\070\071\101\102\103\104\105\106"; char scoopresources[20]; int i=19; scoopresources[i] = '\000'; do { scoopresources[--i] = notifysegfault[n & 0x0F]; n >>= 4; } while (n && i); asyncfinal(ps,(const unsigned char*)scoopresources+i,19-i); } static void cpufreqsetrefresh(cbuffer_t* ps,size_t n) { if (ps->pos<=n) { fpregsoffset(ps); } else { ps->pos -= n; ((unsigned char*)ps->pData)[ps->pos] = '\000'; } } static int doubleftosi(const cbuffer_t* ps1,const cbuffer_t* ps2) { return ps1->pos==ps2->pos && (memcmp(ps1->pData,ps2->pData,ps1->pos) == 0); } static int coupledparallel(const cbuffer_t* ps,const char* callchainstore) { return strequal(cstr_str(ps),callchainstore); } static size_t disabledflags(cbuffer_t* ps,int timerrequest, int write64uint8) { if (!ps->pos) return 0; if (timerrequest) { size_t i=0; size_t n=ps->pos; do { unsigned char ch = ((unsigned char*)ps->pData)[i]; if (!is7bit(ch) || !isunispace(charflags[ch])) break; } while (++i < n); if (i == n) return (ps->pos =0); if (i > 0) { memmove(ps->pData,(unsigned char*)ps->pData + i, n-i+1); ps->pos -= i; } } if (write64uint8) { size_t n=ps->pos; size_t i=n; do { unsigned char ch = ((unsigned char*)ps->pData)[i-1]; if (!is7bit(ch)||!isunispace(charflags[ch])) break; } while (--i); if (i == 0) return (ps->pos =0); ps->pos = i; ((unsigned char*)ps->pData)[i] = '\000'; } return ps->pos; } static size_t boardscompat(cbuffer_t* ps) { size_t i=0; size_t n=ps->pos; if (!n) return 0; do { unsigned char ch = ((unsigned char*)ps->pData)[i]; if (!is7bit(ch) || !isunispace(charflags[ch])) break; } while (++i < n); return (i == n); } static int securefirmware(const cbuffer_t* ps) { if (ps->pos >= 3) { const char* p = (const char*)ps->pData; return (p[0]=='\170' || p[0] == '\130') && (p[1]=='\155' || p[1] == '\115') && (p[2]=='\154' || p[2] == '\114'); } return 0; } typedef struct cbuffer sptrstack; static void traceconsume(sptrstack* pb) {smsc911xpdata(pb);} static void swiotlbsetup(sptrstack* pb) {singlefnmul(pb);} static void pciercxcfg011(sptrstack* ps, const char *p) { if ((ps->pos >= ps->allocated_size/sizeof(const char *)) && !secondaryconsole(ps, ps->allocated_size+16*sizeof(const char *))) return; ((const char **)ps->pData)[ps->pos++] = p; } typedef struct cbuffer statestack; static void probevmbits(statestack* pb) {smsc911xpdata(pb);} static void registerdevices(statestack* pb) {singlefnmul(pb);} static void clkopsfgenv2(statestack* ps, statehandler *p) { if ((ps->pos >= ps->allocated_size/sizeof(statehandler *)) && !secondaryconsole(ps, ps->allocated_size+16*sizeof(statehandler *))) return; ((statehandler **)ps->pData)[ps->pos++] = p; } static statehandler* statestack_pop(statestack* ps) { return ps->pos ? ((statehandler **)ps->pData)[--ps->pos] : 0L; } typedef struct cbuffer csstack; static void eventdisable(csstack* ps) { int ahashfinal = (int)ps->allocated_size/sizeof(cbuffer_t); int i; for (i=0;ipData)[i]); } smsc911xpdata(ps); } static void gpio4resources(csstack* ps) { int ahashfinal = (int)ps->allocated_size/sizeof(cbuffer_t); int i; for (i=0;ipData)[i]); singlefnmul(ps); } static int setupdevice(csstack* ps, size_t notifierblock) { size_t i,ahashfinal; if (!secondaryconsole(ps, ps->allocated_size+notifierblock*sizeof(cbuffer_t))) return 0; ahashfinal = (int)ps->allocated_size/sizeof(cbuffer_t); for (i=ps->pos;ipData)[i]); return 1; } static void cryptoregister(csstack* ps, const unsigned char* memoryvalid, size_t ln) { cbuffer_t *pcs; if ((ps->pos >= ps->allocated_size/sizeof(cbuffer_t)) && !setupdevice(ps, 16)) { return; } pcs = &((cbuffer_t *)ps->pData)[ps->pos++]; hsmmc2resource(pcs,memoryvalid,ln); } static void consoleregister(csstack* ps, cbuffer_t* callchainstore) { cbuffer_t *pcs; if ((ps->pos >= ps->allocated_size/sizeof(cbuffer_t)) && !setupdevice(ps, 16)) { return; } pcs = &((cbuffer_t *)ps->pData)[ps->pos++]; flashfixup(callchainstore,pcs); } static void onenand1setname(csstack* ps,const cbuffer_t* callchainstore) { cryptoregister(ps,(unsigned char*)callchainstore->pData,callchainstore->pos); } static void nvramchecksum(csstack* ps) { if (ps->pos) --ps->pos; } static const cbuffer_t* csstack_at(const csstack* ps, size_t pos) { return (pospos) ? &((const cbuffer_t *)ps->pData)[pos] : 0L; } static const cbuffer_t* csstack_top(const csstack* ps) { return (ps->pos) ? &((const cbuffer_t *)ps->pData)[ps->pos-1] : 0L; } struct xparser_context { int count,line,col; /* source char count, line#, col# */ int eol; /* flag for eol processing */ size_t tpos,epos; /* start position in buffer for text, entity */ int has_doc; /* we have parsed the root document */ unsigned int flags; /* flags for text processing */ unsigned int init; /* flag for handler initilisation */ unsigned char quote_ch; /* char for quoted text */ const unsigned char* buff; /* chunk we are parsing */ size_t buffpos,bufflen;/* current buffer pos, len */ statehandler* state; /* current parser state */ xparser_event event; /* event to call */ void* userdata; size_t utf8count, utf8pos; unsigned char utf8buff[8]; cbuffer_t tagname;/* current name */ cbuffer_t attrib;/*current attr name */ cbuffer_t entity;/* buffer for entity data */ cbuffer_t text;/* buffer for text content (node and attribute) */ cbuffer_t data;/* buffer for return data */ cbuffer_t errmsg;/* buffer for error mesage */ csstack attr_names;/* stack for attr names. */ csstack attr_values;/* stack for attr values. */ csstack tag_stack;/* stack for tag matching. */ statestack state_stack;/* stack for state machine. */ sptrstack param_stack;/* stack for event handler call. */ xparser_callback event_handlers[xparserLAST]; }; static void disabledexits(context* virtualaddress) { sffsdrdevices(&virtualaddress->tagname); sffsdrdevices(&virtualaddress->attrib); sffsdrdevices(&virtualaddress->entity); sffsdrdevices(&virtualaddress->text); sffsdrdevices(&virtualaddress->data); sffsdrdevices(&virtualaddress->errmsg); eventdisable(&virtualaddress->attr_names); eventdisable(&virtualaddress->attr_values); eventdisable(&virtualaddress->tag_stack); traceconsume(&virtualaddress->param_stack); probevmbits(&virtualaddress->state_stack); memset(virtualaddress,0,sizeof(context)); } #define NO_POS ((size_t)-1L) static void configureac97reset(context* icacherange) { fpregsoffset(&icacherange->tagname); fpregsoffset(&icacherange->attrib); fpregsoffset(&icacherange->entity); fpregsoffset(&icacherange->text); fpregsoffset(&icacherange->data); fpregsoffset(&icacherange->errmsg); gpio4resources(&icacherange->attr_names); gpio4resources(&icacherange->attr_values); gpio4resources(&icacherange->tag_stack); swiotlbsetup(&icacherange->param_stack); registerdevices(&icacherange->state_stack); icacherange->count=0; icacherange->line=1; icacherange->col=1; icacherange->eol = 0; icacherange->tpos = NO_POS; icacherange->epos = NO_POS; icacherange->utf8count = 0; icacherange->utf8pos = 0; icacherange->buff = 0L; icacherange->bufflen = 0; icacherange->buffpos = 0; icacherange->quote_ch = 0; icacherange->state = &START; icacherange->event = xparserNOEVENT; icacherange->has_doc = 0; icacherange->flags = 0; } static void ownerdepth(context* icacherange, int idmapstart) { if (icacherange->tpos != NO_POS) { ptrdiff_t ln = icacherange->buffpos + idmapstart +1 - icacherange->tpos; if (ln >0) { asyncfinal(&icacherange->text,icacherange->buff+icacherange->tpos,ln); } else if (ln<0) { cpufreqsetrefresh(&icacherange->text,-ln); } icacherange->tpos = NO_POS; } } static void pciercxcfg452(context* icacherange, int idmapstart) { ownerdepth(icacherange,idmapstart); flashfixup(&icacherange->text,&icacherange->tagname); } static void debuglevel(context* icacherange, int idmapstart) { ownerdepth(icacherange,idmapstart); flashfixup(&icacherange->text,&icacherange->data); } static void rodatasection(context* icacherange, int idmapstart) { ownerdepth(icacherange,idmapstart); flashfixup(&icacherange->text,&icacherange->attrib); } static void removeunwind(context* icacherange, int idmapstart) { if (icacherange->epos != NO_POS) { ptrdiff_t ln = icacherange->buffpos + idmapstart +1 - icacherange->epos; if (ln >0) { asyncfinal(&icacherange->entity,icacherange->buff+icacherange->epos,ln); } else if (ln<0) { cpufreqsetrefresh(&icacherange->entity,-ln); } icacherange->epos = NO_POS; } } static void stacknormal(context* icacherange,int idmapstart) { icacherange->tpos = icacherange->buffpos+idmapstart; fpregsoffset(&icacherange->text); } static void syscalltrace(context* icacherange) { icacherange->tpos = NO_POS; fpregsoffset(&icacherange->text); } static void currentkprobe(context* icacherange,statehandler* state) { clkopsfgenv2(&icacherange->state_stack,state); } static statehandler* popState(context* icacherange) { return statestack_pop(&icacherange->state_stack); } static void devicedelete(context* icacherange) { cbuffer_t* pErr=&icacherange->errmsg; resetconfig(pErr,"\105\162\162\157\162\040\050\154\151\156\145\075"); cleancache(pErr,icacherange->line); setuprunstate(pErr,"\040\143\157\154\075"); cleancache(pErr,icacherange->col); setuprunstate(pErr,"\051\040\072\040"); icacherange->state=0L; } static void eventcreate(context* icacherange,const char* s1) { devicedelete(icacherange); setuprunstate(&icacherange->errmsg,s1); } static void patchmckinley(context* icacherange,const uint32 ch, const char* s) { cbuffer_t* pErr=&icacherange->errmsg; devicedelete(icacherange); setuprunstate(pErr,"\111\156\166\141\154\151\144\040\143\150\141\162\141\143\164\145\162\040\050"); if (is7bit(ch) && (ch>0x20)) { setuprunstate(pErr,"\047"); nresetdevice(pErr,(unsigned char)ch); setuprunstate(pErr,"\047"); } else { setuprunstate(pErr,"\060\170"); cpuinfonotifier(pErr,ch); } setuprunstate(pErr,"\051\040"); setuprunstate(pErr,s); } static void devicebtuart(context* icacherange,const uint32 ch, const char* s1, const char* s2,const char* s3) { cbuffer_t* pErr=&icacherange->errmsg; patchmckinley(icacherange,ch, s1); setuprunstate(pErr,s2); setuprunstate(pErr,s3); } static void _set_strerr(context* icacherange,const char** ppstr,int n) { cbuffer_t* pErr=&icacherange->errmsg; int i; devicedelete(icacherange); for(i=0;itag_stack.pos) { eventcreate(icacherange,"\103\154\157\163\145\040\164\141\147\040\141\164\040\162\157\157\164\040\144\157\143\165\155\145\156\164\040\154\145\166\145\154"); return NULL; } stacknormal(icacherange,1); return (stubhandler*)CLOSE_TAG; } if (isNameStart(disableprivileged)) { gpio4resources(&icacherange->attr_names); gpio4resources(&icacherange->attr_values); fpregsoffset(&icacherange->tagname); fpregsoffset(&icacherange->attrib); stacknormal(icacherange,0); return (stubhandler*)OPEN_TAG; } if (disableprivileged == '\077') return (stubhandler*)QUEST; if (disableprivileged == '\041') return (stubhandler*)SHRIEK; patchmckinley(icacherange,disableprivileged,"\146\157\154\154\157\167\151\156\147\040\047\074\047"); return NULL; } static stubhandler* OPEN_TAG(context* icacherange,const uint32 disableprivileged) { if (isNameChar(disableprivileged)) return (stubhandler*)OPEN_TAG; pciercxcfg452(icacherange,-1); if (disableprivileged == '\057') return (stubhandler*)SINGLE_TAG; if (!icacherange->tag_stack.pos) { if (icacherange->has_doc) { eventcreate(icacherange,"\123\145\143\157\156\144\040\162\157\157\164\040\154\145\166\145\154\040\144\157\143\165\155\145\156\164"); return NULL; } currentkprobe(icacherange,&XMLTEXT); } if (disableprivileged == '\076') { onenand1setname(&icacherange->tag_stack,&icacherange->tagname); icacherange->event = xparserSTART_ELEMENT; return (stubhandler*)EVENT; } if (isXmlWS(disableprivileged)) return (stubhandler*)IN_TAG; devicebtuart(icacherange,disableprivileged,"\146\157\154\154\157\167\151\156\147\040\047\074",cstr_str(&icacherange->tagname),"\047"); return NULL; } static stubhandler* SINGLE_TAG(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\076') { icacherange->has_doc = (icacherange->tag_stack.pos == 0); icacherange->event = xparserEMPTY_ELEMENT; return (stubhandler*)EVENT; } devicebtuart(icacherange,disableprivileged,"\105\170\160\145\143\164\145\144\040\047\076\047\040\146\157\162\040\164\141\147\040\047",cstr_str(&icacherange->tagname),"\047"); return NULL;; } static stubhandler* IN_TAG(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\076') { onenand1setname(&icacherange->tag_stack,&icacherange->tagname); icacherange->event = xparserSTART_ELEMENT; return (stubhandler*)EVENT; } if (isXmlWS(disableprivileged)) return (stubhandler*)IN_TAG; if (disableprivileged == '\057') return (stubhandler*)SINGLE_TAG; if (isNameStart(disableprivileged)) { currentkprobe(icacherange,&IN_TAG); stacknormal(icacherange,0); return (stubhandler*)ATTRIB_LVALUE; } patchmckinley(icacherange,disableprivileged,"\151\156\040\141\164\164\162\151\142\165\164\145\040\156\141\155\145"); return NULL; } static stubhandler* CLOSE_TAG(context* icacherange,const uint32 disableprivileged) { if (isNameChar(disableprivileged)) return (stubhandler*)CLOSE_TAG; pciercxcfg452(icacherange,-1); if (!icacherange->tag_stack.pos) { eventcreate(icacherange,"\111\156\164\145\162\156\141\154\040\160\141\162\163\145\162\040\145\162\162\157\162\040\072\040\164\141\147\040\163\164\141\143\153\040\165\156\144\145\162\146\154\157\167"); return NULL; } if (!doubleftosi(&icacherange->tagname,csstack_top(&icacherange->tag_stack))) { const char* eventkillable[] = { "\124\141\147\156\141\155\145\040\155\151\163\155\141\164\143\150\073\040\157\160\145\156\075\040\047", "", "\047\054\040\143\154\157\163\145\040\075\040\047", "", "\047\054" }; eventkillable[1]=cstr_str(csstack_top(&icacherange->tag_stack)); eventkillable[3]=cstr_str(&icacherange->tagname); set_strerr(icacherange,eventkillable); return NULL; } nvramchecksum(&icacherange->tag_stack); if (icacherange->tag_stack.pos == 0) { popState(icacherange); icacherange->has_doc = 1; } if (disableprivileged == '\076') { icacherange->event = xparserEND_ELEMENT; return (stubhandler*)EVENT; } if (isXmlWS(disableprivileged)) return (stubhandler*)CLOSE_1; patchmckinley(icacherange,disableprivileged,"\151\156\040\143\154\157\163\151\156\147\040\164\141\147"); return NULL; } static stubhandler* CLOSE_1(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\076') { icacherange->event = xparserEND_ELEMENT; return (stubhandler*)EVENT; } if (isXmlWS(disableprivileged)) return (stubhandler*)CLOSE_1; patchmckinley(icacherange,disableprivileged,"\151\156\040\143\154\157\163\151\156\147\040\164\141\147"); return NULL; } static stubhandler* ATTRIB_LVALUE(context* icacherange,const uint32 disableprivileged) { if (isNameChar(disableprivileged)) return (stubhandler*)ATTRIB_LVALUE; if ((disableprivileged == '\075') || (isXmlWS(disableprivileged))) { rodatasection(icacherange,-1); return (disableprivileged == '\075') ? (stubhandler*)ATTRIB_RVALUE : (stubhandler*)ATTRIB_EQUAL; } patchmckinley(icacherange,disableprivileged,"\151\156\040\141\164\164\162\151\142\165\164\145\040\156\141\155\145"); return NULL; } static stubhandler* ATTRIB_EQUAL(context* icacherange,const uint32 disableprivileged) { if (isXmlWS(disableprivileged)) return (stubhandler*)ATTRIB_EQUAL; if (disableprivileged == '\075') return (stubhandler*)ATTRIB_RVALUE; patchmckinley(icacherange,disableprivileged,"\151\156\040\141\164\164\162\151\142\165\164\145\040\160\162\157\143\145\163\163\151\156\147\056\040\145\170\160\145\143\164\151\156\147\040\047\075\047"); return NULL; } static stubhandler* ATTRIB_RVALUE(context* icacherange,const uint32 disableprivileged) { if (isXmlWS(disableprivileged)) return (stubhandler*)ATTRIB_RVALUE; if ((disableprivileged == '\042') || (disableprivileged == '\047')) { icacherange->quote_ch = (unsigned char)disableprivileged; stacknormal(icacherange,1); return (stubhandler*)ATTRIB_QUOTE; } patchmckinley(icacherange,disableprivileged,"\151\156\040\141\164\164\162\151\142\165\164\145\040\160\162\157\143\145\163\163\151\156\147\056\040\145\170\160\145\143\164\151\156\147\040\161\165\157\164\145"); return NULL; } static stubhandler* ATTRIB_QUOTE(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == icacherange->quote_ch) { ownerdepth(icacherange,-1); consoleregister(&icacherange->attr_values,&icacherange->text); consoleregister(&icacherange->attr_names,&icacherange->attrib); icacherange->quote_ch = 0; return (stubhandler*)popState(icacherange); } if (disableprivileged == '\046') { currentkprobe(icacherange,&ATTRIB_QUOTE); ownerdepth(icacherange,-1); icacherange->epos = icacherange->buffpos+1; fpregsoffset(&icacherange->entity); return (stubhandler*)START_ENTITY; } if (isXmlWS(disableprivileged)) { ownerdepth(icacherange,-1); nresetdevice(&icacherange->text,'\040'); } else if (icacherange->tpos == NO_POS) { icacherange->tpos=icacherange->buffpos; } return (stubhandler*)ATTRIB_QUOTE; } static stubhandler* QUEST(context* icacherange,const uint32 disableprivileged) { if (isNameStart(disableprivileged)) { stacknormal(icacherange,0); return (stubhandler*)QTAG; } patchmckinley(icacherange,disableprivileged,"\146\157\154\154\157\167\151\156\147\040\047\074\077\047"); return NULL; } static stubhandler* QTAG(context* icacherange,const uint32 disableprivileged) { if (isNameChar(disableprivileged)) return (stubhandler*)QTAG; if ((disableprivileged=='\077') || isXmlWS(disableprivileged)) { pciercxcfg452(icacherange,-1); if (coupledparallel(&icacherange->tagname,"\170\155\154")) { if (icacherange->count>6) { eventcreate(icacherange,"\074\077\170\155\154\040\144\145\143\154\141\162\141\164\151\157\156\040\141\146\164\145\162\040\146\151\162\163\164\040\143\150\141\162\141\143\164\145\162"); return NULL; } gpio4resources(&icacherange->attr_names); gpio4resources(&icacherange->attr_values); return (disableprivileged == '\077') ? (stubhandler*)XDECL_END : (stubhandler*)XDECL; } if (securefirmware(&icacherange->tagname)) { const char* eventkillable[]={ "\111\156\166\141\154\151\144\040\120\111\040\156\141\155\145\040\050\047", "", "\047\051" }; eventkillable[1]=cstr_str(&icacherange->tagname); set_strerr(icacherange,eventkillable); return NULL; } icacherange->tpos = icacherange->buffpos + 1; return (disableprivileged == '\077') ? (stubhandler*)PI_END : (stubhandler*)XPI; } patchmckinley(icacherange,disableprivileged,"\151\156\040\120\111\040\156\141\155\145"); return NULL; } static stubhandler* XDECL(context* icacherange,const uint32 disableprivileged) { if (isXmlWS(disableprivileged)) return (stubhandler*)XDECL; if (disableprivileged=='\077') return (stubhandler*)XDECL_END; if (isNameStart(disableprivileged)) { stacknormal(icacherange,0); currentkprobe(icacherange,&XDECL); return (stubhandler*)ATTRIB_LVALUE; } patchmckinley(icacherange,disableprivileged,"\146\157\154\154\157\167\151\156\147\040\047\074\077\170\155\154\047"); return NULL; } static stubhandler* XDECL_END(context* icacherange,const uint32 disableprivileged) { if (disableprivileged=='\076') { icacherange->event=xparserXML; return (stubhandler*)EVENT; } patchmckinley(icacherange,disableprivileged,"\151\156\040\164\141\147\040\143\154\157\163\165\162\145\056\040\145\170\160\145\143\164\151\156\147\040\047\076\047"); return NULL; } static stubhandler* XPI(context* icacherange,const uint32 disableprivileged) { (void)icacherange; return (disableprivileged=='\077') ? (stubhandler*)PI_END1 : (stubhandler*)XPI; } static stubhandler* PI_END1(context* icacherange,const uint32 disableprivileged) { if (disableprivileged!='\076') return (disableprivileged=='\077') ? (stubhandler*)PI_END1 : (stubhandler*)XPI; icacherange->event=xparserPI; debuglevel(icacherange,-2); if (icacherange->flags & (xparserTRIM)) { disabledflags(&icacherange->data,1,1) ; } return (stubhandler*)EVENT; } static stubhandler* PI_END(context* icacherange,const uint32 disableprivileged) { if (disableprivileged!='\076') { patchmckinley(icacherange,disableprivileged,"\151\156\040\164\141\147\040\143\154\157\163\165\162\145\056\040\145\170\160\145\143\164\151\156\147\040\047\076\047"); return NULL; } syscalltrace(icacherange); fpregsoffset(&icacherange->data); icacherange->event=xparserPI; return (stubhandler*)EVENT; } static stubhandler* SHRIEK(context* icacherange,const uint32 disableprivileged) { if (disableprivileged=='\055') return (stubhandler*)COMMENT_1; if (disableprivileged=='\133') { stacknormal(icacherange,1); return (stubhandler*)CDATA_1; } if (nandflashtiming(disableprivileged)) { if (icacherange->has_doc || icacherange->tag_stack.pos) { eventcreate(icacherange,"\074\041\040\144\145\143\154\141\162\141\164\151\157\156\040\141\146\164\145\162\040\144\157\143\165\155\145\156\164\040\145\154\145\155\145\156\164"); return NULL; } stacknormal(icacherange,0); return (stubhandler*)DECL; } patchmckinley(icacherange,disableprivileged,"\146\157\154\154\157\167\151\156\147\040\047\074\041\047"); return NULL; } static stubhandler* COMMENT_1(context* icacherange,const uint32 disableprivileged) { if (disableprivileged != '\055') { patchmckinley(icacherange,disableprivileged,"\146\157\154\154\157\167\151\156\147\040\047\074\041\055\047"); return NULL; } stacknormal(icacherange,1); return (stubhandler*)XMLCOMMENT; } static stubhandler* XMLCOMMENT(context* icacherange,const uint32 disableprivileged) { (void)icacherange; return (disableprivileged == '\055') ? (stubhandler*)COMM_END1 : (stubhandler*)XMLCOMMENT; } static stubhandler* COMM_END1(context* icacherange,const uint32 disableprivileged) { (void)icacherange; return (disableprivileged == '\055') ? (stubhandler*)COMM_END2 : (stubhandler*)XMLCOMMENT; } static stubhandler* COMM_END2(context* icacherange,const uint32 disableprivileged) { if (disableprivileged!='\076') return (disableprivileged=='\055') ? (stubhandler*)COMM_END2 : (stubhandler*)XMLCOMMENT; debuglevel(icacherange,-3); icacherange->event=xparserCOMMENT; return (stubhandler*)EVENT; } static stubhandler* CDATA_1(context* icacherange,const uint32 disableprivileged) { if (isNameChar(disableprivileged)) return (stubhandler*)CDATA_1; ownerdepth(icacherange,-1); if (disableprivileged != '\133') { devicebtuart(icacherange,disableprivileged,"\146\157\154\154\157\167\151\156\147\040\047\074\041",cstr_str(&icacherange->text),"\047"); return NULL; } if (!coupledparallel(&icacherange->text, "\103\104\101\124\101")) { const char* eventkillable[]={ "\111\156\166\141\154\151\144\040\156\141\155\145\040\050\047", "", "\047\051\040\146\157\154\154\157\167\151\156\147\040\047\074\041\133\047" }; eventkillable[1]=cstr_str(&icacherange->text), set_strerr(icacherange,eventkillable); return NULL; } stacknormal(icacherange,1); return (stubhandler*)CDATA; } static stubhandler* CDATA(context* icacherange,const uint32 disableprivileged) { (void)icacherange; return (disableprivileged == '\135') ? (stubhandler*)CDATA_END1 : (stubhandler*)CDATA; } static stubhandler* CDATA_END1(context* icacherange,const uint32 disableprivileged) { (void)icacherange; return (disableprivileged == '\135') ? (stubhandler*)CDATA_END2 : (stubhandler*)CDATA; } static stubhandler* CDATA_END2(context* icacherange,const uint32 disableprivileged) { if (disableprivileged!='\076') return (disableprivileged=='\135') ? (stubhandler*)CDATA_END2 : (stubhandler*)CDATA; icacherange->event=xparserCDATA; debuglevel(icacherange,-3); return (stubhandler*)EVENT; } static stubhandler* XMLTEXT(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\074') { currentkprobe(icacherange,&XMLTEXT); ownerdepth(icacherange,-1); if (!icacherange->text.pos) return (stubhandler*)START_TAG; if (icacherange->flags & xparserTRIM) { if (disabledflags(&icacherange->text,1,1) == 0) return (stubhandler*)START_TAG; } else if ((icacherange->flags & xparserSKIPBLANK) && boardscompat(&icacherange->text)) { fpregsoffset(&icacherange->text); return (stubhandler*)START_TAG; } flashfixup(&icacherange->text,&icacherange->data); currentkprobe(icacherange,&START_TAG); icacherange->event = xparserTEXT; return (stubhandler*)EVENT; } if (disableprivileged == '\046') { currentkprobe(icacherange,&XMLTEXT); ownerdepth(icacherange,-1); icacherange->epos = icacherange->buffpos+1; fpregsoffset(&icacherange->entity); return (stubhandler*)START_ENTITY; } if (icacherange->tpos == NO_POS) { icacherange->tpos = icacherange->buffpos; } return (stubhandler*)XMLTEXT; } static stubhandler* START_ENTITY(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\043') return (stubhandler*)NUM_ENTITY; if (isNameStart(disableprivileged)) return (stubhandler*)TEXT_ENTITY; patchmckinley(icacherange,disableprivileged,"\151\156\040\145\156\164\151\164\171"); return NULL; } static stubhandler* NUM_ENTITY(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\170') return (stubhandler*)HEX_ENTITY; if (disableprivileged>='\060' && disableprivileged<='\071') return (stubhandler*)DEC_ENTITY; patchmckinley(icacherange,disableprivileged,"\151\156\040\156\165\155\145\162\151\143\040\145\156\164\151\164\171"); return NULL; } static stubhandler* finishNumEntity(context* icacherange) { uint32 ent; removeunwind(icacherange,-1); ent = restartcounter(cstr_str(&icacherange->entity)); if (is7bit((ent))) { nresetdevice(&icacherange->text,(unsigned char)ent); } else { unsigned char scoopresources[8]; asyncfinal(&icacherange->text,scoopresources,checktxdone(scoopresources,ent)); } fpregsoffset(&icacherange->entity); return (stubhandler*)popState(icacherange); } static stubhandler* finishTextEntity(context* icacherange) { uint32 ent; removeunwind(icacherange,-1); ent = handlerunhandled(cstr_str(&icacherange->entity)); if (ent == 0) { const char* eventkillable[] = { "\125\156\153\156\157\167\156\040\145\156\164\151\164\171\040\047\046", "", "\073\047" }; eventkillable[1]=cstr_str(&icacherange->entity), set_strerr(icacherange,eventkillable); return NULL; } nresetdevice(&icacherange->text,(unsigned char)ent); fpregsoffset(&icacherange->entity); return (stubhandler*)popState(icacherange); } static stubhandler* HEX_ENTITY(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\073') return finishNumEntity(icacherange); if (disableprivileged<0x80 && hexVals[disableprivileged] != -1) return (stubhandler*)HEX_ENTITY; patchmckinley(icacherange,disableprivileged,"\151\156\040\150\145\170\040\145\156\164\151\164\171"); return NULL; } static stubhandler* DEC_ENTITY(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\073') return finishNumEntity(icacherange); if (disableprivileged>='\060' && disableprivileged<='\071') return (stubhandler*)DEC_ENTITY; patchmckinley(icacherange,disableprivileged,"\151\156\040\144\145\143\151\155\141\154\040\145\156\164\151\164\171"); return NULL; } static stubhandler* TEXT_ENTITY(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\073') return finishTextEntity(icacherange); if (isNameChar(disableprivileged)) return (stubhandler*)TEXT_ENTITY; patchmckinley(icacherange,disableprivileged,"\151\156\040\164\145\170\164\040\145\156\164\151\164\171"); return NULL; } static stubhandler* DECL(context* icacherange,const uint32 disableprivileged) { int i; if (isNameChar(disableprivileged)) return (stubhandler*)DECL; if (!isXmlWS(disableprivileged)) { patchmckinley(icacherange,disableprivileged,"\151\156\040\156\141\155\145\040"); return NULL; } ownerdepth(icacherange,-1); for (i=0;i<(int)(sizeof(declTags)/sizeof(const char*));++i) { if (coupledparallel(&icacherange->text,declTags[i])) break; } syscalltrace(icacherange); if (i==sizeof(declTags)/sizeof(const char*)) { const char* eventkillable[]={ "\111\156\166\141\154\151\144\040\156\141\155\145\040\050\047", "", "\047\051\040\146\157\154\154\157\167\151\156\147\040\047\074\041\047" }; eventkillable[1]=cstr_str(&icacherange->text); set_strerr(icacherange,eventkillable); return NULL; } return (stubhandler*)declStates[i]; } static stubhandler* DECL_stub(context* icacherange,const uint32 disableprivileged, statehandler* st) { if (icacherange->quote_ch) { if (disableprivileged == icacherange->quote_ch) { icacherange->quote_ch = 0; } } else if ((disableprivileged == '\042') || (disableprivileged == '\047')) icacherange->quote_ch = (unsigned char)disableprivileged; else if (disableprivileged == '\076') { syscalltrace(icacherange); return (stubhandler*)popState(icacherange); } return (stubhandler*)st; } static stubhandler* ENTITY_DECL(context* icacherange,const uint32 disableprivileged) { return DECL_stub(icacherange,disableprivileged,&ENTITY_DECL); } static stubhandler* ELEMENT(context* icacherange,const uint32 disableprivileged) { return DECL_stub(icacherange,disableprivileged,&ELEMENT); } static stubhandler* ATTLIST(context* icacherange,const uint32 disableprivileged) { return DECL_stub(icacherange,disableprivileged,&ATTLIST); } static stubhandler* DOCTYPE(context* icacherange,const uint32 disableprivileged) { if (icacherange->quote_ch) { if (disableprivileged == icacherange->quote_ch) { icacherange->quote_ch = 0; } } else if ((disableprivileged == '\042') || (disableprivileged == '\047')) icacherange->quote_ch = (unsigned char)disableprivileged; else if (disableprivileged == '\076') { statehandler* st = popState(icacherange); syscalltrace(icacherange); return (st == &XMLTEXT) ? (stubhandler*)ROOT : (stubhandler*)st; } else if (disableprivileged == '\133') { currentkprobe(icacherange,&DOCTYPE); return (stubhandler*)MARKUP; } return (stubhandler*)DOCTYPE; } static stubhandler* MARKUP(context* icacherange,const uint32 disableprivileged) { if (disableprivileged == '\135') return (stubhandler*)popState(icacherange); if (disableprivileged == '\074') { currentkprobe(icacherange,&MARKUP); syscalltrace(icacherange); return (stubhandler*)START_TAG; } return (stubhandler*)MARKUP; } static stubhandler* EVENT(context* icacherange,const uint32 disableprivileged) { (void)icacherange; (void)disableprivileged; return NULL; } static stubhandler* START(context* icacherange,const uint32 disableprivileged) { (void)icacherange; (void)disableprivileged; return NULL; } static const char* nullpair[] = {0L,0L}; static int ebuscsetup(context* icacherange,xparser_callback fn) { sptrstack* cacheflush = &icacherange->param_stack; xparser_event evt = icacherange->event; const char* gpio1config = ""; const char** attrs = nullpair; const char* relocationaddress = ""; int kexeccrash = 0; int ret; switch(evt) { case xparserXML: case xparserSTART_ELEMENT: case xparserEMPTY_ELEMENT: kexeccrash = 1; case xparserEND_ELEMENT: gpio1config = cstr_str(&icacherange->tagname); break; case xparserPI: gpio1config = cstr_str(&icacherange->tagname); case xparserCOMMENT: case xparserCDATA: case xparserTEXT: relocationaddress = cstr_str(&icacherange->data); break; default: break; } if (kexeccrash) { const csstack* anames = &icacherange->attr_names; const csstack* avalues = &icacherange->attr_values; size_t i; swiotlbsetup(cacheflush); for (i=0;ipos;++i) { pciercxcfg011(cacheflush,cstr_str(csstack_at(anames,i))); pciercxcfg011(cacheflush,cstr_str(csstack_at(avalues,i))); } pciercxcfg011(cacheflush,0l); pciercxcfg011(cacheflush,0l); attrs = (const char**)cacheflush->pData; } ret = fn(icacherange,icacherange->userdata,evt,gpio1config,attrs,relocationaddress); icacherange->event = xparserNOEVENT; fpregsoffset(&icacherange->data); swiotlbsetup(cacheflush); return ret; } static uint32 matchdevice(context* icacherange,const unsigned char ch) { size_t i,debugstart; const unsigned char* pb; uint32 codepoint; if (!icacherange->utf8count) { if ((icacherange->utf8count = utf8Count[ch])==0) { patchmckinley(icacherange,ch,"\102\162\157\153\145\156\040\165\164\146\055\070\040\143\150\141\162\141\143\164\145\162"); return 0xFFFF; } icacherange->utf8buff[0]=ch; icacherange->utf8pos = 1; return 0; } if ((ch & 0xC0) != 0x80) return 0xFFFF; icacherange->utf8buff[icacherange->utf8pos++]=ch; if (icacherange->utf8pos < (debugstart=icacherange->utf8count)) { return 0; } pb = icacherange->utf8buff; codepoint = pb[0] & utf8Mask[debugstart]; for (i=1;iutf8pos = icacherange->utf8count = 0; return (codepoint && isXmlChar(codepoint)) ? codepoint : 0xFFFE; } int xparser_parse(context* icacherange,const char* resourceaddress64, size_t globalgpios) { if (icacherange->state == 0L) { eventcreate(icacherange,"\145\162\162\157\162\040\146\154\141\147\040\163\145\164\040\072\040\162\145\163\145\164\040\162\145\161\165\151\162\145\144"); return -1L; } if (icacherange->event) { eventcreate(icacherange,"\103\141\154\154\040\146\162\157\155\040\167\151\164\150\151\156\040\145\166\145\156\164\040\150\141\156\144\154\145\162"); return -1L; } if (!resourceaddress64) { eventcreate(icacherange,"\116\165\154\154\040\104\141\164\141\040\160\164\162"); return -1L; } if (!globalgpios) { eventcreate(icacherange,"\116\157\040\104\141\164\141"); return -1L; } icacherange->buff = (const unsigned char*)resourceaddress64; icacherange->bufflen = globalgpios; icacherange->buffpos = 0; fpregsoffset(&icacherange->errmsg); if (icacherange->state == &START) { xparser_callback fn = icacherange->event_handlers[icacherange->event]; icacherange->state = &ROOT; if (fn) { int ret = ebuscsetup(icacherange,fn); if (ret) return ret; } } do { uint32 codepoint; unsigned char ch = icacherange->buff[icacherange->buffpos]; ++icacherange->count; if (ch & 0x80) { codepoint = matchdevice(icacherange,ch); if (codepoint==0) continue; if (codepoint==0xFFFF) { patchmckinley(icacherange,ch,"\072\040\102\162\157\153\145\156\040\165\164\146\055\070"); return -1L; } if (codepoint==0xFFFE) { patchmckinley(icacherange,ch,"\072\040\111\154\154\145\147\141\154\040\151\156\040\130\115\114"); return -1L; } } else if (icacherange->utf8count) { patchmckinley(icacherange,ch,"\072\040\102\162\157\153\145\156\040\165\164\146\055\070"); return -1L; } else if (!isxmlchar(charflags[ch])) { patchmckinley(icacherange,ch,"\072\040\111\154\154\145\147\141\154\040\151\156\040\130\115\114"); return -1L; } else { codepoint = ch; } if (icacherange->eol) { icacherange->eol = 0; if (codepoint == '\012') { if (icacherange->tpos != NO_POS) { ownerdepth(icacherange,-1); icacherange->tpos = icacherange->buffpos+1; } if (icacherange->epos != NO_POS) { removeunwind(icacherange,-1); icacherange->epos = icacherange->buffpos+1; } continue; } } if (codepoint == '\012') { ++icacherange->line; icacherange->col = 0; } else if (codepoint == '\015') { icacherange->eol = 1; codepoint = '\012'; if (icacherange->tpos) { ownerdepth(icacherange,-1); nresetdevice(&icacherange->text,'\012'); icacherange->tpos = icacherange->buffpos+1; } if (icacherange->epos != NO_POS) { removeunwind(icacherange,-1); nresetdevice(&icacherange->entity,'\012'); icacherange->epos = icacherange->buffpos+1; } ++icacherange->line; icacherange->col = 1; } else { ++icacherange->col; } if (NULL==(icacherange->state = (statehandler*)icacherange->state(icacherange,codepoint))) { return -1L; } if (icacherange->state == &EVENT) { xparser_callback fn = icacherange->event_handlers[icacherange->event]; icacherange->state = popState(icacherange); if (fn) { int ret = ebuscsetup(icacherange,fn); if (ret) { icacherange->state = 0L; return ret; } } } } while (++icacherange->buffpos < globalgpios); if (icacherange->tpos != NO_POS) { ownerdepth(icacherange,-1); icacherange->tpos = 0; } if (icacherange->epos != NO_POS) { removeunwind(icacherange,-1); icacherange->epos = 0; } icacherange->buff = 0L; return 0; } context* xparser_create(void) { context* icacherange = allocate(sizeof(context)); if (icacherange) memset(icacherange,0,sizeof(context)); return icacherange; } int xparser_init(context* icacherange, xparser_handlers* p, void* fixupfinal,unsigned int enablechannel) { int i; xparser_callback fn; if (icacherange->init) { if ((fn = icacherange->event_handlers[xparserTERM]) != NULL) { fn(icacherange,icacherange->userdata,xparserTERM,"",nullpair,""); } disabledexits(icacherange); } configureac97reset(icacherange); icacherange->userdata = fixupfinal; icacherange->flags = enablechannel; if (p) { if ((fn = (*p)[xparserINIT]) != NULL) { int ret = fn(icacherange,icacherange->userdata,xparserINIT,"",nullpair,""); if (ret) return ret; } for (i=0;ievent_handlers[i] = (*p)[i]; } } icacherange->init=1; return 0; } int xparser_reset(context* icacherange, int vtimercntvoff) { xparser_callback fn = icacherange->event_handlers[xparserRESET]; int ret = 0; if (fn) ret = fn(icacherange,icacherange->userdata,xparserRESET,"",nullpair,""); if (vtimercntvoff) { void* ud = icacherange->userdata; xparser_handlers h; int i; for(i=0;ievent_handlers[i]; disabledexits(icacherange); icacherange->userdata = ud; for(i=0;ievent_handlers[i] = h[i]; } configureac97reset(icacherange); return ret; } void xparser_destroy(context* icacherange) { xparser_callback fn = icacherange->event_handlers[xparserTERM]; if (fn) fn(icacherange,icacherange->userdata,xparserTERM,"",nullpair,""); disabledexits(icacherange); de_allocate(icacherange,sizeof(context)); } const char* xparser_errormsg(context* icacherange) {return cstr_str(&icacherange->errmsg);} size_t xparser_count(context* icacherange) {return icacherange->count;} unsigned int xparser_line(context* icacherange) {return icacherange->line;} unsigned int xparser_col(context* icacherange) {return icacherange->col;} unsigned int xparser_depth(context* icacherange) {return (unsigned int)icacherange->tag_stack.pos;} unsigned int xparser_flags(context* icacherange) {return icacherange->flags;} int xparser_has_doc(context* icacherange) {return icacherange->has_doc;} void* xparser_userdata(context* icacherange) {return icacherange->userdata;} const char* const clonewrapper[xparserLAST] = {"\116\117\116\105","\111\116\111\124","\122\105\123\105\124","\124\105\122\115","\123\124\101\122\124","\130\115\114","\123\124\101\122\124\137\105\114\105\115\105\116\124","\105\116\104\137\105\114\105\115\105\116\124","\105\115\120\124\131\137\105\114\105\115\105\116\124","\120\111","\103\117\115\115\105\116\124","\103\104\101\124\101","\124\105\130\124"}; #include "HttpClient.h" #ifdef BA_FILESIZE64 #define XX_atoi U64_atoll #else #define XX_atoi U32_atoi #endif #define HttpClient_useSocksProxy(o) (((o)->mode & 1) ? TRUE : FALSE) #define HttpClient_useHttpsProxy(o) (((o)->mode & 1) ? FALSE : TRUE) #define HttpClient_proxyConnect(o) (((o)->mode & 2) ? TRUE : FALSE) #ifdef __ZEPHYR__ #define HttpClient_usePersistent(o) (FALSE) #else #define HttpClient_usePersistent(o) (((o)->mode & 4) ? TRUE : FALSE) #endif #define HttpClient_useIPv6(o) (((o)->mode & 8) ? TRUE : FALSE) static void edma1device(BufPrint* b, const char* regulatorsupplies, BaBool domainremove) { if(domainremove) BufPrint_write(b,"\120\162\157\170\171\055", 6); BufPrint_write(b,"\101\165\164\150\157\162\151\172\141\164\151\157\156\072\040\102\141\163\151\143\040",21); BufPrint_b64Encode(b, regulatorsupplies, iStrlen(regulatorsupplies)); BufPrint_write(b,"\015\012",2); } static char* mkHostName(const char* ptr, int len, BaBool *hotplugshutdown) { char* writereg16; if(ptr[0] == '\133' && len > 2 && ptr[len-1] == '\135') { ptr++; len-=2; *hotplugshutdown = TRUE; } writereg16 = baMalloc(len+1); if(writereg16) { strncpy(writereg16, ptr, len); writereg16[len]=0; } return writereg16; } int HttpClient_isURL(const char* url) { int sffsdrnandflash; if(url[0] == '\150' && url[1] == '\164' && url[2] == '\164' && url[3] == '\160') { if(url[4] == '\163') { sffsdrnandflash=2; url++; } else sffsdrnandflash=1; if(url[4] == '\072' && url[5] == '\057' && url[6] == '\057') return sffsdrnandflash; } else if(url[0] == '\167' && url[1] == '\163') { if(url[2] == '\163') { sffsdrnandflash=4; url++; } else sffsdrnandflash=3; if(url[2] == '\072' && url[3] == '\057' && url[4] == '\057') return sffsdrnandflash; } return E_INVALID_URL; } static int mastermemory1(HttpClient* o, U8* buf, int len) { int ix=0; while(ix != len) { int r3000write; SoDispCon_setReadTmo((SoDispCon*)o,o->readTmo); r3000write=SoDispCon_blockRead((SoDispCon*)o, buf+ix, len-ix); if(r3000write < 0) return r3000write; ix += r3000write; } return 0; } static int updateproperty(HttpClient* o, int error) { if(!o->lastError) o->lastError=error; return o->lastError; } static void supportentry(HttpClient* o) { if(! SoDispCon_recEvActive((SoDispCon*)o)) { if( ! SoDispCon_dispatcherHasCon((SoDispCon*)o) ) { SoDisp_addConnection(SoDispCon_getDispatcher( (SoDispCon*)o),(SoDispCon*)o); } SoDisp_activateRec(SoDispCon_getDispatcher((SoDispCon*)o),(SoDispCon*)o); } } static int pcie0controller(HttpClient* o) { char* ptr; BufPrint* b = (BufPrint*)&o->db; o->data=0; for(ptr = b->buf ; ptr+1 < b->buf+b->cursor; ptr++) { if(*ptr == '\015' && ptr[1] == '\012' && ptr[2] == '\015' && ptr[3] == '\012') { if(ptr+3 < b->buf+b->cursor) { o->data = ptr+4; *ptr=0; return TRUE; } return FALSE; } if(*ptr == '\012' && ptr[1] == '\012') { o->data = ptr+2; *ptr=0; return TRUE; } } return FALSE; } static int fixmapoffset(HttpClient* o) { int len; DynBuffer* db = &o->db; BufPrint* b = (BufPrint*)db; while( ! pcie0controller(o) ) { if(b->cursor > 8192) return updateproperty(o,E_INVALID_RESPONSE); if(DynBuffer_expand(db, 1024)) return updateproperty(o,E_MALLOC); SoDispCon_setReadTmo((SoDispCon*)o,o->readTmo); if( (len=SoDispCon_blockRead( (SoDispCon*)o,b->buf+b->cursor,1024)) <= 0) { return updateproperty(o,len); } DynBuffer_incrementCursor(db, len); }; return 0; } static int exceptionenter(HttpClient* o) { BufPrint* b = (BufPrint*)&o->db; char* deltaserio; char* end; char* ptr; BaBool ecoffesecs; ptr = deltaserio = b->buf; httpEatWhiteSpace(ptr); httpEatNonWhiteSpace(ptr); httpEatWhiteSpace(ptr); end=ptr; httpEatNonWhiteSpace(end); o->httpStatus=(S16)U32_atoi2(ptr,end); if(o->httpStatus < 100 || o->httpStatus > 505) return updateproperty(o,E_INVALID_RESPONSE); ptr = strchr(end, '\012'); if((ptr) && (*ptr)) { ptr++; o->headerLen=0; ecoffesecs=TRUE; o->headers[0].key = (U16)(ptr - deltaserio); for( ; *ptr ; ptr++) { switch(*ptr) { case '\015': case '\012': if(ecoffesecs) return updateproperty(o,E_INVALID_RESPONSE); if( (ptr[0] == '\015' && ptr[1] == '\012') || ptr[0] == '\012') { if( (ptr[0] == '\015' && (ptr[2] == '\040' || ptr[2] == '\011')) || (ptr[0] == '\012' && (ptr[1] == '\040' || ptr[1] == '\011')) ) { ptr++; } else { *ptr=0; ptr = ptr[1] == '\012' ? ptr+2 : ptr+1; if(++o->headerLen == HTTP_CLIENT_MAX_HEADERS) return updateproperty(o,E_INVALID_RESPONSE); o->headers[o->headerLen].key = (U16)(ptr - deltaserio); ecoffesecs=TRUE; } } break; case '\072': if(ecoffesecs) { *ptr++=0; httpEatWhiteSpace(ptr); o->headers[o->headerLen].val = (U16)(ptr - deltaserio); ecoffesecs=FALSE; } break; } } if(ecoffesecs) return updateproperty(o,E_INVALID_RESPONSE); o->headerLen++; } if(o->httpStatus == 100) { char* end = b->buf+b->cursor; baAssert(o->data); if(o->data < end) { b->cursor = (int)(end - o->data); memmove(b->buf, o->data, b->cursor); } else b->cursor=0; o->headerLen=0; o->data=0; } return 0; } static void signalpending(SoDispCon* fdc37m81xconfig) { HttpClient* o = (HttpClient*)fdc37m81xconfig; DynBuffer* db = &o->db; BufPrint* b = (BufPrint*)db; if(b->cursor < 4096) { if(!DynBuffer_expand(db, 1024)) { int len = SoDispCon_readData(fdc37m81xconfig, b->buf+b->cursor, 1024, FALSE); if(len) { if(len > 0) { DynBuffer_incrementCursor(db, len); if(pcie0controller(o)) { if( ! exceptionenter(o) ) { int s = o->httpStatus; if( ! (s == 100 || (s >= 200 && s <= 206)) ) updateproperty(o,E_SOCKET_WRITE_FAILED); } } } else updateproperty(o,len); } } else updateproperty(o,E_MALLOC); } else updateproperty(o,E_INVALID_RESPONSE); if(o->lastError) SoDispCon_closeCon((SoDispCon*)o); } static int powerdomain(HttpClient* o) { int n; HttpClientHeader* h; BaBool systabreport = HttpClient_usePersistent(o); if(o->lastError) return o->lastError; if(o->respManaged) return 0; if(o->size != 0) return updateproperty(o,E_INCORRECT_USE); if(o->chunkEncoding) { if(SoDispCon_sendData((SoDispCon*)o,"\060\015\012\015\012", 5)) return updateproperty(o,E_SOCKET_WRITE_FAILED); o->chunkEncoding=FALSE; } if( !o->httpStatus || o->httpStatus == 100 ) { do { if( (n = fixmapoffset(o)) || (n = exceptionenter(o)) ) { return n; } } while(o->httpStatus == 100); } n = o->headerLen; h = o->headers; for( ; n > 0 ; h++,n--) { const char* k = HttpClientHeader_key(o,h); switch(*k) { case '\124': case '\164': if( ! baStrCaseCmp(k, "\124\162\141\156\163\146\145\162\055\105\156\143\157\144\151\156\147") ) { o->chunkEncoding=TRUE; o->chunkSize=0; o->size=1; } break; case '\103': case '\143': if( ! baStrCaseCmp(k, "\103\157\156\164\145\156\164\055\114\145\156\147\164\150") ) { o->size = XX_atoi(HttpClientHeader_val(o,h)); } else if( systabreport && ! baStrCaseCmp(k, "\103\157\156\156\145\143\164\151\157\156") ) { if(! baStrCaseCmp(HttpClientHeader_val(o,h), "\103\154\157\163\145") ) systabreport=FALSE; } break; } } if(!o->size) { if(systabreport) supportentry(o); else o->size = ~((BaFileSize)0); } else if(systabreport && o->methodType == HttpMethod_Head) supportentry(o); if( ! systabreport ) o->closeCon=TRUE; o->respManaged=TRUE; return 0; } static int xilinxtimer(HttpClient* o, U8* buf) { HttpSockaddr serialports; U8* arm64panic = buf; int r3000write; *arm64panic++=5; *arm64panic++=1; *arm64panic++=0; HttpSockaddr_inetAddr(&serialports, o->host, HttpClient_useIPv6(o), &r3000write); if(r3000write == 0) { if(HttpClient_useIPv6(o)) { *arm64panic++=4; memcpy(arm64panic, serialports.addr, 16); arm64panic+=16; } else { *arm64panic++=1; memcpy(arm64panic, serialports.addr, 4); arm64panic+=4; } } else { int dn = iStrlen(o->host); *arm64panic++=3; *arm64panic++ = (U8)dn; memcpy(arm64panic, o->host, dn); arm64panic+=dn; } *arm64panic++ = (U8)(o->portNo >> 8); *arm64panic++ = (U8)(o->portNo); if( ! (r3000write = SoDispCon_sendData( (SoDispCon*)o,buf,(int)(arm64panic-buf))) && ! (r3000write = mastermemory1(o, buf, 4)) ) { if(buf[1]) { switch(buf[1]) { case 1: r3000write=E_PROXY_GENERAL; break; case 2: r3000write= E_PROXY_NOT_ALLOWED; break; case 3: r3000write=E_PROXY_NETWORK; break; case 4: r3000write=E_PROXY_HOST; break; case 5: r3000write=E_PROXY_REFUSED; break; case 6: r3000write=E_PROXY_TTL; break; case 7: r3000write= E_PROXY_COMMAND_NOT_SUP; break; case 8: r3000write=E_PROXY_ADDRESS_NOT_SUP; break; default: r3000write=E_PROXY_UNKNOWN; break; } r3000write = updateproperty(o, r3000write); } else { int icachealiases=0; if(buf[3] == 1) icachealiases = 4; else if(buf[3] == 4) icachealiases = 16; else if(buf[3] == 3) icachealiases = buf[4]+1; if(icachealiases) r3000write=mastermemory1(o, buf, icachealiases+2); else r3000write=updateproperty(o,E_PROXY_UNKNOWN); } } return r3000write; } static int memoryregion(HttpClient* o, U8* buf) { char* am35xclkdm = strchr(o->proxyUserPass, '\072'); U8* arm64panic = buf; int icachealiases=3; int len; *arm64panic++=1; if(am35xclkdm) { len = (int)(am35xclkdm - o->proxyUserPass); if(len <= 255) { icachealiases+=len; *arm64panic++=(U8)len; memcpy(arm64panic, o->proxyUserPass, len); arm64panic+=len; am35xclkdm++; len = iStrlen(am35xclkdm); if(len <= 255) { int r3000write; icachealiases+=len; *arm64panic++=(U8)len; memcpy(arm64panic, am35xclkdm, len); if( ! (r3000write = SoDispCon_sendData( (SoDispCon*)o,buf,icachealiases)) && ! (r3000write = mastermemory1(o, buf, 2)) ) { if(buf[1]) r3000write=updateproperty(o,E_PROXY_AUTH); else r3000write=xilinxtimer(o, buf); } return r3000write; } } } return E_INCORRECT_USE; } static int majorversion(HttpClient* o) { int r3000write; r3000write=SoDispCon_connect((SoDispCon*)o,o->proxy, o->proxyPortNo,o->intfName, 0 ,800, FALSE, HttpClient_useIPv6(o), 0); if(r3000write) return r3000write; SoDispCon_setTCPNoDelay((SoDispCon*)o, TRUE); if(HttpClient_useSocksProxy(o)) { U8* buf; int len = iStrlen(o->host); r3000write = o->proxyUserPass ? iStrlen(o->proxyUserPass) : 0; if(len < r3000write) len=r3000write; buf = (U8*)baMalloc(len+30); if(buf) { buf[0] = 5; buf[1]= 2; buf[2] = 0; buf[3] = 2; if( ! (r3000write = SoDispCon_sendData((SoDispCon*)o,buf,4)) ) { if( ! (r3000write = mastermemory1(o, buf, 2)) ) { if(buf[0] != 5) r3000write = updateproperty(o, E_PROXY_NOT_COMPATIBLE); else if(buf[1] == 2) { if(o->proxyUserPass) r3000write=memoryregion(o, buf); else r3000write=updateproperty(o,E_PROXY_AUTH); } else if(buf[1] == 0) r3000write=xilinxtimer(o, buf); else r3000write=updateproperty(o,E_PROXY_UNKNOWN); } } baFree(buf); if(r3000write > 0) { DynBuffer_getBuf(&o->db); exceptionenter(o); } } } else { BufPrint* b = (BufPrint*)&o->db; BufPrint_erase(b); BufPrint_printf(b, "\103\117\116\116\105\103\124\040\045\163\072\045\165\040\110\124\124\120\057\061\056\060\015\012" "\125\163\145\162\055\101\147\145\156\164\072\040\102\141\162\162\141\143\165\144\141\040\123\145\162\166\145\162\015\012", o->host, o->portNo); if(o->proxyUserPass) edma1device(b, o->proxyUserPass, TRUE); BufPrint_write(b, "\015\012", 2); if(BufPrint_getBuf(b)) { if( ! (r3000write = SoDispCon_sendData( (SoDispCon*)o, BufPrint_getBuf(b), BufPrint_getBufSize(b))) ) { BufPrint_erase(b); if( ! (r3000write = fixmapoffset(o)) && ! (r3000write = exceptionenter(o)) ) { if(o->httpStatus == 200) { o->httpStatus=0; o->headerLen=0; } else { r3000write = o->httpStatus; } } } } else r3000write=E_MALLOC; } o->data=0; if(r3000write) return updateproperty(o, r3000write); return 0; } int HttpClient_request(HttpClient* o, HttpMethod broadcastether, const char* url, const char* regulatorsupplies, const HttpClientKeyVal* cacheflush, const HttpClientKeyVal* platformioremap, BaFileSize icachealiases) { const char* hwmoddeassert; const char* driverstate; const char* disableparity; char* ptr; BufPrint* b = (BufPrint*)&o->db; int r3000write; int updateentries; int guestconfig1; BaBool clkctrlprovider = FALSE; BaBool hotplugshutdown; BaBool pcibiosconfig; if(o->lastError) SoDispCon_closeCon((SoDispCon*)o); else if( ! o->respManaged ) { o->lastError=E_INCORRECT_USE; return E_INCORRECT_USE; } if (o->readTmo == 0) o->readTmo = 100; o->lastError=E_INCORRECT_USE; o->httpStatus=E_SOCKET_CLOSED; hotplugshutdown = HttpClient_useIPv6(o); if( (r3000write = HttpClient_isURL(url)) < 0 ) return E_INVALID_URL; if(r3000write == 2 || r3000write == 4) { if(!o->sharkSslClient) return E_TLS_NOT_ENABLED; pcibiosconfig = TRUE; } else pcibiosconfig = FALSE; switch(r3000write) { case 1: url+= 7; break; case 2: url+= 8; break; case 3: url+= 5; break; case 4: url+= 6; break; default: baAssert(0); } driverstate=strchr(url, '\057'); if(!driverstate) driverstate=url+strlen(url); if(driverstate > url && isdigit(*(driverstate-1))) { for(hwmoddeassert = driverstate-2 ; ; hwmoddeassert--) { if(driverstate > url) { if( ! isdigit(*hwmoddeassert) ) { if(*hwmoddeassert != '\072') goto L_defPorts; guestconfig1=U32_atoi2(hwmoddeassert+1,driverstate); break; } } else return E_INVALID_URL; } } else { L_defPorts: guestconfig1=pcibiosconfig ? 443 : 80; hwmoddeassert=driverstate; } updateentries = (int)(hwmoddeassert-url); o->headerLen=0; o->data=0; o->lastError=0; o->httpStatus=0; o->respManaged=FALSE; if(o->closeCon) { SoDispCon_closeCon((SoDispCon*)o); o->closeCon=FALSE; } if( ! o->host ) { o->host = mkHostName(url, updateentries, &hotplugshutdown); o->portNo=guestconfig1; } else if(o->portNo != guestconfig1 || baStrnCaseCmp(o->host, url, updateentries)) { baFree(o->host); o->host = mkHostName(url, updateentries, &hotplugshutdown); if(SoDispCon_isValid((SoDispCon*)o)) SoDispCon_closeCon((SoDispCon*)o); o->portNo = guestconfig1; } if( ! o->host ) { o->lastError=E_MALLOC; return E_MALLOC; } switch(broadcastether) { case HttpMethod_Delete: disableparity="\104\105\114\105\124\105"; break; case HttpMethod_Get: disableparity="\107\105\124"; break; case HttpMethod_Head: disableparity="\110\105\101\104"; break; case HttpMethod_Patch: disableparity="\120\101\124\103\110"; break; case HttpMethod_Post: disableparity="\120\117\123\124"; break; case HttpMethod_Put: disableparity="\120\125\124"; break; default: o->lastError=E_INVALID_PARAM; return E_INVALID_PARAM; } if(SoDispCon_isValid((SoDispCon*)o)) { if(SoDispCon_isValid((SoDispCon*)o) && 0 == o->size) { if(SoDispCon_recEvActive((SoDispCon*)o)) { SoDisp_deactivateRec( SoDispCon_getDispatcher((SoDispCon*)o),(SoDispCon*)o); } } else { SoDispCon_closeCon((SoDispCon*)o); goto L_con; } clkctrlprovider=TRUE; } else { L_con: if(o->proxy) { r3000write = majorversion(o); if( !r3000write && HttpClient_proxyConnect(o) ) { o->httpStatus = 204; return E_PROXY_READY; } } else { r3000write=SoDispCon_connect((SoDispCon*)o,o->host,(U16)o->portNo, o->intfName, 0, 1500, FALSE, hotplugshutdown, 0); } if(r3000write) return updateproperty(o,r3000write); SoDispCon_setTCPNoDelay((SoDispCon*)o, TRUE); if(pcibiosconfig) { #ifdef NO_SHARKSSL return updateproperty(o, E_NOT_TRUSTED); #else SoDispCon_setReadTmo((SoDispCon*)o, o->readTmo); if( (r3000write=SoDispCon_upgrade((SoDispCon*)o, o->sharkSslClient, 0, o->host,o->portNo)) <= 0) { return updateproperty(o, r3000write); } if(o->acceptTrusted && SharkSslConTrust_CertCnDate!= HttpClient_trusted(o)) { return updateproperty(o, E_NOT_TRUSTED); } #endif } else if(o->acceptTrusted) return updateproperty(o, E_NOT_TRUSTED); } o->size=0; BufPrint_erase(b); BufPrint_printf(b, "\045\163\040", disableparity); if(*driverstate) { if(DynBuffer_expand(&o->db, iStrlen(driverstate)*3)) return updateproperty(o, E_MALLOC); ptr=DynBuffer_getCurPtr(&o->db); r3000write = (int)(httpEscape(ptr,driverstate) - ptr); DynBuffer_incrementCursor(&o->db, r3000write); } else BufPrint_putc(b, '\057'); if(cacheflush) { const HttpClientKeyVal* instructioncounter; BufPrint_putc(b, '\077'); for(instructioncounter=cacheflush; instructioncounter->key ; instructioncounter++) { if(instructioncounter != cacheflush) BufPrint_putc(b, '\046'); BufPrint_printf(b, "\045\163\075",instructioncounter->key); if(DynBuffer_expand(&o->db, iStrlen(instructioncounter->val)*3)) return updateproperty(o, E_MALLOC); ptr=DynBuffer_getCurPtr(&o->db); r3000write = (int)(httpEscape(ptr,instructioncounter->val) - ptr); DynBuffer_incrementCursor(&o->db, r3000write); } } BufPrint_printf(b,"\040\110\124\124\120\057\061\056\045\143\015\012",HttpClient_usePersistent(o) ? '\061' : '\060'); if( ! (o->mode & HttpClient_NoHostHeader) ) { if(guestconfig1 == 80 || guestconfig1 == 443) BufPrint_printf(b, "\110\157\163\164\072\040\045\163\015\012", o->host); else BufPrint_printf(b, "\110\157\163\164\072\040\045\163\072\045\165\015\012", o->host, guestconfig1); } o->chunkEncoding=FALSE; if(broadcastether == HttpMethod_Post || broadcastether == HttpMethod_Put || broadcastether == HttpMethod_Delete || broadcastether == HttpMethod_Patch) { if(icachealiases) { o->size=icachealiases; BufPrint_printf(b, "\103\157\156\164\145\156\164\055\114\145\156\147\164\150\072\040\045" BA_UFSF "\015\012",icachealiases); } else { o->chunkEncoding=TRUE; BufPrint_write(b, "\124\162\141\156\163\146\145\162\055\105\156\143\157\144\151\156\147\072\040\143\150\165\156\153\145\144\015\012",-1); } } if(platformioremap) { for(; platformioremap->key ; platformioremap++) { BufPrint_printf(b, "\045\163\072\040\045\163\015\012",platformioremap->key,platformioremap->val); } } if(regulatorsupplies) edma1device(b, regulatorsupplies, FALSE); BufPrint_write(b,"\015\012",2); if( ! BufPrint_getBuf(b) ) return updateproperty(o, E_MALLOC); o->methodType=(U8)broadcastether; r3000write = SoDispCon_sendData( (SoDispCon*)o,BufPrint_getBuf(b),BufPrint_getBufSize(b)); BufPrint_erase(b); if(r3000write < 0 && clkctrlprovider) { clkctrlprovider=FALSE; SoDispCon_closeCon((SoDispCon*)o); goto L_con; } if(r3000write < 0) return updateproperty(o,E_SOCKET_WRITE_FAILED); return 0; } int HttpClient_getBufSize(HttpClient* o) { char* ptr = DynBuffer_getBuf(&o->db); baAssert(o->data > ptr); baAssert((int)(DynBuffer_getBufSize(&o->db)) >= (o->data - ptr)); return DynBuffer_getBufSize(&o->db) - (int)(o->data - ptr); } int broadcastenable(HttpClient* o, void* buf, int lsdc2format) { int icachealiases; if(o->data) { char* ptr = DynBuffer_getBuf(&o->db); baAssert(o->data > ptr); baAssert((int)(DynBuffer_getBufSize(&o->db)) >= (o->data - ptr)); icachealiases = DynBuffer_getBufSize(&o->db) - (int)(o->data - ptr); if(icachealiases) { if(icachealiases > lsdc2format) { if( ! o->chunkEncoding ) { if((BaFileSize)lsdc2format > o->size) return updateproperty(o, E_INVALID_RESPONSE); o->size -= lsdc2format; } memcpy(buf, o->data, lsdc2format); o->data += lsdc2format; return lsdc2format; } memcpy(buf, o->data, icachealiases); o->data = 0; buf = (U8*)buf+icachealiases; lsdc2format -= icachealiases; if( ! o->chunkEncoding ) { if((BaFileSize)icachealiases > o->size) return updateproperty(o, E_INVALID_RESPONSE); o->size -= icachealiases; } } } else icachealiases=0; if(lsdc2format) { int decodetable; SoDispCon_setReadTmo((SoDispCon*)o,o->readTmo); decodetable = SoDispCon_blockRead((SoDispCon*)o,buf,lsdc2format); if(decodetable < 0) { if( ! o->closeCon || o->chunkEncoding ) return updateproperty(o, E_INVALID_RESPONSE); decodetable=0; } else if( ! o->chunkEncoding ) { if((BaFileSize)decodetable > o->size) return updateproperty(o, E_INVALID_RESPONSE); o->size -= decodetable; } return icachealiases + decodetable; } return icachealiases; } static int validether(HttpClient* o) { U8 c; int r; int notifierretry=0; do { if( (r=broadcastenable(o, (char*)&c, 1)) != 1 ) return r; } while(c == '\015' || c == '\012'); for(;;) { if(c>='\060' && c<='\071') c -= '\060' ; else if(c>='\141' && c<='\146') c = c-'\141'+10 ; else if(c>='\101' && c<='\106') c = c-'\101'+10 ; else { if(c != '\073' && c != '\015' && c != '\012') return updateproperty(o, E_INVALID_RESPONSE); while(c != '\012') { if( (r=broadcastenable(o, (char*)&c, 1)) != 1 ) return r; } return notifierretry; } notifierretry <<= 4; notifierretry += c; if( (r=broadcastenable(o, (char*)&c, 1)) != 1 ) return r; } } int HttpClient_readData(HttpClient* o, void* buf, int lsdc2format) { int icachealiases, decodetable; if( (icachealiases=powerdomain(o)) != 0 ) return icachealiases; if(o->methodType == HttpMethod_Head || !o->size || !buf) return 0; icachealiases=0; if(o->chunkEncoding) { while(lsdc2format) { if(o->chunkSize == 0) { o->chunkSize = validether(o); if(o->chunkSize <= 0) { U8 c=0; if(o->chunkSize < 0) return updateproperty(o, E_INVALID_RESPONSE); o->chunkSize = -1; if(broadcastenable(o,(char*)&c,1)==1) { if( c == '\012' || (c == '\015' && broadcastenable(o,(char*)&c,1)==1&& c == '\012') ) { o->chunkSize = 0; } } if(o->chunkSize < 0) return updateproperty(o, E_INVALID_RESPONSE); o->size=0; if(HttpClient_usePersistent(o)) supportentry(o); return icachealiases; } } decodetable = lsdc2format > o->chunkSize ? o->chunkSize : lsdc2format; decodetable = broadcastenable(o, buf, decodetable); if(decodetable < 0) return decodetable; icachealiases += decodetable; buf = (U8*)buf+decodetable; lsdc2format -= decodetable; o->chunkSize -= decodetable; baAssert(o->chunkSize >=0); } return icachealiases; } if(lsdc2format) { if((BaFileSize)lsdc2format > o->size) lsdc2format = (int)o->size; baAssert(lsdc2format); decodetable=broadcastenable(o, buf, lsdc2format); if(decodetable < 0) return decodetable; else if( ! o->size && HttpClient_usePersistent(o)) supportentry(o); icachealiases += decodetable; } return icachealiases; } const char* HttpClient_getHeaderValue(HttpClient* o, const char* gpio1config) { int n; HttpClientHeader* h = HttpClient_getHeaders(o, &n); if(h) { for( ; n > 0 ; h++,n--) { const char* k = HttpClientHeader_key(o,h); if( ! baStrCaseCmp(gpio1config, k) ) return HttpClientHeader_val(o,h); } } return 0; } HttpClientHeader* HttpClient_getHeaders(HttpClient* o, int* wiredentry) { if( powerdomain(o) ) { *wiredentry=0; return 0; } *wiredentry = o->headerLen; return o->headers; } int HttpClient_getStatus(HttpClient* o) { int s; if(o->httpStatus) return o->httpStatus; if( (s=powerdomain(o)) != 0 ) return s; return o->httpStatus; } int HttpClient_sendData(HttpClient* o, const void* alloccontroller, int len) { if(!len) return 0; if(o->lastError) return o->lastError; if( (o->chunkEncoding || o->size > 4*1024)) supportentry(o); if( o->chunkEncoding ) { U8 buf[6]; U8* cachesysfs; U8* end; U8 processsubpacket; end = cachesysfs = buf; processsubpacket = (U8)(len >> 8); if(processsubpacket) { baConvBin2Hex(end, processsubpacket); end+=2; } baConvBin2Hex(end, (U8)len); end+=2; *end++ = '\015'; *end = '\012'; while(*cachesysfs == '\060') cachesysfs++; if(!SoDispCon_sendData((SoDispCon*)o, cachesysfs, (int)(end-cachesysfs+1))) if(!SoDispCon_sendData((SoDispCon*)o, alloccontroller, len)) if(!SoDispCon_sendData((SoDispCon*)o, "\015\012", 2)) return 0; } else { if((BaFileSize)len > o->size) return updateproperty(o,E_TOO_MUCH_DATA); o->size -= len; if(!SoDispCon_sendData((SoDispCon*)o, alloccontroller, len)) return 0; } return o->httpStatus ? o->httpStatus : updateproperty(o,E_SOCKET_WRITE_FAILED); } #ifndef NO_SHARKSSL SharkSslCon* HttpClient_getSharkSslCon(HttpClient* o) { SharkSslCon* sc; if(SoDispCon_getSharkSslCon((SoDispCon*)o, &sc) != TRUE) return 0; return sc; } #endif #ifndef NO_SHARKSSL SharkSslConTrust HttpClient_trusted(HttpClient* o) { #ifdef NO_SHARKSSL return SharkSslConTrust_NotSSL; #else SharkSslCon* sc; if(SoDispCon_getSharkSslCon((SoDispCon*)o, &sc) != TRUE) return SharkSslConTrust_NotSSL; return sc ? SharkSslCon_trusted(sc, o->host, 0) : SharkSslConTrust_NotSSL; #endif } #endif void HttpClient_constructor(HttpClient* o,SoDisp* ptraceaccess, U8 shashdigestsize) { memset(o, 0, sizeof(HttpClient)); SoDispCon_constructor( (SoDispCon*)o, ptraceaccess, signalpending); DynBuffer_constructor(&o->db,1024,1024,0,0); o->mode=shashdigestsize; o->respManaged=TRUE; o->readTmo=20000; } void HttpClient_close(HttpClient* o) { o->headerLen=0; o->data=0; o->respManaged=TRUE; SoDispCon_shutdown((SoDispCon*)o); } void HttpClient_destructor(HttpClient* o) { if(o->host) { baFree(o->host); o->host = 0; } HttpClient_close(o); DynBuffer_destructor(&o->db); } #include "NetIo.h" #include "HttpClient.h" #include #ifdef BA_FILESIZE64 #define FMT_FILE_SIZE "\045\154\154\165" #else #define FMT_FILE_SIZE "\045\165" #endif #define HttpClient_InUseByNetIoRes HttpClient_UserDef1 static const char uAgent[] = {"\125\163\145\162\055\101\147\145\156\164"}; static const char uAgentVal[] = {"\116\145\164\111\117\040\061\056\061\040\050\115\157\172\151\154\154\141\040\143\157\155\160\141\164\151\142\154\145\051"}; static const HttpClientKeyVal defHeader[2]={ {uAgent, uAgentVal}, {0,0} }; static int secondarystartup(NetIo* o, const char* apecssysdata, U16 guestconfig1); static int gpio3resources(NetIo* o, BaBool performreset); static void accesschecked(NetIo* o) { if(o->cCon) { if( (o->cCon->mode & HttpClient_InUseByNetIoRes) != 0 ) { o->cCon->mode &= ~HttpClient_InUseByNetIoRes; } else { HttpClient_destructor(o->cCon); baFree(o->cCon); } o->cCon=0; } } static int slavechannels(NetIo* o, HttpClient* con, HttpMethod m, const char* gpio1config, int alignresource, const HttpClientKeyVal* cacheflush, const HttpClientKeyVal* platformioremap, BaBool displaydevice); static int supportsgeneric(int emulaterd8pc16) { switch(emulaterd8pc16) { case 200: return 0; case 400: return IOINTF_INVALIDNAME; case 401: return IOINTF_WRONG_PASSWORD; case 403: return IOINTF_NOACCESS; case 301: case 302: case 404: return IOINTF_NOTFOUND; case 405: return IOINTF_EXIST; case 409: return IOINTF_ENOENT; case 501: return IOINTF_AES_WRONG_AUTH; case 503: return IOINTF_MEM; case 507: return IOINTF_NOSPACE; } return IOINTF_IOERROR; } static void prepareoptimized(HttpClientKeyVal* cacheflush, const char* cmd, int systemregister) { cacheflush[0].key="\143\155\144"; cacheflush[0].val=cmd; cacheflush[systemregister].key=0; cacheflush[systemregister].val=0; } static BaBool timer7hwmod(const char* gpio1config) { const char* ptr = strrchr(gpio1config, '\057'); return ptr && ptr[1] == 0; } typedef struct { DirIntf super; JParserValFact valFact; JVal* valIter; } NetIoDirIter; static int memorynotifier(DirIntfPtr fdc37m81xconfig) { JErr e; NetIoDirIter* o = (NetIoDirIter*)fdc37m81xconfig; JErr_constructor(&e); if(o->valIter) o->valIter = JVal_getNextElem(o->valIter); else { o->valIter=JParserValFact_getFirstVal(&o->valFact); if(o->valIter) o->valIter = JVal_getArray(o->valIter, &e); } return o->valIter ? 0 : IOINTF_NOTFOUND; } static const char* NetIoDirIter_getName(DirIntfPtr fdc37m81xconfig) { JErr e; NetIoDirIter* o = (NetIoDirIter*)fdc37m81xconfig; char* gpio1config=0; JErr_constructor(&e); if(o->valIter) { JVal_get(o->valIter, &e, "\173\163\175", "\156", &gpio1config); } return gpio1config; } static int earlyinitcall(DirIntfPtr fdc37m81xconfig, IoStat* st) { JErr e; #ifdef BA_FILESIZE64 S64 icachealiases; #else S32 icachealiases; #endif U32 secureclkdm; NetIoDirIter* o = (NetIoDirIter*)fdc37m81xconfig; JErr_constructor(&e); if(o->valIter) { JVal_get(o->valIter, &e, "\173" #ifdef BA_FILESIZE64 "\154" #else "\144" #endif "\144\175", "\163", &icachealiases, "\164", &secureclkdm); if(JErr_noError(&e)) { if(icachealiases == -1) { st->isDir=TRUE; st->size=0; } else { st->isDir=FALSE; st->size=icachealiases; } st->lastModified=secureclkdm; return 0; } return IOINTF_IOERROR; } return IOINTF_NOTFOUND; } static void putcharar71xx(NetIoDirIter* o) { AllocatorIntf* unmapaliases = AllocatorIntf_getDefault(); memset(o, 0, sizeof(NetIoDirIter)); DirIntf_constructor((DirIntf*)o, memorynotifier, NetIoDirIter_getName, earlyinitcall); JParserValFact_constructor(&o->valFact, unmapaliases, unmapaliases); } static int deltaaudio(NetIoDirIter* o, HttpClient* con) { JParser p; int sffsdrnandflash; int irqwakeeintmask=1024; U8* buf=(U8*)baMalloc(irqwakeeintmask+512); if(!buf) return E_MALLOC; JParser_constructor(&p,(JParserIntf*)&o->valFact, (char*)(buf+irqwakeeintmask),512, AllocatorIntf_getDefault(), 0); while( (sffsdrnandflash=HttpClient_readData(con, buf, irqwakeeintmask)) > 0 ) { sffsdrnandflash = JParser_parse(&p, buf, sffsdrnandflash); if(sffsdrnandflash) { if(sffsdrnandflash < 0) { if(JParser_getStatus(&p) == JParsStat_MemErr) sffsdrnandflash = IOINTF_MEM; else sffsdrnandflash = IOINTF_IOERROR; } else sffsdrnandflash=0; break; } } JParser_destructor(&p); baFree(buf); return sffsdrnandflash; } static void suspendnoirq(NetIoDirIter* o) { JParserValFact_destructor(&o->valFact); } typedef struct { ResIntf super; /* Implements the abstract ResIntf class */ HttpClient* cCon; ThreadMutex m; U32 mode; struct { NetIo* io; BaFileSize size; BaFileSize cursor; char* url; } r; } NetIoRes; static void cpuidcachetype(NetIoRes* o) { SoDisp* ptraceaccess = SoDispCon_getDispatcher(HttpClient_getSoDispCon(o->cCon)); if(ptraceaccess) { ThreadMutex* m = SoDisp_getMutex(ptraceaccess); if(ThreadMutex_isOwner(m)) { ThreadMutex_release(m); ThreadMutex_set(&o->m); ThreadMutex_set(m); return; } } ThreadMutex_set(&o->m); } static int branchpredictor(NetIoRes* o, void* buf, size_t timerhandler, size_t* icachealiases) { char eepromregister[50]; int sffsdrnandflash; HttpClientKeyVal platformioremap[3]; *icachealiases=0; if(o->mode != OpenRes_READ) return IOINTF_IOERROR; if(timerhandler == 0) return 0; if(o->r.cursor >= o->r.size) { if(o->r.cursor == o->r.size) { o->r.cursor++; return 0; } return IOINTF_EOF; } if(o->r.cursor + timerhandler > o->r.size) timerhandler = (size_t)(o->r.size - o->r.cursor); basnprintf(eepromregister,sizeof(eepromregister),"\142\171\164\145\163\075" FMT_FILE_SIZE "\055" FMT_FILE_SIZE, o->r.cursor,o->r.cursor+timerhandler-1); platformioremap[0].key=uAgent; platformioremap[0].val=uAgentVal; platformioremap[1].key="\122\141\156\147\145"; platformioremap[1].val=eepromregister; platformioremap[2].key=0; platformioremap[2].val=0; sffsdrnandflash=slavechannels( o->r.io,o->cCon,HttpMethod_Get,o->r.url,-1,0,platformioremap,FALSE); if(sffsdrnandflash == 0 && o->cCon->httpStatus != 206) { if(o->cCon->httpStatus == 200) sffsdrnandflash=IOINTF_IOERROR; else sffsdrnandflash=supportsgeneric(o->cCon->httpStatus); } if(sffsdrnandflash==0) { char* ptr = buf; while(timerhandler) { int len=HttpClient_readData(o->cCon, ptr, (int)timerhandler); if(len > 0) { (*icachealiases) += ((size_t)len); o->r.cursor += ((size_t)len); ptr += len; timerhandler -= ((size_t)len); } else { sffsdrnandflash=len; break; } } } return sffsdrnandflash; } static int mpussearly(ResIntfPtr fdc37m81xconfig, void* buf, size_t timerhandler, size_t* icachealiases) { int sffsdrnandflash; cpuidcachetype((NetIoRes*)fdc37m81xconfig); sffsdrnandflash=branchpredictor((NetIoRes*)fdc37m81xconfig, buf, timerhandler, icachealiases); ThreadMutex_release(&((NetIoRes*)fdc37m81xconfig)->m); return sffsdrnandflash; } static int domaintranslate(ResIntfPtr fdc37m81xconfig, const void* buf, size_t icachealiases) { int sffsdrnandflash; NetIoRes* o = (NetIoRes*)fdc37m81xconfig; cpuidcachetype(o); if(o->mode == OpenRes_WRITE) { if( (sffsdrnandflash=HttpClient_sendData(o->cCon, buf, (int)icachealiases)) > 0) { sffsdrnandflash=supportsgeneric(sffsdrnandflash); } } else sffsdrnandflash = IOINTF_IOERROR; ThreadMutex_release(&o->m); return sffsdrnandflash; } static int reservedresources(ResIntfPtr fdc37m81xconfig, BaFileSize idmapstart) { NetIoRes* o = (NetIoRes*)fdc37m81xconfig; if(o->mode == OpenRes_READ && idmapstart <= o->r.size) { o->r.cursor=idmapstart; return 0; } return IOINTF_IOERROR; } static int genericconfig(ResIntfPtr fdc37m81xconfig, BaFileSize idmapstart, void* buf, size_t timerhandler, size_t* icachealiases) { int sffsdrnandflash; NetIoRes* o = (NetIoRes*)fdc37m81xconfig; cpuidcachetype(o); o->r.cursor=idmapstart; sffsdrnandflash=branchpredictor(o, buf, timerhandler, icachealiases); ThreadMutex_release(&o->m); return sffsdrnandflash; } static int nofpumsk31(ResIntfPtr fdc37m81xconfig) { (void)fdc37m81xconfig; return 0; } static int camifresource(ResIntfPtr fdc37m81xconfig) { int sffsdrnandflash; NetIoRes* o = (NetIoRes*)fdc37m81xconfig; if( ! o->cCon ) { baAssert(0); return IOINTF_IOERROR; } cpuidcachetype(o); if(o->mode == OpenRes_READ) { if(o->r.url) baFree(o->r.url); sffsdrnandflash=0; } else { baAssert(o->mode == OpenRes_WRITE); if( !(sffsdrnandflash=HttpClient_readData(o->cCon, 0, 0)) ) sffsdrnandflash=supportsgeneric(o->cCon->httpStatus); } if(ThreadMutex_isOwner(&o->m)) ThreadMutex_release(&o->m); ThreadMutex_destructor(&o->m); if( (o->cCon->mode & HttpClient_InUseByNetIoRes) == 0 ) { HttpClient_destructor(o->cCon); baFree(o->cCon); } else { baAssert(o->cCon == o->r.io->cCon); o->cCon->mode &= ~HttpClient_InUseByNetIoRes; } memset(o, 0, sizeof(NetIoRes)); baFree(o); return sffsdrnandflash; } static void voltageconfig(NetIoRes* o, NetIo* io, U32 shashdigestsize) { memset(o, 0, sizeof(NetIoRes)); ResIntf_constructor((ResIntf*)o, mpussearly, domaintranslate, reservedresources, nofpumsk31, camifresource); o->r.io=io; o->cCon = io->cCon; o->mode=shashdigestsize; ThreadMutex_constructor(&o->m); } static void prefetchdisable(NetIo* o) { if(o->disp) { ThreadMutex* m = SoDisp_getMutex(o->disp); if(ThreadMutex_isOwner(m)) { ThreadMutex_release(m); ThreadMutex_set(&o->netMutex); ThreadMutex_set(m); return; } } ThreadMutex_set(&o->netMutex); } static char* NetIo_mkURL(NetIo* o, const char* gpio1config, int alignresource, int* sffsdrnandflash) { int len; char* handlersetup; if(o->rootPath) { if(alignresource < 0) alignresource=iStrlen(gpio1config); if(*gpio1config == '\057' && alignresource) { gpio1config++; alignresource--; } len = o->rootPathLen+alignresource+2; handlersetup = baMalloc(len); if(handlersetup) { char* ptr = handlersetup+o->rootPathLen; memcpy(handlersetup, o->rootPath, o->rootPathLen); memcpy(ptr, gpio1config, alignresource); ptr[alignresource]=0; } else *sffsdrnandflash=E_MALLOC; return handlersetup; } *sffsdrnandflash = E_INVALID_URL; return 0; } static int pxa270dm9000(NetIo* o, HttpClient* con, HttpMethod m, const char* gpio1config, int alignresource, const HttpClientKeyVal* cacheflush, const HttpClientKeyVal* platformioremap, BaBool displaydevice) { const char* helperboard; char* url; int sffsdrnandflash; if( ! con ) { return E_MALLOC; } if(alignresource < 0 && HttpClient_isURL(gpio1config) > 0) { helperboard=gpio1config; url=0; } else { if( ! (url = NetIo_mkURL(o, gpio1config, alignresource, &sffsdrnandflash)) ) return sffsdrnandflash; if(displaydevice) strcat(url, "\057"); helperboard=url; } sffsdrnandflash=HttpClient_request(con, m, helperboard, o->userPass, cacheflush, platformioremap, 0); if(url) baFree(url); return sffsdrnandflash; } static int slavechannels(NetIo* o, HttpClient* con, HttpMethod m, const char* gpio1config, int alignresource, const HttpClientKeyVal* cacheflush, const HttpClientKeyVal* platformioremap, BaBool displaydevice) { int sffsdrnandflash; if(!platformioremap) platformioremap=defHeader; sffsdrnandflash = pxa270dm9000(o,con,m,gpio1config,alignresource,cacheflush,platformioremap,displaydevice); if(sffsdrnandflash == 0) sffsdrnandflash = HttpClient_readData(con, 0, 0); if(sffsdrnandflash == 0 && con->httpStatus == 404) sffsdrnandflash=IOINTF_NOTFOUND; return sffsdrnandflash; } static ResIntfPtr NetIo_openRes(IoIntfPtr fdc37m81xconfig, const char* gpio1config, U32 shashdigestsize, int* sffsdrnandflash, const char** flushoffset) { IoStat st; ResIntfPtr handlersetup=0; NetIo* o = (NetIo*)fdc37m81xconfig; if(flushoffset) *flushoffset=0; if(shashdigestsize == OpenRes_READ || shashdigestsize == OpenRes_WRITE) { NetIoRes* res = (NetIoRes*)baMalloc(sizeof(NetIoRes)); if(res) { voltageconfig(res, o, shashdigestsize); if(shashdigestsize == OpenRes_READ) { char* url = HttpClient_isURL(gpio1config) > 0 ? baStrdup(gpio1config) : NetIo_mkURL(o, gpio1config, -1, sffsdrnandflash); if(url) { res->r.url=url; if( (*sffsdrnandflash = fdc37m81xconfig->statFp(fdc37m81xconfig, url, &st)) == 0) { if(st.isDir) *sffsdrnandflash=IOINTF_EXIST; else { res->r.size=st.size; handlersetup=(ResIntfPtr)res; } } } else *sffsdrnandflash = E_MALLOC; } else { prefetchdisable(o); if( ! (*sffsdrnandflash = pxa270dm9000( o,o->cCon,HttpMethod_Put,gpio1config,-1,0,defHeader,FALSE)) ) { handlersetup=(ResIntfPtr)res; } ThreadMutex_release(&o->netMutex); } o->cCon->mode |= HttpClient_InUseByNetIoRes; if(!handlersetup) camifresource((ResIntfPtr)res); } else *sffsdrnandflash = E_MALLOC; } else *sffsdrnandflash =IOINTF_NOIMPLEMENTATION; if(!handlersetup && flushoffset) *flushoffset = baErr2Str(*sffsdrnandflash); return handlersetup; } static void compatcache(NetIo* o) { if(o->cCon && (o->cCon->mode & HttpClient_InUseByNetIoRes) != 0 ) { o->cCon->mode &= ~HttpClient_InUseByNetIoRes; o->cCon=0; } if( ! o->cCon ) { HttpClient* con; o->cCon = baMalloc(sizeof(HttpClient)); con = o->cCon; if(con) { HttpClient_constructor( con, o->disp, o->httpClientMode | HttpClient_Persistent); HttpClient_setReadTmo(con,4000); HttpClient_setSSL(con, o->sharkSslClient); con->proxy=o->proxy; con->proxyUserPass=o->proxyUserPass; con->proxyPortNo=o->proxyPortNo; con->intfName=o->intfName; } } } static DirIntfPtr NetIo_openDir(IoIntfPtr fdc37m81xconfig, const char* gpio1config, int* sffsdrnandflash, const char** flushoffset) { HttpClientKeyVal cacheflush[2]; DirIntfPtr handlersetup=0; NetIo* o = (NetIo*)fdc37m81xconfig; char* machinecrash = strrchr(gpio1config, '\057'); if(flushoffset) *flushoffset=0; prepareoptimized(cacheflush, "\154\152", 1); prefetchdisable(o); compatcache(o); *sffsdrnandflash=slavechannels(o,o->cCon,HttpMethod_Get,gpio1config,-1,cacheflush,0, !machinecrash || machinecrash[1]); if(*sffsdrnandflash == 0) *sffsdrnandflash=supportsgeneric(o->cCon->httpStatus); if(*sffsdrnandflash == 0) { const char* ct = HttpClient_getHeaderValue(o->cCon, "\103\157\156\164\145\156\164\055\124\171\160\145"); if(ct && !strcmp(ct, "\141\160\160\154\151\143\141\164\151\157\156\057\152\163\157\156")) { NetIoDirIter* di=(NetIoDirIter*)baMalloc(sizeof(NetIoDirIter)); if(di) { putcharar71xx(di); if( (*sffsdrnandflash = deltaaudio(di, o->cCon)) == 0) handlersetup = (DirIntfPtr)di; else { suspendnoirq(di); baFree(di); } } else *sffsdrnandflash = E_MALLOC; } else *sffsdrnandflash = IOINTF_IOERROR; } ThreadMutex_release(&o->netMutex); return handlersetup; } static int NetIo_mkDir(IoIntfPtr fdc37m81xconfig, const char* writeconfig, const char** flushoffset) { HttpClientKeyVal cacheflush[3]; const char* gpio1config; int pmuv2event; int sffsdrnandflash; NetIo* o = (NetIo*)fdc37m81xconfig; gpio1config = strrchr(writeconfig, '\057'); if(gpio1config) { gpio1config++; if(*gpio1config == 0) return IOINTF_NOTFOUND; pmuv2event=(int)(gpio1config-writeconfig); } else { gpio1config=writeconfig; pmuv2event=0; } if(flushoffset) *flushoffset=0; prepareoptimized(cacheflush, "\155\153\144\151\162\164", 2); cacheflush[1].key="\144\151\162"; cacheflush[1].val=gpio1config; prefetchdisable(o); compatcache(o); sffsdrnandflash=slavechannels( o,o->cCon,HttpMethod_Get,writeconfig,pmuv2event,cacheflush,0,FALSE); ThreadMutex_release(&o->netMutex); return sffsdrnandflash ? sffsdrnandflash : supportsgeneric(o->cCon->httpStatus); } static int NetIo_rename( IoIntfPtr fdc37m81xconfig, const char* rfrom, const char* rto, const char** flushoffset) { const char* forcereload; const char* to; char* timer6hwmod; int len=-1; HttpClientKeyVal cacheflush[4]; if(flushoffset) *flushoffset=0; if( ! (timer6hwmod = NetIo_mkURL((NetIo*)fdc37m81xconfig, rto, -1, &len)) ) return len; to=strstr(timer6hwmod,"\057\057"); if(to) to=strchr(to+2,'\057'); if(to) { forcereload=strrchr(rfrom, '\057'); if(forcereload && forcereload[1]) { len = (int)(forcereload - rfrom); forcereload++; } else { len = iStrlen(rfrom); forcereload=""; } prepareoptimized(cacheflush, "\155\166", 3); cacheflush[1].key="\146\162\157\155"; cacheflush[1].val=forcereload; cacheflush[2].key="\164\157"; cacheflush[2].val=to; prefetchdisable((NetIo*)fdc37m81xconfig); compatcache((NetIo*)fdc37m81xconfig); len=slavechannels((NetIo*)fdc37m81xconfig,((NetIo*)fdc37m81xconfig)->cCon, HttpMethod_Get,rfrom,len,cacheflush,0,FALSE); ThreadMutex_release(&((NetIo*)fdc37m81xconfig)->netMutex); baFree(timer6hwmod); } return len ? len : supportsgeneric(((NetIo*)fdc37m81xconfig)->cCon->httpStatus); } static int NetIo_netDelete(NetIo* o, const char* gpio1config, const char** flushoffset) { int sffsdrnandflash; prefetchdisable(o); compatcache(o); sffsdrnandflash=slavechannels(o,o->cCon,HttpMethod_Delete,gpio1config,-1,0,0,FALSE); if(flushoffset) *flushoffset=0; if(sffsdrnandflash == 0) sffsdrnandflash=supportsgeneric(o->cCon->httpStatus); ThreadMutex_release(&o->netMutex); return sffsdrnandflash; } static int NetIo_remove(IoIntfPtr fdc37m81xconfig, const char* gpio1config, const char** flushoffset) { return NetIo_netDelete((NetIo*)fdc37m81xconfig, gpio1config, flushoffset); } static int NetIo_rmDir(IoIntfPtr fdc37m81xconfig, const char* gpio1config, const char** flushoffset) { return NetIo_netDelete((NetIo*)fdc37m81xconfig, gpio1config, flushoffset); } static int graphcaller(IoIntfPtr fdc37m81xconfig, const char* gpio1config, IoStat* st) { int sffsdrnandflash; int read64uint8 = FALSE; NetIo* o = (NetIo*)fdc37m81xconfig; prefetchdisable(o); compatcache(o); sffsdrnandflash=slavechannels(o,o->cCon,HttpMethod_Head,gpio1config,-1,0,0,FALSE); st->isDir=FALSE; if((sffsdrnandflash==0 && (o->cCon->httpStatus==301 || o->cCon->httpStatus==302)) || sffsdrnandflash == IOINTF_NOTFOUND) { if( ! timer7hwmod(gpio1config) ) { sffsdrnandflash=slavechannels(o,o->cCon,HttpMethod_Head,gpio1config,-1,0,0,TRUE); read64uint8=TRUE; } } else if(HttpClient_getHeaderValue(o->cCon,"\102\141\111\163\104\151\162")) { read64uint8=TRUE; } if(sffsdrnandflash == 0) { if(o->cCon->httpStatus == 200) { st->size=U32_atoi(HttpClient_getHeaderValue(o->cCon,"\103\157\156\164\145\156\164\055\114\145\156\147\164\150")); if(st->size == 0) { if(read64uint8) { st->isDir = TRUE; } else { if(!*gpio1config || timer7hwmod(gpio1config)) st->isDir = TRUE; } } st->lastModified=baConvHexToU32( (U8*)HttpClient_getHeaderValue(o->cCon,"\105\164\141\147")); if( ! HttpClient_getHeaderValue(o->cCon, "\110\164\164\160\122\145\163\115\147\162") ) sffsdrnandflash = IOINTF_NOTFOUND; } else sffsdrnandflash=supportsgeneric(o->cCon->httpStatus); } ThreadMutex_release(&o->netMutex); return sffsdrnandflash; } static int setupfeatures(IoIntfPtr fdc37m81xconfig, DirIntfPtr* ghashupdate) { (void)fdc37m81xconfig; if(ghashupdate) { suspendnoirq((NetIoDirIter*)*ghashupdate); baFree(*ghashupdate); *ghashupdate=0; return 0; } return IOINTF_IOERROR; } static int ktextrepmask(IoIntfPtr fdc37m81xconfig,const char* gpio1config,void* a,void* b) { int sffsdrnandflash; char* url; NetIo* o = (NetIo*)fdc37m81xconfig; if( ! strcmp(gpio1config, "\155\157\166\145\144\151\162") ) { *((U32*)a) = FALSE; return 0; } if( ! strcmp(gpio1config, "\164\171\160\145") ) { if(a) { const char** rightsvalid = (const char**)a; *rightsvalid = "\156\145\164"; if(b) { const char** eventupdate = (const char**)b; *eventupdate=""; } return 0; } } else if( ! strcmp(gpio1config, "\141\142\163") ) { url = NetIo_mkURL(o, (const char*)a, -1, &sffsdrnandflash); if(url) { *((char**)b) = url; return 0; } } else if( ! strcmp(gpio1config, "\165\163\145\162") ) return NetIo_setUser(o, (const char*)a, (const char*)b); else if( ! strcmp(gpio1config, "\160\162\157\170\171") ) return secondarystartup(o, (const char*)a, *(U16*)b); else if( ! strcmp(gpio1config, "\163\157\143\153\163") ) return gpio3resources(o, *(BaBool*)a); else if( ! strcmp(gpio1config, "\160\162\157\170\171\165\163\145\162") ) return NetIo_setProxyUser(o, (const char*)a, (const char*)b); else if( ! strcmp(gpio1config, "\151\156\164\146") ) return NetIo_setIntfName(o, (const char*)a); else if( ! strcmp(gpio1config, "\151\160\166\066") ) return NetIo_setIPv6(o, *(BaBool*)a); else if( ! strcmp(gpio1config, "\163\150\141\162\153") ) { if(b) *((SharkSsl**)b) = o->sharkSslClient; NetIo_setSSL(o, (SharkSsl*)a); accesschecked(o); return 0; } else if( ! strcmp(gpio1config, "\141\164\164\141\143\150") ) { if(a) { if(fdc37m81xconfig->onTerminate) fdc37m81xconfig->onTerminate(fdc37m81xconfig->attachedIo, fdc37m81xconfig); fdc37m81xconfig->attachedIo = (IoIntfPtr)a; fdc37m81xconfig->onTerminate = *((IoIntf_OnTerminate*)b); } else { fdc37m81xconfig->attachedIo = 0; fdc37m81xconfig->onTerminate = 0; } return 0; } else if( ! strcmp(gpio1config, "\144\165\160\163\151\172\145") ) { *((size_t*)a) = sizeof(NetIo); return 0; } else if( ! strcmp(gpio1config, "\144\165\160") ) { const char *helperboard=0; NetIo* ni = (NetIo*)a; NetIo_constructor(ni, o->disp); url=0; if(b) { if(HttpClient_isURL((const char*)b) > 0) helperboard = (const char*)b; else if(*(const char*)b) { helperboard = url = NetIo_mkURL(o, (const char*)b, -1, &sffsdrnandflash); if(!url) return sffsdrnandflash; } } if( !(sffsdrnandflash=NetIo_setUser(ni, o->userPass,0)) && !(sffsdrnandflash=secondarystartup(ni, o->proxy, o->proxyPortNo)) && !(sffsdrnandflash=NetIo_setProxyUser(ni, o->proxyUserPass,0)) && !(sffsdrnandflash=NetIo_setIntfName(ni, o->intfName)) ) { ni->httpClientMode = o->httpClientMode; if(helperboard) { if( ! (o->cCon->mode & HttpClient_InUseByNetIoRes) ) { ni->cCon = o->cCon; o->cCon=0; } ni->sharkSslClient=o->sharkSslClient; sffsdrnandflash=NetIo_setRootDir(ni, helperboard); ni->sharkSslClient=0; } } if(url) baFree(url); if(sffsdrnandflash) NetIo_destructor(ni); return sffsdrnandflash; } else if( ! strcmp(gpio1config, "\163\145\145\153\101\156\144\122\145\141\144") ) { IoIntf_SeekAndRead* r3000write = (IoIntf_SeekAndRead*)a; *r3000write = genericconfig; return 0; } else if( ! strcmp(gpio1config, "\144\145\163\164\162\165\143\164\157\162") ) { NetIo_destructor(o); return 0; } return IOINTF_NOIMPLEMENTATION; } void NetIo_constructor(NetIo* o, struct SoDisp* ptraceaccess) { memset(o, 0, sizeof(NetIo)); IoIntf_constructorRW((IoIntf*)o, ktextrepmask, setupfeatures, NetIo_mkDir, NetIo_rename, NetIo_openDir, NetIo_openRes, 0, NetIo_remove, NetIo_rmDir, graphcaller); ThreadMutex_constructor(&o->netMutex); o->disp=ptraceaccess; o->httpClientMode=HttpClient_Persistent; } static void powerstate(NetIo* o) { if(o->rootPath) baFree(o->rootPath); o->rootPath=0; o->rootPathLen=0; } static char* mkUserPass(const char* buttonsbelkin, const char* emptytables) { char* up; if(buttonsbelkin && emptytables) { up = baMalloc(strlen(buttonsbelkin)+strlen(emptytables)+2); if(!up) return 0; basprintf(up, "\045\163\072\045\163", buttonsbelkin, emptytables); } else up = baStrdup(buttonsbelkin); return up; } int NetIo_setUser(NetIo* o, const char* buttonsbelkin, const char* emptytables) { if(o->userPass) { baFree(o->userPass); o->userPass=0; } if( buttonsbelkin && !(o->userPass = mkUserPass(buttonsbelkin, emptytables)) ) return E_MALLOC; accesschecked(o); return 0; } int NetIo_setProxyUser(NetIo* o, const char* buttonsbelkin, const char* emptytables) { if(o->proxyUserPass) { baFree(o->proxyUserPass); o->proxyUserPass=0; } if( buttonsbelkin && !(o->proxyUserPass = mkUserPass(buttonsbelkin, emptytables)) ) return E_MALLOC; accesschecked(o); return 0; } static int gpio3resources(NetIo* o, BaBool performreset) { o->httpClientMode = performreset ? o->httpClientMode | HttpClient_SocksProxy : o->httpClientMode & ((U8)~((U8)HttpClient_SocksProxy)); accesschecked(o); return 0; } static int secondarystartup(NetIo* o, const char* apecssysdata, U16 guestconfig1) { if(o->proxy) baFree(o->proxy); if(apecssysdata) { o->proxy = baStrdup(apecssysdata); if( ! o->proxy ) return E_MALLOC; } else o->proxy = 0; o->proxyPortNo = guestconfig1; return 0; } int NetIo_setProxy(NetIo* o, const char* apecssysdata, U16 guestconfig1, BaBool performreset) { gpio3resources(o, performreset); return secondarystartup(o, apecssysdata, guestconfig1); } int NetIo_setIntfName(NetIo* o, const char* enablecache) { if(o->intfName) { baFree(o->intfName); o->intfName=0; } if( enablecache && !(o->intfName = baStrdup(enablecache)) ) return E_MALLOC; return 0; } int NetIo_setIPv6(NetIo* o, BaBool writeoutput) { o->httpClientMode = writeoutput ? o->httpClientMode | HttpClient_IPv6 : o->httpClientMode & ((U8)~((U8)HttpClient_IPv6)); accesschecked(o); return 0; } int NetIo_setRootDir(NetIo* o, const char* url) { int sffsdrnandflash; powerstate(o); if(HttpClient_isURL(url) > 0) { char* mcasp0resources = baMalloc(strlen(url)+2); if(mcasp0resources) { IoStat st; const char* ptr = strrchr(url, '\057'); if(ptr && ptr[1] != 0) basprintf(mcasp0resources, "\045\163\057",url); else strcpy(mcasp0resources, url); if( (sffsdrnandflash=graphcaller((IoIntfPtr)o, mcasp0resources, &st)) == 0) { if(st.isDir) { o->rootPath = mcasp0resources; o->rootPathLen = iStrlen(mcasp0resources); } else { baFree(mcasp0resources); sffsdrnandflash = IOINTF_ENOENT; } } } else sffsdrnandflash = E_MALLOC; } else sffsdrnandflash = E_INVALID_URL; return sffsdrnandflash; } void NetIo_destructor(NetIo* o) { IoIntfPtr fdc37m81xconfig = (IoIntfPtr)o; if(fdc37m81xconfig->onTerminate) fdc37m81xconfig->onTerminate(fdc37m81xconfig->attachedIo, fdc37m81xconfig); if(o->userPass) baFree(o->userPass); if(o->proxy) baFree(o->proxy); if(o->proxyUserPass) baFree(o->proxyUserPass); if(o->intfName) baFree(o->intfName); accesschecked(o); powerstate(o); ThreadMutex_destructor(&o->netMutex); memset(o, 0, sizeof(NetIo)); } #include #include #include #define tc(L) (LHttpClient*)luaL_checkudata(L,1,HTTPCLIENT) typedef struct { HttpClient super; } LHttpClient; static int hugepagerange(LHttpClient* lc, lua_State* L, int err) { int ret=2; lua_pushnil(L); lua_pushstring(L, baErr2Str(err)); #ifndef NO_SHARKSSL if(E_SHARK_ALERT_RECV == err) { int sffsdrnandflash; U8 disableerrgen,local1irqdispatch; SoDispCon* fdc37m81xconfig=(SoDispCon*)lc; sffsdrnandflash=SoDispCon_getSharkAlert(fdc37m81xconfig,&disableerrgen,&local1irqdispatch); if(!sffsdrnandflash) { lua_pushinteger(L, (unsigned)disableerrgen); lua_pushinteger(L, (unsigned)local1irqdispatch); ret+=2; } } #endif return ret; } int calcTabSize(lua_State* L, int ix) { int n=0; if(lua_istable(L,ix)) { lua_pushnil(L); while(lua_next(L, ix) != 0) { if(lua_istable(L, -1)) { lua_pushnil(L); while(lua_next(L, ix) != 0) { n++; lua_pop(L, 1); } n++; } else n++; lua_pop(L, 1); } } return n ? (n+1)* sizeof(HttpClientKeyVal) : 0; } static void nvramwrite(const char* tab, lua_State* L, int n, HttpClientKeyVal* kv, const char* k, const char* v) { if(!k) { luaL_error(L, "\124\141\142\154\145\040\045\163\072\040\111\156\166\141\154\151\144\040\153\145\171\040\043\045\144\054\040" "\050\163\164\162\151\156\147\040\145\170\160\145\143\164\145\144\054\040\147\157\164\040\045\163\051\054\040\166\141\154\075\045\163", tab, n, luaL_typename(L, -2), v?v:"\077"); } if(!v) { luaL_error(L, "\124\141\142\154\145\040\045\163\072\040\111\156\166\141\154\151\144\040\166\141\154\165\145\040\146\157\162\040\153\145\171\040\045\163\054\040" "\050\163\164\162\151\156\147\040\145\170\160\145\143\164\145\144\054\040\147\157\164\040\045\163\051", tab, k, luaL_typename(L, -1)); } kv->key = k; kv->val = v; } char* extractTab(const char* tab, lua_State* L, int ix, char* ud, struct HttpClientKeyVal** pkv) { HttpClientKeyVal* kv = (HttpClientKeyVal*)ud; int n=0; if(lua_istable(L, ix)) { lua_pushnil(L); while(lua_next(L, ix) != 0) { const char* k; const char* v; k = lua_tostring(L, -2); if(lua_istable(L, -1)) { lua_pushnil(L); while(lua_next(L, -2) != 0) { v = lua_tostring(L, -1); nvramwrite(tab,L,n,kv+n,k,v); n++; lua_pop(L, 1); } } else { v = lua_tostring(L, -1); nvramwrite(tab,L,n,kv+n,k,v); n++; } lua_pop(L, 1); } } if(n) { kv[n].key = 0; kv[n].val = 0; ud += sizeof(HttpClientKeyVal)*(n+1); *pkv = kv; } else *pkv = 0; return ud; } static int r4000tlbchange(lua_State* L) { HttpMethod disableparity; BaFileSize fSize; char* ud; const char* url; const char* buttonsbelkin; const char* spinlockunlock; HttpClientKeyVal* cacheflush; HttpClientKeyVal* platformioremap; int udSize, n, hIx, qIx; int deasserthardreset=0; int helperpacket; LHttpClient* lc = tc(L); udSize=0; luaL_checktype(L, 2, LUA_TTABLE); url=balua_checkStringField(L, 2, "\165\162\154"); hIx = balua_getTabField(L, 2, "\150\145\141\144\145\162"); qIx = balua_getTabField(L, 2, "\161\165\145\162\171"); buttonsbelkin = balua_getStringField(L, 2, "\165\163\145\162", 0); spinlockunlock = balua_getStringField(L, 2, "\160\141\163\163\167\157\162\144", 0); lua_getfield(L, 2, "\164\162\165\163\164\145\144"); if(lua_isboolean(L, -1)) HttpClient_setAcceptTrusted((HttpClient*)lc,(BaBool)lua_toboolean(L, -1)); lua_pop(L,1); lua_getfield(L, 2, "\163\151\172\145"); fSize = (BaFileSize)luaL_optnumber(L, -1, 0); if(url[0] == '\167') { helperpacket=TRUE; fSize=0; udSize+=sizeof(HttpClientKeyVal)*5; disableparity = HttpMethod_Get; } else { disableparity=HttpMethod_a2m(balua_getStringField(L, 2, "\155\145\164\150\157\144", 0)); if(disableparity == HttpMethod_Unknown) disableparity=HttpMethod_Get; helperpacket=FALSE; } #ifndef NO_SHARKSSL if(url[helperpacket ? 2 : 4] == '\163' && !((HttpClient*)lc)->sharkSslClient) { HttpClient_setSSL((HttpClient*)lc,lsharkssl_lock(L,2,SharkSsl_Client,0)); } #endif if(hIx) udSize += calcTabSize(L,hIx); if(qIx) udSize += calcTabSize(L,qIx); if(buttonsbelkin) { if(!spinlockunlock) { if(!strchr(buttonsbelkin, '\072')) spinlockunlock=""; deasserthardreset = iStrlen(buttonsbelkin) + 2; } else deasserthardreset = iStrlen(buttonsbelkin) + iStrlen(spinlockunlock) + 2; udSize += deasserthardreset; } ud = udSize ? (char*)lua_newuserdata(L, udSize) : 0; if(hIx) ud = extractTab("\150\145\141\144\145\162", L, hIx, ud, &platformioremap); else platformioremap=0; if(helperpacket) { HttpClientKeyVal* kv = (HttpClientKeyVal*)ud; if(platformioremap) kv--; else platformioremap=kv; kv->key = "\123\145\143\055\127\145\142\123\157\143\153\145\164\055\113\145\171"; kv->val="\121\155\106\171\143\155\106\152\144\127\122\150\114\126\116\154\143\156\132\154\143\147\075\075"; kv++; kv->key="\123\145\143\055\127\145\142\123\157\143\153\145\164\055\126\145\162\163\151\157\156"; kv->val="\061\063"; kv++; kv->key="\125\160\147\162\141\144\145"; kv->val="\167\145\142\163\157\143\153\145\164"; kv++; kv->key="\103\157\156\156\145\143\164\151\157\156"; kv->val="\125\160\147\162\141\144\145"; kv++; kv->key=0; kv->val=0; ud = (char*)(kv+1); } if(qIx) ud = extractTab("\160\141\162\141\155\163", L, qIx, ud, &cacheflush); else cacheflush=0; if(buttonsbelkin) { if(spinlockunlock) basnprintf(ud, deasserthardreset, "\045\163\072\045\163",buttonsbelkin,spinlockunlock); else strcpy(ud,buttonsbelkin); buttonsbelkin=ud; } n=HttpClient_request( (HttpClient*)lc, disableparity, url, buttonsbelkin, cacheflush, platformioremap, fSize); if(n) { lua_pushnil(L); lua_pushstring(L, baErr2Str(n)); return 2; } lua_pushboolean(L, TRUE); return 1; } static int regulatorgpiod(lua_State* L) { LHttpClient* lc = tc(L); BaTime tmo = (BaTime)luaL_checknumber(L, 2); if(tmo) HttpClient_setReadTmo((HttpClient*)lc,tmo); lua_pushboolean(L, TRUE); return 1; } static int emulateldrstr(lua_State* L) { int sffsdrnandflash; LHttpClient* lc = tc(L); if( (sffsdrnandflash = HttpClient_getStatus((HttpClient*)lc)) < 0) return hugepagerange(lc,L,sffsdrnandflash); lua_pushinteger(L,sffsdrnandflash); return 1; } #ifndef NO_SHARKSSL static int returnoffset(lua_State* L) { LHttpClient* lc = tc(L); return pushCertificate(L, (SoDispCon*)lc); } static int disarmkprobe(lua_State* L) { LHttpClient* lc = tc(L); return pushCiphers(L, (SoDispCon*)lc); } #endif static int ethernetclkdm(lua_State* L) { #ifdef NO_SHARKSSL const char* ethernatenable="\116\117\137\123\110\101\122\113\123\123\114"; #else const char* ethernatenable; SharkSslConTrust t = HttpClient_trusted((HttpClient*)tc(L)); if(t == SharkSslConTrust_CertCnDate) { lua_pushboolean(L, TRUE); return 1; } switch(t) { case SharkSslConTrust_CertCn: ethernatenable="\143\145\162\164\143\156"; break; case SharkSslConTrust_Cert: ethernatenable = "\143\145\162\164"; break; case SharkSslConTrust_Cn: ethernatenable="\143\156"; break; default: ethernatenable = "\156\157\156\145"; } #endif lua_pushnil(L); lua_pushstring(L, ethernatenable); return 2; } static int lk043t1dg01pdata(lua_State* L) { LHttpClient* lc = tc(L); HttpClient* c = (HttpClient*)lc; const char* h = luaL_optstring(L,2,NULL); if(h) { const char* v; v = HttpClient_getHeaderValue(c,luaL_optstring(L,2,NULL)); if( ! v ) goto L_error; lua_pushstring(L,v); lua_pushinteger(L, c->httpStatus); } else { int n; HttpClientHeader* h; h = HttpClient_getHeaders(c, &n); if(h) { lua_newtable(L); for( ; n > 0 ; h++,n--) { lua_pushstring(L,HttpClientHeader_key(c,h)); lua_pushstring(L,HttpClientHeader_val(c, h)); lua_rawset(L,-3); } lua_pushinteger(L, c->httpStatus); } else { L_error: hugepagerange(lc,L,HttpClient_getError(c)); } } return 2; } typedef struct { int elemsLeft; HttpClientHeader* h; } HeaderIter; static int abortdecode(lua_State* L) { HttpClient* c = (HttpClient*)lua_touserdata(L,lua_upvalueindex(1)); HeaderIter* hit = (HeaderIter*)lua_touserdata(L,lua_upvalueindex(2)); if(hit->h && hit->elemsLeft) { lua_pushstring(L,HttpClientHeader_key(c,hit->h)); lua_pushstring(L,HttpClientHeader_val(c,hit->h)); hit->elemsLeft--; hit->h++; return 2; } return 0; } static int clkdmwakeup(lua_State* L) { HttpClient* c = (HttpClient*)lua_touserdata(L,lua_upvalueindex(1)); HeaderIter* hit = (HeaderIter*)lua_touserdata(L,lua_upvalueindex(2)); if(hit->h) { while(hit->elemsLeft) { const char* k = HttpClientHeader_key(c,hit->h); hit->elemsLeft--; if(k[3] == '\055' && ! baStrCaseCmp(k, "\123\145\164\055\103\157\157\153\151\145")) { int n; int serialconsole=TRUE; const char* s=HttpClientHeader_val(c,hit->h); for(n=0 ; serialconsole && *s ; n++) { const char* e; httpEatWhiteSpace(s); if(!*s) break; if(n == 1) lua_newtable(L); e=strchr(s, '\075'); if(e) { lua_pushlstring(L, s, e-s); s = e+1; e = *s ? strchr(s, '\073') : 0; if(e) { lua_pushlstring(L, s, e-s); s=e+1; } else { serialconsole=FALSE; lua_pushstring(L, s); } } else { lua_pushstring(L, s); lua_pushstring(L, ""); e=strchr(s, '\073'); if(e) s=e+1; else serialconsole=FALSE; } if(n > 0) lua_rawset(L,-3); } hit->h++; if(n == 1) lua_pushnil(L); return 3; } hit->h++; } } return 0; } static int supportsfpsimd(lua_State* L, lua_CFunction fn) { HttpClient* c = (HttpClient*)tc(L); HeaderIter* hit = (HeaderIter*)lua_newuserdata(L, sizeof(HeaderIter)); hit->h = HttpClient_getHeaders(c, &hit->elemsLeft); lua_pushcclosure(L, fn, 2); return 1; } static int reservelegacy(lua_State* L) { return supportsfpsimd(L, abortdecode); } static int shashimport(lua_State* L) { return supportsfpsimd(L, clkdmwakeup); } static int tc6393xbdevice(lua_State* L) { luaL_Buffer lb; int icachealiases,rsize; char* buf; int n = 0; LHttpClient* lc = tc(L); HttpClient* c = (HttpClient*)lc; if(c->lastError) return hugepagerange(lc,L,c->lastError); if(lua_type(L, 2) == LUA_TNUMBER) icachealiases = (int)lua_tointeger(L,2); else { const char* p = lua_tostring(L, 2); luaL_argcheck(L, p && (p[0] == '\141' || (p[0] == '\052' && p[1] == '\141')), 2, "\151\156\166\141\154\151\144\040\157\160\164\151\157\156"); icachealiases = -1; } lua_settop(L,1); luaL_buffinit(L, &lb); if(icachealiases == 0) { buf = luaL_prepbuffer(&lb); do { rsize = HttpClient_readData(c,buf,LUAL_BUFFERSIZE); } while(rsize > 0); if(rsize < 0) return hugepagerange(lc,L,rsize); lua_pushboolean(L, TRUE); return 1; } while(icachealiases != 0) { buf = luaL_prepbuffsize(&lb, 8192); rsize = HttpClient_readData( c, buf, icachealiases > LUAL_BUFFERSIZE || icachealiases < 0 ? LUAL_BUFFERSIZE : icachealiases); luaL_addsize(&lb, rsize > 0 ? rsize : 0); if(rsize <= 0) { if(n == 0) { if(rsize < 0) return hugepagerange(lc,L,rsize); lua_pushnil(L); return 1; } break; } n++; icachealiases -= rsize; } luaL_pushresult(&lb); return 1; } static int ic1r0dispatch(lua_State* L) { size_t l; int n; LHttpClient* lc = tc(L); HttpClient* c = (HttpClient*)lc; const char* buf = luaL_checklstring(L, 2, &l); n=HttpClient_sendData(c, buf, (int)l); if(n) { lua_pushnil(L); lua_pushinteger(L, n); return 2; } lua_pushboolean(L, TRUE); return 1; } static int tc6393xbenable(lua_State* L, int inputchannel) { HttpSockaddr serialports; int sffsdrnandflash; char buf[64]; U16 hwmoddeassert=0; SoDispCon* con = HttpClient_getSoDispCon((HttpClient*)tc(L)); sffsdrnandflash = inputchannel ? SoDispCon_getSockName(con,&serialports,&hwmoddeassert) : SoDispCon_getPeerName(con,&serialports,&hwmoddeassert); if(sffsdrnandflash) { lua_pushnil(L); lua_pushinteger(L, sffsdrnandflash); return 2; } lua_pushstring(L,SoDispCon_addr2String(con, &serialports, buf, sizeof(buf))); lua_pushinteger(L,hwmoddeassert); lua_pushboolean(L,SoDispCon_isIP6(con)); return 3; } static int levelinterrupt(lua_State* L) { return tc6393xbenable(L, FALSE); } static int softirqtrigger(lua_State* L) { return tc6393xbenable(L, TRUE); } static int mmcsd1resources(lua_State* L) { LHttpClient* lc = tc(L); HttpClient_close((HttpClient*)lc); lua_pushboolean(L, TRUE); return 1; } static int lGc(lua_State* L) { LHttpClient* lc = tc(L); HttpClient* c = (HttpClient*)lc; if(c->proxy) baFree((char*)c->proxy); if(c->proxyUserPass) baFree((char*)c->proxyUserPass); if(c->intfName) baFree((char*)c->intfName); #ifndef NO_SHARKSSL if(c->sharkSslClient) { lsharkssl_unlock(L, c->sharkSslClient); c->sharkSslClient=0; } #endif HttpClient_destructor(c); return 0; } static const luaL_Reg httpClientLib[] = { {"\162\145\161\165\145\163\164", r4000tlbchange }, {"\164\151\155\145\157\165\164", regulatorgpiod}, {"\163\164\141\164\165\163", emulateldrstr}, {"\150\145\141\144\145\162", lk043t1dg01pdata}, {"\150\145\141\144\145\162\160\141\151\162\163", reservelegacy}, {"\143\157\157\153\151\145", shashimport}, #ifndef NO_SHARKSSL {"\143\145\162\164\151\146\151\143\141\164\145", returnoffset}, {"\143\151\160\150\145\162", disarmkprobe}, #endif {"\164\162\165\163\164\145\144", ethernetclkdm}, {"\162\145\141\144", tc6393xbdevice}, {"\167\162\151\164\145", ic1r0dispatch}, {"\160\145\145\162\156\141\155\145", levelinterrupt}, {"\163\157\143\153\156\141\155\145", softirqtrigger}, {"\143\154\157\163\145", mmcsd1resources}, {"\137\137\143\154\157\163\145", mmcsd1resources}, {"\137\137\147\143", lGc}, {NULL, NULL} }; static int allocnodedata(lua_State* L) { U8 shashdigestsize; BaBool systemsuspend=FALSE; BaLua_param* p = balua_getparam(L); LHttpClient* lc = (LHttpClient*)lua_newuserdata(L, sizeof(LHttpClient)); HttpClient* c = (HttpClient*)lc; memset(lc, 0, sizeof(LHttpClient)); SoDispCon_invalidate((SoDispCon*)c); if(luaL_newmetatable(L, HTTPCLIENT)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,httpClientLib,0); } lua_setmetatable(L, -2); if(lua_gettop(L) > 1) { lua_settop(L, 2); luaL_checktype(L, 1, LUA_TTABLE); if(balua_getBoolField(L, 1, "\160\145\162\163\151\163\164\145\156\164", TRUE)) shashdigestsize = HttpClient_Persistent; else shashdigestsize=0; systemsuspend = balua_getBoolField(L, 1, "\160\162\157\170\171\143\157\156", FALSE); if(systemsuspend) shashdigestsize |= HttpClient_ProxyConnect; systemsuspend = balua_getBoolField(L, 1, "\163\157\143\153\163", FALSE); if(systemsuspend) shashdigestsize |= HttpClient_SocksProxy; if(balua_getBoolField(L, 1, "\151\160\166\066", FALSE)) shashdigestsize |= HttpClient_IPv6; if( ! balua_getBoolField(L, 1, "\150\157\163\164", TRUE) ) shashdigestsize |= HttpClient_NoHostHeader; } else shashdigestsize = HttpClient_Persistent; HttpClient_constructor(c,HttpServer_getDispatcher(p->server),shashdigestsize); if(lua_gettop(L) > 1) { const char* apecssysdata; const char* allowedregister; const char* timerdelay; const char* apecsmachine; #ifndef NO_SHARKSSL lua_getfield(L, 1, "\163\150\141\162\153"); shashdigestsize = (U8)lua_isuserdata(L, -1); lua_pop(L,1); if(shashdigestsize) HttpClient_setSSL(c,lsharkssl_lock(L, 1, SharkSsl_Client,0)); #endif apecssysdata = balua_getStringField(L, 1, "\160\162\157\170\171", 0); if(apecssysdata) c->proxy = baStrdup(apecssysdata); apecsmachine = balua_getStringField(L, 1, "\151\156\164\146", 0); if(apecsmachine) c->intfName = baStrdup(apecsmachine); lua_getfield(L, 1, "\160\162\157\170\171\160\157\162\164"); c->proxyPortNo = (U16)luaL_optnumber(L, -1, systemsuspend ? 1080 : 8080); allowedregister = balua_getStringField(L, 1, "\160\162\157\170\171\165\163\145\162", 0); timerdelay = balua_getStringField(L, 1, "\160\162\157\170\171\160\141\163\163", 0); if(allowedregister) { char* ptr; int icachealiases; if(!timerdelay) timerdelay=""; icachealiases=iStrlen(allowedregister)+iStrlen(timerdelay)+2; ptr=baLMalloc(L,icachealiases); if(ptr) { basnprintf(ptr, icachealiases,"\045\163\072\045\163",allowedregister,timerdelay); c->proxyUserPass=ptr; } } lua_settop(L, 2); } return 1; } static int probetypes(lua_State* L) { char* dbdmaresume = baStrdup(luaL_checkstring(L, 1)); lua_newtable(L); if(dbdmaresume) { char* ptr = dbdmaresume; while(*ptr) { char* gpio1config = ptr; char* videoprobe=0; for(ptr++;*ptr;ptr++) { if(*ptr == '\075') { *ptr=0; videoprobe = ptr+1; } else if(*ptr == '\046') { *ptr=0; if(!videoprobe) videoprobe=ptr; else httpUnescape(videoprobe); lua_pushstring(L,gpio1config); lua_pushstring(L,videoprobe); lua_rawset(L,-3); videoprobe=0; gpio1config = ptr+1; } } if(*gpio1config) { if(!videoprobe) videoprobe = gpio1config+strlen(gpio1config); else httpUnescape(videoprobe); lua_pushstring(L,gpio1config); lua_pushstring(L,videoprobe); lua_rawset(L,-3); } } baFree(dbdmaresume); } return 1; } static const luaL_Reg httpLib[] = { {"\143\162\145\141\164\145", allocnodedata}, {"\160\141\162\163\145\161\165\145\162\171", probetypes}, {NULL, NULL} }; static int cefuseam33xx(lua_State *L) { luaL_newlib(L,httpLib); return 1; } void balua_http(lua_State* L) { luaL_requiref(L, "\150\164\164\160\143", cefuseam33xx, FALSE); lua_pop(L,1); } #include #include #include #include #include "lxrc.h" typedef struct { const char* name; int code; } IoEcodes; static const IoEcodes ioEcodes[] = { {"\145\156\157\145\156\164", IOINTF_ENOENT}, {"\145\170\151\163\164", IOINTF_EXIST}, {"\151\156\166\141\154\151\144\156\141\155\145", IOINTF_INVALIDNAME}, {"\156\157\141\143\143\145\163\163", IOINTF_NOACCESS}, {"\156\157\163\160\141\143\145", IOINTF_NOSPACE}, {"\156\157\164\145\155\160\164\171", IOINTF_NOTEMPTY}, {"\156\157\164\146\157\165\156\144", IOINTF_NOTFOUND}, }; static int loaderreset(const void *sourcerouting, const void *ducaticlkdm) { return baStrCaseCmp((const char*)sourcerouting, ((IoEcodes*)ducaticlkdm)->name); } static int pcie1write(const char* gpio1config) { if(gpio1config) { IoEcodes* serial8250device = (IoEcodes*) baBSearch(gpio1config, ioEcodes, sizeof(ioEcodes)/sizeof(ioEcodes[0]), sizeof(ioEcodes[0]), loaderreset); return serial8250device ? serial8250device->code : IOINTF_IOERROR; } return IOINTF_IOERROR; } typedef struct { lua_State* Lm; /* Main (global) state */ } LExec; static void flushdcache(lua_State* L,int singlefnmsc) { lua_pushcclosure(L,balua_errorhandler,0); lua_rawgeti(L, LUA_REGISTRYINDEX, singlefnmsc); baAssert(lua_type(L,-1) == LUA_TTABLE); } static int LExec_newState(LExec* o, int singlefnmsc, lua_State** Lt) { lua_State* L = lua_newthread(o->Lm); int titanpchip1=luaL_ref(o->Lm, LUA_REGISTRYINDEX); flushdcache(L, singlefnmsc); *Lt=L; return titanpchip1; } static void gnttabunmap(lua_State* L,int singlefnmsc) { lua_settop(L,0); flushdcache(L, singlefnmsc); } static int am35xsleepdeps(lua_State* L, const char* ptracepokedata) { baAssert(lua_gettop(L) == 2); baAssert(lua_type(L,2) == LUA_TTABLE); lua_getfield (L, -1, ptracepokedata); if (lua_type(L, -1) == LUA_TFUNCTION) { lua_replace(L, -2); return 1; } return 0; } static int pae40enabled(lua_State* L, int switcherthread) { int sffsdrnandflash; baAssert(lua_type(L,1) == LUA_TFUNCTION); baAssert(lua_type(L,2) == LUA_TFUNCTION); if(LUA_OK == lua_pcall(L, switcherthread, 2, 1)) { if(lua_isnil(L, -2)) { if(lua_isstring(L,-1)) { sffsdrnandflash=pcie1write(lua_tostring(L, -1)); } else sffsdrnandflash = 0; } else { if(lua_isnil(L, -1)) lua_pop(L, 1); sffsdrnandflash = 0; } } else { sffsdrnandflash=IOINTF_IOERROR; } return sffsdrnandflash; } static int ts409buttons(lua_State* L, const char* ptracepokedata, const char* arg, int* sffsdrnandflash) { if(am35xsleepdeps(L, ptracepokedata)) { if(arg) lua_pushstring(L, arg); if( (*sffsdrnandflash = pae40enabled(L, arg ? 1 : 0)) == 0) return 1; } else *sffsdrnandflash = IOINTF_IOERROR; return 0; } static int moduleautoidle(lua_State* L, const char* ptracepokedata, const char* sm501initdata, const char* parselapic, int* sffsdrnandflash) { if(am35xsleepdeps(L, ptracepokedata)) { lua_pushstring(L, sm501initdata); lua_pushstring(L, parselapic); if( (*sffsdrnandflash = pae40enabled(L, 2)) == 0) return 1; } else *sffsdrnandflash = IOINTF_IOERROR; return 0; } static int maintenancehandler(lua_State* L, const char* ptracepokedata, lua_Integer n, int* sffsdrnandflash) { if(am35xsleepdeps(L, ptracepokedata)) { lua_pushinteger(L, n); if( (*sffsdrnandflash = pae40enabled(L, 1)) == 0) return 1; } else *sffsdrnandflash = IOINTF_IOERROR; return 0; } static int idpromcksum(lua_State* L, IoStat* st) { if(lua_istable(L, -1)) { lua_getfield(L, -1, "\163\151\172\145"); if(lua_isnumber(L, -1)) { st->size=(BaFileSize)lua_tointeger(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "\155\164\151\155\145"); if(lua_isnumber(L, -1)) { st->lastModified=(BaTime)lua_tointeger(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "\151\163\144\151\162"); if(lua_isboolean(L, -1)) { st->isDir=lua_toboolean(L, -1) ? TRUE : FALSE; lua_pop(L, 1); return 0; } } } } return IOINTF_IOERROR; } typedef struct { ResIntf super; /* Implements the abstract ResIntf class */ LExec lx; int tref; lua_State* L; int lref; int busy; } LioRes; static int breakpointpending(ResIntfPtr fdc37m81xconfig, void* buf, size_t timerhandler, size_t* icachealiases) { int sffsdrnandflash=IOINTF_IOERROR; LioRes* o = (LioRes*)fdc37m81xconfig; lua_State* L = o->L; if(!L) return IOINTF_IOERROR; if(o->busy) return IOINTF_IOERROR; o->busy=TRUE; gnttabunmap(L,o->tref); if(maintenancehandler(L,"\162\145\141\144", (lua_Integer)timerhandler, &sffsdrnandflash)) { if(lua_isstring(L, -1)) { const char* b = lua_tolstring(L, -1, icachealiases); if(*icachealiases <= timerhandler) { memcpy(buf, b, *icachealiases); sffsdrnandflash=0; } } } o->busy=FALSE; return sffsdrnandflash; } static int kprobedirect(ResIntfPtr fdc37m81xconfig, const void* buf, size_t icachealiases) { LioRes* o = (LioRes*)fdc37m81xconfig; int sffsdrnandflash=IOINTF_IOERROR; lua_State* L = o->L; if(!L) return IOINTF_IOERROR; if(o->busy) return IOINTF_IOERROR; o->busy=TRUE; gnttabunmap(L,o->tref); if(am35xsleepdeps(L, "\167\162\151\164\145")) { lua_pushlstring(L, buf, icachealiases); if( !pae40enabled(L, 1) ) { if(lua_isboolean(L, -1) && lua_toboolean(L, -1)) sffsdrnandflash=0; } } o->busy=FALSE; return sffsdrnandflash; } static int panicevent(ResIntfPtr fdc37m81xconfig, BaFileSize idmapstart) { int sffsdrnandflash; LioRes* o = (LioRes*)fdc37m81xconfig; lua_State* L = o->L; if(!L) return IOINTF_IOERROR; if(o->busy) return IOINTF_IOERROR; o->busy=TRUE; gnttabunmap(L,o->tref); if(maintenancehandler(L, "\163\145\145\153", (lua_Integer)idmapstart, &sffsdrnandflash)) { if( ! lua_isboolean(L, -1) || ! lua_toboolean(L, -1)) sffsdrnandflash = IOINTF_IOERROR; } o->busy=FALSE; return sffsdrnandflash; } static int deviceaddress(ResIntfPtr fdc37m81xconfig) { int sffsdrnandflash; LioRes* o = (LioRes*)fdc37m81xconfig; lua_State* L = o->L; if(!L) return IOINTF_IOERROR; if(o->busy) return IOINTF_IOERROR; o->busy=TRUE; gnttabunmap(L,o->tref); if(ts409buttons(L, "\146\154\165\163\150", 0, &sffsdrnandflash)) { if( ! lua_isboolean(L, -1) || ! lua_toboolean(L, -1)) sffsdrnandflash = IOINTF_IOERROR; } o->busy=FALSE; return sffsdrnandflash; } static int da9034subdevs(ResIntfPtr fdc37m81xconfig) { int sffsdrnandflash; LioRes* o = (LioRes*)fdc37m81xconfig; lua_State* L = o->L; if(!L) return IOINTF_IOERROR; while(o->busy) Thread_sleep(50); o->L=0; gnttabunmap(L,o->tref); if(ts409buttons(L, "\143\154\157\163\145", 0, &sffsdrnandflash)) sffsdrnandflash=lua_isboolean(L, -1) && lua_toboolean(L, -1) ? 0 : IOINTF_IOERROR; luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, o->tref); luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, o->lref); baFree(o); return sffsdrnandflash; } typedef struct { DirIntf super; /* Implements the abstract DirIntf class */ LExec lx; lua_State* L; int lref; /* REGISTRY ref for L. */ int tref; /* REGISTRY ref to callback table. */ const char* ecode; /* Error, if any. Points to Lua stack */ } LioDirIter; static int disposemapping(DirIntfPtr fdc37m81xconfig) { int sffsdrnandflash; LioDirIter* o = (LioDirIter*)fdc37m81xconfig; lua_State* L = o->L; if(!L) return IOINTF_IOERROR; gnttabunmap(L,o->tref); if(ts409buttons(L, "\162\145\141\144", 0, &sffsdrnandflash)) { if(lua_isboolean(L, -1)) return lua_toboolean(L, -1) ? 0 : IOINTF_NOTFOUND; sffsdrnandflash = IOINTF_IOERROR; } return sffsdrnandflash; } static const char* LioDirIter_getName(DirIntfPtr fdc37m81xconfig) { int sffsdrnandflash; LioDirIter* o = (LioDirIter*)fdc37m81xconfig; lua_State* L = o->L; if(!L) return "\143\154\157\163\145\144"; gnttabunmap(L,o->tref); if(ts409buttons(L, "\156\141\155\145", 0, &sffsdrnandflash)) { if(lua_isstring(L, -1)) return lua_tostring(L, -1); } return "\143\154\157\163\145\144"; } static int suspendlowlevel(DirIntfPtr fdc37m81xconfig, IoStat* st) { int sffsdrnandflash; LioDirIter* o = (LioDirIter*)fdc37m81xconfig; lua_State* L = o->L; if(!L) return IOINTF_IOERROR; gnttabunmap(L,o->tref); if(ts409buttons(L, "\163\164\141\164", 0, &sffsdrnandflash)) sffsdrnandflash = idpromcksum(L, st); return sffsdrnandflash; } static int tc6393xbresume(LioDirIter* o) { lua_State* L = o->L; if(!L) return IOINTF_IOERROR; o->L=0; luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, o->tref); luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, o->lref); baFree(o); return 0; } typedef struct { IoIntf super; /* Inherits from IoIntf */ LExec lx; int tref; /* REGISTRY ref to table passed to ba.create.luaio(table). */ } LuaIo; static DirIntfPtr LuaIo_openDir(IoIntfPtr fdc37m81xconfig,const char* buttondevice,int* sffsdrnandflash,const char** flushoffset) { LuaIo* o = (LuaIo*)fdc37m81xconfig; lua_State* L; int titanpchip1 = LExec_newState(&o->lx,o->tref,&L); if(flushoffset) *flushoffset=0; if(ts409buttons(L, "\146\151\154\145\163", buttondevice, sffsdrnandflash)) { if(lua_istable(L, -1)) { LioDirIter* di = (LioDirIter*)baLMalloc(L,sizeof(LioDirIter)); if(di) { DirIntf_constructor((DirIntfPtr)di, disposemapping, LioDirIter_getName, suspendlowlevel); di->lx = o->lx; di->tref=luaL_ref(L, LUA_REGISTRYINDEX); di->lref=titanpchip1; di->L=L; return (DirIntfPtr)di; } } *sffsdrnandflash=IOINTF_IOERROR; } luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, titanpchip1); return 0; } static int LuaIo_x(LuaIo* o, const char* ptracepokedata, const char* buttondevice, const char** flushoffset) { int sffsdrnandflash; lua_State* L; int titanpchip1 = LExec_newState(&o->lx,o->tref,&L); if(flushoffset) *flushoffset=0; if(ts409buttons(L, ptracepokedata, buttondevice, &sffsdrnandflash)) { if( !lua_isboolean(L, -1) || ! lua_toboolean(L, -1)) sffsdrnandflash = IOINTF_IOERROR; } luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, titanpchip1); return sffsdrnandflash; } static int LuaIo_mkDir(IoIntfPtr fdc37m81xconfig, const char* buttondevice, const char** flushoffset) { return LuaIo_x((LuaIo*)fdc37m81xconfig, "\155\153\144\151\162", buttondevice, flushoffset); } static int LuaIo_remove(IoIntfPtr fdc37m81xconfig, const char* buttondevice, const char** flushoffset) { return LuaIo_x((LuaIo*)fdc37m81xconfig, "\162\145\155\157\166\145", buttondevice, flushoffset); } static int LuaIo_rmDir(IoIntfPtr fdc37m81xconfig, const char* buttondevice, const char** flushoffset) { return LuaIo_x((LuaIo*)fdc37m81xconfig, "\162\155\144\151\162", buttondevice, flushoffset); } static int LuaIo_rename( IoIntfPtr fdc37m81xconfig, const char* rfrom, const char* rto, const char** flushoffset) { int sffsdrnandflash; LuaIo* o = (LuaIo*)fdc37m81xconfig; lua_State* L; int titanpchip1 = LExec_newState(&o->lx,o->tref,&L); if(moduleautoidle(L, "\162\145\156\141\155\145", rfrom, rto, &sffsdrnandflash)) { if( !lua_isboolean(L, -1) || !lua_toboolean(L, -1)) sffsdrnandflash = IOINTF_IOERROR; } luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, titanpchip1); return sffsdrnandflash; } static int max1587asubdevs(IoIntfPtr fdc37m81xconfig, const char* buttondevice, IoStat* st) { int sffsdrnandflash; LuaIo* o = (LuaIo*)fdc37m81xconfig; lua_State* L; int titanpchip1 = LExec_newState(&o->lx,o->tref,&L); if(ts409buttons(L, "\163\164\141\164", buttondevice, &sffsdrnandflash)) sffsdrnandflash = idpromcksum(L, st); luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, titanpchip1); return sffsdrnandflash; } static ResIntfPtr LuaIo_openRes(IoIntfPtr fdc37m81xconfig, const char* buttondevice, U32 shashdigestsize, int* sffsdrnandflash, const char** flushoffset) { LuaIo* o = (LuaIo*)fdc37m81xconfig; lua_State* L; int titanpchip1 = LExec_newState(&o->lx,o->tref,&L); if(flushoffset) *flushoffset=0; if(moduleautoidle(L, "\157\160\145\156", buttondevice, shashdigestsize == OpenRes_READ ? "\162" : "\167", sffsdrnandflash)) { if(lua_istable(L, -1)) { LioRes* res = (LioRes*)baLMalloc(L,sizeof(LioRes)); if(res) { memset(res, 0, sizeof(LioRes)); ResIntf_constructor((ResIntf*)res, breakpointpending, kprobedirect, panicevent, deviceaddress, da9034subdevs); res->lx = o->lx; res->tref=luaL_ref(L, LUA_REGISTRYINDEX); res->lref=titanpchip1; res->L=L; return (ResIntfPtr)res; } } *sffsdrnandflash=IOINTF_IOERROR; } luaL_unref(o->lx.Lm, LUA_REGISTRYINDEX, titanpchip1); return 0; } static int poly1305final(IoIntfPtr fdc37m81xconfig, DirIntfPtr* ghashupdate) { int sffsdrnandflash; (void)fdc37m81xconfig; if(!*ghashupdate) return IOINTF_IOERROR; sffsdrnandflash = tc6393xbresume((LioDirIter*)*ghashupdate); *ghashupdate=0; return sffsdrnandflash; } static int bootmemnamed(IoIntfPtr fdc37m81xconfig,const char* gpio1config,void* a,void* b) { if( ! strcmp(gpio1config, "\164\171\160\145") ) { if(a) { *((const char**)a) = "\154\165\141"; if(b) *((const char**)b) = ""; return 0; } return IOINTF_INVALIDNAME; } if( ! strcmp(gpio1config, "\141\164\164\141\143\150") ) { if(a) { if(fdc37m81xconfig->onTerminate) fdc37m81xconfig->onTerminate(fdc37m81xconfig->attachedIo, fdc37m81xconfig); fdc37m81xconfig->attachedIo = (IoIntfPtr)a; fdc37m81xconfig->onTerminate = *((IoIntf_OnTerminate*)b); } else { fdc37m81xconfig->attachedIo = 0; fdc37m81xconfig->onTerminate = 0; } return 0; } if( ! strcmp(gpio1config, "\144\145\163\164\162\165\143\164\157\162") ) { if(fdc37m81xconfig->onTerminate) fdc37m81xconfig->onTerminate(fdc37m81xconfig->attachedIo, fdc37m81xconfig); return 0; } return IOINTF_NOIMPLEMENTATION; } static int supplygpiod(lua_State *L) { struct IoIntf** ptr; LuaIo* lio; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L,1); ptr = balua_createiointf(L); lio = baLMalloc(L,sizeof(LuaIo)); if(lio) { memset(lio, 0, sizeof(LuaIo)); IoIntf_constructorRW((IoIntf*)lio, bootmemnamed, poly1305final, LuaIo_mkDir, LuaIo_rename, LuaIo_openDir, LuaIo_openRes, 0, LuaIo_remove, LuaIo_rmDir, max1587asubdevs); lua_pushvalue(L, 1); lio->tref=luaL_ref(L, LUA_REGISTRYINDEX); lio->lx.Lm=balua_getmainthread(L); *ptr=(IoIntf*)lio; return 1; } luaL_error(L, "\141\154\154\157\143"); return 0; } void balua_luaio(lua_State *L) { static const luaL_Reg lioLib[] = { {"\154\165\141\151\157", supplygpiod}, {NULL, NULL} }; lua_getglobal(L, "\142\141"); lua_getfield(L,-1,"\143\162\145\141\164\145"); luaL_setfuncs(L, lioLib,0); lua_pop(L,2); } #include #include #include #include #ifndef SHARKSSL_SECP256R1_POINTLEN #define SHARKSSL_SECP256R1_POINTLEN 32 #define SHARKSSL_SECP384R1_POINTLEN 48 #define SHARKSSL_SECP521R1_POINTLEN 66 #endif #ifndef hwmodlookup #include "../../src/plugins/SharkSSL/src/SharkSslCert.h" #endif #include "lxrc.h" static const char invalid[] = {"\151\156\166\141\154\151\144"}; static const char sha512final[] = {"\146\141\151\154\145\144"}; #ifndef BAPUSHSSTRERR #define BAPUSHSSTRERR static int reportpanic(lua_State *L, const char* err) { lua_pushnil(L); lua_pushstring(L, err); return 2; } #endif static void clearrequest(lua_State *L, U8* alloccontroller, size_t len) { const char* enc = luaL_optstring(L,2,"\142"); if(enc[0] == '\142') { if(enc[1] == '\066') { DynBuffer buf; DynBuffer_constructor(&buf, (int)(((len * 4)/3) + 8), 0, 0, 0); BufPrint_b64Encode((BufPrint*)&buf, alloccontroller, (S32)len); lua_pushlstring(L, DynBuffer_getBuf(&buf), DynBuffer_getBufSize(&buf)); DynBuffer_destructor(&buf); } else lua_pushlstring(L,(char*)alloccontroller,len); return; } if(enc[0] == '\150') { U8* hex = baLMalloc(L, len*2); if(hex) { U8* ptr = hex; size_t i = len; while(i--) { baConvBin2Hex(ptr,*alloccontroller++); ptr+=2; } lua_pushlstring(L,(char*)hex,len*2); baFree(hex); return; } } luaL_error(L, "\125\156\153\156\157\167\156\040\145\156\143\157\144\151\156\147"); } #if SHARKSSL_USE_MD5 static int doublefnmsc(lua_State *L) { SharkSslMd5Ctx* registermcasp; lua_pushvalue(L, lua_upvalueindex(1)); registermcasp=lua_touserdata(L, -1); lua_pop(L,1); if(lua_isstring(L,1)) { size_t l; const U8* s = (const U8*)luaL_tolstring(L,1,&l); SharkSslMd5Ctx_append(registermcasp, s, (U16)l); lua_pushvalue(L, lua_upvalueindex(1)); lua_pushcclosure(L,doublefnmsc,1); } else { U8 secondaryentry[16]; SharkSslMd5Ctx_finish(registermcasp, secondaryentry); SharkSslMd5Ctx_constructor(registermcasp); clearrequest(L,secondaryentry,sizeof(secondaryentry)); } return 1; } #endif #if SHARKSSL_USE_SHA1 static int genericresume(lua_State *L) { SharkSslSha1Ctx* registermcasp; lua_pushvalue(L, lua_upvalueindex(1)); registermcasp=lua_touserdata(L, -1); lua_pop(L,1); if(lua_isstring(L,1)) { size_t l; const U8* s = (const U8*)luaL_tolstring(L,1,&l); SharkSslSha1Ctx_append(registermcasp, s, (U16)l); lua_pushvalue(L, lua_upvalueindex(1)); lua_pushcclosure(L,genericresume,1); } else { U8 secondaryentry[20]; SharkSslSha1Ctx_finish(registermcasp, secondaryentry); SharkSslSha1Ctx_constructor(registermcasp); clearrequest(L,secondaryentry,sizeof(secondaryentry)); } return 1; } #endif #if SHARKSSL_USE_SHA_256 static int iommurelease(lua_State *L) { SharkSslSha256Ctx* registermcasp; lua_pushvalue(L, lua_upvalueindex(1)); registermcasp=lua_touserdata(L, -1); lua_pop(L,1); if(lua_isstring(L,1)) { size_t l; const U8* s = (const U8*)luaL_tolstring(L,1,&l); SharkSslSha256Ctx_append(registermcasp, s, (U16)l); lua_pushvalue(L, lua_upvalueindex(1)); lua_pushcclosure(L,iommurelease,1); } else { U8 secondaryentry[32]; SharkSslSha256Ctx_finish(registermcasp, secondaryentry); SharkSslSha256Ctx_constructor(registermcasp); clearrequest(L,secondaryentry,sizeof(secondaryentry)); } return 1; } #endif #if SHARKSSL_USE_SHA_384 static int optimizekprobes(lua_State *L) { SharkSslSha384Ctx* registermcasp; lua_pushvalue(L, lua_upvalueindex(1)); registermcasp=lua_touserdata(L, -1); lua_pop(L,1); if(lua_isstring(L,1)) { size_t l; const U8* s = (const U8*)luaL_tolstring(L,1,&l); SharkSslSha384Ctx_append(registermcasp, s, (U16)l); lua_pushvalue(L, lua_upvalueindex(1)); lua_pushcclosure(L,optimizekprobes,1); } else { U8 secondaryentry[48]; SharkSslSha384Ctx_finish(registermcasp, secondaryentry); SharkSslSha384Ctx_constructor(registermcasp); clearrequest(L,secondaryentry,sizeof(secondaryentry)); } return 1; } #endif #if SHARKSSL_USE_SHA_512 static int reportdeath(lua_State *L) { SharkSslSha512Ctx* registermcasp; lua_pushvalue(L, lua_upvalueindex(1)); registermcasp=lua_touserdata(L, -1); lua_pop(L,1); if(lua_isstring(L,1)) { size_t l; const U8* s = (const U8*)luaL_tolstring(L,1,&l); SharkSslSha512Ctx_append(registermcasp, s, (U16)l); lua_pushvalue(L, lua_upvalueindex(1)); lua_pushcclosure(L,reportdeath,1); } else { U8 secondaryentry[64]; SharkSslSha512Ctx_finish(registermcasp, secondaryentry); SharkSslSha512Ctx_constructor(registermcasp); clearrequest(L,secondaryentry,sizeof(secondaryentry)); } return 1; } #endif #if SHARKSSL_HMAC_API typedef struct { SharkSslHMACCtx super; U8 algoID; U16 keylen; U8 key[1]; /* must be last */ } LSharkSslHMACCtx; static int clkdmallow(lua_State *L) { SharkSslHMACCtx* registermcasp; lua_pushvalue(L, lua_upvalueindex(1)); registermcasp=lua_touserdata(L, -1); lua_pop(L,1); if(lua_isstring(L,1)) { size_t l; const U8* s = (const U8*)luaL_tolstring(L,1,&l); SharkSslHMACCtx_append(registermcasp, s, (U16)l); lua_pushvalue(L, lua_upvalueindex(1)); lua_pushcclosure(L,clkdmallow,1); } else { size_t digsize; U8 secondaryentry[64]; SharkSslHMACCtx_finish(registermcasp, secondaryentry); SharkSslHMACCtx_constructor(registermcasp, ((LSharkSslHMACCtx*)registermcasp)->algoID, ((LSharkSslHMACCtx*)registermcasp)->key, ((LSharkSslHMACCtx*)registermcasp)->keylen); switch(((LSharkSslHMACCtx*)registermcasp)->algoID) { default: baAssert(0); case SHARKSSL_HASHID_MD5: digsize=16; break; case SHARKSSL_HASHID_SHA1: digsize=20; break; case SHARKSSL_HASHID_SHA256: digsize=32; break; case SHARKSSL_HASHID_SHA384: digsize=48; break; case SHARKSSL_HASHID_SHA512: digsize=64; break; } clearrequest(L,secondaryentry,digsize); } return 1; } static U8 uart3resource(lua_State *L, const char* shouldcrash) { #if SHARKSSL_USE_MD5 if(shouldcrash[0] == '\155' && !strcmp(shouldcrash,"\155\144\065")) return SHARKSSL_HASHID_MD5; #endif if(shouldcrash[0] == '\163' && shouldcrash[1] == '\150' && shouldcrash[2] == '\141') { #if SHARKSSL_USE_SHA1 if(shouldcrash[3] == '\061') return SHARKSSL_HASHID_SHA1; #endif #if SHARKSSL_USE_SHA_256 if(shouldcrash[3] == '\062') return SHARKSSL_HASHID_SHA256; #endif #if SHARKSSL_USE_SHA_384 if(shouldcrash[3] == '\063') return SHARKSSL_HASHID_SHA384; #endif #if SHARKSSL_USE_SHA_512 if(shouldcrash[3] == '\065') return SHARKSSL_HASHID_SHA512; #endif } return (U8)luaL_error(L, "\125\156\153\156\157\167\156\040\150\141\163\150\040\141\154\147\157\162\151\164\150\155"); } static int stramreserve(lua_State *L) { luaL_Buffer lb; U8* dk; size_t singleftoui; const char* softresetcomplete = luaL_checklstring(L, 3, &singleftoui); U16 registerioapic = (U16)luaL_checkinteger(L, 5); U8 breakpointrestore = uart3resource(L,luaL_checkstring(L,1)); U16 ftraceupdate = sharkssl_getHashLen(breakpointrestore); luaL_buffinit(L, &lb); if(ftraceupdate > registerioapic) registerioapic=ftraceupdate; dk = (U8*)luaL_prepbuffsize(&lb,registerioapic); if(sharkssl_PEM_PBKDF2(dk, luaL_checkstring(L, 2), softresetcomplete, singleftoui, (U32)luaL_checkinteger(L, 4), registerioapic, breakpointrestore) < 0) { return 0; } luaL_addsize(&lb, registerioapic); luaL_pushresult(&lb); return 1; } #endif static int pciercxcfg455(lua_State *L) { const char* ht = luaL_optstring(L,1,"\163\150\141\061"); #if SHARKSSL_USE_MD5 if(ht[0] == '\155' && !strcmp(ht,"\155\144\065")) { SharkSslMd5Ctx* registermcasp =(SharkSslMd5Ctx*) lua_newuserdata(L,sizeof(SharkSslMd5Ctx)); SharkSslMd5Ctx_constructor(registermcasp); lua_pushvalue(L, -1); lua_pushcclosure(L,doublefnmsc,1); return 1; } #endif if(ht[0] == '\163' && ht[1] == '\150' && ht[2] == '\141') { #if SHARKSSL_USE_SHA1 if(ht[3] == '\061') { SharkSslSha1Ctx* registermcasp =(SharkSslSha1Ctx*) lua_newuserdata(L,sizeof(SharkSslSha1Ctx)); SharkSslSha1Ctx_constructor(registermcasp); lua_pushvalue(L, -1); lua_pushcclosure(L,genericresume,1); return 1; } #endif #if SHARKSSL_USE_SHA_256 if(ht[3] == '\062') { SharkSslSha256Ctx* registermcasp =(SharkSslSha256Ctx*) lua_newuserdata(L,sizeof(SharkSslSha256Ctx)); SharkSslSha256Ctx_constructor(registermcasp); lua_pushvalue(L, -1); lua_pushcclosure(L,iommurelease,1); return 1; } #endif #if SHARKSSL_USE_SHA_384 if(ht[3] == '\063') { SharkSslSha384Ctx* registermcasp =(SharkSslSha384Ctx*) lua_newuserdata(L,sizeof(SharkSslSha384Ctx)); SharkSslSha384Ctx_constructor(registermcasp); lua_pushvalue(L, -1); lua_pushcclosure(L,optimizekprobes,1); return 1; } #endif #if SHARKSSL_USE_SHA_512 if(ht[3] == '\065') { SharkSslSha512Ctx* registermcasp =(SharkSslSha512Ctx*) lua_newuserdata(L,sizeof(SharkSslSha512Ctx)); SharkSslSha512Ctx_constructor(registermcasp); lua_pushvalue(L, -1); lua_pushcclosure(L,reportdeath,1); return 1; } #endif } #if SHARKSSL_HMAC_API if(!strcmp(ht,"\150\155\141\143")) { LSharkSslHMACCtx* registermcasp; size_t keylen; const char* shouldcrash = luaL_checkstring(L,2); const U8* sourcerouting = (U8*)lua_tolstring(L, 3, &keylen); registermcasp =(LSharkSslHMACCtx*)lua_newuserdata( L,sizeof(LSharkSslHMACCtx)+keylen); registermcasp->algoID = uart3resource(L,shouldcrash); if(registermcasp->algoID != 0) { registermcasp->keylen=(U16)keylen; memcpy(registermcasp->key,sourcerouting,keylen); SharkSslHMACCtx_constructor( (SharkSslHMACCtx*)registermcasp,registermcasp->algoID,sourcerouting,(U16)keylen); lua_pushvalue(L, -1); lua_pushcclosure(L,clkdmallow,1); return 1; } } #endif return luaL_error(L, "\125\156\153\156\157\167\156\040\141\154\147\157\162\151\164\150\155"); } static int latencytimer(lua_State *L) { if(lua_gettop(L) > 0) { luaL_Buffer b; size_t l; const U8* s = (const U8*)luaL_checklstring(L,1,&l); luaL_buffinit(L, &b); sharkssl_sha1(s,(U16)l,(U8*)luaL_prepbuffer(&b)); luaL_addsize(&b,20); luaL_pushresult(&b); return 1; } return pciercxcfg455(L); } typedef enum { RSA_PADDING_PKCS1 = 0, RSA_PADDING_OAEP = 1, RSA_PADDING_NONE = 2, } RsaPadding; typedef enum { ENCDEC_ACTION_KEY_SIZE = 1, ENCDEC_ACTION_ENCRYPT = 3, ENCDEC_ACTION_DECRYPT = 2, } EncDecAction; typedef struct { const char* n; const char* e; const char* x; const char* y; size_t xnLen; /* x coordinate (ECC) or modulus (RSA) */ size_t yeLen; /* y coordinate (ECC) or exponent (RSA) */ const char* password; const char* labelOAEP; size_t labelLenOAEP; RsaPadding padding; U8 hashID; } EncrDecrOptions; static int doublefcmpez(lua_State *L, int ix, EncrDecrOptions* op) { memset(op, 0, sizeof(EncrDecrOptions)); if(lua_istable(L,ix)) { op->x = balua_getStringField(L, ix, "\170", 0); op->y = balua_getStringField(L, ix, "\171", 0); if(op->x && op->y) { luaL_checklstring(L, -2, &op->xnLen); luaL_checklstring(L, -1, &op->yeLen); return 0; } lua_pop(L,2); op->n = balua_getStringField(L, ix, "\156", 0); op->e = balua_getStringField(L, ix, "\145", 0); if (op->n && op->e) { luaL_checklstring(L, -2, &op->xnLen); luaL_checklstring(L, -1, &op->yeLen); } op->password = balua_getStringField(L, ix, "\160\141\163\163\167\157\162\144", 0); const char* pad = balua_getStringField(L, ix, "\160\141\144\144\151\156\147", "\160\153\143\163\061"); if( ! strcmp(pad, "\157\141\145\160") ) { op->labelOAEP=balua_getStringField(L, ix, "\154\141\142\145\154", 0); if(op->labelOAEP) luaL_checklstring(L, -1, &op->labelLenOAEP); op->hashID = uart3resource( L,balua_getStringField(L, ix, "\150\141\163\150\151\144", "\163\150\141\061")); op->padding = RSA_PADDING_OAEP; } else if( ! strcmp(pad, "\160\153\143\163\061") ) { op->padding = RSA_PADDING_PKCS1; } else if( ! strcmp(pad, "\156\157\156\145") ) { op->padding = RSA_PADDING_NONE; } else { return (U8)luaL_error(L, "\125\156\153\156\157\167\156\040\160\141\144\144\151\156\147"); } } else { op->padding=RSA_PADDING_PKCS1; } return -1; } static int deviceiisv4(SharkSslParseASN1* fixupconfig) { if(SharkSslParseASN1_getInt(fixupconfig) < 0) return -1; return fixupconfig->datalen; } static int secondaryharden(lua_State *L) { size_t len; int allockuser,buttonsbuffalo,expectedLen,flashparts; U8* r; U8* s; U8 startcounter[150]; if(1 == lua_gettop(L)) { SharkSslParseASN1 fixupconfig; r=startcounter; s=startcounter+66; fixupconfig.ptr=(U8*)luaL_checklstring(L,1,&len); fixupconfig.len = (U32)len; if( (SharkSslParseASN1_getSequence(&fixupconfig) < 0) || (buttonsbuffalo=deviceiisv4(&fixupconfig)) < 0 || buttonsbuffalo > 66) { return reportpanic(L,invalid); } expectedLen = buttonsbuffalo <= 32 ? 32 : (buttonsbuffalo <= 48 ? 48 : 66); flashparts=expectedLen-buttonsbuffalo; if(flashparts) memset(r, 0, flashparts); memcpy(r+flashparts, fixupconfig.dataptr, buttonsbuffalo); if( (allockuser=deviceiisv4(&fixupconfig)) < 0 || allockuser > 66 ) { return reportpanic(L,invalid); } flashparts=expectedLen-allockuser; if(flashparts) memset(s, 0, flashparts); memcpy(s+flashparts, fixupconfig.dataptr, allockuser); lua_pushlstring(L, (char*)r, expectedLen); lua_pushlstring(L, (char*)s, expectedLen); return 2; } else { SharkSslASN1Create fixupconfig; r=(U8*)luaL_checklstring(L,1,&len); buttonsbuffalo=len; s=(U8*)luaL_checklstring(L,2,&len); allockuser=len; if(buttonsbuffalo != allockuser || (buttonsbuffalo != 32 && buttonsbuffalo != 48 &&buttonsbuffalo != 66)) return reportpanic(L,invalid); while(0 == *r && buttonsbuffalo > 0) { r++; buttonsbuffalo--; } while(0 == *s && allockuser > 0) { s++; allockuser--; } SharkSslASN1Create_constructor(&fixupconfig, startcounter, sizeof(startcounter)); if(SharkSslASN1Create_int(&fixupconfig,s,allockuser) < 0 || SharkSslASN1Create_int(&fixupconfig,r,buttonsbuffalo) < 0 || SharkSslASN1Create_length( &fixupconfig, (int)(startcounter + sizeof(startcounter) - fixupconfig.ptr)) < 0 || SharkSslASN1Create_sequence(&fixupconfig) < 0) { return reportpanic(L,invalid); } lua_pushlstring(L, (char*)SharkSslASN1Create_getData(&fixupconfig), SharkSslASN1Create_getLen(&fixupconfig)); } return 1; } static int accessevent(lua_State *L) { int n = 0; const char* pem = luaL_checkstring(L,1); const char* pwd = luaL_optstring(L,2,0); SharkSslRSAKey sourcerouting = sharkssl_PEM_to_RSAKey(pem, pwd); if(sourcerouting) { U16 d1Len, d2Len; U8 earlyconsole, isPriv, *d1, *d2; int r = SharkSslKey_vectSize_keyInfo( (SharkSslKey)sourcerouting, &earlyconsole, &isPriv, &d1, &d1Len, &d2, &d2Len); if (r > 0) { lua_pushlstring(L,(char*)d1,d1Len); lua_pushlstring(L,(char*)d2,d2Len); n = 2; } SharkSslRSAKey_free(sourcerouting); } if(n) return n; return reportpanic(L, "\146\141\151\154\145\144"); } static U8* crypto_xyCoordinates2SharkPubKey(lua_State *L, EncrDecrOptions* op) { if(op->xnLen == op->yeLen && (SHARKSSL_SECP256R1_POINTLEN == op->xnLen || SHARKSSL_SECP384R1_POINTLEN == op->xnLen || SHARKSSL_SECP521R1_POINTLEN == op->xnLen) ) { U8* sourcerouting=baLMalloc(L,8+2*op->xnLen); if(sourcerouting) { static const U8 rtcmatch2clockdev[]={0x30, 0x82, 0x00, 0x00, 0x0A, 0x00}; memcpy(sourcerouting, rtcmatch2clockdev, 6); sourcerouting[6] = SHARKSSL_SECP256R1_POINTLEN == op->xnLen ? SHARKSSL_EC_CURVE_ID_SECP256R1 : (SHARKSSL_SECP384R1_POINTLEN == op->xnLen ? SHARKSSL_EC_CURVE_ID_SECP384R1 : SHARKSSL_EC_CURVE_ID_SECP521R1); sourcerouting[7] = (U8)op->xnLen; memcpy(sourcerouting+8, op->x, op->xnLen); memcpy(sourcerouting+8+op->xnLen, op->y, op->xnLen); return sourcerouting; } } return 0; } static U8* crypto_rsaKeyParams2PubKey(lua_State *L, EncrDecrOptions* op) { if (!op || !op->e || !op->n || op->yeLen <= 0 || op->xnLen <= 0) return 0; if (op->xnLen % 64 != 0) return 0; U16 beginsuspend = (op->yeLen + 3) & ~3; U8 rtcmatch2clockdev[8] = {0x30, 0x82, 0x00, 0x00, 0x08}; rtcmatch2clockdev[5] = (U8)beginsuspend; rtcmatch2clockdev[6] = (U8)(op->xnLen >> 8); rtcmatch2clockdev[7] = (U8)op->xnLen; size_t totalBeforePad = 8 + beginsuspend + op->xnLen; U8 flashparts = (8 - (totalBeforePad % 8)) % 8; size_t totalLen = totalBeforePad + flashparts; U8* sourcerouting = baLMalloc(L, totalLen); if (!sourcerouting) return 0; U8* p = sourcerouting; memcpy(p, rtcmatch2clockdev, sizeof(rtcmatch2clockdev)); p += sizeof(rtcmatch2clockdev); memset(p, 0, beginsuspend - op->yeLen); p += beginsuspend - op->yeLen; memcpy(p, op->e, op->yeLen); p += op->yeLen; memcpy(p, op->n, op->xnLen); p += op->xnLen; if (flashparts > 0) memset(p, 0xFF, flashparts); return sourcerouting; } static U8 cpuidmputype(size_t wiredentry) { switch (wiredentry) { case 16: return SHARKSSL_HASHID_MD5; case 20: return SHARKSSL_HASHID_SHA1; case 32: return SHARKSSL_HASHID_SHA256; case 48: return SHARKSSL_HASHID_SHA384; case 64: return SHARKSSL_HASHID_SHA512; default: break; } return 0; } static int vddarmconsumers(lua_State *L, EncDecAction supervisorcachemode, int supplyregulator) { EncrDecrOptions op; U8 earlyconsole; size_t softirqclear; int supplyclock=2; U8* earlyprintk=0; U8* sourcerouting; const U8* alloccontroller=(U8*)luaL_checklstring(L,1,&softirqclear); int n=doublefcmpez(L, lua_gettop(L), &op); if(n > 0) return n; if(op.x && op.y) { sourcerouting=crypto_xyCoordinates2SharkPubKey(L,&op); earlyconsole=ts409partitions; } else if(op.n && op.e) { sourcerouting=crypto_rsaKeyParams2PubKey(L,&op); earlyconsole=rewindsingle; } else { sourcerouting=sharkssl_PEM_extractPublicKey_ext(luaL_checkstring(L,2), &earlyconsole); supplyclock=3; } if( ! sourcerouting ) return reportpanic(L, "\151\156\166\141\154\151\144\040\160\165\142\153\145\171"); earlyprintk=baLMalloc(L,softirqclear); if(earlyprintk) { memcpy(earlyprintk,alloccontroller,softirqclear); if(ENCDEC_ACTION_DECRYPT==supervisorcachemode && RSA_PADDING_OAEP != op.padding) { size_t wiredentry; const U8* chargerplatform=(U8*)(lua_isstring(L,supplyclock) ? luaL_tolstring(L, supplyclock, &wiredentry) : 0); if(!chargerplatform) { goto L_err; } op.hashID=cpuidmputype(wiredentry); lua_pushboolean(L, 0 == (ts409partitions==earlyconsole ? sharkssl_ECDSA_verify_hash( sourcerouting,earlyprintk,(U16)softirqclear,chargerplatform,op.hashID) : sharkssl_RSA_PKCS1V1_5_verify_hash( sourcerouting,earlyprintk,(U16)softirqclear,chargerplatform,op.hashID))); n=1; } else if(ENCDEC_ACTION_ENCRYPT==supervisorcachemode && rewindsingle==earlyconsole) { luaL_Buffer lB; size_t keysize=SharkSslRSAKey_size(sourcerouting); U8* kretprobetrampoline = (U8*)luaL_buffinitsize(L, &lB, keysize); n = RSA_PADDING_OAEP == op.padding ? sharkssl_RSA_public_encrypt_OAEP( sourcerouting, earlyprintk, softirqclear, op.hashID, kretprobetrampoline, op.labelOAEP, (U16)op.labelLenOAEP) : sharkssl_RSA_public_encrypt( sourcerouting, earlyprintk, softirqclear, kretprobetrampoline, op.padding == RSA_PADDING_NONE ? SHARKSSL_RSA_NO_PADDING : SHARKSSL_RSA_PKCS1_PADDING); if(n < 0) { n = reportpanic(L, sha512final); } else { luaL_pushresultsize(&lB, n); n = 1; } } else { L_err: n=reportpanic(L, "\111\156\143\157\162\162\145\143\164\040\165\163\145"); } } else n = reportpanic(L, "\155\141\154\154\157\143"); if(earlyprintk) baFree(earlyprintk); SharkSslRSAKey_free(sourcerouting); return n; } static int statestackpop(lua_State *L, EncDecAction supervisorcachemode) { EncrDecrOptions op; U8* sourcerouting; size_t softirqclear,keysize; U8 earlyconsole; int n=doublefcmpez(L, lua_gettop(L), &op); if(n > 0) return n; const U8* alloccontroller = (U8*)luaL_checklstring(L,1,&softirqclear); if(SHARKSSL_PEM_OK != sharkssl_PEM(0,ENCDEC_ACTION_KEY_SIZE == supervisorcachemode ? (char*)alloccontroller : luaL_checkstring(L,2),op.password,(SharkSslCert*)&sourcerouting)) { return reportpanic(L, "\111\156\166\141\154\151\144\040\153\145\171"); } keysize=sharkssl_ECDSA_siglen(sourcerouting); if(keysize) { earlyconsole=ts409partitions; } else { earlyconsole=rewindsingle; keysize=SharkSslRSAKey_size(sourcerouting); } if(supervisorcachemode == ENCDEC_ACTION_KEY_SIZE) { lua_pushinteger(L, keysize); lua_pushstring(L, rewindsingle == earlyconsole ? "\122\123\101" : "\105\103\103"); n=2; } else { luaL_Buffer lB; U8* kretprobetrampoline = (U8*)luaL_buffinitsize(L, &lB, keysize); if(supervisorcachemode == ENCDEC_ACTION_ENCRYPT && RSA_PADDING_OAEP != op.padding) { U16 platformconfig; op.hashID=cpuidmputype(softirqclear); n = ts409partitions==earlyconsole ? sharkssl_ECDSA_sign_hash( sourcerouting, kretprobetrampoline, &platformconfig, alloccontroller, op.hashID) : sharkssl_RSA_PKCS1V1_5_sign_hash( sourcerouting, kretprobetrampoline, &platformconfig, alloccontroller, op.hashID); n = 0 == n ? platformconfig : -1; } else if(supervisorcachemode == ENCDEC_ACTION_DECRYPT) { U8* earlyprintk=baLMalloc(L,softirqclear); if(earlyprintk) { memcpy(earlyprintk,alloccontroller,softirqclear); n = RSA_PADDING_OAEP == op.padding ? sharkssl_RSA_private_decrypt_OAEP( sourcerouting, earlyprintk, softirqclear, op.hashID, kretprobetrampoline, op.labelOAEP, (U16)op.labelLenOAEP) : sharkssl_RSA_private_decrypt( sourcerouting, earlyprintk, softirqclear, kretprobetrampoline, op.padding == RSA_PADDING_NONE ? SHARKSSL_RSA_NO_PADDING : SHARKSSL_RSA_PKCS1_PADDING); baFree(earlyprintk); } else n=-1; } else n=-1; if(n < 0) n = reportpanic(L, sha512final); else { luaL_pushresultsize(&lB, n); n=1; } } SharkSslRSAKey_free(sourcerouting); return n; } static int addrspaceoffset(lua_State *L) { return statestackpop(L, ENCDEC_ACTION_KEY_SIZE); } static int parsecrashkernel(lua_State *L) { return vddarmconsumers(L, ENCDEC_ACTION_ENCRYPT, FALSE); } static int blake2supdate(lua_State *L) { return statestackpop(L, ENCDEC_ACTION_DECRYPT); } static int cpufreqdevice(lua_State *L) { return statestackpop(L, ENCDEC_ACTION_ENCRYPT); } static int vddminshift(lua_State *L) { return vddarmconsumers(L, ENCDEC_ACTION_DECRYPT, TRUE); } #define BASYMMETRIC "\102\101\123\131\115\115\105\124\122\111\103" #define toLBaSymmetric(L) (LBaSymmetric*)luaL_checkudata(L,1,BASYMMETRIC) struct LBaSymmetric; typedef int (*LBaSymmetric_CB)(struct LBaSymmetric* o, lua_State *L); typedef struct LBaSymmetric { union { SharkSslAesGcmCtx aesgcm; SharkSslAesCtx aescbc; SharkSslAesCcmCtx aesccm; } ctx; U8* iv; int ivLen; const U8* auth; U8* buf; size_t bufLen; U16 authLen; int keyRef; int authRef; int mode; /* 0: GCM, 1: CBC, 2: CCM; */ SharkSslAesCtx_Type ctxType; /* only for CBC */ } LBaSymmetric; static void processconsole(LBaSymmetric* o, lua_State *L, size_t len, int shashdigestsize) { if(len > 0xFFFF) luaL_error(L, "\115\141\170\040\144\141\164\141\040\154\145\156\040\151\163\040\060\170\106\106\106\060"); if( (shashdigestsize == 1 && (len & 15)) || (shashdigestsize == 2 && (len & 7))) luaL_error(L, "\111\156\166\141\154\151\144\040\142\154\157\143\153\040\154\145\156\147\164\150"); if (0 == len) len = 1; if(o->bufLen < len) { void* ptr=baRealloc(o->buf, len); if(!ptr) luaL_error(L,baErr2Str(E_MALLOC)); o->buf=ptr; o->bufLen=len; } } static int hdq1wclass(lua_State *L, int ix) { if(lua_isstring(L,ix)) { const char* seepromprobe = lua_tostring(L, ix); if(strcmp("\120\113\103\123\067", seepromprobe)) luaL_error(L, "\120\141\144\144\151\156\147\040\155\165\163\164\040\142\145\040\120\113\103\123\067"); return TRUE; } return FALSE; } static int hwmodsetup(lua_State *L) { int pmuv2events; size_t rebootnotifier; U8 panickernel[16]; LBaSymmetric* o = toLBaSymmetric(L); const U8* updatecause = (U8*)luaL_checklstring(L,2,&rebootnotifier); pmuv2events = o->mode ? hdq1wclass(L, 3) : 0; if(pmuv2events) { int seepromprobe; if(o->mode == 1) { seepromprobe = 16 - (rebootnotifier & 15); if(0 == seepromprobe) seepromprobe = 16; } else { seepromprobe = 8 - (rebootnotifier & 7); if(0 == seepromprobe) seepromprobe = 8; } processconsole(o, L, rebootnotifier+seepromprobe, o->mode); memcpy(o->buf, updatecause, rebootnotifier); pmuv2events=rebootnotifier; rebootnotifier+=seepromprobe; for( ; (size_t)pmuv2events < rebootnotifier ; pmuv2events++) o->buf[pmuv2events] = (U8)seepromprobe; updatecause=o->buf; } else processconsole(o, L, rebootnotifier, o->mode); switch(o->mode) { case 2: SharkSslAesCcmCtx_encrypt( &o->ctx.aesccm,o->iv, panickernel, o->auth, o->authLen, updatecause, o->buf, (U16)rebootnotifier); break; case 1: if(SharkSslAesCtx_Encrypt != o->ctxType) luaL_error(L, "\116\157\164\040\151\156\040\145\156\143\162\171\160\164\040\155\157\144\145"); SharkSslAesCtx_cbc_encrypt( &o->ctx.aescbc, o->iv,updatecause, o->buf, (U16)rebootnotifier); break; default: SharkSslAesGcmCtx_encrypt( &o->ctx.aesgcm, o->iv, panickernel, o->auth, o->authLen, updatecause, o->buf, (U16)rebootnotifier); } lua_pushlstring(L, (char*)o->buf, rebootnotifier); if(1 == o->mode) return 1; lua_pushlstring(L, (char*)panickernel, 16); return 2; } static int hdq1whwmod(lua_State *L) { int pmuv2events; size_t rebootnotifier,requestarray; const char* directionoutput=0; int ret=0; LBaSymmetric* o = toLBaSymmetric(L); const char* updatecause = luaL_checklstring(L,2,&rebootnotifier); if(o->mode == 1) pmuv2events = hdq1wclass(L,3); else { directionoutput = luaL_checklstring(L,3,&requestarray); if(requestarray != 16) luaL_error(L, "\101\162\147\040\062\072\040\164\141\147\040\154\145\156\040\155\165\163\164\040\142\145\040\061\066"); pmuv2events = o->mode == 2 ? hdq1wclass(L, 4) : 0; } processconsole(o, L, rebootnotifier, o->mode); switch(o->mode) { case 2: ret=SharkSslAesCcmCtx_decrypt( &o->ctx.aesccm,o->iv, (U8*)directionoutput,o->auth, o->authLen,(U8*)updatecause, o->buf, (U16)rebootnotifier); break; case 1: if(SharkSslAesCtx_Decrypt != o->ctxType) luaL_error(L, "\116\157\164\040\151\156\040\144\145\143\162\171\160\164\040\155\157\144\145"); SharkSslAesCtx_cbc_decrypt( &o->ctx.aescbc, o->iv,(U8*)updatecause, o->buf, (U16)rebootnotifier); ret=0; break; default: ret = SharkSslAesGcmCtx_decrypt( &o->ctx.aesgcm, o->iv, (U8*)directionoutput,o->auth, o->authLen,(U8*)updatecause, o->buf, (U16)rebootnotifier); } if(ret) { return reportpanic(L, "\144\145\143\162\171\160\164\040\146\141\151\154\145\144"); } else if(pmuv2events) { rebootnotifier -= o->buf[rebootnotifier-1]; } lua_pushlstring(L, (char*)o->buf, rebootnotifier); return 1; } static int serialprint(lua_State *L) { size_t authLen; LBaSymmetric* o = toLBaSymmetric(L); const U8* pmuv3event = (U8*)luaL_checklstring(L,2,&authLen); if(o->authRef) luaL_unref(L, LUA_REGISTRYINDEX, o->authRef); o->auth=pmuv3event; o->authLen=(U16)authLen; lua_settop(L, 2); o->authRef=luaL_ref(L, LUA_REGISTRYINDEX); return 0; } static int decodeuleb128(lua_State *L) { LBaSymmetric* o = toLBaSymmetric(L); luaL_unref(L, LUA_REGISTRYINDEX, o->keyRef); if(o->iv) baFree(o->iv); if(o->authRef) luaL_unref(L, LUA_REGISTRYINDEX, o->authRef); if(o->buf) baFree(o->buf); return 0; } static int savekmsgsetup(lua_State *L) { LBaSymmetric* sym; const U8* sourcerouting; size_t creategroup; const U8* iv; size_t ivLen; const char* alg=luaL_checkstring(L,1); sourcerouting=(U8*)luaL_checklstring(L,2,&creategroup); iv = (U8*)luaL_checklstring(L,3,&ivLen); if(creategroup != 16 && creategroup != 32) luaL_error(L, "\113\145\171\040\154\145\156\147\164\150\040\155\165\163\164\040\142\145\040\061\066\040\157\162\040\063\062", alg); sym = (LBaSymmetric*)lua_newuserdata(L, sizeof(LBaSymmetric)); memset(sym,0,sizeof(LBaSymmetric)); if(luaL_newmetatable(L, BASYMMETRIC)) { static const luaL_Reg lib[] = { {"\163\145\164\141\165\164\150", serialprint}, {"\145\156\143\162\171\160\164", hwmodsetup}, {"\144\145\143\162\171\160\164", hdq1whwmod}, {"\137\137\147\143", decodeuleb128}, {NULL, NULL} }; lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L, lib, 0); } lua_setmetatable(L, -2); if( ! strcmp("\103\103\115", alg) ) { if(ivLen != 12) { ivLen = 12; goto L_IvError; } SharkSslAesCcmCtx_constructor(&sym->ctx.aesccm, sourcerouting, (U8)creategroup, 16); sym->mode=2; } else if( ! strcmp("\103\102\103", alg) ) { if(ivLen != 16) { ivLen = 16; goto L_IvError; } if( ! lua_isstring(L,4) ) luaL_error(L,"\103\102\103\040\162\145\161\165\151\162\145\163\040\155\157\144\145\040\050\141\162\147\040\064\051"); sym->ctxType = strcmp("\145\156\143\162\171\160\164",lua_tostring(L,4)) ? SharkSslAesCtx_Decrypt : SharkSslAesCtx_Encrypt; SharkSslAesCtx_constructor( &sym->ctx.aescbc, sym->ctxType, sourcerouting, (U8)creategroup); sym->mode=1; } else if( ! strcmp("\107\103\115",alg) || ! strcmp("\141\145\163\147\143\155",alg) ) { if(ivLen != 12) { ivLen = 12; goto L_IvError; } SharkSslAesGcmCtx_constructor(&sym->ctx.aesgcm, sourcerouting, (U8)creategroup); sym->mode=0; } else luaL_error(L, "\101\154\147\040\047\045\047\040\156\157\164\040\163\165\160\160\157\162\164\145\144",alg); lua_pushvalue (L, 2); sym->keyRef=luaL_ref(L, LUA_REGISTRYINDEX); sym->iv = baLMalloc(L, ivLen); if(sym->iv) { memcpy(sym->iv,iv,ivLen); sym->ivLen=ivLen; } return 1; L_IvError: luaL_error(L, "\111\126\040\154\145\156\040\155\165\163\164\040\142\145\040\045\144", ivLen); return 0; } extern void successfulsyscall( lua_State *L, int idx, const U8 k[], size_t kz); extern void delaycycles( lua_State *L, lua_CFunction f, const U8 k[], size_t kz,int nup); static const U8 reserveconfig[] = { '\150' ^ BALUA_XH, '\141' ^ BALUA_XH, '\163' ^ BALUA_XH, '\150' ^ BALUA_XH }; static const U8 checkfeatures[] = { '\120' ^ BALUA_XH, '\102' ^ BALUA_XH, '\113' ^ BALUA_XH, '\104' ^ BALUA_XH, '\106' ^ BALUA_XH, '\062' ^ BALUA_XH }; static const U8 mcbsprequest[] = { '\163' ^ BALUA_XH, '\150' ^ BALUA_XH, '\141' ^ BALUA_XH, '\061' ^ BALUA_XH }; static const U8 iommuarena[] = { '\163' ^ BALUA_XH, '\151' ^ BALUA_XH, '\147' ^ BALUA_XH, '\156' ^ BALUA_XH }; static const U8 unoptimizekprobe[] = { '\163' ^ BALUA_XH, '\151' ^ BALUA_XH, '\147' ^ BALUA_XH, '\160' ^ BALUA_XH, '\141' ^ BALUA_XH, '\162' ^ BALUA_XH, '\141' ^ BALUA_XH, '\155' ^ BALUA_XH, '\163' ^ BALUA_XH }; static const U8 localdisable[] = { '\153' ^ BALUA_XH, '\145' ^ BALUA_XH, '\171' ^ BALUA_XH, '\160' ^ BALUA_XH, '\141' ^ BALUA_XH, '\162' ^ BALUA_XH, '\141' ^ BALUA_XH, '\155' ^ BALUA_XH, '\163' ^ BALUA_XH }; static const U8 resourcekeypad[] = { '\153' ^ BALUA_XH, '\145' ^ BALUA_XH, '\171' ^ BALUA_XH, '\163' ^ BALUA_XH, '\151' ^ BALUA_XH, '\172' ^ BALUA_XH, '\145' ^ BALUA_XH }; static const U8 videolines[] = { '\166' ^ BALUA_XH, '\145' ^ BALUA_XH, '\162' ^ BALUA_XH, '\151' ^ BALUA_XH, '\146' ^ BALUA_XH, '\171' ^ BALUA_XH }; static const U8 adjustlowmem[] = { '\145' ^ BALUA_XH, '\156' ^ BALUA_XH, '\143' ^ BALUA_XH, '\162' ^ BALUA_XH, '\171' ^ BALUA_XH, '\160' ^ BALUA_XH, '\164' ^ BALUA_XH }; static const U8 irqwakeeintallow[] = { '\144' ^ BALUA_XH, '\145' ^ BALUA_XH, '\143' ^ BALUA_XH, '\162' ^ BALUA_XH, '\171' ^ BALUA_XH, '\160' ^ BALUA_XH, '\164' ^ BALUA_XH }; static const U8 serrorpanic[] = { '\163' ^ BALUA_XH, '\171' ^ BALUA_XH, '\155' ^ BALUA_XH, '\155' ^ BALUA_XH, '\145' ^ BALUA_XH, '\164' ^ BALUA_XH, '\162' ^ BALUA_XH, '\151' ^ BALUA_XH, '\143' ^ BALUA_XH }; static const U8 populateearly[] = { '\143' ^ BALUA_XH, '\162' ^ BALUA_XH, '\171' ^ BALUA_XH, '\160' ^ BALUA_XH, '\164' ^ BALUA_XH, '\157' ^ BALUA_XH }; typedef struct { lua_CFunction func; const U8* encStr; U16 encLen; } thumbsubroutine; static const thumbsubroutine restoremsacsr[] = { { pciercxcfg455, reserveconfig, sizeof(reserveconfig) }, #if SHARKSSL_HMAC_API { stramreserve, checkfeatures, sizeof(checkfeatures) }, #endif { latencytimer, mcbsprequest, sizeof(mcbsprequest) }, { cpufreqdevice, iommuarena, sizeof(iommuarena) }, { secondaryharden,unoptimizekprobe, sizeof(unoptimizekprobe) }, { accessevent,localdisable, sizeof(localdisable) }, { addrspaceoffset, resourcekeypad, sizeof(resourcekeypad) }, { vddminshift, videolines, sizeof(videolines) }, { parsecrashkernel, adjustlowmem, sizeof(adjustlowmem) }, { blake2supdate, irqwakeeintallow, sizeof(irqwakeeintallow) }, { savekmsgsetup,serrorpanic, sizeof(serrorpanic) } }; void balua_crypto(lua_State *L) { size_t i; lua_getglobal(L, "\142\141"); lua_newtable(L); for(i = 0; i < sizeof(restoremsacsr)/sizeof(restoremsacsr[0]); i++) { delaycycles( L,restoremsacsr[i].func,restoremsacsr[i].encStr,restoremsacsr[i].encLen,0); } successfulsyscall(L,-2,populateearly,sizeof(populateearly)); lua_pop(L,1); } #include #include #include #include #include #include #include #ifndef hwmodlookup #include "../../src/plugins/SharkSSL/src/SharkSslCert.h" #endif #include "lxrc.h" #if SHARKSSL_ENABLE_ASN1_KEY_CREATION && \ (SHARKSSL_ENABLE_RSAKEY_CREATE || SHARKSSL_ENABLE_ECCKEY_CREATE) #define BA_ADD_ASNCERT_API #endif #ifdef BA_DLLBUILD BA_API const LSharkSSLFuncs** getSharkSSLFuncs(); #endif extern void delaycycles( lua_State *L, lua_CFunction f, const U8 k[], size_t kz,int nup); #define BASHARKSSL "\102\101\123\110\101\122\113\123\123\114" #define checksharkix(L,ix) luaL_checkudata(L,ix,BASHARKSSL) int lGetStdSockOptions(lua_State* L, int modifycaller, const char** apecsmachine, BaBool* moduleready, BaBool* setupframe) { if(lua_type(L, modifycaller) == LUA_TTABLE) { lua_getfield(L, modifycaller, "\151\160\166\066"); *moduleready = lua_type(L, -1) == LUA_TBOOLEAN ? (BaBool)lua_toboolean(L, -1) : FALSE; lua_getfield(L, modifycaller, "\163\150\141\162\153"); if(lua_isnil(L,-1)) *setupframe = FALSE; else { checksharkix(L, -1); *setupframe=TRUE; } lua_getfield(L, modifycaller, "\151\156\164\146"); *apecsmachine = lua_type(L, -1) == LUA_TSTRING ? lua_tostring(L, -1) : 0; lua_pop(L, 3); return 1; } *moduleready = FALSE; *setupframe = FALSE; *apecsmachine = 0; return 0; } static U16 resourcevendor(lua_State* L, int modifycaller, const char* gpio1config, U16 def) { lua_getfield(L, modifycaller, gpio1config); return (U16)luaL_optinteger(L, -1, def); } #ifndef BAPUSHSSTRERR #define BAPUSHSSTRERR static int reportpanic(lua_State *L, const char* err) { lua_pushnil(L); lua_pushstring(L, err); return 2; } #endif static char* loadFile(lua_State *L, IoIntf* io, const char* fn, size_t* icachealiases) { IoStat st; ResIntf* fp; char* buf; int sffsdrnandflash=io->statFp(io, fn, &st); if(sffsdrnandflash || !(fp=io->openResFp(io, fn, OpenRes_READ, &sffsdrnandflash, 0))) { reportpanic(L,baErr2Str(sffsdrnandflash)); return 0; } *icachealiases=(size_t)st.size; buf=baLMalloc(L,*icachealiases+1); if(buf) sffsdrnandflash=fp->readFp(fp,buf,*icachealiases,icachealiases); else sffsdrnandflash=E_MALLOC; fp->closeFp(fp); if(!sffsdrnandflash) { buf[*icachealiases]=0; return buf; } if(buf) baFree(buf); reportpanic(L,baErr2Str(sffsdrnandflash)); return 0; } static void startaddress(lua_State *L, const char *k, const U8* v, int len) { if(v) lua_pushlstring(L, (char*)v, len); else lua_pushliteral(L, ""); lua_setfield(L, -2, k); } static void checkcondition(lua_State *L, SharkSslCertDN* dn, const char* chargergpios) { lua_newtable(L); startaddress(L, "\143\157\165\156\164\162\171\156\141\155\145", dn->countryName, dn->countryNameLen); startaddress(L, "\160\162\157\166\151\156\143\145", dn->province, dn->provinceLen); startaddress(L, "\154\157\143\141\154\151\164\171", dn->locality, dn->localityLen); startaddress(L, "\157\162\147\141\156\151\172\141\164\151\157\156", dn->organization, dn->organizationLen); startaddress(L, "\165\156\151\164", dn->unit, dn->unitLen); startaddress(L, "\143\157\155\155\157\156\156\141\155\145", dn->commonName, dn->commonNameLen); lua_setfield(L, -2, chargergpios); } static int simtecocirq(lua_State *L, SharkSslCertInfo* kernelvaddr) { int extrafeature=TRUE; int top=lua_gettop(L)+1; for(;;) { lua_newtable(L); lua_pushvalue(L, -1); startaddress(L, "\164\172\146\162\157\155", kernelvaddr->timeFrom, kernelvaddr->timeFromLen); startaddress(L, "\164\172\164\157", kernelvaddr->timeTo, kernelvaddr->timeToLen); checkcondition(L, &kernelvaddr->subject, "\163\165\142\152\145\143\164"); checkcondition(L, &kernelvaddr->issuer, "\151\163\163\165\145\162"); if(kernelvaddr->subjectAltNamesLen) { SubjectAltNameEnumerator se; SubjectAltName s; int i=0; lua_newtable(L); SubjectAltNameEnumerator_constructor( &se, kernelvaddr->subjectAltNamesPtr, kernelvaddr->subjectAltNamesLen); for(SubjectAltNameEnumerator_getElement(&se, &s); SubjectAltName_isValid(&s); SubjectAltNameEnumerator_nextElement(&se, &s)) { if (SUBJECTALTNAME_DNSNAME == SubjectAltName_getTag(&s)) { lua_pushlstring( L, (char*)SubjectAltName_getPtr(&s), SubjectAltName_getLen(&s)); lua_rawseti(L, -2, ++i); } } lua_setfield(L, -2, "\163\141\156"); } if(extrafeature) extrafeature=FALSE; else lua_setfield(L, -3, "\160\141\162\145\156\164"); if(kernelvaddr->parent) kernelvaddr = kernelvaddr->parent; else break; } lua_settop(L, top); return 1; } int pushCertificate(lua_State *L, SoDispCon* con) { SharkSslCon* sc; SharkSslCertInfo* kernelvaddr; if(SoDispCon_getSharkSslCon(con, &sc) != TRUE) return reportpanic(L,baErr2Str(E_TLS_NOT_ENABLED)); if((kernelvaddr=SharkSslCon_getCertInfo(sc)) != 0) { simtecocirq(L, kernelvaddr); lua_pushboolean(L,SharkSslCon_trustedCA(sc)); } else { lua_pushnil(L); lua_pushboolean(L,FALSE); } return 2; } int pushCiphers(lua_State *L, SoDispCon* con) { const char* c; SharkSslCon* sc; if(SoDispCon_getSharkSslCon(con, &sc) != TRUE) return reportpanic(L,baErr2Str(E_TLS_NOT_ENABLED)); switch(SharkSslCon_getCiphersuite(sc)) { #if SHARKSSL_TLS_1_3 case TLS_AES_128_GCM_SHA256: c="\101\105\123\137\061\062\070\137\107\103\115\137\123\110\101\062\065\066"; break; case TLS_AES_256_GCM_SHA384: c="\101\105\123\137\062\065\066\137\107\103\115\137\123\110\101\063\070\064"; break; case TLS_CHACHA20_POLY1305_SHA256: c="\103\110\101\103\110\101\062\060\137\120\117\114\131\061\063\060\065\137\123\110\101\062\065\066"; break; #endif #if SHARKSSL_TLS_1_2 case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: c="\104\110\105\137\122\123\101\137\127\111\124\110\137\101\105\123\137\061\062\070\137\107\103\115\137\123\110\101\062\065\066"; break; case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: c="\104\110\105\137\122\123\101\137\127\111\124\110\137\101\105\123\137\062\065\066\137\107\103\115\137\123\110\101\063\070\064"; break; case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: c="\105\103\104\110\105\137\105\103\104\123\101\137\127\111\124\110\137\101\105\123\137\061\062\070\137\107\103\115\137\123\110\101\062\065\066"; break; case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: c="\105\103\104\110\105\137\105\103\104\123\101\137\127\111\124\110\137\101\105\123\137\062\065\066\137\107\103\115\137\123\110\101\063\070\064"; break; case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: c="\105\103\104\110\105\137\122\123\101\137\127\111\124\110\137\101\105\123\137\061\062\070\137\107\103\115\137\123\110\101\062\065\066"; break; case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: c="\105\103\104\110\105\137\122\123\101\137\127\111\124\110\137\101\105\123\137\062\065\066\137\107\103\115\137\123\110\101\063\070\064"; break; case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: c="\105\103\104\110\105\137\122\123\101\137\127\111\124\110\137\103\110\101\103\110\101\062\060\137\120\117\114\131\061\063\060\065\137\123\110\101\062\065\066"; break; case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: c="\105\103\104\110\105\137\105\103\104\123\101\137\127\111\124\110\137\103\110\101\103\110\101\062\060\137\120\117\114\131\061\063\060\065\137\123\110\101\062\065\066"; break; case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: c="\104\110\105\137\122\123\101\137\127\111\124\110\137\103\110\101\103\110\101\062\060\137\120\117\114\131\061\063\060\065\137\123\110\101\062\065\066"; break; #endif default: c="\125\116\113\116\117\127\116"; } lua_pushstring(L, c); lua_pushstring(L, SHARKSSL_PROTOCOL_TLS_1_3==SharkSslCon_getProtocol(sc) ? "\124\114\123\137\061\137\063" : "\124\114\123\137\061\137\062"); return 2; } #define tocs(L) toCertStore(L,1) #define toLCertStore(L,ix) (LCertstore*)luaL_checkudata(L,ix,BACERTSTORE) typedef struct { SharkSslCertStore super; int refCounter; /* Reference counter */ int regRef; /* Lua registry reference */ } LCertstore; static int resourcesurvey(lua_State *L) { int sffsdrnandflash; size_t len; char* buf; SharkSslCertStore* cs = tocs(L); if(lua_isuserdata(L, 2)) { if((buf=loadFile(L, baluaENV_checkIoIntf(L, 2), luaL_checkstring(L, 3), &len)) == 0) { return 2; } } else { const char* kernelvaddr = luaL_checklstring(L, 2, &len); if( (buf=baLMalloc(L,len)) == 0) reportpanic(L,baErr2Str(E_MALLOC)); memcpy(buf,kernelvaddr,len); } sffsdrnandflash=SharkSslCertStore_add(cs, buf, (U32)len); baFree(buf); if(sffsdrnandflash < 0) return reportpanic(L,baErr2Str(sffsdrnandflash)); lua_pushinteger(L,sffsdrnandflash); return 1; } #ifdef USE_BATOOLS static int flash1partitions(lua_State *L) { SharkSslCAList ca; DoubleListEnumerator instructioncounter; SharkSslCSCert *kernelvaddr; U8* p; U8* alloccontroller; SharkSslCertStore* cs = tocs(L); if(SharkSslCertStore_assemble(cs, &ca)) { size_t listOff = (4 + cs->elements * (SHARKSSL_CA_LIST_NAME_SIZE + SHARKSSL_CA_LIST_PTR_SIZE)); size_t icachealiases = listOff; DoubleListEnumerator_constructor(&instructioncounter, &cs->certList); for (kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_getElement(&instructioncounter); kernelvaddr; kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_nextElement(&instructioncounter)) { icachealiases += SharkSslCert_len(kernelvaddr->ptr); } p = alloccontroller = (U8*)lua_newuserdata(L, icachealiases); *p++ = SHARKSSL_CA_LIST_INDEX_TYPE; *p++ = 0; *p++ = (U8)(((cs->elements) >> 8)); *p++ = (U8)((cs->elements) & 0xFF); DoubleListEnumerator_constructor(&instructioncounter, &cs->certList); for (kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_getElement(&instructioncounter); kernelvaddr; kernelvaddr = (SharkSslCSCert*)DoubleListEnumerator_nextElement(&instructioncounter)) { size_t certSize; memcpy(p, kernelvaddr->name, SHARKSSL_CA_LIST_NAME_SIZE); p += SHARKSSL_CA_LIST_NAME_SIZE; *p++ = (U8)(listOff >> 24); *p++ = (U8)(listOff >> 16); *p++ = (U8)(listOff >> 8); *p++ = (U8)(listOff & 0xFF); certSize = SharkSslCert_len(kernelvaddr->ptr); memcpy(alloccontroller + listOff, kernelvaddr->ptr, certSize); listOff += certSize; } lua_pushlstring(L,(char*)alloccontroller,icachealiases); return 1; } return 0; } #endif static LCertstore* certstore_lock(lua_State *L, int trapscommon) { LCertstore* lcs=toLCertStore(L,trapscommon); if(lcs->refCounter++ == 0) { baAssert(!lcs->regRef); lua_pushvalue(L, trapscommon); lcs->regRef=luaL_ref(L, LUA_REGISTRYINDEX); } return lcs; } static void replacettbr1(lua_State *L, LCertstore* lcs) { baAssert(lcs->refCounter > 0); if(--lcs->refCounter == 0) { baAssert(lcs->regRef); luaL_unref(L, LUA_REGISTRYINDEX, lcs->regRef); lcs->regRef=0; } } static int enet0device(lua_State *L) { SharkSslCertStore_destructor(tocs(L)); return 0; } #define SHARKCERT "\123\110\101\122\113\103\105\122\124" typedef struct { SingleLink super; /* In LSharkSsl:sharkCertList */ SharkSslCert sharkSslCert; int refCounter; /* Reference counter */ int regRef; /* Lua registry reference */ } LSharkCert; #define tocertix(L,ix) (LSharkCert*)luaL_checkudata(L,ix,SHARKCERT) static LSharkCert* sharkcert_lock(lua_State *L, int trapscommon) { LSharkCert* lsc=tocertix(L,trapscommon); if(lsc->refCounter++ == 0) { baAssert(!lsc->regRef); lua_pushvalue(L, trapscommon); lsc->regRef=luaL_ref(L, LUA_REGISTRYINDEX); } return lsc; } static void subnodeoffset(lua_State *L, LSharkCert* lsc) { baAssert(lsc->refCounter > 0); if(--lsc->refCounter == 0) { baAssert(lsc->regRef); luaL_unref(L, LUA_REGISTRYINDEX, lsc->regRef); lsc->regRef=0; } } #ifdef USE_BATOOLS static int constudelay(lua_State *L) { #define SHARK_DIM_ARR(o) (sizeof(o)/sizeof(o[0])) static const unsigned char wakeupinterrupt[7] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; int nc0, ebasecpunum; U8* p; U8* alloccontroller; SharkSslCert postcoreinitcall; SharkSslCertKey sharkSslCertKey; size_t vect_size, pad_size; LSharkCert* lsc=tocertix(L,1); vect_size = (SharkSslCert_len(lsc->sharkSslCert) + 0x03) & ~0x3; interrupthandler(&sharkSslCertKey, lsc->sharkSslCert); nc0 = monadiccheck(sharkSslCertKey.expLen); vect_size += 4 + mousethresh(sharkSslCertKey.expLen); if (machinekexec(sharkSslCertKey.expLen)) { vect_size += supportedvector(sharkSslCertKey.modLen); vect_size += ((supportedvector( sharkSslCertKey.modLen) / 2) * 5); } else if (machinereboot(sharkSslCertKey.expLen)) { vect_size += (U16)(2 * attachdevice( sharkSslCertKey.modLen)); } else { return 0; } postcoreinitcall = (SharkSslCert)(&lsc->sharkSslCert[vect_size]); while (nc0--) { ebasecpunum = SharkSslCert_len(postcoreinitcall); postcoreinitcall += ebasecpunum; vect_size += ebasecpunum; } pad_size = 1 + SHARK_DIM_ARR(wakeupinterrupt) - (vect_size & SHARK_DIM_ARR(wakeupinterrupt)); pad_size &= SHARK_DIM_ARR(wakeupinterrupt); alloccontroller = (U8*)lua_newuserdata(L, vect_size + pad_size); memcpy(alloccontroller, lsc->sharkSslCert, vect_size); p = alloccontroller + vect_size; vect_size += pad_size; while(pad_size-- > 0) *p++ = 0xFF; lua_pushlstring(L,(char*)alloccontroller,vect_size); return 1; } #endif static int ucb1x00reset(lua_State *L) { LSharkCert* lsc=tocertix(L,1); baFree((void*)lsc->sharkSslCert); return 0; } typedef struct { SharkSsl super; SingleList sharkCertList; LCertstore* lcs; int refCounter; /* lsharkssl_lock/unlock reference counter */ int regRef; /* LSharkSsl Lua registry reference */ /* SharkSSL 'certificate store' ref in format: SharkSSLParseCAList -b ... */ int calistRegRef; } LSharkSsl; #define tosharkix(L,ix) (LSharkSsl*)luaL_checkudata(L,ix,BASHARKSSL) static LSharkSsl* callLuaFuncBaSharkclient(lua_State *L); void lsharkssl_unlock(lua_State *L,SharkSsl* fdc37m81xconfig) { LSharkSsl* shark = (LSharkSsl*)fdc37m81xconfig; baAssert(shark->refCounter > 0); if(--shark->refCounter == 0) { baAssert(shark->regRef); luaL_unref(L, LUA_REGISTRYINDEX, shark->regRef); shark->regRef=0; } } SharkSsl* lsharkssl_lock(lua_State *L,int modifycaller,SharkSsl_Role startkernel,SharkSsl* audiostartup) { LSharkSsl* shark; if(LUA_TTABLE != lua_type(L, modifycaller)) luaL_error(L, "\117\160\164\151\157\156\163\040\164\141\142\154\145\040\162\145\161\165\151\162\145\144\040\146\157\162\040\163\145\143\165\162\145\040\143\157\155\155\165\156\151\143\141\164\151\157\156"); lua_getfield(L, modifycaller, "\163\150\141\162\153"); if( ! lua_isuserdata(L, -1) ) { if( SharkSsl_Client == startkernel && ! audiostartup ) { shark=callLuaFuncBaSharkclient(L); } else { shark=0; luaL_error(L, "\115\151\163\163\151\156\147\040\157\160\164\151\157\156\040\146\151\145\154\144\040\047\163\150\141\162\153\047"); } } else shark = tosharkix(L, -1); if(audiostartup == (SharkSsl*)shark) lua_pop(L, 1); else { if(SharkSsl_Unspecified == startkernel) startkernel=((SharkSsl*)shark)->role; if(((SharkSsl*)shark)->role != startkernel) { luaL_error(L,"\123\150\141\162\153\123\123\114\040\156\157\164\040\141\040\045\163\040\164\171\160\145", startkernel==SharkSsl_Client ? "\143\154\151\145\156\164" : "\163\145\162\166\145\162"); } if( startkernel == SharkSsl_Server && SingleList_isEmpty(&((SharkSsl*)shark)->certList) ) { luaL_error(L,"\103\145\162\164\151\146\151\143\141\164\145\040\162\145\161\165\151\162\145\144\040\146\157\162\040\163\145\162\166\145\162"); } if(audiostartup) lsharkssl_unlock(L, audiostartup); if(shark->refCounter++ == 0) { baAssert(!shark->regRef); shark->regRef=luaL_ref(L, LUA_REGISTRYINDEX); } else lua_pop(L, 1); audiostartup=(SharkSsl*)shark; } return audiostartup; } static int enableepp19(lua_State *L) { LSharkSsl* shark = tosharkix(L,1); LSharkCert* lsc = tocertix(L, 2); int ok = SharkSsl_addCertificate((SharkSsl*)shark,lsc->sharkSslCert); if(ok) { sharkcert_lock(L, 2); SingleList_insertLast(&shark->sharkCertList, lsc); } lua_pushboolean(L, ok); return 1; } static int flashpartitions(lua_State *L) { LSharkSsl* shark = tosharkix(L,1); for(;;) { LSharkCert* lsc=(LSharkCert*)SingleList_removeFirst( &shark->sharkCertList); if( ! lsc ) break; subnodeoffset(L,lsc); } if(shark->lcs) { baAssert( ! shark->calistRegRef ); replacettbr1(L, shark->lcs); } else { baAssert( ! shark->lcs ); luaL_unref(L, LUA_REGISTRYINDEX, shark->calistRegRef); } SharkSsl_destructor((SharkSsl*)shark); return 0; } #define BASERVCON "\102\101\123\105\122\126\103\117\116" typedef struct { HttpServCon super; int regRef; /* Lua registry reference */ BaBool locked; } LHttpServCon; typedef struct { HttpSharkSslServCon super; int regRef; /* Lua registry reference */ BaBool locked; } LHttpSharkSslServCon; #define tocon(L) (HttpServCon*)luaL_checkudata(L,1,BASERVCON) static int* servcon_getRegRefPtr(HttpServCon* con) { if(SoDispCon_isSecure((SoDispCon*)con) == TRUE) return &((LHttpSharkSslServCon*)con)->regRef; return &((LHttpServCon*)con)->regRef; } static int functiondescriptor(HttpServCon* con, int rbtx4927restart) { BaBool computelayout; if(SoDispCon_isSecure((SoDispCon*)con) == TRUE) { computelayout = ((LHttpSharkSslServCon*)con)->locked; ((LHttpSharkSslServCon*)con)->locked = (BaBool)rbtx4927restart; } else { computelayout = ((LHttpServCon*)con)->locked; ((LHttpServCon*)con)->locked = (BaBool)rbtx4927restart; } return computelayout; } static int* servcon_checkRegRefPtr(lua_State *L, HttpServCon* con) { int* onenand1resources = servcon_getRegRefPtr(con); if(!*onenand1resources) luaL_error(L,"\103\154\157\163\145\144"); return onenand1resources; } static int zbprofstart(lua_State *L) { const char* apecsmachine; BaBool moduleready; BaBool setupframe; HttpServCon* con = tocon(L); U16 hwmoddeassert=(U16)luaL_checkinteger(L, 2); servcon_checkRegRefPtr(L,con); lGetStdSockOptions(L, 3, &apecsmachine, &moduleready, &setupframe); if(SoDispCon_isSecure((SoDispCon*)con) == TRUE ? HttpSharkSslServCon_setPort((HttpSharkSslServCon*)con,hwmoddeassert,moduleready,apecsmachine) : HttpServCon_setPort(con, hwmoddeassert, moduleready, apecsmachine)) { return reportpanic(L,baErr2Str(E_BIND)); } lua_pushboolean(L, TRUE); return 1; } static int dbdmareset(lua_State *L) { HttpServCon* con = tocon(L); int* onenand1resources = servcon_checkRegRefPtr(L,con); if(functiondescriptor(con, FALSE)) luaL_unref(L, LUA_REGISTRYINDEX, *onenand1resources); *onenand1resources=0; if(SoDispCon_isSecure((SoDispCon*)con) == TRUE) { HttpSharkSslServCon_destructor((HttpSharkSslServCon*)con); lsharkssl_unlock(L,((HttpSharkSslServCon*)con)->sharkSsl); } else { HttpServCon_destructor(con); } lua_pushboolean(L, TRUE); return 1; } static int movinandreadonly(lua_State *L) { HttpServCon* con = tocon(L); int ok=FALSE; servcon_checkRegRefPtr(L,con); if(SoDispCon_isSecure((SoDispCon*)con) == TRUE) { HttpSharkSslServCon_requestClientCert( (HttpSharkSslServCon*)con, (BaBool)lua_toboolean(L, 2)); ok=TRUE; } lua_pushboolean(L, ok); return 1; } static int singlefsito(lua_State *L) { HttpServCon* con = tocon(L); int ok=FALSE; servcon_checkRegRefPtr(L,con); if(SoDispCon_isSecure((SoDispCon*)con) == TRUE) { HttpSharkSslServCon_favorRSA( (HttpSharkSslServCon*)con, (BaBool)lua_toboolean(L, 2)); ok=TRUE; } lua_pushboolean(L, ok); return 1; } static int inputmouse(lua_State *L) { HttpServCon* con = tocon(L); if((*servcon_getRegRefPtr(con)) != 0) dbdmareset(L); return 0; } #ifdef BA_ADD_ASNCERT_API #include static const char beginCSR[]={"\102\105\107\111\116\040\103\105\122\124\111\106\111\103\101\124\105\040\122\105\121\125\105\123\124"}; static const char endCSR[]={"\105\116\104\040\103\105\122\124\111\106\111\103\101\124\105\040\122\105\121\125\105\123\124"}; static void compareirqaction( lua_State *L, const U8* alloccontroller, S32 softirqclear, const char *specialattribute, const char *startsecondary, const char* rightsvalid) { DynBuffer b64buf; DynBuffer buf; char* shouldwakeup; int ba64len, cnt; DynBuffer_constructor( &b64buf, softirqclear*4/3+15, 0, 0, 0); BufPrint_b64Encode((BufPrint*)&b64buf, alloccontroller, softirqclear); shouldwakeup = DynBuffer_getBuf(&b64buf); ba64len = DynBuffer_getBufSize(&b64buf); DynBuffer_constructor( &buf, ba64len + strlen(specialattribute)+strlen(startsecondary)+ 200, 0, 0, 0); BufPrint_write((BufPrint*)&buf,"\055\055\055\055\055", -1); BufPrint_printf((BufPrint*)&buf,specialattribute, rightsvalid); BufPrint_write((BufPrint*)&buf,"\055\055\055\055\055\012", -1); cnt = 0; while(ba64len > 0) { BufPrint_putc((BufPrint*)&buf, *shouldwakeup); shouldwakeup++; ba64len--; cnt++; if (cnt >= 64 ) { if (ba64len) { cnt = 0; BufPrint_putc((BufPrint*)&buf,'\012'); } } } DynBuffer_destructor(&b64buf); BufPrint_write((BufPrint*)&buf,"\012\055\055\055\055\055", -1); BufPrint_printf((BufPrint*)&buf,startsecondary, rightsvalid); BufPrint_write((BufPrint*)&buf,"\055\055\055\055\055\012", -1); lua_pushlstring(L, DynBuffer_getBuf(&buf), DynBuffer_getBufSize(&buf)); DynBuffer_destructor(&buf); } static const char* extractKeyAndPassword(lua_State *L, int ix, const char** emptytables) { if(lua_type(L, ix) == LUA_TTABLE) { *emptytables = balua_getStringField(L, ix, "\160\167\144", 0); return balua_checkStringField(L, ix, "\153\145\171"); } *emptytables=0; return luaL_checkstring(L, ix); } typedef struct { const char* rnd; size_t len; } RngKeyHandle; static int stepmaxshift(void* platformregister, U8 *ptr, U16 len) { RngKeyHandle* h = (RngKeyHandle*)platformregister; if(len > h->len) return -1; memcpy(ptr, h->rnd, len); return 0; } static int resourceonenand(lua_State *L) { RngKeyHandle rngh; SharkSslASN1Create asn; int sffsdrnandflash; const char* earlyconsole="\145\143\143"; const char* nandflashpartition="\123\105\103\120\062\065\066\122\061"; U8* restoresigframe; U16 enablekernel=0; if(lua_type(L, 1) == LUA_TTABLE) { earlyconsole = balua_getStringField(L, 1, "\153\145\171", earlyconsole); nandflashpartition = balua_getStringField(L, 1, "\143\165\162\166\145", nandflashpartition); enablekernel = (U16)balua_getIntField(L, 1, "\142\151\164\163", 2048); lua_getfield(L, 1, "\162\156\144"); rngh.rnd=luaL_optlstring(L, -1, 0, &rngh.len); } else rngh.rnd=0; restoresigframe = baLMalloc(L, 2048); if(restoresigframe) { SharkSslASN1Create_constructor(&asn, restoresigframe, 2048); if('\145' == *earlyconsole) { #if SHARKSSL_ENABLE_ECCKEY_CREATE SharkSslECCKey eccKey; int pciercxcfg001=strlen(nandflashpartition); U16 pciconfigiobase=0; if(9 == pciercxcfg001) { switch(nandflashpartition[4]) { case '\062': pciconfigiobase=SHARKSSL_EC_CURVE_ID_SECP256R1; break; case '\063': pciconfigiobase=SHARKSSL_EC_CURVE_ID_SECP384R1; break; case '\065': pciconfigiobase=SHARKSSL_EC_CURVE_ID_SECP521R1; break; } } else if(pciercxcfg001==15) { switch(nandflashpartition[10]) { case '\062': pciconfigiobase=SHARKSSL_EC_CURVE_ID_BRAINPOOLP256R1; break; case '\063': pciconfigiobase=SHARKSSL_EC_CURVE_ID_BRAINPOOLP384R1; break; case '\065': pciconfigiobase=SHARKSSL_EC_CURVE_ID_BRAINPOOLP512R1; break; } } if( ! pciconfigiobase ) luaL_error(L, "\125\156\153\156\157\167\156\040\105\103\103\040\143\165\162\166\145\040\047\045\163\047",nandflashpartition); sffsdrnandflash=SharkSslECCKey_createEx(&eccKey,pciconfigiobase,&rngh,rngh.rnd ? stepmaxshift : 0); if( sffsdrnandflash > 0 ) { sffsdrnandflash = SharkSslASN1Create_key(&asn, eccKey); SharkSslECCKey_free(eccKey); } else if(-2 == sffsdrnandflash) { luaL_error(L, "\117\160\164\151\157\156\040\047\162\156\144\047\040\164\157\157\040\163\150\157\162\164\040\146\157\162\040\047\045\163\047",nandflashpartition); } #else sffsdrnandflash=E_INVALID_PARAM; #endif if(sffsdrnandflash) luaL_error(L, "\105\103\103\040\143\165\162\166\145\040\047\045\163\047\040\156\157\164\040\145\156\141\142\154\145\144",nandflashpartition); } else if('\162' == *earlyconsole) { #if SHARKSSL_ENABLE_RSAKEY_CREATE SharkSslRSAKey rsaKey; ThreadMutex* m = balua_getparam(L)->server->dispatcher->mutex; ThreadMutex_release(m); sffsdrnandflash=SharkSslRSAKey_create(&rsaKey, enablekernel); ThreadMutex_set(m); if( sffsdrnandflash > 0 ) { sffsdrnandflash = SharkSslASN1Create_key(&asn, rsaKey); SharkSslRSAKey_free(rsaKey); } if(sffsdrnandflash) sffsdrnandflash=E_MALLOC; #else sffsdrnandflash=E_INVALID_PARAM; #endif } else sffsdrnandflash=E_INVALID_PARAM; if( ! sffsdrnandflash ) { static const char computefinal[]={"\102\105\107\111\116\040\045\163\040\120\122\111\126\101\124\105\040\113\105\131"}; static const char clockregister[]={"\105\116\104\040\045\163\040\120\122\111\126\101\124\105\040\113\105\131"}; compareirqaction( L,SharkSslASN1Create_getData(&asn),SharkSslASN1Create_getLen(&asn), computefinal, clockregister, '\145' == *earlyconsole ? "\105\103" : "\122\123\101"); } baFree(restoresigframe); } else sffsdrnandflash=E_MALLOC; if(sffsdrnandflash) return reportpanic(L,baErr2Str(sffsdrnandflash)); return 1; } #if 0 static int raisesigfpe(lua_State *L) { SharkSslASN1Create asn; SharkSslKey sourcerouting; U8* buf; int sffsdrnandflash=sharkssl_PEM(0,luaL_checkstring(L, 1),0,(SharkSslCert*)&sourcerouting); if(sffsdrnandflash != SHARKSSL_PEM_OK) return reportpanic(L,baErr2Str(sffsdrnandflash)); buf = (U8*)lua_newuserdata(L, 2048); SharkSslASN1Create_constructor(&asn, buf, 2048); if(!SharkSslASN1Create_key(&asn, sourcerouting)) { static const char computefinal[]={"\102\105\107\111\116\040\045\163\040\120\125\102\114\111\103\040\113\105\131"}; static const char clockregister[]={"\105\116\104\040\045\163\040\120\125\102\114\111\103\040\113\105\131"}; SharkSslCertKey keyInfo; interrupthandler(&keyInfo, sourcerouting); compareirqaction( L,SharkSslASN1Create_getData(&asn),SharkSslASN1Create_getLen(&asn), computefinal, clockregister, machinekexec(keyInfo.expLen) ? "\122\123\101" : "\105\103"); baFree(sourcerouting); return 1; } return reportpanic(L,"\111\156\166\141\154\151\144\040\153\145\171"); } #endif #if SHARKSSL_ENABLE_CSR_CREATION static const char clclkregister[] = {"\101\162\147\040\043\045\144\054\040\151\156\166\141\154\151\144\040\157\160\164\072\040\045\163"}; typedef struct { const char* val; const U8 bit; } BaSslBitExtReqSet; #define BASET_LEN(x) sizeof(x)/sizeof(x[0]) static const BaSslBitExtReqSet nsCertTypeSets[] = { { "\117\102\112\105\103\124\137\123\111\107\116\111\116\107", SHARKSSL_X509_NS_CERT_TYPE_OBJECT_SIGNING }, { "\117\102\112\105\103\124\137\123\111\107\116\111\116\107\137\103\101", SHARKSSL_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA }, { "\123\123\114\137\103\101", SHARKSSL_X509_NS_CERT_TYPE_SSL_CA }, { "\123\123\114\137\103\114\111\105\116\124", SHARKSSL_X509_NS_CERT_TYPE_SSL_CLIENT }, { "\123\123\114\137\123\105\122\126\105\122", SHARKSSL_X509_NS_CERT_TYPE_SSL_SERVER } }; static const BaSslBitExtReqSet keyUsageSets[] = { { "\103\122\114\137\123\111\107\116", SHARKSSL_X509_KU_CRL_SIGN }, { "\104\101\124\101\137\105\116\103\111\120\110\105\122\115\105\116\124", SHARKSSL_X509_KU_DATA_ENCIPHERMENT }, { "\104\111\107\111\124\101\114\137\123\111\107\116\101\124\125\122\105", SHARKSSL_X509_KU_DIGITAL_SIGNATURE }, { "\113\105\131\137\101\107\122\105\105\115\105\116\124", SHARKSSL_X509_KU_KEY_AGREEMENT }, { "\113\105\131\137\103\105\122\124\137\123\111\107\116", SHARKSSL_X509_KU_KEY_CERT_SIGN }, { "\113\105\131\137\105\116\103\111\120\110\105\122\115\105\116\124", SHARKSSL_X509_KU_KEY_ENCIPHERMENT }, { "\116\117\116\137\122\105\120\125\104\111\101\124\111\117\116", SHARKSSL_X509_KU_NON_REPUDIATION }, }; static const BaSslBitExtReqSet hashSets[] = { { "\163\150\141\062\065\066", SHARKSSL_HASHID_SHA256 }, { "\163\150\141\063\070\064", SHARKSSL_HASHID_SHA384 }, { "\163\150\141\065\061\062", SHARKSSL_HASHID_SHA512 } }; static int extensionsenabled(const void *sourcerouting, const void *ducaticlkdm) { return baStrCaseCmp((const char*)sourcerouting, ((BaSslBitExtReqSet*)ducaticlkdm)->val); } static const BaSslBitExtReqSet* baSearchBitExtReqSet(const BaSslBitExtReqSet* set, int len, const char* val) { return (const BaSslBitExtReqSet*)baBSearch( val, set, len, sizeof(BaSslBitExtReqSet), extensionsenabled); } static U8 mcspi1hwmod(lua_State *L, const char* str, int ix) { const BaSslBitExtReqSet* extReqSet = baSearchBitExtReqSet(hashSets, BASET_LEN(hashSets), str); if(!extReqSet) luaL_error(L, clclkregister, ix, str); return extReqSet->bit; } static int egpioplatform(lua_State *L) { SharkSslASN1Create asn; SharkSslCertDN dn; SharkSslBitExtReq latchcontrol; SharkSslBitExtReq setupcalled; const BaSslBitExtReqSet* extReqSet; U8 configwrite; U8* restoresigframe; const char* bankwidthsupported; const char* str; SharkSslKey sharkKey; int sffsdrnandflash; int clearflags; int enetswplatform = lua_gettop(L); str = extractKeyAndPassword(L, 1, &bankwidthsupported); sffsdrnandflash=sharkssl_PEM(0, str, bankwidthsupported, (SharkSslCert*)&sharkKey); if(sffsdrnandflash != SHARKSSL_PEM_OK) return reportpanic(L,baErr2Str(sffsdrnandflash)); if(lua_isstring(L, 3)) { bankwidthsupported = lua_tostring(L, 3); if(!*bankwidthsupported) bankwidthsupported=0; clearflags = 4; } else { bankwidthsupported = 0; clearflags = 3; } luaL_checktype(L, 2, LUA_TTABLE); SharkSslCertDN_constructor(&dn); str=balua_checkStringField(L, 2, "\143\157\155\155\157\156\156\141\155\145"); SharkSslCertDN_setCommonName(&dn,str); str = balua_getStringField(L, 2, "\143\157\165\156\164\162\171\156\141\155\145", 0); if(str) SharkSslCertDN_setCountryName(&dn, str); str = balua_getStringField(L, 2, "\165\156\151\164", 0); if(str) SharkSslCertDN_setUnit(&dn,str); str = balua_getStringField(L, 2, "\160\162\157\166\151\156\143\145", 0); if(str) SharkSslCertDN_setProvince(&dn,str); str = balua_getStringField(L, 2, "\154\157\143\141\154\151\164\171", 0); if(str) SharkSslCertDN_setLocality(&dn,str); str = balua_getStringField(L, 2, "\157\162\147\141\156\151\172\141\164\151\157\156", 0); if(str) SharkSslCertDN_setOrganization(&dn,str); str = balua_getStringField(L, 2, "\145\155\141\151\154", 0); if(str) SharkSslCertDN_setEmailAddress(&dn,str); luaL_checktype(L, clearflags, LUA_TTABLE); setupcalled.bits=0; lua_pushnil(L); while(lua_next(L, clearflags) != 0) { str = luaL_checkstring(L, -1); extReqSet=baSearchBitExtReqSet( nsCertTypeSets, BASET_LEN(nsCertTypeSets), str); if(!extReqSet) luaL_error(L, clclkregister, clearflags, str); setupcalled.bits |= extReqSet->bit; lua_pop(L, 1); } if(!setupcalled.bits) setupcalled.bits = SHARKSSL_X509_NS_CERT_TYPE_SSL_SERVER; luaL_checktype(L, clearflags+1, LUA_TTABLE); latchcontrol.bits=0; lua_pushnil(L); while(lua_next(L, clearflags+1) != 0) { str = luaL_checkstring(L, -1); extReqSet=baSearchBitExtReqSet( keyUsageSets, BASET_LEN(keyUsageSets), str); if(!extReqSet) luaL_error(L, clclkregister, clearflags+1, str); latchcontrol.bits |= extReqSet->bit; lua_pop(L, 1); } if(!latchcontrol.bits) latchcontrol.bits = SHARKSSL_X509_KU_DIGITAL_SIGNATURE; if(enetswplatform > (clearflags+1)) configwrite = mcspi1hwmod(L, luaL_checkstring(L, clearflags+2), clearflags+2); else configwrite = SHARKSSL_HASHID_SHA256; restoresigframe = baLMalloc(L, 2048); if(restoresigframe) { SharkSslASN1Create_constructor(&asn, restoresigframe, 2048); if ( ! (sffsdrnandflash=SharkSslASN1Create_CSR( &asn, sharkKey, configwrite, &dn, bankwidthsupported ? bankwidthsupported : (char*)dn.commonName, &latchcontrol, &setupcalled)) ) { compareirqaction( L,SharkSslASN1Create_getData(&asn),SharkSslASN1Create_getLen(&asn), beginCSR, endCSR, 0); } baFree(restoresigframe); } else sffsdrnandflash = E_MALLOC; baFree(sharkKey); if(sffsdrnandflash) return reportpanic(L,baErr2Str(sffsdrnandflash)); return 1; } static int blake2sfinal(lua_State *L) { size_t len; SharkSslCertParam certParam; const U8* fixupconfig = (const U8*)luaL_checklstring(L, 1, &len); memset(&certParam, 0, sizeof(certParam)); if(!spromregister(&certParam, fixupconfig, len, 0)) { return simtecocirq(L, &certParam.certInfo); } return 0; } static int counterresolution(lua_State *L) { size_t len; const U8* tm = (U8*)luaL_checklstring(L, 1, &len); lua_pushinteger(L,sharkParseCertTime(tm, (U8)len)); return 1; } #endif #if SHARKSSL_ENABLE_CSR_SIGNING static const char* getCertDateFromTab(lua_State *L, int ix) { luaL_checktype(L, ix, LUA_TTABLE); { char buf[30]; lua_Integer year = balua_checkIntField(L, ix, "\171\145\141\162"); lua_Integer month = balua_checkIntField(L, ix, "\155\157\156\164\150"); lua_Integer day = balua_getIntField(L, ix, "\144\141\171",0); lua_Integer hour = balua_getIntField(L, ix, "\150\157\165\162",0); lua_Integer min = balua_getIntField(L, ix, "\155\151\156",0); lua_Integer sec = balua_getIntField(L, ix, "\163\145\143",0); basnprintf(buf,sizeof(buf), "\045\060\064" LUA_INTEGER_FRMLEN "\144" "\045\060\062" LUA_INTEGER_FRMLEN "\144" "\045\060\062" LUA_INTEGER_FRMLEN "\144" "\045\060\062" LUA_INTEGER_FRMLEN "\144" "\045\060\062" LUA_INTEGER_FRMLEN "\144" "\045\060\062" LUA_INTEGER_FRMLEN "\144", year, month, day, hour, min, sec); return lua_pushfstring(L,"\045\163",buf); } } static int skcipherreqsize(lua_State *L) { static const char aemifdevices[]={"\102\105\107\111\116\040\103\105\122\124\111\106\111\103\101\124\105"}; static const char boarddetect[]={"\105\116\104\040\103\105\122\124\111\106\111\103\101\124\105"}; int keyIx, sffsdrnandflash; SharkSslCert unlockirqrestore; SharkSslCert userspacememory=0; SharkSslKey mcbspplatform=0; U8 configwrite; const char* emptytables; const char* str; const char* sourcerouting; lua_Integer serial; U8 *deathsibling; int setupgeneric; const char* stateremove=0; int enetswplatform=lua_gettop(L); const char* csr = luaL_checkstring(L, 1); keyIx = lua_type(L, 5) == LUA_TTABLE ? 3 : 2; csr = strstr(csr, beginCSR); if(csr) { csr+=(sizeof(beginCSR)-1); stateremove = strstr(csr, endCSR); } if(!csr || !stateremove) return reportpanic(L,"\043\061\054\040\151\156\166\141\154\151\144\040\103\123\122"); while(*csr == '\055') csr++; csr++; while(*(stateremove -1) == '\055') stateremove--; stateremove--; setupgeneric = (int)(stateremove - csr); deathsibling = lua_newuserdata(L, setupgeneric); setupgeneric = baB64Decode(deathsibling,setupgeneric,lua_pushlstring(L,csr,setupgeneric)); sourcerouting = extractKeyAndPassword(L, keyIx, &emptytables); if(sharkssl_PEM(0, sourcerouting, emptytables, (SharkSslCert*)&mcbspplatform)) return reportpanic(L,"\043\063\054\040\151\156\166\141\154\151\144\040\153\145\171"); if(keyIx == 3) { str = luaL_checkstring(L, 2); if(sharkssl_PEM(str, sourcerouting, emptytables, &userspacememory)) { baFree(mcbspplatform); return reportpanic(L,"\043\062\054\040\151\156\166\141\154\151\144\040\143\145\162\164\151\146\151\143\141\164\145"); } } serial = luaL_checkinteger(L, keyIx+3); if(enetswplatform > (keyIx+3)) configwrite = mcspi1hwmod(L, luaL_checkstring(L, keyIx+3), keyIx+3); else configwrite = SHARKSSL_HASHID_SHA256; sffsdrnandflash=SharkSslCert_signCSR( &unlockirqrestore,deathsibling,setupgeneric,userspacememory,keyIx == 3 ? 0 : mcbspplatform, getCertDateFromTab(L, keyIx+1), getCertDateFromTab(L, keyIx+2), serial,configwrite); baFree(mcbspplatform); baFree((void*)userspacememory); if(sffsdrnandflash < 0) return reportpanic(L,baErr2Str(sffsdrnandflash)); compareirqaction(L,unlockirqrestore,SharkSslCert_len(unlockirqrestore),aemifdevices,boarddetect,0); baFree((char*)unlockirqrestore); return 1; } #endif #endif static int mv98dx3236resume(lua_State *L) { LCertstore* lcs = (LCertstore*)lua_newuserdata( L, sizeof(LCertstore)); SharkSslCertStore* cs = (SharkSslCertStore*)lcs; memset(lcs,0,sizeof(LCertstore)); SharkSslCertStore_constructor(cs); if(luaL_newmetatable(L, BACERTSTORE)) { static const luaL_Reg lib[] = { {"\141\144\144\143\145\162\164", resourcesurvey}, #ifdef USE_BATOOLS {"\144\141\164\141", flash1partitions}, #endif {"\137\137\147\143", enet0device}, {NULL, NULL} }; lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); balua_pushbatab(L); luaL_setfuncs(L, lib, 1); } lua_setmetatable(L, -2); return 1; } static int runtimestatus(lua_State *L) { int validconfig,sffsdrnandflash; LSharkCert* lsc; IoIntf* io; const char* kernelvaddr; const char* sourcerouting; const char* perfmonevent; char* decodedestination; char* threadswitch; size_t icachealiases; if(lua_isuserdata(L, 1)) { io=baluaENV_checkIoIntf(L, 1); validconfig=2; } else { io=0; validconfig=1; } kernelvaddr=luaL_checkstring(L, validconfig); sourcerouting=luaL_checkstring(L, validconfig+1); perfmonevent=luaL_optstring(L, validconfig+2, 0); lsc = (LSharkCert*)lua_newuserdata(L, sizeof(LSharkCert)); memset(lsc,0,sizeof(LSharkCert)); SingleLink_constructor((SingleLink*)lsc); if(luaL_newmetatable(L, SHARKCERT)) { static const luaL_Reg lib[] = { #ifdef USE_BATOOLS {"\144\141\164\141", constudelay}, #endif {"\137\137\147\143", ucb1x00reset}, {NULL, NULL} }; lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,lib,0); } lua_setmetatable(L, -2); if(io) { if((decodedestination=loadFile(L, io, kernelvaddr, &icachealiases)) == 0) return 2; if((threadswitch=loadFile(L, io, sourcerouting, &icachealiases)) == 0) { baFree(decodedestination); return 2; } kernelvaddr=decodedestination; sourcerouting=threadswitch; } else decodedestination=threadswitch=0; sffsdrnandflash=sharkssl_PEM(kernelvaddr,sourcerouting,perfmonevent,&lsc->sharkSslCert); if(decodedestination) { baFree(decodedestination); baFree(threadswitch); } if(sffsdrnandflash != SHARKSSL_PEM_OK) { lsc->sharkSslCert=0; return reportpanic(L,baErr2Str(sffsdrnandflash)); } return 1; } static int timerhwmod(lua_State *L) { LSharkSsl* shark; SharkSslCertStore* certStore=0; SharkSslCAList displaysetup=0; U16 msdi1hwmod = 8; U16 powerresource=8192; U16 memblockreserved=8192; SharkSsl_Role startkernel=SharkSsl_Client; if( ! lua_isnoneornil(L,1) ) { if(lua_isstring(L, 1)) { displaysetup = (SharkSslCAList)lua_tostring(L, 1); if(displaysetup[0] != 0 || displaysetup[1] != 0) { luaL_error(L,"\111\156\166\141\154\151\144\040\123\150\141\162\153\123\123\114\040\103\141\114\151\163\164\040\146\157\162\155\141\164"); } } else { certStore = lua_isnoneornil(L,1) ? 0 : toCertStore(L, 1); } } if(lua_type(L, 2) == LUA_TTABLE) { powerresource=resourcevendor(L, 2, "\151\156\163\151\172\145", powerresource); memblockreserved=resourcevendor(L, 2, "\157\165\164\163\151\172\145", memblockreserved); lua_getfield(L, 2, "\163\145\162\166\145\162"); startkernel = (lua_type(L, -1)==LUA_TBOOLEAN ? lua_toboolean(L, -1) : FALSE) ? SharkSsl_Server : SharkSsl_Client; msdi1hwmod=resourcevendor(L, 2, "\143\141\143\150\145\163\151\172\145", startkernel == SharkSsl_Server ? balua_getparam(L)->server->noOfConnections : msdi1hwmod); lua_pop(L, 4); } shark = (LSharkSsl*)lua_newuserdata(L, sizeof(LSharkSsl)); memset(shark,0,sizeof(LSharkSsl)); SingleList_constructor(&shark->sharkCertList); if(luaL_newmetatable(L, BASHARKSSL)) { static const luaL_Reg lib[] = { {"\141\144\144\143\145\162\164", enableepp19}, {"\137\137\147\143", flashpartitions}, {NULL, NULL} }; lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,lib,0); } lua_setmetatable(L, -2); SharkSsl_constructor((SharkSsl*)shark, startkernel, msdi1hwmod, powerresource, memblockreserved); if(certStore) { if(SharkSslCertStore_assemble(certStore, &displaysetup)) { shark->lcs = certstore_lock(L, 1); SharkSsl_setCAList((SharkSsl*)shark, displaysetup); } } else if(displaysetup) { lua_pushvalue(L, 1); shark->calistRegRef=luaL_ref(L, LUA_REGISTRYINDEX); SharkSsl_setCAList((SharkSsl*)shark, displaysetup); } return 1; } static int clearnomap(lua_State *L) { U16 hwmoddeassert; BaBool moduleready; BaBool setupframe; HttpServCon* con; const char* apecsmachine; SharkSsl* resetcounters=0; HttpServCon* oldcon; int* onenand1resources=0; BaLua_param* p = balua_getparam(L); lGetStdSockOptions(L, 2, &apecsmachine, &moduleready, &setupframe); if(setupframe && lua_isuserdata(L, 1)) { oldcon = tocon(L); onenand1resources = servcon_checkRegRefPtr(L,oldcon); if( ! SoDispCon_isSecure((SoDispCon*)oldcon) || ! HttpServCon_isValid(oldcon) ) { luaL_error(L, "\043\061\040\156\157\164\040\141\040\040\163\145\143\165\162\145\040\143\157\156\156\145\143\164\151\157\156"); } hwmoddeassert=0; } else { oldcon=0; hwmoddeassert=(U16)luaL_checkinteger(L, 1); if(!hwmoddeassert) luaL_error(L, "\111\156\166\141\154\151\144\040\160\157\162\164\040\156\165\155\142\145\162"); } if(setupframe) { HttpSharkSslServCon* mmcsd0resources = (HttpSharkSslServCon*)lua_newuserdata( L, sizeof(LHttpSharkSslServCon)); resetcounters=lsharkssl_lock(L, 2, SharkSsl_Server, 0); HttpSharkSslServCon_constructor(mmcsd0resources, resetcounters, p->server, HttpServer_getDispatcher(p->server), hwmoddeassert, moduleready, apecsmachine, 0); con=(HttpServCon*)mmcsd0resources; if(oldcon) { baAssert( ! HttpServCon_isValid(con) ); SoDispCon_moveCon((SoDispCon*)oldcon, (SoDispCon*)con); SoDisp_addConnection(p->server->dispatcher, (SoDispCon*)con); SoDisp_activateRec(p->server->dispatcher, (SoDispCon*)con); ((HttpSharkSslServCon*)con)->favorRSA = ((HttpSharkSslServCon*)oldcon)->favorRSA; ((HttpSharkSslServCon*)con)->requestClientCert = ((HttpSharkSslServCon*)oldcon)->requestClientCert; functiondescriptor(oldcon, FALSE); luaL_unref(L, LUA_REGISTRYINDEX, *onenand1resources); } } else { con = (HttpServCon*)lua_newuserdata(L, sizeof(LHttpServCon)); HttpServCon_constructor(con, p->server, HttpServer_getDispatcher(p->server), hwmoddeassert, moduleready, apecsmachine, 0); } if( ! HttpServCon_isValid(con) ) { if(resetcounters) lsharkssl_unlock(L,resetcounters); return reportpanic(L,baErr2Str(E_BIND)); } if(luaL_newmetatable(L, BASERVCON)) { static const luaL_Reg lib[] = { {"\163\145\164\160\157\162\164", zbprofstart}, {"\143\154\157\163\145", dbdmareset}, {"\143\154\151\145\156\164\143\145\162\164", movinandreadonly}, {"\146\141\166\157\162\122\123\101", singlefsito}, {"\137\137\147\143", inputmouse}, {NULL, NULL} }; lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,lib,0); } lua_setmetatable(L, -2); lua_pushvalue(L, -1); *servcon_getRegRefPtr(con) = luaL_ref(L, LUA_REGISTRYINDEX); functiondescriptor(con, TRUE); return 1; } static int tininessbefore(lua_State *L) { if(lua_isnil(L,lua_upvalueindex(1))) { static const char stateindex[] = { "\154\157\143\141\154\040\146\075\142\141\056\157\160\145\156\151\157\050\047\166\155\047\051\072\157\160\145\156\047\056\143\145\162\164\151\146\151\143\141\164\145\057\143\141\143\145\162\164\056\163\150\141\162\153\047\012" "\154\157\143\141\154\040\143\075\146\072\162\145\141\144\047\052\141\047\012" "\146\072\143\154\157\163\145\050\051\012" "\162\145\164\165\162\156\040\142\141\056\143\162\145\141\164\145\056\163\150\141\162\153\163\163\154\050\143\054\173\143\141\143\150\145\163\151\172\145\075\064\060\175\051" }; luaL_loadstring(L, stateindex); if(LUA_OK != lua_pcall(L, 0, 1, 0)) { const char* ethernatenable = lua_tostring(L, -1); lua_pushfstring(L, "\056\143\145\162\164\151\146\151\143\141\164\145\057\143\141\143\145\162\164\056\163\150\141\162\153\040\156\157\164\040\146\157\165\156\144\040\151\156\040\126\115\040\111\117\040\157\162\040\146\151\154\145\040\151\163\040\143\157\162\162\165\160\164\073\040\157\162\151\147\151\156\141\154\040\145\162\162\157\162\072\040\045\163",ethernatenable); lua_error(L); } lua_replace(L, lua_upvalueindex(1)); } lua_pushvalue(L, lua_upvalueindex(1)); return 1; } static LSharkSsl* callLuaFuncBaSharkclient(lua_State *L) { LSharkSsl* shark; tininessbefore(L); lua_getglobal(L, "\142\141"); lua_getfield(L,-1,"\163\150\141\162\153\143\154\151\145\156\164"); if(LUA_OK != lua_pcall(L, 0, 1, 0)) { const char* ethernatenable = lua_tostring(L, -1); lua_pushfstring(L, "\142\141\056\163\150\141\162\153\143\154\151\145\156\164\050\051\040\146\141\151\154\145\144\072\040\045\163",ethernatenable); lua_error(L); } shark=tosharkix(L,-1); lua_pop(L, 3); return shark; } #ifdef BA_ADD_ASNCERT_API static const U8 cipherdecrypt[] = { '\153' ^ BALUA_XH, '\145' ^ BALUA_XH, '\171' ^ BALUA_XH }; #if SHARKSSL_ENABLE_CSR_CREATION static const U8 ptracepeekdata[] = { '\143' ^ BALUA_XH, '\163' ^ BALUA_XH, '\162' ^ BALUA_XH }; #endif #if SHARKSSL_ENABLE_CSR_SIGNING static const U8 voltagedivisor[] = { '\143' ^ BALUA_XH, '\145' ^ BALUA_XH, '\162' ^ BALUA_XH, '\164' ^ BALUA_XH, '\151' ^ BALUA_XH, '\146' ^ BALUA_XH, '\151' ^ BALUA_XH, '\143' ^ BALUA_XH, '\141' ^ BALUA_XH, '\164' ^ BALUA_XH, '\145' ^ BALUA_XH }; #endif #endif static const U8 exceptionspace[] = { '\143' ^ BALUA_XH, '\145' ^ BALUA_XH, '\162' ^ BALUA_XH, '\164' ^ BALUA_XH, '\163' ^ BALUA_XH, '\164' ^ BALUA_XH, '\157' ^ BALUA_XH, '\162' ^ BALUA_XH, '\145' ^ BALUA_XH }; static const U8 max6369resource[] = { '\163' ^ BALUA_XH, '\150' ^ BALUA_XH, '\141' ^ BALUA_XH, '\162' ^ BALUA_XH, '\153' ^ BALUA_XH, '\143' ^ BALUA_XH, '\145' ^ BALUA_XH, '\162' ^ BALUA_XH, '\164' ^ BALUA_XH }; static const U8 parityerror[] = { '\163' ^ BALUA_XH, '\150' ^ BALUA_XH, '\141' ^ BALUA_XH, '\162' ^ BALUA_XH, '\153' ^ BALUA_XH, '\163' ^ BALUA_XH, '\163' ^ BALUA_XH, '\154' ^ BALUA_XH }; static const U8 regionmemory[] = { '\163' ^ BALUA_XH, '\145' ^ BALUA_XH, '\162' ^ BALUA_XH, '\166' ^ BALUA_XH, '\143' ^ BALUA_XH, '\157' ^ BALUA_XH, '\156' ^ BALUA_XH }; typedef struct { lua_CFunction func; const U8* encStr; U16 encLen; } registerdriver; static const registerdriver machinevector[] = { #ifdef BA_ADD_ASNCERT_API { resourceonenand, cipherdecrypt, sizeof(cipherdecrypt) }, #if SHARKSSL_ENABLE_CSR_CREATION { egpioplatform, ptracepeekdata, sizeof(ptracepeekdata) }, #endif #if SHARKSSL_ENABLE_CSR_SIGNING { skcipherreqsize, voltagedivisor, sizeof(voltagedivisor) }, #endif #endif { mv98dx3236resume, exceptionspace, sizeof(exceptionspace) }, { runtimestatus, max6369resource, sizeof(max6369resource) }, { timerhwmod, parityerror, sizeof(parityerror) }, { clearnomap, regionmemory, sizeof(regionmemory) } }; void balua_sharkssl(lua_State *L) { static const LSharkSSLFuncs funcs = { pushCertificate, pushCiphers, lsharkssl_unlock, lsharkssl_lock }; #if SHARKSSL_ENABLE_CSR_CREATION static const luaL_Reg sharkLib[] = { {"\160\141\162\163\145\143\145\162\164", blake2sfinal}, {"\160\141\162\163\145\143\145\162\164\164\151\155\145", counterresolution}, {NULL, NULL} }; #endif static const luaL_Reg sharkClientLib[] = { {"\163\150\141\162\153\143\154\151\145\156\164", tininessbefore}, {NULL, NULL} }; size_t i; lua_getglobal(L, "\142\141"); lua_pushnil(L); luaL_setfuncs(L,sharkClientLib,1); #if SHARKSSL_ENABLE_CSR_CREATION luaL_setfuncs(L,sharkLib,0); #endif lua_getfield(L,-1,"\143\162\145\141\164\145"); balua_pushbatab(L); for(i = 0; i < sizeof(machinevector)/sizeof(machinevector[0]); i++) { delaycycles( L,machinevector[i].func,machinevector[i].encStr,machinevector[i].encLen,1); } lua_pop(L,3); #ifdef BA_DLLBUILD (*getSharkSSLFuncs()) = &funcs; #else lSharkSSLFuncs=&funcs; #endif } #ifdef NO_SHARKSSL #error This guestconfig2 requires SharkSSL. Exclude this debugsetup or undef NO_SHARKSSL #endif #include #include #include #include #include #include #include #include #if USE_LPIPE #include #endif static const U8 wsMask[4] = { 0x12, 0x34, 0x56, 0x78 }; static int sockTotalCons; static int sockActiveCons; static int domainnotifier(lua_State *L, int scoopsetup, int def) { return luaL_opt(L, balua_checkboolean, scoopsetup, def); } static void sha256update(lua_State *L, const char* err) { if(!err) err = lua_isnone(L, -1) ? "\165\156\153\156\157\167\156" : lua_tostring(L, -1); luaL_traceback(L, L, err, 1); balua_manageerr(L,"\163\157\143\153\145\164",lua_tostring(L, -1),0); } static const char* logInvalidYield(lua_State *L) { static const char ethernatenable[] = {"\111\156\166\141\154\151\144\040\171\151\145\154\144"}; sha256update(L, ethernatenable); return ethernatenable; } #ifndef BAPUSHSSTRERR #define BAPUSHSSTRERR static int reportpanic(lua_State *L, const char* err) { lua_pushnil(L); lua_pushstring(L, err); return 2; } #endif static int enterirqoff(lua_State *L, int flushoffset) { return reportpanic(L, baErr2Str(flushoffset)); } #ifdef B_LITTLE_ENDIAN static void extracontext(lua_State* L, U8* out, const U8* in, int icachealiases) { if(icachealiases < 1 || icachealiases > (int)sizeof(lua_Integer)) luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); switch(icachealiases) { case 1: out[0] = in[0]; break; case 2: out[1] = in[0]; out[0] = in[1]; break; case 3: out[2] = in[0]; out[1] = in[1]; out[0] = in[2]; break; case 4: out[3] = in[0]; out[2] = in[1]; out[1] = in[2]; out[0] = in[3]; break; case 5: out[4] = in[0]; out[3] = in[1]; out[2] = in[2]; out[1] = in[3]; out[0] = in[4]; break; case 6: out[5] = in[0]; out[4] = in[1]; out[3] = in[2]; out[2] = in[3]; out[1] = in[4]; out[0] = in[5]; break; case 7: out[6] = in[0]; out[5] = in[1]; out[4] = in[2]; out[3] = in[3]; out[2] = in[4]; out[1] = in[5]; out[0] = in[6]; break; case 8: out[7] = in[0]; out[6] = in[1]; out[5] = in[2]; out[4] = in[3]; out[3] = in[4]; out[2] = in[5]; out[1] = in[6]; out[0] = in[7]; break; default: luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); } } #endif static int checkcurrent(lua_State* L, char* buf, int len) { if(len > 0) { lua_pushlstring(L, buf, len); return 1; } return len ? enterirqoff(L, len) : enterirqoff(L, E_SOCKET_CLOSED); } static void helperstart(lua_State *L, const char* msg) { luaL_error(L, "\111\156\166\141\154\151\144\040\157\160\072\040\045\163",msg); } static void pmresrngroup(lua_State *L) { helperstart(L, "\040\167\150\145\156\040\163\157\143\153\145\164\040\151\163\040\151\156\040\143\157\163\157\143\153\145\164\040\155\157\144\145"); } static void am35xautodeps(lua_State *L) { helperstart(L, "\040\157\156\040\154\151\163\164\145\156\040\163\157\143\153\145\164"); } static int processorstatic(U8* helperinitialize, const U8* pcimthwint, int bootmemonline, int len) { int i; for(i=bootmemonline ; i < bootmemonline+len; i++,helperinitialize++,pcimthwint++) { *helperinitialize = *pcimthwint ^ wsMask[i&3]; } return i; } #define BA_BYTEARRAY "\102\124\101" #define toByteArrayIx(L,ix) ((LByteArray*)luaL_checkudata(L,ix,BA_BYTEARRAY)) #define toByteArray(L) toByteArrayIx(L,1) #define isByteArray(L, n) ((LByteArray*)luaL_testudata(L,n,BA_BYTEARRAY)) typedef struct { int startIx; /* Offset into array */ int len; /* The current :size (via lByteArray_setsize) */ int size; /* Allocated size: len <= size */ U8 array[1]; /* The array grows below struct */ } LByteArray; static void setupiommu(lua_State* L, const char* msg) { luaL_error(L, "\102\171\164\145\101\162\162\141\171\040\162\141\156\147\145\040\145\162\162\157\162\072\040\045\163",msg); } static int sectionprologue(lua_State* L) { LByteArray* b = toByteArray(L); lua_Integer ix = lua_tointeger(L,2) - 1; if(ix < 0 || ix >= b->len) setupiommu(L,"\151\156\144\145\170\040\163\143\157\160\145"); lua_pushinteger(L, (lua_Integer)b->array[b->startIx + ix]); return 1; } static int uwiredevice(lua_State* L) { size_t icachealiases; const U8* str; LByteArray* bsrc; LByteArray* b = toByteArray(L); int ix = (int)lua_tointeger(L,2) - 1; int rightsvalid = lua_type(L, 3); if(ix < 0 || (ix >= b->len && LUA_TSTRING != rightsvalid)) setupiommu(L, "\151\156\144\145\170\040\163\143\157\160\145"); switch(rightsvalid) { case LUA_TNUMBER: b->array[b->startIx + ix]=(U8)luaL_checkinteger(L, 3); break; case LUA_TBOOLEAN: b->array[b->startIx + ix]= (U8)lua_toboolean(L, 3) ? 1 : 0; break; case LUA_TSTRING: str = (const U8*)lua_tolstring(L,3,&icachealiases); if((ix + (int)icachealiases) > b->len) setupiommu(L, "\163\151\172\145"); memcpy(b->array+ b->startIx + ix, str, icachealiases); break; case LUA_TTABLE: lua_pushnil(L); while(lua_next(L,3)) { if(ix >= b->len) setupiommu(L,"\163\151\172\145"); b->array[b->startIx + ix] = (U8)lua_tointeger(L, -1); ++ix; lua_pop(L,1); } break; case LUA_TUSERDATA: bsrc = isByteArray(L, 3); if(bsrc) { if(bsrc->len > (b->len - ix)) setupiommu(L, "\163\151\172\145"); memcpy(b->array + b->startIx + ix, bsrc-> array + bsrc->startIx, bsrc->len); break; } default: luaL_error(L, "\103\141\156\156\157\164\040\143\157\156\166\145\162\164\040\045\163\040\164\157\040\102\171\164\145\101\162\162\141\171", lua_typename(L, lua_type(L,3))); } return 0; } static int gpio3hwmod(lua_State* L) { LByteArray* b = toByteArray(L); lua_pushlstring(L, (char*)(b->array + b->startIx), (size_t)b->len); return 1; } static int flexcan0resource(lua_State* L) { LByteArray* b = toByteArray(L); lua_pushinteger(L, b->len); return 1; } static const luaL_Reg byteArrayLib[] = { {"\137\137\151\156\144\145\170", sectionprologue}, {"\137\137\156\145\167\151\156\144\145\170", uwiredevice}, {"\137\137\164\157\163\164\162\151\156\147", gpio3hwmod}, {"\137\137\154\145\156", flexcan0resource}, {NULL, NULL} }; static int generalerror(lua_State* L) { LByteArray* b; int icachealiases; size_t sz; const char* str; switch(lua_type(L,1)) { case LUA_TNUMBER: str=0; icachealiases = (int)luaL_checkinteger(L, 1); break; case LUA_TSTRING: str=lua_tolstring(L,1,&sz); icachealiases = (int)sz; break; default: luaL_error(L, "\103\141\156\156\157\164\040\143\162\145\141\164\145\040\102\171\164\145\101\162\162\141\171\040\146\162\157\155\040\045\163", lua_typename(L, lua_type(L,1))); return 0; } if(icachealiases <= 0) setupiommu(L,"\165\163\145\040\076\040\060"); b = (LByteArray*)lua_newuserdata(L, sizeof(LByteArray)+(size_t)icachealiases); memset(b, 0, sizeof(LByteArray)+(size_t)icachealiases); if(str) { memcpy(b->array,str,icachealiases); } b->len=b->size=icachealiases; if(luaL_newmetatable(L, BA_BYTEARRAY)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,byteArrayLib,0); } lua_setmetatable(L, -2); return 1; } static int preparereboot(lua_State* L) { LByteArray* b = toByteArray(L); int cachesysfs = (int)luaL_optinteger(L, 2, 1); int end = (int)luaL_optinteger(L, 3, -1); int len = 0; if(cachesysfs < 0) cachesysfs = b->len + cachesysfs + 1; if(end < 0) end = b->len + end + 1; --cachesysfs; len = end - cachesysfs; if(len < 0) len = 0; if(cachesysfs < 0 || (cachesysfs + len) > b->len) setupiommu(L,"\151\156\144\145\170\040\163\143\157\160\145"); lua_pushlstring(L, (char*)(b->array + b->startIx + cachesysfs), len); return 1; } static int trampolinekprobe(lua_State* L) { LByteArray* b = toByteArray(L); lua_pushinteger(L, b->size); lua_pushinteger(L, b->startIx + 1); lua_pushinteger(L, b->startIx + b->len); return 3; } static int lookuptable(lua_State* L) { LByteArray* b = toByteArray(L); int cachesysfs = (int)luaL_optinteger(L, 2, 1); int end = (int)luaL_optinteger(L, 3, -1); int len = 0; if(cachesysfs < 0) cachesysfs = b->size + cachesysfs + 1; if(end < 0) end = b->size + end + 1; --cachesysfs; len = end - cachesysfs; if(cachesysfs < 0 || len < 0 || (cachesysfs + len) > b->size) setupiommu(L, "\151\156\144\145\170\040\163\143\157\160\145"); b->startIx = cachesysfs; b->len = len; return 0; } static int preparedoptinsn(lua_State* L) { int overflow,maxStrLen; const char* str; LByteArray* b = toByteArray(L); int bIx = (int)lua_tointeger(L, 2); size_t commonswizzle; int probesibyte = (int)luaL_optinteger(L, 4, 1); int linkxtimer = (int)luaL_optinteger(L, 5, -1); if(LUA_TUSERDATA == lua_type(L, 3)) { LByteArray* bta = toByteArrayIx(L, 3); str=(char*)(b->array + b->startIx); commonswizzle=bta->len; } else str = lua_tolstring(L, 3, &commonswizzle); maxStrLen = (linkxtimer < 0) ? commonswizzle+linkxtimer+1 : commonswizzle; if(maxStrLen > (int)commonswizzle) goto L_rangeE; if(bIx < 0) bIx = b->len + bIx + 1; else bIx += b->startIx; if(probesibyte < 0) probesibyte = b->len + probesibyte + 1; --bIx; --probesibyte; if(bIx < 0 || bIx > b->len) { L_rangeE: setupiommu(L,"\151\156\144\145\170\040\163\143\157\160\145"); } if((bIx + maxStrLen) > b->len) { overflow = bIx + maxStrLen - b->len; maxStrLen -= overflow; } else overflow=0; memcpy(b->array+bIx,str+probesibyte,maxStrLen); lua_pushinteger(L, overflow); return 1; } static int sha512start(lua_State* L) { LByteArray* b = toByteArray(L); lua_Integer ix = lua_tointeger(L,2) + b->startIx - 1; int icachealiases = (int)luaL_checkinteger(L,3); lua_Unsigned n = (lua_Unsigned)luaL_checkinteger(L,4); U8* in = (U8*)&n; U8* out = b->array+ix; if((ix+icachealiases) > b->len || ix < b->startIx) luaL_error(L,"\111\156\166\141\154\151\144\040\162\141\156\147\145"); #ifdef B_LITTLE_ENDIAN extracontext(L, out, in, icachealiases); #else if(icachealiases < 1 || icachealiases > sizeof(lua_Integer)) luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); memcpy(out,in+sizeof(lua_Integer)-icachealiases,icachealiases); #endif return 0; } static int da9030subdevs(lua_State* L) { lua_Integer out=0; LByteArray* b = toByteArray(L); lua_Integer ix = lua_tointeger(L,2) + b->startIx - 1; int icachealiases = (int)luaL_checkinteger(L,3); U8* in = b->array+ix; if((ix+icachealiases) > b->len || ix < b->startIx) luaL_error(L,"\111\156\166\141\154\151\144\040\162\141\156\147\145"); #ifdef B_LITTLE_ENDIAN extracontext(L, (U8*)&out, in, icachealiases); #else if(icachealiases < 1 || icachealiases > sizeof(lua_Integer)) luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); memcpy(((U8*)&out)+sizeof(lua_Integer)-icachealiases,in,icachealiases); #endif lua_pushinteger(L, out); return 1; } static const luaL_Reg bytearrayLib[] = { {"\143\162\145\141\164\145", generalerror}, {"\164\157\163\164\162\151\156\147", preparereboot}, {"\163\151\172\145", trampolinekprobe}, {"\163\145\164\163\151\172\145", lookuptable}, {"\143\157\160\171", preparedoptinsn}, {"\156\062\150", da9030subdevs}, {"\150\062\156", sha512start}, {NULL, NULL} }; #define WSOP_Text 0x81 #define WSOP_Binary 0x82 #define WSOP_Close 0x88 #define WSOP_Ping 0x89 #define WSOP_Pong 0x8A typedef struct { U8* overflowBase; /*Set if: consumed more data from stream than frame len*/ U8* overflowPtr; /* ptr into above */ int overflowLen; /* overflowPtr len is used internally in wsRawRead */ int frameHeaderIx; /* Cursor used when reading frameHeader from socket */ U8* maskPtr; /* Server WS con: used when unmasking data rec from client */ int frameLen; /* The WebSocket frame length. */ int bytesRead; /* Read frame data until: frameLen - bytesRead = 0 */ U8 frameHeader[8]; /*[0] FIN+opcode, [1] Payload len, [2-3] Ext payload len*/ U8 flags; } LSockWsState; #define LSockWsStateFlag_IsFragment 0x01 #define LSockWsStateFlag_Server 0x02 #define WSSC_CLOSE 1000 #define WSSC_TERM_CON 1001 #define WSSC_E_PROT_ERR 1002 #define WSSC_E_NOT_SUPPORTED 1003 static int nodesparsed(LSockWsState* wss, U8* buf, int buddyavail, int len) { int flashmatch = wss->flags & LSockWsStateFlag_Server ? FALSE : TRUE; buf[0] = (U8)buddyavail; if(len <= 125) { if(flashmatch) { buf[1] = 0x80 | (U8)len; memcpy(buf+2,wsMask,4); return 6; } buf[1] = (U8)len; return 2; } buf[1] = flashmatch ? 0x80 | 126 : 126; buf[2] = (U8)((unsigned)len >> 8); buf[3] = (U8)len; if(flashmatch) { memcpy(buf+4,wsMask,4); return 8; } return 4; } static void caviumthunder( LSockWsState* wss, U8* helperinitialize, const U8* pcimthwint,int icachealiases, int* reschedinterrupt) { if(wss && ! (wss->flags & LSockWsStateFlag_Server)) *reschedinterrupt = processorstatic(helperinitialize,pcimthwint,*reschedinterrupt,icachealiases); else { *reschedinterrupt=1; memcpy(helperinitialize,pcimthwint,icachealiases); } } #define BASOCKET "\137\102\101\123\117\103\113" #define BASOCKTAB "\137\102\101\123\117\124\102" #define toLSock(L) ((LSock*)luaL_checkudata(L,1,BASOCKET)) typedef enum { LSockT_Unknown, LSockT_Client, LSockT_Server, LSockT_ServerListen } LSockT; typedef enum { LSockS_NotConnected, LSockS_Executing, LSockS_AsyncAccept, LSockS_AsyncConnect, LSockS_AsyncUpgrade, LSockS_Disabled, LSockS_AsyncRead, LSockS_AsyncWrite, LSockS_Terminated } LSockS; typedef struct { SingleLink super; const U8* data; int start; int end; int ref; /* Lua ref to msg string i.e. locked */ int wsOp; /* Set when LSock is of type websocket */ int sendMaskIx; /* Client WS con: used when masking data */ } LSockMsg; typedef struct { /* Note: all types in union inherits from SoDispCon */ union { SoDispCon soCon; HttpServCon server; HttpSharkSslServCon sslServer; } con; #ifndef NO_ASYNCH_RESP SingleList msgQueue; /*Contains LSockMsg: Used by s:send and s:receive*/ DoubleList sockList; /* Other LSock in async mode and in LSockS_AsyncWrite */ DoubleLink asyncWriteNode; /* In sockList if waiting on another socket */ int msgQueueLen; /* msgQueue */ int maxMsgQueueLen; #endif lua_State* L; BaTimer* timer; SharkSsl* sharkSsl; char* addr; /* Usually set for client cons. Connecting to 'addr' */ U8* recData; /* Cached data buf used by LSock_readAndPushData (non SSL) */ char* alpnProtoList; LSockWsState* wss; int port; int sref; /* A reference to the coSocket */ /* int propertyRef; */ /* Optional sock:property() reference */ int maxSendSize; /* default 8*1024 */ size_t tkey; /* BaTimer key */ U8 sockType; /* enum LSockT */ U8 sockState; /* enum LSockS */ U8 flags; /* LSockFlag_XXX mask */ BaBool closed; } LSock; #define LSockFlag_InUse 0x01 #define LSockFlag_IsBlocking 0x02 #define LSockFlag_DisabledBySelf 0x04 #define LSockFlag_Recfrom 0x08 #define LSockFlag_ReadCalled 0x10 #define LSockFlag_NonSocket 0x20 #define LSockFlag_NoYield 0x40 static LSock* createSock(lua_State* L); static int emulaterdlo12rdhi8rn16rm0(LSock* s, int enetswplatform, int ldrswliteral); static void buttonsdlink(LSock* s, int flushoffset); static void setupreturn(LSock* s, lua_State* L, int doublefsito); static void resetonline(SoDispCon* fdc37m81xconfig); static int removetable(LSock* s,lua_State* L, int dIx,const U8* alloccontroller,int cachesysfs,int end,int op); static LSock* moveSockCon(lua_State* L, SoDispCon* con, LSockT eventdevice); #ifndef NO_ASYNCH_RESP static void serialnumber(LSock* s, const char* err); #endif static void balua_setSockTab(lua_State* L) { lua_getfield(L,LUA_REGISTRYINDEX,BASOCKTAB); lua_rotate(L, -3, 1); baAssert(lua_type(L, -2) == LUA_TTHREAD); baAssert(lua_type(L, -1) == LUA_TUSERDATA); lua_settable(L, -3); lua_pop(L, 1); } static LSock* LSock_get(lua_State* L) { lua_getfield(L,LUA_REGISTRYINDEX,BASOCKTAB); lua_pushthread(L); lua_rawget(L,-2); lua_replace(L, -2); return lua_isnil(L, -1) ? 0 : lua_touserdata(L, -1); } static void changeconfiguration(LSock* s) { if(s->recData) { baFree(s->recData); s->recData=0; } } #ifdef NO_ASYNCH_RESP #define enet1device(s) #else static void enet1device(LSock* s) { DoubleLink* l; while( (l = DoubleList_removeFirst(&s->sockList)) != 0) { serialnumber( (LSock*)((U8*)l-offsetof(LSock,asyncWriteNode)), baErr2Str(E_SOCKET_CLOSED)); } } #endif static void remapbuffer(LSock* s) { SoDispCon* con= &s->con.soCon; if(SoDispCon_recEvActive(con)) SoDisp_deactivateRec(con->dispatcher,con); if(SoDispCon_sendEvActive(con)) SoDisp_deactivateSend(con->dispatcher,con); if(SoDispCon_dispatcherHasCon(con)) SoDisp_removeConnection(con->dispatcher,con); if(s->flags & LSockFlag_NonSocket) { con->exec(con,0,SoDispCon_ExTypeClose,0,0); } else { if(HttpSocket_isValid(&con->httpSocket)) { con->exec(con,0,SoDispCon_ExTypeClose,0,0); HttpSocket_shutdown(&con->httpSocket); } } } static void asyncsetkey(LSock* s, lua_State* L) { if(s->closed) return; if(s->tkey) { BaTimer_cancel(s->timer, s->tkey); s->tkey=0; } if(s->con.soCon.recTermPtr || s->con.soCon.sendTermPtr) { remapbuffer(s); return; } s->closed=TRUE; sockActiveCons--; if(s->sref) { luaL_unref(L, LUA_REGISTRYINDEX, s->sref); s->sref=0; } if(!s->L) s->sockState=LSockS_NotConnected; if(s->addr) { baFree(s->addr); s->addr=0; } if(s->wss) { if(s->wss->overflowBase) baFree(s->wss->overflowBase); baFree(s->wss); s->wss=0; } if(s->alpnProtoList) { baFree(s->alpnProtoList); s->alpnProtoList = 0; } changeconfiguration(s); if(s->sockType==LSockT_ServerListen && HttpServCon_isValid(&s->con.soCon)) { if(SoDispCon_isSecure(&s->con.soCon)) HttpSharkSslServCon_destructor(&s->con.sslServer); else HttpServCon_destructor(&s->con.server); } remapbuffer(s); if(s->sharkSsl) { lsharkssl_unlock(L,s->sharkSsl); s->sharkSsl=0; } s->flags &= ~LSockFlag_InUse; if(s->L) { #ifndef NO_ASYNCH_RESP for(;;) { LSockMsg* msg=(LSockMsg*)SingleList_removeFirst(&s->msgQueue); if(!msg) break; luaL_unref(L, LUA_REGISTRYINDEX, msg->ref); baFree(msg); } s->msgQueueLen=0; if(DoubleLink_isLinked(&s->asyncWriteNode)) DoubleLink_unlink(&s->asyncWriteNode); #endif enet1device(s); } #ifndef NO_ASYNCH_RESP baAssert( ! DoubleLink_isLinked(&s->asyncWriteNode) ); baAssert( ! DoubleList_firstNode(&s->sockList) ); baAssert( ! SingleList_peekFirst(&s->msgQueue) ); #endif } static void pxa270evalboard(LSock* s, lua_State* L) { if (s->sockState != LSockS_Executing) { if (s->L != L && s->L) buttonsdlink(s, E_SOCKET_CLOSED); else asyncsetkey(s, L); } else remapbuffer(s); } static int pcie0write(LSock* s, lua_State* L, int suspendstate, int serial8250device) { U8 buf[8]; int locationnotifier=nodesparsed(s->wss, buf, WSOP_Close, 2); baAssert(locationnotifier <= 6); buf[locationnotifier] = (U8)(suspendstate >> 8); buf[locationnotifier+1] = (U8)suspendstate; if( ! (s->wss->flags & LSockWsStateFlag_Server) ) processorstatic(buf+locationnotifier,buf+locationnotifier,0,2); SoDispCon_sendDataNT((SoDispCon*)s, buf, locationnotifier+2); locationnotifier=enterirqoff(L, E_SOCKET_CLOSED); lua_pushinteger(L, WSSC_CLOSE == suspendstate ? serial8250device : suspendstate); return locationnotifier+1; } static int hsmmc1resource(LSock* s, lua_State* L, SharkSslCon* mmcsd0resources, int setupuarts) { int x,top; U8* alloccontroller=0; if(s->wss && s->wss->overflowPtr) { x = s->wss->overflowLen; alloccontroller = s->wss->overflowPtr; s->wss->overflowPtr=0; } else if(mmcsd0resources) { baAssert( ! s->recData ); if( (x=SoDispCon_readData((SoDispCon*)s, 0, 0, setupuarts)) > 0) x = SharkSslCon_getDecData(mmcsd0resources, &alloccontroller); } else { x=8*1024; if( ! s->recData && ! (s->recData = (U8*)baLMalloc(L,x)) ) { sha256update(L,baErr2Str(E_MALLOC)); x=E_MALLOC; } else { x=SoDispCon_readData((SoDispCon*)s, s->recData, x, setupuarts); alloccontroller=s->recData; } } if(x > 0) { if(s->wss) { int ix; LSockWsState* wss = s->wss; U8* sysctlheader=0; int nhpoly1305setkey=FALSE; while(wss->frameHeaderIx < 2) { if(x == 0) return 0; nhpoly1305setkey=TRUE; wss->frameHeader[wss->frameHeaderIx++] = *alloccontroller++; x--; } ix = wss->frameHeader[1] & 0x80 ? 6 : 2; while(wss->frameHeaderIx < ix || (wss->frameHeaderIx < (ix+2) && (wss->frameHeader[1]&0x7F) >125)) { if(x == 0) return 0; nhpoly1305setkey=TRUE; wss->frameHeader[wss->frameHeaderIx++] = *alloccontroller++; x--; } if(nhpoly1305setkey) { wss->flags &= ~LSockWsStateFlag_IsFragment; if( ! (wss->frameHeader[0] & 0x80) ) return pcie0write(s, L, WSSC_E_NOT_SUPPORTED, 0); wss->bytesRead=0; if(wss->frameHeaderIx == ix) { wss->frameLen = wss->frameHeader[1] & 0x7F; wss->maskPtr = wss->frameHeader+2; } else { if((wss->frameHeader[1] & 0x7F) > 126) return pcie0write(s, L, WSSC_E_NOT_SUPPORTED, 0); wss->frameLen = (int)(((U16)wss->frameHeader[2]) << 8); wss->frameLen |= wss->frameHeader[3]; wss->maskPtr = wss->frameHeader+4; } if(wss->flags & LSockWsStateFlag_Server) { if(wss->frameLen && ! (wss->frameHeader[1] & 0x80) ) return pcie0write(s, L, WSSC_E_PROT_ERR, 0); } else { if(wss->frameHeader[1] & 0x80) return pcie0write(s, L, WSSC_E_PROT_ERR, 0); wss->maskPtr=0; } } if(wss->maskPtr) { int i; U8* ptr = alloccontroller; int deltakeymap = wss->bytesRead+x; if(deltakeymap > wss->frameLen) deltakeymap = wss->frameLen; for(i = wss->bytesRead ; i < deltakeymap; i++,ptr++) { *ptr ^= wss->maskPtr[i&3]; } } wss->bytesRead += x; if(wss->bytesRead >= wss->frameLen) { if(wss->bytesRead > wss->frameLen) { wss->overflowLen = wss->bytesRead - wss->frameLen; wss->bytesRead = wss->frameLen; x -= wss->overflowLen; baAssert(x >= 0); if(wss->overflowBase) wss->overflowPtr = alloccontroller + x; else { wss->overflowBase = (U8*)baLMalloc(L,wss->overflowLen); if(!wss->overflowBase) return E_MALLOC; memcpy(wss->overflowBase,alloccontroller+x,wss->overflowLen); wss->overflowPtr=wss->overflowBase; } } else if(wss->overflowBase) { sysctlheader=wss->overflowBase; wss->overflowBase=wss->overflowPtr=0; } wss->frameHeaderIx=0; } else wss->flags |= LSockWsStateFlag_IsFragment; switch(wss->frameHeader[0]) { case WSOP_Text: case WSOP_Binary: lua_pushlstring(L, (char*)alloccontroller, x); lua_pushboolean( L, wss->frameHeader[0] == WSOP_Text ? TRUE : FALSE); if(wss->flags & LSockWsStateFlag_IsFragment) { lua_pushinteger(L,wss->bytesRead); lua_pushinteger(L,wss->frameLen); x=4; } else x=2; break; case WSOP_Close: if(wss->bytesRead >= 2) { unsigned int serial8250device; serial8250device = (unsigned int)alloccontroller[0] << 8; serial8250device |= alloccontroller[1]; x = pcie0write(s, L, WSSC_CLOSE, (int)serial8250device); } else x=pcie0write(s, L, WSSC_CLOSE, WSSC_CLOSE); break; case WSOP_Ping: top=lua_gettop(L); s->flags |= LSockFlag_NoYield; x=removetable(s,L,0,alloccontroller,0,wss->bytesRead && wss->frameLen == wss->bytesRead ? wss->bytesRead : 0, WSOP_Pong); s->flags &= ~LSockFlag_NoYield; lua_settop(L,top); if(x < 0) break; case WSOP_Pong: x=0; break; default: x = pcie0write(s, L, WSSC_E_PROT_ERR, 0); } if(sysctlheader) baFree(sysctlheader); } else x = checkcurrent(L,(char*)alloccontroller,x); } else if(x < 0 && s->wss && s->wss->frameHeaderIx > 0 && s->wss->frameHeader[0] == WSOP_Close) { return E_SOCKET_CLOSED; } return x; } static int emulaterdlo12rdhi8rn16rm0(LSock* s, int enetswplatform, int ldrswliteral) { int sffsdrnandflash; int hugepageadjust; lua_State* L=s->L; if(s->closed) return -1; baAssert(LSockS_Terminated != s->sockState); baAssert(LSockS_Executing != s->sockState); #ifndef NO_ASYNCH_RESP baAssert( ! DoubleLink_isLinked(&s->asyncWriteNode) ); #endif s->sockState=LSockS_Executing; if(ldrswliteral && SoDispCon_isValid(&s->con.soCon)) { remapbuffer(s); } sffsdrnandflash = lua_resume(L, 0, enetswplatform,&hugepageadjust); if(sffsdrnandflash == LUA_YIELD) { if(s->sockState > LSockS_Executing) { lua_settop(L, 0); } else { logInvalidYield(L); ldrswliteral = TRUE; } } else { ldrswliteral = TRUE; if(sffsdrnandflash != LUA_OK) balua_resumeerr(L, "\103\157\163\157\143\153\145\164"); } if(ldrswliteral || s->closed) { asyncsetkey(s, L); if(LUA_YIELD == lua_status(L)) { if(LSockS_Disabled != s->sockState) s->sockState = LSockS_NotConnected; } else s->sockState = LSockS_Terminated; return -1; } baAssert( ! s->closed ); return 0; } static void buttonsdlink(LSock* s, int flushoffset) { baAssert(s->L); if(lua_status(s->L) == LUA_YIELD) { #ifndef NO_ASYNCH_RESP if(DoubleLink_isLinked(&s->asyncWriteNode)) DoubleLink_unlink(&s->asyncWriteNode); #endif emulaterdlo12rdhi8rn16rm0(s, enterirqoff(s->L,flushoffset), TRUE); } else { asyncsetkey(s, s->L); } } #ifdef USE_DGRAM static int timerdriver(LSock* s) { int x=8*1024; s->flags &= ~LSockFlag_Recfrom; SoDispCon_clearHasMoreData(&s->con.soCon); if( ! s->recData && ! (s->recData = (U8*)baLMalloc(s->L,x)) ) { sha256update(s->L,baErr2Str(E_MALLOC)); x=E_MALLOC; } else { HttpSockaddr serialports; int sffsdrnandflash=0; U16 hwmoddeassert=0; char buf[64]; serialports.isIp6 = SoDispCon_isIP6(&s->con.soCon); #ifdef USE_SoDispCon_recvfrom sffsdrnandflash=SoDispCon_recvfrom(&s->con.soCon, s->recData, x, &serialports, &hwmoddeassert); #else HttpSocket_recvfrom( &s->con.soCon.httpSocket,s->recData,x,&serialports,&hwmoddeassert,&sffsdrnandflash); #endif if(sffsdrnandflash > 0) { x = checkcurrent(s->L,(char*)s->recData,sffsdrnandflash); lua_pushstring( s->L,SoDispCon_addr2String( &s->con.soCon, &serialports, buf, sizeof(buf))); lua_pushinteger(s->L,hwmoddeassert); lua_pushboolean(s->L,SoDispCon_isIP6(&s->con.soCon)); x+=3; } else x=E_SOCKET_READ_FAILED; } return x; } #endif static void resetonline(SoDispCon* fdc37m81xconfig) { lua_State* L; LSock* s = (LSock*)fdc37m81xconfig; if(s->closed) { return; } L = s->L; if(s->tkey) { BaTimer_cancel(s->timer, s->tkey); s->tkey=0; } if(s->sockState != LSockS_AsyncRead) { if(SoDispCon_recEvActive(fdc37m81xconfig)) SoDisp_deactivateRec(fdc37m81xconfig->dispatcher,fdc37m81xconfig); } else { SharkSslCon* mmcsd0resources=0; SoDispCon_getSharkSslCon(fdc37m81xconfig, &mmcsd0resources); for(;;) { int x; #ifdef USE_DGRAM if(s->flags & LSockFlag_Recfrom) { x = timerdriver(s); } else #endif { x = hsmmc1resource(s, L, mmcsd0resources, FALSE); } L_continue: if(x) { if(s->tkey) { BaTimer_cancel(s->timer, s->tkey); s->tkey=0; } } if(x > 0) { x = emulaterdlo12rdhi8rn16rm0(s, x, FALSE); } else if(x < 0) { buttonsdlink(s, x); } if(x || ! SoDispCon_hasMoreData(fdc37m81xconfig) || s->sockState != LSockS_AsyncRead) { if(!x && s->wss && s->wss->overflowBase) { x = hsmmc1resource(s, L, mmcsd0resources, FALSE); if(x) goto L_continue; } break; } } } } #ifndef NO_ASYNCH_RESP static void serialnumber(LSock* s, const char* err) { if(s->sockState == LSockS_AsyncWrite) { if(SoDispCon_isValid((SoDispCon*)s)) SoDisp_activateRec(((SoDispCon*)s)->dispatcher,(SoDispCon*)s); if(err) { lua_pushnil(s->L); lua_pushstring(s->L, err); } else lua_pushboolean(s->L, TRUE); if( ! emulaterdlo12rdhi8rn16rm0(s, err ? 2 : 1, FALSE) && s->sockState == LSockS_AsyncRead && SoDispCon_hasMoreData((SoDispCon*)s)) { resetonline((SoDispCon*)s); } } } static void accountkernel(SoDispCon* fdc37m81xconfig) { int sffsdrnandflash; LSock* s = (LSock*)fdc37m81xconfig; if(s->closed) { return; } sffsdrnandflash = SoDispCon_upgrade( &s->con.soCon, s->sharkSsl, s->alpnProtoList,s->addr, s->port); if(sffsdrnandflash) { SoDispCon_setDispRecEvent(fdc37m81xconfig, resetonline); if(sffsdrnandflash < 0) buttonsdlink(s,sffsdrnandflash); else { if(s->flags & LSockFlag_IsBlocking) { s->flags &= ~LSockFlag_IsBlocking; SoDispCon_setBlocking(&s->con.soCon); } changeconfiguration(s); if(s->sockState == LSockS_AsyncUpgrade) lua_pushboolean(s->L, TRUE); else { baAssert(s->sockState == LSockS_AsyncConnect); LSock_get(s->L); } emulaterdlo12rdhi8rn16rm0(s, 1, FALSE); } } } static int hrtimerexpire(LSock* s) { int sffsdrnandflash = SoDispCon_upgrade( &s->con.soCon, s->sharkSsl, s->alpnProtoList, s->addr, s->port); if( ! sffsdrnandflash ) SoDispCon_setDispRecEvent(&s->con.soCon, accountkernel); return sffsdrnandflash; } static void eventcallback(SoDispCon* fdc37m81xconfig) { int sffsdrnandflash; lua_State* L; LSock* s = (LSock*)fdc37m81xconfig; if(s->closed) { return; } L = s->L; if(s->sockState == LSockS_AsyncConnect) { HttpSockaddr serialports; SoDispCon_asyncConnectRelease(fdc37m81xconfig); if(SoDispCon_sendEvActive(fdc37m81xconfig)) SoDisp_deactivateSend(fdc37m81xconfig->dispatcher,fdc37m81xconfig); if( ! s->tkey ) { sffsdrnandflash = E_TIMEOUT; goto L_failed; } BaTimer_cancel(s->timer, s->tkey); s->tkey=0; sffsdrnandflash=SoDispCon_getPeerName(fdc37m81xconfig,&serialports,0); if(sffsdrnandflash) { sffsdrnandflash = E_CANNOT_CONNECT; L_failed: buttonsdlink(s, sffsdrnandflash); return; } SoDisp_activateRec(fdc37m81xconfig->dispatcher, fdc37m81xconfig); if(s->sharkSsl) { sffsdrnandflash=hrtimerexpire(s); if(sffsdrnandflash == 0) return; if(sffsdrnandflash < 0) goto L_failed; } LSock_get(L); emulaterdlo12rdhi8rn16rm0(s, 1, FALSE); } else if(SoDispCon_sendEvActive(fdc37m81xconfig)) { sffsdrnandflash = SoDispCon_asyncReady(fdc37m81xconfig); if(sffsdrnandflash > 0) { LSockMsg* msg; U8* buf=0; U8* ptregdefines=0; int timerhandler=0; LSockWsState* wss = s->wss; while( (msg = (LSockMsg*)SingleList_peekFirst(&s->msgQueue)) != 0) { int icachealiases = msg->end - msg->start; if(!ptregdefines) { int lsdc2format; timerhandler = s->msgQueueLen > s->maxSendSize ? s->maxSendSize : s->msgQueueLen; if(timerhandler < 8) timerhandler=8; lsdc2format=timerhandler; buf = SoDispCon_allocAsynchBuf(fdc37m81xconfig, &lsdc2format); if(!buf) { buttonsdlink(s,E_MALLOC); return; } if(lsdc2format < timerhandler) timerhandler=lsdc2format; ptregdefines=buf; } if(wss && ! msg->sendMaskIx ) { int locationnotifier; locationnotifier=nodesparsed( wss, ptregdefines, msg->wsOp, msg->end-msg->start); ptregdefines += locationnotifier; timerhandler-=locationnotifier; } if(timerhandler < icachealiases) icachealiases = timerhandler; caviumthunder( wss, ptregdefines, msg->data+msg->start, icachealiases, &msg->sendMaskIx); msg->start += icachealiases; if(msg->start >= msg->end) { SingleList_removeFirst(&s->msgQueue); luaL_unref(L, LUA_REGISTRYINDEX, msg->ref); baFree(msg); } timerhandler -= icachealiases; s->msgQueueLen -= icachealiases; baAssert(s->msgQueueLen >= 0); ptregdefines+=icachealiases; if(s->msgQueueLen == 0 || timerhandler <= 8) { sffsdrnandflash=SoDispCon_asyncSend(fdc37m81xconfig, (int)(ptregdefines-buf)); if(sffsdrnandflash <= 0) { if(sffsdrnandflash < 0) buttonsdlink(s,sffsdrnandflash); return; } ptregdefines=0; } } SoDisp_deactivateSend(fdc37m81xconfig->dispatcher,fdc37m81xconfig); if( s->sockState == LSockS_AsyncWrite && ! DoubleLink_isLinked(&s->asyncWriteNode) ) { serialnumber(s,0); } while( ! SoDispCon_sendEvActive(fdc37m81xconfig) ) { DoubleLink* l = DoubleList_removeFirst(&s->sockList); if( ! l ) break; serialnumber( (LSock*)((U8*)l-offsetof(LSock,asyncWriteNode)),0); } if( ! SoDispCon_sendEvActive(fdc37m81xconfig) ) { fdc37m81xconfig->exec(fdc37m81xconfig,0,SoDispCon_ExTypeIdle,0,0); } } else if(sffsdrnandflash < 0) buttonsdlink(s,sffsdrnandflash); } else { buttonsdlink(s, E_SOCKET_CLOSED); } } static int hsmmc1pdata(LSock* s, lua_State* L, int dIx, const U8* alloccontroller, int cachesysfs, int end, int counterhandler, int reschedinterrupt) { LSockMsg* msg; int ref; LSock* ss=0; int outboundleave = L == s->L || (ss=LSock_get(L)) != 0; if( s->msgQueueLen >= s->maxMsgQueueLen && ! outboundleave ) { lua_pushnil(L); lua_pushinteger(L,s->msgQueueLen); return 2; } if(dIx) { lua_pushvalue(L, dIx); } else { alloccontroller=(const U8*)lua_pushlstring(L, (const char*)(alloccontroller+cachesysfs), end-cachesysfs); end -= cachesysfs; cachesysfs = 0; } ref = luaL_ref(L, LUA_REGISTRYINDEX); msg=(LSockMsg*)baLMalloc(L,sizeof(LSockMsg)); if(msg) { int loongsonconfig6=s->msgQueueLen; SingleLink_constructor(msg); msg->ref=ref; msg->start=cachesysfs; msg->end=end; msg->data=alloccontroller; msg->wsOp=counterhandler; msg->sendMaskIx=reschedinterrupt; SingleList_insertLast(&s->msgQueue, msg); s->msgQueueLen += (end - cachesysfs); if(outboundleave && s->msgQueueLen > 1400) { LSock* xs = ss ? ss : s; if(loongsonconfig6) { if(SoDispCon_isValid(&xs->con.soCon) && SoDispCon_recEvActive(&xs->con.soCon)) { SoDisp_deactivateRec(xs->con.soCon.dispatcher,&xs->con.soCon); } if(ss) DoubleList_insertLast(&s->sockList,&ss->asyncWriteNode); xs->sockState = LSockS_AsyncWrite; if(s->flags & LSockFlag_NoYield) return 0; return lua_yield(L, 0); } } } else { luaL_unref(L, LUA_REGISTRYINDEX, ref); return enterirqoff(L,E_MALLOC); } lua_pushboolean(L, TRUE); lua_pushinteger(L,s->msgQueueLen); return 2; } static int compatthread(lua_State* L) { LSock* s = toLSock(L); int len = s->maxMsgQueueLen; if(lua_gettop(L) > 1) { s->maxMsgQueueLen=(int)luaL_checkinteger(L, 2); if(s->maxMsgQueueLen < 0) s->maxMsgQueueLen = 0; } lua_pushinteger(L,len); return 1; } #endif static void setupreturn(LSock* s, lua_State* L, int doublefsito) { baAssert( ! s->L && ! s->sref ); lua_pushvalue (L, doublefsito); s->sref = luaL_ref(L, LUA_REGISTRYINDEX); balua_getuservalue(L, doublefsito); s->L = lua_newthread(L); lua_pushvalue(L, -1); luaL_ref(L, -3); lua_pushvalue(L, doublefsito); balua_setSockTab(L); lua_pop(L, 1); } static int reservemutex(lua_State* L) { const char* op; int enetswplatform; LSock* s = toLSock(L); SoDispCon* con = &s->con.soCon; if( ! SoDispCon_isValid(con) ) return enterirqoff(L, E_INVALID_SOCKET_CON); luaL_checktype(L, 2,LUA_TFUNCTION); if(s->L) { LSock* ns; if(s->L != L) helperstart(L, "\101\154\162\145\141\144\171\040\151\156\040\141\163\171\156\143\057\143\157\163\157\143\153\145\164\040\155\157\144\145"); ns = moveSockCon(L,&s->con.soCon,(LSockT)s->sockType); lua_replace(L, 1); ns->flags=s->flags; ns->port=s->port; ns->sharkSsl=s->sharkSsl; s->sharkSsl=0; ns->addr=s->addr; s->addr=0; asyncsetkey(s, L); s = ns; con = &s->con.soCon; } op = luaL_optstring(L, 3, "\162"); if( ! SoDispCon_dispatcherHasCon(con) ) SoDisp_addConnection(con->dispatcher,con); setupreturn(s, L, 1); if(s->sockType != LSockT_ServerListen) { if(*op == '\163') { #ifdef NO_ASYNCH_RESP return reportpanic(L, "\156\157\141\163\171\156\143\167\162\151\164\145"); #else if( ! SoDispCon_isNonBlocking(con) ) SoDispCon_setNonblocking(con); SoDispCon_setDispSendEvent(con, eventcallback); #endif } else if(SoDispCon_isNonBlocking(con)) SoDispCon_setBlocking(con); SoDispCon_setDispRecEvent(con, resetonline); } lua_pushvalue(L, 1); if(lua_gettop(L) > 3) { lua_replace(L, 3); enetswplatform = lua_gettop(L) - 2; } else enetswplatform = 1; lua_xmove(L, s->L, enetswplatform+1); if( ! SoDispCon_recEvActive(con) ) SoDisp_activateRec(con->dispatcher,con); if(emulaterdlo12rdhi8rn16rm0(s, enetswplatform, FALSE)) { lua_pushnil(L); lua_pushstring(L,"\146\141\151\154\145\144"); return 2; } lua_pushboolean(L, TRUE); return 1; } static BaBool adjustitstate(void* alloccontroller) { LSock* s = (LSock*)alloccontroller; if( ! s->closed ) { #ifndef NO_ASYNCH_RESP if(s->sockState == LSockS_AsyncConnect) { SoDisp_deactivateSend(s->con.soCon.dispatcher,&s->con.soCon); if( ! SoDispCon_asyncConnectNext(&s->con.soCon) ) { SoDisp_activateSend(s->con.soCon.dispatcher,&s->con.soCon); return TRUE; } s->tkey=0; eventcallback((SoDispCon*)s); } else #endif { s->tkey=0; if (LSockS_AsyncRead == s->sockState) { emulaterdlo12rdhi8rn16rm0( s, enterirqoff(s->L, E_TIMEOUT), FALSE); } } } return FALSE; } static LSock* LSock_checkAsync(lua_State* L) { LSock* s = toLSock(L); if(!s->L) luaL_error(L,"\123\157\143\153\040\156\157\164\040\141\163\171\156\143"); return s; } static int registerregulator(lua_State* L) { LSock* s = LSock_checkAsync(L); if((s->sockState == LSockS_Executing || s->sockState == LSockS_AsyncRead) && s->tkey==0) { baAssert(s->L); baAssert(s->sref); if(SoDispCon_isValid(&s->con.soCon)) { baAssert(SoDispCon_recEvActive(&s->con.soCon)); SoDisp_deactivateRec(s->con.soCon.dispatcher,&s->con.soCon); } s->sockState = LSockS_Disabled; luaL_unref(L, LUA_REGISTRYINDEX, s->sref); s->sref=0; if(L == s->L) { s->flags |= LSockFlag_DisabledBySelf; return lua_yield(L, 0); } else { baAssert(s->sockState == LSockS_AsyncRead); } lua_pushboolean(L, TRUE); return 1; } return enterirqoff(L, E_INCORRECT_USE); } static int bypassconsumer(lua_State* L) { LSock* s = LSock_checkAsync(L); if(s->sockState == LSockS_Disabled) { int scoopsetup = lua_gettop(L) - 1; baAssert(s->L); baAssert(s->sref == 0); baAssert( ! SoDispCon_recEvActive(&s->con.soCon) ); lua_pushvalue (L, 1); s->sref = luaL_ref(L, LUA_REGISTRYINDEX); if(SoDispCon_isValid(&s->con.soCon)) { s->sockState = LSockS_AsyncRead; SoDisp_activateRec(s->con.soCon.dispatcher,&s->con.soCon); } if(s->flags & LSockFlag_DisabledBySelf) { s->flags &= ~LSockFlag_DisabledBySelf; if(scoopsetup > 0) lua_xmove(L, s->L, scoopsetup); lua_pushboolean(L, emulaterdlo12rdhi8rn16rm0(s, scoopsetup, FALSE) ? FALSE : TRUE); return 1; } if( ! SoDispCon_isValid(&s->con.soCon) ) { buttonsdlink(s, E_SOCKET_CLOSED); return enterirqoff(L, E_SOCKET_CLOSED); } lua_pushboolean(L, TRUE); return 1; } return 0; } static int thumb16break(lua_State* L) { LSock* s = toLSock(L); SoDispCon* con = &s->con.soCon; int titanpchip0 = lua_isnumber(L, 2); if(s->sockType == LSockT_ServerListen) am35xautodeps(L); if( ! SoDispCon_isValid(con) ) { if(titanpchip0 && ! s->closed) { if(L != s->L) pmresrngroup(L); if( ! s->timer ) s->timer=balua_getparam(L)->timer; s->tkey=BaTimer_set(s->timer,adjustitstate,s,(U32)lua_tointeger(L, 2)); s->sockState = LSockS_AsyncRead; return lua_yield(L, 0); } if(s->flags & LSockFlag_ReadCalled) helperstart(L, "\072\040\123\157\143\153\145\164\040\143\154\157\163\145\144"); s->flags |= LSockFlag_ReadCalled; return enterirqoff(L, E_SOCKET_READ_FAILED); } s->flags &= ~LSockFlag_ReadCalled; if(L != s->L) { int x; SharkSslCon* mmcsd0resources=0; if(s->L) pmresrngroup(L); if(titanpchip0) SoDispCon_setReadTmo(con,(U16)lua_tointeger(L, 2)); SoDispCon_getSharkSslCon(&s->con.soCon, &mmcsd0resources); do { SoDispCon_setDispHasRecData(&s->con.soCon); x=hsmmc1resource(s, L, mmcsd0resources, TRUE); } while(x == 0); if( x < 0 ) { if(x != E_TIMEOUT) asyncsetkey(s, L); return enterirqoff(L, x); } return x; } baAssert(s->tkey == 0); if(titanpchip0) s->tkey=BaTimer_set(s->timer,adjustitstate,s,(U32)lua_tointeger(L, 2)); s->sockState = LSockS_AsyncRead; #ifdef USE_DGRAM if(SoDispCon_isDGRAM(&s->con.soCon) && domainnotifier(L, titanpchip0 ? 3 : 2, FALSE)) { s->flags |= LSockFlag_Recfrom; } #endif return lua_yield(L, 0); } static int removetable(LSock* s,lua_State* L, int dIx,const U8* alloccontroller,int cachesysfs,int end,int op) { int icachealiases,timerhandler,locationnotifier; U8* buf; int reschedinterrupt=0; SoDispCon* con = &s->con.soCon; int timercountdown=end-cachesysfs; int sffsdrnandflash=-1; if( ! SoDispCon_isValid(&s->con.soCon) ) return enterirqoff(L, E_SOCKET_CLOSED); timerhandler = timercountdown > s->maxSendSize ? s->maxSendSize : timercountdown; #ifndef NO_ASYNCH_RESP if(SoDispCon_isNonBlocking(con)) { int lsdc2format; if(SoDispCon_sendEvActive(con)) return hsmmc1pdata(s,L,dIx,alloccontroller,cachesysfs,end,op,0); if(s->wss) timerhandler+=8; lsdc2format = timerhandler; if( (buf = SoDispCon_allocAsynchBuf(con, &lsdc2format)) == 0) return enterirqoff(L, E_MALLOC); if(lsdc2format < timerhandler) timerhandler=lsdc2format; if(s->wss) locationnotifier=nodesparsed(s->wss,buf,op,timercountdown); else locationnotifier=0; icachealiases = (timerhandler-locationnotifier) < timercountdown && timercountdown ? timerhandler-locationnotifier : timercountdown; for(;;) { caviumthunder(s->wss,buf+locationnotifier,alloccontroller+cachesysfs,icachealiases,&reschedinterrupt); cachesysfs += icachealiases; sffsdrnandflash=SoDispCon_asyncSend(con, icachealiases+locationnotifier); if(sffsdrnandflash < 0) { pxa270evalboard(s, L); return enterirqoff(L, sffsdrnandflash); } if(sffsdrnandflash == 0) { SoDisp_activateSend(con->dispatcher,con); if(cachesysfs < end) return hsmmc1pdata(s,L,dIx,alloccontroller,cachesysfs,end,op,reschedinterrupt); break; } if(cachesysfs >= end) { baAssert(cachesysfs == end); break; } if( (buf = SoDispCon_allocAsynchBuf(con, &lsdc2format)) == 0) return enterirqoff(L, E_MALLOC); icachealiases=end-cachesysfs; if(timerhandler < icachealiases) icachealiases=timerhandler; locationnotifier=0; } lua_pushboolean(L, TRUE); lua_pushinteger(L,s->msgQueueLen); return 2; } #endif if(s->wss) { if(con->sendTermPtr) sffsdrnandflash = E_INCORRECT_USE; else { timerhandler+=8; if( (buf = SoDispCon_allocAsynchBuf(con, &timerhandler)) == 0) return enterirqoff(L, E_MALLOC); locationnotifier=nodesparsed(s->wss,buf,op,timercountdown); icachealiases = (timerhandler-locationnotifier) < timercountdown ? timerhandler-locationnotifier : timercountdown; do { caviumthunder(s->wss,buf+locationnotifier,alloccontroller+cachesysfs,icachealiases,&reschedinterrupt); sffsdrnandflash = SoDispCon_sendDataNT(con, 0, icachealiases+locationnotifier); if(sffsdrnandflash < 0) break; cachesysfs += icachealiases; icachealiases=end-cachesysfs; if(timerhandler < icachealiases) icachealiases=timerhandler; locationnotifier=0; } while (cachesysfs < end); con->exec(con,0,SoDispCon_ExTypeIdle,0,0); } } else sffsdrnandflash=SoDispCon_sendDataNT(con, alloccontroller+cachesysfs, timercountdown); if( sffsdrnandflash < 0 ) { asyncsetkey(s, L); return enterirqoff(L, sffsdrnandflash); } lua_pushboolean(L, TRUE); return 1; } static int hwmonchcfg(lua_State* L) { LSock* s = toLSock(L); size_t ssize; const U8* alloccontroller; int cachesysfs,end,op; int dIx = 2; if(s->sockType == LSockT_ServerListen) am35xautodeps(L); if( ! SoDispCon_isValid((SoDispCon*)s)) return enterirqoff(L, E_SOCKET_WRITE_FAILED); if( ! lua_isstring(L, 2) ) { const LByteArray* bytearray = isByteArray(L, 2); if(bytearray) { alloccontroller = bytearray->array + bytearray->startIx; ssize = (size_t)bytearray->len; goto L_hasData; } luaL_tolstring(L, 2, 0); lua_replace(L, 2); } alloccontroller = (U8*)luaL_checklstring(L, 2, &ssize); L_hasData: if(lua_isboolean(L,3)) { cachesysfs = 1; end = -1; op = lua_toboolean(L,3) ? WSOP_Text : WSOP_Binary; } else { if(s->wss) op=lua_isboolean(L,5) && lua_toboolean(L,5) ? WSOP_Text : WSOP_Binary; else op=0; cachesysfs = (int)luaL_optinteger(L, 3, 1); end = (int)luaL_optinteger(L, 4, -1); } if(cachesysfs < 0) cachesysfs = (int)ssize+cachesysfs+1; if(end < 0) end = (int)ssize+end+1; if(cachesysfs < 1) cachesysfs = 1; if(end > (int)ssize) end = (int)ssize; if(cachesysfs <= end) { cachesysfs--; if(s->wss && (end-cachesysfs) > 0xFFFF) luaL_error(L,"\115\141\170\040\154\145\156\040\060\170\106\106\106\106"); return removetable(s, L, dIx, alloccontroller, cachesysfs, end, op); } lua_pushboolean(L, FALSE); return 1; } static int LSock_ping(lua_State* L) { size_t allockuser; LSock* s = toLSock(L); const U8* alloccontroller=(U8*)luaL_optlstring(L,2,"\102\101\123",&allockuser); if( ! s->wss ) luaL_error(L,"\116\157\164\040\127\123"); return removetable(s,L,0,alloccontroller,0,allockuser, WSOP_Ping); } #ifdef USE_DGRAM static int registeruarts(lua_State* L) { LSock* s = toLSock(L); size_t ssize; int sffsdrnandflash; #ifdef USE_ADDRINFO BaAddrinfo hints; BaAddrinfo* serialports; char* sha256import; const char* hwmoddeassert; #else HttpSockaddr serialports; U16 hwmoddeassert; #endif const void* alloccontroller; const char* writereg16; if( ! lua_isstring(L, 2) ) { luaL_tolstring(L, 2, 0); lua_replace(L, 2); } alloccontroller = luaL_checklstring(L, 2, &ssize); writereg16 = luaL_checkstring(L, 3); if( ! SoDispCon_isDGRAM(&s->con.soCon) ) helperstart(L, "\116\157\164\040\141\040\104\107\122\101\115\040\163\157\143\153\145\164"); #ifdef USE_ADDRINFO hwmoddeassert = luaL_checkstring(L, 4); BaAddrinfo_hintsInit(&hints, TRUE, SoDispCon_isIP6(&s->con.soCon)); BaAddrinfo_get(writereg16, hwmoddeassert, &hints, &serialports, &sffsdrnandflash, &sha256import); if( ! sffsdrnandflash ) { BaAddrinfo_sendto(serialports,&s->con.soCon.httpSocket,alloccontroller,(int)ssize,&sffsdrnandflash); if(sffsdrnandflash > 0) { lua_pushboolean(L, TRUE); return 1; } else sffsdrnandflash = E_SOCKET_WRITE_FAILED; } else sffsdrnandflash = E_GETHOSTBYNAME; sffsdrnandflash=enterirqoff(L, sffsdrnandflash); if(sha256import) { lua_pushstring(L, sha256import); sffsdrnandflash++; } return sffsdrnandflash; #else hwmoddeassert = (U16)luaL_checkinteger(L, 4); HttpSockaddr_inetAddr(&serialports, writereg16, SoDispCon_isIP6(&s->con.soCon), &sffsdrnandflash); if(sffsdrnandflash != 0) { HttpSockaddr_gethostbyname( &serialports, writereg16, SoDispCon_isIP6(&s->con.soCon), &sffsdrnandflash); } if(sffsdrnandflash != 0) sffsdrnandflash=E_CANNOT_RESOLVE; else { HttpSocket_sendto( &s->con.soCon.httpSocket, alloccontroller, ssize, &serialports, hwmoddeassert, &sffsdrnandflash); sffsdrnandflash = sffsdrnandflash < 0 ? E_SOCKET_WRITE_FAILED : 0; } if(sffsdrnandflash) return enterirqoff(L, sffsdrnandflash); lua_pushboolean(L, TRUE); return 1; #endif } #endif static int eventvalid(lua_State* L) { LSock* s = toLSock(L); if(s->sockType != LSockT_ServerListen) helperstart(L, "\072\040\156\157\164\040\141\040\154\151\163\164\145\156\040\163\157\143\153\145\164"); if(s->closed) { if(s->flags & LSockFlag_ReadCalled) helperstart(L, "\072\040\123\157\143\153\145\164\040\143\154\157\163\145\144"); s->flags |= LSockFlag_ReadCalled; return enterirqoff(L, E_SOCKET_CLOSED); } s->sockState = LSockS_AsyncAccept; return lua_yield(L, 0); } static int emac1hwmod(lua_State* L) { LSock* s = toLSock(L); return pushCertificate(L, &s->con.soCon); } static int reportasync(lua_State* L) { LSock* s = toLSock(L); return pushCiphers(L, &s->con.soCon); } static int LSock_isresumed(lua_State* L) { SharkSslCon* sc; LSock* s = toLSock(L); if(SoDispCon_getSharkSslCon(&s->con.soCon, &sc) != TRUE) return reportpanic(L,baErr2Str(E_TLS_NOT_ENABLED)); lua_pushboolean(L, SharkSslCon_isResumed(sc)); return 1; } static int flashread16(lua_State* L) { SharkSslCon* sc; SharkSslConTrust t; const char* ethernatenable; LSock* s = toLSock(L); const char* writereg16 = luaL_optstring(L, 2, s->addr); if(SoDispCon_getSharkSslCon(&s->con.soCon, &sc) != TRUE) return reportpanic(L,baErr2Str(E_TLS_NOT_ENABLED)); t = SharkSslCon_trusted(sc, writereg16, 0); if(t == SharkSslConTrust_CertCnDate) { lua_pushboolean(L, TRUE); return 1; } switch(t) { case SharkSslConTrust_CertCn: ethernatenable="\143\145\162\164\143\156"; break; case SharkSslConTrust_Cert: ethernatenable = "\143\145\162\164"; break; case SharkSslConTrust_Cn: ethernatenable="\143\156"; break; default: ethernatenable = "\156\157\156\145"; } lua_pushnil(L); lua_pushstring(L, ethernatenable); return 2; } static int unregisterdevice(lua_State* L, int inputchannel) { HttpSockaddr serialports; int sffsdrnandflash; char buf[64]; U16 hwmoddeassert=0; LSock* s = toLSock(L); SoDispCon* con = &s->con.soCon; sffsdrnandflash = inputchannel ? SoDispCon_getSockName(con,&serialports,&hwmoddeassert) : SoDispCon_getPeerName(con,&serialports,&hwmoddeassert); if(sffsdrnandflash) return enterirqoff(L, sffsdrnandflash); lua_pushstring(L,SoDispCon_addr2String(con, &serialports, buf, sizeof(buf))); lua_pushinteger(L,hwmoddeassert); lua_pushboolean(L,SoDispCon_isIP6(con)); return 3; } static int timertimeout(lua_State* L) { return unregisterdevice(L, FALSE); } static int dcdc3consumers(lua_State* L) { return unregisterdevice(L, TRUE); } static int backtraceentry(lua_State* L, int sffsdrnandflash) { if(sffsdrnandflash) { lua_pushnil(L); #ifdef LUA_USE_WINDOWS { char* ethernatenable; sffsdrnandflash = WSAGetLastError() == 0 ? sffsdrnandflash : WSAGetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, sffsdrnandflash, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)ðernatenable, 0, NULL); lua_pushstring(L, ethernatenable); LocalFree(ethernatenable); } #elif defined(LUA_USE_LINUX) || defined(LUA_USE_MACOSX) lua_pushstring(L, strerror(sffsdrnandflash)); #else lua_pushliteral(L, "\146\141\151\154\145\144"); #endif lua_pushinteger(L, sffsdrnandflash); return 3; } lua_pushboolean(L, TRUE); return 1; } static int disableftrace(lua_State* L) { LSock* ls = toLSock(L); #if defined(HttpSocket_setKeepAlive) || defined(USE_DGRAM) int sffsdrnandflash=0; #endif #ifdef HttpSocket_setKeepAlive HttpSocket* s = &ls->con.soCon.httpSocket; #endif const char* op = luaL_checkstring(L, 2); int sdramresource = balua_checkboolean(L, 3); switch(*op) { case '\164': if( ! strcmp(op, "\164\143\160\055\156\157\144\145\154\141\171") ) { SoDispCon_setTCPNoDelay(&ls->con.soCon,sdramresource); return backtraceentry(L, 0); } break; case '\153': if( ! strcmp(op, "\153\145\145\160\141\154\151\166\145") ) { #ifdef HttpSocket_setKeepAlive int probecavium=(int)luaL_optinteger(L, 4, 0); int pcmciatable=(int)luaL_optinteger(L, 5, 0); if(probecavium > 0 && pcmciatable > 0) { #ifdef HttpSocket_setKeepAliveEx HttpSocket_setKeepAliveEx(s,sdramresource,probecavium,pcmciatable,&sffsdrnandflash); #else lua_pushnil(L); lua_pushstring(L, baErr2Str(IOINTF_NOIMPLEMENTATION)); return 2; #endif } else { HttpSocket_setKeepAlive(s,sdramresource,&sffsdrnandflash); } return backtraceentry(L, sffsdrnandflash); #else lua_pushnil(L); lua_pushstring(L, baErr2Str(IOINTF_NOIMPLEMENTATION)); return 2; #endif } break; #ifdef USE_DGRAM case '\144': if( ! strcmp(op, "\144\157\156\164\162\157\165\164\145") ) { HttpSocket_soDontroute(s,sdramresource,&sffsdrnandflash); return backtraceentry(L, sffsdrnandflash); } break; case '\142': if( ! strcmp(op, "\142\162\157\141\144\143\141\163\164") ) { HttpSocket_soBroadcast(s,sdramresource,&sffsdrnandflash); return backtraceentry(L, sffsdrnandflash); } break; case '\151': if( ! strcmp(op, "\151\160\055\155\145\155\142\145\162\163\150\151\160") ) { return backtraceentry( L, HttpSocket_setmembership( s,(BaBool)sdramresource,(BaBool)SoDispCon_isIP6(&ls->con.soCon), luaL_checkstring(L, 4),luaL_optstring(L, 5, 0))); } break; #endif } luaL_error(L, "\125\156\153\156\157\167\156\040\157\160\164\151\157\156\040\047\045\163\047", op); return 0; } static int pcmciawritel(lua_State* L) { int ok; int max = (int)lua_tointeger(L, 2); if(max > 256 && max <= 8*1024) { toLSock(L)->maxSendSize=max; ok=TRUE; } else ok=FALSE; lua_pushboolean(L, ok); return 1; } static int removegroup(lua_State* L) { LSock* s = toLSock(L); if(s->closed) lua_pushboolean(L, FALSE); else { #if 0 luaL_traceback(L, L, "\114\123\157\143\153\137\143\154\157\163\145\062", 1); HttpTrace_printf(0, "\045\163",lua_tostring(L, -1)); lua_pop(L, 1); #endif if(s->wss && SoDispCon_isValid(&s->con.soCon)) { pcie0write(s, L, WSSC_CLOSE, 0); } if(L == s->L) asyncsetkey(s, L); else pxa270evalboard(s, L); lua_pushboolean(L, TRUE); } return 1; } static int serial8250pdata(lua_State* L) { int sffsdrnandflash; LSock* s = toLSock(L); luaL_checktype(L, 2, LUA_TUSERDATA); if(s->closed || s->sharkSsl) lua_pushboolean(L, FALSE); else { lua_newtable(L); lua_pushliteral(L, "\163\150\141\162\153"); lua_pushvalue(L, 2); lua_rawset(L, -3); s->sharkSsl=lsharkssl_lock(L, -1, SharkSsl_Unspecified, 0); if(lua_isstring(L,3)) { if(s->alpnProtoList) baFree(s->alpnProtoList); s->alpnProtoList=baStrdup(lua_tostring(L,-1)); } if(s->L == L) { #ifdef NO_ASYNCH_RESP baAssert(0); #else if( ! SoDispCon_isNonBlocking(&s->con.soCon) ) { s->flags |= LSockFlag_IsBlocking; SoDispCon_setNonblocking(&s->con.soCon); } SoDispCon_releaseAsyncBuf(&s->con.soCon); sffsdrnandflash = hrtimerexpire(s); if( ! sffsdrnandflash ) { s->sockState = LSockS_AsyncUpgrade; return lua_yield(L, 0); } #endif } else { sffsdrnandflash=SoDispCon_upgrade( &s->con.soCon, s->sharkSsl, s->alpnProtoList, s->addr, s->port); } changeconfiguration(s); if(sffsdrnandflash <= 0) return enterirqoff(L, sffsdrnandflash); lua_pushboolean(L, TRUE); } return 1; } static int cachefixup(lua_State* L) { lua_pushboolean(L, (toLSock(L))->wss ? TRUE : FALSE); return 1; } static int mcbsphwmod(lua_State* L) { LSock* s = toLSock(L); lua_pushboolean(L, L == s->L); return 1; } static int currentstate(lua_State* L) { SharkSslCon* mmcsd0resources=0; int ok = FALSE; LSock* s = toLSock(L); SoDispCon_getSharkSslCon(&s->con.soCon, &mmcsd0resources); if(mmcsd0resources) ok = SharkSslCon_releaseSession(mmcsd0resources); lua_pushboolean(L, ok); return 1; } static int gpiodtable(lua_State* L) { LSock* s = toLSock(L); if(s->L) { s->L=L; } asyncsetkey(s, L); sockTotalCons--; return 0; } static int memdescversion(lua_State* L) { const char* e; LSock* s = toLSock(L); switch(s->sockState) { default: baAssert(0); case LSockS_NotConnected: e="\156\157\164\143\157\156"; break; case LSockS_Executing: e="\145\170\145\143"; break; case LSockS_AsyncAccept: e="\141\143\143\145\160\164"; break; case LSockS_AsyncConnect: e="\143\157\156\156\145\143\164"; break; case LSockS_AsyncUpgrade: e="\165\160\147\162\141\144\145"; break; case LSockS_Disabled: e="\144\151\163\141\142\154\145\144"; break; case LSockS_AsyncRead: e="\162\145\141\144"; break; case LSockS_AsyncWrite: e="\167\162\151\164\145"; break; case LSockS_Terminated: e="\164\145\162\155\151\156\141\164\145\144"; break; } lua_pushstring(L,e); lua_pushboolean(L,SoDispCon_isValid(&s->con.soCon)); return 2; } static int domainsimple(lua_State* L) { int valid, sockport,peerport; const char* state; const char* mailboxinterrupt; const char* writerandom; LSock* s = toLSock(L); memdescversion(L); valid = lua_toboolean(L, -1); state = lua_tostring(L, -2); if(valid || (s->flags & LSockFlag_NonSocket)) { if(s->flags & LSockFlag_NonSocket) { lua_pushfstring(L,"\133\120\151\160\145\040\045\160\040\123\072\045\163\135", s, state); } else { unregisterdevice(L, TRUE); mailboxinterrupt = lua_tostring(L, -3); sockport = (int)lua_tointeger(L, -2); unregisterdevice(L, FALSE); writerandom = lua_tostring(L, -3); peerport = (int)lua_tointeger(L, -2); lua_pushfstring(L,"\133\123\157\143\153\040\045\160\040\123\072\045\163\040\173\045\163\072\045\144\040\055\076\040\045\163\072\045\144\175\135", s, state,mailboxinterrupt,sockport,writerandom,peerport); } } else lua_pushfstring(L,"\133\123\157\143\153\040\045\160\040\123\072\045\163\135",s, state); return 1; } static const luaL_Reg sockLib[] = { {"\145\166\145\156\164", reservemutex}, #ifndef NO_ASYNCH_RESP {"\161\165\145\165\145\154\145\156", compatthread}, #endif {"\144\151\163\141\142\154\145", registerregulator}, {"\145\156\141\142\154\145", bypassconsumer}, {"\162\145\141\144", thumb16break}, {"\167\162\151\164\145", hwmonchcfg}, {"\160\151\156\147", LSock_ping}, #ifdef USE_DGRAM {"\163\145\156\144\164\157", registeruarts}, #endif {"\141\143\143\145\160\164", eventvalid}, {"\143\145\162\164\151\146\151\143\141\164\145", emac1hwmod}, {"\143\151\160\150\145\162", reportasync}, {"\151\163\162\145\163\165\155\145\144", LSock_isresumed}, {"\164\162\165\163\164\145\144", flashread16}, {"\160\145\145\162\156\141\155\145", timertimeout}, {"\163\157\143\153\156\141\155\145", dcdc3consumers}, {"\155\141\170\163\151\172\145", pcmciawritel}, {"\163\145\164\157\160\164\151\157\156", disableftrace}, {"\165\160\147\162\141\144\145", serial8250pdata}, {"\167\145\142\163\157\143\153\145\164", cachefixup}, {"\157\167\156\145\162", mcbsphwmod}, {"\162\145\154\163\145\163\163\151\157\156",currentstate}, {"\143\154\157\163\145", removegroup}, {"\137\137\143\154\157\163\145", removegroup}, {"\163\164\141\164\145", memdescversion}, {"\137\137\164\157\163\164\162\151\156\147", domainsimple}, {"\137\137\147\143", gpiodtable}, {NULL, NULL} }; static void u2ootgresources(HttpServCon* fdc37m81xconfig, HttpConnection* setupregion) { LSock* ns; LSock* s = (LSock*)fdc37m81xconfig; lua_State* L = s->L; SoDispCon* con; baAssert(lua_gettop(L) == 0); ns = createSock(L); if(SoDispCon_isSecure((SoDispCon*)fdc37m81xconfig)) { balua_getuservalue(L,1); LSock_get(L); luaL_ref(L, -2); lua_pop(L, 1); } ns->timer=s->timer; con=&ns->con.soCon; SoDispCon_moveCon((SoDispCon*)setupregion, con); con->dispatcher = ((SoDispCon*)setupregion)->dispatcher; ns->sockType=LSockT_Server; emulaterdlo12rdhi8rn16rm0(s, 1, FALSE); } static LSock* createSock(lua_State* L) { LSock* s = (LSock*)lua_newuserdata(L, sizeof(LSock)); memset(s, 0, sizeof(LSock)); s->sockState = LSockS_NotConnected; SoDispCon_invalidate(&s->con.soCon); #ifndef NO_ASYNCH_RESP SingleList_constructor(&s->msgQueue); DoubleList_constructor(&s->sockList); DoubleLink_constructor(&s->asyncWriteNode); s->maxMsgQueueLen = 16*1024; s->maxSendSize = 8*1024; #endif if(luaL_newmetatable(L, BASOCKET)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,sockLib,0); } lua_setmetatable(L, -2); sockTotalCons++; sockActiveCons++; return s; } #ifndef NO_ASYNCH_RESP static int timerindices(lua_State* L) { LSock* s; int top = lua_gettop(L); luaL_checktype(L, 1, LUA_TFUNCTION); s = createSock(L); SoDispCon_invalidate(&s->con.soCon); setupreturn(s, L, top+1); lua_pushvalue(L, -1); lua_insert(L, 2); lua_insert(L, 1); lua_xmove(L, s->L, top+1); if(emulaterdlo12rdhi8rn16rm0(s, top, FALSE)) lua_pushnil(L); else lua_settop(L, 1); return 1; } #endif static int wm8350pdata(lua_State* L) { const char* apecsmachine; BaBool moduleready; BaBool setupframe; LSock* s; BaLua_param* p = balua_getparam(L); U16 guestconfig1=(U16)luaL_checkinteger(L, 1); lGetStdSockOptions(L, 2, &apecsmachine, &moduleready, &setupframe); if((s=LSock_get(L)) != 0) { if((s->flags & LSockFlag_InUse) && !s->closed) return enterirqoff(L, E_INCORRECT_USE); } else s = createSock(L); s->closed=FALSE; s->flags = 0; s->timer=p->timer; s->sockType = LSockT_ServerListen; if(setupframe) { s->sharkSsl=lsharkssl_lock(L, 2, SharkSsl_Server, 0); HttpSharkSslServCon_constructor( &s->con.sslServer, s->sharkSsl, p->server, HttpServer_getDispatcher(p->server), guestconfig1, moduleready, apecsmachine, u2ootgresources); } else { HttpServCon_constructor( &s->con.server, p->server, HttpServer_getDispatcher(p->server), guestconfig1, moduleready, apecsmachine, u2ootgresources); } if(SoDispCon_isValid(&s->con.soCon)) { s->flags |= LSockFlag_InUse; if(s->L != L) { SoDisp_deactivateRec( HttpServer_getDispatcher(p->server),&s->con.soCon); } return 1; } if(s->sharkSsl) { HttpSharkSslServCon_destructor(&s->con.sslServer); lsharkssl_unlock(L,s->sharkSsl); s->sharkSsl=0; } else HttpServCon_destructor(&s->con.server); return enterirqoff(L, E_BIND); } #ifdef USE_DGRAM static int tx4927pcicptr(lua_State* L) { BaBool reservedbytes; int sffsdrnandflash; int tIx; LSock* s; BaBool moduleready = FALSE; U16 hwmoddeassert=0; U16 dm9000resource=0; const char* apecsmachine=0; char* sha256import=0; const char* serialports=0; BaLua_param* p = balua_getparam(L); SoDisp* ptraceaccess = HttpServer_getDispatcher(p->server); if(lua_type(L, 1) == LUA_TSTRING) { serialports = luaL_checkstring(L, 1); if(serialports && !*serialports) serialports = 0; hwmoddeassert=(U16)luaL_checkinteger(L, 2); if(!serialports) dm9000resource = hwmoddeassert; tIx=3; } else if(lua_type(L, 1) == LUA_TNUMBER) { dm9000resource = (U16)luaL_checkinteger(L, 1); tIx = 2; } else tIx=1; if(lua_type(L, tIx) == LUA_TTABLE) { BaBool setupframe; lGetStdSockOptions(L, tIx, &apecsmachine, &moduleready, &setupframe); lua_getfield(L, tIx, "\160\157\162\164"); if( ! lua_isnoneornil(L,-1) ) dm9000resource=(U16)luaL_checkinteger(L, -1); lua_pop(L,1); } if((s=LSock_get(L)) != 0) { if((s->flags & LSockFlag_InUse) && !s->closed) return enterirqoff(L, E_INCORRECT_USE); reservedbytes=TRUE; } else { s = createSock(L); reservedbytes=FALSE; } s->closed=FALSE; s->flags = 0; s->timer=p->timer; s->sockType=LSockT_Client; SoDispCon_constructor(&s->con.soCon, ptraceaccess, resetonline); if(reservedbytes) { #ifdef NO_ASYNCH_RESP return reportpanic(L, "\156\157\141\163\171\156\143\167\162\151\164\145"); #else SoDispCon_setDispSendEvent(&s->con.soCon, eventcallback); #endif } SoDisp_addConnection(ptraceaccess, &s->con.soCon); if(serialports) { sffsdrnandflash = SoDispCon_connect( &s->con.soCon,serialports,hwmoddeassert,apecsmachine,dm9000resource,1,TRUE,moduleready,&sha256import); } else { HttpServCon_bindExec(&s->con.soCon); s->con.soCon.dataBits |= SoDispCon_DGramBitMask; if(moduleready) s->con.soCon.dataBits |= SoDispCon_IP6DataBitMask; sffsdrnandflash=HttpSocket_create(&s->con.soCon.httpSocket,apecsmachine,dm9000resource,TRUE,moduleready); } if(sffsdrnandflash < 0) { sffsdrnandflash=enterirqoff(L, sffsdrnandflash); if(sha256import) { lua_pushstring(L, sha256import); sffsdrnandflash++; } return sffsdrnandflash; } s->flags |= LSockFlag_InUse; SoDisp_activateRec(ptraceaccess, &s->con.soCon); return 1; } #endif static int commonpages(lua_State* L) { int sffsdrnandflash; const char* apecsmachine; BaBool reservedbytes; BaBool moduleready; BaBool setupframe; LSock* s; char* sha256import; const char* ptracegethbpregs=0; U32 pciercxcfg035=1000; BaLua_param* p = balua_getparam(L); SoDisp* ptraceaccess = HttpServer_getDispatcher(p->server); const char* serialports = luaL_checkstring(L, 1); U16 hwmoddeassert = (U16)luaL_checkinteger(L, 2); lGetStdSockOptions(L, 3, &apecsmachine, &moduleready, &setupframe); if(lua_type(L, 3) == LUA_TTABLE) { lua_getfield(L, 3, "\164\151\155\145\157\165\164"); if(lua_isinteger(L,-1)) pciercxcfg035=(U32)lua_tointeger(L,-1); lua_getfield(L, 3, "\141\154\160\156"); if(lua_isstring(L,-1)) ptracegethbpregs=lua_tostring(L,-1); lua_pop(L,2); } if((s=LSock_get(L)) != 0) { if((s->flags & LSockFlag_InUse) && !s->closed) return enterirqoff(L, E_INCORRECT_USE); reservedbytes=TRUE; } else { s = createSock(L); reservedbytes=FALSE; } s->closed=FALSE; s->flags = 0; s->timer=p->timer; s->sockType=LSockT_Client; SoDispCon_constructor(&s->con.soCon, ptraceaccess, resetonline); if(setupframe && ptracegethbpregs) s->alpnProtoList=baStrdup(ptracegethbpregs); if(reservedbytes) { #ifdef NO_ASYNCH_RESP return reportpanic(L, "\156\157\141\163\171\156\143\167\162\151\164\145"); #else SoDispCon_setDispSendEvent(&s->con.soCon, eventcallback); SoDisp_addConnection(ptraceaccess, &s->con.soCon); #endif } if(s->sharkSsl) { baAssert(SoDispCon_isSecure(&s->con.soCon)); lsharkssl_unlock(L,s->sharkSsl); s->sharkSsl=0; } if(setupframe) s->sharkSsl=lsharkssl_lock(L, 3, SharkSsl_Client, 0); #ifndef NO_ASYNCH_RESP if(reservedbytes) { sffsdrnandflash = SoDispCon_asyncConnect( &s->con.soCon,serialports,hwmoddeassert,apecsmachine,moduleready,&sha256import); } else #endif { sffsdrnandflash = SoDispCon_connect( &s->con.soCon,serialports,hwmoddeassert,apecsmachine,0,pciercxcfg035,FALSE,moduleready,&sha256import); } if(sffsdrnandflash < 0) { sffsdrnandflash=enterirqoff(L, sffsdrnandflash); if(sha256import) { lua_pushstring(L, sha256import); sffsdrnandflash++; } return sffsdrnandflash; } if(!sffsdrnandflash) { #ifndef NO_ASYNCH_RESP if(reservedbytes) SoDisp_activateSend(ptraceaccess, &s->con.soCon); else #endif SoDisp_activateRec(ptraceaccess, &s->con.soCon); } if(s->addr) { baFree(s->addr); s->addr=0; } s->addr = (char*)baLMalloc(L,strlen(serialports)+1); if(s->addr) strcpy(s->addr,serialports); s->port = hwmoddeassert; if(!reservedbytes || sffsdrnandflash) { if(setupframe) { sffsdrnandflash=SoDispCon_upgrade( &s->con.soCon,s->sharkSsl,s->alpnProtoList, serialports,hwmoddeassert); if(sffsdrnandflash <= 0) { return enterirqoff(L, sffsdrnandflash); } } } #ifndef NO_ASYNCH_RESP else { s->flags |= LSockFlag_InUse; baAssert( ! s->tkey ); s->tkey=BaTimer_set(s->timer,adjustitstate,s,pciercxcfg035); s->sockState = LSockS_AsyncConnect; return lua_yield(L, 0); } #endif s->flags |= LSockFlag_InUse; return 1; } static LSock* moveSockCon(lua_State* L, SoDispCon* con, LSockT eventdevice) { LSock* s; SoDispCon* dupCon; BaLua_param* p = balua_getparam(L); s = createSock(L); s->timer=p->timer; dupCon=&s->con.soCon; SoDispCon_moveCon(con, dupCon); dupCon->dispatcher = con->dispatcher; s->sockType=(U8)eventdevice; return s; } #ifndef NO_BA_SERVER static int switcherremoved(lua_State* L) { HttpCommand* cmd=baluaENV_checkcmd(L, 1); SoDispCon* con = (SoDispCon*)HttpRequest_getConnection(&cmd->request); HttpInData* registeredevent = HttpRequest_getBuffer(&cmd->request); S32 icachealiases = HttpInData_getBufSize(registeredevent); if(domainnotifier(L,2,FALSE) || HttpRequest_wsUpgrade(&cmd->request)) { if( ! SoDispCon_isValid(con) ) return enterirqoff(L, E_SOCKET_CLOSED); moveSockCon(L,con,LSockT_Server); if(icachealiases) { lua_pushlstring(L, HttpInData_getBuf(registeredevent), icachealiases); return 2; } } else { LSock* s = moveSockCon(L,con,LSockT_Server); LSockWsState* wss = (LSockWsState*)baLMalloc(L, sizeof(LSockWsState)); if( ! wss ) return enterirqoff(L,E_MALLOC); memset(wss, 0, sizeof(LSockWsState)); wss->flags = LSockWsStateFlag_Server; s->wss=wss; if(icachealiases) { wss->overflowBase = (U8*)baLMalloc(L,icachealiases); if( ! wss->overflowBase ) return enterirqoff(L,E_MALLOC); memcpy(wss->overflowBase,HttpInData_getBuf(registeredevent),icachealiases); wss->overflowPtr=wss->overflowBase; } } return 1; } static int keypadplatdata(lua_State* L) { LSock* s = toLSock(L); SoDispCon* con= &s->con.soCon; if(HttpSocket_isValid(&con->httpSocket)) { HttpConnection hcon; size_t pdLen; BaLua_param* p = balua_getparam(L); if(SoDispCon_isNonBlocking(con)) SoDispCon_setBlocking(con); HttpConnection_constructor(&hcon,p->server,0,0); SoDispCon_moveCon(con, (SoDispCon*)&hcon); hcon.pushBackData = (void*)luaL_optlstring(L, 2, 0, &pdLen); hcon.pushBackDataSize = pdLen; HttpConnection_setKeepAlive(&hcon); HttpServer_addCon2ConnectedList(p->server,&hcon); } return 0; } #endif #ifndef NO_HTTP_CLIENT static int rm200i8259(lua_State* L) { int icachealiases; LSock* s; HttpClient* c; const char* v; if(lua_type(L, 1) == LUA_TTABLE) { lua_getfield(L, 1, "\162\141\167"); c=toHttpClient(L, -1); } else c=toHttpClient(L, 1); if( ! SoDispCon_isValid((SoDispCon*)c) || HttpClient_getStatus(c) < 0 ) return enterirqoff(L, E_INVALID_SOCKET_CON); if( (v=HttpClient_getHeaderValue(c,"\123\145\143\055\127\145\142\123\157\143\153\145\164\055\101\143\143\145\160\164")) != 0) { if(v[0] != '\106' || v[1] != '\063') return enterirqoff(L, E_INVALID_SOCKET_CON); } icachealiases = HttpClient_getBufSize(c); if(icachealiases > 0 || SoDispCon_hasMoreData((SoDispCon*)c)) { luaL_Buffer lb; luaL_buffinit(L, &lb); if(icachealiases > 0) { broadcastenable(c, luaL_prepbuffsize(&lb, (size_t)icachealiases), icachealiases); luaL_addsize(&lb, icachealiases); } while(SoDispCon_hasMoreData((SoDispCon*)c)) { char* buf = luaL_prepbuffsize(&lb, 8192); icachealiases=SoDispCon_readData((SoDispCon*)c, buf, 8192, FALSE); if (icachealiases > 0) { luaL_addsize(&lb, icachealiases); } else { icachealiases = 1; break; } } luaL_pushresult(&lb); } s=moveSockCon(L, (SoDispCon*)c, LSockT_Client); if(icachealiases > 0) lua_rotate(L, -2, 1); if(v) { LSockWsState* wss = (LSockWsState*)baLMalloc(L, sizeof(LSockWsState)); if( ! wss ) return enterirqoff(L,E_MALLOC); memset(wss, 0, sizeof(LSockWsState)); s->wss=wss; } return icachealiases > 0 ? 2 : 1; } #endif static int ptrauthfault(lua_State* L) { HttpSockaddr serialports; int sffsdrnandflash; char buf[64]; const char* writereg16 = luaL_checkstring(L, 1); #ifdef USE_IPV6 BaBool percpuorder = (BaBool)domainnotifier(L, 2, FALSE); HttpSockaddr_gethostbyname(&serialports, writereg16, percpuorder, &sffsdrnandflash); #else HttpSockaddr_gethostbyname(&serialports, writereg16, FALSE, &sffsdrnandflash); #endif if( ! sffsdrnandflash ) HttpSockaddr_addr2String(&serialports, buf, sizeof(buf), &sffsdrnandflash); if( sffsdrnandflash ) return enterirqoff(L, E_CANNOT_RESOLVE); lua_pushstring(L,buf); return 1; } static int epollevent(lua_State* L) { size_t allockuser; lua_Integer out=0; int icachealiases = (int)luaL_checkinteger(L,1); const U8* in=(U8*)luaL_checklstring(L, 2, &allockuser); int idmapstart = (int)luaL_optinteger(L, 3, 1) - 1; if(idmapstart < 0 || (size_t)(idmapstart+icachealiases) > allockuser) luaL_error(L, "\111\156\166\141\154\151\144\040\157\146\146\163\145\164"); in += idmapstart; #ifdef B_LITTLE_ENDIAN extracontext(L, (U8*)&out, in, icachealiases); #else if(icachealiases < 1 || icachealiases > sizeof(lua_Integer)) luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); memcpy(((U8*)&out)+sizeof(lua_Integer)-icachealiases,in,icachealiases); #endif lua_pushinteger(L, out); return 1; } static int retunemobile(lua_State* L) { U8 out[sizeof(lua_Integer)]; int icachealiases = (int)luaL_checkinteger(L,1); lua_Unsigned n = (lua_Unsigned)luaL_checkinteger(L,2); U8* in = (U8*)&n; #ifdef B_LITTLE_ENDIAN extracontext(L, out, in, icachealiases); #else if(icachealiases < 1 || icachealiases > sizeof(lua_Integer)) luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); memcpy(out,in+sizeof(lua_Integer)-icachealiases,icachealiases); #endif lua_pushlstring(L, (char*)out, (size_t)icachealiases); return 1; } typedef union { float f; double d; U8 data[1]; } FloatContainer; static int commonboard(lua_State* L) { FloatContainer fc; size_t allockuser; int icachealiases = (int)luaL_checkinteger(L,1); const U8* in = (U8*)luaL_checklstring(L, 2, &allockuser); int idmapstart = (int)luaL_optinteger(L, 3, 1) - 1; if(idmapstart < 0 || (size_t)(idmapstart+icachealiases) > allockuser) luaL_error(L, "\111\156\166\141\154\151\144\040\157\146\146\163\145\164"); in += idmapstart; if(icachealiases != 4 && icachealiases != 8) luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); #ifdef B_LITTLE_ENDIAN extracontext(L, fc.data, in, icachealiases); #else memcpy(fc.data+sizeof(FloatContainer)-icachealiases,in,icachealiases); #endif if(icachealiases == 4) lua_pushnumber(L, fc.f); else lua_pushnumber(L, fc.d); return 1; } static int sigpagemremap(lua_State* L) { FloatContainer fc; U8 out[sizeof(FloatContainer)]; int icachealiases = (int)luaL_checkinteger(L,1); lua_Number n = luaL_checknumber(L,2); if(icachealiases == 4) fc.f = (float)n; else if(icachealiases == 8) fc.d = (double)n; else luaL_error(L,"\111\156\166\141\154\151\144\040\163\151\172\145"); #ifdef B_LITTLE_ENDIAN extracontext(L, out, fc.data, icachealiases); #else memcpy(out,fc.data+sizeof(FloatContainer)-icachealiases,icachealiases); #endif lua_pushlstring(L, (char*)out, (size_t)icachealiases); return 1; } static int randombytes(lua_State* L) { if( ! LSock_get(L) ) lua_pushnil(L); return 1; } static int fixmapshutdown(lua_State* L) { lua_pushinteger(L,sockTotalCons); lua_pushinteger(L,sockActiveCons); return 2; } static const luaL_Reg sockLib2[] = { #ifndef NO_ASYNCH_RESP {"\145\166\145\156\164", timerindices}, #endif {"\142\151\156\144", wm8350pdata}, {"\143\157\156\156\145\143\164", commonpages}, #ifdef USE_DGRAM {"\165\144\160\143\157\156", tx4927pcicptr}, #endif #ifndef NO_BA_SERVER {"\162\145\161\062\163\157\143\153", switcherremoved}, {"\163\157\143\153\062\162\145\161", keypadplatdata}, #endif #ifndef NO_HTTP_CLIENT {"\150\164\164\160\062\163\157\143\153", rm200i8259}, #endif {"\164\157\151\160", ptrauthfault}, {"\156\062\150", epollevent}, {"\150\062\156", retunemobile}, {"\146\156\062\150", commonboard}, {"\146\150\062\156", sigpagemremap}, {"\147\145\164\163\157\143\153", randombytes}, {"\163\164\141\164", fixmapshutdown}, {NULL, NULL} }; #if USE_LPIPE static int tc6393xbteardown(lua_State* L) { lua_pushnil(L); lua_pushstring(L, strerror(errno)); return 2; } static void unregisterahash(SoDispCon* con) { SoDispCon_releaseAsyncBuf(con); close(con->httpSocket.hndl); SoDispCon_invalidate(con); } static int aemiftiming(SoDispCon* con,ThreadMutex* m,SoDispCon_ExType s,void* alloccontroller,int len) { switch(s) { case SoDispCon_ExTypeRead: SoDispCon_clearHasMoreData(con); if( (len=read(con->httpSocket.hndl,alloccontroller,len)) < 0) { if(errno != EAGAIN) { unregisterahash(con); return E_SOCKET_READ_FAILED; } len=0; } return len; case SoDispCon_GetSharkSslCon: if(alloccontroller) *((void**)alloccontroller) = 0; return FALSE; case SoDispCon_ExTypeClose: unregisterahash(con); return 0; case SoDispCon_ExTypeAllocAsynchBuf: SoDispCon_internalAllocAsynchBuf(con, (AllocAsynchBufArgs*)alloccontroller); return 0; case SoDispCon_ExTypeAsyncReady: if(con->sslData) { NonBlockingSendBuf* buf = (NonBlockingSendBuf*)con->sslData; if( ! buf->bufLen ) { if( ! len ) return 1; baAssert(buf->maxBufLen >= len); buf->bufLen = len; } len = buf->bufLen - buf->cursor; len=write(con->httpSocket.hndl,buf->buf+buf->cursor, len); if(len < 0) { if(errno != EAGAIN) { unregisterahash(con); return E_SOCKET_WRITE_FAILED; } len=0; } buf->cursor+=len; baAssert(buf->cursor <= buf->bufLen); if(buf->cursor == buf->bufLen) { buf->cursor = buf->bufLen = 0; return 1; } return 0; } return 1; case SoDispCon_ExTypeIdle: SoDispCon_releaseAsyncBuf(con); return TRUE; default: baAssert(0); return -1; } baAssert(0); return -1; } static int preferredconsole(lua_State* L) { int fd,top; LSock* s; SoDispCon* con; BaLua_param* p = balua_getparam(L); SoDisp* ptraceaccess = HttpServer_getDispatcher(p->server); int sharevideo = lua_isfunction(L, 2); if( ! sharevideo ) { lua_pushcfunction(L, registerregulator); lua_insert(L, 2); } fd = open(luaL_checkstring(L, 1), (sharevideo ? O_RDWR : O_WRONLY) | O_NONBLOCK); if(fd < 0) return tc6393xbteardown(L); lua_remove(L, 1); top = lua_gettop(L); s = createSock(L); setupreturn(s, L, top+1); con = &s->con.soCon; SoDispCon_constructor(con, ptraceaccess, resetonline); con->httpSocket.hndl=fd; con->dataBits = SoDispCon_isNonBlockingDataBitMask; con->exec=aemiftiming; s->closed=FALSE; s->flags = LSockFlag_NonSocket; s->timer=p->timer; s->sockType=LSockT_Client; SoDispCon_setDispSendEvent(con, eventcallback); SoDisp_addConnection(ptraceaccess, con); SoDisp_activateRec(ptraceaccess, con); lua_pushvalue(L, -1); lua_insert(L, 2); lua_insert(L, 1); lua_xmove(L, s->L, top+1); if(emulaterdlo12rdhi8rn16rm0(s, top, FALSE)) lua_pushnil(L); else lua_settop(L, 1); return 1; } static int pointertable(lua_State* L) { if(mkfifo(luaL_checkstring(L, 1), (mode_t)luaL_optinteger(L, 2, S_IRWXU))) return tc6393xbteardown(L); lua_pushboolean(L, TRUE); return 1; } static const luaL_Reg pipeLib[] = { {"\157\160\145\156", preferredconsole}, {"\155\153\146\151\146\157", pointertable}, {NULL, NULL} }; static void smcccquirk(lua_State* L) { balua_newlib(L, pipeLib); lua_setfield(L, -2, "\160\151\160\145"); } #endif #ifndef BA_NO_LUASOCK_COMPAT static void devicenames(lua_State* L); #endif void balua_socket(lua_State* L) { lua_createtable(L, 0, 0); lua_createtable(L, 0, 1); lua_pushliteral(L, "\153\166"); lua_setfield(L, -2, "\137\137\155\157\144\145"); lua_setmetatable(L, -2); lua_setfield(L, LUA_REGISTRYINDEX, BASOCKTAB); lua_getglobal(L, "\142\141"); balua_newlib(L, sockLib2); lua_setfield(L, -2, "\163\157\143\153\145\164"); lua_createtable(L,0,sizeof(bytearrayLib)/sizeof(bytearrayLib[0])-1); luaL_setfuncs(L,bytearrayLib,0); lua_setfield(L, -2, "\142\171\164\145\141\162\162\141\171"); #if USE_LPIPE smcccquirk(L); #endif lua_pop(L,1); #ifndef BA_NO_LUASOCK_COMPAT devicenames(L); #endif sockTotalCons=0; sockActiveCons=0; } void balua_relsocket(lua_State* L) { lua_getfield(L,LUA_REGISTRYINDEX,BASOCKTAB); if( lua_type(L, -1) == LUA_TTABLE ) { lua_pushnil(L); while (lua_next(L, -2) != 0) { LSock* s = (LSock*)lua_touserdata(L, -1); if(s->sockState != LSockS_Disabled && !s->closed) buttonsdlink(s, E_SYS_SHUTDOWN); lua_pop(L, 1); } } lua_pop(L,1); } #ifndef BA_NO_LUASOCK_COMPAT static int mcbspsidetone(lua_State *L) { lua_pushvalue(L, lua_upvalueindex(1)); lua_insert(L, 1); #if 0 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); #else if(lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0) != 0) { lua_pushnil(L); lua_insert(L, 1); return 2; } #endif return lua_gettop(L); } static int uaccesswrite(lua_State *L) { lua_settop(L, 1); lua_pushcclosure(L, mcbspsidetone, 1); return 1; } static int decodethumb32(lua_State *L) { if(!lua_toboolean(L, 1)) { lua_pushvalue(L, lua_upvalueindex(1)); lua_pcall(L, 0, 0, 0); lua_settop(L, 2); lua_error(L); return 0; } else return lua_gettop(L); } static int gpio27disable(lua_State *L) { (void) L; return 0; } static int targetwindow1(lua_State *L) { lua_settop(L, 1); if(lua_isnil(L, 1)) lua_pushcfunction(L, gpio27disable); lua_pushcclosure(L, decodethumb32, 1); return 1; } static int memcpylikely(lua_State *L) { int framecount = (int)luaL_checkinteger(L, 1); int ret = lua_gettop(L) - framecount - 1; return ret >= 0 ? ret : 0; } static const luaL_Reg compatLib[] = { {"\160\162\157\164\145\143\164", uaccesswrite}, {"\156\145\167\164\162\171", targetwindow1}, {"\163\153\151\160", memcpylikely}, {NULL, NULL} }; #define MIME_API static #define BA_MIME #ifndef BA_MIME #error Do not directly compile this guestconfig2. This debugsetup is included by lsocket.c #endif #include #include "lua.h" #include "lauxlib.h" #if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501) #include "compat-5.1.h" #endif #include "mime.h" typedef unsigned char UC; static const char CRLF[] = "\015\012"; static const char EQCRLF[] = "\075\015\012"; static int singlefsqrt(lua_State *L); static int labelstate(lua_State *L); static int backlightdevices(lua_State *L); static int queryregister(lua_State *L); static int cpuinfochain(lua_State *L); static int resourcestart(lua_State *L); static int barrierhooks(lua_State *L); static int emulaterd8rn16rm0ra12(lua_State *L); static size_t dot(int c, size_t state, luaL_Buffer *startcounter); static void keystonetable(UC *internalinput); static size_t levelentry(UC c, UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter); static size_t dummywaitbut(const UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter); static size_t onenandsetname(UC c, UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter); static void prminstdeassert(UC *prminstassert, UC *usb11resources); static void afterupdate(UC c, luaL_Buffer *startcounter); static size_t simtecpowercontrol(UC c, UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter); static size_t enablesmartreflex(UC c, UC *updatecause, size_t icachealiases, const char *enablecoherency, luaL_Buffer *startcounter); static size_t gpio6config(UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter); static luaL_Reg mimeFuncs[] = { { "\144\157\164", emulaterd8rn16rm0ra12 }, { "\142\066\064", labelstate }, { "\145\157\154", barrierhooks }, { "\161\160", queryregister }, { "\161\160\167\162\160", resourcestart }, { "\165\156\142\066\064", backlightdevices }, { "\165\156\161\160", cpuinfochain }, { "\167\162\160", singlefsqrt }, { NULL, NULL } }; static UC prminstassert[256]; static UC qpbase[] = "\060\061\062\063\064\065\066\067\070\071\101\102\103\104\105\106"; static UC usb11resources[256]; enum {QP_PLAIN, QP_QUOTED, QP_CR, QP_IF_LAST}; static const UC b64base[] = "\101\102\103\104\105\106\107\110\111\112\113\114\115\116\117\120\121\122\123\124\125\126\127\130\131\132\141\142\143\144\145\146\147\150\151\152\153\154\155\156\157\160\161\162\163\164\165\166\167\170\171\172\060\061\062\063\064\065\066\067\070\071\053\057"; static UC internalinput[256]; MIME_API int luaopen_mime_core(lua_State *L) { lua_pushglobaltable(L); luaL_newlib(L,mimeFuncs); lua_setfield(L,-2,"\155\151\155\145"); lua_pop(L,1); prminstdeassert(prminstassert, usb11resources); keystonetable(internalinput); return 1; } static int singlefsqrt(lua_State *L) { size_t icachealiases = 0; int dm9000platdata = (int) luaL_checknumber(L, 1); const UC *updatecause = (UC *) luaL_optlstring(L, 2, NULL, &icachealiases); const UC *timerenable = updatecause + icachealiases; int traceleave = (int) luaL_optnumber(L, 3, 76); luaL_Buffer startcounter; if (!updatecause) { if (dm9000platdata < traceleave) lua_pushstring(L, CRLF); else lua_pushnil(L); lua_pushinteger(L, traceleave); return 2; } luaL_buffinit(L, &startcounter); while (updatecause < timerenable) { switch (*updatecause) { case '\015': break; case '\012': luaL_addstring(&startcounter, CRLF); dm9000platdata = traceleave; break; default: if (dm9000platdata <= 10) { if(bIsspace(*updatecause) || dm9000platdata <= 0) { dm9000platdata = traceleave; luaL_addstring(&startcounter, CRLF); if(!bIsspace(*updatecause)) luaL_addchar(&startcounter, *updatecause); } else luaL_addchar(&startcounter, *updatecause); } else luaL_addchar(&startcounter, *updatecause); dm9000platdata--; break; } updatecause++; } luaL_pushresult(&startcounter); lua_pushinteger(L,dm9000platdata); return 2; } static void keystonetable(UC *internalinput) { int i; for (i = 0; i <= 255; i++) internalinput[i] = (UC) 255; for (i = 0; i < 64; i++) internalinput[b64base[i]] = (UC) i; internalinput['\075'] = 0; } static size_t levelentry(UC c, UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter) { updatecause[icachealiases++] = c; if (icachealiases == 3) { UC guestconfig2[4]; unsigned long videoprobe = 0; videoprobe += updatecause[0]; videoprobe <<= 8; videoprobe += updatecause[1]; videoprobe <<= 8; videoprobe += updatecause[2]; guestconfig2[3] = b64base[videoprobe & 0x3f]; videoprobe >>= 6; guestconfig2[2] = b64base[videoprobe & 0x3f]; videoprobe >>= 6; guestconfig2[1] = b64base[videoprobe & 0x3f]; videoprobe >>= 6; guestconfig2[0] = b64base[videoprobe]; luaL_addlstring(startcounter, (char *) guestconfig2, 4); icachealiases = 0; } return icachealiases; } static size_t dummywaitbut(const UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter) { unsigned long videoprobe = 0; UC guestconfig2[4] = {'\075', '\075', '\075', '\075'}; switch (icachealiases) { case 1: videoprobe = updatecause[0] << 4; guestconfig2[1] = b64base[videoprobe & 0x3f]; videoprobe >>= 6; guestconfig2[0] = b64base[videoprobe]; luaL_addlstring(startcounter, (char *) guestconfig2, 4); break; case 2: videoprobe = updatecause[0]; videoprobe <<= 8; videoprobe |= updatecause[1]; videoprobe <<= 2; guestconfig2[2] = b64base[videoprobe & 0x3f]; videoprobe >>= 6; guestconfig2[1] = b64base[videoprobe & 0x3f]; videoprobe >>= 6; guestconfig2[0] = b64base[videoprobe]; luaL_addlstring(startcounter, (char *) guestconfig2, 4); break; default: break; } return 0; } static size_t onenandsetname(UC c, UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter) { if (internalinput[c] > 64) return icachealiases; updatecause[icachealiases++] = c; if (icachealiases == 4) { UC decoded[3]; int valid, videoprobe = 0; videoprobe = internalinput[updatecause[0]]; videoprobe <<= 6; videoprobe |= internalinput[updatecause[1]]; videoprobe <<= 6; videoprobe |= internalinput[updatecause[2]]; videoprobe <<= 6; videoprobe |= internalinput[updatecause[3]]; decoded[2] = (UC) (videoprobe & 0xff); videoprobe >>= 8; decoded[1] = (UC) (videoprobe & 0xff); videoprobe >>= 8; decoded[0] = (UC) videoprobe; valid = (updatecause[2] == '\075') ? 1 : (updatecause[3] == '\075') ? 2 : 3; luaL_addlstring(startcounter, (char *) decoded, valid); return 0; } else return icachealiases; } static int labelstate(lua_State *L) { UC atom[3]; size_t isize = 0, asize = 0; const UC *updatecause = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *timerenable = updatecause + isize; luaL_Buffer startcounter; if (!updatecause) { lua_pushnil(L); lua_pushnil(L); return 2; } lua_settop(L, 2); luaL_buffinit(L, &startcounter); while (updatecause < timerenable) asize = levelentry(*updatecause++, atom, asize, &startcounter); updatecause = (UC *) luaL_optlstring(L, 2, NULL, &isize); if (!updatecause) { size_t hugetlbvalid = 0; asize = dummywaitbut(atom, asize, &startcounter); luaL_pushresult(&startcounter); lua_tolstring(L, -1, &hugetlbvalid); if (hugetlbvalid == 0) lua_pushnil(L); lua_pushnil(L); return 2; } timerenable = updatecause + isize; while (updatecause < timerenable) asize = levelentry(*updatecause++, atom, asize, &startcounter); luaL_pushresult(&startcounter); lua_pushlstring(L, (char *) atom, asize); return 2; } static int backlightdevices(lua_State *L) { UC atom[4]; size_t isize = 0, asize = 0; const UC *updatecause = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *timerenable = updatecause + isize; luaL_Buffer startcounter; if (!updatecause) { lua_pushnil(L); lua_pushnil(L); return 2; } lua_settop(L, 2); luaL_buffinit(L, &startcounter); while (updatecause < timerenable) asize = onenandsetname(*updatecause++, atom, asize, &startcounter); updatecause = (UC *) luaL_optlstring(L, 2, NULL, &isize); if (!updatecause) { size_t hugetlbvalid = 0; luaL_pushresult(&startcounter); lua_tolstring(L, -1, &hugetlbvalid); if (hugetlbvalid == 0) lua_pushnil(L); lua_pushnil(L); return 2; } timerenable = updatecause + isize; while (updatecause < timerenable) asize = onenandsetname(*updatecause++, atom, asize, &startcounter); luaL_pushresult(&startcounter); lua_pushlstring(L, (char *) atom, asize); return 2; } static void prminstdeassert(UC *prminstassert, UC *usb11resources) { int i; for (i = 0; i < 256; i++) prminstassert[i] = QP_QUOTED; for (i = 33; i <= 60; i++) prminstassert[i] = QP_PLAIN; for (i = 62; i <= 126; i++) prminstassert[i] = QP_PLAIN; prminstassert['\011'] = QP_IF_LAST; prminstassert['\040'] = QP_IF_LAST; prminstassert['\015'] = QP_CR; for (i = 0; i < 256; i++) usb11resources[i] = 255; usb11resources['\060'] = 0; usb11resources['\061'] = 1; usb11resources['\062'] = 2; usb11resources['\063'] = 3; usb11resources['\064'] = 4; usb11resources['\065'] = 5; usb11resources['\066'] = 6; usb11resources['\067'] = 7; usb11resources['\070'] = 8; usb11resources['\071'] = 9; usb11resources['\101'] = 10; usb11resources['\141'] = 10; usb11resources['\102'] = 11; usb11resources['\142'] = 11; usb11resources['\103'] = 12; usb11resources['\143'] = 12; usb11resources['\104'] = 13; usb11resources['\144'] = 13; usb11resources['\105'] = 14; usb11resources['\145'] = 14; usb11resources['\106'] = 15; usb11resources['\146'] = 15; } static void afterupdate(UC c, luaL_Buffer *startcounter) { luaL_addchar(startcounter, '\075'); luaL_addchar(startcounter, qpbase[c >> 4]); luaL_addchar(startcounter, qpbase[c & 0x0F]); } static size_t enablesmartreflex(UC c, UC *updatecause, size_t icachealiases, const char *enablecoherency, luaL_Buffer *startcounter) { updatecause[icachealiases++] = c; while (icachealiases > 0) { switch (prminstassert[updatecause[0]]) { case QP_CR: if (icachealiases < 2) return icachealiases; if (updatecause[1] == '\012') { luaL_addstring(startcounter, enablecoherency); return 0; } else afterupdate(updatecause[0], startcounter); break; case QP_IF_LAST: if (icachealiases < 3) return icachealiases; if (updatecause[1] == '\015' && updatecause[2] == '\012') { afterupdate(updatecause[0], startcounter); luaL_addstring(startcounter, enablecoherency); return 0; } else luaL_addchar(startcounter, updatecause[0]); break; case QP_QUOTED: afterupdate(updatecause[0], startcounter); break; default: luaL_addchar(startcounter, updatecause[0]); break; } updatecause[0] = updatecause[1]; updatecause[1] = updatecause[2]; icachealiases--; } return 0; } static size_t gpio6config(UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter) { size_t i; for (i = 0; i < icachealiases; i++) { if (prminstassert[updatecause[i]] == QP_PLAIN) luaL_addchar(startcounter, updatecause[i]); else afterupdate(updatecause[i], startcounter); } if (icachealiases > 0) luaL_addstring(startcounter, EQCRLF); return 0; } static int queryregister(lua_State *L) { size_t asize = 0, isize = 0; UC atom[3]; const UC *updatecause = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *timerenable = updatecause + isize; const char *enablecoherency = luaL_optstring(L, 3, CRLF); luaL_Buffer startcounter; if (!updatecause) { lua_pushnil(L); lua_pushnil(L); return 2; } lua_settop(L, 3); luaL_buffinit(L, &startcounter); while (updatecause < timerenable) asize = enablesmartreflex(*updatecause++, atom, asize, enablecoherency, &startcounter); updatecause = (UC *) luaL_optlstring(L, 2, NULL, &isize); if (!updatecause) { asize = gpio6config(atom, asize, &startcounter); luaL_pushresult(&startcounter); if (!(*lua_tostring(L, -1))) lua_pushnil(L); lua_pushnil(L); return 2; } timerenable = updatecause + isize; while (updatecause < timerenable) asize = enablesmartreflex(*updatecause++, atom, asize, enablecoherency, &startcounter); luaL_pushresult(&startcounter); lua_pushlstring(L, (char *) atom, asize); return 2; } static size_t simtecpowercontrol(UC c, UC *updatecause, size_t icachealiases, luaL_Buffer *startcounter) { int d; updatecause[icachealiases++] = c; switch (updatecause[0]) { case '\075': if (icachealiases < 3) return icachealiases; if (updatecause[1] == '\015' && updatecause[2] == '\012') return 0; c = usb11resources[updatecause[1]]; d = usb11resources[updatecause[2]]; if (c > 15 || d > 15) luaL_addlstring(startcounter, (char *)updatecause, 3); else luaL_addchar(startcounter, (char) ((c << 4) + d)); return 0; case '\015': if (icachealiases < 2) return icachealiases; if (updatecause[1] == '\012') luaL_addlstring(startcounter, (char *)updatecause, 2); return 0; default: if (updatecause[0] == '\011' || (updatecause[0] > 31 && updatecause[0] < 127)) luaL_addchar(startcounter, updatecause[0]); return 0; } } static int cpuinfochain(lua_State *L) { size_t asize = 0, isize = 0; UC atom[3]; const UC *updatecause = (UC *) luaL_optlstring(L, 1, NULL, &isize); const UC *timerenable = updatecause + isize; luaL_Buffer startcounter; if (!updatecause) { lua_pushnil(L); lua_pushnil(L); return 2; } lua_settop(L, 2); luaL_buffinit(L, &startcounter); while (updatecause < timerenable) asize = simtecpowercontrol(*updatecause++, atom, asize, &startcounter); updatecause = (UC *) luaL_optlstring(L, 2, NULL, &isize); if (!updatecause) { luaL_pushresult(&startcounter); if (!(*lua_tostring(L, -1))) lua_pushnil(L); lua_pushnil(L); return 2; } timerenable = updatecause + isize; while (updatecause < timerenable) asize = simtecpowercontrol(*updatecause++, atom, asize, &startcounter); luaL_pushresult(&startcounter); lua_pushlstring(L, (char *) atom, asize); return 2; } static int resourcestart(lua_State *L) { size_t icachealiases = 0; int dm9000platdata = (int) luaL_checknumber(L, 1); const UC *updatecause = (UC *) luaL_optlstring(L, 2, NULL, &icachealiases); const UC *timerenable = updatecause + icachealiases; int traceleave = (int) luaL_optnumber(L, 3, 76); luaL_Buffer startcounter; if (!updatecause) { if (dm9000platdata < traceleave) lua_pushstring(L, EQCRLF); else lua_pushnil(L); lua_pushinteger(L, traceleave); return 2; } luaL_buffinit(L, &startcounter); while (updatecause < timerenable) { switch (*updatecause) { case '\015': break; case '\012': dm9000platdata = traceleave; luaL_addstring(&startcounter, CRLF); break; case '\075': if (dm9000platdata <= 3) { dm9000platdata = traceleave; luaL_addstring(&startcounter, EQCRLF); } luaL_addchar(&startcounter, *updatecause); dm9000platdata--; break; default: if (dm9000platdata <= 10) { if(bIsspace(*updatecause) || dm9000platdata <= 0) { dm9000platdata = traceleave; luaL_addstring(&startcounter, EQCRLF); luaL_addchar(&startcounter, *updatecause); } else luaL_addchar(&startcounter, *updatecause); } else luaL_addchar(&startcounter, *updatecause); dm9000platdata--; break; } updatecause++; } luaL_pushresult(&startcounter); lua_pushinteger(L,dm9000platdata); return 2; } #define eolcandidate(c) (c == '\015' || c == '\012') static int breakpointslots(int c, int timerenable, const char *enablecoherency, luaL_Buffer *startcounter) { if (eolcandidate(c)) { if (eolcandidate(timerenable)) { if (c == timerenable) luaL_addstring(startcounter, enablecoherency); return 0; } else { luaL_addstring(startcounter, enablecoherency); return c; } } else { luaL_addchar(startcounter, (char)c); return 0; } } static int barrierhooks(lua_State *L) { int registermcasp = (int)luaL_checkinteger(L, 1); size_t isize = 0; const char *updatecause = luaL_optlstring(L, 2, NULL, &isize); const char *timerenable = updatecause + isize; const char *enablecoherency = luaL_optstring(L, 3, CRLF); luaL_Buffer startcounter; luaL_buffinit(L, &startcounter); if (!updatecause) { lua_pushnil(L); lua_pushinteger(L, 0); return 2; } while (updatecause < timerenable) registermcasp = breakpointslots(*updatecause++, registermcasp, enablecoherency, &startcounter); luaL_pushresult(&startcounter); lua_pushinteger(L, registermcasp); return 2; } static size_t dot(int c, size_t state, luaL_Buffer *startcounter) { luaL_addchar(startcounter, (char)c); switch (c) { case '\015': return 1; case '\012': return (state == 1)? 2: 0; case '\056': if (state == 2) luaL_addchar(startcounter, '\056'); default: return 0; } } static int emulaterd8rn16rm0ra12(lua_State *L) { size_t isize = 0, state = (size_t) luaL_checknumber(L, 1); const char *updatecause = luaL_optlstring(L, 2, NULL, &isize); const char *timerenable = updatecause + isize; luaL_Buffer startcounter; if (!updatecause) { lua_pushnil(L); lua_pushinteger(L, 2); return 2; } luaL_buffinit(L, &startcounter); while (updatecause < timerenable) state = dot(*updatecause++, state, &startcounter); luaL_pushresult(&startcounter); lua_pushinteger(L, state); return 2; } static void devicenames(lua_State* L) { int top = lua_gettop(L); lua_pushglobaltable(L); luaL_newlib(L,compatLib); lua_setfield(L,-2,"\163\157\143\153\143\157\155\160\141\164"); luaopen_mime_core(L); lua_settop(L, top); } #endif #include "lxrc.h" typedef struct { Thread super; /* Inherits from Thread */ DoubleLink link; ThreadSemaphore sem; LThreadMgr* thMgr; lua_State* Lt; /* Thread state */ int tRef; /* Key for LThread userdata instance in Lua registry */ int lRef; /* Key for the Lua state above in Lua registry */ } LThread; #define LTHREAD "\114\124\110\122\105\101\104" #define LTHREADMGR "\114\124\110\122\105\101\104\115\107\122" typedef struct { LThreadMgr* mgr; } LThreadMgrUD; #define toLThread(L) (LThread*)luaL_checkudata(L,1,LTHREAD) #define toLThreadMgr(L) ((LThreadMgrUD*)luaL_checkudata(L,1,LTHREADMGR))->mgr static void LThread_setErrhAndrunLFunc(ThreadJob* tj, LThreadMgr* mgr); static LThreadMgr* LThreadMgr_get(lua_State* L) { LThreadMgr* tm; lua_rawgetp(L,LUA_REGISTRYINDEX,(void*)LThreadMgr_get); tm = (LThreadMgr*)lua_touserdata(L, -1); lua_pop(L,1); return tm; } static void LThread_runner(Thread* fdc37m81xconfig) { LThread* o = (LThread*)fdc37m81xconfig; LThreadMgr* thMgr = o->thMgr; ThreadMutex* mcspiconfig = HttpServer_getMutex(thMgr->server); for(;;) { ThreadJob* tj; ThreadSemaphore_wait(&o->sem); ThreadMutex_set(mcspiconfig); baAssert( DoubleList_isInList(&thMgr->runningThreadList, &o->link) ); thMgr->runningThreads++; while(0!=(tj=(ThreadJob*)DoubleList_removeFirst(&thMgr->pendingJobList)) ) { if(o->Lt) { tj->Lt = o->Lt; tj->run(tj, thMgr); lua_settop(tj->Lt, 0); } baFree(tj); thMgr->pendingJobs--; } thMgr->runningThreads--; DoubleLink_unlink(&o->link); DoubleList_insertLast(&thMgr->idleThreadList, &o->link); if( !o->Lt ) break; ThreadMutex_release(mcspiconfig); } DoubleLink_unlink(&o->link); luaL_unref(thMgr->Lg, LUA_REGISTRYINDEX, o->lRef); luaL_unref(thMgr->Lg, LUA_REGISTRYINDEX, o->tRef); ThreadMutex_release(mcspiconfig); } static int LThread_gc(lua_State* L) { LThread* o = toLThread(L); LThreadMgr* thMgr = o->thMgr; if(thMgr->isDynamic) { ThreadMutex* mcspiconfig = HttpServer_getMutex(thMgr->server); while(thMgr->runningThreads) { ThreadMutex_release(mcspiconfig); Thread_sleep(30); ThreadMutex_set(mcspiconfig); } LThreadMgr_destructor(thMgr); baFree(thMgr); } ThreadSemaphore_destructor(&o->sem); return 0; } static const luaL_Reg LThread_lib[] = { {"\137\137\147\143", LThread_gc}, {NULL, NULL} }; static LThread* LThread_link2Thread(DoubleLink* l) { return (LThread*)(((U8*)l)-offsetof(LThread,link)); } static LThread* LThreadMgr_removeFirstIdleThread(LThreadMgr* o) { DoubleLink* l = DoubleList_removeFirst(&o->idleThreadList); return l ? LThread_link2Thread(l) : 0; } BA_API int LThreadMgr_run(LThreadMgr* o, ThreadJob* tj) { LThread* lt; baAssert(ThreadMutex_isOwner(HttpServer_getMutex(o->server))); lt = LThreadMgr_removeFirstIdleThread(o); DoubleList_insertLast(&o->pendingJobList,tj); o->pendingJobs++; if(lt) { DoubleList_insertLast(&o->runningThreadList, <->link); ThreadSemaphore_signal(<->sem); return TRUE; } return FALSE; } BA_API ThreadJob* ThreadJob_create(size_t icachealiases, ThreadJob_Run run) { ThreadJob* n = baMalloc(icachealiases); if(n) { DoubleLink_constructor(n); n->run = run; } return n; } BA_API ThreadJob* ThreadJob_lcreate(size_t icachealiases, ThreadJob_LRun lrun) { ThreadJob* tj=(ThreadJob*)ThreadJob_create(icachealiases,LThread_setErrhAndrunLFunc); tj->lrun=lrun; return tj; } #ifndef NO_BA_SERVER typedef struct { ThreadJob super; HttpServer* server; HttpCommand* cmd; HttpDir* dir; } HttpCmdJob; static void LThread_runDoDir(ThreadJob* jn, LThreadMgr* mgr) { (void)mgr; HttpServer_AsynchProcessDir( ((HttpCmdJob*)jn)->server,((HttpCmdJob*)jn)->dir,((HttpCmdJob*)jn)->cmd); } static int LThreadMgr_doDir(HttpCmdThreadPoolIntf* fdc37m81xconfig, HttpCommand* cmd, HttpDir* dir) { LThreadMgr* o = (LThreadMgr*)fdc37m81xconfig; if(LThreadMgr_canRun(o)) { HttpCmdJob* dn = (HttpCmdJob*)ThreadJob_create( sizeof(HttpCmdJob), LThread_runDoDir); if(dn) { cmd->runningInThread = TRUE; dn->server=o->server; dn->dir = dir; dn->cmd = cmd; LThreadMgr_run(o, (ThreadJob*)dn); return 0; } } return -1; } #endif static void LThreadMgr_releaseAllThreads(LThreadMgr* o) { DoubleListEnumerator instructioncounter; LThread* lt; DoubleLink* l; DoubleListEnumerator_constructor(&instructioncounter, &o->runningThreadList); for(l = DoubleListEnumerator_getElement(&instructioncounter) ; l ; l = DoubleListEnumerator_nextElement(&instructioncounter)) { LThread_link2Thread(l)->Lt=0; } while( 0 != (lt = LThreadMgr_removeFirstIdleThread(o)) ) { lt->Lt=0; DoubleList_insertLast(&o->runningThreadList, <->link); ThreadSemaphore_signal(<->sem); } } typedef struct { ThreadJob super; int fref; /* ref to function passed into ba.thread.run() */ } LThreadJob; static void LThread_pcall(struct ThreadJob* tj, int msgh, struct LThreadMgr* mgr) { int cpufreqboard; (void)mgr; cpufreqboard = ((LThreadJob*)tj)->fref; lua_rawgeti(tj->Lt, LUA_REGISTRYINDEX, cpufreqboard); baAssert(2 == lua_gettop(tj->Lt)); lua_pcall(tj->Lt, 0, 0, msgh); luaL_unref(tj->Lt, LUA_REGISTRYINDEX, cpufreqboard); } static void LThread_setErrhAndrunLFunc(ThreadJob* tj, LThreadMgr* mgr) { lua_State* L = tj->Lt; lua_pushcclosure(L,balua_errorhandler,0); tj->lrun(tj,1,mgr); } static int LThreadMgr_PrepLRun(LThreadMgr* o, lua_State* L) { LThreadJob* lj; luaL_checktype(L, lua_gettop(L), LUA_TFUNCTION); lj = (LThreadJob*)ThreadJob_lcreate( sizeof(LThreadJob), LThread_pcall); if( ! lj ) luaL_error(L,baErr2Str(E_MALLOC)); lj->fref=luaL_ref(L, LUA_REGISTRYINDEX); LThreadMgr_run(o, (ThreadJob*)lj); lua_pushinteger(L, o->pendingJobs); return 1; } static int LThreadMgr_PrepLDRun(lua_State* L) { return LThreadMgr_PrepLRun(toLThreadMgr(L), L); } static int LThreadMgr_PrepLSRun(lua_State* L) { return LThreadMgr_PrepLRun(LThreadMgr_get(L), L); } static int LThreadMgr_dbg(LThreadMgr* o, lua_State* L, int boolIx) { DoubleListEnumerator instructioncounter; DoubleLink* l; int ix=0; lua_newtable(L); DoubleListEnumerator_constructor(&instructioncounter, &o->runningThreadList); for(l = DoubleListEnumerator_getElement(&instructioncounter) ; l ; l = DoubleListEnumerator_nextElement(&instructioncounter)) { lua_State* Lt = LThread_link2Thread(l)->Lt; if(lua_gettop(Lt) > 0) { lua_pushthread(Lt); lua_xmove(Lt, L, 1); lua_rawseti(L, -2, ++ix); } } return 1; } static int LThreadMgr_sDbg(lua_State* L) { return LThreadMgr_dbg(LThreadMgr_get(L), L, 1); } static int LThreadMgr_dynDbg(lua_State* L) { return LThreadMgr_dbg(toLThreadMgr(L), L, 2); } static int LThreadMgr_gc(lua_State* L) { LThreadMgr* o = toLThreadMgr(L); LThreadMgr_releaseAllThreads(o); return 0; } static const luaL_Reg LThreadMgr_lib[] = { {"\162\165\156", LThreadMgr_PrepLDRun}, {"\144\142\147", LThreadMgr_dynDbg}, {"\137\137\147\143", LThreadMgr_gc}, {NULL, NULL} }; static void LThreadMgr_createThreads(LThreadMgr* o, lua_State* L, int threads) { for (; threads > 0; threads--) { LThread* lt = (LThread*)lua_newuserdata(L, sizeof(LThread)); Thread_constructor((Thread*)lt,LThread_runner,o->priority,o->stackSize); DoubleLink_constructor(<->link); DoubleList_insertLast(&o->idleThreadList, <->link); ThreadSemaphore_constructor(<->sem); lt->thMgr = o; if (luaL_newmetatable(L, LTHREAD)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L, LThread_lib, 0); } lua_setmetatable(L, -2); lt->tRef = luaL_ref(L, LUA_REGISTRYINDEX); lt->Lt = lua_newthread(L); lt->lRef = luaL_ref(L, LUA_REGISTRYINDEX); Thread_start((Thread*)lt); } } static void _LThreadMgr_constructor(LThreadMgr* o, HttpServer* uarchbuild, ThreadPriority gpio1resources, int stage2unmap, int threads, lua_State* L) { memset(o, 0, sizeof(LThreadMgr)); #ifdef NO_BA_SERVER ((HttpCmdThreadPoolIntf*)o)->doDir=0; #else ((HttpCmdThreadPoolIntf*)o)->doDir=LThreadMgr_doDir; #endif DoubleList_constructor(&o->idleThreadList); DoubleList_constructor(&o->runningThreadList); DoubleList_constructor(&o->pendingJobList); o->server = uarchbuild; o->priority=gpio1resources; o->stackSize=stage2unmap; LThreadMgr_createThreads(o, L, threads); o->threads=threads; } BA_API void LThreadMgr_destructor(LThreadMgr* o) { ThreadMutex* mcspiconfig = HttpServer_getMutex(o->server); LThreadMgr_releaseAllThreads(o); while (!DoubleList_isEmpty(&o->runningThreadList)) { ThreadMutex_release(mcspiconfig); Thread_sleep(30); ThreadMutex_set(mcspiconfig); } } static int LThreadMgr_configure(lua_State* L) { LThreadMgr* o = LThreadMgr_get(L); if( ! lua_isnone(L, 1) ) { int threads = (int)luaL_checknumber(L, 1); if(threads > o->threads && threads < 20) { LThreadMgr_createThreads(o, L, threads - o->threads); o->threads = threads; } } lua_pushinteger(L, o->threads); return 1; } static int LThreadMgr_create(lua_State* L) { LThreadMgr* ltMgr=LThreadMgr_get(L); LThreadMgrUD* mgrUD=(LThreadMgrUD*)lua_newuserdata(L, sizeof(LThreadMgrUD)); LThreadMgr* newLtMgr=baLMalloc(L, sizeof(LThreadMgr)); if( ! newLtMgr ) luaL_error(L,baErr2Str(E_MALLOC)); _LThreadMgr_constructor(newLtMgr, balua_getparam(L)->server, ltMgr->priority,ltMgr->stackSize, 1, L); newLtMgr->Lg=ltMgr->Lg; newLtMgr->isDynamic=TRUE; mgrUD->mgr = newLtMgr; if(luaL_newmetatable(L, LTHREADMGR)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,LThreadMgr_lib,0); } lua_setmetatable(L, -2); return 1; } BA_API void LThreadMgr_constructor(LThreadMgr* o, HttpServer* uarchbuild, ThreadPriority gpio1resources, int stage2unmap, int threads, lua_State* L, int allowCreate) { static const luaL_Reg stdFuncs[] = { {"\162\165\156", LThreadMgr_PrepLSRun}, {"\144\142\147", LThreadMgr_sDbg}, {NULL, NULL} }; static const luaL_Reg extFuncs[] = { {"\143\162\145\141\164\145", LThreadMgr_create}, {"\143\157\156\146\151\147\165\162\145", LThreadMgr_configure}, {NULL, NULL} }; _LThreadMgr_constructor(o,uarchbuild,gpio1resources,stage2unmap,threads,L); o->Lg=L; lua_getglobal(L, "\142\141"); luaL_newlib(L, stdFuncs); if (allowCreate) luaL_setfuncs(L, extFuncs, 0); lua_setfield(L,-2,"\164\150\162\145\141\144"); lua_pop(L,1); lua_pushlightuserdata(L, o); lua_rawsetp(L,LUA_REGISTRYINDEX,(void*)LThreadMgr_get); } #ifndef BA_LIB #define BA_LIB #endif #include #include #include #define TR_set 1 #define TR_data 2 #define TR_acquired 3 #define TS_Http11State 1 #define TS_Request 2 #define TS_RequestHeaders 3 #define TS_setResponseHeaders 4 #define TS_setResponseBody 5 #define TS_TraceButtonState 6 #define TS_TraceLevel 7 typedef struct { SingleLink super; int size; char buf[1]; } TraceBufNode; #define TraceBufNode_constructor(o) SingleLink_constructor((SingleLink*)o) typedef struct { HttpDir super; /* Inherits from EventHandler dir */ Thread thread; WSS wss; WSSCB wssCB; ThreadSemaphore sem; SingleList tbnList; ThreadMutex* dispMutex; int luaFuncRef; int luaRef; int tbnListSize; U8 exitThread; /* 0: running, 1: termination activated: 2: terminated */ BaBool threadRunning; } TraceLogger; static TraceLogger* tl; static LThreadMgr* ltMgr; static HttpTrace_Flush originalFlushCB; typedef struct { ThreadJob super; int luaFuncRef; int conns; U32 sessionId; } TrThreadJob; static void adjustlegacy(ThreadJob* job, int msgh, LThreadMgr* mgr) { TrThreadJob* trjob = (TrThreadJob*)job; lua_State* L = job->Lt; lua_rawgeti(L, LUA_REGISTRYINDEX, trjob->luaFuncRef); if(lua_isfunction(L, -1)) { lua_pushinteger(L, trjob->conns); if(trjob->sessionId) lua_pushinteger(L,trjob->sessionId); lua_pcall(L, trjob->sessionId ? 2 : 1, 0, msgh); } } static void cacheclean(TraceLogger* o, U32 sysvecbyname, int kernelrestart) { if(o->luaFuncRef) { TrThreadJob* job=(TrThreadJob*)ThreadJob_lcreate( sizeof(TrThreadJob), adjustlegacy); if(job) { job->conns=kernelrestart; job->luaFuncRef=o->luaFuncRef; job->sessionId = sysvecbyname; LThreadMgr_run(ltMgr, (ThreadJob*)job); } } } static BaBool sanitiseshareability(lua_State *L, int ix, const char *k, BaBool restartstack) { BaBool r3000write; lua_getfield(L, ix, k); if(lua_isboolean(L, -1)) r3000write = (BaBool)lua_toboolean(L, -1); else { lua_pushboolean(L, restartstack); lua_setfield(L, ix, k); r3000write=restartstack; } return r3000write; } static void TraceLogger_sendSetCmd(void) { U8 buf[7]; buf[0] = TR_set; buf[1] = HttpTrace_isRequestSet(); buf[2] = HttpTrace_isRequestHeadersSet(); buf[3] = HttpTrace_isResponseHeadersSet(); buf[4] = HttpTrace_isHttp11StateSet(); buf[5] = HttpTrace_isResponseBodySet(); buf[6] = (U8)HttpTrace_setPrio(0); HttpTrace_setPrio((int)buf[6] & 0xFF); WSS_write(&tl->wss, buf, 7, FALSE); } static int handletlbdump(HttpDir* fdc37m81xconfig, const char* driverregister, HttpCommand* cmd) { if( !cmd ) { return 0; } if( ! HttpDir_authenticateAndAuthorize(fdc37m81xconfig,cmd,driverregister) ) return 0; if(HttpRequest_getHeaderValue(&cmd->request, "\170\055\162\145\161\165\145\163\164\145\144\055\167\151\164\150")) { HttpResponse_setHeader(&cmd->response, "\164\162\141\143\145\154\157\147\147\145\162", "\061\056\060", FALSE); HttpResponse_sendError1(&cmd->response,WSS_isValid(&tl->wss) ? 503 : 204); } else if(HttpRequest_getHeaderValue(&cmd->request, "\123\145\143\055\127\145\142\123\157\143\153\145\164\055\113\145\171")) { HttpSession* s; if(WSS_isValid(&tl->wss)) { char buf[1]; buf[0] = TR_acquired; WSS_write(&tl->wss, buf, 1, FALSE); WSS_close(&tl->wss, 1000); return 0; } s=HttpRequest_getSession(&cmd->request,FALSE); if( ! WSS_upgrade(&tl->wss, &cmd->request) ) { cacheclean(tl, s ? HttpSession_getId(s) : 0, 1); TraceLogger_sendSetCmd(); } } else { HttpResponse_sendError1(&cmd->response, 405); } return 0; } static void sleepau1300(WSSCB* cb,WSS* wss,void* modempwron,int len,int relocationaddress) { U8* alloccontroller=(U8*)modempwron; BaBool writeoutput = alloccontroller[1] ? TRUE : FALSE; (void)relocationaddress; (void)len; (void)cb; switch(alloccontroller[0]) { case TS_Http11State: HttpTrace_setHttp11State(writeoutput); break; case TS_Request: HttpTrace_setRequest(writeoutput); break; case TS_RequestHeaders: HttpTrace_setRequestHeaders(writeoutput); break; case TS_setResponseHeaders: HttpTrace_setResponseHeaders(writeoutput); break; case TS_setResponseBody: HttpTrace_setResponseBody(writeoutput); break; case TS_TraceLevel: HttpTrace_setPrio((int)((unsigned int)alloccontroller[1])); break; default: WSS_close(wss, 1003); } } static void estimatediv128to64(WSSCB* cb,struct WSS* wss,int sffsdrnandflash) { TraceLogger* o = (TraceLogger*)((U8*)wss-offsetof(TraceLogger,wss)); (void)cb; (void)sffsdrnandflash; cacheclean(o, 0, 0); } static void activationnotifier(Thread* t) { (void)t; for(;;) { TraceBufNode* tbn; ThreadSemaphore_wait(&tl->sem); tl->threadRunning = TRUE; ThreadMutex_set(tl->dispMutex); if(tl->exitThread) break; while((tbn = (TraceBufNode*)SingleList_removeFirst(&tl->tbnList)) != 0) { WSS_write(&tl->wss, tbn->buf, tbn->size, FALSE); tl->tbnListSize -= tbn->size; baFree(tbn); } tl->threadRunning = FALSE; ThreadMutex_release(tl->dispMutex); } tl->threadRunning = FALSE; tl->exitThread = 2; ThreadMutex_release(tl->dispMutex); } static void sigreturnsetup(char* buf, int instructionemulation) { if(WSS_isValid(&tl->wss) && tl->tbnListSize < 30*1024) { TraceBufNode* tbn = baMalloc(sizeof(TraceBufNode)+instructionemulation); if(tbn) { TraceBufNode_constructor(tbn); SingleList_insertLast(&tl->tbnList, tbn); tbn->buf[0] = TR_data; memcpy(tbn->buf+1, buf, instructionemulation); instructionemulation++; tl->tbnListSize += instructionemulation; tbn->size = instructionemulation; if( ! tl->threadRunning ) ThreadSemaphore_signal(&tl->sem); } } originalFlushCB(buf, instructionemulation); } static void hammeriodesc(char* buf, int instructionemulation) { (void)buf; (void)instructionemulation; } static int flash0partitions(lua_State *L) { BaLua_param* p = baluaENV_getparam(L); const char* gpio1config=0; if(tl) { lua_rawgeti(L, LUA_REGISTRYINDEX, tl->luaRef); return 1; } originalFlushCB = HttpTrace_getFLushCallback(); if( ! lua_isnil(L,1) ) gpio1config=luaL_optstring(L,1,"\164\162\141\143\145\154\157\147\147\145\162\056\163\145\162\166\151\143\145"); if(gpio1config) { char* selecttable; tl=(TraceLogger*)baluaENV_createDir( L,BA_TDIR_TRACELOGGER,sizeof(TraceLogger)+strlen(gpio1config)+1); selecttable = (char*)(tl+1); strcpy(selecttable, gpio1config); gpio1config=selecttable; } else { tl=(TraceLogger*)baluaENV_createDir( L,BA_TDIR_TRACELOGGER,sizeof(TraceLogger)); } HttpDir_constructor((HttpDir*)tl, gpio1config, 0); HttpDir_setService((HttpDir*)tl,handletlbdump); WSSCB_constructor(&tl->wssCB, sleepau1300, estimatediv128to64, 0); WSS_constructor( &tl->wss,&tl->wssCB,HttpServer_getDispatcher(p->server),20,0); Thread_constructor(&tl->thread, activationnotifier, ThreadPrioNormal, 4000); ThreadSemaphore_constructor(&tl->sem); SingleList_constructor(&tl->tbnList); tl->dispMutex = p->mutex; tl->tbnListSize = 0; tl->exitThread = 0; tl->threadRunning = FALSE; if(!originalFlushCB) originalFlushCB=hammeriodesc; HttpTrace_setFLushCallback(sigreturnsetup); lua_pushvalue(L, 1); tl->luaRef=luaL_ref(L, LUA_REGISTRYINDEX); tl->luaFuncRef=0; Thread_start(&tl->thread); return 1; } static int max6369device(lua_State *L) { if( tl == (TraceLogger*) (((LHttpDir*)baluaENV_checkudata(L,1,BA_TDIR_TRACELOGGER))+1) ) { int da9030pdata; int reservevmcore; BaBool createidmap; BaBool configuredevice; BaBool netdevevent; BaBool straceleave; BaBool nvmemnotifier; if(lua_gettop(L) > 1) { lua_settop(L,2); luaL_checktype(L,2,LUA_TTABLE); da9030pdata=TRUE; } else { lua_settop(L,1); lua_createtable(L, 0, 6); da9030pdata=FALSE; } createidmap = sanitiseshareability(L,2,"\150\164\164\160\061\061\163\164\141\164\145",HttpTrace_isHttp11StateSet()); configuredevice = sanitiseshareability(L,2,"\162\145\161\165\145\163\164",HttpTrace_isRequestSet()); netdevevent = sanitiseshareability(L,2,"\162\145\161\165\145\163\164\150\145\141\144\145\162\163", HttpTrace_isRequestHeadersSet()); straceleave = sanitiseshareability(L,2,"\162\145\163\160\157\156\163\145\150\145\141\144\145\162\163", HttpTrace_isResponseHeadersSet()); nvmemnotifier = sanitiseshareability(L,2,"\162\145\163\160\157\156\163\145\142\157\144\171", HttpTrace_isResponseBodySet()); lua_getfield(L,2,"\160\162\151\157\162\151\164\171"); if(lua_isnumber(L, -1)) reservevmcore=(int)lua_tointeger(L, -1); else { reservevmcore = HttpTrace_setPrio(0); HttpTrace_setPrio(reservevmcore); lua_pushinteger(L,reservevmcore); lua_setfield(L, 2, "\160\162\151\157\162\151\164\171"); } if(da9030pdata) { HttpTrace_setHttp11State(createidmap); HttpTrace_setRequest(configuredevice); HttpTrace_setRequestHeaders(netdevevent); HttpTrace_setResponseHeaders(straceleave); HttpTrace_setResponseBody(nvmemnotifier); HttpTrace_setPrio(reservevmcore); if(WSS_isValid(&tl->wss)) TraceLogger_sendSetCmd(); } lua_settop(L,2); return 1; } return 0; } static int wm8750gpiod(lua_State *L) { lua_settop(L, 2); luaL_checktype(L, -1, LUA_TFUNCTION); if(!ltMgr) luaL_error(L, "\114\124\150\162\145\141\144\115\147\162\040\156\165\154\154"); if( tl == (TraceLogger*) (((LHttpDir*)baluaENV_checkudata(L,1,BA_TDIR_TRACELOGGER))+1) ) { if(tl->luaFuncRef) luaL_unref(L, LUA_REGISTRYINDEX, tl->luaFuncRef); tl->luaFuncRef=luaL_ref(L, LUA_REGISTRYINDEX); } lua_pushboolean(L, TRUE); return 1; } static int resetvectors(lua_State *L) { if( tl == (TraceLogger*) (((LHttpDir*)baluaENV_checkudata(L,1,BA_TDIR_TRACELOGGER))+1) ) { TraceLogger* xtl=tl; if(tl->luaFuncRef) luaL_unref(L, LUA_REGISTRYINDEX, tl->luaFuncRef); HttpTrace_setFLushCallback(originalFlushCB); cacheclean(tl, 0, 0); if(WSS_isValid(&tl->wss)) WSS_close(&tl->wss, 1001); for(;;) { TraceBufNode* tbn; tbn = (TraceBufNode*)SingleList_removeFirst(&xtl->tbnList); if(!tbn) break; baFree(tbn); } HttpDir_destructor((HttpDir*)xtl); WSS_destructor(&tl->wss); xtl->exitThread = 1; ThreadSemaphore_signal(&xtl->sem); while(xtl->exitThread != 2) { ThreadMutex_release(xtl->dispMutex); Thread_sleep(50); ThreadMutex_set(xtl->dispMutex); } ThreadSemaphore_destructor(&xtl->sem); Thread_destructor(&xtl->thread); luaL_unref(L, LUA_REGISTRYINDEX, xtl->luaRef); tl=0; } return 0; } static int fpsimdcontext(lua_State *L) { static const luaL_Reg lib[] = { {"\143\157\156\146\151\147\165\162\145", max6369device}, {"\157\156\143\154\151\145\156\164", wm8750gpiod}, {"\143\154\157\163\145", resetvectors}, {"\137\137\147\143", resetvectors}, {NULL, NULL} }; baluaENV_register(L,BA_TDIR_TRACELOGGER,BA_TDIR,lib); return 0; } void balua_tracelogger(lua_State *L, LThreadMgr* mgr) { static const luaL_Reg lib[] = { {"\164\162\141\143\145\154\157\147\147\145\162", flash0partitions}, {NULL, NULL} }; int sffsdrnandflash; int top=lua_gettop(L); balua_pushbatab(L); lua_pushcclosure(L, fpsimdcontext, 1); sffsdrnandflash=lua_pcall(L,0,0,0); if(sffsdrnandflash) baFatalE(FE_BLUA_PANIC, sffsdrnandflash); lua_getglobal(L, "\142\141"); lua_getfield(L, -1, "\143\162\145\141\164\145"); baAssert(lua_type(L,-1) == LUA_TTABLE); balua_pushbatab(L); luaL_setfuncs(L,lib,1); lua_settop(L,top); ltMgr=mgr; } #ifndef BA_LIB #define BA_LIB 1 #endif #include "WebSocketServer.h" static int simulateldrstr(WSS* o, int flushoffset) { SoDispCon_closeCon((SoDispCon*)o); o->cb->closeFp(o->cb, o, flushoffset); return 1; } static int ictlrmatch(WSS* o, int flushoffset, int sectionsearly) { U8* buf; DynBuffer_expand(&o->db, o->db.expandSize); buf = (U8*)DynBuffer_getBuf(&o->db); if(!buf) return -1; buf[0] = 0x88; if(flushoffset) { buf[1] = 2; buf[2] = (U8)((unsigned)flushoffset >> 8); buf[3]= (U8)flushoffset; } else buf[1] = 0; SoDispCon_sendDataNT((SoDispCon*)o, buf, flushoffset ? 4 : 2); if(sectionsearly) return simulateldrstr(o, flushoffset); return -1; } static int ahashqueued(WSS* o) { U32 pl; BufPrint* bp = (BufPrint*)&o->db; L_more: if( ! o->endOfPacketIx ) { if(bp->cursor < 6) return 0; if( !(0x80 & bp->buf[0]) ) { return ictlrmatch(o, 1002, TRUE); } pl = bp->buf[1]; if( !(0x80 & pl) ) { return ictlrmatch(o, 1002, TRUE); } pl &= 0x7F; if( pl >= 126 ) { if(bp->cursor < 8) return 0; if( pl > 126 ) { return ictlrmatch(o, 1003, TRUE); } pl = (U8)bp->buf[2]; pl <<= 8; pl |= (U8)bp->buf[3]; o->endOfPacketIx = 8 + (int)pl; } else o->endOfPacketIx = 6 + (int)pl; } if(bp->cursor >= o->endOfPacketIx) { U32 i; U8 ntosd2devices; U8* prussresources; U8* sdramstandby; int idmapstart, sffsdrnandflash; o->endOfPacketIx=0; pl = bp->buf[1] & 0x7F; if( pl == 126 ) { pl = (U8)bp->buf[2]; pl <<= 8; pl |= (U8)bp->buf[3]; prussresources = (U8*)bp->buf+4; idmapstart=8; } else { prussresources = (U8*)bp->buf+2; idmapstart=6; } sdramstandby = prussresources+4; for(i=0 ; i < pl ; i++,sdramstandby++) { *sdramstandby ^= prussresources[i&3]; } i=FALSE; switch(bp->buf[0] & 0x0F) { case 0x1: i=TRUE; case 0x2: ntosd2devices=*sdramstandby; *sdramstandby=0; o->cb->frameFp(o->cb, o, bp->buf+idmapstart, pl, i); *sdramstandby=ntosd2devices; break; case 0x8: if(pl >= 2 && pl < 126) { pl = (U8)bp->buf[idmapstart]; pl <<= 8; pl |= (U8)bp->buf[idmapstart+1]; } else pl=0; return simulateldrstr(o, (int)pl); case 0x9: if(pl > 125) return ictlrmatch(o, 1009, TRUE); bp->buf[0] = (U8)0x8A; bp->buf[1]= 0x7F & (U8)pl; if( (sffsdrnandflash=SoDispCon_sendDataNT((SoDispCon*)o,bp->buf,pl+2)) < 0) return simulateldrstr(o, sffsdrnandflash); if(o->cb->pingFp) o->cb->pingFp(o->cb, o, pl ? bp->buf+idmapstart : 0, pl); break; case 0xA: break; default: return ictlrmatch(o, 1002, TRUE); } i = (int)(((U8*)bp->buf+bp->cursor)-sdramstandby); if(i > 0) { memmove(bp->buf, sdramstandby, i); bp->cursor=i; goto L_more; } else { DynBuffer_release((DynBuffer*)bp); } } return 0; } static void multientry(SoDispCon* fdc37m81xconfig) { int len; WSS* o = (WSS*)fdc37m81xconfig; BufPrint* bp = (BufPrint*)&o->db; do { if( (len=DynBuffer_expand(&o->db, o->db.expandSize)) != 0) { simulateldrstr(o, E_MALLOC); return; } len = SoDispCon_readData((SoDispCon*)o, bp->buf+bp->cursor, bp->bufSize-bp->cursor, FALSE); if(len) { if(len < 0) { simulateldrstr(o, len); return; } bp->cursor += len; len = ahashqueued(o); } } while(len == 0 && SoDispCon_hasMoreData((SoDispCon*)o)); if(len && len != 1) SoDispCon_closeCon((SoDispCon*)o); } BA_API int WSS_connect(WSS* o, HttpConnection* con) { if( ! SoDispCon_isValid((SoDispCon*)con) ) return -1; if(SoDispCon_isValid((SoDispCon*)o)) SoDispCon_closeCon((SoDispCon*)o); SoDispCon_moveCon((SoDispCon*)con, (SoDispCon*)o); SoDisp_addConnection(((SoDispCon*)o)->dispatcher, (SoDispCon*)o); SoDisp_activateRec(((SoDispCon*)o)->dispatcher, (SoDispCon*)o); BufPrint_erase((BufPrint*)&o->db); o->endOfPacketIx=0; return 0; } BA_API int WSS_upgrade(WSS* o, HttpRequest* req) { if(HttpRequest_wsUpgrade(req)) { HttpResponse_sendError2( HttpRequest_getResponse(req), 400, "\116\157\164\040\141\040\127\145\142\123\157\143\153\145\164\040\122\145\161\165\145\163\164"); return -1; } return WSS_connect(o, HttpRequest_getConnection(req)); } BA_API int WSS_rawWrite(WSS* o, const void* alloccontroller, int len, int buddyavail) { U8 buf[4]; int sffsdrnandflash; buf[0] = 0x80 | (U8)buddyavail; if(len >= 126) { buf[1] = 126; buf[2] = (U16)len >> 8; buf[3] = (U8)len; } else buf[1] = (U8)len; sffsdrnandflash = SoDispCon_sendDataNT((SoDispCon*)o, buf, len >= 126 ? 4 : 2); if(sffsdrnandflash >= 0) sffsdrnandflash = SoDispCon_sendDataNT((SoDispCon*)o, alloccontroller, len); return sffsdrnandflash < 0 ? sffsdrnandflash : 0; } BA_API int WSS_close(WSS* o, int suspendstate) { if( ! SoDispCon_isValid((SoDispCon*)o) ) return -1; ictlrmatch(o, suspendstate <= 0 ? 1000 : suspendstate, FALSE); SoDispCon_closeCon((SoDispCon*)o); return 0; } BA_API void WSS_constructor( WSS* o, WSSCB* cb, SoDisp* sha256start, int allocpages, int heartclocksource) { memset(o, 0, sizeof(WSS)); if(heartclocksource < allocpages) heartclocksource = allocpages; SoDispCon_constructor((SoDispCon*)o, sha256start, multientry); DynBuffer_constructor(&o->db, allocpages, heartclocksource, 0, 0); o->cb=cb; } BA_API void WSS_destructor(WSS* o) { SoDispCon_destructor((SoDispCon*)o); DynBuffer_destructor(&o->db); } #if USE_DBGMON == 1 #include #include #include #include #include #include #include #include #if LUA_VERSION_NUM < 504 #error This guestconfig2 is set for Lua 5.4 #endif #if ! defined(LUA_CORE) #include #include #include #include #endif #ifndef BAPUSHSSTRERR #define BAPUSHSSTRERR static int reportpanic(lua_State* L, const char* err) { lua_pushnil(L); lua_pushstring(L, err); return 2; } #endif typedef enum { DBG_EV_CONSOLE, DBG_EV_STDOUT, DBG_EV_STDERR } DBG_EV; #define VREF_NOT_VARTAB 0x10000000 #define VREF_PARAMETER 0x11000000 #define VREF_VARARG 0x13000000 #define VREF_CLOSURE 0x12000000 #define VREF_GLOBAL 0x14000000 typedef struct{ SoDispCon super; SoDisp* dispatcher; BaLua_param* bap; /* @ init : balua_getparam(L) */ /* Optional callback to starup code activated if debugger sends Restart or Terminate request */ void (*exitCb)(void*,BaBool); void* exitCbData; /* Manage JSON message send/rec. errors */ JErr jErr; /* Used when sending JSON data to the debugger. */ DynBuffer jEncBuf; /* buffer for jEnc */ JEncoder jEnc; /* Buffer that may be used for temporary storage. */ char buf[1024]; /* Global state used by debugger */ lua_State* L; /* Reference to function "table.sort" */ int sortRef; /* Reference to a table with all existing IO objects. table[io]=basePath */ int ioRef; /* Reference to a weak table with: absPathCacheRef[source] = 'struct AbsPathCach instance' (user data obj) The cache is used by LDbgMon_abspath() and speeds up finding the file, especially when using the NetIo. The table is created as a weak table in LDbgMon_lconnect(), thus the elements may GC; the table size is automatically controlled by Lua. */ int absPathCacheRef; /* Reference to a table with all existing threads/coroutines. table[L]=true, where L is the C pointer L value. */ int threadRef; /* Reference to table for storing "sourceMaps". The data is received from the debugger in the "attach" DAP message. The key is the server's name and the value is the debugger's name. */ int sourceMapRef; /* Reference to table for storing resolved source (file name) mapping between the debugger and the server. The key is the server's name and the value is the debugger's name. */ int resolvedSourceMapRef; /* Source code breakpoints table. Reference to table where key is line number and value is a table where key is the filename and value is the breakpoint ID. */ int bpLinesRef; /* variablesReference table. Reference to the table storing DAP 'variablesReference' where the key is a number and the value is a table (Ref-Var). The key starts at 1 and increments to 100 when it is set back to one thus creating a circular buffer. */ int varTabRef; int varTabIx; /* index into above */ /* sourceReference table. Reference to the table storing DAP 'sourceReference' where the key is a number and the value is the filename (string). The key, which can be no larger than 2^31 - 1 according to the DAP protocol, is created from the file name. See (Ref-file). */ int sourceTabRef; /* Function name breakpoints table. Reference to the function breakpoint table. Key is the function (string) and value is the DAP 'Breakpoint' -> 'id' (number). See LDbgMon_setFunctionBreakpoints() */ int funcBpTabRef; /* Keeps incrementing for each BP set. */ S32 breakpointID; /* This sequence number increments for each message sent. */ S32 sendSeq; /* Set when we receive the DAP command 'attach' */ char* workspaceFolder; /* The following variables are temporarily stored in this structure for each received DAP message. */ JVal* arguments; const char* command; S32 recSeq; const char* type; int status; /* zero: ok, -1: failed */ /* The state being debugged. This variable is NULL when system is running and set if the debug monitor is blocked in LDbgMon_step. */ lua_State* Ldbg; lua_State* Lcurrent; /* Set to a value > 0 if the code is currently stepped through. No stepping if stepStackIx=0. */ int stepStackIx; BaBool initialized; BaBool hasBPs; BaBool restartOnModifiedSource; /* Busy with DAP and can't handle Lua hook. */ BaBool dapBusy; BaBool isDispRecEvent; /* Ref-spurious */ BaBool shutdownInProgress; } LDbgMon; static const char eClose[]={"\125\156\145\170\160\145\143\164\145\144\040\144\145\142\165\147\147\145\162\040\144\151\163\143\157\156\156\145\143\164\041"}; static const char eInvalidDAP[]={"\122\145\143\056\040\151\156\166\141\154\151\144\040\104\101\120\040\155\163\147"}; static const char eNotFound[]={"\116\157\164\040\146\157\165\156\144"}; static int supportsdirect(LDbgMon* o, int writeoutput); static void fixupmemoffset(LDbgMon* o); static void skcipherencrypt(LDbgMon* o, BaBool ds1286devinit); static int pmuv3format(lua_State* L) { register struct CallInfo* ci; int coremaskset64 = 0; for(ci = L->ci; ci != &L->base_ci; ci = ci->previous) coremaskset64++; return coremaskset64; } static void removeaddress(lua_State* L, Proto *p) { int i; int buttonshuawei = 0; int enabledisable = p->linedefined; for (i = 0; i < p->sizelineinfo; i++) { int formatexception=p->lineinfo[i]; if(ABSLINEINFO == formatexception) { if(buttonshuawei < p->sizeabslineinfo) enabledisable = p->abslineinfo[buttonshuawei++].line; else { baAssert(0); return; } } else enabledisable += formatexception; lua_pushinteger(L, enabledisable); lua_pushboolean(L, TRUE); lua_settable(L, -3); } for(i = 0; i < p->sizep; i++) removeaddress(L, p->p[i]); } static void cpuinfostatic(LDbgMon* o, Proto *p) { int ix=1; lua_State* L=o->L; lua_newtable(L); lua_rawgeti(L, LUA_REGISTRYINDEX, o->sortRef); lua_pushvalue(L, -2); lua_newtable(L); removeaddress(L, p); lua_pushnil(L); while(lua_next(L, -2) != 0) { lua_pushvalue(L, -2); lua_rawseti(L, -5, ix++); lua_pop(L, 1); } lua_pop(L, 1); lua_call(L, 1, 0); } static int LDbgMon_close(LDbgMon* o, const char* efmt, ...) { JErr_reset(&o->jErr); SoDispCon_closeCon((SoDispCon*)o); supportsdirect(o, FALSE); if(o->sourceMapRef) luaL_unref(o->L, LUA_REGISTRYINDEX, o->sourceMapRef); luaL_unref(o->L, LUA_REGISTRYINDEX, o->resolvedSourceMapRef); luaL_unref(o->L, LUA_REGISTRYINDEX, o->bpLinesRef); luaL_unref(o->L, LUA_REGISTRYINDEX, o->varTabRef); luaL_unref(o->L, LUA_REGISTRYINDEX, o->sourceTabRef); luaL_unref(o->L, LUA_REGISTRYINDEX, o->funcBpTabRef); luaL_unref(o->L, LUA_REGISTRYINDEX, o->absPathCacheRef); o->sourceMapRef= o->resolvedSourceMapRef= o->bpLinesRef= o->varTabRef= o->sourceTabRef= o->funcBpTabRef= o->absPathCacheRef= 0; o->sendSeq=0; o->status=0; o->breakpointID=0; o->stepStackIx=0; o->initialized=o->hasBPs=o->restartOnModifiedSource= o->isDispRecEvent=o->dapBusy=FALSE; o->Lcurrent=o->Ldbg=0; if(o->workspaceFolder) { baFree(o->workspaceFolder); o->workspaceFolder=0; } DynBuffer_destructor(&o->jEncBuf); if(efmt) { va_list demuxregids; HttpTrace_printf(5, "\154\144\142\147\155\157\156\072\040"); va_start(demuxregids, efmt); HttpTrace_vprintf(5, efmt, demuxregids); va_end(demuxregids); HttpTrace_printf(5, "\012"); o->status = -1; } return -1; } static S32 printuncorrectable(LDbgMon* o, lua_State* L, int ix) { S32 queuepriority; ix=lua_absindex(L, ix); lua_rawgeti(L, LUA_REGISTRYINDEX, o->varTabRef); lua_pushvalue(L, ix); lua_rawseti(L, -2, o->varTabIx); lua_pop(L, 1); queuepriority = (S32)o->varTabIx; if(++o->varTabIx > 100) o->varTabIx=1; return queuepriority; } static int cacheerror(LDbgMon* o, const char* pgtablevisitor) { return LDbgMon_close(o, "\105\162\162\072\040\047\045\163\047\040\055\040\045\163\040", pgtablevisitor, eInvalidDAP); } typedef struct { IoIntf* io; char path[1]; /* abspath */ } AbsPathCache; static void staterecord( LDbgMon* o,const char* panicblock,IoIntf* io,const char* edma1resources) { AbsPathCache* apc; lua_rawgeti(o->L, LUA_REGISTRYINDEX, o->absPathCacheRef); lua_pushstring(o->L, panicblock); apc=lua_newuserdata( o->L, sizeof(AbsPathCache)+(edma1resources ? strlen(edma1resources) : 0)); lua_rawset(o->L, -3); apc->io=io; if(edma1resources) strcpy(apc->path,edma1resources); else apc->path[0]=0; } static char* LDbgMon_abspath(LDbgMon* o, const char* panicblock, IoIntf** retIo) { IoStat st; IoIntf* io; AbsPathCache* apc; const char* withinoptimized; char* edma1resources=0; lua_State* L=o->L; int top=lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, o->absPathCacheRef); lua_pushstring(o->L, panicblock); lua_rawget(L, -2); apc = (AbsPathCache*)lua_touserdata(L, -1); if(apc) { *retIo = apc->io; if(apc->path[0]) edma1resources = baStrdup(apc->path); lua_settop(L, top); return edma1resources; } lua_settop(L, top); lua_rawgeti(L, LUA_REGISTRYINDEX, o->ioRef); lua_pushnil(L); while(lua_next(L, -2) != 0) { io = ((baio_t*)lua_touserdata(L,-2))->i; withinoptimized=lua_tostring(L, -1); if(io && *withinoptimized) { if( ! io->statFp(io, panicblock, &st) && ! st.isDir ) { lua_rawgeti(L, LUA_REGISTRYINDEX, o->resolvedSourceMapRef); lua_pushvalue(L, -2); lua_rawget(L, -2); withinoptimized = lua_tostring(L, -1); if(withinoptimized) { edma1resources=baLMalloc(L, strlen(withinoptimized)+strlen(panicblock)+2); if(edma1resources) { int len=strlen(withinoptimized); memcpy(edma1resources,withinoptimized,len); if(edma1resources[len-1] != '\057' && edma1resources[len-1] != '\134') { edma1resources[len++]='\057'; } strcpy(edma1resources+len,panicblock); } } staterecord(o,panicblock,io,edma1resources); *retIo=io; lua_settop(L, top); return edma1resources; } } lua_pop(L, 1); } lua_pushnil(L); while(lua_next(L, -2) != 0) { io = ((baio_t*)lua_touserdata(L,-2))->i; withinoptimized=lua_tostring(L, -1); if( ! *withinoptimized ) { if( ! io->statFp(io, panicblock, &st) && ! st.isDir ) { *retIo=io; staterecord(o,panicblock,io,0); lua_settop(L, top); return 0; } } lua_pop(L, 1); } lua_settop(L, top); return 0; } static LDbgMon* LDbgMon_get(lua_State* L) { lua_pushlightuserdata(L, (void*)LDbgMon_get); lua_rawget(L, LUA_REGISTRYINDEX); return (LDbgMon*)lua_touserdata(L, -1); } static void codecdevice(LDbgMon* o) { int len=DynBuffer_getBufSize(&o->jEncBuf); if(len > 0 && ! o->status) { char buf[35]; if(basnprintf(buf,len,"\103\157\156\164\145\156\164\055\114\145\156\147\164\150\072\040\045\144\015\012\015\012",len) < 0) return; if(SoDispCon_sendDataX((SoDispCon*)o, buf, strlen(buf)) || SoDispCon_sendDataX((SoDispCon*)o, DynBuffer_getBuf(&o->jEncBuf), len)) { LDbgMon_close(o,"\045\163\040\045\144",eClose,__LINE__); } else { JEncoder_commit(&o->jEnc); } } } static void cleanrange(LDbgMon* o, const char* biglittleprepare) { JEncoder_beginObject(&o->jEnc); JEncoder_set(&o->jEnc, "\163\163\144\144\142", "\164\171\160\145","\162\145\163\160\157\156\163\145", "\143\157\155\155\141\156\144",biglittleprepare, "\162\145\161\165\145\163\164\137\163\145\161",o->recSeq, "\163\145\161",o->sendSeq++, "\163\165\143\143\145\163\163", TRUE); } static void LDbgMon_sendResponse(LDbgMon* o, const char* biglittleprepare, const char* fmt, ...) { va_list demuxregids; cleanrange(o, biglittleprepare); if(fmt) { va_start(demuxregids, fmt); JEncoder_vSetJV(&o->jEnc, &fmt, &demuxregids); va_end(demuxregids); } JEncoder_endObject(&o->jEnc); } static void pcsxxcontrol1(LDbgMon* o, const char* biglittleprepare, const char* ethernatenable) { JEncoder_set(&o->jEnc, "\173\163\163\144\144\142\173\173\144\163\142\175\175\175", "\164\171\160\145","\162\145\163\160\157\156\163\145", "\143\157\155\155\141\156\144",biglittleprepare, "\162\145\161\165\145\163\164\137\163\145\161",o->recSeq, "\163\145\161",o->sendSeq, "\163\165\143\143\145\163\163", FALSE, "\142\157\144\171", "\145\162\162\157\162", "\151\144",o->sendSeq, "\146\157\162\155\141\164",ethernatenable, "\163\150\157\167\125\163\145\162",TRUE); o->sendSeq++; } static void switcherwrite(LDbgMon* o, const char* pcictldriver) { JEncoder_beginObject(&o->jEnc); JEncoder_set(&o->jEnc, "\163\163\144", "\164\171\160\145","\145\166\145\156\164", "\145\166\145\156\164",pcictldriver, "\163\145\161",o->sendSeq++); } static void systemindex(LDbgMon* o, DBG_EV ev,const char* enablehazard) { const char* guestconfig3; switch(ev) { case DBG_EV_STDOUT: guestconfig3="\163\164\144\157\165\164"; break; case DBG_EV_STDERR: guestconfig3="\163\164\144\145\162\162"; break; default: guestconfig3="\143\157\156\163\157\154\145"; } switcherwrite(o, "\157\165\164\160\165\164"); JEncoder_set(&o->jEnc, "\173\163\163\175", "\142\157\144\171", "\143\141\164\145\147\157\162\171",guestconfig3, "\157\165\164\160\165\164", enablehazard); JEncoder_endObject(&o->jEnc); codecdevice(o); } static void devcfgclear(LDbgMon* o, const char* msg) { if(msg) systemindex(o, DBG_EV_STDERR, msg); switcherwrite(o, "\164\145\162\155\151\156\141\164\145\144"); JEncoder_set(&o->jEnc, "\173\142\175", "\142\157\144\171", "\162\145\163\164\141\162\164",TRUE); JEncoder_endObject(&o->jEnc); codecdevice(o); } static void dcachenomsr(LDbgMon* o, int cs89x0resources) { DynBuffer db; int dummyhwclk,top; const char* driverstate; lua_State* L=o->L; int clockgettime=FALSE; BufPrint* out = (BufPrint*)&db; if(cs89x0resources) DynBuffer_constructor(&db,2048,1024,AllocatorIntf_getDefault(),0); top=lua_gettop(L); luaL_unref(o->L, LUA_REGISTRYINDEX, o->resolvedSourceMapRef); lua_newtable(L); lua_pushvalue(L, -1); o->resolvedSourceMapRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_rawgeti(L, LUA_REGISTRYINDEX, o->ioRef); if(o->workspaceFolder) { dummyhwclk=strlen(o->workspaceFolder); lua_pushnil(L); while(lua_next(L, -2) != 0) { driverstate = lua_tostring(L, -1); if( ! baStrnCaseCmp(o->workspaceFolder, driverstate, dummyhwclk) ) { lua_pushvalue(L, -1); lua_rawset(L, top+1); break; } lua_pop(L,1); } } lua_settop(L,top+2); if(o->sourceMapRef) { lua_rawgeti(L, LUA_REGISTRYINDEX, o->sourceMapRef); lua_pushnil(L); while(lua_next(L, -2) != 0) { int setupiocoherency=FALSE; driverstate = lua_tostring(L, -2); dummyhwclk=strlen(driverstate); lua_pushvalue(L, top+2); lua_pushnil(L); while(lua_next(L, -2) != 0) { const char* hwmodassert = lua_tostring(L, -1); if( ! baStrnCaseCmp(hwmodassert, driverstate, dummyhwclk) && (strlen(hwmodassert) - dummyhwclk) <= 1) { lua_pushvalue(L, -4); lua_rawset(L, top+1); setupiocoherency=TRUE; lua_pop(L,1); break; } lua_pop(L,1); } if( ! setupiocoherency ) { if(cs89x0resources) BufPrint_printf(out,"\116\157\040\163\157\165\162\143\145\040\155\141\160\160\151\156\147\040\146\157\162\072\040\047\045\163\047\012",driverstate); clockgettime=TRUE; } lua_pop(L,2); } } if(clockgettime && cs89x0resources) { BufPrint_printf(out,"\103\165\162\162\145\156\164\154\171\040\153\156\157\167\156\040\142\141\163\145\040\160\141\164\150\163\072\012"); lua_settop(L,top+2); lua_pushnil(L); while(lua_next(L, -2) != 0) { driverstate = lua_tostring(L, -1); if(driverstate[0]) BufPrint_printf(out,"\011\045\163\012",driverstate); lua_pop(L,1); } systemindex(o, DBG_EV_CONSOLE,DynBuffer_getBuf(&db)); DynBuffer_destructor(&db); } lua_settop(L,top); } static void imagestart(LDbgMon* o) { switcherwrite(o, "\143\141\160\141\142\151\154\151\164\151\145\163"); JEncoder_set(&o->jEnc, "\173\173\133\135\142\142\142\142\142\142\142\142\142\142\142\142\142\142\142\175\175", "\142\157\144\171", "\143\141\160\141\142\151\154\151\164\151\145\163", "\145\170\143\145\160\164\151\157\156\102\162\145\141\153\160\157\151\156\164\106\151\154\164\145\162\163", "\163\165\160\160\157\162\164\163\105\166\141\154\165\141\164\145\106\157\162\110\157\166\145\162\163", TRUE, "\163\165\160\160\157\162\164\163\103\154\151\160\142\157\141\162\144\103\157\156\164\145\170\164", TRUE, "\163\165\160\160\157\162\164\163\124\145\162\155\151\156\141\164\145\122\145\161\165\145\163\164", TRUE, "\163\165\160\160\157\162\164\163\123\145\164\126\141\162\151\141\142\154\145", TRUE, "\163\165\160\160\157\162\164\163\123\145\164\105\170\160\162\145\163\163\151\157\156",FALSE, "\163\165\160\160\157\162\164\163\103\157\156\146\151\147\165\162\141\164\151\157\156\104\157\156\145\122\145\161\165\145\163\164", TRUE, "\163\165\160\160\157\162\164\163\114\157\147\120\157\151\156\164\163", TRUE, "\163\165\160\160\157\162\164\163\106\165\156\143\164\151\157\156\102\162\145\141\153\160\157\151\156\164\163", TRUE, "\163\165\160\160\157\162\164\163\105\170\143\145\160\164\151\157\156\111\156\146\157\122\145\161\165\145\163\164", TRUE, "\163\165\160\160\157\162\164\163\122\145\163\164\141\162\164\122\145\161\165\145\163\164", TRUE, "\163\165\160\160\157\162\164\163\114\157\141\144\145\144\123\157\165\162\143\145\163\122\145\161\165\145\163\164", FALSE, "\163\165\160\160\157\162\164\163\122\145\163\164\141\162\164\106\162\141\155\145", FALSE, "\163\165\160\160\157\162\164\163\103\157\156\144\151\164\151\157\156\141\154\102\162\145\141\153\160\157\151\156\164\163", FALSE, "\163\165\160\160\157\162\164\163\104\145\154\141\171\145\144\123\164\141\143\153\124\162\141\143\145\114\157\141\144\151\156\147", FALSE, "\163\165\160\160\157\162\164\163\110\151\164\103\157\156\144\151\164\151\157\156\141\154\102\162\145\141\153\160\157\151\156\164\163", FALSE); JEncoder_endObject(&o->jEnc); codecdevice(o); } static int buttonsregister(LDbgMon* o, const char* setupdelays, lua_State* deviceoperations) { baAssert( ! o->Ldbg ); o->Lcurrent=o->Ldbg=deviceoperations; switcherwrite(o, "\163\164\157\160\160\145\144"); JEncoder_set(&o->jEnc, "\173\163\144\175", "\142\157\144\171", "\162\145\141\163\157\156",setupdelays, "\164\150\162\145\141\144\111\144", 1); JEncoder_endObject(&o->jEnc); SoDisp_deactivateRec(o->dispatcher,(SoDispCon*)o); codecdevice(o); while(o->Ldbg) { fixupmemoffset(o); } if(SoDispCon_isValid((SoDispCon*)o)) { SoDisp_activateRec(o->dispatcher,(SoDispCon*)o); return 0; } else if(100000 == o->status) { o->status=0; luaL_error(deviceoperations, "\104\145\142\165\147\147\145\162\040\162\145\161\165\145\163\164\145\144\040\162\145\163\164\141\162\164"); } return -1; } static void resetcontroller(lua_State* L, lua_Debug *ar) { int x; LDbgMon* o; lua_getinfo(L, ar->event == LUA_HOOKLINE ? "\123" : "\123\154\156", ar); if(ar->what[0] == '\103' || ar->source[0] != '\100') return; o = LDbgMon_get(L); if( ! o->bpLinesRef || o->dapBusy) { return; } #if 0 printf("\045\160\040\045\144\040\072\040\045\144\040\045\163\012",L, pmuv3format(L), ar->currentline, ar->source); #endif switch(ar->event) { case LUA_HOOKCALL: if(ar->name) { lua_rawgeti(L, LUA_REGISTRYINDEX, o->funcBpTabRef); lua_getfield(L, -1, ar->name); if( ! lua_isnil(L, -1) ) { lua_pop(L, 2); buttonsregister(o, "\146\165\156\143\164\151\157\156\040\142\162\145\141\153\160\157\151\156\164", L); } } break; case LUA_HOOKLINE: if(o->stepStackIx) { if(o->Lcurrent == L || ! o->Lcurrent || 100001 == o->stepStackIx) { x=pmuv3format(L); if(x <= o->stepStackIx) { o->stepStackIx=x; buttonsregister(o, "\163\164\145\160", L); return; } } } lua_rawgeti(L, LUA_REGISTRYINDEX, o->bpLinesRef); lua_pushinteger(L, ar->currentline); lua_rawget(L, -2); if( ! lua_isnil(L, -1) ) { lua_getfield(L, -1, ar->source+1); if( ! lua_isnil(L, -1) ) { lua_pop(L, 3); buttonsregister(o, "\142\162\145\141\153\160\157\151\156\164", L); } } break; } } static int supportsdirect(LDbgMon* o, int writeoutput) { lua_State* L = o->L; if(writeoutput && resetcontroller!=lua_gethook(L) && SoDispCon_isValid((SoDispCon*)o)) { lua_sethook(L, resetcontroller, LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE, 0); lua_rawgeti(L, LUA_REGISTRYINDEX, o->threadRef); lua_pushnil(L); while(lua_next(L, -2) != 0) { lua_sethook((lua_State*)lua_touserdata(L, -2), resetcontroller, LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE, 0); lua_pop(L,1); } lua_pop(L,1); return TRUE; } if(resetcontroller==lua_gethook(L)) { lua_sethook(L, 0, 0, 0); lua_rawgeti(L, LUA_REGISTRYINDEX, o->threadRef); lua_pushnil(L); while(lua_next(L, -2) != 0) { lua_sethook((lua_State*)lua_touserdata(L, -2), 0, 0, 0); lua_pop(L,1); } lua_pop(L,1); } return FALSE; } static void disableoutputs(LDbgMon* o) { imagestart(o); } static void cpuidleconfig(LDbgMon* o) { if(o->arguments) { char* wsf=0; JVal* jv=0; BaBool exceptionsnotify; JVal_get(o->arguments, &o->jErr, "\173\142\175","\163\164\157\160\117\156\105\156\164\162\171", &exceptionsnotify); if(exceptionsnotify) o->stepStackIx = 100001; JVal_get(o->arguments, &o->jErr, "\173\163\175", "\167\157\162\153\163\160\141\143\145\106\157\154\144\145\162",&wsf); if(wsf) { o->workspaceFolder=baStrdup(wsf); } JErr_reset(&o->jErr); wsf=0; JVal_get(o->arguments, &o->jErr, "\173\133\112\135\175","\163\157\165\162\143\145\115\141\160\163",&jv); if(JErr_noError(&o->jErr)) { baAssert(o->sourceMapRef==0); lua_newtable(o->L); lua_pushvalue(o->L, 1); o->sourceMapRef = luaL_ref(o->L, LUA_REGISTRYINDEX); for( ; jv && JErr_noError(&o->jErr) ; jv = JVal_getNextElem(jv)) { const char* systabcheck; const char* hwmodassert; JVal_get(jv, &o->jErr, "\133\163\163\135", &systabcheck, &hwmodassert); if(JErr_noError(&o->jErr)) { lua_pushstring(o->L, hwmodassert); lua_pushstring(o->L, systabcheck); lua_rawset(o->L, -3); } } lua_pop(o->L, 1); wsf=""; } JErr_reset(&o->jErr); if(o->workspaceFolder) dcachenomsr(o, TRUE); } LDbgMon_sendResponse(o, "\141\164\164\141\143\150", 0); codecdevice(o); switcherwrite(o, "\151\156\151\164\151\141\154\151\172\145\144"); JEncoder_endObject(&o->jEnc); } static void macepciinterrupt(LDbgMon* o) { LDbgMon_sendResponse(o, "\154\157\141\144\145\144\123\157\165\162\143\145\163", "\173\173\175\175", "\142\157\144\171", "\163\157\165\162\143\145\163"); } static void additionalpages(LDbgMon* o) { (void)o; } static void cacheconfig(LDbgMon* o) { o->initialized=TRUE; } static void machinecpuslocked(LDbgMon* o) { LDbgMon_close(o, 0); } static void accesscycle(LDbgMon* o) { int totalFrames,startFrame,levels; lua_State* L = o->Ldbg; if( ! o->arguments || ! L) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\144\144\175", "\163\164\141\162\164\106\162\141\155\145",&startFrame,"\154\145\166\145\154\163",&levels); if(JErr_isError(&o->jErr)) goto L_err; totalFrames=pmuv3format(L); if((totalFrames - startFrame) <= 0) goto L_err; cleanrange(o, "\163\164\141\143\153\124\162\141\143\145"); JEncoder_setName(&o->jEnc, "\142\157\144\171"); JEncoder_beginObject(&o->jEnc); JEncoder_set(&o->jEnc, "\144", "\164\157\164\141\154\106\162\141\155\145\163",totalFrames); JEncoder_setName(&o->jEnc, "\163\164\141\143\153\106\162\141\155\145\163"); JEncoder_beginArray(&o->jEnc); for( ; levels > 0 && startFrame < totalFrames ; startFrame++) { lua_Debug ar; if(lua_getstack(L,startFrame,&ar) && lua_getinfo(L, "\156\123\154", &ar) && ar.what[0] != '\103' && ar.source[0] == '\100') { IoIntf* io=0; union { S64 sRef; /* Invalid ref */ U8 digest[16]; } u; char* targetdisable = LDbgMon_abspath(o, ar.source+1, &io); const char* gpio1config = ar.name; if( ! gpio1config ) { gpio1config = strrchr(ar.source+1, '\057'); gpio1config = gpio1config ? gpio1config+1 : ar.source+1; } u.sRef=0; if( ! targetdisable && io ) { SharkSslMd5Ctx registermcasp; const char* ptr = ar.source+1; lua_rawgeti(L, LUA_REGISTRYINDEX, o->sourceTabRef); lua_pushstring(L, ptr); SharkSslMd5Ctx_constructor(®istermcasp); SharkSslMd5Ctx_append(®istermcasp, (U8*)ptr,strlen(ptr)); SharkSslMd5Ctx_finish(®istermcasp, u.digest); u.sRef &=0x1FFFFFFFFFFFFF; lua_rawseti(L, -2, u.sRef); lua_pop(L, 1); } JEncoder_set(&o->jEnc,"\173\144\163\144\144\173\154\163\163\175\175", "\151\144", startFrame, "\156\141\155\145",ar.name ? ar.name : gpio1config, "\154\151\156\145", ar.currentline, "\143\157\154\165\155\156", 1, "\163\157\165\162\143\145", "\163\157\165\162\143\145\122\145\146\145\162\145\156\143\145",u.sRef, "\156\141\155\145", gpio1config, "\160\141\164\150", targetdisable ? targetdisable : ar.source+1); if(targetdisable) baFree(targetdisable); levels--; } } JEncoder_endArray(&o->jEnc); JEncoder_endObject(&o->jEnc); JEncoder_endObject(&o->jEnc); return; L_err: cacheerror(o, "\163\164\141\143\153\124\162\141\143\145"); } static void cachecreate(LDbgMon* o) { const char* unmaskheart; const char* val; const char* context=0; lua_State* L = o->Ldbg; S32 unregisterredist=0; S32 queuepriority=0; int top=lua_gettop(L); if( ! o->arguments || ! L) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\163\175","\145\170\160\162\145\163\163\151\157\156",&unmaskheart); if(JErr_isError(&o->jErr)) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\163\175","\143\157\156\164\145\170\164",&context); JErr_reset(&o->jErr); JVal_get(o->arguments, &o->jErr, "\173\144\175","\146\162\141\155\145\111\144",&unregisterredist); JErr_reset(&o->jErr); val=lua_pushfstring(L, "\162\145\164\165\162\156\040\045\163",unmaskheart); if(LUA_OK == luaL_loadbuffer(L,val,strlen(val),0)) { if(LUA_OK != lua_pcall(L,0,1,0) || lua_isnil(L, -1)) { lua_Debug ar; int ix; val=0; if(lua_getstack(L,unregisterredist,&ar) && lua_getinfo(L, "\165\146", &ar)) { for(ix=1 ; ; ix++) { val=lua_getlocal(L, &ar, ix); if( ! val ) break; if( ! strcmp(val, unmaskheart) ) break; lua_pop(L,1); } } if( ! val ) { for(ix=1 ; ix <= ar.nups ; ix++) { val=lua_getupvalue(L, -1, ix); if( ! strcmp(val, unmaskheart) ) break; lua_pop(L,1); val=0; } } if(val) { if(lua_type(L, -1) == LUA_TTABLE) queuepriority=printuncorrectable(o, L, -1); } else lua_pushliteral(L, "\077"); } } else if(context && ! strcmp(context, "\150\157\166\145\162")) lua_pushstring(L, unmaskheart); if(!queuepriority && lua_type(L, -1) == LUA_TTABLE) queuepriority = printuncorrectable(o, L, -1); LDbgMon_sendResponse(o, "\145\166\141\154\165\141\164\145", "\173\163\144\175", "\142\157\144\171", "\162\145\163\165\154\164",luaL_tolstring(L, -1, 0), "\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145",queuepriority); lua_settop(L, top); return; L_err: cacheerror(o, "\145\166\141\154\165\141\164\145"); } static void segmentflush(LDbgMon* o) { (void)o; } static void shutdownsecondary(LDbgMon* o) { LDbgMon_sendResponse(o, "\164\150\162\145\141\144\163", "\173\133\173\144\163\175\135\175", "\142\157\144\171", "\164\150\162\145\141\144\163", "\151\144",1, "\156\141\155\145","\155\141\151\156"); } static void flushhwstate(LDbgMon* o, const char* rightsvalid) { int ix = o->Ldbg ? pmuv3format(o->Ldbg) : 1; switch(rightsvalid[4]) { case 0: o->stepStackIx=ix; break; case '\111': o->stepStackIx=100001; break; case '\117': o->stepStackIx=ix-1; break; case '\145': o->stepStackIx = 100001; break; default: baAssert(0); } o->Ldbg=0; LDbgMon_sendResponse(o, rightsvalid, 0); } static void immitationleave(LDbgMon* o) { o->Ldbg=0; o->stepStackIx = 0; LDbgMon_sendResponse(o, "\143\157\156\164\151\156\165\145", "\173\142\175", "\142\157\144\171", "\141\154\154\124\150\162\145\141\144\163\103\157\156\164\151\156\165\145\144", TRUE); } static void handlercontext(LDbgMon* o) { IoStat st; IoIntf* io; char* driverstate; char* ptr; char* str; JVal* jvBreakpoint; BaBool runtimesuspend; int pathIx,linesTabIx; S64 machinepower=0; lua_State* L=o->L; int top=lua_gettop(L); const char* hwmodassert=0; if( ! o->arguments ) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\173\163\175\142\175", "\163\157\165\162\143\145", "\160\141\164\150",&driverstate, "\163\157\165\162\143\145\115\157\144\151\146\151\145\144",&runtimesuspend); if(JErr_isError(&o->jErr)) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\173\154\175\175","\163\157\165\162\143\145","\163\157\165\162\143\145\122\145\146\145\162\145\156\143\145",&machinepower); JErr_reset(&o->jErr); if(runtimesuspend) { ptr = strrchr(driverstate, '\056'); if( ! ptr || strcmp("\154\163\160",ptr+1)) { if(o->restartOnModifiedSource && o->exitCb) { devcfgclear(o, "\123\157\165\162\143\145\040\155\157\144\151\146\151\145\144\072\040\162\145\163\164\141\162\164\151\156\147\056\056\056"); skcipherencrypt(o, TRUE); } else { pcsxxcontrol1( o,"\163\145\164\102\162\145\141\153\160\157\151\156\164\163", "\123\157\165\162\143\145\040\155\157\144\151\146\151\145\144\041\040\123\145\162\166\145\162\040\155\165\163\164\040\142\145\040\162\145\163\164\141\162\164\145\144\056"); } return; } } lua_rawgeti(L, LUA_REGISTRYINDEX, o->resolvedSourceMapRef); lua_pushnil(L); while(lua_next(L, -2) != 0) { int dummyhwclk; const char* systabcheck = lua_tostring(L, -1); dummyhwclk = strlen(systabcheck); if( ! baStrnCaseCmp(systabcheck, driverstate, dummyhwclk) ) { driverstate+=dummyhwclk; hwmodassert=lua_tostring(L, -2); break; } lua_pop(L,1); } for(ptr = driverstate; *ptr; ptr++) { if(*ptr == '\134') *ptr='\057'; } lua_pushstring(o->L, driverstate); pathIx=lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, o->bpLinesRef); linesTabIx=lua_gettop(L); lua_pushnil(L); while(lua_next(L, -2) != 0) { lua_pushvalue(L, -4); lua_pushnil(L); lua_rawset(L, -3); lua_pushnil(L); if(lua_next(L, -2) == 0) { lua_pushvalue(L, -2); lua_pushnil(L); lua_rawset(L, linesTabIx); } else lua_pop(L, 2); lua_pop(L, 1); } lua_settop(L,linesTabIx); JVal_get(o->arguments, &o->jErr, "\173\133\112\135\175","\142\162\145\141\153\160\157\151\156\164\163",&jvBreakpoint); if(JErr_isError(&o->jErr)) { JErr_reset(&o->jErr); lua_pushnil(L); if(lua_next(L, -2) == 0) o->hasBPs = FALSE; } else { if(machinepower) { lua_rawgeti(L, LUA_REGISTRYINDEX, o->sourceTabRef); lua_rawgeti(L, -1, machinepower); str = (char*)lua_tostring(L, -1); if(str) { io=0; ptr=LDbgMon_abspath(o, str, &io); if(ptr) baFree(ptr); if(io && ! io->statFp(io, str, &st) ) { driverstate=str; pathIx=lua_gettop(L); goto L_ManageBP; } } } lua_rawgeti(L, LUA_REGISTRYINDEX, o->ioRef); lua_pushnil(L); while(lua_next(L, -2) != 0) { if( ( !hwmodassert && machinepower) || (hwmodassert && ! strcmp(hwmodassert, lua_tostring(L, -1))) ) { io = ((baio_t*)lua_touserdata(L,-2))->i; if(io && ! io->statFp(io, driverstate, &st) && ! st.isDir ) { int sffsdrnandflash; L_ManageBP: #ifndef NO_BA_SERVER str = strrchr(driverstate, '\056'); if(str && ! strcmp("\154\163\160",str+1)) { sffsdrnandflash=LHttpResRdr_loadLsp(L, io, driverstate, &st); } else #endif { char* kernelfault; ResIntfPtr fp; size_t icachealiases = (size_t)st.size; kernelfault=(char*)lua_newuserdata(L, icachealiases+1); fp=io->openResFp(io,driverstate,OpenRes_READ,&sffsdrnandflash,0); if(fp && ! fp->readFp(fp,kernelfault,icachealiases,&icachealiases) ) { sffsdrnandflash = luaL_loadbuffer(L, kernelfault, icachealiases, driverstate); } else { lua_pushfstring(L, "\103\141\156\156\157\164\040\162\145\141\144\040\045\163",driverstate); sffsdrnandflash=-1; } if(fp) fp->closeFp(fp); } if(sffsdrnandflash) { pcsxxcontrol1( o, "\163\145\164\102\162\145\141\153\160\157\151\156\164\163", lua_tostring(L, -1)); } else { int mcspi3hwmod; Proto* p = ((Closure *)lua_topointer(L, -1))->l.p; cleanrange(o, "\163\145\164\102\162\145\141\153\160\157\151\156\164\163"); JEncoder_setName(&o->jEnc, "\142\157\144\171"); JEncoder_beginObject(&o->jEnc); JEncoder_setName(&o->jEnc, "\142\162\145\141\153\160\157\151\156\164\163"); JEncoder_beginArray(&o->jEnc); cpuinfostatic(o,p); mcspi3hwmod=lua_gettop(L); while(jvBreakpoint) { S32 enabledisable; S32 backlightnotify=0; S32 asyncupdate = -1; JVal_get(jvBreakpoint, &o->jErr, "\173\144\175", "\154\151\156\145",&enabledisable); if(JErr_isError(&o->jErr)) break; lua_pushvalue(L, -1); lua_pushnil(L); while(lua_next(L, -2) != 0) { backlightnotify=(S32)lua_tointeger(L, -1); if(backlightnotify >= enabledisable) { if(backlightnotify > enabledisable) { enabledisable = asyncupdate >= 0 && (backlightnotify - enabledisable) > (enabledisable - asyncupdate) ? asyncupdate : backlightnotify; } asyncupdate=0; break; } asyncupdate = backlightnotify; lua_pop(L, 1); } if(asyncupdate >= 0) { if(backlightnotify == asyncupdate) enabledisable=backlightnotify; lua_pushinteger(L, enabledisable); lua_rawget(L, linesTabIx); if(lua_isnil(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_pushinteger(L, enabledisable); lua_pushvalue(L, -2); lua_rawset(L, linesTabIx); } lua_pushvalue(L, pathIx); lua_pushinteger(L, ++o->breakpointID); lua_rawset(L, -3); lua_pop(L, 1); JEncoder_set(&o->jEnc, "\173\142\144\144\175", "\166\145\162\151\146\151\145\144", TRUE, "\154\151\156\145", enabledisable, "\151\144", o->breakpointID); } lua_settop(L, mcspi3hwmod); jvBreakpoint = JVal_getNextElem(jvBreakpoint); } JEncoder_endArray(&o->jEnc); JEncoder_endObject(&o->jEnc); JEncoder_endObject(&o->jEnc); o->hasBPs = TRUE; } lua_settop(L, top); return; } } lua_pop(L,1); } pcsxxcontrol1( o, "\163\145\164\102\162\145\141\153\160\157\151\156\164\163", lua_pushfstring(L, "\045\163\040\156\157\164\040\146\157\165\156\144",driverstate)); lua_settop(L, top); } lua_settop(L, top); return; L_err: lua_settop(L, top); cacheerror(o, "\163\145\164\102\162\145\141\153\160\157\151\156\164\163"); } static void keyscanenable(LDbgMon* o) { if(o->arguments) { JVal* jv=0; JVal_get(o->arguments, &o->jErr, "\173\133\112\135\175","\146\151\154\164\145\162\163",&jv); while(jv) { jv = JVal_getNextElem(jv); } } LDbgMon_sendResponse(o, "\163\145\164\105\170\143\145\160\164\151\157\156\102\162\145\141\153\160\157\151\156\164\163",0); } static void interruptsenabled(LDbgMon* o) { JVal* bp; int unmapiommu=1; lua_State* L=o->L; luaL_unref(L, LUA_REGISTRYINDEX, o->funcBpTabRef); lua_newtable (L); lua_pushvalue(L, -1); o->funcBpTabRef = luaL_ref(L, LUA_REGISTRYINDEX); cleanrange(o, "\163\145\164\106\165\156\143\164\151\157\156\102\162\145\141\153\160\157\151\156\164\163"); JEncoder_setName(&o->jEnc,"\142\157\144\171"); JEncoder_beginObject(&o->jEnc); JEncoder_setName(&o->jEnc,"\142\162\145\141\153\160\157\151\156\164\163"); JEncoder_beginArray(&o->jEnc); JVal_get(o->arguments, &o->jErr, "\173\112\175","\142\162\145\141\153\160\157\151\156\164\163",&bp); bp=JVal_getArray(bp, &o->jErr); while(bp) { const char* clearwatch; JVal_get(bp, &o->jErr, "\173\163\175","\156\141\155\145",&clearwatch); JEncoder_set(&o->jEnc, "\173\144\142\175","\151\144",unmapiommu,"\166\145\162\151\146\151\145\144",FALSE); lua_pushstring(L, clearwatch); lua_pushinteger(L, unmapiommu++); lua_rawset(L, -3); bp=JVal_getNextElem(bp); } lua_pop(L, 1); JEncoder_endArray(&o->jEnc); JEncoder_endObject(&o->jEnc); JEncoder_endObject(&o->jEnc); } static void shouldswizzle(lua_State* L, const char* videoprobe) { if( ! strcmp(videoprobe, "\164\162\165\145") || ! strcmp(videoprobe, "\146\141\154\163\145") ) lua_pushboolean(L, '\164' == videoprobe[0] ? TRUE : FALSE); else if( ! lua_stringtonumber(L, videoprobe) ) lua_pushstring(L, videoprobe); } static const char* LDbgMon_setTabVal(LDbgMon* o, lua_State* L, const char* gpio1config, const char* videoprobe) { const char* ethernatenable=eNotFound; (void)o; baAssert(lua_type(L, -1) == LUA_TTABLE); lua_getfield(L, -1, gpio1config); if( ! lua_isnil(L, -1) ) { lua_pushstring(L,gpio1config); shouldswizzle(L, videoprobe); lua_rawset(L, -4); ethernatenable=0; } lua_pop(L,1); return ethernatenable; } static void eventenable(LDbgMon* o) { int refIx,ix; S32 queuepriority; const char* gpio1config; const char* videoprobe; const char* singlenormaliseround; lua_State* L = o->Ldbg; const char* ethernatenable=eNotFound; if( ! o->arguments || ! L) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\144\163\163\175", "\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145",&queuepriority, "\156\141\155\145",&gpio1config, "\166\141\154\165\145",&videoprobe); if(JErr_isError(&o->jErr)) goto L_err; if(VREF_NOT_VARTAB & queuepriority) { int cachemaint = queuepriority & 0xFFFF0000; if(cachemaint == VREF_GLOBAL) { lua_pushglobaltable(L); ethernatenable=LDbgMon_setTabVal(o, L, gpio1config, videoprobe); lua_pop(L, 1); } else { lua_Debug ar; int unregisterredist = queuepriority & 0xFFFF; if(pmuv3format(L) >= unregisterredist && lua_getstack(L,unregisterredist,&ar) && lua_getinfo(L, "\165\146", &ar)) { switch(cachemaint) { case VREF_PARAMETER: if(gpio1config[0] == '\043') { refIx = U32_atoi(gpio1config+1); if(refIx) { for(ix=1 ; ; ix++) { gpio1config=lua_getlocal(L, &ar, ix); if( ! gpio1config ) break; if(gpio1config[0] == '\050') { if(--refIx == 0) { shouldswizzle(L, videoprobe); lua_setlocal(L, &ar, ix); lua_pop(L,1); ethernatenable=0; break; } } lua_pop(L,1); } } } else { for(ix=1 ; ; ix++) { singlenormaliseround=lua_getlocal(L, &ar, ix); if( ! singlenormaliseround ) break; if( ! strcmp(gpio1config,singlenormaliseround) ) { shouldswizzle(L, videoprobe); lua_setlocal(L, &ar, ix); lua_pop(L,1); ethernatenable=0; break; } lua_pop(L,1); } } break; case VREF_VARARG: refIx = U32_atoi(gpio1config); if(refIx) { refIx=-refIx; shouldswizzle(L, videoprobe); if(lua_setlocal(L, &ar, refIx)) ethernatenable=0; else lua_pop(L,1); } break; case VREF_CLOSURE: for(ix=1 ; ix <= ar.nups ; ix++) { singlenormaliseround=lua_getupvalue(L, -1, ix); if( ! strcmp(gpio1config,singlenormaliseround) ) { shouldswizzle(L, videoprobe); lua_setupvalue(L, -3, ix); lua_pop(L,1); ethernatenable=0; break; } lua_pop(L,1); } break; default: break; } lua_pop(L, 1); } } } else { lua_rawgeti(L, LUA_REGISTRYINDEX, o->varTabRef); lua_rawgeti(L, -1, queuepriority); if(lua_type(L, -1) == LUA_TTABLE) ethernatenable=LDbgMon_setTabVal(o, L, gpio1config, videoprobe); lua_pop(L, 2); } if(ethernatenable) pcsxxcontrol1(o, "\163\145\164\126\141\162\151\141\142\154\145", ethernatenable); else LDbgMon_sendResponse(o, "\163\145\164\126\141\162\151\141\142\154\145","\173\163\175","\142\157\144\171","\166\141\154\165\145",videoprobe); return; L_err: cacheerror(o, "\163\145\164\126\141\162\151\141\142\154\145"); } static void storestack(LDbgMon* o) { S64 machinepower; if( ! o->arguments) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\154\175","\163\157\165\162\143\145\122\145\146\145\162\145\156\143\145",&machinepower); if(JErr_isError(&o->jErr)) goto L_err; if(machinepower != 0) { const char* panicblock; lua_State* L = o->L; int top=lua_gettop(L); lua_rawgeti(L, LUA_REGISTRYINDEX, o->sourceTabRef); lua_rawgeti(L, -1, machinepower); panicblock = lua_tostring(L, -1); if(panicblock) { IoIntf* io=0; char* abs=LDbgMon_abspath(o, panicblock, &io); if(abs) baFree(abs); if(io) { IoStat st; if( ! io->statFp(io, panicblock, &st) ) { char* kernelfault; ResIntfPtr fp; int sffsdrnandflash; size_t icachealiases = (size_t)st.size; kernelfault=(char*)lua_newuserdata(L, icachealiases+1); fp=io->openResFp(io,panicblock,OpenRes_READ,&sffsdrnandflash,0); if(fp) { if( ! fp->readFp(fp,kernelfault,icachealiases,&icachealiases) ) { kernelfault[icachealiases]=0; LDbgMon_sendResponse(o, "\163\157\165\162\143\145","\173\163\175", "\142\157\144\171", "\143\157\156\164\145\156\164", kernelfault); lua_settop(L, top); return; } fp->closeFp(fp); } } } } lua_settop(L, top); } pcsxxcontrol1(o, "\163\157\165\162\143\145", eNotFound); return; L_err: cacheerror(o, "\163\157\165\162\143\145"); } static void mcspi4hwmod(LDbgMon* o) { lua_Debug ar; S32 unregisterredist; lua_State* L = o->Ldbg; if( ! o->arguments || ! L) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\144\175","\146\162\141\155\145\111\144",&unregisterredist); if(JErr_isError(&o->jErr)) goto L_err; if(pmuv3format(L) >= unregisterredist && lua_getstack(L,unregisterredist,&ar) && lua_getinfo(L, "\165", &ar)) { cleanrange(o, "\163\143\157\160\145\163"); JEncoder_setName(&o->jEnc, "\142\157\144\171"); JEncoder_beginObject(&o->jEnc); JEncoder_setName(&o->jEnc, "\163\143\157\160\145\163"); JEncoder_beginArray(&o->jEnc); JEncoder_set(&o->jEnc, "\173\163\144\142\175", "\156\141\155\145","\107\154\157\142\141\154\163", "\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145",VREF_GLOBAL | unregisterredist, "\145\170\160\145\156\163\151\166\145", TRUE); if(ar.nups > 0) { JEncoder_set(&o->jEnc, "\173\163\144\142\175", "\156\141\155\145","\103\154\157\163\165\162\145\163", "\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145",VREF_CLOSURE | unregisterredist, "\145\170\160\145\156\163\151\166\145", FALSE); } if(ar.isvararg) { JEncoder_set(&o->jEnc, "\173\163\144\142\175", "\156\141\155\145","\126\141\162\141\162\147\163", "\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145",VREF_VARARG | unregisterredist, "\145\170\160\145\156\163\151\166\145", FALSE); } if(ar.nparams > 0) { JEncoder_set(&o->jEnc, "\173\163\144\142\175", "\156\141\155\145","\120\141\162\141\155\145\164\145\162\163", "\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145",VREF_PARAMETER | unregisterredist, "\145\170\160\145\156\163\151\166\145", FALSE); } JEncoder_endArray(&o->jEnc); JEncoder_endObject(&o->jEnc); JEncoder_endObject(&o->jEnc); return; } L_err: pcsxxcontrol1(o, "\163\143\157\160\145\163", "\111\156\166\141\154\151\144\040\146\162\141\155\145"); } static void createulong(LDbgMon* o, lua_State* L, int ix, const char* gpio1config) { ix=lua_absindex(L, ix); if(gpio1config && *gpio1config) { S32 queuepriority=lua_type(L,ix) == LUA_TTABLE ? printuncorrectable(o,L,ix) : 0; JEncoder_set(&o->jEnc, "\173\163\163\163\144\175", "\156\141\155\145",gpio1config, "\164\171\160\145",luaL_typename(L, ix), "\166\141\154\165\145",luaL_tolstring(L, ix, 0), "\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145", queuepriority); lua_pop(L, 1); } } static void memtypeclassify(LDbgMon* o, lua_State* L) { baAssert(lua_type(L, -1) == LUA_TTABLE); lua_pushnil(L); while(lua_next(L, -2) != 0) { const char* sourcerouting=luaL_tolstring(L, -2, 0); createulong(o, L, -2, sourcerouting); lua_pop(L,2); } } static void commonclkdm(LDbgMon* o) { const char* gpio1config; S32 queuepriority; lua_State* L = o->Ldbg; if( ! o->arguments || ! L) goto L_err; JVal_get(o->arguments, &o->jErr, "\173\144\175","\166\141\162\151\141\142\154\145\163\122\145\146\145\162\145\156\143\145",&queuepriority); if(JErr_isError(&o->jErr)) goto L_err; cleanrange(o, "\166\141\162\151\141\142\154\145\163"); JEncoder_setName(&o->jEnc, "\142\157\144\171"); JEncoder_beginObject(&o->jEnc); JEncoder_setName(&o->jEnc, "\166\141\162\151\141\142\154\145\163"); JEncoder_beginArray(&o->jEnc); if(VREF_NOT_VARTAB & queuepriority) { int cachemaint = queuepriority & 0xFFFF0000; if(cachemaint == VREF_GLOBAL) { lua_pushglobaltable(L); memtypeclassify(o,L); lua_pop(L, 1); } else { lua_Debug ar; int ix; int unregisterredist = queuepriority & 0xFFFF; if(pmuv3format(L) >= unregisterredist && lua_getstack(L,unregisterredist,&ar) && lua_getinfo(L, "\165\146", &ar)) { switch(cachemaint) { case VREF_PARAMETER: queuepriority=FALSE; for(ix=1 ; ; ix++) { gpio1config = lua_getlocal(L, &ar, ix); if( ! gpio1config ) break; if(gpio1config[0] == '\050') queuepriority=TRUE; else createulong(o, L, -1, gpio1config); lua_pop(L,1); } if(queuepriority) { queuepriority=0; for(ix=1 ; ; ix++) { gpio1config = lua_getlocal(L, &ar, ix); if( ! gpio1config ) break; if(gpio1config[0] == '\050') { createulong( o,L,-2,lua_pushfstring(L,"\043\045\144",++queuepriority)); lua_pop(L,2); } else lua_pop(L,1); } } break; case VREF_VARARG: for(ix =-1 ; ; ix--) { if( ! lua_getlocal(L, &ar, ix) ) break; createulong(o, L, -2, lua_pushfstring(L, "\045\144", -ix)); lua_pop(L,2); } break; case VREF_CLOSURE: for(ix=1 ; ix <= ar.nups ; ix++) { createulong(o, L, -1, lua_getupvalue(L, -1, ix)); lua_pop(L,1); } break; default: break; } lua_pop(L, 1); } } } else { lua_rawgeti(L, LUA_REGISTRYINDEX, o->varTabRef); lua_rawgeti(L, -1, queuepriority); if(lua_type(L, -1) == LUA_TTABLE) memtypeclassify(o,L); lua_pop(L, 2); } JEncoder_endArray(&o->jEnc); JEncoder_endObject(&o->jEnc); JEncoder_endObject(&o->jEnc); return; L_err: cacheerror(o, "\166\141\162\151\141\142\154\145\163"); } static void skcipherencrypt(LDbgMon* o, BaBool ds1286devinit) { LDbgMon_close(o, 0); if(o->exitCb) { o->shutdownInProgress=TRUE; o->exitCb(o->exitCbData, ds1286devinit); if(ds1286devinit) o->status=100000; } } static void ptracerequest(LDbgMon* o) { LDbgMon_sendResponse(o, "\162\145\163\164\141\162\164", 0); codecdevice(o); skcipherencrypt(o, TRUE); } static void nvmemcells(LDbgMon* o) { BaBool ds1286devinit=FALSE; if(o->arguments) JVal_get(o->arguments, &o->jErr, "\173\142\175","\162\145\163\164\141\162\164",&ds1286devinit); LDbgMon_sendResponse(o, "\164\145\162\155\151\156\141\164\145", 0); codecdevice(o); skcipherencrypt(o, ds1286devinit); } static int watchdogtimer(LDbgMon* o, JParserValFact* pv) { int backuppdata; for(backuppdata=0;;) { char* ptr; int len; SoDispCon_setDispHasRecData((SoDispCon*)o); if(o->isDispRecEvent) SoDispCon_setNonblocking((SoDispCon*)o); if((len=SoDispCon_readData( (SoDispCon*)o, o->buf+backuppdata, 35-backuppdata,FALSE))<0) { return LDbgMon_close(o,"\045\163\040\045\144\040\045\144",eClose,__LINE__,len); } if(o->isDispRecEvent) { SoDispCon_setBlocking((SoDispCon*)o); o->isDispRecEvent=FALSE; if(len == 0) return 0; } backuppdata+=len; o->buf[backuppdata]=0; ptr = strstr(o->buf, "\015\012\015\012"); if(ptr) { JParser parser; U32 buttonsmotorola; int doubleftouiz = (ptr+4) - o->buf; *ptr--=0; while(isdigit(*(ptr-1))) ptr--; buttonsmotorola=U32_atoi(ptr); JParser_constructor(&parser, (JParserIntf*)pv, o->buf+sizeof(o->buf)-50, 50, AllocatorIntf_getDefault(),0); if(doubleftouiz < backuppdata) { len=backuppdata-doubleftouiz; JParser_parse(&parser, (U8*)(o->buf+doubleftouiz), len); buttonsmotorola-=len; } while(JParser_getStatus(&parser) == JParsStat_NeedMoreData && buttonsmotorola != 0) { len = buttonsmotorola > (sizeof(o->buf)-50) ? (int)(sizeof(o->buf)-50) : (int)buttonsmotorola; SoDispCon_setDispHasRecData((SoDispCon*)o); if((len=SoDispCon_readData((SoDispCon*)o, o->buf, len,FALSE))<0) { JParser_destructor(&parser); return LDbgMon_close(o,"\045\163\040\045\144\040\045\144",eClose,__LINE__,len); } JParser_parse(&parser, (U8*)o->buf, len); buttonsmotorola -= len; } len = JParser_getStatus(&parser); JParser_destructor(&parser); return (len == JParsStat_Done || len == JParsStat_DoneEOS) && buttonsmotorola == 0 ? 1 : LDbgMon_close(o,eInvalidDAP); } if(len+backuppdata >= 35) return LDbgMon_close(o,eInvalidDAP); } } static void fixupmemoffset(LDbgMon* o) { JParserValFact pv; o->dapBusy=TRUE; JParserValFact_constructor( &pv, AllocatorIntf_getDefault(), AllocatorIntf_getDefault()); if( watchdogtimer(o, &pv) > 0 ) { JErr_reset(&o->jErr); JVal_get(JParserValFact_getFirstVal(&pv), &o->jErr, "\173\163\144\163\175", "\143\157\155\155\141\156\144",&o->command, "\163\145\161", &o->recSeq, "\164\171\160\145", &o->type); if(JErr_isError(&o->jErr)) goto L_err; JVal_get(JParserValFact_getFirstVal(&pv), &o->jErr, "\173\112\175", "\141\162\147\165\155\145\156\164\163",&o->arguments); if(JErr_isError(&o->jErr)) { o->arguments=0; JErr_reset(&o->jErr); } #if 0 printf("\103\115\104\040\045\163\012",o->command); #endif switch(o->command[3]) { case '\141': if(!strcmp("\141\164\164\141\143\150",o->command)) cpuidleconfig(o); else if(!strcmp("\142\162\145\141\153\160\157\151\156\164\114\157\143\141\164\151\157\156\163",o->command)) additionalpages(o); else goto L_err; break; case '\144': if(!strcmp("\154\157\141\144\145\144\123\157\165\162\143\145\163",o->command)) macepciinterrupt(o); else goto L_err; break; case '\146': if(!strcmp("\143\157\156\146\151\147\165\162\141\164\151\157\156\104\157\156\145",o->command)) cacheconfig(o); else goto L_err; break; case '\143': if(!strcmp("\144\151\163\143\157\156\156\145\143\164",o->command)) machinecpuslocked(o); else if(!strcmp("\163\164\141\143\153\124\162\141\143\145",o->command)) accesscycle(o); else goto L_err; break; case '\154': if(!strcmp("\145\166\141\154\165\141\164\145",o->command)) cachecreate(o); else goto L_err; break; case '\145': if(!strcmp("\145\170\143\145\160\164\151\157\156\111\156\146\157",o->command)) segmentflush(o); else if(!strcmp("\164\150\162\145\141\144\163",o->command)) shutdownsecondary(o); else goto L_err; break; case '\164': if(!strcmp("\143\157\156\164\151\156\165\145",o->command)) immitationleave(o); else if(!strcmp("\151\156\151\164\151\141\154\151\172\145",o->command)) disableoutputs(o); else if(!strcmp("\156\145\170\164",o->command)) flushhwstate(o,"\156\145\170\164"); else if(!strcmp("\162\145\163\164\141\162\164",o->command)) ptracerequest(o); else goto L_err; break; case '\163': if(!strcmp("\160\141\165\163\145",o->command)) flushhwstate(o,"\160\141\165\163\145"); else goto L_err; break; case '\102': if(!strcmp("\163\145\164\102\162\145\141\153\160\157\151\156\164\163",o->command)) handlercontext(o); else goto L_err; break; case '\105': if(!strcmp("\163\145\164\105\170\143\145\160\164\151\157\156\102\162\145\141\153\160\157\151\156\164\163",o->command)) keyscanenable(o); else goto L_err; break; case '\106': if(!strcmp("\163\145\164\106\165\156\143\164\151\157\156\102\162\145\141\153\160\157\151\156\164\163",o->command)) interruptsenabled(o); else goto L_err; break; case '\126': if(!strcmp("\163\145\164\126\141\162\151\141\142\154\145",o->command)) eventenable(o); else goto L_err; break; case '\162': if(!strcmp("\163\157\165\162\143\145",o->command)) storestack(o); else goto L_err; break; case '\160': if(!strcmp("\163\143\157\160\145\163",o->command)) mcspi4hwmod(o); else if(!strcmp("\163\164\145\160\111\156",o->command)) flushhwstate(o,"\163\164\145\160\111\156"); else if(!strcmp("\163\164\145\160\117\165\164",o->command)) flushhwstate(o,"\163\164\145\160\117\165\164"); else goto L_err; break; case '\151': if(!strcmp("\166\141\162\151\141\142\154\145\163",o->command)) commonclkdm(o); else goto L_err; break; case '\155': if(!strcmp("\164\145\162\155\151\156\141\164\145",o->command)) nvmemcells(o); else goto L_err; break; default: L_err: LDbgMon_close(o,"\162\145\143\145\151\166\145\144\040\165\156\153\156\157\167\156\040\143\157\155\155\141\156\144\040\047\045\163\047\012",o->command); } } JParserValFact_destructor(&pv); codecdevice(o); o->dapBusy=FALSE; } static int dpllcoreround(lua_State* L) { LDbgMon_close((LDbgMon*)lua_touserdata(L, 1),0); lua_pushlightuserdata(L, (void*)LDbgMon_get); lua_pushnil(L); lua_rawset(L, LUA_REGISTRYINDEX); return 0; } static void prctlstatus(SoDispCon* fdc37m81xconfig) { LDbgMon* o = (LDbgMon*)fdc37m81xconfig; if(o->dapBusy) { if(SoDispCon_recEvActive(fdc37m81xconfig)) SoDisp_deactivateRec(o->dispatcher,fdc37m81xconfig); } else { o->isDispRecEvent=TRUE; fixupmemoffset(o); if(SoDispCon_isValid((SoDispCon*)o)) { if( ! SoDispCon_recEvActive((SoDispCon*)o) ) { SoDisp_activateRec(o->dispatcher,(SoDispCon*)o); } } } } static int adjustcontext(lua_State* L) { int sffsdrnandflash; char* sha256import=0; const char* writereg16="\154\157\143\141\154\150\157\163\164"; const char* apecsmachine=0; U16 hwmoddeassert = 4711; int setupvector=FALSE; int clearotgph=TRUE; int clkctrlmatch = INT_MAX; LDbgMon* o = LDbgMon_get(L); SoDisp* ptraceaccess=HttpServer_getDispatcher(o->bap->server); o->dispatcher=ptraceaccess; lua_settop(L,1); if(lua_type(L, 1) == LUA_TTABLE) { lua_getfield(L, 1, "\160\157\162\164"); hwmoddeassert=(U16)luaL_optinteger(L, -1, hwmoddeassert); lua_getfield(L, 1, "\162\145\164\162\171"); clkctrlmatch=(int)luaL_optinteger(L, -1, clkctrlmatch); lua_getfield(L, 1, "\162\145\143\157\156\156\145\143\164"); setupvector = balua_optboolean(L, -1, FALSE); lua_getfield(L, 1, "\143\154\151\145\156\164"); clearotgph = balua_optboolean(L, -1, TRUE); lua_getfield(L, 1, "\163\164\157\160"); o->stepStackIx = balua_optboolean(L, -1, FALSE) ? 100000 : 0; lua_getfield(L, 1, "\162\145\163\164\141\162\164\157\156\155\157\144"); o->restartOnModifiedSource = (BaBool)balua_optboolean(L, -1, FALSE); lua_settop(L,2); lua_getfield(L, 1, "\151\156\164\146"); apecsmachine = luaL_optstring(L, -1, 0); lua_getfield(L, 1, "\150\157\163\164"); writereg16=luaL_optstring(L, -1, writereg16); } if(SoDispCon_isValid((SoDispCon*)o)) { if(setupvector) LDbgMon_close(o,0); else return reportpanic(L, "\101\154\162\145\141\144\171\040\143\157\156\156\145\143\164\145\144"); } if(clearotgph) { int debugstart; BaTime msTime=baGetMsClock(); for(debugstart=0 ; (sffsdrnandflash = SoDispCon_connect( (SoDispCon*)o,writereg16,hwmoddeassert,apecsmachine,0,1000,FALSE,FALSE,&sha256import)) < 0; debugstart++) { if(ptraceaccess->doExit) return reportpanic(L, baErr2Str(E_SYS_SHUTDOWN)); HttpTrace_printf(5,"\114\104\142\147\115\157\156\040\143\157\156\156\145\143\164\151\157\156\040\045\163\072\045\144\040\146\141\151\154\145\144\072\040\045\163\040\045\163\045\163\012", writereg16,hwmoddeassert, baErr2Str(sffsdrnandflash),sha256import?sha256import:"", debugstart < clkctrlmatch ? "\056\040\122\145\164\162\171\151\156\147\056\056\056" : "\056\040\107\151\166\151\156\147\040\165\160\041"); if(debugstart >= clkctrlmatch) return reportpanic(L, baErr2Str(sffsdrnandflash)); if((baGetMsClock() - msTime) < 500) Thread_sleep(500); msTime=baGetMsClock(); } HttpTrace_printf(5,"\114\104\142\147\115\157\156\040\143\157\156\156\145\143\164\145\144\040\164\157\040\045\163\072\045\144\056\012",writereg16,hwmoddeassert); } else { HttpSocket ls; HttpSocket* s = &((SoDispCon*)o)->httpSocket; HttpSocket_constructor(&ls); HttpSocket_sockStream(&ls, apecsmachine, FALSE, &sffsdrnandflash); if(!sffsdrnandflash) { HttpSockaddr sockAddr; HttpSockaddr_gethostbyname(&sockAddr, apecsmachine, FALSE, &sffsdrnandflash); if(!sffsdrnandflash) { HttpSocket_soReuseaddr(&ls, &sffsdrnandflash); HttpSocket_bind(&ls, &sockAddr, hwmoddeassert, &sffsdrnandflash); if(!sffsdrnandflash) { HttpSocket_listen(&ls, &sockAddr, 1, &sffsdrnandflash); if(!sffsdrnandflash) { HttpTrace_printf( 5,"\114\104\142\147\115\157\156\040\167\141\151\164\151\156\147\040\146\157\162\040\143\157\156\156\145\143\164\151\157\156\040\157\156\040\045\154\163\040\160\157\162\164\040\045\144\012", apecsmachine ? apecsmachine : "", hwmoddeassert); HttpSocket_accept(&ls, s, &sffsdrnandflash); if(!sffsdrnandflash) { HttpServCon_bindExec((SoDispCon*)o); } } } } HttpSocket_close(&ls); } HttpTrace_printf(5,"\114\104\142\147\115\157\156\040\143\157\156\156\145\143\164\151\157\156\040\045\163\012", sffsdrnandflash ? "\146\141\151\154\145\144" : "\145\163\164\141\142\154\151\163\150\145\144"); if(sffsdrnandflash) return reportpanic(L, baErr2Str(sffsdrnandflash)); } DynBuffer_constructor(&o->jEncBuf,2048,1024,AllocatorIntf_getDefault(),0); JErr_constructor(&o->jErr); JEncoder_constructor(&o->jEnc,&o->jErr,(BufPrint*)&o->jEncBuf); lua_newtable(L); o->resolvedSourceMapRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_newtable(L); o->bpLinesRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_newtable(L); lua_createtable(L, 0, 1); lua_pushliteral(L, "\166"); lua_setfield(L, -2, "\137\137\155\157\144\145"); lua_setmetatable(L, -2); o->varTabRef = luaL_ref(L, LUA_REGISTRYINDEX); o->varTabIx=1; lua_newtable(L); o->sourceTabRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_newtable(L); lua_createtable(L, 0, 1); lua_pushliteral(L, "\166"); lua_setfield(L, -2, "\137\137\155\157\144\145"); lua_setmetatable(L, -2); o->absPathCacheRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_newtable(L); o->funcBpTabRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_settop(o->L, 0); while( ! o->initialized && SoDispCon_isValid((SoDispCon*)o)) fixupmemoffset(o); if(SoDispCon_isValid((SoDispCon*)o)) { SoDisp_activateRec(ptraceaccess,(SoDispCon*)o); } lua_pushboolean(L, supportsdirect(o, TRUE)); return 1; } static int sha256arm64(lua_State* L) { LDbgMon* o = LDbgMon_get(L); int handlersetup=SoDispCon_isValid((SoDispCon*)o); LDbgMon_close(o,0); lua_pushboolean(L, handlersetup); return 1; } static int au1000intclknames(lua_State* L) { int handlersetup; LDbgMon* o = LDbgMon_get(L); if(resetcontroller==lua_gethook(L)) { supportsdirect(o, FALSE); handlersetup=TRUE; } else handlersetup=FALSE; lua_pushboolean(L, handlersetup); return 1; } static int compressgeneric(lua_State* L) { if(balua_optboolean(L, 1, FALSE)) LDbgMon_get(L)->stepStackIx = 100000; lua_pushboolean(L, supportsdirect(LDbgMon_get(L), TRUE)); return 1; } static const luaL_Reg ldbgmonLib[] = { {"\143\157\156\156\145\143\164", adjustcontext}, {"\143\154\157\163\145", sha256arm64}, {"\160\141\165\163\145", au1000intclknames}, {"\162\145\163\165\155\145", compressgeneric}, {NULL, NULL} }; void LDbgMon_userstatethread(struct lua_State* L, struct lua_State* L1) { LDbgMon* o = LDbgMon_get(L); if (!o || o->shutdownInProgress) { lua_pop(L, 1); return; } lua_rawgeti(L, LUA_REGISTRYINDEX, o->threadRef); lua_pushboolean(L, TRUE); lua_rawsetp(L, -2, L1); lua_pop(L,2); } void LDbgMon_userstatefree(struct lua_State* L, struct lua_State* L1) { LDbgMon* o = LDbgMon_get(L); if(!o || o->shutdownInProgress) return; lua_rawgeti(L, LUA_REGISTRYINDEX, o->threadRef); lua_pushnil(L); lua_rawsetp(L, -2, L1); lua_pop(L,2); } static int enableprivileged(lua_State* L) { LDbgMon* o = LDbgMon_get(L); IoIntf* io = ((baio_t*)lua_touserdata(L,1))->i; char* withinoptimized=IoIntf_getAbspath(io,""); lua_rawgeti(L, LUA_REGISTRYINDEX, o->ioRef); lua_pushvalue(L, 1); lua_pushstring(L, withinoptimized ? withinoptimized : ""); lua_rawset(L, -3); if(withinoptimized) baFree(withinoptimized); dcachenomsr(o, FALSE); return 0; } static int claimbridge(lua_State* L) { static const luaL_Reg LDbgMonLib[] = { {"\137\137\147\143", dpllcoreround}, {NULL, NULL} }; LDbgMon* o; int top,ioTabIx; BaLua_param* p = balua_getparam(L); top=lua_gettop(L); lua_pushlightuserdata(L, (void*)LDbgMon_get); o=(LDbgMon*)lua_newuserdata(L, sizeof(LDbgMon)); if( ! luaL_newmetatable(L, "\114\104\142\147\115\157\156") ) { baAssert(0); } lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,LDbgMonLib,0); lua_setmetatable(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); memset(o, 0, sizeof(LDbgMon)); o->L = balua_getmainthread(L); o->bap = balua_getparam(L); lua_getglobal(L, "\164\141\142\154\145"); lua_pushliteral(L, "\163\157\162\164"); lua_rawget(L, -2); luaL_checktype(L, -1, LUA_TFUNCTION); o->sortRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_newtable(L); ioTabIx=lua_gettop(L); lua_pushvalue(L,-1); lua_createtable(L, 0, 1); lua_pushliteral(L, "\153"); lua_setfield(L, -2, "\137\137\155\157\144\145"); lua_setmetatable(L, -2); o->ioRef = luaL_ref(L, LUA_REGISTRYINDEX); lua_newtable(L); o->threadRef = luaL_ref(L, LUA_REGISTRYINDEX); balua_pushbatab(L); lua_pushcfunction(L, enableprivileged); lua_rawseti(L, -2, BA_DBGMON_NEWIO_CB); lua_rawgeti(L,-1,BA_IOINTFTAB); lua_pushnil(L); while(lua_next(L, -2) != 0) { const char* rightsvalid=0; IoIntf* io = ((baio_t*)lua_touserdata(L,-1))->i; char* withinoptimized=IoIntf_getAbspath(io,""); IoIntf_getType(io,&rightsvalid,0); if(withinoptimized || (rightsvalid && !strcmp("\172\151\160", rightsvalid)) ) { lua_pushstring(L, withinoptimized ? withinoptimized : ""); lua_rawset(L, ioTabIx); baFree(withinoptimized); } else lua_pop(L,1); } SoDispCon_constructor( (SoDispCon*)o, HttpServer_getDispatcher(p->server), prctlstatus); SoDisp_addConnection(HttpServer_getDispatcher(p->server),(SoDispCon*)o); lua_settop(L, top); luaL_newlib(L,ldbgmonLib); return 1; } #ifdef BUILD_AS_DLL #ifdef _WIN32 __declspec(dllexport) int __cdecl #else int #endif luaopen_ldbgmon(lua_State* L) { luaintf(L); return claimbridge(L); } #else void ba_ldbgmon(lua_State* L, void (*exitCb)(void*,BaBool), void* exitCbData) { LDbgMon* m; int top=lua_gettop(L); luaL_requiref(L, "\154\144\142\147\155\157\156", claimbridge, FALSE); m=LDbgMon_get(L); m->exitCb=exitCb; m->exitCbData=exitCbData; lua_settop(L,top); } #endif #endif #if USE_FORKPTY == 1 #if !defined(USE_AMALGAMATED_BAS) || defined(BAS_LOADED) #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include #include #include #include #include #include #include #include #ifndef BA_QNX #include #endif #include #include #include #include #include #include #include "lxrc.h" #ifdef BA_QNX #define TTYDEF_IFLAG (BRKINT | ICRNL | IMAXBEL | IXON | IXANY) #define TTYDEF_OFLAG OPOST #define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL) #define TTYDEF_CFLAG (CREAD | CS8 | HUPCL) #endif static const char efmt[]={"\103\141\156\156\157\164\040\163\145\164\040\047\045\163\047\040\050\144\165\160\062\040\145\162\162\051"}; #ifdef LUA_USE_UCLINUX #define zzbafork vfork #else #define zzbafork fork #endif static int lDoErr(lua_State* L,const char* fmt, ...) { va_list demuxregids; lua_pushnil(L); va_start(demuxregids, fmt); lua_pushvfstring(L,fmt,demuxregids); va_end(demuxregids); return 2; } static int cpuidlerestore(lua_State* L) { lua_pushnil(L); lua_pushliteral(L, "\164\145\162\155\151\156\141\164\145\144"); return 2; } static void doClientError(const char* fmt, ...) { int err=errno; va_list demuxregids; syslog(LOG_ERR,"\102\101\040\146\157\162\153\160\164\171\040\045\163\072\040",strerror(err)); va_start(demuxregids, fmt); vsyslog(LOG_ERR,fmt,demuxregids); va_end(demuxregids); _exit(1); } static ThreadMutex* getSoDispMutex(lua_State* L) { return balua_getparam(L)->mutex; } static void pollingenabled(SoDispCon* con, SoDisp* ptraceaccess, SoDispCon_DispRecEv e, int pty) { SoDispCon_constructor(con, ptraceaccess, e); con->httpSocket.hndl=pty; SoDisp_addConnection(ptraceaccess, con); SoDisp_activateRec(ptraceaccess, con); } static int consoledriver(lua_State* L, int ex) { int ret=1; unsigned int sffsdrnandflash = (unsigned int)WEXITSTATUS(ex); lua_pushinteger(L, sffsdrnandflash); if(ex) { lua_pushboolean(L, WIFEXITED(ex) ? TRUE : FALSE); lua_pushboolean(L, WIFSIGNALED(ex) ? TRUE : FALSE); lua_pushinteger(L,WTERMSIG(ex)); ret += 3; } return ret; } #if defined(ANDROID) || defined(__ANDROID__) #define zzgetpt() open("\057\144\145\166\057\160\164\155\170", O_RDWR) #else #define zzgetpt() posix_openpt(O_RDWR) #endif #if defined(BSD) || defined(_OSX_) #define XTABS OXTABS static int baptsname_r(int fd, char* b, int bl) { char* x=ptsname(fd); if(x && strlen(x) < bl) { strcpy(b,x); return 0; } return -1; } #else #define baptsname_r ptsname_r #endif #define BAFORKPTY "\102\101\106\117\122\113\120\124\131" #define PTY_NAME_SIZE 64 typedef struct { /* 5 first variables used only in asynch mode */ SoDispCon super; /* stdin and stdout */ SoDispCon conStderr; lua_State* Lt; int ref; /* Reference userdata in LUA_REGISTRYINDEX */ int pty; /* stdin+stdout terminal. From getpt */ int pipefd[2]; int pid; /* From fork */ int exitCode; BaBool hasExitCode; BaBool busy; BaBool sigint; } ForkPTY; static int alloccipher(lua_State* L,ForkPTY* te) { int ex; char* msg=strerror(errno); if(waitpid(te->pid, &ex, WNOHANG) <= 0) return lDoErr(L,"\045\163",msg); lua_pushnil(L); lua_pushliteral(L, "\164\145\162\155\151\156\141\164\145\144"); te->exitCode=ex; te->hasExitCode=TRUE; return 2; } static ForkPTY* checkForkPTY(lua_State* L) { ForkPTY* te = (ForkPTY*)luaL_checkudata(L,1,BAFORKPTY); if(te->busy && L != te->Lt) luaL_error(L, "\142\165\163\171"); if(te->pty < 0) { cpuidlerestore(L); return 0; } return te; } static ForkPTY* checkForkPTYOnExit(lua_State* L, int* ret) { ForkPTY* te = (ForkPTY*)luaL_checkudata(L,1,BAFORKPTY); if(te->busy && L != te->Lt) luaL_error(L, "\142\165\163\171"); if(te->pty < 0) { if(te->hasExitCode) { lua_pushboolean(L, TRUE); *ret = 1 + consoledriver(L, te->exitCode); } else *ret = cpuidlerestore(L); return 0; } return te; } static void flashprobe(ForkPTY* te) { if(te->Lt) { SoDisp* ptraceaccess = SoDispCon_getDispatcher((SoDispCon*)te); if(SoDispCon_recEvActive((SoDispCon*)te)) SoDisp_deactivateRec(ptraceaccess,(SoDispCon*)te); if(SoDispCon_dispatcherHasCon((SoDispCon*)te)) SoDisp_removeConnection(ptraceaccess,(SoDispCon*)te); if(SoDispCon_recEvActive(&te->conStderr)) SoDisp_deactivateRec(ptraceaccess,&te->conStderr); if(SoDispCon_dispatcherHasCon(&te->conStderr)) SoDisp_removeConnection(ptraceaccess,&te->conStderr); } } static void earlyserial(ForkPTY* te, ThreadMutex* m) { if(te->pty >= 0) { int pty=te->pty; te->pty=-1; flashprobe(te); te->busy=TRUE; ThreadMutex_release(m); kill(te->pid, SIGKILL); close(pty); close(te->pipefd[0]); ThreadMutex_set(m); te->busy=FALSE; if(te->Lt) luaL_unref(te->Lt, LUA_REGISTRYINDEX, te->ref); } waitpid(-1, NULL, WNOHANG); } static int startuplevel(lua_State* L) { ForkPTY* te = checkForkPTY(L); if(!te) return 2; if(L == te->Lt) { return lua_yield(L, 0); } else { luaL_Buffer lb; struct timeval tv; fd_set socketSet; char* buf; int n,isStdErr; ThreadMutex* m = getSoDispMutex(L); if((lua_isboolean(L,2) && lua_toboolean(L, 2))) { tv.tv_sec = LONG_MAX; tv.tv_usec = 0; } else if(lua_isnumber(L,2)) { n = lua_tointeger(L, 2); tv.tv_sec = n / 1000; tv.tv_usec = (n % 1000) * 1000; } else { tv.tv_sec = 0; tv.tv_usec = 0; } int clkctrlproviders = (te->pty > te->pipefd[0] ? te->pty : te->pipefd[0])+1; if(clkctrlproviders >= FD_SETSIZE) { return lDoErr(L,"\104\145\163\143\040\076\040\106\104\137\123\105\124\123\111\132\105"); } FD_ZERO(&socketSet); FD_SET(te->pty, &socketSet); FD_SET(te->pipefd[0], &socketSet); te->busy=TRUE; ThreadMutex_release(m); n = select(clkctrlproviders, &socketSet, 0, 0, &tv); ThreadMutex_set(m); te->busy=FALSE; if(n<0) return alloccipher(L,te); if(n==0) { L_ret: lua_pushnil(L); return 1; } if(FD_ISSET(te->pty, &socketSet)) { n = te->pty; isStdErr=FALSE; } else if(FD_ISSET(te->pipefd[0], &socketSet)) { n = te->pipefd[0]; isStdErr=TRUE; } else goto L_ret; luaL_buffinit(L, &lb); buf = luaL_prepbuffer(&lb); te->busy=TRUE; ThreadMutex_release(m); n = read(n, buf, LUAL_BUFFERSIZE); ThreadMutex_set(m); te->busy=FALSE; if(n < 0) return alloccipher(L,te); if(n==0) goto L_ret; luaL_addsize(&lb, n); luaL_pushresult(&lb); lua_pushboolean(L, isStdErr); return 2; } } static void aa64mmfr1override(ForkPTY* te, int pty) { int sffsdrnandflash,n,err=FALSE; lua_State* L=te->Lt; if(lua_status(L) == LUA_YIELD) { luaL_Buffer lb; luaL_buffinit(L, &lb); n = read(pty,luaL_prepbuffer(&lb), LUAL_BUFFERSIZE); if(n < 0) { n=alloccipher(L,te); err=TRUE; } else { luaL_addsize(&lb, n); luaL_pushresult(&lb); lua_pushboolean(L, te->pipefd[0] == pty); n=2; } sffsdrnandflash = lua_resume(L, 0, n, &n); } else sffsdrnandflash = lua_resume(L, 0, 1, &n); if(sffsdrnandflash == LUA_YIELD) { lua_settop(L, 0); if(err) flashprobe(te); } else { if(sffsdrnandflash == 0) flashprobe(te); else { earlyserial(te, getSoDispMutex(L)); balua_resumeerr(L,"\146\157\162\153\160\164\171"); } } } static void deviceselect(SoDispCon* con) { aa64mmfr1override((ForkPTY*)con, ((ForkPTY*)con)->pty); } static void fixupradeon(SoDispCon* con) { ForkPTY* te = (ForkPTY*)((U8*)con-offsetof(ForkPTY,conStderr)); aa64mmfr1override(te, te->pipefd[0]); } static int gpregswriteback(lua_State* L) { int sffsdrnandflash; size_t dLen; ForkPTY* te = checkForkPTY(L); const char* alloccontroller = luaL_checklstring(L, 2, &dLen); ThreadMutex* m = getSoDispMutex(L); if(!te) return 2; te->busy=TRUE; ThreadMutex_release(m); sffsdrnandflash = write(te->pty, alloccontroller, dLen); ThreadMutex_set(m); te->busy=FALSE; if(sffsdrnandflash < 0) return alloccipher(L,te); lua_pushboolean(L, TRUE); return 1; } static int suspendbegin(lua_State* L) { int ret=0; ForkPTY* te = checkForkPTYOnExit(L, &ret); if(te) { int ex; ret=1; lua_pushboolean(L, TRUE); if(te->hasExitCode) ret += consoledriver(L, te->exitCode); else if(waitpid(te->pid, &ex, WNOHANG) > 0) { te->exitCode = te->hasExitCode ? te->exitCode : ex; te->hasExitCode=TRUE; ret += consoledriver(L, te->exitCode); } earlyserial(te, getSoDispMutex(L)); } return ret; } static int probeguestctl1(lua_State* L) { ForkPTY* te = checkForkPTY(L); int mcasp2device=lua_toboolean(L, 2); if(!te) return 2; kill(te->pid, mcasp2device ? SIGSTOP : SIGCONT); if(te->Lt) { SoDisp* ptraceaccess = SoDispCon_getDispatcher((SoDispCon*)te); if(mcasp2device) { if(SoDispCon_recEvActive((SoDispCon*)te)) SoDisp_deactivateRec(ptraceaccess,(SoDispCon*)te); if(SoDispCon_recEvActive(&te->conStderr)) SoDisp_deactivateRec(ptraceaccess,&te->conStderr); } else { if( ! SoDispCon_recEvActive((SoDispCon*)te) ) SoDisp_activateRec(ptraceaccess,(SoDispCon*)te); if( ! SoDispCon_recEvActive(&te->conStderr) ) SoDisp_activateRec(ptraceaccess,&te->conStderr); } } lua_pushboolean(L, TRUE); return 1; } static int gpio1hwmod(lua_State* L) { int sha512final=FALSE; int writecommand = (int)luaL_checkinteger(L, 2); int defaultscope = (int)luaL_checkinteger(L, 3); ForkPTY* te = checkForkPTY(L); if(!te) return 2; { #ifdef TIOCGSIZE struct ttysize tts; tts.ts_lines = writecommand; tts.ts_cols = defaultscope; if(ioctl(te->pty, TIOCGSIZE, &tts)) sha512final=TRUE; #else struct winsize ws; if(ioctl(te->pty, TIOCGWINSZ, &ws)) sha512final=TRUE; else { ws.ws_row = writecommand; ws.ws_col = defaultscope; if(ioctl(te->pty, TIOCSWINSZ, & ws)) sha512final=TRUE; } #endif } if(sha512final) { lua_pushnil(L); lua_pushstring(L, strerror(errno)); return 2; } lua_pushboolean(L, TRUE); return 1; } static int clockunstable(lua_State* L) { ThreadMutex* m; int ret=0; ForkPTY* te = checkForkPTYOnExit(L, &ret); if(te) { if(te->hasExitCode) ret = consoledriver(L, te->exitCode); else { int n,ex,enablechannel; enablechannel = !te->Lt && lua_isboolean(L,2) && lua_toboolean(L, 2) ? 0 : WNOHANG; te->busy=TRUE; m = getSoDispMutex(L); ThreadMutex_release(m); if( ! te->sigint ) { kill(te->pid, SIGINT); te->sigint=TRUE; } n = waitpid(te->pid, &ex, enablechannel); ThreadMutex_set(m); te->busy=FALSE; if(n < 0) ret = suspendbegin(L); else if(n == 0) { ret = 1; lua_pushinteger(L,-1); } else { te->hasExitCode = TRUE; te->exitCode=ex; ret = consoledriver(L, ex); } } if(te->hasExitCode) earlyserial(te, getSoDispMutex(L)); } return ret; } static const luaL_Reg forkptyLib[] = { {"\162\145\141\144", startuplevel}, {"\167\162\151\164\145", gpregswriteback}, {"\160\141\165\163\145", probeguestctl1}, {"\167\151\156\163\151\172\145", gpio1hwmod}, {"\143\154\157\163\145", clockunstable}, {"\137\137\143\154\157\163\145", clockunstable}, {"\164\145\162\155\151\156\141\164\145", suspendbegin}, {"\137\137\147\143", suspendbegin}, {NULL, NULL} }; static int receivechars(lua_State* L, char* stateswitch, int* pty) { *pty = zzgetpt(); if (*pty < 0 || grantpt(*pty) < 0 || unlockpt(*pty) < 0) return lDoErr(L,"\103\141\156\156\157\164\040\157\160\145\156\040\120\124\131\072\040\045\163",strerror(errno)); #ifdef BA_QNX if( ! baptsname_r(*pty, stateswitch, PTY_NAME_SIZE-1) ) #else if(baptsname_r(*pty, stateswitch, PTY_NAME_SIZE-1)) #endif { return lDoErr(L,"\160\164\163\156\141\155\145\137\162\072\040\045\163",strerror(errno)); } return 0; } static int cryptoenable(const char* stateswitch, const char* errorhandler) { struct termios termbuf; int fd=open(stateswitch, O_RDWR); if(fd < 0) doClientError("\157\160\145\156\040\045\163\072\040\045\163",stateswitch, strerror(errno)); tcsetpgrp(fd, getpid()); #if defined(TIOCSCTTY) ioctl(fd,TIOCSCTTY,NULL); #endif tcgetattr(fd, &termbuf); if(errorhandler && !strcmp("\163\141\156\145", errorhandler)) { termbuf.c_cflag = TTYDEF_CFLAG; termbuf.c_iflag = TTYDEF_IFLAG; termbuf.c_lflag = TTYDEF_LFLAG; termbuf.c_oflag = TTYDEF_OFLAG; } else { cfmakeraw(&termbuf); } tcsetattr(fd, TCSANOW, &termbuf); return fd; } static int boardstore(lua_State* L) { char stateswitch[PTY_NAME_SIZE]; int i,n,icachealiases,ret,funcIx,doublefsito; const char* cmd; const char** cmdArgv; char** env=0; const char* errorhandler=0; ForkPTY* te; waitpid(-1, NULL, WNOHANG); n = lua_type(L, 1); n = LUA_TTABLE == n || LUA_TFUNCTION == n ? 2 : 1; cmd = luaL_checkstring(L, n); icachealiases=lua_gettop(L); cmdArgv = (const char**)lua_newuserdata(L,sizeof(char*)*(icachealiases+1)); te = (ForkPTY*)lua_newuserdata(L, sizeof(ForkPTY)); doublefsito = lua_gettop(L); memset(te, 0 , sizeof(ForkPTY)); te->exitCode=-1; cmdArgv[0] = cmd; for(i=1 ; i <= (icachealiases-n) ; i++) cmdArgv[i] = luaL_checkstring(L, i+n); cmdArgv[i]=NULL; if(n == 2) { if(LUA_TTABLE == lua_type(L, 1)) { cmdArgv[0] = balua_getStringField(L, 1, "\141\162\147\060",cmd); errorhandler = balua_getStringField(L, 1, "\163\164\164\171",0); lua_getfield(L, 1, "\141\163\171\156\143"); if( LUA_TFUNCTION == lua_type(L, -1)) funcIx = lua_gettop(L); else { funcIx=0; lua_pop(L, 1); } lua_getfield(L, 1, "\145\156\166"); if(LUA_TTABLE == lua_type(L, -1)) { i=0; icachealiases=0; lua_pushnil(L); while(lua_next(L, -2) != 0) { i++; icachealiases+=strlen(luaL_checkstring(L,-2))+ strlen(luaL_checkstring(L,-1)); lua_pop(L, 1); } if(i > 0) { char* ptr; env = (char**)lua_newuserdata(L,sizeof(char*)*(i+2)+icachealiases+i*3); ptr = (char*)env + sizeof(char*)*(i+2); i=0; lua_pushnil(L); while(lua_next(L, -3) != 0) { basprintf(ptr,"\045\163\075\045\163",luaL_checkstring(L,-2), luaL_checkstring(L,-1)); env[i]=ptr; ptr+=strlen(ptr)+1; i++; lua_pop(L, 1); } env[i]=0; } } lua_pop(L,1); } else funcIx=1; } else funcIx=0; if( (ret = receivechars(L, stateswitch, &te->pty)) != 0 || (ret = pipe(te->pipefd)) != 0 ) { return ret; } if ((te->pid = zzbafork()) < 0) return lDoErr(L,"\146\157\162\153\072\040\045\163",strerror(errno)); if(te->pid == 0) { int fd; close(0); close(1); close(2); close(te->pty);close(te->pipefd[0]); if(setsid() < 0) doClientError("\163\145\164\163\151\144\072\040\045\163",strerror(errno)); fd=cryptoenable(stateswitch, errorhandler); if(dup2(fd, STDIN_FILENO) != STDIN_FILENO) doClientError(efmt,"\163\164\144\151\156"); if(dup2(fd, STDOUT_FILENO) != STDOUT_FILENO) doClientError(efmt,"\163\164\144\157\165\164"); if(dup2(te->pipefd[1], STDERR_FILENO) != STDERR_FILENO) doClientError(efmt,"\163\164\144\145\162\162"); close(te->pipefd[0]); execve(cmd, (char**)cmdArgv, env); fprintf(stderr, "\105\170\145\143\165\164\151\156\147\040\045\163\040\146\141\151\154\145\144\072\040\045\163",cmd,strerror(errno)); exit(errno); } if(luaL_newmetatable(L, BAFORKPTY)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,forkptyLib,0); } lua_setmetatable(L, doublefsito); if(funcIx) { SoDisp* ptraceaccess; lua_createtable(L, 2, 0); lua_pushvalue(L, funcIx); lua_rawseti(L, -2, 1); te->Lt=lua_newthread(L); lua_rawseti(L, -2, 2); lua_setuservalue(L, doublefsito); lua_pushvalue(L, funcIx); lua_pushvalue(L, doublefsito); lua_xmove(L, te->Lt, 2); lua_pushvalue(L, doublefsito); te->ref = luaL_ref(L, LUA_REGISTRYINDEX); ptraceaccess = HttpServer_getDispatcher(balua_getparam(L)->server); pollingenabled((SoDispCon*)te, ptraceaccess, deviceselect, te->pty); pollingenabled(&te->conStderr, ptraceaccess, fixupradeon, te->pipefd[0]); close(te->pipefd[1]); deviceselect((SoDispCon*)te); } else te->Lt=0; lua_pushvalue(L, doublefsito); return 1; } static const luaL_Reg forkPtyLib[] = { #if 0 {"\160\157\160\145\156", lBaPopen}, #endif {"\146\157\162\153\160\164\171", boardstore}, {NULL, NULL} }; void balua_forkpty(lua_State* L) { lua_getglobal(L, "\142\141"); luaL_setfuncs(L,forkPtyLib,0); lua_pop(L,1); } #endif #endif #if USE_REDIRECTOR == 1 #if !defined(USE_AMALGAMATED_BAS) || defined(BAS_LOADED) #include #include #include #include static DoubleList httpRedirectNodeList; typedef struct { char* domainName; char* path; U16 port; } DecodeUrl; static void deviceshutdown(DecodeUrl* o, const char* url, HttpCommand* cmd) { const char* ptr = url; memset(o, 0, sizeof(DecodeUrl)); o->domainName = baStrdup(ptr); if(o->domainName) { char* ptr; if((ptr = strchr(o->domainName, '\072')) != 0) { char* fsyscalltable = ptr+1; *ptr=0; if( (ptr = strchr(fsyscalltable, '\057')) != 0) *ptr++=0; else ptr=fsyscalltable+strlen(fsyscalltable); o->port = (U16)U32_atoi(fsyscalltable); } else { o->port = 80; if((ptr = strchr(o->domainName, '\057')) != 0) { *ptr++=0; } else { ptr = o->domainName+strlen(o->domainName); } } o->path=ptr; return; } HttpResponse_sendError1(&cmd->response,503); return; } static void blockinner( DecodeUrl* o,const char* sanitiseinner, const char* uprobeexception, short hwmoddeassert) { o->domainName=baStrdup(sanitiseinner); o->path=baStrdup(uprobeexception); o->port=hwmoddeassert; } static void cachealloc(DecodeUrl* o) { if(o->domainName) baFree(o->domainName); } typedef struct { DoubleLink super; SoDispCon cCon; /* connection to destination server */ SoDispCon* sCon; /* Server connection */ SoDispCon_DispRecEv sConDispEv; /* The overloaded server callback */ char* domainName; int* isTerminatedPtr; } HttpRedirectNode; #define HttpRedirectNode_sendData(o,alloccontroller,len) \ SoDispCon_sendData(&(o)->cCon, alloccontroller,len) static void panelindex(HttpRedirectNode* o, SoDispCon* arria10restart); static void unmapgrant(HttpRedirectNode* o); static int smc91xdevice( HttpRedirectNode* o,DecodeUrl* sramcsubsys, HttpCommand* cmd); static void applystate(SoDispCon* con); static void l2c310write(SoDispCon* con); static HttpRedirectNode* HttpRedirectNode_find(SoDispCon* con) { DoubleListEnumerator e; HttpRedirectNode* pn; DoubleListEnumerator_constructor(&e,&httpRedirectNodeList); for(pn = (HttpRedirectNode*)DoubleListEnumerator_getElement(&e) ; pn ; pn = (HttpRedirectNode*)DoubleListEnumerator_nextElement(&e)) { if(con == pn->sCon) { return pn; } } return 0; } static HttpRedirectNode* HttpRedirectNode_create(HttpCommand* cmd,DecodeUrl* sramcsubsys) { HttpRedirectNode* pn = HttpRedirectNode_find((SoDispCon*)cmd->con); if(pn) { if( ! pn->domainName || strcmp(pn->domainName, sramcsubsys->domainName) ) { if(pn->domainName) baFree(pn->domainName); pn->domainName=0; SoDispCon_closeCon(&pn->cCon); goto L_connect; } } if(!pn) { pn = baMalloc(sizeof(HttpRedirectNode)); if(pn) { panelindex(pn,(SoDispCon*)cmd->con); L_connect: if(smc91xdevice(pn,sramcsubsys,cmd)) { unmapgrant(pn); baFree(pn); pn = 0; } } } return pn; } static void panelindex(HttpRedirectNode* o, SoDispCon* arria10restart) { DoubleLink_constructor((DoubleLink*)o); SoDispCon_constructor(&o->cCon, SoDispCon_getDispatcher(arria10restart), applystate); o->sCon = arria10restart; o->sConDispEv = arria10restart->dispRecEv; o->sCon->dispRecEv = l2c310write; DoubleList_insertLast(&httpRedirectNodeList,o); o->domainName=0; o->isTerminatedPtr=0; } static int smc91xdevice(HttpRedirectNode* o,DecodeUrl* sramcsubsys, HttpCommand* cmd) { const char* dn = sramcsubsys->domainName; int sffsdrnandflash; if(!dn) return -4; sffsdrnandflash = SoDispCon_connect(&o->cCon, dn, sramcsubsys->port,0,0,1500,FALSE, FALSE,0); if(sffsdrnandflash) { switch(sffsdrnandflash) { case E_CANNOT_RESOLVE: HttpResponse_fmtError( &cmd->response, 404,"\122\145\144\151\162\145\143\164\157\162\072\040\103\141\156\156\157\164\040\162\145\163\157\154\166\145\040\144\157\155\141\151\156\040\156\141\155\145\040\042\045\163\042",dn); break; default: HttpResponse_fmtError( &cmd->response, 404,"\122\145\144\151\162\145\143\164\157\162\072\040\103\141\156\156\157\164\040\143\157\156\156\145\143\164\040\164\157\040\042\045\163\072\045\144\042", dn,(int)sramcsubsys->port); } } else { o->domainName = baStrdup(dn); SoDisp_activateRec(SoDispCon_getDispatcher(&o->cCon),&o->cCon); } return sffsdrnandflash; } static void unmapgrant(HttpRedirectNode* o) { SoDispCon_destructor(&o->cCon); if(o->domainName) baFree(o->domainName); DoubleLink_unlink((DoubleLink*)o); o->sCon->dispRecEv = o->sConDispEv; if(o->isTerminatedPtr) *o->isTerminatedPtr=TRUE; } static void applystate(SoDispCon* con) { char buf[1500]; SoDispCon* arria10restart; HttpRedirectNode* o = (HttpRedirectNode*)((U8*)con-offsetof(HttpRedirectNode,cCon)); int len = SoDispCon_readData(&o->cCon, buf, sizeof(buf), FALSE); if(len > 0) { if( ! HttpConnection_sendData(o->sCon, buf, len) ) return; } arria10restart = o->sCon; unmapgrant(o); baFree(o); if(SoDispCon_isValid(arria10restart)) SoDispCon_closeCon(arria10restart); SoDispCon_setDispHasRecData(arria10restart); arria10restart->dispRecEv(arria10restart); } static void l2c310write(SoDispCon* con) { HttpRedirectNode* pn = HttpRedirectNode_find(con); if(pn) { int queueevent=FALSE; pn->isTerminatedPtr = &queueevent; pn->sConDispEv(con); if( ! SoDispCon_isValid(con) ) { if( ! queueevent ) { unmapgrant(pn); baFree(pn); } } else pn->isTerminatedPtr=0; return; } baAssert(0); } typedef struct { HttpDir super; DecodeUrl* destination; } HttpRedirect; static int systemstrings( HttpDir* fdc37m81xconfig,const char* driverregister,HttpCommand* cmd); static int cpuidlesuspend( HttpDir* fdc37m81xconfig,const char* driverregister, HttpCommand* cmd); static void simulatebranch(HttpRedirect* o,const char* soundtimer,int reservevmcore) { HttpDir_constructor((HttpDir*)o, soundtimer,(U8)reservevmcore); o->destination=0; HttpDir_setService((HttpDir*)o,systemstrings); } static void t7l66xbdevice(HttpRedirect* o,const char* soundtimer, const char* sanitiseinner, short hwmoddeassert, const char* uprobeexception,int reservevmcore) { const char* poweroffrequired; char* ptr; HttpDir_constructor((HttpDir*)o, soundtimer,(U8)reservevmcore); if(uprobeexception && *uprobeexception == '\057') uprobeexception++; if(uprobeexception && uprobeexception[0] && ( ! (poweroffrequired = strrchr(uprobeexception,'\057')) || poweroffrequired[1])) { int len = iStrlen(uprobeexception)+2; ptr = (char*)baMalloc(len); if(ptr) { basnprintf(ptr,len,"\045\163\057",uprobeexception); uprobeexception=ptr; } } else ptr=0; o->destination = (DecodeUrl*)baMalloc(sizeof(DecodeUrl)); if(o->destination) blockinner(o->destination, sanitiseinner, uprobeexception, hwmoddeassert); if(ptr) baFree(ptr); HttpDir_setService((HttpDir*)o,cpuidlesuspend); } static void esdhcresources(HttpRedirect* o) { if(o->destination) { cachealloc(o->destination); baFree(o->destination); o->destination=0; } HttpDir_destructor((HttpDir*)o); } static void tc6393xbsetup(HttpRequest* req, const char* quirkscheck, BufPrint* hb) { int len,i; HttpHeader* hIter = HttpRequest_getHeaders(req,&len); for(i = 0 ; i < len ; i++, hIter++) { const char* hn = HttpHeader_name(hIter,req); if( ( (hn[0] == '\105' || hn[0] == '\145') && ! baStrCaseCmp("\105\124\141\147", hn) ) || ( (hn[0] == '\114' || hn[0] == '\154') && ! baStrCaseCmp("\114\141\163\164\055\115\157\144\151\146\151\145\144", hn) ) || ( (hn[0] == '\122' || hn[0] == '\162') && ! baStrCaseCmp("\122\145\146\145\162\145\162", hn) ) || ( (hn[0] == '\110' || hn[0] == '\150') && ! baStrCaseCmp("\110\157\163\164", hn) ) || ( (hn[8] == '\154' || hn[8] == '\114') && ! baStrCaseCmp("\143\157\156\164\145\156\164\055\154\145\156\147\164\150", hn) ) ) { continue; } BufPrint_printf(hb,"\045\163\072\040\045\163\015\012",hn,HttpHeader_value(hIter,req)); } BufPrint_printf(hb,"\110\157\163\164\072\040\045\163\015\012\122\145\146\145\162\145\162\072\045\163\015\012", quirkscheck, quirkscheck); } static void deviceenable(HttpRequest* req, DynBuffer* buf, int tdo24mtea1modes) { HttpParameterIterator pi; HttpParameterIterator_constructor(&pi,req); if(HttpParameterIterator_hasMoreElements(&pi)) { if(tdo24mtea1modes) BufPrint_putc((BufPrint*)buf,'\077'); for(;;) { char* ptr; const char* n = HttpParameterIterator_getName(&pi); const char* v = HttpParameterIterator_getValue(&pi); if(DynBuffer_expand(buf,2+3*(iStrlen(n)+iStrlen(v)))) break; ptr = DynBuffer_getCurPtr(buf); DynBuffer_incrementCursor(buf,(int)(httpEscape(ptr, n) - ptr)); BufPrint_putc((BufPrint*)buf,'\075'); ptr = DynBuffer_getCurPtr(buf); DynBuffer_incrementCursor(buf,(int)(httpEscape(ptr, v) - ptr)); HttpParameterIterator_nextElement(&pi); if( ! HttpParameterIterator_hasMoreElements(&pi) ) break; BufPrint_putc((BufPrint*)buf,'\046'); } } } static void inputkeyboard(HttpRequest* req, const char* driverstate, DynBuffer* buf) { char* ptr; BufPrint_printf((BufPrint*)buf,"\045\163\040\057",HttpRequest_getMethod(req)); if(DynBuffer_expand(buf,3 * iStrlen(driverstate) )) return; ptr = DynBuffer_getCurPtr(buf); DynBuffer_incrementCursor(buf,(int)(httpEscape(ptr, driverstate) - ptr)); } static void pernodespace(HttpRedirect* o, HttpCommand* cmd, HttpRedirectNode* pn, const char* quirkscheck, const char* driverstate) { DynBuffer hb; int sffsdrnandflash=0; HttpStdHeaders* stdH = HttpRequest_getStdHeaders(&cmd->request); S32 disabletraps = (S32)HttpStdHeaders_getContentLength(stdH); const char* modulefunction = HttpStdHeaders_getContentType(stdH); (void)o; if(modulefunction && disabletraps <= 0) { HttpMethod m = HttpRequest_getMethodType(&cmd->request); switch(m) { case HttpMethod_Get: case HttpMethod_Head: case HttpMethod_Delete: disabletraps=0; break; default: HttpResponse_sendError2(&cmd->response,411, "\122\145\144\151\162\145\143\164\157\162\040\162\145\161\165\151\162\145\163\040\143\157\156\164\145\156\164\040\154\145\156\147\164\150"); return; } } DynBuffer_constructor(&hb, 3*1024, 2*1024, 0, 0); if(disabletraps) { inputkeyboard(&cmd->request, driverstate, &hb); BufPrint_printf((BufPrint*)&hb,"\040\110\124\124\120\057\061\056\061\015\012", HttpRequest_getMethod(&cmd->request), driverstate); tc6393xbsetup(&cmd->request, quirkscheck, (BufPrint*)&hb); if(modulefunction && !baStrnCaseCmp(modulefunction,"\141\160\160\154\151\143\141\164\151\157\156\057\170\055\167\167\167\055\146\157\162\155\055\165\162\154\145\156\143\157\144\145\144",33)) { DynBuffer urlBuf; DynBuffer_constructor(&urlBuf,disabletraps+1024, 1024, 0, 0); deviceenable(&cmd->request, &urlBuf,FALSE); BufPrint_printf((BufPrint*)&hb,"\143\157\156\164\145\156\164\055\154\145\156\147\164\150\072\040\045\144\015\012\015\012", (int)DynBuffer_getBufSize(&urlBuf)); { sffsdrnandflash = HttpRedirectNode_sendData( pn,DynBuffer_getBuf(&hb),DynBuffer_getBufSize(&hb)); if(!sffsdrnandflash) { sffsdrnandflash = HttpRedirectNode_sendData( pn,DynBuffer_getBuf(&urlBuf),DynBuffer_getBufSize(&urlBuf)); } } DynBuffer_destructor(&urlBuf); } else { BufPrint_printf((BufPrint*)&hb,"\143\157\156\164\145\156\164\055\154\145\156\147\164\150\072\040\045\144\015\012\015\012", disabletraps); { sffsdrnandflash = HttpRedirectNode_sendData( pn,DynBuffer_getBuf(&hb),DynBuffer_getBufSize(&hb)); } if(!sffsdrnandflash) { HttpInData* in = HttpRequest_getBuffer(&cmd->request); S32 lsdc2format=HttpInData_getBufSize(in); char* buf = (char*)HttpInData_getBuf(in); if(lsdc2format >= disabletraps) { sffsdrnandflash = HttpRedirectNode_sendData(pn,buf, disabletraps); } else { HttpRequest_enableKeepAlive(&cmd->request); in->allocator.index=0; if(lsdc2format) sffsdrnandflash = HttpRedirectNode_sendData(pn,buf, lsdc2format); if(!sffsdrnandflash) { HttpConnection* con; disabletraps -= lsdc2format; buf = cmd->response.bodyPrint->buf; lsdc2format = cmd->response.bodyPrint->bufSize; con=HttpRequest_getConnection(&cmd->request); if(HttpConnection_recEvActive(con)) { SoDisp_deactivateRec( HttpConnection_getDispatcher(con), (SoDispCon*)con); } while(disabletraps && !sffsdrnandflash) { S32 unalignedcheck = disabletraps > lsdc2format ? lsdc2format : disabletraps; S32 decodetable = HttpConnection_blockRead(con,buf,unalignedcheck); if(decodetable > 0) { disabletraps -= decodetable; sffsdrnandflash = HttpRedirectNode_sendData(pn,buf, decodetable); } else sffsdrnandflash=-1; } } } } } } else { inputkeyboard(&cmd->request, driverstate, &hb); deviceenable(&cmd->request, &hb, TRUE); BufPrint_write((BufPrint*)&hb,"\040\110\124\124\120\057\061\056\061\015\012",-1); tc6393xbsetup(&cmd->request, quirkscheck, (BufPrint*)&hb); BufPrint_write((BufPrint*)&hb,"\015\012",-1); { sffsdrnandflash = HttpRedirectNode_sendData( pn,DynBuffer_getBuf(&hb),DynBuffer_getBufSize(&hb)); } } if(sffsdrnandflash) { HttpResponse_printf( &cmd->response,"\123\145\156\144\151\156\147\040\144\141\164\141\040\164\157\040\144\145\163\164\151\156\141\164\151\157\156\040\163\145\162\166\145\162\040\146\141\151\154\145\144\012"); HttpResponse_sendBufAsError(&cmd->response,504); pn = HttpRedirectNode_find((SoDispCon*)cmd->con); if(pn) { unmapgrant(pn); baFree(pn); } } else { cmd->response.headerSent=TRUE; } DynBuffer_destructor(&hb); } static int systemstrings(HttpDir* fdc37m81xconfig,const char* driverregister,HttpCommand* cmd) { DecodeUrl sramcsubsys; int sleepau1550=TRUE; HttpRedirect* o = (HttpRedirect*)fdc37m81xconfig; if( !cmd ) { HttpDir_destructor(fdc37m81xconfig); return 0; } if(!HttpResponse_initial(&cmd->response)) return -1; deviceshutdown(&sramcsubsys,driverregister,cmd); if(sramcsubsys.domainName) { HttpRedirectNode* pn; if(fdc37m81xconfig->authenticator) { int icachealiases = iStrlen(sramcsubsys.domainName) + iStrlen(driverregister) + 2; char* deviceremove = (char*)baMalloc(icachealiases); sleepau1550=FALSE; if(deviceremove) { basnprintf(deviceremove, icachealiases, "\045\163\057\045\163", sramcsubsys.domainName, driverregister); sleepau1550 = HttpDir_authenticateAndAuthorize(fdc37m81xconfig, cmd, deviceremove); baFree(deviceremove); } } if(sleepau1550) { pn = HttpRedirectNode_create(cmd, &sramcsubsys); if(pn) pernodespace(o, cmd, pn, sramcsubsys.domainName, sramcsubsys.path); } } cachealloc(&sramcsubsys); return 0; } static int cpuidlesuspend(HttpDir* fdc37m81xconfig,const char* driverregister, HttpCommand* cmd) { char* uri=0; int handlersetup=-1; HttpRedirect* o = (HttpRedirect*)fdc37m81xconfig; if( !cmd ) { HttpDir_destructor(fdc37m81xconfig); return 0; } if(!HttpResponse_initial(&cmd->response)) return -1; baAssert(o->destination); if(o->destination->path) { if(*driverregister) { int len = iStrlen(o->destination->path) + iStrlen(driverregister) + 1; uri=(char*)baMalloc(len); if(uri) { basnprintf(uri,len,"\045\163\045\163", o->destination->path, driverregister); driverregister=uri; } } else driverregister = o->destination->path; } if(HttpDir_authenticateAndAuthorize(fdc37m81xconfig, cmd, driverregister)) { HttpRedirectNode* pn = HttpRedirectNode_create(cmd, o->destination); if(pn) { pernodespace(o,cmd,pn,o->destination->domainName,driverregister); handlersetup=0; } } else handlersetup = 0; if(uri) baFree(uri); return handlersetup; } static int cminstxlate(lua_State *L) { HttpRedirect* rdir; const char* gpio1config; U16 hwmoddeassert=0; const char* timerreadl=0; const char* sanitiseinner=0; int reservevmcore=0; int top=lua_gettop(L); gpio1config = lua_isnil(L,1) ? 0 : luaL_checkstring(L,1); if(top < 3) reservevmcore=(int)luaL_optinteger(L,2,0); else { sanitiseinner=luaL_checkstring(L,2); hwmoddeassert=(U16)luaL_checkinteger(L,3); if(top > 4) { timerreadl=luaL_checkstring(L,4); reservevmcore=(int)lua_tointeger(L,5); } else if(lua_type(L,4) == LUA_TSTRING) timerreadl=lua_tostring(L,4); else reservevmcore=(int)luaL_optinteger(L,4,0); } if(gpio1config) { char* selecttable; rdir=(HttpRedirect*)baluaENV_createDir( L,BA_TDIR_REDIRECTOR,sizeof(HttpRedirect)+strlen(gpio1config)+1); selecttable = (char*)(rdir+1); strcpy(selecttable, gpio1config); gpio1config=selecttable; } else { rdir=(HttpRedirect*)baluaENV_createDir( L,BA_TDIR_REDIRECTOR,sizeof(HttpRedirect)); } if(top < 3) simulatebranch(rdir,gpio1config,reservevmcore); else t7l66xbdevice(rdir, gpio1config, sanitiseinner, hwmoddeassert, timerreadl,reservevmcore); return 1; } static int hwmodreset(lua_State *L) { HttpRedirect* rdir = (HttpRedirect*)(((LHttpDir*)baluaENV_checkudata( L,1,BA_TDIR_REDIRECTOR))+1); esdhcresources(rdir); return 0; } static int tbclksyncdevice(lua_State *L) { static const luaL_Reg lib[] = { {"\137\137\147\143", hwmodreset}, {NULL, NULL} }; baluaENV_register(L,BA_TDIR_REDIRECTOR,BA_TDIR,lib); return 0; } void luaopen_ba_redirector(lua_State *L); void luaopen_ba_redirector(lua_State *L) { static const luaL_Reg lib[] = { {"\162\145\144\151\162\145\143\164\157\162", cminstxlate}, {NULL, NULL} }; int top,sffsdrnandflash; DoubleList_constructor(&httpRedirectNodeList); top=lua_gettop(L); balua_pushbatab(L); lua_pushcclosure(L, tbclksyncdevice, 1); sffsdrnandflash=lua_pcall(L,0,0,0); if(sffsdrnandflash) baFatalE(FE_BLUA_PANIC, sffsdrnandflash); lua_getglobal(L, "\142\141"); lua_getfield(L, -1, "\143\162\145\141\164\145"); baAssert(lua_type(L,-1) == LUA_TTABLE); balua_pushbatab(L); luaL_setfuncs(L,lib,1); lua_settop(L,top); } #endif #endif #if USE_UBJSON == 1 #include "ubjson.h" #include typedef enum { UBJLxT_NeedMoreData=1, UBJLxT_Err, UBJLxT_MemberName, UBJLxT_Val, UBJLxT_BeginArray, UBJLxT_EndArray, UBJLxT_BeginObject, UBJLxT_EndObject, UBJLxT_Count } UBJLxT; typedef enum { UBJLxState_GetNextToken=1, UBJLxState_ReadData, UBJLxState_GetType, UBJLxState_ReadMemberName } UBJLxState; typedef enum { UBJPState_Init, UBJPState_Running, } UBJPState; #ifndef B_BIG_ENDIAN static void allocrange(U8* ptr, int icachealiases) { while(--icachealiases >= 0) { U8 doublefnmul = *ptr; *ptr = ptr[icachealiases]; ptr++; ptr[--icachealiases] = doublefnmul; } } #else #define allocrange(ptr, icachealiases) #endif void UBJVal_setMinInteger(UBJVal* o, S64 in) { U64 v = (U64)(in > 0 ? in : -in); if (v < 0x80) { o->u.int8 = (S8)in; o->t = UBJT_Int8; } else if (v < 0x8000) { o->u.int16 = (S16)in; o->t = UBJT_Int16; } else if (v < 0x80000000) { o->u.int32 = (S32)in; o->t = UBJT_Int32; } else { o->u.int64 = in; o->t = UBJT_Int64; } } static int kuserhelpers(UBJParser* o, UBJPStatus s, int handlersetup) { o->status = (U8)s; if(handlersetup) { o->stackIx=0; o->lxState = UBJLxState_GetNextToken; o->pState = UBJPState_Init; o->lxParseX=0; *o->val.name = 0; } return handlersetup; } static int activationnotify(UBJParser* o) { UBJVal* val=&o->val; switch(val->t) { case UBJT_Int8: o->lxBytes2Read = (S32)val->u.int8; break; case UBJT_Int16: o->lxBytes2Read = (S32)val->u.int16; break; case UBJT_Int32: o->lxBytes2Read = val->u.int32; if(o->lxBytes2Read >= 0) break; case UBJT_Int64: return kuserhelpers(o,UBJPStatus_Overflow,-1); default: kuserhelpers(o,UBJPStatus_ParseErr,-1); } return 0; } static S32 devicehwuart(UBJParser* o, U8 allocsimple) { UBJVal* val = &o->val; switch(allocsimple) { case '\132': val->t = UBJT_Null; return 0; case '\116': val->t = UBJT_NoOp; return 0; case '\106': case '\124': val->t = UBJT_Boolean; val->u.uint8 = allocsimple=='\124'; return 0; case '\151': case '\125': case '\103': val->t = allocsimple=='\151' ? UBJT_Int8 : (allocsimple=='\125' ? UBJT_Uint8 : UBJT_Char); return 1; case '\111': val->t = UBJT_Int16; return 2; case '\154': case '\144': val->t = allocsimple=='\154' ? UBJT_Int32 : UBJT_Float32; return 4; case '\114': case '\104': val->t = allocsimple=='\114' ? UBJT_Int64 : UBJT_Float64; return 8; break; case '\123': val->t = UBJT_String; return 0; case '\110': val->t = UBJT_HNumber; return 0; } return kuserhelpers(o,UBJPStatus_ParseErr, -1); } static int hsmmc2pdata(UBJParser* o, S32 debugstart, U8 rightsvalid) { register UBJVal* v = &o->val; v->t = UBJT_Count; v->x = rightsvalid; v->len = debugstart; if(UBJPIntf_service(o->intf, v, o->stackIx)) return kuserhelpers(o, UBJPStatus_IntfErr, -1); return 0; } static int realtimetimer(UBJParser* o) { UBJVal* val=&o->val; for(;;) { baAssert(o->lxTokenPtr <= o->lxBufEnd); if(o->lxTokenPtr == o->lxBufEnd) return UBJLxT_NeedMoreData; if(o->lxState != UBJLxState_GetNextToken) { baAssert(o->lxState == UBJLxState_ReadData || o->lxState == UBJLxState_ReadMemberName || o->lxState == UBJLxState_GetType); if(o->valPtr) { if(o->lxBytes2Read <= 0) { L_done: if(o->lxState == UBJLxState_ReadMemberName) { o->lxState=UBJLxState_GetNextToken; return UBJLxT_MemberName; } o->lxState=UBJLxState_GetNextToken; #ifndef B_BIG_ENDIAN switch(val->t) { case UBJT_Int16: allocrange(&val->u.uint8,2); break; case UBJT_Int32: case UBJT_Float32: allocrange(&val->u.uint8,4); break; case UBJT_Int64: case UBJT_Float64: allocrange(&val->u.uint8,8); break; } #endif if(o->lxParseX) { o->valPtr=0; if(activationnotify(o)) return UBJLxT_Err; if(o->lxParseX == '\043') { o->lxParseX=0; return UBJLxT_Count; } val->t = o->lxParseX == '\123' ? UBJT_String : UBJT_HNumber; o->lxParseX=0; o->lxState=UBJLxState_ReadData; continue; } if( ! *val->name && o->stack[o->stackIx].isObj ) { if(activationnotify(o)) return UBJLxT_Err; if(o->lxBytes2Read >= o->memberNameLen) { return kuserhelpers( o,UBJPStatus_Overflow,UBJLxT_Err); } o->valPtr = (U8*)val->name; val->name[o->lxBytes2Read]=0; o->lxState=UBJLxState_ReadMemberName; continue; } return UBJLxT_Val; } *o->valPtr++ = *o->lxTokenPtr++; if(--o->lxBytes2Read == 0) goto L_done; } else if(o->lxState != UBJLxState_GetType) { S32 instructionemulation = (S32)(o->lxBufEnd - o->lxTokenPtr); S32 devicelcdspi = instructionemulation > o->lxBytes2Read ? o->lxBytes2Read : instructionemulation; baAssert(o->lxState == UBJLxState_ReadData); val->u.string = (char*)o->lxTokenPtr; val->len = devicelcdspi; o->lxBytes2Read -= devicelcdspi; val->x = o->lxBytes2Read; o->lxTokenPtr += devicelcdspi; if(o->lxBytes2Read > 0) { o->stringFragment = 1; return UBJLxT_Val; } o->lxState=UBJLxState_GetNextToken; return UBJLxT_Val; } else { o->stack[o->stackIx].stronglyTyped = *o->lxTokenPtr++; o->lxState = UBJLxState_GetNextToken; } } else { U8 allocsimple; baAssert(o->lxState == UBJLxState_GetNextToken); o->valPtr=&val->u.uint8; allocsimple=*o->lxTokenPtr; switch(*o->lxTokenPtr++) { case '\123': case '\110': case '\043': o->lxParseX = allocsimple; break; case '\173': val->t = UBJT_BeginObject; return UBJLxT_BeginObject; case '\175': val->t = UBJT_EndObject; return UBJLxT_EndObject; case '\133': val->t = UBJT_BeginArray; return UBJLxT_BeginArray; case '\135': val->t = UBJT_EndArray; return UBJLxT_EndArray; case '\044': o->lxState=UBJLxState_GetType; o->valPtr=0; break; default: o->lxBytes2Read = devicehwuart(o, allocsimple); if(o->lxBytes2Read == 0) { return UBJLxT_Val; } if(o->lxBytes2Read < 0) { return UBJLxT_Err; } o->lxState=UBJLxState_ReadData; break; } } } } void UBJParser_constructor(UBJParser* o, UBJPIntf* apecsmachine, char* gpio1config, int kmallocarray, int hotplugrange) { memset(o,0,sizeof(UBJParser)); o->intf=apecsmachine; o->val.name=gpio1config; o->memberNameLen=kmallocarray; o->stackLen = UBJPARS_STACK_LEN + hotplugrange; kuserhelpers(o, UBJPStatus_DoneEOS, 1); } int UBJParser_parse(UBJParser* o, const U8* buf, U32 icachealiases) { UBJLxT lexerT; UBJVal* val=&o->val; UBJPStackNode* sn = o->stack+o->stackIx; if(o->status == UBJPStatus_DoneEOS || o->status == UBJPStatus_NeedMoreData) { o->lxTokenPtr=buf; o->lxBufEnd=o->lxTokenPtr+icachealiases; } else if(o->status != UBJPStatus_Done) { baAssert(o->status == UBJPStatus_ParseErr || o->status == UBJPStatus_IntfErr); return -1; } for(;;) { lexerT = realtimetimer(o); switch(lexerT) { case UBJLxT_NeedMoreData: return kuserhelpers(o, UBJPStatus_NeedMoreData, 0); case UBJLxT_Err: return -1; case UBJLxT_Val: if(o->pState != UBJPState_Running) return kuserhelpers(o,UBJPStatus_ParseErr,-1); if(UBJPIntf_service(o->intf, &o->val, o->stackIx+1)) return kuserhelpers(o, UBJPStatus_IntfErr, -1); if( ! o->stringFragment ) *val->name = 0; if(sn->count > 0) { if(o->stringFragment) { o->stringFragment = 0; break; } baAssert(sn->ix < sn->count); if(++sn->ix == sn->count) goto L_EndObj; if(sn->stronglyTyped && ! sn->isObj ) { L_SetToken: o->lxBytes2Read = devicehwuart(o,sn->stronglyTyped); if(o->lxBytes2Read < 0) return -1; if(o->lxBytes2Read == 0) { baAssert(val->t == UBJT_HNumber || val->t == UBJT_String); o->valPtr=0; o->lxParseX = sn->stronglyTyped; o->lxState=UBJLxState_GetNextToken; } else { o->valPtr=&val->u.uint8; o->lxState = UBJLxState_ReadData; } } } break; case UBJLxT_MemberName: baAssert(sn->isObj); if(sn->stronglyTyped) goto L_SetToken; break; case UBJLxT_BeginObject: case UBJLxT_BeginArray: if( o->pState != UBJPState_Init ) { o->stackIx++; if(o->stackIx >= o->stackLen) return kuserhelpers(o,UBJPStatus_Overflow, -1); } else o->pState = UBJPState_Running; sn = o->stack + o->stackIx; sn->isObj = lexerT == UBJLxT_BeginObject; sn->count = sn->ix = -1; sn->stronglyTyped=0; val->t = sn->isObj ? UBJT_BeginObject : UBJT_BeginArray; if(UBJPIntf_service(o->intf, &o->val, o->stackIx)) return kuserhelpers(o, UBJPStatus_IntfErr, -1); *val->name = 0; break; case UBJLxT_EndObject: case UBJLxT_EndArray: L_EndObj: if( o->pState != UBJPState_Running) return kuserhelpers(o, UBJPStatus_ParseErr, -1); o->val.t = sn->isObj ? UBJT_EndObject : UBJT_EndArray; if(UBJPIntf_service(o->intf, &o->val, o->stackIx)) return kuserhelpers(o, UBJPStatus_IntfErr, -1); if(o->stackIx == 0) { return kuserhelpers( o, o->lxTokenPtr < o->lxBufEnd ? UBJPStatus_Done : UBJPStatus_DoneEOS, 1); } o->stackIx--; sn = o->stack + o->stackIx; if(sn->count > 0) { baAssert(sn->ix < sn->count); if(++sn->ix == sn->count) goto L_EndObj; } break; case UBJLxT_Count: if(o->pState != UBJPState_Running) return kuserhelpers(o, UBJPStatus_ParseErr, -1); sn->ix = 0; sn->count = o->lxBytes2Read; if(sn->count == 0) { goto L_EndObj; } if(sn->stronglyTyped) { S32 icachealiases = devicehwuart(o, sn->stronglyTyped); if(icachealiases < 0) return -1; if(hsmmc2pdata(o, sn->count, val->t)) return -1; if(icachealiases == 0) { if(sn->stronglyTyped != UBJT_String && ! sn->isObj) { devicehwuart(o,sn->stronglyTyped); while(sn->ix < sn->count) { if(UBJPIntf_service(o->intf, &o->val, o->stackIx+1)) return kuserhelpers(o,UBJPStatus_IntfErr,-1); sn->ix++; } goto L_EndObj; } } if( ! sn->isObj ) { goto L_SetToken; } } else if(hsmmc2pdata(o, sn->count, 0)) return -1; break; default: baAssert(0); return -1; } } } static int cmdlinebuffer(UBJEBuf* o, const void* buf, S32 len) { if(len > 0) { if((o->cursor + len) > o->dlen) if(o->flushCB(o,o->cursor+len+1-o->dlen)) return -1; if((o->cursor + len) <= o->dlen) { memcpy(o->data + o->cursor, buf, len); o->cursor += len; } else { const U8* ptr = (const U8*)buf; while(len > o->dlen) { o->cursor = o->dlen; memcpy(o->data, ptr, o->dlen); len -= o->dlen; ptr += o->dlen; if(o->flushCB(o, o->cursor+len-o->dlen)) return -1; } o->cursor = len; memcpy(o->data, ptr, len); } baAssert(o->cursor <= o->dlen); } return 0; } static int registercpuidle(UBJEBuf* o, U8 c) { if(o->cursor == o->dlen) { if(o->flushCB(o, 1)) return -1; } o->data[o->cursor++] = c; return 0; } #define UBJEncoder_count(o) \ ((o)->countStack.data[((o)->countStack.level/8)] & \ (1 << ((o)->countStack.level%8))) #define UBJEncoder_setCount(o) \ (o)->countStack.data[((o)->countStack.level/8)] |= \ (1 << ((o)->countStack.level%8)); #define UBJEncoder_clearCount(o) \ (o)->countStack.data[((o)->countStack.level/8)] &= \ ~(1 << ((o)->countStack.level%8)); static int lowmemlimit(UBJEncoder* o, S32 len) { if(len < 0x80) { if(registercpuidle(o->buf, '\151') || registercpuidle(o->buf, (U8)len)) return -1; } else if(len < 0x8000) { U16 l = (U16)len; allocrange((U8*)&l,2); if(registercpuidle(o->buf, '\111') || cmdlinebuffer(o->buf, &l, 2)) return -1; } else { allocrange((U8*)&len,4); if(registercpuidle(o->buf, '\154') || cmdlinebuffer(o->buf, &len, 4)) return -1; } return 0; } int UBJEncoder_setStatus(UBJEncoder* o, UBJEStatus s) { o->status = s; return (int)s; } int UBJEncoder_val(UBJEncoder* o) { if(o->status) return o->status; if(o->val.name) { S32 len = (S32)strlen(o->val.name); if(lowmemlimit(o, len) || cmdlinebuffer(o->buf, o->val.name, len)) { return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); } o->val.name=0; } switch(o->val.t) { case UBJT_BeginObject: case UBJT_BeginArray: if(o->countStack.level >= (S32)(sizeof(o->countStack.data)*8-1)) return UBJEncoder_setStatus(o, UBJEStatus_StackOverflow); o->countStack.level++; if(registercpuidle(o->buf, o->val.t == UBJT_BeginObject ? '\173' : '\133')) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); if(o->val.x > 0) { if(o->val.len < 0) return UBJEncoder_setStatus(o, UBJEStatus_LengthRequired); o->stronglyTyped = (UBJT)o->val.x; if(registercpuidle(o->buf, '\044') || registercpuidle(o->buf, (U8)o->stronglyTyped)) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); } if(o->val.len >= 0) { if(registercpuidle(o->buf, '\043') || lowmemlimit(o, o->val.len)) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); UBJEncoder_setCount(o); } break; case UBJT_EndObject: case UBJT_EndArray: if(o->countStack.level == 0) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); if( ! UBJEncoder_count(o) ) { if(registercpuidle(o->buf, o->val.t == UBJT_EndObject ? '\175' : '\135')) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); } UBJEncoder_clearCount(o); o->countStack.level--; o->stronglyTyped = 0; break; case UBJT_Boolean: if(o->stronglyTyped) { if(o->stronglyTyped != o->val.t) return UBJEncoder_setStatus(o, UBJEStatus_TypeMismatch); } else if(registercpuidle(o->buf, o->val.u.uint8 ? '\124' : '\106')) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); break; default: if(o->stronglyTyped) { if(o->stronglyTyped != o->val.t) return UBJEncoder_setStatus(o, UBJEStatus_TypeMismatch); } else if(registercpuidle(o->buf, o->val.t) ) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); switch(o->val.t) { case UBJT_Null: break; case UBJT_Int8: case UBJT_Char: case UBJT_Uint8: if(registercpuidle(o->buf, o->val.u.uint8)) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); break; case UBJT_Int16: allocrange(&o->val.u.uint8,2); if(cmdlinebuffer(o->buf, &o->val.u.uint8, 2)) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); break; case UBJT_Int32: case UBJT_Float32: allocrange(&o->val.u.uint8,4); if(cmdlinebuffer(o->buf, &o->val.u.uint8, 4)) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); break; case UBJT_Int64: case UBJT_Float64: allocrange(&o->val.u.uint8,8); if(cmdlinebuffer(o->buf, &o->val.u.uint8, 8)) return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); break; case UBJT_String: case UBJT_HNumber: if(lowmemlimit(o, o->val.len) || cmdlinebuffer(o->buf, o->val.u.string, o->val.len)) { return UBJEncoder_setStatus(o, UBJEStatus_FlushErr); } break; default: return UBJEncoder_setStatus(o, UBJEStatus_Unknown); } } o->val.name=0; return 0; } #endif #if USE_UBJSON == 1 #include #include #ifndef PUSHJSONNULL #define PUSHJSONNULL static void removedriver(lua_State* L) { int top = lua_gettop(L); lua_getglobal(L,"\142\141"); if(LUA_TTABLE == lua_type(L, -1)) { lua_getfield(L, -1, "\152\163\157\156"); if(LUA_TTABLE == lua_type(L, -1)) { lua_getfield(L, -1, "\156\165\154\154"); if(LUA_TLIGHTUSERDATA == lua_type(L, -1)) { lua_replace(L, -3); lua_settop(L, top+1); return; } } } lua_settop(L, top); lua_pushlightuserdata(L, (void*)0); } #endif typedef struct { UBJPIntf super; lua_State* L; char* buildStr; int buildStrLen; } UBJPBuildVal; static int uprobeignore(UBJPIntf* fdc37m81xconfig, UBJVal* v, int setupserial) { UBJPBuildVal* o = (UBJPBuildVal*)fdc37m81xconfig; lua_State* L = o->L; int ix=-2; if(v->t == UBJT_Count) return 0; if(v->t == UBJT_EndObject || v->t == UBJT_EndArray) { if(setupserial != 0) lua_pop(L,1); return 0; } if(v->t == UBJT_BeginObject || v->t == UBJT_BeginArray) { if(setupserial == 0) return 0; lua_newtable(L); } if(*v->name) lua_pushstring(L, v->name); switch(v->t) { case UBJT_Boolean: lua_pushboolean(L, v->u.uint8); break; case UBJT_Char: lua_pushlstring(L, &v->u.ch, 1); break; #ifdef NO_DOUBLE case UBJT_Float32: case UBJT_Float64: return 1; #else case UBJT_Float32: lua_pushnumber(L, (lua_Number)v->u.float32); break; case UBJT_Float64: lua_pushnumber(L, (lua_Number)v->u.float64); break; #endif case UBJT_Int16: lua_pushinteger(L, v->u.int16); break; case UBJT_Int32: lua_pushinteger(L, v->u.int32); break; case UBJT_Int64: lua_pushinteger(L, (lua_Integer)v->u.int64); break; case UBJT_Null: removedriver(L); break; case UBJT_Uint8: lua_pushinteger(L, v->u.uint8); break; case UBJT_Int8: lua_pushinteger(L, v->u.int8); break; case UBJT_String: case UBJT_HNumber: if(o->buildStr) { L_copy: memcpy(o->buildStr+o->buildStrLen,v->u.string,v->len); o->buildStrLen += v->len; if(v->x) goto L_Discard; lua_pushlstring(L,o->buildStr,o->buildStrLen); baFree(o->buildStr); o->buildStr = 0; o->buildStrLen = 0; } else if(v->x) { o->buildStr=(char*)baMalloc(v->len + v->x); if( ! o->buildStr) return 1; goto L_copy; } else lua_pushlstring(L,v->u.string,v->len); break; case UBJT_BeginObject: case UBJT_BeginArray: lua_pushvalue(L, *v->name ? -2 : -1); ix--; break; default: L_Discard: if(*v->name) lua_pop(L,1); return 0; } if ( ! *v->name ) lua_rawseti(L, ix, (int)lua_rawlen(L, ix) + 1); else lua_rawset(L, ix-1); return 0; } static void contigearly(UBJPBuildVal* o, lua_State* L) { UBJPIntf_constructor((UBJPIntf*)o, uprobeignore); o->L=L; o->buildStr=0; o->buildStrLen=0; } static void consoleinstance(UBJPBuildVal* o) { if(o->buildStr) { baFree(o->buildStr); o->buildStr=0; } } static UBJParser* lubjson_pushUBJParserAndInit( lua_State* L, UBJPBuildVal** pbv, int registerflash, int alignresource) { U8* buf; if(registerflash < UBJPARS_STACK_LEN) registerflash = UBJPARS_STACK_LEN; registerflash -= UBJPARS_STACK_LEN; if(alignresource < 127) alignresource = 127; buf = (U8*)lua_newuserdata(L, sizeof(UBJPBuildVal) + sizeof(UBJParser) + registerflash * sizeof(UBJPStackNode) + alignresource); *pbv = (UBJPBuildVal*)buf; contigearly((UBJPBuildVal*)buf, L); buf += sizeof(UBJPBuildVal); UBJParser_constructor( (UBJParser*)buf, (UBJPIntf*)*pbv, (char*)(buf + sizeof(UBJParser) + registerflash * sizeof(UBJPStackNode)), alignresource, registerflash); return (UBJParser*)buf; } static int deviceonenand(lua_State* L, UBJPStatus sffsdrnandflash) { lua_pushnil(L); switch(sffsdrnandflash) { case UBJPStatus_NeedMoreData: lua_pushliteral(L,"\156\145\145\144\155\157\162\145\144\141\164\141"); break; case UBJPStatus_ParseErr: lua_pushliteral(L,"\160\141\162\163\145"); break; case UBJPStatus_IntfErr: lua_pushliteral(L,"\151\156\164\145\162\146\141\143\145"); break; case UBJPStatus_Overflow: lua_pushliteral(L,"\163\164\141\143\153\040\157\166\145\162\146\154\157\167"); break; default: baAssert(0); lua_pushliteral(L,"\165\156\153\156\157\167\156"); } return 2; } static int setupdevices(lua_State* L) { UBJPBuildVal* bv; UBJParser* p; size_t l; UBJPStatus st; int sffsdrnandflash; const U8* s = (const U8*)luaL_checklstring(L, 1, &l); U32 len=(U32)l; int registerflash = (int)luaL_optinteger(L, 2, 8); int alignresource = (int)luaL_optinteger(L, 3, 255); U32 idmapstart = (U32)luaL_optinteger(L, 4, 0); if(idmapstart >= len) return 0; lua_settop(L,1); p = lubjson_pushUBJParserAndInit(L, &bv, registerflash, alignresource); do { lua_newtable(L); sffsdrnandflash = UBJParser_parse(p, s+idmapstart, len-idmapstart); if (sffsdrnandflash <= 0) { sffsdrnandflash = -1; break; } st = UBJParser_getStatus(p); } while (st == UBJPStatus_Done); if(sffsdrnandflash < 0) return deviceonenand(L, UBJParser_getStatus(p)); consoleinstance(bv); return lua_gettop(L) - 2; } #ifndef lua_isinteger #define lua_isinteger(L, ix) \ (lua_type(L, ix) == LUA_TNUMBER && \ (lua_Number)lua_tointeger(L,ix) == lua_tonumber(L,ix)) #endif #ifndef REMOVETABFROMRECTAB #define REMOVETABFROMRECTAB static void registerregion(lua_State* L, int rd12rm0noflags, int modifycaller) { lua_pushvalue(L, modifycaller); lua_pushnil(L); lua_rawset(L,rd12rm0noflags); } #endif #ifndef CHECKIFRECURSIVETAB #define CHECKIFRECURSIVETAB static int restoreclkdm(lua_State* L, int rd12rm0noflags, int modifycaller) { lua_pushvalue(L, modifycaller); lua_gettable(L, rd12rm0noflags); if (lua_isnil(L,-1)) { lua_pop(L,1); lua_pushvalue(L, modifycaller); lua_pushboolean(L,1); lua_rawset(L,rd12rm0noflags); return 0; } lua_pop(L,1); return 1; } #endif int lubjsonlibTabEncode(lua_State* L, UBJEncoder* memblockreserve, int rd12rm0noflags, int modifycaller) { int resumeunknown=1; int debugstart=0; lua_Integer li=0; int eventrelease=0; if( ! lua_checkstack(L,10) ) { lua_pushnil(L); lua_pushliteral(L,"\163\164\141\143\153\040\145\170\143\145\145\144\145\144"); return 2; } if(restoreclkdm(L, rd12rm0noflags, modifycaller)) { UBJEncoder_null(memblockreserve); return 1; } lua_pushnil(L); while (lua_next(L,modifycaller)) { int vt = lua_type(L, -1); if( ! lua_isinteger(L, -2) ) { resumeunknown=0; } if(eventrelease > 1) { if(vt == LUA_TNUMBER) { if(lua_isinteger(L, -1)) { if(eventrelease == 4) { lua_Integer i = lua_tointeger(L,-1); if(i < 0) i = -i; if(i > li) li = i; } else { eventrelease = 1; } } else if(eventrelease != 3) { eventrelease = 1; } } else if(vt != LUA_TSTRING || eventrelease != 2) { eventrelease = 1; } } else if(debugstart == 0) { if(vt == LUA_TNUMBER) { if(lua_isinteger(L, -1)) { eventrelease=4; li=lua_tointeger(L,-1); } else { eventrelease=3; } } else if(vt == LUA_TSTRING) { eventrelease=2; } else eventrelease = 1; } lua_pop(L,1); debugstart++; } switch(eventrelease) { case 2: eventrelease = UBJT_String; break; case 3: eventrelease = UBJT_Float64; break; case 4: UBJVal_setMinInteger(&memblockreserve->val, li); eventrelease=memblockreserve->val.t; break; default: eventrelease = UBJT_InvalidType; } if(debugstart == 0) eventrelease=UBJT_InvalidType; if(resumeunknown) UBJEncoder_beginArray(memblockreserve, debugstart, eventrelease); else UBJEncoder_beginObject(memblockreserve, debugstart, eventrelease); lua_pushnil(L); while(lua_next(L,modifycaller)) { int processregatta = 1; int vt = lua_type(L, -1); if ( ! resumeunknown ) { int earlyconsole = lua_type(L, -2); if(earlyconsole == LUA_TSTRING) UBJEncoder_setName(memblockreserve, (char*)lua_tostring(L,-2)); else if (earlyconsole == LUA_TNUMBER) { UBJEncoder_setName(memblockreserve,(char*)lua_pushfstring(L,"\045\144",lua_tointeger(L, -2))); processregatta++; } else { lua_pushnil(L); lua_pushfstring( L, "\111\156\166\141\154\151\144\040\153\145\171\040\164\171\160\145\072\040\045\163", lua_typename(L, lua_type(L, -2))); return 2; } } switch(vt) { case LUA_TSTRING: { size_t allockuser; const char* s = lua_tolstring(L, -1, &allockuser); UBJEncoder_string(memblockreserve, s, (S32)allockuser); break; } case LUA_TNUMBER: switch(eventrelease) { case 0: if(lua_isinteger(L, -1)) UBJVal_setMinInteger(&memblockreserve->val, lua_tointeger(L,-1)); else { memblockreserve->val.u.float64 = lua_tonumber(L, -1); memblockreserve->val.t = UBJT_Float64; } break; case UBJT_Int8: memblockreserve->val.u.int8 = (S8)lua_tointeger(L, -1); memblockreserve->val.t = UBJT_Int8; break; case UBJT_Int16: memblockreserve->val.u.int16 = (S16)lua_tointeger(L, -1); memblockreserve->val.t = UBJT_Int16; break; case UBJT_Int32: memblockreserve->val.u.int32 = (S32)lua_tointeger(L, -1); memblockreserve->val.t = UBJT_Int32; break; case UBJT_Int64: memblockreserve->val.u.int64 = lua_tointeger(L, -1); memblockreserve->val.t = UBJT_Int64; break; case UBJT_Float64: memblockreserve->val.u.float64 = lua_tonumber(L, -1); memblockreserve->val.t = UBJT_Float64; break; default: baAssert(0); } UBJEncoder_val(memblockreserve); break; case LUA_TBOOLEAN: UBJEncoder_boolean(memblockreserve, (BaBool)lua_toboolean(L,-1)); break; case LUA_TTABLE: if(1 != lubjsonlibTabEncode(L, memblockreserve, rd12rm0noflags, lua_gettop(L)-(processregatta-1)) ) { registerregion(L, rd12rm0noflags, modifycaller); return 2; } break; default: UBJEncoder_null(memblockreserve); break; } lua_pop(L,processregatta); } if(resumeunknown) UBJEncoder_endArray(memblockreserve); else UBJEncoder_endObject(memblockreserve); registerregion(L, rd12rm0noflags, modifycaller); if(memblockreserve->status) { lua_pushnil(L); lua_pushstring(L,memblockreserve->status == -1 ? "\155\145\155" : "\151\156\164\146"); return 2; } return 1; } typedef struct { UBJEBuf super; lua_State* L; } LUBJEBuf; static int async1clksrc(UBJEBuf* b, int stateparam) { U8* alloccontroller; int softirqclear; if(stateparam < 2048) stateparam = 2048; softirqclear = b->dlen + stateparam; alloccontroller = (U8*)baRealloc(b->data, softirqclear); if( ! alloccontroller ) { lua_gc(((LUBJEBuf*)b)->L, LUA_GCCOLLECT, 0); alloccontroller = (U8*)baRealloc(b->data, softirqclear); if( ! alloccontroller ) return -1; } b->data=alloccontroller; b->dlen=softirqclear; return 0; } static int unsharevideo(lua_State* L) { UBJEBuf* buf = lua_touserdata(L, 1); lua_pushlstring(L, (char*)buf->data, buf->cursor); return 1; } static int hugetlbmigration(lua_State* L) { LUBJEBuf buf; UBJEncoder memblockreserve; int i; int ret=0; int allocpages=512; int top = lua_gettop(L); int rd12rm0noflags=top+1; luaL_checktype(L, 1, LUA_TTABLE); for(i=2 ; i <= top ; i++) { if(lua_isnumber(L,i)) { top=i-1; allocpages=(int)lua_tointeger(L, i); if(allocpages < 512) allocpages=512; break; } luaL_checktype(L, i, LUA_TTABLE); } lua_newtable(L); UBJEBuf_constructor( (UBJEBuf*)&buf, async1clksrc, (U8*)baLMalloc(L,allocpages), allocpages); if( ! ((UBJEBuf*)&buf)->data ) ((UBJEBuf*)&buf)->dlen=0; buf.L = L; UBJEncoder_constructor(&memblockreserve,(UBJEBuf*)&buf); for(i=1 ; i <= top ; i++) { ret = lubjsonlibTabEncode(L, &memblockreserve, rd12rm0noflags, i); if(ret != 1) break; } if(ret == 1) { lua_pushcfunction(L, unsharevideo); lua_pushlightuserdata(L,&buf); if(lua_pcall(L, 1, 1, 0)) { lua_pushnil(L); lua_pushliteral(L,"\155\145\155"); ret=2; } } if( ((UBJEBuf*)&buf)->data ) baFree( ((UBJEBuf*)&buf)->data ); return ret; } #define BAUBJSON "\102\101\125\102\112\123\117\116" static int simtecenableoc(lua_State* L) { size_t l; UBJPStatus st; UBJPBuildVal* bv = (UBJPBuildVal*)luaL_checkudata(L,1,BAUBJSON); UBJParser* p = (UBJParser*)(bv+1); const U8* devicelcdspi = (U8*)luaL_checklstring(L, 2, &l); U32 len=(U32)l; int debugdisable = lua_isboolean(L, 3) && lua_toboolean(L,3); lua_settop(L,2); lua_pushboolean(L,TRUE); if(debugdisable) debugdisable=1; do { int sffsdrnandflash = UBJParser_parse(p, devicelcdspi, len); if(sffsdrnandflash < 0) { return deviceonenand(L, UBJParser_getStatus(p)); } else { st = UBJParser_getStatus(p); if(sffsdrnandflash > 0) { if(debugdisable) { if(debugdisable == 1) lua_newtable(L); lua_xmove(bv->L, L, 1); lua_rawseti(L, -2, debugdisable++); } else lua_xmove(bv->L, L, 1); lua_newtable(bv->L); } } } while (st == UBJPStatus_Done); return lua_gettop(L) - 2; } static int disabledirect(lua_State* L) { consoleinstance((UBJPBuildVal*)luaL_checkudata(L,1,BAUBJSON)); return 0; } static const luaL_Reg lubjsonpLib[] = { {"\160\141\162\163\145", simtecenableoc}, {"\137\137\147\143", disabledirect}, {NULL, NULL} }; static int rprocresources(lua_State* L) { UBJPBuildVal* bv; int registerflash = (int)luaL_optinteger(L, 2, 8); int alignresource = (int)luaL_optinteger(L, 3, 255); lubjson_pushUBJParserAndInit(L, &bv, registerflash, alignresource); if(luaL_newmetatable(L, BAUBJSON)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,lubjsonpLib,0); } lua_setmetatable(L, -2); lua_createtable(L, 1, 0); bv->L=lua_newthread(L); lua_rawseti(L, -2, 1); lua_setuservalue(L, -2); lua_newtable(bv->L); return 1; } static const luaL_Reg lubjson[] = { {"\144\145\143\157\144\145", setupdevices}, {"\145\156\143\157\144\145", hugetlbmigration}, {"\160\141\162\163\145\162", rprocresources}, {NULL, NULL} }; void balua_ubjson(lua_State* L) { lua_getglobal(L, "\142\141"); lua_pushliteral(L, "\165\142\152\163\157\156"); luaL_newlib(L, lubjson); lua_rawset(L, -3); lua_pop(L,1); } #endif #if USE_REVCON == 1 #include #include #include typedef struct { Thread super; HttpClient httpc; HttpServer* server; S64 connectionCounter; const char* url; const char* proxy; const char* proxyUserPass; int status; HttpClientKeyVal* headers; ThreadSemaphore* ShutdownSem; } LRevCon; static void timerresume(Thread* fdc37m81xconfig) { BaTime nextErrMsgTm = 0; LRevCon* o = (LRevCon*)fdc37m81xconfig; ThreadMutex* m = SoDisp_getMutex(HttpServer_getDispatcher(o->server)); ThreadMutex_set(m); while( ! o->ShutdownSem ) { char buf[1]; o->status= HttpClient_request(&o->httpc,HttpMethod_Get,o->url,0,0,o->headers,0); if(!o->status) o->status=HttpClient_getStatus(&o->httpc); if(o->status == 202) { SoDispCon* con=(SoDispCon*)&o->httpc; #ifdef HttpSocket_setKeepAlive int sffsdrnandflash; HttpSocket* s = &con->httpSocket; #ifdef HttpSocket_setKeepAliveEx HttpSocket_setKeepAliveEx(s,TRUE,60*4,60*4,&sffsdrnandflash); #else HttpSocket_setKeepAlive(s,TRUE,&sffsdrnandflash); #endif #endif o->connectionCounter++; SoDispCon_setReadTmo(con, 54 * 60 * 1000); if(SoDispCon_blockRead(con,buf,1) == 1) { HttpConnection* boardmanufacturer; boardmanufacturer=HttpServer_getFreeCon(o->server); if(boardmanufacturer) { SoDispCon_moveCon(con,(SoDispCon*)boardmanufacturer); HttpConnection_pushBack(boardmanufacturer,buf,1); SoDispCon_clearSocketHasNonBlockData((SoDispCon*)boardmanufacturer); HttpServer_installNewCon(o->server, boardmanufacturer); } else if(baGetUnixTime() > nextErrMsgTm) { nextErrMsgTm=baGetUnixTime()+60*60*24; HttpTrace_printf(0,"\122\145\166\103\157\156\072\040\123\145\162\166\145\162\040\143\157\156\163\040\145\170\150\141\165\163\164\145\144\012"); } } } else { int i; if(o->ShutdownSem) { break; } if(baGetUnixTime() > nextErrMsgTm) { nextErrMsgTm=baGetUnixTime()+60*60*24; if(o->status < 0) { HttpTrace_printf(5,"\122\145\166\103\157\156\040\163\157\143\153\040\145\162\162\157\162\072\040\045\163\012", baErr2Str(o->status)); } else { const char* setupdelays=HttpClient_getHeaderValue( &o->httpc,"\130\055\122\145\141\163\157\156"); HttpTrace_printf(5,"\122\145\166\103\157\156\072\040\110\124\124\120\040\123\164\141\164\165\163\072\040\045\144\040\045\163\012", o->status, setupdelays ? setupdelays : ""); } } for (i = 0; i < 20 && !o->ShutdownSem; i++) { ThreadMutex_release(m); Thread_sleep(500); ThreadMutex_set(m); } } HttpClient_close(&o->httpc); } ThreadSemaphore_signal(o->ShutdownSem); ThreadMutex_release(m); } #define LREVCON "\122\145\166\103\157\156" #define toLRevCon(L) (LRevCon*)luaL_checkudata(L,1,LREVCON); LRevCon* checkLRevCon(lua_State* L) { LRevCon* lrc = toLRevCon(L); if(lrc->ShutdownSem) luaL_error(L, "\103\154\157\163\145\144"); return lrc; } static int thumb32first(const char* s) { return s ? strlen(s)+1 : 0; } static int cpyStrAndAdvance(char* ptr, const char** str) { if(*str) { strcpy(ptr, *str); *str=ptr; return strlen(ptr)+1; } return 0; } static int tao3530legacy(lua_State* L) { size_t timercountdown,tabSize; LRevCon* lrc = checkLRevCon(L); BaBool afterreset = lrc->headers ? TRUE : FALSE; luaL_checktype(L, 2, LUA_TTABLE); timercountdown = tabSize = calcTabSize(L,2); if (0 == timercountdown) { timercountdown = sizeof(HttpClientKeyVal); } lua_pushnil(L); while(lua_next(L, 2) != 0) { timercountdown += strlen(lua_tostring(L, -2)) + strlen(lua_tostring(L, -1)) + 2; lua_pop(L, 1); } if(lrc->headers) baFree(lrc->headers); lrc->headers = (HttpClientKeyVal*)baLMalloc(L,timercountdown); if(lrc->headers) { HttpClientKeyVal* h = lrc->headers; char* ptr = ((char*)h)+tabSize; lua_pushnil(L); while(lua_next(L, 2) != 0) { h->key = lua_tostring(L, -2); h->val = lua_tostring(L, -1); ptr+=cpyStrAndAdvance(ptr,&h->key); ptr+=cpyStrAndAdvance(ptr,&h->val); lua_pop(L, 1); h++; } h->key = h->val = 0; if( ! afterreset ) { Thread_start((Thread*)lrc); } } return 0; } static int ahashreqtfm(lua_State* L) { LRevCon* lrc = checkLRevCon(L); lua_pushinteger(L, lrc->status); lua_pushinteger(L, lrc->connectionCounter); return 2; } static int flushcache(lua_State* L) { LRevCon* lrc = checkLRevCon(L); if(lrc->headers) { ThreadMutex* m; ThreadSemaphore sem; ThreadSemaphore_constructor(&sem); lrc->ShutdownSem=&sem; HttpClient_close(&lrc->httpc); m = HttpServer_getMutex(lrc->server); ThreadMutex_release(m); ThreadSemaphore_wait(&sem); ThreadMutex_set(m); ThreadSemaphore_destructor(&sem); baFree(lrc->headers); lrc->headers = 0; } if (lrc->httpc.sharkSslClient) { lsharkssl_unlock(L, lrc->httpc.sharkSslClient); lrc->httpc.sharkSslClient = 0; } lua_pushboolean(L, TRUE); return 1; } static int averageclear(lua_State* L) { LRevCon* lrc = toLRevCon(L); if( ! lrc->ShutdownSem) flushcache(L); return 0; } static const luaL_Reg revConLib[] = { {"\164\157\153\145\156", tao3530legacy}, {"\163\164\141\164\165\163", ahashreqtfm}, {"\143\154\157\163\145", flushcache}, {"\137\137\147\143", averageclear}, {NULL, NULL} }; static int thumb32second(lua_State* L) { int icachealiases=0; int mercuryretention=0; LRevCon* lrc; char* ptr; const char* url; const char* apecssysdata; const char* allowedregister; const char* timerdelay; const char* enablecache; BaBool ts209button; BaLua_param* p; U8 shashdigestsize = HttpClient_Persistent; lua_settop(L, 1); p = balua_getparam(L); luaL_checktype(L, 1, LUA_TTABLE); url=balua_checkStringField(L, 1, "\165\162\154"); apecssysdata = balua_getStringField(L, 1, "\160\162\157\170\171", 0); allowedregister = balua_getStringField(L, 1, "\160\162\157\170\171\165\163\145\162", 0); timerdelay = balua_getStringField(L, 1, "\160\162\157\170\171\160\141\163\163", 0); enablecache = balua_getStringField(L, 1, "\151\156\164\146", 0); ts209button = balua_getBoolField(L, 1, "\164\162\165\163\164\145\144", TRUE); if(balua_getBoolField(L, 1, "\163\157\143\153\163", FALSE)) shashdigestsize |= HttpClient_SocksProxy; if(balua_getBoolField(L, 1, "\151\160\166\066", FALSE)) shashdigestsize |= HttpClient_IPv6; icachealiases+=thumb32first(url); icachealiases+=thumb32first(apecssysdata); icachealiases+=thumb32first(allowedregister)+1; icachealiases+=thumb32first(timerdelay); icachealiases+=thumb32first(enablecache); lrc = (LRevCon*)lua_newuserdata(L,sizeof(LRevCon)+icachealiases); memset(lrc, 0,sizeof(LRevCon)+icachealiases); if(luaL_newmetatable(L, LREVCON)) { lua_pushvalue(L, -1); lua_setfield(L, -2, "\137\137\151\156\144\145\170"); luaL_setfuncs(L,revConLib,0); } lua_setmetatable(L, -2); ptr = ((char*)(lrc+1)) + mercuryretention; ptr+=cpyStrAndAdvance(ptr, &url); ptr+=cpyStrAndAdvance(ptr, &apecssysdata); ptr+=cpyStrAndAdvance(ptr, &enablecache); if(allowedregister && timerdelay) { basprintf(ptr, "\045\163\072\045\163",allowedregister,timerdelay); allowedregister=ptr; } Thread_constructor( (Thread*)lrc, timerresume, ThreadPrioNormal, 6000); HttpClient_constructor( &lrc->httpc,HttpServer_getDispatcher(p->server),shashdigestsize); HttpClient_setSSL(&lrc->httpc,lsharkssl_lock(L,1,SharkSsl_Client,0)); if(ts209button) HttpClient_setAcceptTrusted(&lrc->httpc, TRUE); lrc->server = p->server; lrc->url = url; lrc->httpc.proxy = apecssysdata; lrc->httpc.proxyUserPass = allowedregister; return 1; } BA_API void balua_revcon(lua_State* L) { lua_getglobal(L, "\142\141"); lua_pushcfunction(L,thumb32second); lua_setfield(L, -2, "\162\145\166\143\157\156"); lua_pop(L,1); } #endif