/*! \brief Updates the NPCCharacter Internally updates the inherited LevelData::BaseEntity and the inherited Character. */ void NPCCharacter::update(float deltaTimeInMilliSecs) { //before anything else, update the position updatePosition(deltaTimeInMilliSecs/1000.0f); lua_State* lua = LuaManager::getSingleton().getLuaState(); LuaManager::getSingleton().clearLuaStack(); lua_pushstring(lua,_name.c_str()); lua_setglobal(lua,"callingEntity"); lua_getglobal(lua,this->_scriptName.c_str()); lua_pushnumber(lua,16.666); lua_pushinteger(lua,_prevBhv); lua_pushinteger(lua,_prevAct); lua_pushinteger(lua,static_cast<int>(_isBhvFinished)); lua_pushinteger(lua,static_cast<int>(_isActFinished)); int err = lua_pcall(lua,5,1,0); if(err == 2) { std::cout << "Lua error!" << std::endl; if(lua_isstring(lua,1)) { std::cout << lua_tostring(lua,1) << std::endl; } } int behavior = 0,action = 0; std::string bhvTarget,actTarget,changeWep; Ogre::Vector3 moveTarget,shootTarget,target; int bhvChange = 0,actChange = 0; if(lua_istable(LuaManager::getSingleton().getLuaState(),1)) { bhvChange = LuaManager::getIntegerFromLuaTable(lua,"bhvchange"); _bhvChange = (bhvChange) ? true : false; //get behavior if(_bhvChange) { behavior = LuaManager::getIntegerFromLuaTable(lua,"behavior"); } else { behavior = _prevBhv; } actChange = LuaManager::getIntegerFromLuaTable(lua,"actchange"); _actChange = (actChange) ? true : false; if(_actChange) { action = LuaManager::getIntegerFromLuaTable(lua,"action"); } else { action = _prevAct; } Ogre::Vector3 min,max; switch(behavior) { case AI::BHV_IDLE: _behaviorIdle(); break; case AI::BHV_WANDER: min = LuaManager::getVectorFromLuaTable(lua,"bhvmin"); max = LuaManager::getVectorFromLuaTable(lua,"bhvmax"); if(min == Ogre::Vector3::ZERO || max == Ogre::Vector3::ZERO) { min = _destination; max = _destination; } _behaviorWander(min,max); break; case AI::BHV_TALK: bhvTarget = LuaManager::getStringFromLuaTable(lua,"bhvtarget"); _behaviorTalk(bhvTarget); break; case AI::BHV_MOVE: moveTarget = LuaManager::getVectorFromLuaTable(lua,"bhvtarget"); if(moveTarget == Ogre::Vector3(-1000,-1000,-1000)) { moveTarget = _destination; } _behaviorMove(moveTarget); break; case AI::BHV_FOLLOW: bhvTarget = LuaManager::getStringFromLuaTable(lua,"bhvtarget"); _behaviorFollow(bhvTarget); break; default: _behaviorIdle(); break; } switch(action) { case AI::ACT_IDLE: _actionIdle(); break; case AI::ACT_LOOKAT: target = LuaManager::getVectorFromLuaTable(lua,"lookat"); if(target == Ogre::Vector3::ZERO || target == Ogre::Vector3(-1000,-1000,-1000)) { _actionIdle(); } else { _actionLook(target); } break; default: _actionIdle(); break; } } //Just in case I missed something up there(missing lua_pop,etc) lua_settop(lua,0); //std::cout << behavior << "," << action << std::endl; _prevBhv = behavior; _prevAct = action; //lastly, update the animations //something is funky with FPSC character models. //Will probably have to get custom ones somewhere. _animHandler.addTime(deltaTimeInMilliSecs / 1000.0f); }
ngx_int_t ngx_http_lua_run_thread(lua_State *L, ngx_http_request_t *r, ngx_http_lua_ctx_t *ctx, int nret) { int rv; int cc_ref; lua_State *cc; const char *err, *msg; ngx_int_t rc; /* set Lua VM panic handler */ lua_atpanic(L, ngx_http_lua_atpanic); dd("ctx = %p", ctx); NGX_LUA_EXCEPTION_TRY { cc = ctx->cc; cc_ref = ctx->cc_ref; /* XXX: work-around to nginx regex subsystem */ ngx_http_lua_pcre_malloc_init(r->pool); /* run code */ rv = lua_resume(cc, nret); /* XXX: work-around to nginx regex subsystem */ ngx_http_lua_pcre_malloc_done(); dd("lua resume returns %d", (int) rv); switch (rv) { case LUA_YIELD: /* yielded, let event handler do the rest job */ /* FIXME: add io cmd dispatcher here */ dd("lua coroutine yielded"); #if 0 ngx_http_lua_dump_postponed(r); #endif lua_settop(cc, 0); return NGX_AGAIN; case 0: dd("normal end %.*s", (int) r->uri.len, r->uri.data); #if 0 ngx_http_lua_dump_postponed(r); #endif ngx_http_lua_del_thread(r, L, cc_ref, 0); ctx->cc_ref = LUA_NOREF; if (ctx->cleanup) { dd("cleaning up cleanup"); *ctx->cleanup = NULL; ctx->cleanup = NULL; } if (ctx->entered_content_phase) { rc = ngx_http_lua_send_chain_link(r, ctx, NULL /* indicate last_buf */); if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { return rc; } } return NGX_OK; case LUA_ERRRUN: err = "runtime error"; break; case LUA_ERRSYNTAX: err = "syntax error"; break; case LUA_ERRMEM: err = "memory allocation error"; break; case LUA_ERRERR: err = "error handler error"; break; default: err = "unknown error"; break; } if (lua_isstring(cc, -1)) { dd("user custom error msg"); msg = lua_tostring(cc, -1); } else { if (lua_isnil(cc, -1)) { if (ctx->exited) { dd("run here...exiting... %d", (int) ctx->exit_code); ngx_http_lua_del_thread(r, L, cc_ref, 0); ctx->cc_ref = LUA_NOREF; if (ctx->cleanup) { *ctx->cleanup = NULL; ctx->cleanup = NULL; } if ((ctx->exit_code == NGX_OK && ctx->entered_content_phase) || (ctx->exit_code >= NGX_HTTP_OK && ctx->exit_code < NGX_HTTP_SPECIAL_RESPONSE)) { rc = ngx_http_lua_send_chain_link(r, ctx, NULL /* indicate last_buf */); if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { return rc; } } return ctx->exit_code; } if (ctx->exec_uri.len) { ngx_http_lua_del_thread(r, L, cc_ref, 0); ctx->cc_ref = LUA_NOREF; if (ctx->cleanup) { *ctx->cleanup = NULL; ctx->cleanup = NULL; } if (ctx->exec_uri.data[0] == '@') { if (ctx->exec_args.len > 0) { ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, "query strings %V ignored when exec'ing " "named location %V", &ctx->exec_args, &ctx->exec_uri); } r->write_event_handler = ngx_http_request_empty_handler; rc = ngx_http_named_location(r, &ctx->exec_uri); if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { return rc; } if (! ctx->entered_content_phase && r != r->connection->data) { /* XXX ensure the main request ref count * is decreased because the current * request will be quit */ r->main->count--; } return NGX_DONE; } dd("internal redirect to %.*s", (int) ctx->exec_uri.len, ctx->exec_uri.data); /* resume the write event handler */ r->write_event_handler = ngx_http_request_empty_handler; rc = ngx_http_internal_redirect(r, &ctx->exec_uri, &ctx->exec_args); dd("internal redirect returned %d when in content phase? " "%d", (int) rc, ctx->entered_content_phase); if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) { return rc; } dd("XXYY HERE %d\n", (int) r->main->count); if (! ctx->entered_content_phase && r != r->connection->data) { /* XXX ensure the main request ref count * is decreased because the current * request will be quit */ r->main->count--; } return NGX_DONE; } } msg = "unknown reason"; } ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "lua handler aborted: %s: %s", err, msg); ngx_http_lua_del_thread(r, L, cc_ref, 0); ctx->cc_ref = LUA_NOREF; if (ctx->cleanup) { *ctx->cleanup = NULL; ctx->cleanup = NULL; } dd("headers sent? %d", ctx->headers_sent ? 1 : 0); return ctx->headers_sent ? NGX_ERROR : NGX_HTTP_INTERNAL_SERVER_ERROR; } NGX_LUA_EXCEPTION_CATCH { dd("nginx execution restored"); } return NGX_ERROR; }
/** * The routeQuery entry point. This is passed the query buffer * to which the filter should be applied. Once processed the * query is passed to the downstream component * (filter or router) in the filter chain. * * The Luafilter calls the routeQuery functions of both the session and the global script. * The query is passed as a string parameter to the routeQuery Lua function and * the return values of the session specific function, if any were returned, * are interpreted. If the first value is bool, it is interpreted as a decision * whether to route the query or to send an error packet to the client. * If it is a string, the current query is replaced with the return value and * the query will be routed. If nil is returned, the query is routed normally. * * @param instance The filter instance data * @param session The filter session * @param queue The query data */ static int routeQuery(FILTER *instance, void *session, GWBUF *queue) { LUA_SESSION *my_session = (LUA_SESSION *) session; LUA_INSTANCE *my_instance = (LUA_INSTANCE *) instance; DCB* dcb = my_session->session->client_dcb; char *fullquery = NULL, *ptr; bool route = true; GWBUF* forward = queue; int rc = 0; if (modutil_is_SQL(queue) || modutil_is_SQL_prepare(queue)) { fullquery = modutil_get_SQL(queue); if (fullquery && my_session->lua_state) { spinlock_acquire(&my_session->lock); lua_getglobal(my_session->lua_state, "routeQuery"); lua_pushlstring(my_session->lua_state, fullquery, strlen(fullquery)); if (lua_pcall(my_session->lua_state, 1, 1, 0)) { MXS_ERROR("luafilter: Session scope call to 'routeQuery' failed: '%s'.", lua_tostring(my_session->lua_state, -1)); } else if (lua_gettop(my_session->lua_state)) { if (lua_isstring(my_session->lua_state, -1)) { if (forward) { gwbuf_free(forward); } forward = modutil_create_query((char*) lua_tostring(my_session->lua_state, -1)); } else if (lua_isboolean(my_session->lua_state, -1)) { route = lua_toboolean(my_session->lua_state, -1); } } spinlock_release(&my_session->lock); } if (my_instance->global_lua_state) { spinlock_acquire(&my_instance->lock); lua_getglobal(my_instance->global_lua_state, "routeQuery"); lua_pushlstring(my_instance->global_lua_state, fullquery, strlen(fullquery)); if (lua_pcall(my_instance->global_lua_state, 1, 0, 0)) { MXS_ERROR("luafilter: Global scope call to 'routeQuery' failed: '%s'.", lua_tostring(my_session->lua_state, -1)); } else if (lua_gettop(my_instance->global_lua_state)) { if (lua_isstring(my_instance->global_lua_state, -1)) { if (forward) { gwbuf_free(forward); } forward = modutil_create_query((char*) lua_tostring(my_instance->global_lua_state, -1)); } else if (lua_isboolean(my_instance->global_lua_state, -1)) { route = lua_toboolean(my_instance->global_lua_state, -1); } } spinlock_release(&my_instance->lock); } free(fullquery); } if (!route) { gwbuf_free(queue); GWBUF* err = modutil_create_mysql_err_msg(1, 0, 1045, "28000", "Access denied."); rc = dcb->func.write(dcb, err); } else { rc = my_session->down.routeQuery(my_session->down.instance, my_session->down.session, forward); } return rc; }
void read_object_properties(lua_State *L, int index, ObjectProperties *prop) { if(index < 0) index = lua_gettop(L) + 1 + index; if(!lua_istable(L, index)) return; prop->hp_max = getintfield_default(L, -1, "hp_max", 10); getboolfield(L, -1, "physical", prop->physical); getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects); getfloatfield(L, -1, "weight", prop->weight); lua_getfield(L, -1, "collisionbox"); if(lua_istable(L, -1)) prop->collisionbox = read_aabb3f(L, -1, 1.0); lua_pop(L, 1); getstringfield(L, -1, "visual", prop->visual); getstringfield(L, -1, "mesh", prop->mesh); lua_getfield(L, -1, "visual_size"); if(lua_istable(L, -1)) prop->visual_size = read_v2f(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "textures"); if(lua_istable(L, -1)){ prop->textures.clear(); int table = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 if(lua_isstring(L, -1)) prop->textures.push_back(lua_tostring(L, -1)); else prop->textures.push_back(""); // removes value, keeps key for next iteration lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, -1, "colors"); if (lua_istable(L, -1)) { int table = lua_gettop(L); prop->colors.clear(); for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) { video::SColor color(255, 255, 255, 255); read_color(L, -1, &color); prop->colors.push_back(color); } } lua_pop(L, 1); lua_getfield(L, -1, "spritediv"); if(lua_istable(L, -1)) prop->spritediv = read_v2s16(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "initial_sprite_basepos"); if(lua_istable(L, -1)) prop->initial_sprite_basepos = read_v2s16(L, -1); lua_pop(L, 1); getboolfield(L, -1, "is_visible", prop->is_visible); getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound); getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate); if (getfloatfield(L, -1, "stepheight", prop->stepheight)) prop->stepheight *= BS; lua_getfield(L, -1, "automatic_face_movement_dir"); if (lua_isnumber(L, -1)) { prop->automatic_face_movement_dir = true; prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1); } else if (lua_isboolean(L, -1)) { prop->automatic_face_movement_dir = lua_toboolean(L, -1); prop->automatic_face_movement_dir_offset = 0.0; } lua_pop(L, 1); }
static int zip_openfile (lua_State *L) { ZZIP_FILE** inf; const char * ext2[LUAZIP_MAX_EXTENSIONS+1]; zzip_strings_t *ext = ext2; const char *filename = luaL_checkstring(L, 1); /*const char *mode = luaL_optstring(L, 2, "r");*/ inf = newinternalfile(L); if (lua_isstring(L, 2)) { /* creates a table with the string as the first and only (numerical) element */ lua_newtable(L); lua_pushvalue(L, 2); lua_rawseti(L, -2, 1); /* replaces the string by the table with the string inside */ lua_replace(L, 2); } if (lua_istable(L, 2)) { int i, m, n; /* how many extension were specified? */ n = luaL_getn(L, 2); if (n > LUAZIP_MAX_EXTENSIONS) { luaL_error(L, "too many extensions specified"); } for (i = 0, m = 0; i < n; i++) { lua_rawgeti(L, 2, i+1); if (lua_isstring(L, -1)) { /* luazip specifies "zip" as the extension, but zziplib expects ".zip" */ lua_pushstring(L, "."); lua_insert(L, -2); lua_concat(L, 2); ext2[m] = lua_tostring(L, -1); m++; } lua_pop(L, 1); } ext2[m] = 0; *inf = zzip_open_ext_io(filename, 0, 0664, ext, 0); } else { *inf = zzip_open(filename, 0); } if (*inf) return 1; lua_pushnil(L); lua_pushfstring(L, "could not open file `%s'", filename); return 2; }
/* Lua only functions */ int luaT_lua_newmetatable(lua_State *L) { const char* tname = luaL_checkstring(L, 1); const void *id; lua_settop(L, 5); luaL_argcheck(L, lua_isnoneornil(L, 2) || lua_isstring(L, 2), 2, "parent class name or nil expected"); luaL_argcheck(L, lua_isnoneornil(L, 3) || lua_isfunction(L, 3), 3, "constructor function or nil expected"); luaL_argcheck(L, lua_isnoneornil(L, 4) || lua_isfunction(L, 4), 4, "destructor function or nil expected"); luaL_argcheck(L, lua_isnoneornil(L, 5) || lua_isfunction(L, 5), 5, "factory function or nil expected"); if(luaT_classmodulename(tname)) lua_getfield(L, LUA_GLOBALSINDEX, luaT_classmodulename(tname)); else lua_pushvalue(L, LUA_GLOBALSINDEX); if(!lua_istable(L, 6)) luaL_error(L, "while creating metatable %s: bad ardument #1 (%s is an invalid module name)", tname, luaT_classmodulename(tname)); /* we first create the new metaclass if we have to */ if(!luaT_typename2id(L, tname)) { /* create the metaclass */ lua_newtable(L); id = lua_topointer(L, -1); /* id = pointer on metaclass */ /* __index points on itself */ lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); /* __typename contains the typename */ lua_pushstring(L, tname); lua_setfield(L, -2, "__typename"); /* by default, __version equals 1 */ lua_pushnumber(L, 1); lua_setfield(L, -2, "__version"); /* register in "*torch.id2tname*" registry table (id -> typename) */ lua_getfield(L, LUA_REGISTRYINDEX, "*torch.id2tname*"); if(lua_isnil(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_setfield(L, LUA_REGISTRYINDEX, "*torch.id2tname*"); lua_getfield(L, LUA_REGISTRYINDEX, "*torch.id2tname*"); } lua_pushlightuserdata(L, (void*)id); lua_pushstring(L, tname); lua_settable(L, -3); lua_pop(L, 1); /* register in "*torch.tname2id*" registry table (typename -> id) */ lua_getfield(L, LUA_REGISTRYINDEX, "*torch.tname2id*"); if(lua_isnil(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_setfield(L, LUA_REGISTRYINDEX, "*torch.tname2id*"); lua_getfield(L, LUA_REGISTRYINDEX, "*torch.tname2id*"); } lua_pushstring(L, tname); lua_pushlightuserdata(L, (void*)id); lua_settable(L, -3); lua_pop(L, 1); } /* we retrieve the existing metaclass */ else { id = luaT_typename2id(L, tname); luaT_pushmetaclass(L, id); } /* we assign the parent class if necessary */ if(!lua_isnoneornil(L, 2)) { if(lua_getmetatable(L, -1)) luaL_error(L, "class %s has been already assigned a parent class\n", tname); else { const char* parenttname = luaL_checkstring(L, 2); luaT_pushmetaclass(L, luaT_typename2id(L, parenttname)); if(lua_isnil(L, -1)) luaL_error(L, "bad argument #2 (invalid parent class name %s)", parenttname); lua_setmetatable(L, -2); } } /******** root-metatable ********/ /* id is the pointer on the metatable registry[id] = root-metatable, so try to see if it exists */ lua_pushlightuserdata(L, (void*)id); /* id */ lua_rawget(L, LUA_REGISTRYINDEX); /* not existing? we create a new one! */ if(lua_isnil(L, -1)) { lua_pop(L, 1); /* remove nil on stack */ lua_newtable(L); /* __index handling */ lua_pushcfunction(L, luaT_rmt__index); lua_setfield(L, -2, "__index"); /* __newindex handling */ lua_pushcfunction(L, luaT_rmt__newindex); lua_setfield(L, -2, "__newindex"); /* __metatable field (point on the metaclass) */ lua_pushvalue(L, -2); lua_setfield(L, -2, "__metatable"); /* __typename contains the typename */ lua_pushstring(L, tname); lua_setfield(L, -2, "__typename"); /* operators handling */ #define MT_ADD_OPERATOR(name) \ lua_pushcfunction(L, luaT_rmt__##name); \ lua_setfield(L, -2, "__" #name) MT_ADD_OPERATOR(tostring); MT_ADD_OPERATOR(add); MT_ADD_OPERATOR(sub); MT_ADD_OPERATOR(mul); MT_ADD_OPERATOR(div); MT_ADD_OPERATOR(mod); MT_ADD_OPERATOR(pow); MT_ADD_OPERATOR(unm); MT_ADD_OPERATOR(concat); MT_ADD_OPERATOR(len); MT_ADD_OPERATOR(eq); MT_ADD_OPERATOR(lt); MT_ADD_OPERATOR(le); MT_ADD_OPERATOR(call); /* assign the metaclass as metatable... */ lua_pushvalue(L, -2); lua_setmetatable(L, -2); /* id is the pointer on the metatable set registry[id] = root-metatable */ lua_pushlightuserdata(L, (void*)id); /* id */ lua_pushvalue(L, -2); /* metatable */ lua_rawset(L, LUA_REGISTRYINDEX); /* registry[id] = metatable */ } /* ok, so now we have the root-metatable on the stack */ /* register the destructor function */ if(!lua_isnoneornil(L, 4)) { /* does it exists already? */ lua_pushstring(L, "__gc"); lua_rawget(L, -2); if(lua_isnil(L, -1)) { lua_pop(L, 1); /* pop nil */ lua_pushstring(L, "__gc"); lua_pushvalue(L, 4); lua_rawset(L, -3); } else luaL_error(L, "%s has been already assigned a destructor", tname); } /* register the factory function */ if(!lua_isnoneornil(L, 5)) { /* does it exists already? */ lua_pushstring(L, "__factory"); lua_rawget(L, -2); if(lua_isnil(L, -1)) { lua_pop(L, 1); /* pop nil */ lua_pushstring(L, "__factory"); lua_pushvalue(L, 5); lua_rawset(L, -3); } else luaL_error(L, "%s has been already assigned a factory", tname); } /******** Constructor table and metatable ********/ lua_pushstring(L, "__constructor"); lua_rawget(L, -2); if(lua_isnil(L, -1)) { lua_pop(L, 1); /* pop nil */ lua_newtable(L); /* fancy table */ lua_newtable(L); /* fancy metatable */ lua_pushvalue(L, -4); /* metaclass */ lua_setfield(L, -2, "__index"); /* so we can get the methods */ lua_pushcfunction(L, luaT_cmt__newindex); lua_setfield(L, -2, "__newindex"); /* so we cannot messup */ lua_pushcfunction(L, luaT_cmt__call); lua_setfield(L, -2, "__call"); /* so we can create */ lua_pushvalue(L, -4); lua_setfield(L, -2, "__metatable"); /* redirect to metatable with methods */ lua_setmetatable(L, -2); /* metatable is ... the fancy metatable */ /* set root-metatable[__constructor] = constructor-metatable */ lua_pushstring(L, "__constructor"); lua_pushvalue(L, -2); lua_rawset(L, -4); } /* register the constructor function */ if(!lua_isnoneornil(L, 3)) { /* get constructor metatable */ lua_getmetatable(L, -1); /* does it exists already? */ lua_pushstring(L, "__new"); lua_rawget(L, -2); if(lua_isnil(L, -1)) { lua_pop(L, 1); /* pop nil */ lua_pushstring(L, "__new"); lua_pushvalue(L, 3); lua_rawset(L, -3); } else luaL_error(L, "%s has been already assigned a constructor", tname); /* pop constructor metatable */ lua_pop(L, 1); } lua_setfield(L, 6, luaT_classrootname(tname)); /* module.name = constructor-metatable */ lua_pop(L, 1); /* pop the root-metatable */ return 1; /* returns the metaclass */ }
void Script::callFunction(const char *func,const char *sig,...) { va_list vl; int narg,nres; va_start(vl,sig); lua_getglobal(mThreadState,func); if(lua_isfunction(mThreadState,-1)) { narg = 0; while(*sig) { switch (*sig++) { case 'd': lua_pushnumber(mThreadState,va_arg(vl,double)); break; case 'i': lua_pushnumber(mThreadState,va_arg(vl,int)); break; case 's': lua_pushstring(mThreadState,va_arg(vl,char *)); break; case '>': goto endwhile; break; default: break; } narg++; luaL_checkstack(mThreadState,1,"too many arguments"); } endwhile: nres = strlen(sig); if(lua_pcall(mThreadState,narg,nres,0) != 0) { _formatError(); gLogger->logMsgF("ScriptingEngine::callFunction Runtime Error: %s",MSG_NORMAL,mLastError); } nres = -nres; while(*sig) { switch (*sig++) { case 'd': { if(!lua_isnumber(mThreadState,nres)) { _formatError(); gLogger->logMsgF("ScriptingEngine::callFunction wrong result type: %s",MSG_NORMAL,mLastError); } *va_arg(vl,double *) = lua_tonumber(mThreadState,nres); } break; case 'i': { if(!lua_isnumber(mThreadState,nres)) { _formatError(); gLogger->logMsgF("ScriptingEngine::callFunction wrong result type: %s",MSG_NORMAL,mLastError); } *va_arg(vl,int*) = (int)lua_tonumber(mThreadState,nres); } break; case 's': { if(!lua_isstring(mThreadState,nres)) { _formatError(); gLogger->logMsgF("ScriptingEngine::callFunction wrong result type: %s",MSG_NORMAL,mLastError); } *va_arg(vl,const char **) = lua_tostring(mThreadState,nres); } break; default: { _formatError(); gLogger->logMsgF("ScriptingEngine::callFunction invalid option: %s",MSG_NORMAL,mLastError); } break; } nres++; } } va_end(vl); }
/** * walk through the content array * * content = { "<pre>", { file = "/content" } , "</pre>" } * * header["Content-Type"] = "text/html" * * return 200 */ static int magnet_attach_content(server *srv, connection *con, plugin_data *p, lua_State *L) { UNUSED(p); /** * get the environment of the function */ force_assert(lua_isfunction(L, -1)); lua_getfenv(L, -1); /* -1 is the function */ lua_getfield(L, -1, "lighty"); /* lighty.* from the env */ force_assert(lua_istable(L, -1)); lua_getfield(L, -1, "content"); /* lighty.content */ if (lua_istable(L, -1)) { int i; /* header is found, and is a table */ for (i = 1; ; i++) { lua_rawgeti(L, -1, i); /* -1 is the value and should be the value ... aka a table */ if (lua_isstring(L, -1)) { size_t s_len = 0; const char *s = lua_tolstring(L, -1, &s_len); chunkqueue_append_mem(con->write_queue, s, s_len); } else if (lua_istable(L, -1)) { lua_getfield(L, -1, "filename"); lua_getfield(L, -2, "length"); lua_getfield(L, -3, "offset"); if (lua_isstring(L, -3)) { /* filename has to be a string */ buffer *fn; stat_cache_entry *sce; const char *fn_str; handler_t res; fn_str = lua_tostring(L, -3); fn = buffer_init_string(fn_str); res = stat_cache_get_entry(srv, con, fn, &sce); if (HANDLER_GO_ON == res) { off_t off = 0; off_t len = 0; if (lua_isnumber(L, -1)) { off = lua_tonumber(L, -1); } if (lua_isnumber(L, -2)) { len = lua_tonumber(L, -2); } else { len = sce->st.st_size; } if (off < 0) { buffer_free(fn); return luaL_error(L, "offset for '%s' is negative", fn_str); } if (len < off) { buffer_free(fn); return luaL_error(L, "offset > length for '%s'", fn_str); } chunkqueue_append_file(con->write_queue, fn, off, len - off); } buffer_free(fn); } else { lua_pop(L, 3 + 2); /* correct the stack */ return luaL_error(L, "content[%d] is a table and requires the field \"filename\"", i); } lua_pop(L, 3); } else if (lua_isnil(L, -1)) { /* oops, end of list */ lua_pop(L, 1); break; } else { lua_pop(L, 4); return luaL_error(L, "content[%d] is neither a string nor a table: ", i); } lua_pop(L, 1); /* pop the content[...] table */ } } else { return luaL_error(L, "lighty.content has to be a table"); } lua_pop(L, 1); /* pop the header-table */ lua_pop(L, 1); /* pop the lighty-table */ lua_pop(L, 1); /* php the function env */ return 0; }
static handler_t magnet_attract(server *srv, connection *con, plugin_data *p, buffer *name) { lua_State *L; int lua_return_value = -1; int errfunc; /* get the script-context */ L = script_cache_get_script(srv, con, p->cache, name); if (lua_isstring(L, -1)) { log_error_write(srv, __FILE__, __LINE__, "sbss", "loading script", name, "failed:", lua_tostring(L, -1)); lua_pop(L, 1); force_assert(lua_gettop(L) == 0); /* only the function should be on the stack */ con->http_status = 500; con->mode = DIRECT; return HANDLER_FINISHED; } lua_pushstring(L, "lighty.srv"); lua_pushlightuserdata(L, srv); lua_settable(L, LUA_REGISTRYINDEX); /* registery[<id>] = srv */ lua_pushstring(L, "lighty.con"); lua_pushlightuserdata(L, con); lua_settable(L, LUA_REGISTRYINDEX); /* registery[<id>] = con */ lua_atpanic(L, magnet_atpanic); /** * we want to create empty environment for our script * * setmetatable({}, {__index = _G}) * * if a function, symbol is not defined in our env, __index will lookup * in the global env. * * all variables created in the script-env will be thrown * away at the end of the script run. */ lua_newtable(L); /* my empty environment aka {} (sp += 1) */ /* we have to overwrite the print function */ lua_pushcfunction(L, magnet_print); /* (sp += 1) */ lua_setfield(L, -2, "print"); /* -1 is the env we want to set(sp -= 1) */ /** * lighty.request[] has the HTTP-request headers * lighty.content[] is a table of string/file * lighty.header[] is a array to set response headers */ lua_newtable(L); /* lighty.* (sp += 1) */ lua_newtable(L); /* {} (sp += 1) */ lua_newtable(L); /* the meta-table for the request-table (sp += 1) */ lua_pushcfunction(L, magnet_reqhdr_get); /* (sp += 1) */ lua_setfield(L, -2, "__index"); /* (sp -= 1) */ lua_pushcfunction(L, magnet_reqhdr_pairs); /* (sp += 1) */ lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */ lua_setmetatable(L, -2); /* tie the metatable to request (sp -= 1) */ lua_setfield(L, -2, "request"); /* content = {} (sp -= 1) */ lua_newtable(L); /* {} (sp += 1) */ lua_newtable(L); /* the meta-table for the request-table (sp += 1) */ lua_pushcfunction(L, magnet_env_get); /* (sp += 1) */ lua_setfield(L, -2, "__index"); /* (sp -= 1) */ lua_pushcfunction(L, magnet_env_set); /* (sp += 1) */ lua_setfield(L, -2, "__newindex"); /* (sp -= 1) */ lua_pushcfunction(L, magnet_env_pairs); /* (sp += 1) */ lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */ lua_setmetatable(L, -2); /* tie the metatable to request (sp -= 1) */ lua_setfield(L, -2, "env"); /* content = {} (sp -= 1) */ lua_newtable(L); /* {} (sp += 1) */ lua_newtable(L); /* the meta-table for the request-table (sp += 1) */ lua_pushcfunction(L, magnet_cgi_get); /* (sp += 1) */ lua_setfield(L, -2, "__index"); /* (sp -= 1) */ lua_pushcfunction(L, magnet_cgi_set); /* (sp += 1) */ lua_setfield(L, -2, "__newindex"); /* (sp -= 1) */ lua_pushcfunction(L, magnet_cgi_pairs); /* (sp += 1) */ lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */ lua_setmetatable(L, -2); /* tie the metatable to req_env (sp -= 1) */ lua_setfield(L, -2, "req_env"); /* content = {} (sp -= 1) */ lua_newtable(L); /* {} (sp += 1) */ lua_newtable(L); /* the meta-table for the request-table (sp += 1) */ lua_pushcfunction(L, magnet_status_get); /* (sp += 1) */ lua_setfield(L, -2, "__index"); /* (sp -= 1) */ lua_pushcfunction(L, magnet_status_set); /* (sp += 1) */ lua_setfield(L, -2, "__newindex"); /* (sp -= 1) */ lua_pushcfunction(L, magnet_status_pairs); /* (sp += 1) */ lua_setfield(L, -2, "__pairs"); /* (sp -= 1) */ lua_setmetatable(L, -2); /* tie the metatable to request (sp -= 1) */ lua_setfield(L, -2, "status"); /* content = {} (sp -= 1) */ /* add empty 'content' and 'header' tables */ lua_newtable(L); /* {} (sp += 1) */ lua_setfield(L, -2, "content"); /* content = {} (sp -= 1) */ lua_newtable(L); /* {} (sp += 1) */ lua_setfield(L, -2, "header"); /* header = {} (sp -= 1) */ lua_pushinteger(L, MAGNET_RESTART_REQUEST); lua_setfield(L, -2, "RESTART_REQUEST"); lua_pushcfunction(L, magnet_stat); /* (sp += 1) */ lua_setfield(L, -2, "stat"); /* -1 is the env we want to set (sp -= 1) */ lua_setfield(L, -2, "lighty"); /* lighty.* (sp -= 1) */ /* override the default pairs() function to our __pairs capable version */ lua_getglobal(L, "pairs"); /* push original pairs() (sp += 1) */ lua_pushcclosure(L, magnet_pairs, 1); lua_setfield(L, -2, "pairs"); /* (sp -= 1) */ lua_newtable(L); /* the meta-table for the new env (sp += 1) */ lua_pushvalue(L, LUA_GLOBALSINDEX); /* (sp += 1) */ lua_setfield(L, -2, "__index"); /* { __index = _G } (sp -= 1) */ lua_setmetatable(L, -2); /* setmetatable({}, {__index = _G}) (sp -= 1) */ lua_setfenv(L, -2); /* on the stack should be a modified env (sp -= 1) */ errfunc = push_traceback(L, 0); if (lua_pcall(L, 0, 1, errfunc)) { lua_remove(L, errfunc); log_error_write(srv, __FILE__, __LINE__, "ss", "lua_pcall():", lua_tostring(L, -1)); lua_pop(L, 1); /* remove the error-msg and the function copy from the stack */ force_assert(lua_gettop(L) == 1); /* only the function should be on the stack */ con->http_status = 500; con->mode = DIRECT; return HANDLER_FINISHED; } lua_remove(L, errfunc); /* we should have the function-copy and the return value on the stack */ force_assert(lua_gettop(L) == 2); if (lua_isnumber(L, -1)) { /* if the ret-value is a number, take it */ lua_return_value = (int)lua_tonumber(L, -1); } lua_pop(L, 1); /* pop the ret-value */ magnet_copy_response_header(srv, con, p, L); if (lua_return_value > 99) { con->http_status = lua_return_value; con->file_finished = 1; /* try { ...*/ if (0 == setjmp(exceptionjmp)) { magnet_attach_content(srv, con, p, L); if (!chunkqueue_is_empty(con->write_queue)) { con->mode = p->id; } } else { /* } catch () { */ con->http_status = 500; con->mode = DIRECT; } force_assert(lua_gettop(L) == 1); /* only the function should be on the stack */ /* we are finished */ return HANDLER_FINISHED; } else if (MAGNET_RESTART_REQUEST == lua_return_value) { force_assert(lua_gettop(L) == 1); /* only the function should be on the stack */ return HANDLER_COMEBACK; } else { force_assert(lua_gettop(L) == 1); /* only the function should be on the stack */ return HANDLER_GO_ON; } }
// p = process.openv(shellname, argv, outfile, errfile) tb_int_t xm_process_openv(lua_State* lua) { // check tb_assert_and_check_return_val(lua, 0); // check table if (!lua_istable(lua, 2)) { // error lua_pushfstring(lua, "invalid argv type(%s) for process.openv", luaL_typename(lua, 2)); lua_error(lua); return 0; } // get the output and error file tb_char_t const* shellname = lua_tostring(lua, 1); tb_char_t const* outfile = lua_tostring(lua, 3); tb_char_t const* errfile = lua_tostring(lua, 4); tb_check_return_val(shellname, 0); // get the arguments count tb_long_t argn = lua_objlen(lua, 2); tb_check_return_val(argn >= 0, 0); // get arguments tb_size_t argi = 0; tb_char_t const** argv = tb_nalloc0_type(1 + argn + 1, tb_char_t const*); tb_check_return_val(argv, 0); // fill arguments argv[0] = shellname; for (argi = 0; argi < argn; argi++) { // get argv[i] lua_pushinteger(lua, argi + 1); lua_gettable(lua, 2); // is string? if (lua_isstring(lua, -1)) { // pass this argument argv[1 + argi] = lua_tostring(lua, -1); } else { // error lua_pushfstring(lua, "invalid argv[%ld] type(%s) for process.openv", argi, luaL_typename(lua, -1)); lua_error(lua); } // pop it lua_pop(lua, 1); } // init attributes tb_process_attr_t attr = {0}; // redirect stdout? if (outfile) { // redirect stdout to file attr.outfile = outfile; attr.outmode = TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_APPEND; // remove the outfile first if (tb_file_info(outfile, tb_null)) tb_file_remove(outfile); } // redirect stderr? if (errfile) { // redirect stderr to file attr.errfile = errfile; attr.errmode = TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_APPEND; // remove the errfile first if (tb_file_info(errfile, tb_null)) tb_file_remove(errfile); } // init process tb_process_ref_t process = tb_process_init(shellname, argv, &attr); if (process) lua_pushlightuserdata(lua, process); else lua_pushnil(lua); // exit argv if (argv) tb_free(argv); argv = tb_null; // ok return 1; }
X509_REVOKED *openssl_X509_REVOKED(lua_State*L, int snidx, int timeidx, int reasonidx) { X509_REVOKED *revoked = X509_REVOKED_new(); const char* serial = luaL_checkstring(L, snidx); BIGNUM * bn = NULL; ASN1_TIME *tm = NULL; int reason = 0; ASN1_INTEGER *it = NULL; if(!BN_hex2bn(&bn, serial)) { goto end; }; if(lua_isnumber(L,timeidx) || lua_isnoneornil(L, timeidx)) { time_t t; time(&t); t = luaL_optinteger(L, 3, (lua_Integer)t); tm = ASN1_TIME_new(); ASN1_TIME_set(tm,t); } else if(lua_isstring(L, timeidx)) { } else { goto end; } if(lua_isnumber(L, reasonidx) || lua_isnoneornil(L, reasonidx)) { reason = luaL_optinteger(L, reasonidx, 0); if(reason < 0 || reason >= reason_num) { goto end; } } else if(lua_isstring(L, reasonidx)) { const char* s = lua_tostring(L, reasonidx); reason = openssl_get_revoke_reason(s); if(reason < 0 || reason >= reason_num) { goto end; } } else { goto end; }; it = BN_to_ASN1_INTEGER(bn,NULL); X509_REVOKED_set_revocationDate(revoked, tm); X509_REVOKED_set_serialNumber(revoked, it); #if OPENSSL_VERSION_NUMBER > 0x10000000L revoked->reason = reason; #else /* { ASN1_ENUMERATED * e = ASN1_ENUMERATED_new(); X509_EXTENSION * ext = X509_EXTENSION_new(); ASN1_ENUMERATED_set(e, reason); X509_EXTENSION_set_object(ext, OBJ_nid2obj(NID_crl_reason)); X509_EXTENSION_set_data(ext,e); if(!revoked->extensions) revoked->extensions = sk_X509_EXTENSION_new_null(); X509_REVOKED_add_ext() sk_X509_REVOKED_push(revoked->extensions,ext); X509_EXTENSION_free(ext); ASN1_ENUMERATED_free(e); } */ #endif ASN1_TIME_free(tm); ASN1_INTEGER_free(it); BN_free(bn); return revoked; end: X509_REVOKED_free(revoked); ASN1_TIME_free(tm); ASN1_INTEGER_free(it); BN_free(bn); return NULL; }
static void integrity_check(const char *progname, enum modes progmode_num) { rpmts ts = NULL; rpmlua lua = NULL; char *spec_fn = NULL; char *proc_fn = NULL; char *pkey_fn = NULL; char *spec = NULL; char *proc = NULL; rpmiob spec_iob = NULL; rpmiob proc_iob = NULL; const char *result = NULL; const char *error = NULL; int xx; const char *progmode; int rc = INTEGRITY_ERROR; /* determine paths of integrity checking related files */ spec_fn = rpmExpand("%{?_integrity_spec_cfg}%{!?_integrity_spec_cfg:scripts/integrity.cfg}", NULL); if (spec_fn == NULL || spec_fn[0] == '\0') { integrity_check_message("ERROR: Integrity Configuration Specification file not configured.\n" "rpm: HINT: macro %%{_integrity_spec_cfg} not configured correctly.\n"); goto failure; } proc_fn = rpmExpand("%{?_integrity_proc_lua}%{!?_integrity_proc_lua:scripts/integrity.lua}", NULL); if (proc_fn == NULL || proc_fn[0] == '\0') { integrity_check_message("ERROR: Integrity Validation Processor file not configured.\n" "rpm: HINT: macro %%{_integrity_proc_lua} not configured correctly.\n"); goto failure; } pkey_fn = rpmExpand("%{?_integrity_pkey_pgp}%{!?_integrity_pkey_pgp:scripts/integrity.pgp}", NULL); if (pkey_fn == NULL || pkey_fn[0] == '\0') { integrity_check_message("ERROR: Integrity Autority Public-Key file not configured.\n" "rpm: HINT: macro %%{_integrity_pkey_pgp} not configured correctly.\n"); goto failure; } /* create RPM transaction environment and open RPM database */ ts = rpmtsCreate(); (void)rpmtsOpenDB(ts, O_RDONLY); /* check signature on integrity configuration specification file */ if (rpmnsProbeSignature(ts, spec_fn, NULL, pkey_fn, RPM_INTEGRITY_FP, 0) != RPMRC_OK) { integrity_check_message("ERROR: Integrity Configuration Specification file contains invalid signature.\n" "rpm: HINT: Check file \"%s\".\n", spec_fn); goto failure; } /* check signature on integrity validation processor file */ if (rpmnsProbeSignature(ts, proc_fn, NULL, pkey_fn, RPM_INTEGRITY_FP, 0) != RPMRC_OK) { integrity_check_message("ERROR: Integrity Validation Processor file contains invalid signature.\n" "rpm: HINT: Check file \"%s\".\n", proc_fn); goto failure; } /* load integrity configuration specification file */ xx = rpmiobSlurp(spec_fn, &spec_iob); if (!(xx == 0 && spec_iob != NULL)) { integrity_check_message("ERROR: Unable to load Integrity Configuration Specification file.\n" "rpm: HINT: Check file \"%s\".\n", spec_fn); goto failure; } spec = rpmiobStr(spec_iob); /* load integrity validation processor file */ xx = rpmiobSlurp(proc_fn, &proc_iob); if (!(xx == 0 && proc_iob != NULL)) { integrity_check_message("ERROR: Unable to load Integrity Validation Processor file.\n" "rpm: HINT: Check file \"%s\".\n", proc_fn); goto failure; } proc = rpmiobStr(proc_iob); /* provision program name and mode */ if (progname == NULL || progname[0] == '\0') progname = "rpm"; switch (progmode_num) { case MODE_QUERY: progmode = "query"; break; case MODE_VERIFY: progmode = "verify"; break; case MODE_CHECKSIG: progmode = "checksig"; break; case MODE_RESIGN: progmode = "resign"; break; case MODE_INSTALL: progmode = "install"; break; case MODE_ERASE: progmode = "erase"; break; case MODE_BUILD: progmode = "build"; break; case MODE_REBUILD: progmode = "rebuild"; break; case MODE_RECOMPILE: progmode = "recompile"; break; case MODE_TARBUILD: progmode = "tarbuild"; break; case MODE_REBUILDDB: progmode = "rebuilddb"; break; case MODE_UNKNOWN: progmode = "unknown"; break; default: progmode = "unknown"; break; } /* execute Integrity Validation Processor via Lua glue code */ lua = rpmluaNew(); rpmluaSetPrintBuffer(lua, 1); rpmluaextActivate(lua); lua_getfield(lua->L, LUA_GLOBALSINDEX, "integrity"); lua_getfield(lua->L, -1, "processor"); lua_remove(lua->L, -2); lua_pushstring(lua->L, progname); lua_pushstring(lua->L, progmode); lua_pushstring(lua->L, spec_fn); lua_pushstring(lua->L, spec); lua_pushstring(lua->L, proc_fn); lua_pushstring(lua->L, proc); #ifdef RPM_INTEGRITY_MV lua_pushstring(lua->L, RPM_INTEGRITY_MV); #else lua_pushstring(lua->L, "0"); #endif if (lua_pcall(lua->L, 7, 1, 0) != 0) { error = lua_isstring(lua->L, -1) ? lua_tostring(lua->L, -1) : "unknown error"; lua_pop(lua->L, 1); integrity_check_message("ERROR: Failed to execute Integrity Validation Processor.\n" "rpm: ERROR: Lua: %s.\n" "rpm: HINT: Check file \"%s\".\n", error, proc_fn); goto failure; } /* check Integrity Validation Processor results */ if (!lua_isstring(lua->L, -1)) { integrity_check_message("ERROR: Failed to fetch Integrity Validation Processor results.\n" "rpm: HINT: Check file \"%s\".\n", proc_fn); goto failure; } result = lua_tostring(lua->L, -1); if (strcmp(result, "OK") == 0) rc = INTEGRITY_OK; else if (strncmp(result, "WARNING:", 8) == 0) { rc = INTEGRITY_WARNING; integrity_check_message("%s\n", result); } else { rc = INTEGRITY_ERROR; integrity_check_message("%s\n", result); } /* cleanup processing */ failure: if (lua != NULL) rpmluaFree(lua); if (ts != NULL) (void)rpmtsFree(ts); ts = NULL; if (spec_iob != NULL) spec_iob = rpmiobFree(spec_iob); if (proc_iob != NULL) proc_iob = rpmiobFree(proc_iob); /* final result handling */ if (rc != INTEGRITY_OK) { if (isatty(STDIN_FILENO) || isatty(STDOUT_FILENO)) sleep(4); if (rc == INTEGRITY_ERROR) exit(42); } return; }
ngx_int_t ngx_http_lua_cache_loadfile(lua_State *L, const u_char *script, const u_char *cache_key, char **err, unsigned enabled) { int rc; u_char *p; u_char buf[NGX_HTTP_LUA_FILE_KEY_LEN + 1]; /* calculate digest of script file path */ dd("code cache enabled: %d", (int) enabled); if (enabled) { if (cache_key == NULL) { dd("CACHE file key not pre-calculated...calculating"); p = ngx_copy(buf, NGX_HTTP_LUA_FILE_TAG, NGX_HTTP_LUA_FILE_TAG_LEN); p = ngx_http_lua_digest_hex(p, script, ngx_strlen(script)); *p = '\0'; cache_key = buf; } else { dd("CACHE file key already pre-calculated"); } dd("XXX cache key for file: [%s]", cache_key); if (ngx_http_lua_cache_load_code(L, (char *) cache_key) == NGX_OK) { /* code chunk loaded from cache, sp++ */ dd("Code cache hit! cache key='%s', stack top=%d, file path='%s'", cache_key, lua_gettop(L), script); return NGX_OK; } dd("Code cache missed! cache key='%s', stack top=%d, file path='%s'", cache_key, lua_gettop(L), script); } /* load closure factory of script file to the top of lua stack, sp++ */ rc = ngx_http_lua_clfactory_loadfile(L, (char *) script); if (rc != 0) { /* Oops! error occured when loading Lua script */ if (rc == LUA_ERRMEM) { *err = "memory allocation error"; } else { if (lua_isstring(L, -1)) { *err = (char *) lua_tostring(L, -1); } else { *err = "syntax error"; } } return NGX_ERROR; } if (enabled) { /* store closure factory and gen new closure at the top of lua stack * to code cache */ rc = ngx_http_lua_cache_store_code(L, (char *) cache_key); if (rc != NGX_OK) { *err = "fail to generate new closure from the closure factory"; return NGX_ERROR; } } else { /* call closure factory to generate new closure */ rc = lua_pcall(L, 0, 1, 0); if (rc != 0) { dd("Error: failed to call closure factory!!"); return NGX_ERROR; } ngx_http_lua_clear_package_loaded(L); } return NGX_OK; }
static int _lua_chunkqueue_add_file(lua_State *L, gboolean tempfile) { liChunkQueue *cq; const char *filename; GString g_filename; size_t len; struct stat st; int fd, err; goffset start, length; luaL_checkany(L, 2); cq = li_lua_get_chunkqueue(L, 1); if (cq == NULL) return 0; if (!lua_isstring(L, 2)) { lua_pushliteral(L, "chunkqueue:add expects filename as first parameter"); lua_error(L); return -1; } filename = lua_tolstring(L, 2, &len); g_filename = li_const_gstring(filename, len); if (LI_HANDLER_GO_ON != li_stat_cache_get_sync(NULL, &g_filename, &st, &err, &fd)) { lua_pushliteral(L, "chunkqueue:add couldn't open file: "); lua_pushvalue(L, 2); lua_concat(L, 2); lua_error(L); return -1; } start = 0; length = st.st_size; if (lua_gettop(L) >= 3) { if (!lua_isnumber(L, 3)) { lua_pushliteral(L, "chunkqueue:add expects number (or nothing) as second parameter"); lua_error(L); close(fd); return -1; } start = lua_tonumber(L, 3); } if (lua_gettop(L) >= 4) { if (!lua_isnumber(L, 4)) { lua_pushliteral(L, "chunkqueue:add expects number (or nothing) as third parameter"); lua_error(L); close(fd); return -1; } length = lua_tonumber(L, 3); } if (start < 0 || start >= st.st_size || length < 0 || start + length > st.st_size) { lua_pushliteral(L, "chunkqueue:add: Invalid start/length values"); lua_error(L); close(fd); return -1; } if (tempfile) { li_chunkqueue_append_tempfile_fd(cq, g_string_new_len(filename, len), start, length, fd); } else { li_chunkqueue_append_file_fd(cq, NULL, start, length, fd); } return 0; }
int console_add_route(lua_State *L) { XBT_DEBUG("Adding route"); s_sg_platf_route_cbarg_t route; memset(&route,0,sizeof(route)); int type; /* allocating memory for the buffer, I think 2kB should be enough */ surfxml_bufferstack = xbt_new0(char, surfxml_bufferstack_size); lua_ensure(lua_istable(L, -1), "Bad Arguments to add a route. Should be a table with named arguments"); lua_pushstring(L,"src"); type = lua_gettable(L,-2); lua_ensure(type == LUA_TSTRING, "Attribute 'src' must be specified for any route and must be a string."); const char *srcName = lua_tostring(L, -1); route.src = sg_netcard_by_name_or_null(srcName); lua_ensure(route.src != nullptr, "Attribute 'src=%s' of route does not name a node.", srcName); lua_pop(L,1); lua_pushstring(L,"dest"); type = lua_gettable(L,-2); lua_ensure(type == LUA_TSTRING, "Attribute 'dest' must be specified for any route and must be a string."); const char *dstName = lua_tostring(L, -1); route.dst = sg_netcard_by_name_or_null(dstName); lua_ensure(route.dst != nullptr, "Attribute 'dst=%s' of route does not name a node.", dstName); lua_pop(L,1); lua_pushstring(L,"links"); type = lua_gettable(L,-2); lua_ensure(type == LUA_TSTRING, "Attribute 'links' must be specified for any route and must be a string (different links separated by commas or single spaces."); route.link_list = new std::vector<Link*>(); xbt_dynar_t names = xbt_str_split(lua_tostring(L, -1), ", \t\r\n"); if (xbt_dynar_is_empty(names)) { /* unique name */ route.link_list->push_back(Link::byName(lua_tostring(L, -1))); } else { // Several names separated by , \t\r\n unsigned int cpt; char *name; xbt_dynar_foreach(names, cpt, name) { if (strlen(name)>0) { Link *link = Link::byName(name); route.link_list->push_back(link); } } } lua_pop(L,1); /* We are relying on the XML bypassing mechanism since the corresponding sg_platf does not exist yet. * Et ouais mon pote. That's the way it goes. F34R. * * (Note that above this function, there is a #include statement. Is this * comment related to that statement?) */ lua_pushstring(L,"symmetrical"); lua_gettable(L,-2); if (lua_isstring(L, -1)) { const char* value = lua_tostring(L, -1); if (strcmp("YES", value) == 0) route.symmetrical = true; else route.symmetrical = false; } else { route.symmetrical = true; } lua_pop(L,1); route.gw_src = nullptr; route.gw_dst = nullptr; sg_platf_new_route(&route); return 0; }
JNIEXPORT jboolean JNICALL Java_m_lua_Lua_isString (JNIEnv* env, jobject thiz, jlong nativeObj, jint idx) { return (jboolean) lua_isstring((lua_State*) nativeObj, (int) idx); }
int console_add_ASroute(lua_State *L) { s_sg_platf_route_cbarg_t ASroute; memset(&ASroute,0,sizeof(ASroute)); lua_pushstring(L, "src"); lua_gettable(L, -2); const char *srcName = lua_tostring(L, -1); ASroute.src = sg_netcard_by_name_or_null(srcName); lua_ensure(ASroute.src != nullptr, "Attribute 'src=%s' of AS route does not name a node.", srcName); lua_pop(L, 1); lua_pushstring(L, "dst"); lua_gettable(L, -2); const char *dstName = lua_tostring(L, -1); ASroute.dst = sg_netcard_by_name_or_null(dstName); lua_ensure(ASroute.dst != nullptr, "Attribute 'dst=%s' of AS route does not name a node.", dstName); lua_pop(L, 1); lua_pushstring(L, "gw_src"); lua_gettable(L, -2); const char *name = lua_tostring(L, -1); ASroute.gw_src = sg_netcard_by_name_or_null(name); lua_ensure(ASroute.gw_src, "Attribute 'gw_src=%s' of AS route does not name a valid node", name); lua_pop(L, 1); lua_pushstring(L, "gw_dst"); lua_gettable(L, -2); name = lua_tostring(L, -1); ASroute.gw_dst = sg_netcard_by_name_or_null(name); lua_ensure(ASroute.gw_dst, "Attribute 'gw_dst=%s' of AS route does not name a valid node", name); lua_pop(L, 1); lua_pushstring(L,"links"); lua_gettable(L,-2); ASroute.link_list = new std::vector<Link*>(); xbt_dynar_t names = xbt_str_split(lua_tostring(L, -1), ", \t\r\n"); if (xbt_dynar_is_empty(names)) { /* unique name with no comma */ ASroute.link_list->push_back(Link::byName(lua_tostring(L, -1))); } else { // Several names separated by , \t\r\n unsigned int cpt; char *name; xbt_dynar_foreach(names, cpt, name) { if (strlen(name)>0) { Link *link = Link::byName(name); ASroute.link_list->push_back(link); } } } lua_pop(L,1); lua_pushstring(L,"symmetrical"); lua_gettable(L,-2); if (lua_isstring(L, -1)) { const char* value = lua_tostring(L, -1); if (strcmp("YES", value) == 0) ASroute.symmetrical = true; else ASroute.symmetrical = false; } else { ASroute.symmetrical = true; } lua_pop(L,1); sg_platf_new_route(&ASroute); return 0; }
static int js_generator_value(lua_State *L) { int max; int is_array; int no_vals; int type = lua_type(L, 2); switch ( type ) { case LUA_TNIL: return js_generator_null(L); case LUA_TNUMBER: return js_generator_number(L); case LUA_TBOOLEAN: return js_generator_boolean(L); case LUA_TSTRING: return js_generator_string(L); case LUA_TUSERDATA: if ( lua_topointer(L, 2) == js_null ) { return js_generator_null(L); } case LUA_TLIGHTUSERDATA: case LUA_TTABLE: case LUA_TFUNCTION: case LUA_TTHREAD: if ( luaL_getmetafield(L, 2, "__gen_json") ) { if ( lua_isfunction(L, -1) ) { lua_settop(L, 3); /* gen, obj, func */ lua_insert(L, 1); /* func, gen, obj */ lua_insert(L, 2); /* func, obj, gen */ lua_call(L, 2, 0); return 0; } lua_pop(L, 1); } /* Simply ignore it, perhaps we should warn? */ if ( type != LUA_TTABLE ) { js_generator_open_object(L); js_generator_close(L); return 0; } max = 0; is_array = 1; no_vals = 1; /* First iterate over the table to see if it is an array: */ lua_pushnil(L); while ( lua_next(L, 2) != 0 ) { no_vals = 0; if ( lua_type(L, -2) == LUA_TNUMBER ) { double num = lua_tonumber(L, -2); if ( num == floor(num) ) { if ( num > max ) max = num; } else { lua_pop(L, 2); is_array = 0; break; } } else if (lua_type(L, -2) == LUA_TSTRING && strncmp(lua_tostring(L, -2), "length", 6) == 0) { // ignore "length" } else { lua_pop(L, 2); is_array = 0; break; } lua_pop(L, 1); } if ( is_array && !no_vals ) { int i; js_generator_open_array(L); for ( i=0; i <= max; i++ ) { lua_pushinteger(L, i); lua_gettable(L, 2); /* RECURSIVE CALL: gen, obj, ?, val, func, gen, val */ lua_pushcfunction(L, js_generator_value); lua_pushvalue(L, 1); lua_pushvalue(L, -3); lua_call(L, 2, 0); lua_pop(L, 1); } } else { js_generator_open_object(L); lua_pushnil(L); while ( lua_next(L, 2) != 0 ) { /* gen, obj, ?, key, val, func, gen, key */ lua_pushcfunction(L, js_generator_string); lua_pushvalue(L, 1); if ( lua_isstring(L, -4) ) { lua_pushvalue(L, -4); } else { /* Must coerce into a string: */ lua_getglobal(L, "tostring"); lua_pushvalue(L, -5); lua_call(L, 1, 1); } /* support replacer */ lua_getfenv(L, 1); lua_getfield(L, -1, "replacer"); lua_remove(L, -2); if (!lua_isnil(L, -1)) { lua_pushvalue(L, 2); lua_pushvalue(L, -7); lua_pushvalue(L, -7); lua_call(L, 3, 1); if (lua_isnil(L, -1)) { lua_remove(L, -1); continue; } else { lua_replace(L, -5); } } else { lua_remove(L, -1); } /* push key */ lua_call(L, 2, 0); /* RECURSIVE CALL: gen, obj, ?, key, val, func, gen, val */ lua_pushcfunction(L, js_generator_value); lua_pushvalue(L, 1); lua_pushvalue(L, -3); lua_call(L, 2, 0); lua_pop(L, 1); } } js_generator_close(L); return 0; case LUA_TNONE: lua_pushfstring(L, "MissingArgument: second parameter to js_generator_value() must be defined at %s line %d", type, __FILE__, __LINE__); default: lua_pushfstring(L, "Unreachable: js_generator_value passed lua type (%d) not recognized at %s line %d", type, __FILE__, __LINE__); } /* Shouldn't get here: */ lua_error(L); return 0; }
// Lua: server:listen(port, addr, function(c)), socket:listen(port, addr) int net_listen( lua_State *L ) { lnet_userdata *ud = net_get_udata(L); if (!ud || ud->type == TYPE_TCP_CLIENT) return luaL_error(L, "invalid user data"); if (ud->pcb) return luaL_error(L, "already listening"); int stack = 2; uint16_t port = 0; const char *domain = "0.0.0.0"; if (lua_isnumber(L, stack)) port = lua_tointeger(L, stack++); if (lua_isstring(L, stack)) { size_t dl = 0; domain = luaL_checklstring(L, stack++, &dl); } ip_addr_t addr; if (!ipaddr_aton(domain, &addr)) return luaL_error(L, "invalid IP address"); if (ud->type == TYPE_TCP_SERVER) { if (lua_isfunction(L, stack) || lua_islightfunction(L, stack)) { lua_pushvalue(L, stack++); luaL_unref(L, LUA_REGISTRYINDEX, ud->server.cb_accept_ref); ud->server.cb_accept_ref = luaL_ref(L, LUA_REGISTRYINDEX); } else { return luaL_error(L, "need callback"); } } err_t err = ERR_OK; switch (ud->type) { case TYPE_TCP_SERVER: ud->tcp_pcb = tcp_new(); if (!ud->tcp_pcb) return luaL_error(L, "cannot allocate PCB"); ud->tcp_pcb->so_options |= SOF_REUSEADDR; err = tcp_bind(ud->tcp_pcb, &addr, port); if (err == ERR_OK) { tcp_arg(ud->tcp_pcb, ud); struct tcp_pcb *pcb = tcp_listen(ud->tcp_pcb); if (!pcb) { err = ERR_MEM; } else { ud->tcp_pcb = pcb; tcp_accept(ud->tcp_pcb, net_accept_cb); } } break; case TYPE_UDP_SOCKET: ud->udp_pcb = udp_new(); if (!ud->udp_pcb) return luaL_error(L, "cannot allocate PCB"); udp_recv(ud->udp_pcb, net_udp_recv_cb, ud); err = udp_bind(ud->udp_pcb, &addr, port); break; } if (err != ERR_OK) { switch (ud->type) { case TYPE_TCP_SERVER: tcp_close(ud->tcp_pcb); ud->tcp_pcb = NULL; break; case TYPE_UDP_SOCKET: udp_remove(ud->udp_pcb); ud->udp_pcb = NULL; break; } return lwip_lua_checkerr(L, err); } if (ud->self_ref == LUA_NOREF) { lua_pushvalue(L, 1); ud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX); } return 0; }
/* Draw fixed text */ static int Lua_fixedFontRender(lua_State *L) { if(!App_UsingDisplay) { fprintf(LuaLibrary_Log, "renderer.fixedText : need to call have useDisplay to true to get access to rendering functions\n"); Lua_requestClose = true; } if(!lua_isstring(L, -9)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need string for argument 1\n"); return 0; } if(!lua_isnumber(L, -8)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 2\n"); return 0; } if(!lua_isnumber(L, -7)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 3\n"); return 0; } if(!lua_isnumber(L, -6)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 4\n"); return 0; } if(!lua_isnumber(L, -5)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 5\n"); return 0; } if(!lua_isnumber(L, -4)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 6\n"); return 0; } if(!lua_isnumber(L, -3)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 7\n"); return 0; } if(!lua_isnumber(L, -2)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 8\n"); return 0; } if(!lua_isnumber(L, -1)) { fprintf(LuaLibrary_Log, "renderer.fixedText : need number for argument 9\n"); return 0; } double x = lua_tonumber(L, -8) + Lua_Window.x, y = lua_tonumber(L, -7) + Lua_Window.y; double width = lua_tonumber(L, -6), height = lua_tonumber(L, -5); if(x + width < Lua_Window.x || x > Lua_Window.z + Lua_Window.x || y + height < Lua_Window.y || y > Lua_Window.w + Lua_Window.y) return 0; if(x < Lua_Window.x) { double delta = Lua_Window.x - x; x = Lua_Window.x; width -= delta; } else if(x + width > Lua_Window.x + Lua_Window.z) { double delta = (x + width) - (Lua_Window.x + Lua_Window.z); width -= delta; } if(y < Lua_Window.y) { double delta = Lua_Window.y - y; y = Lua_Window.y; height -= delta; } else if(y + height > Lua_Window.y + Lua_Window.w) { double delta = (y + height) - (Lua_Window.y + Lua_Window.w); height -= delta; } struct Vector4f Color = { lua_tonumber(L, -4), lua_tonumber(L, -3), lua_tonumber(L, -2), lua_tonumber(L, -1) }; Font_FixedRender(DefaultFontManager, lua_tostring(L, -9), x, y, height, width, 1.0f, Color); return 0; }
int libretrodb_lua_to_rmsgpack_value(lua_State *L, int index, struct rmsgpack_dom_value * out) { size_t tmp_len; lua_Number tmp_num; struct rmsgpack_dom_value * tmp_value; int i, rv = -1; const char * tmp_string = NULL; char * tmp_buff = NULL; const int key_idx = -2; const int value_idx = -1; const int MAX_FIELDS = 100; out->type = RDT_MAP; out->val.map.len = 0; out->val.map.items = calloc(MAX_FIELDS, sizeof(struct rmsgpack_dom_pair)); lua_pushnil(L); while (lua_next(L, index - 1) != 0) { if (out->val.map.len > MAX_FIELDS) printf("skipping due to too many keys\n"); else if (!lua_isstring(L, key_idx)) printf("skipping non string key\n"); else if (lua_isnil(L, value_idx)) { /* Skipping nil value fields to save disk space */ } else { i = out->val.map.len; tmp_buff = strdup(lua_tostring(L, key_idx)); out->val.map.items[i].key.type = RDT_STRING; out->val.map.items[i].key.val.string.len = strlen(tmp_buff); out->val.map.items[i].key.val.string.buff = tmp_buff; tmp_value = &out->val.map.items[i].value; switch (lua_type(L, value_idx)) { case LUA_TNUMBER: tmp_num = lua_tonumber(L, value_idx); tmp_value->type = RDT_INT; tmp_value->val.int_ = tmp_num; break; case LUA_TBOOLEAN: tmp_value->type = RDT_BOOL; tmp_value->val.bool_ = lua_toboolean(L, value_idx); break; case LUA_TSTRING: tmp_buff = strdup(lua_tostring(L, value_idx)); tmp_value->type = RDT_STRING; tmp_value->val.string.len = strlen(tmp_buff); tmp_value->val.string.buff = tmp_buff; break; case LUA_TTABLE: lua_getfield(L, value_idx, "binary"); if (!lua_isstring(L, -1)) { lua_pop(L, 1); lua_getfield(L, value_idx, "uint"); if (!lua_isnumber(L, -1)) { lua_pop(L, 1); goto set_nil; } else { tmp_num = lua_tonumber(L, -1); tmp_value->type = RDT_UINT; tmp_value->val.uint_ = tmp_num; lua_pop(L, 1); } } else { tmp_string = lua_tolstring(L, -1, &tmp_len); tmp_buff = malloc(tmp_len); memcpy(tmp_buff, tmp_string, tmp_len); tmp_value->type = RDT_BINARY; tmp_value->val.binary.len = tmp_len; tmp_value->val.binary.buff = tmp_buff; lua_pop(L, 1); } break; default: set_nil: tmp_value->type = RDT_NULL; } out->val.map.len++; } lua_pop(L, 1); } #if 1 /* re-order to avoid random output each run */ struct rmsgpack_dom_pair* ordered_pairs = calloc(out->val.map.len, sizeof(struct rmsgpack_dom_pair)); struct rmsgpack_dom_pair* ordered_pairs_outp = ordered_pairs; const char* ordered_keys[] = { "name", "description", "rom_name", "size", "users", "releasemonth", "releaseyear", "rumble", "analog", "famitsu_rating", "edge_rating", "edge_issue", "edge_review", "enhancement_hw", "barcode", "esrb_rating", "elspa_rating", "pegi_rating", "cero_rating", "franchise", "developer", "publisher", "origin", "crc", "md5", "sha1", "serial" }; for(i = 0; i < (sizeof(ordered_keys)/sizeof(char*)); i++) { int j; for(j = 0; j < out->val.map.len; j++) { if(!strcmp(ordered_keys[i], out->val.map.items[j].key.val.string.buff)) { *ordered_pairs_outp++ = out->val.map.items[j]; break; } } } free(out->val.map.items); out->val.map.items = ordered_pairs; out->val.map.len = ordered_pairs_outp - ordered_pairs; #endif rv = 0; return rv; }
static int l_Quaternion_index(lua_State *L) { Quaternion* quaternion = lua_toquaternion(L, 1); auto numargs = lua_gettop(L); if (numargs > 2) { luaL_error(L, "LUA_ERROR: Wrong number of arguments, %d provided", numargs); } if (lua_isnumber(L, 2)) { integerType index = lua_tointeger(L, 2); lua_pop(L, 1); if (index < 1 || index > 4) { luaL_error(L, "LUA_ERROR: Index out of range --> %d", index); } switch(index) { case 1: lua_pushnumber(L, quaternion->w); break; case 2: lua_pushnumber(L, quaternion->v.x); break; case 3: lua_pushnumber(L, quaternion->v.y); break; case 4: lua_pushnumber(L, quaternion->v.z); break; } return 1; } else if (lua_isstring(L, 2)) { stringType sIndex = lua_tostring(L, 2); if (sIndex == "w") { lua_pushnumber(L, quaternion->w); } else if (sIndex == "x") { lua_pushnumber(L, quaternion->v.x); } else if (sIndex == "y") { lua_pushnumber(L, quaternion->v.y); } else if (sIndex == "z") { lua_pushnumber(L, quaternion->v.z); } else { //get the metafields luaL_getmetatable(L, LUA_USERDATA_QUATERNION); lua_getfield(L, -1, sIndex.c_str()); } return 1; } else { luaL_error(L, "LUA_ERROR: Incorrect type"); return 0; } return 0; }
/* args: const char *className const char *methodName LUA_TABLE args const char *sig */ int CCLuaJavaBridge::callJavaStaticMethod(lua_State *L) { if (!lua_isstring(L, -4) || !lua_isstring(L, -3) || !lua_istable(L, -2) || !lua_isstring(L, -1)) { lua_pushboolean(L, 0); lua_pushinteger(L, LUAJ_ERR_INVALID_SIGNATURES); return 2; } LOGD("%s", "CCLuaJavaBridge::callJavaStaticMethod(lua_State *L)"); const char *className = lua_tostring(L, -4); const char *methodName = lua_tostring(L, -3); const char *methodSig = lua_tostring(L, -1); CallInfo call(className, methodName, methodSig); if (!call.isValid()) { LOGD("CCLuaJavaBridge::callJavaStaticMethod(\"%s\", \"%s\", args, \"%s\") CHECK FAILURE, ERROR CODE: %d", className, methodName, methodSig, call.getErrorCode()); lua_pushboolean(L, 0); lua_pushinteger(L, call.getErrorCode()); return 2; } // check args lua_pop(L, 1); /* L: args */ int count = fetchArrayElements(L, -1); /* L: args e1 e2 e3 e4 ... */ jvalue *args = NULL; if (count > 0) { args = new jvalue[count]; for (int i = count - 1; i >= 0; --i) { int index = -count + i; switch (call.argumentTypeAtIndex(i)) { case TypeInteger: if (lua_isfunction(L, -1)) { args[i].i = retainLuaFunction(L, -1, NULL); } else { args[i].i = (int)lua_tonumber(L, -1); } break; case TypeFloat: args[i].f = lua_tonumber(L, -1); break; case TypeBoolean: args[i].z = lua_toboolean(L, -1) != 0 ? JNI_TRUE : JNI_FALSE; break; case TypeVector: args[i].l = CCLuaJavaBridge::checkVector(L); break; case TypeMap: args[i].l = CCLuaJavaBridge::checkHashMap(L); break; case TypeArrayList: args[i].l = CCLuaJavaBridge::checkArrayList(L); break; case TypeString: default: args[i].l = call.getEnv()->NewStringUTF(lua_tostring(L, -1)); break; } lua_pop(L, 1); } //lua_pop(L, count); /* L: args */ } bool success = args ? call.executeWithArgs(args) : call.execute(); if (args) delete []args; if (!success) { LOGD("CCLuaJavaBridge::callJavaStaticMethod(\"%s\", \"%s\", args, \"%s\") EXECUTE FAILURE, ERROR CODE: %d", className, methodName, methodSig, call.getErrorCode()); lua_pushboolean(L, 0); lua_pushinteger(L, call.getErrorCode()); return 2; } LOGD("CCLuaJavaBridge::callJavaStaticMethod(\"%s\", \"%s\", args, \"%s\") SUCCESS", className, methodName, methodSig); lua_pushboolean(L, 1); return 1 + call.pushReturnValue(L); }
void lua_call_function(t_jit_gl_lua *x, const char *func, const char *sig, ...) { va_list vl; int narg, nres; /* number of arguments and results */ va_start(vl, sig); lua_getglobal(x->lua, func); /* push function */ /****************************** push arguments */ for(narg = 0; *sig; narg++) { /* check stack space */ luaL_checkstack(x->lua, 1, "too many arguments"); switch (*sig++) { case 'd': /* double argument */ lua_pushnumber(x->lua, va_arg(vl, double)); break; case 'i': /* int argument */ lua_pushinteger(x->lua, va_arg(vl, int)); break; case 's': /* string argument */ lua_pushstring(x->lua, va_arg(vl, char *)); break; case '>': /* end of arguments */ goto endargs; default: error("invalid option (%c)", *(sig - 1)); } } endargs: nres = strlen(sig); /* number of expected results */ /* do the call */ if(lua_pcall(x->lua, narg, nres, 0) != 0) { error("error calling %s: %s", func, lua_tostring(x->lua, -1)); } /****************************** retrieve results */ nres = -nres; /* stack index of first result */ while(*sig) { /* repeat for each result */ switch(*sig++) { case 'd': /* double result */ if(! lua_isnumber(x->lua, nres)) { error("wrong result type"); } *va_arg(vl, double *) = lua_tonumber(x->lua, nres); break; case 'i': /* int result */ if(! lua_isnumber(x->lua, nres)) { error("wrong result type"); } *va_arg(vl, int *) = lua_tointeger(x->lua, nres); break; case 's': /* string result */ if(! lua_isstring(x->lua, nres)) { error("wrong result type"); } *va_arg(vl, const char **) = lua_tostring(x->lua, nres); break; default: error("invalid option (%c)", *(sig -1)); } nres++; } va_end(vl); }
void Value::fillTable(LuaState& L, int index, Value& value) { // Push a reference to the table on to the top of the stack lua_pushvalue(L, index); // Push a nil value onto the stack after the table // When the iterator is nil, we know the table is empty and we can stop lua_pushnil(L); while (lua_next(L, -2)) { // TODO: change to unique_ptr Key *key; lua_pushvalue(L, -2); if (lua_isboolean(L, -1)) { key = new Key(static_cast<bool>(lua_toboolean(L, -1))); } else if (lua_isnumber(L, -1)) { key = new Key(lua_tonumber(L, -1)); } else { key = new Key(lua_tostring(L, -1)); } // -1 contains the key // -2 contains the value if (lua_istable(L, -2)) { // If the indeces are numbers, it's a plain array, not an associative one fillTable(L, -2, value[*key]); } else { if (lua_isboolean(L, -2)) { // Read in a boolean value value[*key] = static_cast<bool>(lua_toboolean(L, -2)); } else if (lua_isnumber(L, -2)) { // Read in a number value value[*key] = lua_tonumber(L, -2); } else if (lua_isstring(L, -2)) { // Read in a string value value[*key] = lua_tostring(L, -2); } } lua_pop(L, 2); delete key; } lua_pop(L, 1); }
/** * @upvalue z_stream - Memory for the z_stream. * @upvalue remainder - Any remainder from the last deflate call. * * @param string - "print" to deflate stream. * @param int - flush output buffer? Z_SYNC_FLUSH, Z_FULL_FLUSH, or Z_FINISH. * * if no params, terminates the stream (as if we got empty string and Z_FINISH). */ static int lz_filter_impl(lua_State *L, int (*filter)(z_streamp, int), int (*end)(z_streamp), char* name) { int flush = Z_NO_FLUSH, result; z_stream* stream; luaL_Buffer buff; size_t avail_in; if ( filter == deflate ) { const char *const opts[] = { "none", "sync", "full", "finish", NULL }; flush = luaL_checkoption(L, 2, opts[0], opts); if ( flush ) flush++; /* Z_NO_FLUSH(0) Z_SYNC_FLUSH(2), Z_FULL_FLUSH(3), Z_FINISH (4) */ /* No arguments or nil, we are terminating the stream: */ if ( lua_gettop(L) == 0 || lua_isnil(L, 1) ) { flush = Z_FINISH; } } stream = (z_stream*)lua_touserdata(L, lua_upvalueindex(1)); if ( stream == NULL ) { if ( lua_gettop(L) >= 1 && lua_isstring(L, 1) ) { lua_pushfstring(L, "IllegalState: calling %s function when stream was previously closed", name); lua_error(L); } lua_pushstring(L, ""); lua_pushboolean(L, 1); return 2; /* Ignore duplicate calls to "close". */ } luaL_buffinit(L, &buff); if ( lua_gettop(L) > 1 ) lua_pushvalue(L, 1); if ( lua_isstring(L, lua_upvalueindex(2)) ) { lua_pushvalue(L, lua_upvalueindex(2)); if ( lua_gettop(L) > 1 && lua_isstring(L, -2) ) { lua_concat(L, 2); } } /* Do the actual deflate'ing: */ if (lua_gettop(L) > 0) { stream->next_in = (unsigned char*)lua_tolstring(L, -1, &avail_in); } else { stream->next_in = NULL; avail_in = 0; } stream->avail_in = avail_in; if ( ! stream->avail_in && ! flush ) { /* Passed empty string, make it a noop instead of erroring out. */ lua_pushstring(L, ""); lua_pushboolean(L, 0); lua_pushinteger(L, stream->total_in); lua_pushinteger(L, stream->total_out); return 4; } do { stream->next_out = (unsigned char*)luaL_prepbuffer(&buff); stream->avail_out = LUAL_BUFFERSIZE; result = filter(stream, flush); if ( Z_BUF_ERROR != result ) { /* Ignore Z_BUF_ERROR since that just indicates that we * need a larger buffer in order to proceed. Thanks to * Tobias Markmann for finding this bug! */ lz_assert(L, result, stream, __FILE__, __LINE__); } luaL_addsize(&buff, LUAL_BUFFERSIZE - stream->avail_out); } while ( stream->avail_out == 0 ); /* Need to do this before we alter the stack: */ luaL_pushresult(&buff); /* Save remainder in lua_upvalueindex(2): */ if ( NULL != stream->next_in ) { lua_pushlstring(L, (char*)stream->next_in, stream->avail_in); lua_replace(L, lua_upvalueindex(2)); } /* "close" the stream/remove finalizer: */ if ( result == Z_STREAM_END ) { /* Clear-out the metatable so end is not called twice: */ lua_pushnil(L); lua_setmetatable(L, lua_upvalueindex(1)); /* nil the upvalue: */ lua_pushnil(L); lua_replace(L, lua_upvalueindex(1)); /* Close the stream: */ lz_assert(L, end(stream), stream, __FILE__, __LINE__); lua_pushboolean(L, 1); } else { lua_pushboolean(L, 0); } lua_pushinteger(L, stream->total_in); lua_pushinteger(L, stream->total_out); return 4; }
static int planetL_getBackend( lua_State *L, int landable ) { int i; int *factions; int nfactions; char **planets; int nplanets; const char *rndplanet; LuaSystem luasys; LuaFaction f; Planet *pnt; StarSystem *sys; char *sysname; rndplanet = NULL; planets = NULL; nplanets = 0; /* If boolean return random. */ if (lua_isboolean(L,1)) { pnt = planet_get( space_getRndPlanet(landable, 0, NULL) ); lua_pushplanet(L,planet_index( pnt )); luasys = system_index( system_get( planet_getSystem(pnt->name) ) ); lua_pushsystem(L,luasys); return 2; } /* Get a planet by faction */ else if (lua_isfaction(L,1)) { f = lua_tofaction(L,1); planets = space_getFactionPlanet( &nplanets, &f, 1, landable ); } /* Get a planet by name */ else if (lua_isstring(L,1)) { rndplanet = lua_tostring(L,1); if (landable) { pnt = planet_get( rndplanet ); if (pnt == NULL) { NLUA_ERROR(L, _("Planet '%s' not found in stack"), rndplanet); return 0; } /* Check if can land. */ planet_updateLand( pnt ); if (!pnt->can_land) return 0; } } /* Get a planet from faction list */ else if (lua_istable(L,1)) { /* Get table length and preallocate. */ nfactions = (int) lua_objlen(L,1); factions = malloc( sizeof(int) * nfactions ); /* Load up the table. */ lua_pushnil(L); i = 0; while (lua_next(L, -2) != 0) { if (lua_isfaction(L, -1)) factions[i++] = lua_tofaction(L, -1); lua_pop(L,1); } /* get the planets */ planets = space_getFactionPlanet( &nplanets, factions, nfactions, landable ); free(factions); } else NLUA_INVALID_PARAMETER(L); /* Bad Parameter */ /* No suitable planet found */ if ((rndplanet == NULL) && ((planets == NULL) || nplanets == 0)) return 0; /* Pick random planet */ else if (rndplanet == NULL) { planets = (char**) arrayShuffle( (void**)planets, nplanets ); for (i=0; i<nplanets; i++) { if (landable) { /* Check landing. */ pnt = planet_get( planets[i] ); if (pnt == NULL) continue; planet_updateLand( pnt ); if (!pnt->can_land) continue; } rndplanet = planets[i]; break; } free(planets); } /* Push the planet */ pnt = planet_get(rndplanet); /* The real planet */ if (pnt == NULL) { NLUA_ERROR(L, _("Planet '%s' not found in stack"), rndplanet); return 0; } sysname = planet_getSystem(rndplanet); if (sysname == NULL) { NLUA_ERROR(L, _("Planet '%s' is not placed in a system"), rndplanet); return 0; } sys = system_get( sysname ); if (sys == NULL) { NLUA_ERROR(L, _("Planet '%s' can't find system '%s'"), rndplanet, sysname); return 0; } lua_pushplanet(L,planet_index( pnt )); luasys = system_index( sys ); lua_pushsystem(L,luasys); return 2; }
static int openssl_cms_encrypt(lua_State *L) { STACK_OF(X509)* encerts = openssl_sk_x509_fromtable(L, 1); BIO* in = load_bio_object(L, 2); const EVP_CIPHER* ciphers = get_cipher(L, 3, NULL); unsigned int flags = luaL_optint(L, 4, 0); int ret = 0; CMS_ContentInfo *cms = CMS_encrypt(encerts, in, ciphers, flags); CMS_RecipientInfo *recipient; if (cms) { if (lua_istable(L, 5)) { lua_getfield(L, 5, "key"); lua_getfield(L, 5, "keyid"); if (lua_isstring(L, -1) && lua_isstring(L, -2)) { size_t keylen, keyidlen; const char* key = luaL_checklstring(L, -2, &keylen); const char* keyid = luaL_checklstring(L, -1, &keyidlen); key = memdup(key, keylen); keyid = memdup(keyid, keyidlen); recipient = CMS_add0_recipient_key(cms, NID_undef, (unsigned char*)key, keylen, (unsigned char*)keyid, keyidlen, NULL, NULL, NULL); if (!recipient) ret = 0; } else if (!lua_isnil(L, -1) || !lua_isnil(L, -2)) { luaL_argerror(L, 5, "key and keyid field must be string"); } else ret = 1; lua_pop(L, 2); if (ret) { lua_getfield(L, 5, "password"); if (lua_isstring(L, -1)) { unsigned char*passwd = (unsigned char*)lua_tostring(L, -1); recipient = CMS_add0_recipient_password(cms, -1, NID_undef, NID_undef, passwd, -1, NULL); if (!recipient) ret = 0; } else if (!lua_isnil(L, -1)) { luaL_argerror(L, 5, "password field must be string"); } lua_pop(L, 1); } } if (ret) { if (flags & CMS_STREAM) ret = CMS_final(cms, in, NULL, flags); } } if (ret) { PUSH_OBJECT(cms, "openssl.cms"); return 1; } return openssl_pushresult(L, ret); }
// hud_change(self, id, stat, data) int ObjectRef::l_hud_change(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; u32 id = lua_isnumber(L, 2) ? lua_tonumber(L, 2) : -1; HudElement *e = player->getHud(id); if (!e) return 0; HudElementStat stat = HUD_STAT_NUMBER; if (lua_isstring(L, 3)) { int statint; std::string statstr = lua_tostring(L, 3); stat = string_to_enum(es_HudElementStat, statint, statstr) ? (HudElementStat)statint : HUD_STAT_NUMBER; } void *value = NULL; switch (stat) { case HUD_STAT_POS: e->pos = read_v2f(L, 4); value = &e->pos; break; case HUD_STAT_NAME: e->name = luaL_checkstring(L, 4); value = &e->name; break; case HUD_STAT_SCALE: e->scale = read_v2f(L, 4); value = &e->scale; break; case HUD_STAT_TEXT: e->text = luaL_checkstring(L, 4); value = &e->text; break; case HUD_STAT_NUMBER: e->number = luaL_checknumber(L, 4); value = &e->number; break; case HUD_STAT_ITEM: e->item = luaL_checknumber(L, 4); value = &e->item; break; case HUD_STAT_DIR: e->dir = luaL_checknumber(L, 4); value = &e->dir; break; case HUD_STAT_ALIGN: e->align = read_v2f(L, 4); value = &e->align; break; case HUD_STAT_OFFSET: e->offset = read_v2f(L, 4); value = &e->offset; break; case HUD_STAT_WORLD_POS: e->world_pos = read_v3f(L, 4); value = &e->world_pos; break; case HUD_STAT_SIZE: e->size = read_v2s32(L, 4); value = &e->size; break; } getServer(L)->hudChange(player, id, stat, value); lua_pushboolean(L, true); return 1; }
// TODO: Implement, verify, and rename unknown 5th parameter void Lua_V2::PlayActorChore() { lua_Object actorObj = lua_getparam(1); lua_Object choreObj = lua_getparam(2); lua_Object costumeObj = lua_getparam(3); lua_Object modeObj = lua_getparam(4); /* lua_Object paramObj = */ lua_getparam(5); if (!lua_isuserdata(actorObj) || lua_tag(actorObj) != MKTAG('A','C','T','R')) return; Actor *actor = getactor(actorObj); if (!lua_isstring(choreObj) || !lua_isstring(costumeObj)) lua_pushnil(); bool mode = false; // float param = 0.0; if (!lua_isnil(modeObj)) { if (lua_getnumber(modeObj) != 0.0) mode = true; //if (!lua_isnil(paramObj)) // if (lua_isnumber(paramObj)) // param = lua_getnumber(paramObj); } const char *choreName = lua_getstring(choreObj); const char *costumeName = lua_getstring(costumeObj); Costume *costume; // If a new wear chore is set and it uses a different costume than the // current one and neither of them is the shadow costume stop all active // chores and remove the old costume before setting the new one. // // This is necessary, because always the last costume on the stack, even // if it is not active, is returned by getCurrentCostume(). This would // cause an issue if the costumes would have different joints and the lua // code would consider a different costume active than the C code. if (0 == strncmp("wear_", choreName, 5)) { if (0 != strncmp("fx/dumbshadow.cos", costumeName, 17)) { if (actor->getCurrentCostume() != NULL && actor->getCurrentCostume()->getFilename() != "fx/dumbshadow.cos" && actor->getCurrentCostume()->getFilename().compareToIgnoreCase(costumeName) != 0) { actor->stopAllChores(); actor->setRestChore(-1, NULL); actor->setWalkChore(-1, NULL); actor->setTurnChores(-1, -1, NULL); actor->setMumbleChore(-1, NULL); actor->popCostume(); } } } if (!findCostume(costumeObj, actor, &costume)) return; EMIChore *chore = (EMIChore *)costume->getChore(choreName); if (0 == strncmp("wear_", choreName, 5)) { actor->setLastWearChore(costume->getChoreId(choreName), costume); } if (mode) { costume->playChoreLooping(choreName); } else { costume->playChore(choreName); } if (chore) { lua_pushusertag(chore->getId(), MKTAG('C','H','O','R')); } else { lua_pushnil(); } }