static int factor__tostring (lua_State *L) { lua_pushfstring(L, "factor: %p", lua_touserdata(L, 1)); return 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 _sock_tostring(lua_State *L) { socket_t *sock = _getsock(L, 1); lua_pushfstring(L, "socket: %p", sock); return 1; }
static int lc_local_addresses(lua_State *L) { #ifndef _WIN32 /* Link-local IPv4 addresses; see RFC 3927 and RFC 5735 */ const long ip4_linklocal = htonl(0xa9fe0000); /* 169.254.0.0 */ const long ip4_mask = htonl(0xffff0000); struct ifaddrs *addr = NULL, *a; #endif int n = 1; int type = luaL_checkoption(L, 1, "both", type_strings); const char link_local = lua_toboolean(L, 2); /* defaults to 0 (false) */ const char ipv4 = (type == 0 || type == 1); const char ipv6 = (type == 0 || type == 2); #ifndef _WIN32 if (getifaddrs(&addr) < 0) { lua_pushnil(L); lua_pushfstring(L, "getifaddrs failed (%d): %s", errno, strerror(errno)); return 2; } #endif lua_newtable(L); #ifndef _WIN32 for (a = addr; a; a = a->ifa_next) { int family; char ipaddr[INET6_ADDRSTRLEN]; const char *tmp = NULL; if (a->ifa_addr == NULL || a->ifa_flags & IFF_LOOPBACK) continue; family = a->ifa_addr->sa_family; if (ipv4 && family == AF_INET) { struct sockaddr_in *sa = (struct sockaddr_in *)a->ifa_addr; if (!link_local &&((sa->sin_addr.s_addr & ip4_mask) == ip4_linklocal)) continue; tmp = inet_ntop(family, &sa->sin_addr, ipaddr, sizeof(ipaddr)); } else if (ipv6 && family == AF_INET6) { struct sockaddr_in6 *sa = (struct sockaddr_in6 *)a->ifa_addr; if (!link_local && IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) continue; if (IN6_IS_ADDR_V4MAPPED(&sa->sin6_addr) || IN6_IS_ADDR_V4COMPAT(&sa->sin6_addr)) continue; tmp = inet_ntop(family, &sa->sin6_addr, ipaddr, sizeof(ipaddr)); } if (tmp != NULL) { lua_pushstring(L, tmp); lua_rawseti(L, -2, n++); } /* TODO: Error reporting? */ } freeifaddrs(addr); #else if (ipv4) { lua_pushstring(L, "0.0.0.0"); lua_rawseti(L, -2, n++); } if (ipv6) { lua_pushstring(L, "::"); lua_rawseti(L, -2, n++); } #endif return 1; }
static int queryuserdata_mtcall(lua_State *l) { lua_settop(l, 1); //[u] assert(lua_type(l, 1) == LUA_TUSERDATA); struct queryuserdata *ud = (struct queryuserdata *)lua_touserdata(l, 1); assert(ud != NULL); if(ud->stmt == NULL) { lua_pushnil(l); //[u_] return 1; } int rc = sqlite3_step(ud->stmt); if(rc == SQLITE_DONE) { sqlite3_finalize(ud->stmt); ud->stmt = NULL; lua_pushnil(l); //[u_] return 1; } if(rc != SQLITE_ROW) { lua_pushfstring(l, "Failed to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(ud->stmt))); sqlite3_finalize(ud->stmt); ud->stmt = NULL; return lua_error(l); } assert(rc == SQLITE_ROW); lua_newtable(l); //[ut] int col = sqlite3_column_count(ud->stmt) - 1; while(col >= 0) { switch(sqlite3_column_type(ud->stmt, col)) { case SQLITE_NULL: lua_pushnil(l); break; case SQLITE_INTEGER: case SQLITE_FLOAT: lua_pushnumber(l, sqlite3_column_double(ud->stmt, col)); break; case SQLITE_TEXT: lua_pushlstring(l, (const char *)sqlite3_column_text(ud->stmt, col), sqlite3_column_bytes(ud->stmt, col)); break; case SQLITE_BLOB: lua_pushlstring(l, (const char *)sqlite3_column_blob(ud->stmt, col), sqlite3_column_bytes(ud->stmt, col)); break; default: assert(0); return luaL_error(l, "Logic Error: unknown col type"); } //[ut?] lua_pushvalue(l, -1); //[ut??] if(ud->intkey) { lua_rawseti(l, -3, col+1); //[ut?] } else { lua_pop(l, 1); //[ut?] } if(ud->assockey) { lua_setfield(l, -2, sqlite3_column_name(ud->stmt, col)); //[ut] } else { lua_pop(l, 1); //[ut] } --col; } return 1; }
static int ngx_stream_lua_socket_udp_setpeername(lua_State *L) { ngx_stream_session_t *s; ngx_stream_lua_ctx_t *ctx; ngx_str_t host; int port; ngx_resolver_ctx_t *rctx, temp; int saved_top; int n; u_char *p; size_t len; ngx_url_t url; ngx_int_t rc; ngx_stream_lua_srv_conf_t *lscf; ngx_stream_lua_udp_connection_t *uc; int timeout; ngx_stream_lua_co_ctx_t *coctx; ngx_stream_lua_socket_udp_upstream_t *u; /* * TODO: we should probably accept an extra argument to setpeername() * to allow the user bind the datagram unix domain socket himself, * which is necessary for systems without autobind support. */ n = lua_gettop(L); if (n != 2 && n != 3) { return luaL_error(L, "ngx.socket.udp setpeername: expecting 2 or 3 " "arguments (including the object), but seen %d", n); } s = ngx_stream_lua_get_session(L); if (s == NULL) { return luaL_error(L, "no session found"); } ctx = ngx_stream_get_module_ctx(s, ngx_stream_lua_module); if (ctx == NULL) { return luaL_error(L, "no ctx found"); } ngx_stream_lua_check_context(L, ctx, NGX_STREAM_LUA_CONTEXT_CONTENT | NGX_STREAM_LUA_CONTEXT_TIMER); luaL_checktype(L, 1, LUA_TTABLE); p = (u_char *) luaL_checklstring(L, 2, &len); host.data = ngx_palloc(s->connection->pool, len + 1); if (host.data == NULL) { return luaL_error(L, "no memory"); } host.len = len; ngx_memcpy(host.data, p, len); host.data[len] = '\0'; if (n == 3) { port = luaL_checkinteger(L, 3); if (port < 0 || port > 65536) { lua_pushnil(L); lua_pushfstring(L, "bad port number: %d", port); return 2; } } else { /* n == 2 */ port = 0; } lua_rawgeti(L, 1, SOCKET_CTX_INDEX); u = lua_touserdata(L, -1); lua_pop(L, 1); if (u) { if (u->session && u->session != s) { return luaL_error(L, "bad session"); } if (u->waiting) { lua_pushnil(L); lua_pushliteral(L, "socket busy"); return 2; } if (u->udp_connection.connection) { ngx_log_debug0(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, "stream lua udp socket reconnect without " "shutting down"); ngx_stream_lua_socket_udp_finalize(s, u); } ngx_log_debug0(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, "stream lua reuse socket upstream ctx"); } else { u = lua_newuserdata(L, sizeof(ngx_stream_lua_socket_udp_upstream_t)); if (u == NULL) { return luaL_error(L, "no memory"); } #if 1 lua_pushlightuserdata(L, &ngx_stream_lua_udp_udata_metatable_key); lua_rawget(L, LUA_REGISTRYINDEX); lua_setmetatable(L, -2); #endif lua_rawseti(L, 1, SOCKET_CTX_INDEX); } ngx_memzero(u, sizeof(ngx_stream_lua_socket_udp_upstream_t)); u->session = s; /* set the controlling session */ lscf = ngx_stream_get_module_srv_conf(s, ngx_stream_lua_module); u->conf = lscf; uc = &u->udp_connection; uc->log = *s->connection->log; dd("lua peer connection log: %p", &uc->log); lua_rawgeti(L, 1, SOCKET_TIMEOUT_INDEX); timeout = (ngx_int_t) lua_tointeger(L, -1); lua_pop(L, 1); if (timeout > 0) { u->read_timeout = (ngx_msec_t) timeout; } else { u->read_timeout = u->conf->read_timeout; } ngx_memzero(&url, sizeof(ngx_url_t)); url.url.len = host.len; url.url.data = host.data; url.default_port = (in_port_t) port; url.no_resolve = 1; if (ngx_parse_url(s->connection->pool, &url) != NGX_OK) { lua_pushnil(L); if (url.err) { lua_pushfstring(L, "failed to parse host name \"%s\": %s", host.data, url.err); } else { lua_pushfstring(L, "failed to parse host name \"%s\"", host.data); } return 2; } u->resolved = ngx_pcalloc(s->connection->pool, sizeof(ngx_stream_lua_resolved_t)); if (u->resolved == NULL) { return luaL_error(L, "no memory"); } if (url.addrs && url.addrs[0].sockaddr) { ngx_log_debug0(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, "stream lua udp socket network address given directly"); u->resolved->sockaddr = url.addrs[0].sockaddr; u->resolved->socklen = url.addrs[0].socklen; u->resolved->naddrs = 1; u->resolved->host = url.addrs[0].name; } else { u->resolved->host = host; u->resolved->port = (in_port_t) port; } if (u->resolved->sockaddr) { rc = ngx_stream_lua_socket_resolve_retval_handler(s, u, L); if (rc == NGX_AGAIN) { return lua_yield(L, 0); } return rc; } temp.name = host; rctx = ngx_resolve_start(lscf->resolver, &temp); if (rctx == NULL) { u->ft_type |= NGX_STREAM_LUA_SOCKET_FT_RESOLVER; lua_pushnil(L); lua_pushliteral(L, "failed to start the resolver"); return 2; } if (rctx == NGX_NO_RESOLVER) { u->ft_type |= NGX_STREAM_LUA_SOCKET_FT_RESOLVER; lua_pushnil(L); lua_pushfstring(L, "no lua_resolver defined to resolve \"%s\"", host.data); return 2; } rctx->name = host; #if !defined(nginx_version) || nginx_version < 1005008 rctx->type = NGX_RESOLVE_A; #endif rctx->handler = ngx_stream_lua_socket_resolve_handler; rctx->data = u; rctx->timeout = lscf->resolver_timeout; u->co_ctx = ctx->cur_co_ctx; u->resolved->ctx = rctx; saved_top = lua_gettop(L); coctx = ctx->cur_co_ctx; ngx_stream_lua_cleanup_pending_operation(coctx); coctx->cleanup = ngx_stream_lua_udp_resolve_cleanup; if (ngx_resolve_name(rctx) != NGX_OK) { ngx_log_debug0(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, "stream lua udp socket fail to run resolver " "immediately"); u->ft_type |= NGX_STREAM_LUA_SOCKET_FT_RESOLVER; u->resolved->ctx = NULL; lua_pushnil(L); lua_pushfstring(L, "%s could not be resolved", host.data); return 2; } if (u->waiting == 1) { /* resolved and already connecting */ return lua_yield(L, 0); } n = lua_gettop(L) - saved_top; if (n) { /* errors occurred during resolving or connecting * or already connected */ return n; } /* still resolving */ u->waiting = 1; u->prepare_retvals = ngx_stream_lua_socket_resolve_retval_handler; coctx->data = u; ctx->write_event_handler = ngx_stream_lua_content_wev_handler; return lua_yield(L, 0); }
static int ngx_stream_lua_socket_udp_send(lua_State *L) { ssize_t n; ngx_stream_session_t *s; u_char *p; size_t len; ngx_stream_lua_socket_udp_upstream_t *u; int type; const char *msg; ngx_str_t query; ngx_stream_lua_srv_conf_t *lscf; if (lua_gettop(L) != 2) { return luaL_error(L, "expecting 2 arguments (including the object), " "but got %d", lua_gettop(L)); } s = ngx_stream_lua_get_session(L); if (s == NULL) { return luaL_error(L, "session object not found"); } luaL_checktype(L, 1, LUA_TTABLE); lua_rawgeti(L, 1, SOCKET_CTX_INDEX); u = lua_touserdata(L, -1); lua_pop(L, 1); if (u == NULL || u->udp_connection.connection == NULL) { lscf = ngx_stream_get_module_srv_conf(s, ngx_stream_lua_module); if (lscf->log_socket_errors) { ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, "attempt to send data on a closed socket: u:%p, c:%p", u, u ? u->udp_connection.connection : NULL); } lua_pushnil(L); lua_pushliteral(L, "closed"); return 2; } if (u->session != s) { return luaL_error(L, "bad session"); } if (u->ft_type) { u->ft_type = 0; } if (u->waiting) { lua_pushnil(L); lua_pushliteral(L, "socket busy"); return 2; } type = lua_type(L, 2); switch (type) { case LUA_TNUMBER: case LUA_TSTRING: lua_tolstring(L, 2, &len); break; case LUA_TTABLE: len = ngx_stream_lua_calc_strlen_in_table(L, 2, 2, 1 /* strict */); break; default: msg = lua_pushfstring(L, "string, number, boolean, nil, " "or array table expected, got %s", lua_typename(L, type)); return luaL_argerror(L, 2, msg); } query.data = lua_newuserdata(L, len); query.len = len; switch (type) { case LUA_TNUMBER: case LUA_TSTRING: p = (u_char *) lua_tolstring(L, 2, &len); ngx_memcpy(query.data, (u_char *) p, len); break; case LUA_TTABLE: (void) ngx_stream_lua_copy_str_in_table(L, 2, query.data); break; default: return luaL_error(L, "impossible to reach here"); } u->ft_type = 0; /* mimic ngx_stream_upstream_init_session here */ #if 1 u->waiting = 0; #endif dd("sending query %.*s", (int) query.len, query.data); n = ngx_send(u->udp_connection.connection, query.data, query.len); dd("ngx_send returns %d (query len %d)", (int) n, (int) query.len); if (n == NGX_ERROR || n == NGX_AGAIN) { u->socket_errno = ngx_socket_errno; return ngx_stream_lua_socket_error_retval_handler(s, u, L); } if (n != (ssize_t) query.len) { dd("not the while query was sent"); u->ft_type |= NGX_STREAM_LUA_SOCKET_FT_PARTIALWRITE; return ngx_stream_lua_socket_error_retval_handler(s, u, L); } dd("n == len"); lua_pushinteger(L, 1); return 1; }
static int Vector___tostring (lua_State *L) { Vector *v = luaL_checkvector(L, 1); lua_pushfstring(L, "Vector: %s", static_cast<const char *>(CFmtStr("(%f, %f, %f)", v->x, v->y, v->z))); return 1; }
static int QAngle___tostring (lua_State *L) { QAngle *v = luaL_checkangle(L, 1); lua_pushfstring(L, "QAngle: %s", static_cast<const char *>(CFmtStr("(%f, %f, %f)", v->x, v->y, v->z))); return 1; }
static void fileerror(lua_State *L, int arg, const wchar_t *filename) { const char* utf8name = push_utf8_string(L, filename, -1); lua_pushfstring(L, "%s: %s", utf8name, strerror(errno)); luaL_argerror(L, arg, lua_tostring(L, -1)); }
static int qltimer_add(lua_State *state) { int timeout, cycle; const char *mod, *func; qactor_t *actor; qdict_t *args; qengine_t *engine; qid_t id; qltimer_t *timer; timeout = (int)lua_tonumber(state, 1); cycle = (int)lua_tonumber(state, 2); mod = lua_tostring(state, 3); func = lua_tostring(state, 4); if (timeout < 0 || cycle < 0 || mod == NULL || func == NULL) { lua_pushnil(state); lua_pushliteral(state, "wrong param"); return 2; } /* if there exist mod.fun? */ lua_getglobal(state, mod); if (!lua_istable(state, -1)) { lua_pushnil(state); lua_pushfstring(state, "mod %s not exist", mod); return 2; } lua_getfield(state, -1, func); if (!lua_isfunction(state, -1)) { lua_pushnil(state); lua_pushfstring(state, "%s.%s is not lua function", mod, func); return 2; } /* pop the result */ lua_pop(state, -1); args = qdict_new(5); if (args == NULL) { lua_pushnil(state); lua_pushliteral(state, "create args table error"); return 2; } if (qlua_copy_table(state, 4, args) != QOK) { qdict_free(args); lua_pushnil(state); lua_pushliteral(state, "copy args table error"); return 2; } timer = new_timer(args, mod, func); if (timer == NULL) { qdict_free(args); lua_pushnil(state); lua_pushliteral(state, "create timer error"); return 2; } actor = qlua_get_actor(state); engine = qactor_get_engine(actor->aid); id = qtimer_add(engine, timeout, timer_handler, free_timer, cycle, timer); timer->state = state; timer->id = id; timer->engine = engine; qdict_set_numdata(actor->timers, id, timer, engine_free_timer); lua_pushnumber(state, id); return 1; }
/* Processes a result and pushes the data onto the stack returns the number of items pushed */ static int push_fs_result(lua_State* L, uv_fs_t* req) { luv_req_t* data = req->data; if (req->fs_type == UV_FS_ACCESS) { lua_pushboolean(L, req->result >= 0); return 1; } if (req->result < 0) { lua_pushnil(L); if (req->path) { lua_pushfstring(L, "%s: %s: %s", uv_err_name(req->result), uv_strerror(req->result), req->path); } else { lua_pushfstring(L, "%s: %s", uv_err_name(req->result), uv_strerror(req->result)); } return 2; } switch (req->fs_type) { case UV_FS_CLOSE: case UV_FS_RENAME: case UV_FS_UNLINK: case UV_FS_RMDIR: case UV_FS_MKDIR: case UV_FS_FTRUNCATE: case UV_FS_FSYNC: case UV_FS_FDATASYNC: case UV_FS_LINK: case UV_FS_SYMLINK: case UV_FS_CHMOD: case UV_FS_FCHMOD: case UV_FS_CHOWN: case UV_FS_FCHOWN: case UV_FS_UTIME: case UV_FS_FUTIME: lua_pushboolean(L, 1); return 1; case UV_FS_OPEN: case UV_FS_SENDFILE: case UV_FS_WRITE: lua_pushinteger(L, req->result); return 1; case UV_FS_STAT: case UV_FS_LSTAT: case UV_FS_FSTAT: luv_push_stats_table(L, &req->statbuf); return 1; case UV_FS_MKDTEMP: lua_pushstring(L, req->path); return 1; case UV_FS_READLINK: lua_pushstring(L, (char*)req->ptr); return 1; case UV_FS_READ: lua_pushlstring(L, data->data, req->result); return 1; case UV_FS_SCANDIR: // Expose the userdata for the request. lua_rawgeti(L, LUA_REGISTRYINDEX, data->req_ref); return 1; default: lua_pushnil(L); lua_pushfstring(L, "UNKNOWN FS TYPE %d\n", req->fs_type); return 2; } }
static int ngx_http_lua_ngx_exec(lua_State *L) { int n; ngx_http_request_t *r; ngx_http_lua_ctx_t *ctx; ngx_str_t uri; ngx_str_t args, user_args; ngx_uint_t flags; u_char *p; u_char *q; size_t len; const char *msg; n = lua_gettop(L); if (n != 1 && n != 2) { return luaL_error(L, "expecting one or two arguments, but got %d", n); } r = ngx_http_lua_get_req(L); if (r == NULL) { return luaL_error(L, "no request object found"); } ngx_str_null(&args); /* read the 1st argument (uri) */ p = (u_char *) luaL_checklstring(L, 1, &len); if (len == 0) { return luaL_error(L, "The uri argument is empty"); } uri.data = ngx_palloc(r->pool, len); if (uri.data == NULL) { return luaL_error(L, "no memory"); } ngx_memcpy(uri.data, p, len); uri.len = len; ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module); if (ctx == NULL) { return luaL_error(L, "no ctx found"); } ngx_http_lua_check_context(L, ctx, NGX_HTTP_LUA_CONTEXT_REWRITE | NGX_HTTP_LUA_CONTEXT_ACCESS | NGX_HTTP_LUA_CONTEXT_CONTENT); ngx_http_lua_check_if_abortable(L, ctx); if (ngx_http_parse_unsafe_uri(r, &uri, &args, &flags) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (n == 2) { /* read the 2nd argument (args) */ dd("args type: %s", luaL_typename(L, 2)); switch (lua_type(L, 2)) { case LUA_TNUMBER: case LUA_TSTRING: p = (u_char *) lua_tolstring(L, 2, &len); user_args.data = ngx_palloc(r->pool, len); if (user_args.data == NULL) { return luaL_error(L, "no memory"); } ngx_memcpy(user_args.data, p, len); user_args.len = len; break; case LUA_TTABLE: ngx_http_lua_process_args_option(r, L, 2, &user_args); dd("user_args: %.*s", (int) user_args.len, user_args.data); break; case LUA_TNIL: ngx_str_null(&user_args); break; default: msg = lua_pushfstring(L, "string, number, or table expected, " "but got %s", luaL_typename(L, 2)); return luaL_argerror(L, 2, msg); } } else { user_args.data = NULL; user_args.len = 0; } if (user_args.len) { if (args.len == 0) { args = user_args; } else { p = ngx_palloc(r->pool, args.len + user_args.len + 1); if (p == NULL) { return luaL_error(L, "no memory"); } q = ngx_copy(p, args.data, args.len); *q++ = '&'; ngx_memcpy(q, user_args.data, user_args.len); args.data = p; args.len += user_args.len + 1; } } if (r->header_sent || ctx->header_sent) { return luaL_error(L, "attempt to call ngx.exec after " "sending out response headers"); } ctx->exec_uri = uri; ctx->exec_args = args; ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "lua exec \"%V?%V\"", &ctx->exec_uri, &ctx->exec_args); return lua_yield(L, 0); }
// --=============================================== __tostring static int GLWidget___tostring(lua_State *L) { GLWidget *self = *((GLWidget **)dub_checksdata_n(L, 1, "mimas.GLWidget")); lua_pushfstring(L, "mimas.GLWidget: %p", self); return 1; }
// --=============================================== __tostring static int ofBuffer___tostring(lua_State *L) { ofBuffer *self = *((ofBuffer **)dub_checksdata_n(L, 1, "ofBuffer")); lua_pushfstring(L, "ofBuffer: %p", self); return 1; }
const char* luaX_pushtypeerror (lua_State *L, int narg, const char *argname, const char *tname) { return lua_pushfstring(L, "%s expected, got %s", tname, luaX_typename(L, narg)); }
static int luaL_typerror(lua_State *L, int narg, const char *tname) { const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, luaL_typename(L, narg)); return luaL_argerror(L, narg, msg); }
static int cgroup_tostring (lua_State *L) { struct u_cgroup *group = lua_touserdata(L, 1); lua_pushfstring(L, "cgroup: %s <%p>", group->name, group->group); return 1; }
static void ngx_stream_lua_socket_resolve_handler(ngx_resolver_ctx_t *ctx) { ngx_stream_session_t *s; ngx_stream_lua_resolved_t *ur; ngx_stream_lua_ctx_t *lctx; lua_State *L; u_char *p; size_t len; #if defined(nginx_version) && nginx_version >= 1005008 socklen_t socklen; struct sockaddr *sockaddr; #else struct sockaddr_in *sin; #endif ngx_uint_t i; unsigned waiting; ngx_stream_lua_socket_udp_upstream_t *u; u = ctx->data; s = u->session; ur = u->resolved; ngx_log_debug0(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, "stream lua udp socket resolve handler"); lctx = ngx_stream_get_module_ctx(s, ngx_stream_lua_module); if (lctx == NULL) { return; } lctx->cur_co_ctx = u->co_ctx; u->co_ctx->cleanup = NULL; L = lctx->cur_co_ctx->co; dd("setting socket_ready to 1"); waiting = u->waiting; if (ctx->state) { ngx_log_debug2(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, "stream lua udp socket resolver error: %s (waiting: %d)", ngx_resolver_strerror(ctx->state), (int) u->waiting); lua_pushnil(L); lua_pushlstring(L, (char *) ctx->name.data, ctx->name.len); lua_pushfstring(L, " could not be resolved (%d: %s)", (int) ctx->state, ngx_resolver_strerror(ctx->state)); lua_concat(L, 2); #if 1 ngx_resolve_name_done(ctx); ur->ctx = NULL; #endif u->prepare_retvals = ngx_stream_lua_socket_error_retval_handler; ngx_stream_lua_socket_udp_handle_error(s, u, NGX_STREAM_LUA_SOCKET_FT_RESOLVER); return; } ur->naddrs = ctx->naddrs; ur->addrs = ctx->addrs; #if (NGX_DEBUG) { # if defined(nginx_version) && nginx_version >= 1005008 u_char text[NGX_SOCKADDR_STRLEN]; ngx_str_t addr; # else in_addr_t addr; # endif ngx_uint_t i; # if defined(nginx_version) && nginx_version >= 1005008 addr.data = text; for (i = 0; i < ctx->naddrs; i++) { addr.len = ngx_sock_ntop(ur->addrs[i].sockaddr, ur->addrs[i].socklen, text, NGX_SOCKADDR_STRLEN, 0); ngx_log_debug1(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, "name was resolved to %V", &addr); } # else for (i = 0; i < ctx->naddrs; i++) { dd("addr i: %d %p", (int) i, &ctx->addrs[i]); addr = ntohl(ctx->addrs[i]); ngx_log_debug4(NGX_LOG_DEBUG_STREAM, c->log, 0, "name was resolved to %ud.%ud.%ud.%ud", (addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff, addr & 0xff); } # endif } #endif ngx_stream_lua_assert(ur->naddrs > 0); if (ur->naddrs == 1) { i = 0; } else { i = ngx_random() % ur->naddrs; } dd("selected addr index: %d", (int) i); #if defined(nginx_version) && nginx_version >= 1005008 socklen = ur->addrs[i].socklen; sockaddr = ngx_palloc(s->connection->pool, socklen); if (sockaddr == NULL) { goto nomem; } ngx_memcpy(sockaddr, ur->addrs[i].sockaddr, socklen); switch (sockaddr->sa_family) { #if (NGX_HAVE_INET6) case AF_INET6: ((struct sockaddr_in6 *) sockaddr)->sin6_port = htons(ur->port); break; #endif default: /* AF_INET */ ((struct sockaddr_in *) sockaddr)->sin_port = htons(ur->port); } p = ngx_pnalloc(s->connection->pool, NGX_SOCKADDR_STRLEN); if (p == NULL) { goto nomem; } len = ngx_sock_ntop(sockaddr, socklen, p, NGX_SOCKADDR_STRLEN, 1); ur->sockaddr = sockaddr; ur->socklen = socklen; #else /* for nginx older than 1.5.8 */ len = NGX_INET_ADDRSTRLEN + sizeof(":65536") - 1; p = ngx_pnalloc(s->pool, len + sizeof(struct sockaddr_in)); if (p == NULL) { goto nomem; } sin = (struct sockaddr_in *) &p[len]; ngx_memzero(sin, sizeof(struct sockaddr_in)); len = ngx_inet_ntop(AF_INET, &ur->addrs[i], p, NGX_INET_ADDRSTRLEN); len = ngx_sprintf(&p[len], ":%d", ur->port) - p; sin->sin_family = AF_INET; sin->sin_port = htons(ur->port); sin->sin_addr.s_addr = ur->addrs[i]; ur->sockaddr = (struct sockaddr *) sin; ur->socklen = sizeof(struct sockaddr_in); #endif ur->host.data = p; ur->host.len = len; ur->naddrs = 1; ngx_resolve_name_done(ctx); ur->ctx = NULL; u->waiting = 0; if (waiting) { lctx->resume_handler = ngx_stream_lua_socket_udp_resume; lctx->write_event_handler(s, lctx); } else { (void) ngx_stream_lua_socket_resolve_retval_handler(s, u, L); } return; nomem: if (ur->ctx) { ngx_resolve_name_done(ctx); ur->ctx = NULL; } u->prepare_retvals = ngx_stream_lua_socket_error_retval_handler; ngx_stream_lua_socket_udp_handle_error(s, u, NGX_STREAM_LUA_SOCKET_FT_NOMEM); if (!waiting) { lua_pushnil(L); lua_pushliteral(L, "no memory"); } }
static int tostring_Context (lua_State *L) { Context *o = check_Context_ud(L, 1); lua_pushfstring(L, "Context (%p), cairo_t (%p)", (void*)o, (void*)o->cr_); return 1; }
/** ** Parse Spell. ** ** @param l Lua state. */ static int CclDefineSpell(lua_State *l) { std::string identname; SpellType *spell; const char *value; int args; int i; args = lua_gettop(l); identname = LuaToString(l, 1); spell = SpellTypeByIdent(identname); if (spell != NULL) { DebugPrint("Redefining spell-type `%s'\n" _C_ identname.c_str()); } else { spell = new SpellType(SpellTypeTable.size(), identname); for (std::vector<CUnitType *>::size_type i = 0; i < UnitTypes.size(); ++i) { // adjust array for caster already defined if (UnitTypes[i]->CanCastSpell) { char *newc = new char[(SpellTypeTable.size() + 1) * sizeof(char)]; memcpy(newc, UnitTypes[i]->CanCastSpell, SpellTypeTable.size() * sizeof(char)); delete[] UnitTypes[i]->CanCastSpell; UnitTypes[i]->CanCastSpell = newc; UnitTypes[i]->CanCastSpell[SpellTypeTable.size()] = 0; } if (UnitTypes[i]->AutoCastActive) { char *newc = new char[(SpellTypeTable.size() + 1) * sizeof(char)]; memcpy(newc, UnitTypes[i]->AutoCastActive, SpellTypeTable.size() * sizeof(char)); delete[] UnitTypes[i]->AutoCastActive; UnitTypes[i]->AutoCastActive = newc; UnitTypes[i]->AutoCastActive[SpellTypeTable.size()] = 0; } } SpellTypeTable.push_back(spell); } for (i = 1; i < args; ++i) { value = LuaToString(l, i + 1); ++i; if (!strcmp(value, "showname")) { spell->Name = LuaToString(l, i + 1); } else if (!strcmp(value, "manacost")) { spell->ManaCost = LuaToNumber(l, i + 1); } else if (!strcmp(value, "range")) { if (!lua_isstring(l, i + 1) && !lua_isnumber(l, i + 1)) { LuaError(l, "incorrect argument"); } if (lua_isstring(l, i + 1) && !strcmp(lua_tostring(l, i + 1), "infinite")) { spell->Range = INFINITE_RANGE; } else if (lua_isnumber(l, i + 1)) { spell->Range = static_cast<int>(lua_tonumber(l, i + 1)); } else { LuaError(l, "Invalid range"); } } else if (!strcmp(value, "repeat-cast")) { spell->RepeatCast = 1; --i; } else if (!strcmp(value, "target")) { value = LuaToString(l, i + 1); if (!strcmp(value, "self")) { spell->Target = TargetSelf; } else if (!strcmp(value, "unit")) { spell->Target = TargetUnit; } else if (!strcmp(value, "position")) { spell->Target = TargetPosition; } else { LuaError(l, "Unsupported spell target type tag: %s" _C_ value); } } else if (!strcmp(value, "action")) { int subargs; int k; if (!lua_istable(l, i + 1)) { LuaError(l, "incorrect argument"); } subargs = lua_objlen(l, i + 1); for (k = 0; k < subargs; ++k) { lua_rawgeti(l, i + 1, k + 1); spell->Action.push_back(CclSpellAction(l)); lua_pop(l, 1); } } else if (!strcmp(value, "condition")) { if (!spell->Condition) { spell->Condition = new ConditionInfo; } lua_pushvalue(l, i + 1); CclSpellCondition(l, spell->Condition); lua_pop(l, 1); } else if (!strcmp(value, "autocast")) { if (!spell->AutoCast) { spell->AutoCast = new AutoCastInfo(); } lua_pushvalue(l, i + 1); CclSpellAutocast(l, spell->AutoCast); lua_pop(l, 1); } else if (!strcmp(value, "ai-cast")) { if (!spell->AICast) { spell->AICast = new AutoCastInfo(); } lua_pushvalue(l, i + 1); CclSpellAutocast(l, spell->AICast); lua_pop(l, 1); } else if (!strcmp(value, "sound-when-cast")) { // Free the old name, get the new one spell->SoundWhenCast.Name = LuaToString(l, i + 1); spell->SoundWhenCast.Sound = SoundForName(spell->SoundWhenCast.Name); // Check for sound. if (!spell->SoundWhenCast.Sound) { spell->SoundWhenCast.Name.clear(); } } else if (!strcmp(value, "depend-upgrade")) { value = LuaToString(l, i + 1); spell->DependencyId = UpgradeIdByIdent(value); if (spell->DependencyId == -1) { lua_pushfstring(l, "Bad upgrade name: %s", value); } } else { LuaError(l, "Unsupported tag: %s" _C_ value); } } return 0; }
static void invalidformat (lua_State *L, char c) { const char *msg = lua_pushfstring(L, "invalid format option [%c]", c); luaL_argerror(L, 1, msg); }
// --=============================================== __tostring static int btConvexInternalShape___tostring(lua_State *L) { btConvexInternalShape *self = *((btConvexInternalShape **)dub_checksdata_n(L, 1, "bt.ConvexInternalShape")); lua_pushfstring(L, "bt.ConvexInternalShape: %p", self); return 1; }
static int lua_dir(lua_State *L) { int k = 0; const char *s = luaL_checkstring(L, 1); #ifdef _WIN32 SB sb; struct _finddata_t info; long hfind; /* special cases */ lua_createtable(L, 0, 0); if ((s[0]=='/' || s[0]=='\\') && (s[1]=='/' || s[1]=='\\') && !s[2]) { int drive; hfind = GetLogicalDrives(); for (drive='A'; drive<='Z'; drive++) if (hfind & (1<<(drive-'A'))) { lua_pushfstring(L, "%c:/", drive); lua_rawseti(L, -2, ++k); } } else if (dirp(L, 1)) { lua_pushliteral(L, ".."); lua_rawseti(L, -2, ++k); } else { lua_pushnil(L); return 1; } /* files */ sbinit(&sb); sbaddn(&sb, s, strlen(s)); if (sb.len>0 && sb.buffer[sb.len-1]!='/' && sb.buffer[sb.len-1]!='\\') sbadd1(&sb, '/'); sbaddn(&sb, "*.*", 3); sbadd1(&sb, 0); hfind = _findfirst(sb.buffer, &info); if (hfind != -1) { do { if (strcmp(".",info.name) && strcmp("..",info.name)) { lua_pushstring(L, info.name); lua_rawseti(L, -2, ++k); } } while ( _findnext(hfind, &info) != -1 ); _findclose(hfind); } sbfree(&sb); #else DIR *dirp; struct dirent *d; dirp = opendir(s); if (dirp) { lua_createtable(L, 0, 0); while ((d = readdir(dirp))) { int n = NAMLEN(d); lua_pushlstring(L, d->d_name, n); lua_rawseti(L, -2, ++k); } closedir(dirp); } else lua_pushnil(L); #endif return 1; }
// --=============================================== __tostring static int MenuBar___tostring(lua_State *L) { MenuBar *self = *((MenuBar **)dub_checksdata_n(L, 1, "mimas.MenuBar")); lua_pushfstring(L, "mimas.MenuBar: %p", self); return 1; }
static int lua_getregistryvalue(lua_State *L) { #ifdef _WIN32 static char *keynames[] = { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_CONFIG", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", NULL }; static HKEY keys[] = { HKEY_CLASSES_ROOT, HKEY_CURRENT_CONFIG, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_USERS }; HKEY rkey = keys[ luaL_checkoption(L, 1, NULL, keynames) ]; const char *subkey = luaL_checkstring(L, 2); const char *value = luaL_checkstring(L, 3); HKEY skey; DWORD type; DWORD len = 0; char *data = NULL; LONG res; res = RegOpenKeyExA(rkey, subkey, 0, KEY_READ, &skey); if (res != ERROR_SUCCESS) { lua_pushnil(L); lua_pushinteger(L, res); if (res == ERROR_FILE_NOT_FOUND) lua_pushstring(L, "subkey not found"); if (res == ERROR_ACCESS_DENIED) lua_pushstring(L, "subkey access denied"); else return 2; return 3; } res = RegQueryValueExA(skey, value, NULL, &type, (LPBYTE)data, &len); if (len > 0) { len += 8; data = (char*)malloc(len); if (! data) luaL_error(L, "out of memory"); res = RegQueryValueExA(skey, value, NULL, &type, (LPBYTE)data, &len); } RegCloseKey(skey); if (res != ERROR_SUCCESS) { if (data) free(data); lua_pushnil(L); lua_pushinteger(L, res); if (res == ERROR_FILE_NOT_FOUND) lua_pushstring(L, "value not found"); if (res == ERROR_ACCESS_DENIED) lua_pushstring(L, "value access denied"); else return 2; return 3; } switch(type) { case REG_DWORD: lua_pushinteger(L, (lua_Integer)*(const DWORD*)data); if (data) free(data); return 1; case REG_EXPAND_SZ: if (data && len > 0) { if ((len = ExpandEnvironmentStrings(data, NULL, 0)) > 0) { char *buf = (char*)malloc(len + 8); if (!buf) luaL_error(L, "out of memory"); len = ExpandEnvironmentStrings(data, buf, len+8); free(data); data = buf; } } /* fall thru */ case REG_SZ: if (data && len > 0) if (((const char*)data)[len-1] == 0) len -= 1; /* fall thru */ case REG_BINARY: if (data && len > 0) lua_pushlstring(L, (const char*)data, (int)len); else lua_pushliteral(L, ""); if (data) free(data); return 1; /* unimplemented */ case REG_QWORD: case REG_MULTI_SZ: default: lua_pushnil(L); lua_pushinteger(L, res); lua_pushfstring(L, "getting registry type %d not implemented", type); return 3; } #else luaL_error(L, "This function exists only on windows"); return 0; #endif }
LUA_API int luafan_objectbuf_decode(lua_State *L) { size_t len; const char *buf = luaL_checklstring(L, 1, &len); BYTEARRAY input; bytearray_wrap_buffer(&input, (uint8_t *)buf, len); // will not change buf. int sym_idx = 0; if (lua_istable(L, 2)) { sym_idx = 2; } uint8_t flag = 0; bytearray_read8(&input, &flag); switch (flag) { case 0: lua_pushboolean(L, false); return 1; case 1: lua_pushboolean(L, true); return 1; default: break; } lua_newtable(L); int index_map_idx = lua_gettop(L); uint32_t index = 2; if (!sym_idx) { lua_newtable(L); } else { lua_rawgeti(L, sym_idx, SYM_INDEX_INDEX); index = lua_tointeger(L, -1); lua_pop(L, 1); lua_rawgeti(L, sym_idx, SYM_INDEX_MAP_VK); } int sym_map_vk_idx = lua_gettop(L); int last_top = index + 1; if (!sym_idx) { lua_pushboolean(L, false); lua_rawseti(L, index_map_idx, FALSE_INDEX); lua_pushboolean(L, true); lua_rawseti(L, index_map_idx, TRUE_INDEX); } if (flag & HAS_NUMBER_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed, can't get `number` count."); return 2; } uint32_t i = 1; for (; i <= count; i++) { double result = 0; if (!ffi_stream_get_d64(&input, &result)) { lua_pushnil(L); lua_pushfstring(L, "decode failed, can't decode `number`, %d/%d", i, count); return 2; } lua_pushnumber(L, result); lua_rawseti(L, index_map_idx, ++index); } } if (flag & HAS_U30_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t i = 1; for (; i <= count; i++) { uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } lua_pushinteger(L, count); lua_rawseti(L, index_map_idx, ++index); } } if (flag & HAS_STRING_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t i = 1; for (; i <= count; i++) { uint8_t *buff = NULL; size_t buflen = 0; ffi_stream_get_string(&input, &buff, &buflen); if (!buff) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } lua_pushlstring(L, (const char *)buff, buflen); lua_rawseti(L, index_map_idx, ++index); } } if (flag & HAS_TABLE_MASK) { last_top = index + 1; uint32_t count = 0; if (!ffi_stream_get_u30(&input, &count)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t i = 1; for (; i <= count; i++) { lua_newtable(L); lua_rawseti(L, index_map_idx, index + i); } i = 1; for (; i <= count; i++) { uint8_t *buff = NULL; size_t buflen = 0; ffi_stream_get_string(&input, &buff, &buflen); if (!buff) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } BYTEARRAY d = {0}; bytearray_wrap_buffer(&d, buff, buflen); lua_rawgeti(L, index_map_idx, index + i); while (bytearray_read_available(&d) > 0) { uint32_t ki = 0; if (!ffi_stream_get_u30(&d, &ki)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } uint32_t vi = 0; if (!ffi_stream_get_u30(&d, &vi)) { lua_pushnil(L); lua_pushliteral(L, "decode failed."); return 2; } lua_rawgeti(L, sym_map_vk_idx, ki); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_rawgeti(L, index_map_idx, ki); if (lua_isnil(L, -1)) { luaL_error(L, "ki=%d not found.", ki); } } lua_rawgeti(L, sym_map_vk_idx, vi); if (lua_isnil(L, -1)) { lua_pop(L, 1); lua_rawgeti(L, index_map_idx, vi); if (lua_isnil(L, -1)) { luaL_error(L, "vi=%d not found.", vi); } } lua_rawset(L, -3); } lua_pop(L, 1); } } lua_rawgeti(L, sym_map_vk_idx, last_top); if (lua_isnil(L, -1)) { lua_rawgeti(L, index_map_idx, last_top); } // return sym_map_vk[last_top] or index_map[last_top] // lua_pushvalue(L, index_map_idx); // lua_pushinteger(L, last_top); return 1; }
/*****************************************************************************\ tostring \*****************************************************************************/ static int imluaFile_tostring (lua_State *L) { imFile **ifile_p = (imFile **)lua_touserdata(L, 1); lua_pushfstring(L, "imFile(%p)%s", ifile_p, (*ifile_p)? "": "-closed"); return 1; }
/*****************************************************************************\ tostring \*****************************************************************************/ static int imluaPalette_tostring (lua_State *L) { imluaPalette *pal = (imluaPalette*)lua_touserdata(L, 1); lua_pushfstring(L, "imPalette(%p)%s", pal, (pal->color)? "": "-destroyed"); return 1; }
static void fileerror (lua_State *L, int arg, const char *filename) { lua_pushfstring(L, "%s: %s", filename, strerror(errno)); luaL_argerror(L, arg, lua_tostring(L, -1)); }