Beispiel #1
0
/* return any possible fd, otherwise error out */
int nixio__checkfd(lua_State *L, int ud) {
	int fd = nixio__tofd(L, ud);
	return (fd != -1) ? fd : luaL_argerror(L, ud, "invalid file descriptor");
}
Beispiel #2
0
LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  if (lua_type(L, narg) == LUA_TNONE)
    luaL_argerror(L, narg, "value expected");
}
Beispiel #3
0
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));
}
Beispiel #4
0
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);
}
Beispiel #5
0
/*
 * Arguments: options (table: {1..n: library names, "cpu": number}),
 *	filename (string) | function_dump (string),
 *	[arguments (string | number | boolean | ludata | share_object) ...]
 * Returns: [thread_udata]
 */
static int
thread_runvm (lua_State *L)
{
  const char *path = luaL_checkstring(L, 2);
  struct sys_thread *vmtd = sys_thread_get();
  struct sys_thread *td, *faketd;
  lua_State *NL;
  unsigned int loadlibs = ~0U;  /* load all standard libraries */
  int is_affin = 0, cpu = 0;

  if (!vmtd) luaL_argerror(L, 0, "Threading not initialized");

  /* options */
  if (lua_istable(L, 1)) {
    unsigned int libs = 0;
    int i;

    for (i = 1; ; ++i) {
      const char *s;
      lua_rawgeti(L, 1, i);
      s = lua_tostring(L, -1);
      if (!s || !*s) {
        if (s) loadlibs = 0;  /* don't load any libraries */
        lua_pop(L, 1);
        break;
      }
      libs |= 1 << luaL_checkoption(L, -1, NULL, stdlib_names);
      lua_pop(L, 1);
    }
    if (libs) loadlibs = libs;

    /* CPU affinity */
    lua_getfield(L, 1, "cpu");
    if (lua_type(L, -1) == LUA_TNUMBER) {
      cpu = (int) lua_tointeger(L, -1);
      is_affin = 1;
    }
    lua_pop(L, 1);
  }

  td = thread_newvm(NULL, vmtd, loadlibs);
  if (!td) goto err;

  faketd = sys_thread_new(L, vmtd, td, 1);
  if (!faketd) goto err;

  lua_replace(L, 1);  /* fake thread_udata */

  if (is_affin)
    td->vmtd->cpu = cpu;

  NL = td->L;

  /* function */
  if (path[0] == LUA_SIGNATURE[0]
   ? luaL_loadbuffer(NL, path, lua_rawlen(L, ARG_LAST), "thread")
   : luaL_loadfile(NL, path)) {
    lua_pushstring(L, lua_tostring(NL, -1));  /* error message */
    lua_close(NL);
    lua_error(L);
  }

  /* arguments */
  {
    int i, top = lua_gettop(L);

    luaL_checkstack(NL, top + LUA_MINSTACK, "too many arguments");

    for (i = ARG_LAST + 1; i <= top; ++i) {
      switch (lua_type(L, i)) {
      case LUA_TSTRING:
        {
          size_t len;
          const char *s = lua_tolstring(L, i, &len);
          lua_pushlstring(NL, s, len);
        }
        break;
      case LUA_TNUMBER:
        lua_pushnumber(NL, lua_tonumber(L, i));
        break;
      case LUA_TBOOLEAN:
        lua_pushboolean(NL, lua_toboolean(L, i));
        break;
      case LUA_TLIGHTUSERDATA:
        lua_pushlightuserdata(NL, lua_touserdata(L, i));
        break;
      case LUA_TUSERDATA:
        if (!luaL_getmetafield(L, i, THREAD_XDUP_TAG))
          luaL_argerror(L, i, "shareable object expected");
        lua_pushvalue(L, i);
        lua_pushlightuserdata(L, NL);
        lua_call(L, 2, 0);
        break;
      case LUA_TNIL:
        lua_pushnil(NL);
        break;
      default:
        luaL_argerror(L, i, "primitive type expected");
      }
    }
  }

  if (!sys_thread_create(td, is_affin)) {
    faketd->tid = td->tid;
    lua_settop(L, 1);
    return 1;
  }
  lua_close(NL);
 err:
  return sys_seterror(L, 0);
}
Beispiel #6
0
static int str_format (lua_State *L) {
	int top = lua_gettop(L);
	int arg = 1;
	size_t sfl;
	const char *strfrmt = luaL_checklstring(L, arg, &sfl);
	const char *strfrmt_end = strfrmt+sfl;
	luaL_Buffer b;
	luaL_buffinit(L, &b);
	while (strfrmt < strfrmt_end) {
	if (*strfrmt != L_ESC)
		luaL_addchar(&b, *strfrmt++);
	else if (*++strfrmt == L_ESC)
		luaL_addchar(&b, *strfrmt++);  /* %% */
	else { /* format item */
		char form[MAX_FORMAT];  /* to store the format (`%...') */
		char *buff = luaL_prepbuffsize(&b, MAX_ITEM);  /* to put formatted item */
		int nb = 0;  /* number of bytes in added item */
		if (++arg > top)
		luaL_argerror(L, arg, "no value");
		strfrmt = scanformat(L, strfrmt, form);
		switch (*strfrmt++) {
		case 'c': {
			nb = sprintf(buff, form, luaL_checkint(L, arg));
			break;
		}
		case 'd': case 'i': {
			lua_Number n = luaL_checknumber(L, arg);
			LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
			lua_Number diff = n - (lua_Number)ni;
			luaL_argcheck(L, -1 < diff && diff < 1, arg,
						"not a number in proper range");
			addlenmod(form, LUA_INTFRMLEN);
			nb = sprintf(buff, form, ni);
			break;
		}
		case 'o': case 'u': case 'x': case 'X': {
			lua_Number n = luaL_checknumber(L, arg);
			unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
			lua_Number diff = n - (lua_Number)ni;
			luaL_argcheck(L, -1 < diff && diff < 1, arg,
						"not a non-negative number in proper range");
			addlenmod(form, LUA_INTFRMLEN);
			nb = sprintf(buff, form, ni);
			break;
		}
		case 'e': case 'E': case 'f':
#if defined(LUA_USE_AFORMAT)
		case 'a': case 'A':
#endif
		case 'g': case 'G': {
			addlenmod(form, LUA_FLTFRMLEN);
			nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
			break;
		}
		case 'q': {
			addquoted(L, &b, arg);
			break;
		}
		case 's': {
			size_t l;
			const char *s = luaL_tolstring(L, arg, &l);
			if (!strchr(form, '.') && l >= 100) {
			/* no precision and string is too long to be formatted;
			   keep original string */
			luaL_addvalue(&b);
			break;
			}
			else {
			nb = sprintf(buff, form, s);
			lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */
			break;
			}
		}
		default: {  /* also treat cases `pnLlh' */
			return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
								LUA_QL("format"), *(strfrmt - 1));
		}
		}
		luaL_addsize(&b, nb);
	}
	}
	luaL_pushresult(&b);
	return 1;
}
Beispiel #7
0
void *luabridge::checkclass (lua_State *L, int idx, const char *tname,
	bool exact)
{
	// If idx is relative to the top of the stack, convert it into an index
	// relative to the bottom of the stack, so we can push our own stuff
	if (idx < 0)
		idx += lua_gettop(L) + 1;

	int top = lua_gettop(L);

	// Check that the thing on the stack is indeed a userdata
	if (!lua_isuserdata(L, idx))
		luaL_typerror(L, idx, tname);

	// Lookup the given name in the registry
	luaL_getmetatable(L, tname);

	// Lookup the metatable of the given userdata
	lua_getmetatable(L, idx);
	
	// If exact match required, simply test for identity.
	if (exact)
	{
		// Ignore "const" for exact tests (which are used for destructors).
		if (!strncmp(tname, "const ", 6))
			tname += 6;

		if (lua_rawequal(L, -1, -2))
			return lua_touserdata(L, idx);
		else
		{
			// Generate an informative error message
			rawgetfield(L, -1, "__type");
			char buffer[256];
			snprintf(buffer, 256, "%s expected, got %s", tname,
				lua_tostring(L, -1));
			// luaL_argerror does not return
			luaL_argerror(L, idx, buffer);
			return 0;
		}
	}

	// Navigate up the chain of parents if necessary
	while (!lua_rawequal(L, -1, -2))
	{
		// Check for equality to the const metatable
		rawgetfield(L, -1, "__const");
		if (!lua_isnil(L, -1))
		{
			if (lua_rawequal(L, -1, -3))
				break;
		}
		lua_pop(L, 1);

		// Look for the metatable's parent field
		rawgetfield(L, -1, "__parent");

		// No parent field?  We've failed; generate appropriate error
		if (lua_isnil(L, -1))
		{
			// Lookup the __type field of the original metatable, so we can
			// generate an informative error message
			lua_getmetatable(L, idx);
			rawgetfield(L, -1, "__type");

			char buffer[256];
			snprintf(buffer, 256, "%s expected, got %s", tname,
				lua_tostring(L, -1));
			// luaL_argerror does not return
			luaL_argerror(L, idx, buffer);
			return 0;
		}

		// Remove the old metatable from the stack
		lua_remove(L, -2);
	}
	
	lua_settop(L, top);
	// Found a matching metatable; return the userdata
	return lua_touserdata(L, idx);
}
LUALIB_API lua_KeyValues *luaL_checkkeyvalues (lua_State *L, int narg) {
  lua_KeyValues **d = (lua_KeyValues **)luaL_checkudata(L, narg, "KeyValues");
  if (*d == 0)  /* avoid extra test when d is not 0 */
    luaL_argerror(L, narg, "KeyValues expected, got NULL keyvalues");
  return *d;
}
Beispiel #9
0
static int str_format (lua_State *L) {
    int top = lua_gettop(L);
    int arg = 1;
    size_t sfl;
    const char *strfrmt = luaL_checklstring(L, arg, &sfl);
    const char *strfrmt_end = strfrmt+sfl;
    luaL_Buffer b;
    luaL_buffinit(L, &b);
    while (strfrmt < strfrmt_end) {
        if (*strfrmt != L_ESC)
            luaL_addchar(&b, *strfrmt++);
        else if (*++strfrmt == L_ESC)
            luaL_addchar(&b, *strfrmt++);  /* %% */
        else { /* format item */
            char form[MAX_FORMAT];  /* to store the format (`%...') */
            char buff[MAX_ITEM];  /* to store the formatted item */
            if (++arg > top)
                luaL_argerror(L, arg, "no value");
            strfrmt = scanformat(L, strfrmt, form);
            switch (*strfrmt++) {
            case 'c': {
                sprintf(buff, form, (int)luaL_checknumber(L, arg));
                break;
            }
            case 'd':
            case 'i': {
                addintlen(form);
                sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
                break;
            }
            case 'o':
            case 'u':
            case 'x':
            case 'X': {
                addintlen(form);
                sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));
                break;
            }
            case 'e':
            case 'E':
            case 'f':
            case 'g':
            case 'G': {
                // SPRING sprintf(buff, form, (double)luaL_checknumber(L, arg));
                // float2str in printf is desyncing (between windows & linux) we need to use our own syncing one
                lua_number2fmt(buff, form, luaL_checknumber(L, arg));
                break;
            }
            case 'q': {
                addquoted(L, &b, arg);
                continue;  /* skip the 'addsize' at the end */
            }
            case 's': {
                size_t l;
                const char *s = luaL_checklstring(L, arg, &l);
                if (!strchr(form, '.') && l >= 100) {
                    /* no precision and string is too long to be formatted;
                       keep original string */
                    lua_pushvalue(L, arg);
                    luaL_addvalue(&b);
                    continue;  /* skip the `addsize' at the end */
                }
                else {
                    sprintf(buff, form, s);
                    break;
                }
            }
            default: {  /* also treat cases `pnLlh' */
                return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
                                  LUA_QL("format"), *(strfrmt - 1));
            }
            }
            luaL_addlstring(&b, buff, strlen(buff));
        }
    }
    luaL_pushresult(&b);
    return 1;
}
Beispiel #10
0
static void interror (lua_State *L, int arg) {
  if (lua_isnumber(L, arg))
    luaL_argerror(L, arg, "number has no integer representation");
  else
    tag_error(L, arg, LUA_TNUMBER);
}
Beispiel #11
0
/***
Encrypt a plain string. Use Argon2i (by default) or Argon2d to hash a string.
@function encrypt
@param[type=string] plain Plain string to encrypt.
@param[type=string] salt Salt to use to hash pwd.
@param[type=table] options Options with which to hash the plain string. See
`options`. This parameter is optional, if values are omitted the default ones
will be used.
@treturn string `hash`: Hash computed by Argon2 or nil if an error occurred.
@treturn string `error`: `nil` or a string describing the error if any.

@usage
local hash, err = argon2.encrypt("password", "somesalt")
local hash, err = argon2.encrypt("password", "somesalt", {t_cost = 4})
*/
static int largon2_encrypt(lua_State *L) {
    largon2_config *cfg = largon2_arg_init(L, 3);

    char encoded[ENCODED_LEN];
    int ret_code;

    const char *plain, *salt;
    size_t plainlen, saltlen;

    uint32_t t_cost;
    uint32_t m_cost;
    uint32_t parallelism;
    argon2_type argon2_t;

    plain = luaL_checklstring(L, 1, &plainlen);
    salt = luaL_checklstring(L, 2, &saltlen);

    t_cost = cfg->t_cost;
    m_cost = cfg->m_cost;
    parallelism = cfg->parallelism;
    argon2_t = cfg->argon2_t;

    if (!lua_isnil(L, 3)) {
        if (!lua_istable(L, 3)) {
            luaL_argerror(L, 3, "expected to be a table");
        }

        lua_getfield(L, 3, "t_cost");
        largon2_integer_opt(L, -1, 3, &t_cost, "t_cost");
        lua_pop(L, 1);

        lua_getfield(L, 3, "m_cost");
        largon2_integer_opt(L, -1, 3, &m_cost, "m_cost");
        lua_pop(L, 1);

        lua_getfield(L, 3, "parallelism");
        largon2_integer_opt(L, -1, 3, &parallelism, "parallelism");
        lua_pop(L, 1);

        lua_getfield(L, -1, "argon2d");
        if (!lua_isnil(L, -1) && lua_isboolean(L, -1)) {
            // reverse checking to allow overriding the module settings
            argon2_t = lua_toboolean(L, -1) ? Argon2_d : Argon2_i;
        }

        lua_pop(L, 1);
    }

    if (argon2_t == Argon2_i)
        ret_code =
            argon2i_hash_encoded(t_cost, m_cost, parallelism, plain, plainlen,
                                 salt, saltlen, HASH_LEN, encoded, ENCODED_LEN);
    else
        ret_code =
            argon2d_hash_encoded(t_cost, m_cost, parallelism, plain, plainlen,
                                 salt, saltlen, HASH_LEN, encoded, ENCODED_LEN);

    if (ret_code != ARGON2_OK) {
        const char *err_msg = argon2_error_message(ret_code);
        lua_pushnil(L);
        lua_pushstring(L, err_msg);
        return 2;
    }

    lua_pushstring(L, encoded);

    return 1;
}
Beispiel #12
0
static int luaprimbull_index(lua_State *L)
{
	PRIMARYWEAPONBULLET *bullet;
	const char *name;
	int *id;
	int bullidx = *((int *) luaL_checkudata(L, 1, "PRIMARYWEAPONBULLETIDX"));
	bullet = &PrimBulls[bullidx];
	name = luaL_checkstring(L, 2);
	/*if (!strcmp(name, "table")) -- TODO
	{
		lua_pushcfunction(L, luaprimbull_table);
		return 1;
	}
	else*/ if (!strcmp(name, "index") || !strcmp(name, "Index"))
	{
		lua_pushinteger(L, bullidx + 1);
		return 1;
	}
	else if (!strcmp(name, "category"))
	{
		lua_pushliteral(L, "primary");
		return 1;
	}
	FIELD(Used, boolean);
	if (!strcmp(name, "Next") && bullet->Next != (u_int16_t) -1)
	{
		pushprimbull(L, bullet->Next);
		return 1;
	}
	else if (!strcmp(name, "Prev") && bullet->Prev != (u_int16_t) -1)
	{
		pushprimbull(L, bullet->Prev);
		return 1;
	}
	else if (!strcmp(name, "Type"))
	{
		GETTABLEFORPRIM(bullet->Type);
		return 1;
	}
	FIELD(OwnerType, integer);
	if (!strcmp(name, "Owner"))
		return pushentity(L, bullet->OwnerType, bullet->Owner);
	/* FIELD(EnemyGun, ??); -- TODO */
	if (!strcmp(name, "Weapon"))
	{
		GETTABLEFORPRIM(bullet->Weapon);
		return 1;
	}
	FIELD(PowerLevel, integer);
	FIELD(TrojPower, number);
	FIELD(LifeCount, number);
	FIELD(Speed, number);
	FIELD(ColRadius, number);
	FIELD(ColType, integer);
	FIELDPTR(Offset, vector);
	FIELDPTR(Pos, vector);
	FIELDPTR(Dir, vector);
	FIELDPTR(LocalDir, vector);
	FIELDPTR(UpVector, vector);
	FIELDPTR(ColStart, vector);
	FIELD(ColDist, number);
	FIELD(ColFlag, integer);
	FIELDPTR(ColPoint, vector); /* VERT */
	FIELDPTR(ColPointNormal, vector); /* NORMAL */
	FIELD(ColGroup, integer);
	FIELD(GroupImIn, integer);
	FIELDPTR(Mat, matrix);
	FIELD(line, integer);
	FIELD(fmpoly, integer);
	FIELD(numfmpolys, integer);
	FIELD(poly, integer);
	FIELD(numpolys, integer);
	FIELD(light, integer);
	FIELD(lightsize, number);
	FIELD(r, number);
	FIELD(g, number);
	FIELD(b, number);
	FIELD(Bounces, integer);
	FIELD(TimeInterval, number);
	FIELD(TimeCount, number);
	FIELD(FirePoint, integer);
	FIELD(SpotFX, integer);
	FIELD(FramelagAddition, number);
	return luaL_argerror(L, 2, "unknown field name");
}
Beispiel #13
0
static int luasecbull_index(lua_State *L)
{
	SECONDARYWEAPONBULLET *bullet;
	const char *name;
	int *id;
	int bullidx = *((int *) luaL_checkudata(L, 1, "SECONDARYWEAPONBULLETIDX"));
	bullet = &SecBulls[bullidx];
	name = luaL_checkstring(L, 2);
	/*if (!strcmp(name, "table")) -- TODO
	{
		lua_pushcfunction(L, luasecbull_table);
		return 1;
	}
	else*/ if (!strcmp(name, "index") || !strcmp(name, "Index"))
	{
		lua_pushinteger(L, bullidx + 1 + MAXPRIMARYWEAPONBULLETS);
		return 1;
	}
	else if (!strcmp(name, "category"))
	{
		lua_pushliteral(L, "secondary");
		return 1;
	}
	FIELD(Used, boolean);
	if (!strcmp(name, "Next") && bullet->Next != (u_int16_t) -1)
	{
		pushsecbull(L, bullet->Next);
		return 1;
	}
	else if (!strcmp(name, "Prev") && bullet->Prev != (u_int16_t) -1)
	{
		pushsecbull(L, bullet->Prev);
		return 1;
	}
	else if (!strcmp(name, "NextInGroup") && bullet->NextInGroup != NULL)
	{
		pushsecbull(L, bullet->NextInGroup - SecBulls);
		return 1;
	}
	else if (!strcmp(name, "PrevInGroup") && bullet->PrevInGroup != NULL)
	{
		pushsecbull(L, bullet->PrevInGroup - SecBulls);
		return 1;
	}
	else if (!strcmp(name, "Flags"))
	{
		/* FIXME: not really consistent */
		lua_createtable(L, 0, 3);
		SECFLAG(CanShoot);
		SECFLAG(CanTarget);
		SECFLAG(NoIncoming);
		return 1;
	}
	FIELD(SecType, integer);
	if (!strcmp(name, "Type"))
	{
		GETTABLEFORSEC(bullet->Type);
		return 1;
	}
	FIELD(MoveType, integer);
	FIELD(State, integer);
	FIELD(OwnerType, integer);
	if (!strcmp(name, "Owner"))
		return pushentity(L, bullet->OwnerType, bullet->Owner);
	FIELD(ID, integer);
	if (!strcmp(name, "Weapon"))
	{
		GETTABLEFORSEC(bullet->Weapon);
		return 1;
	}
	FIELD(Lensflare, boolean);
	FIELD(LifeCount, number);
	FIELD(LifeSpan, number);
	FIELD(SpeedInc, number);
	FIELD(SpeedWanted, number);
	FIELD(Speed, number);
	FIELD(DropCount, number);
	FIELDPTR(DropVector, vector);
	FIELD(Size, number);
	FIELDPTR(Pos, vector);
	FIELDPTR(Offset, vector);
	FIELDPTR(StartPos, vector);
	FIELDPTR(StartDir, vector);
	FIELDPTR(StartMat, matrix);
	FIELDPTR(ColStart, vector);
	FIELD(ColDist, number);
	FIELD(ColFlag, integer);
	FIELD(ColGroup, integer);
	FIELDPTR(ColPoint, vector); /* VERT */
	FIELDPTR(ColPointNormal, vector); /* NORMAL */
	FIELD(GroupImIn, integer);
	FIELD(ModelNum, integer);
	FIELD(ModelIndex, integer);
	FIELDPTR(Mat, matrix);
	FIELD(fmpoly, integer);
	FIELD(numfmpolys, integer);
	FIELD(poly, integer);
	FIELD(numpolys, integer);
	FIELD(xsize, number);
	FIELD(ysize, number);
	FIELD(light, integer);
	FIELD(lightsize, number);
	FIELD(r, number);
	FIELD(g, number);
	FIELD(b, number);
	FIELD(TurnSpeed, number);
	FIELD(ViewCone, number);
	FIELD(TargetType, integer);
	if (!strcmp(name, "Target"))
		return pushentity(L, bullet->TargetType, bullet->Target);
	/* FIELDPTR(DirQuat, quat); -- TODO */
	FIELDPTR(DirVector, vector);
	FIELDPTR(UpVector, vector);
	FIELD(Shield, number);
	FIELD(Damage, number);
	FIELD(Ammo, integer);
	FIELD(NumBounces, integer);
	FIELD(NumOldPos, integer);
	FIELD(RetractPos, number);
	FIELD(ColRadius, number);
	FIELD(Interval, number);
	FIELD(Time, number);
	FIELD(FramelagAddition, number);
	return luaL_argerror(L, 2, "unknown field name");
}
static int
ngx_http_lua_socket_udp_send(lua_State *L)
{
    ssize_t                              n;
    ngx_http_request_t                  *r;
    u_char                              *p;
    size_t                               len;
    ngx_http_lua_socket_udp_upstream_t  *u;
    int                                  type;
    const char                          *msg;
    ngx_str_t                            query;
    ngx_http_lua_loc_conf_t             *llcf;

    if (lua_gettop(L) != 2) {
        return luaL_error(L, "expecting 2 arguments (including the object), "
                          "but got %d", lua_gettop(L));
    }

    r = ngx_http_lua_get_req(L);
    if (r == NULL) {
        return luaL_error(L, "request 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) {
        llcf = ngx_http_get_module_loc_conf(r, ngx_http_lua_module);

        if (llcf->log_socket_errors) {
            ngx_log_error(NGX_LOG_ERR, r->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->request != r) {
        return luaL_error(L, "bad request");
    }

    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_http_lua_calc_strlen_in_table(L, 2, 2, 1 /* strict */);
            break;

        case LUA_TNIL:
            len = sizeof("nil") - 1;
            break;

        case LUA_TBOOLEAN:
            if (lua_toboolean(L, 2)) {
                len = sizeof("true") - 1;

            } else {
                len = sizeof("false") - 1;
            }

            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_http_lua_copy_str_in_table(L, 2, query.data);
            break;

        case LUA_TNIL:
            p = query.data;
            *p++ = 'n';
            *p++ = 'i';
            *p++ = 'l';
            break;

        case LUA_TBOOLEAN:
            p = query.data;

            if (lua_toboolean(L, 2)) {
                *p++ = 't';
                *p++ = 'r';
                *p++ = 'u';
                *p++ = 'e';

            } else {
                *p++ = 'f';
                *p++ = 'a';
                *p++ = 'l';
                *p++ = 's';
                *p++ = 'e';
            }

            break;

        default:
            return luaL_error(L, "impossible to reach here");
    }

    u->ft_type = 0;

    /* mimic ngx_http_upstream_init_request 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_http_lua_socket_error_retval_handler(r, u, L);
    }

    if (n != (ssize_t) query.len) {
        dd("not the while query was sent");

        u->ft_type |= NGX_HTTP_LUA_SOCKET_FT_PARTIALWRITE;
        return ngx_http_lua_socket_error_retval_handler(r, u, L);
    }

    dd("n == len");

    lua_pushinteger(L, 1);
    return 1;
}
Beispiel #15
0
static void type_error (lua_State *L, int narg, int t) {
  char buff[50];
  sprintf(buff, "%.8s expected, got %.8s", lua_typename(L, t),
                                           lua_typename(L, lua_type(L, narg)));
  luaL_argerror(L, narg, buff);
}
Beispiel #16
0
Datei: marshal.c Projekt: ntd/lgi
/* Marshalls given callable from Lua to C. */
static int
marshal_2c_callable (lua_State *L, GICallableInfo *ci, GIArgInfo *ai,
		     gpointer *callback, int narg, gboolean optional,
		     GICallableInfo *argci, void **args)
{
  int nret = 0;
  GIScopeType scope;
  gpointer user_data = NULL;
  gint nargs = 0;

  if (argci != NULL)
    nargs = g_callable_info_get_n_args (argci);

  /* Check 'nil' in optional case.  In this case, return NULL as
     callback. */
  if (lua_isnoneornil (L, narg))
    {
      if (optional)
	{
	  *callback = NULL;

	  /* Also set associated destroy handler to NULL, because some
	     callees tend to call it when left as garbage even when
	     main callback is NULL (gtk_menu_popup_for_device()
	     case). */
	  if (ai != NULL)
	    {
	      gint arg = g_arg_info_get_destroy (ai);
	      if (arg >= 0 && arg < nargs)
		((GIArgument *) args[arg])->v_pointer = NULL;
	    }
	  return 0;
	}
      else
	return luaL_argerror (L, narg, "nil is not allowed");
    }

  /* Check lightuserdata case; simply use that data if provided. */
  if (lua_islightuserdata (L, narg))
    {
      *callback = lua_touserdata (L, narg);
      return 0;
    }

  if (argci != NULL)
    {
      gint arg = g_arg_info_get_closure (ai);

      /* user_data block is already preallocated from function call. */
      g_assert (args != NULL);
      if (arg >= 0 && arg < nargs)
	{
	  user_data = ((GIArgument *) args[arg])->v_pointer;
	  arg = g_arg_info_get_destroy (ai);
	  if (arg >= 0 && arg < nargs)
	    ((GIArgument *) args[arg])->v_pointer = lgi_closure_destroy;
	}
    }

  scope = g_arg_info_get_scope (ai);
  if (user_data == NULL)
    {
      /* Closure without user_data block.  Create new data block,
	 setup destruction according to scope. */
      user_data = lgi_closure_allocate (L, 1);
      if (scope == GI_SCOPE_TYPE_CALL)
	{
	  *lgi_guard_create (L, lgi_closure_destroy) = user_data;
	  nret++;
	}
      else
	g_assert (scope == GI_SCOPE_TYPE_ASYNC);
    }

  /* Create the closure. */
  lgi_callable_create (L, ci, NULL);
  *callback = lgi_closure_create (L, user_data, narg,
				  scope == GI_SCOPE_TYPE_ASYNC);
  return nret;
}
Beispiel #17
0
sf::Keyboard::Key lua_get<sf::Keyboard::Key>(lua_State * l,int i)
{
    unsigned int value = lua_get<unsigned int>(l,i);
    if(value >= sf::Keyboard::KeyCount) luaL_argerror(l,i,"Not valid enum value");
    return (sf::Keyboard::Key)value;
}
static size_t
ngx_http_lua_calc_strlen_in_table(lua_State *L, int arg_i)
{
    double              key;
    int                 max;
    int                 i;
    int                 type;
    size_t              size;
    size_t              len;
    const char         *msg;

    max = 0;

    lua_pushnil(L); /* stack: table key */
    while (lua_next(L, -2) != 0) { /* stack: table key value */
        if (lua_type(L, -2) == LUA_TNUMBER && (key = lua_tonumber(L, -2))) {
            if (floor(key) == key && key >= 1) {
                if (key > max) {
                    max = key;
                }

                lua_pop(L, 1); /* stack: table key */
                continue;
            }
        }

        /* not an array (non positive integer key) */
        lua_pop(L, 2); /* stack: table */

        msg = lua_pushfstring(L, "on-array table found");
        luaL_argerror(L, arg_i, msg);
        return 0;
    }

    size = 0;

    for (i = 1; i <= max; i++) {
        lua_rawgeti(L, -1, i); /* stack: table value */
        type = lua_type(L, -1);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                lua_tolstring(L, -1, &len);
                size += len;
                break;

            case LUA_TNIL:
                size += sizeof("nil") - 1;
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, -1)) {
                    size += sizeof("true") - 1;

                } else {
                    size += sizeof("false") - 1;
                }

                break;

            case LUA_TTABLE:
                size += ngx_http_lua_calc_strlen_in_table(L, arg_i);
                break;

            default:
                msg = lua_pushfstring(L, "bad data type %s found",
                        lua_typename(L, type));
                luaL_argerror(L, arg_i, msg);
                return 0;
        }

        lua_pop(L, 1); /* stack: table */
    }

    return size;
}
Beispiel #19
0
static LUA_FUNCTION(openssl_evp_cipher)
{
  const EVP_CIPHER* cipher = NULL;
  if (lua_istable(L, 1))
  {
    if (lua_getmetatable(L, 1) && lua_equal(L, 1, -1))
    {
      lua_pop(L, 1);
      lua_remove(L, 1);
    }
    else
      luaL_error(L, "call function with invalid state");
  }

  cipher = get_cipher(L, 1, NULL);

  if (cipher)
  {
    int enc = lua_toboolean(L, 2);
    size_t input_len = 0;
    const char *input = luaL_checklstring(L, 3, &input_len);
    size_t key_len = 0;
    const char *key = luaL_checklstring(L, 4, &key_len);
    size_t iv_len = 0;
    const char *iv = luaL_optlstring(L, 5, NULL, &iv_len); /* can be NULL */

    int pad = lua_isnone(L, 6) ? 1 : lua_toboolean(L, 6);
    ENGINE *e = lua_isnoneornil(L, 7) ? NULL : CHECK_OBJECT(7, ENGINE, "openssl.engine");

    EVP_CIPHER_CTX *c = EVP_CIPHER_CTX_new();

    int output_len = 0;
    int len = 0;

    char evp_key[EVP_MAX_KEY_LENGTH] = {0};
    char evp_iv[EVP_MAX_IV_LENGTH] = {0};

    int ret;

    if (key)
    {
      key_len = EVP_MAX_KEY_LENGTH > key_len ? key_len : EVP_MAX_KEY_LENGTH;
      memcpy(evp_key, key, key_len);
    }
    if (iv_len > 0 && iv)
    {
      iv_len = EVP_MAX_IV_LENGTH > iv_len ? iv_len : EVP_MAX_IV_LENGTH;
      memcpy(evp_iv, iv, iv_len);
    }

    EVP_CIPHER_CTX_init(c);
    ret = EVP_CipherInit_ex(c, cipher, e, (const byte*)evp_key, iv_len > 0 ? (const byte*)evp_iv : NULL, enc);
    if (ret == 1)
    {
      ret = EVP_CIPHER_CTX_set_padding(c, pad);
      if (ret == 1)
      {
        char *buffer;
        len = input_len + EVP_MAX_BLOCK_LENGTH;
        buffer = OPENSSL_malloc(len);
        ret = EVP_CipherUpdate(c, (byte*)buffer, &len, (const byte*)input, input_len);
        if (ret == 1)
        {
          output_len += len;
          len = input_len + EVP_MAX_BLOCK_LENGTH - len;
          ret = EVP_CipherFinal(c, (byte*)buffer + output_len, &len);
          if (ret == 1)
          {
            output_len += len;
            lua_pushlstring(L, buffer, output_len);
          }
        }
        OPENSSL_free(buffer);
      }
    }
    EVP_CIPHER_CTX_cleanup(c);
    EVP_CIPHER_CTX_free(c);
    return (ret == 1) ? ret : openssl_pushresult(L, ret);
  }
  else
    luaL_argerror(L, 1, "invvalid cipher algorithm or openssl.evp_cipher object");

  return 0;
}
static int
ngx_http_lua_ngx_echo(lua_State *L, unsigned newline)
{
    ngx_http_request_t          *r;
    ngx_http_lua_ctx_t          *ctx;
    const char                  *p;
    size_t                       len;
    size_t                       size;
    ngx_buf_t                   *b;
    ngx_chain_t                 *cl;
    ngx_int_t                    rc;
    int                          i;
    int                          nargs;
    int                          type;
    const char                  *msg;

    lua_getglobal(L, GLOBALS_SYMBOL_REQUEST);
    r = lua_touserdata(L, -1);
    lua_pop(L, 1);

    if (r == NULL) {
        return luaL_error(L, "no request object found");
    }

    ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);

    if (ctx == NULL) {
        return luaL_error(L, "no request ctx found");
    }

    if ((r->method & NGX_HTTP_HEAD) || r->header_only) {
        return 0;
    }

    if (ctx->eof) {
        return luaL_error(L, "seen eof already");
    }

    nargs = lua_gettop(L);
    size = 0;

    for (i = 1; i <= nargs; i++) {
        type = lua_type(L, i);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                lua_tolstring(L, i, &len);
                size += len;
                break;

            case LUA_TNIL:
                size += sizeof("nil") - 1;
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, i)) {
                    size += sizeof("true") - 1;

                } else {
                    size += sizeof("false") - 1;
                }

                break;

            case LUA_TTABLE:
                size += ngx_http_lua_calc_strlen_in_table(L, i);
                break;

            default:
                msg = lua_pushfstring(L, "string, number, boolean, nil, "
                        "or array table expected, got %s",
                        lua_typename(L, type));

                return luaL_argerror(L, i, msg);
        }
    }

    if (newline) {
        size += sizeof("\n") - 1;
    }

    if (size == 0) {
        /* do nothing for empty strings */
        return 0;
    }

    b = ngx_create_temp_buf(r->pool, size);
    if (b == NULL) {
        return luaL_error(L, "out of memory");
    }

    for (i = 1; i <= nargs; i++) {
        type = lua_type(L, i);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                p = lua_tolstring(L, i, &len);
                b->last = ngx_copy(b->last, (u_char *) p, len);
                break;

            case LUA_TNIL:
                *b->last++ = 'n';
                *b->last++ = 'i';
                *b->last++ = 'l';
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, i)) {
                    *b->last++ = 't';
                    *b->last++ = 'r';
                    *b->last++ = 'u';
                    *b->last++ = 'e';

                } else {
                    *b->last++ = 'f';
                    *b->last++ = 'a';
                    *b->last++ = 'l';
                    *b->last++ = 's';
                    *b->last++ = 'e';
                }

                break;

            case LUA_TTABLE:
                b->last = ngx_http_lua_copy_str_in_table(L, b->last);
                break;

            default:
                return luaL_error(L, "impossible to reach here");
        }
    }

    if (newline) {
        *b->last++ = '\n';
    }

    if (b->last != b->end) {
        return luaL_error(L, "buffer error: %p != %p", b->last, b->end);
    }

    cl = ngx_alloc_chain_link(r->pool);
    if (cl == NULL) {
        return luaL_error(L, "out of memory");
    }

    cl->next = NULL;
    cl->buf = b;

    rc = ngx_http_lua_send_chain_link(r, ctx, cl);

    if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) {
        return luaL_error(L, "failed to send data through the output filters");
    }

    return 0;
}
static int
ngx_http_lua_ngx_echo(lua_State *L, unsigned newline)
{
    ngx_http_request_t          *r;
    ngx_http_lua_ctx_t          *ctx;
    const char                  *p;
    size_t                       len;
    size_t                       size;
    ngx_buf_t                   *b;
    ngx_chain_t                 *cl;
    ngx_int_t                    rc;
    int                          i;
    int                          nargs;
    int                          type;
    const char                  *msg;
    ngx_buf_tag_t                tag;

    lua_getglobal(L, GLOBALS_SYMBOL_REQUEST);
    r = lua_touserdata(L, -1);
    lua_pop(L, 1);

    if (r == NULL) {
        return luaL_error(L, "no request object found");
    }

    ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);

    if (ctx == NULL) {
        return luaL_error(L, "no request ctx found");
    }

    if ((r->method & NGX_HTTP_HEAD) || r->header_only) {
        return 0;
    }

    if (ctx->eof) {
        return luaL_error(L, "seen eof already");
    }

    nargs = lua_gettop(L);
    size = 0;

    for (i = 1; i <= nargs; i++) {

        type = lua_type(L, i);

        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:

                lua_tolstring(L, i, &len);
                size += len;
                break;

            case LUA_TNIL:

                size += sizeof("nil") - 1;
                break;

            case LUA_TBOOLEAN:

                if (lua_toboolean(L, i)) {
                    size += sizeof("true") - 1;

                } else {
                    size += sizeof("false") - 1;
                }

                break;

            case LUA_TTABLE:

                size += ngx_http_lua_calc_strlen_in_table(L, i, 0);
                break;

            case LUA_TLIGHTUSERDATA:

                dd("userdata: %p", lua_touserdata(L, i));

                if (lua_touserdata(L, i) == NULL) {
                    size += sizeof("null") - 1;
                    break;
                }

                continue;

            default:

                msg = lua_pushfstring(L, "string, number, boolean, nil, "
                                      "ngx.null, or array table expected, "
                                      "but got %s", lua_typename(L, type));

                return luaL_argerror(L, i, msg);
        }
    }

    if (newline) {
        size += sizeof("\n") - 1;
    }

    if (size == 0) {
        /* do nothing for empty strings */
        return 0;
    }

    tag = (ngx_buf_tag_t) &ngx_http_lua_module;

    cl = ngx_http_lua_chains_get_free_buf(r->connection->log, r->pool,
                                          &ctx->free_bufs, size, tag);

    if (cl == NULL) {
        return luaL_error(L, "out of memory");
    }

    b = cl->buf;

    for (i = 1; i <= nargs; i++) {
        type = lua_type(L, i);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                p = lua_tolstring(L, i, &len);
                b->last = ngx_copy(b->last, (u_char *) p, len);
                break;

            case LUA_TNIL:
                *b->last++ = 'n';
                *b->last++ = 'i';
                *b->last++ = 'l';
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, i)) {
                    *b->last++ = 't';
                    *b->last++ = 'r';
                    *b->last++ = 'u';
                    *b->last++ = 'e';

                } else {
                    *b->last++ = 'f';
                    *b->last++ = 'a';
                    *b->last++ = 'l';
                    *b->last++ = 's';
                    *b->last++ = 'e';
                }

                break;

            case LUA_TTABLE:
                b->last = ngx_http_lua_copy_str_in_table(L, b->last);
                break;

            case LUA_TLIGHTUSERDATA:
                *b->last++ = 'n';
                *b->last++ = 'u';
                *b->last++ = 'l';
                *b->last++ = 'l';
                break;

            default:
                return luaL_error(L, "impossible to reach here");
        }
    }

    if (newline) {
        *b->last++ = '\n';
    }

#if 0
    if (b->last != b->end) {
        return luaL_error(L, "buffer error: %p != %p", b->last, b->end);
    }
#endif

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   newline ? "lua say response" : "lua print response");

    rc = ngx_http_lua_send_chain_link(r, ctx, cl);

    if (rc == NGX_ERROR || rc >= NGX_HTTP_SPECIAL_RESPONSE) {
        return luaL_error(L, "failed to send data through the output filters");
    }

    dd("downstream write: %d, buf len: %d", (int) rc,
            (int) (b->last - b->pos));

    if (!ctx->out) {
#if nginx_version >= 1001004
        ngx_chain_update_chains(r->pool,
#else
        ngx_chain_update_chains(
#endif
                                &ctx->free_bufs, &ctx->busy_bufs, &cl, tag);

        dd("out lua buf tag: %p, buffered: %x, busy bufs: %p",
            &ngx_http_lua_module, (int) r->connection->buffered,
            ctx->busy_bufs);
    }
Beispiel #22
0
static int InitContext(lua_State *L) 
/* init_context([major, minor, context, debug])
 *
 *                      type  | profile     | features
 * ---------------------------------------------------------
 * core                 full  | core        | current release
 * compatible           full  | compatible  | all ever
 * forward compatible   f.c.  | core        | non-deprecated
 */
    {
    int major, minor, context, flags, profile;
    if(!lua_isnoneornil(L, 1)) /* set */
        {
        major = luaL_checkinteger(L, 1);
        minor = luaL_checkinteger(L, 2);

        flags = profile = 0;
        context = ContextCodes[checkoption(L, 3, NULL, ContextStrings)];
        switch(context)
            {
            case MOONGL_CORE: 
                        profile |= GLUT_CORE_PROFILE;
                        break;
            case MOONGL_COMPATIBLE:
                        profile |= GLUT_COMPATIBILITY_PROFILE;
                        break;
            case MOONGL_FORWARD_COMPATIBLE:
                        flags |= GLUT_FORWARD_COMPATIBLE;
                        profile |= GLUT_CORE_PROFILE;
                        break;
            default:
                return luaL_error(L, UNEXPECTED_ERROR);
            }

        if(lua_isboolean(L, 4))
            {
            if(lua_toboolean(L, 4))
                flags |= GLUT_DEBUG;
            }
        else if(!lua_isnoneornil(L, 4))
            return luaL_argerror(L, 4, "boolean expected");

        glutInitContextVersion(major, minor);
        glutInitContextFlags(flags);
        glutInitContextProfile(profile);
        }

    major = glutGet(GLUT_INIT_MAJOR_VERSION);
    minor = glutGet(GLUT_INIT_MINOR_VERSION);
    profile = glutGet(GLUT_INIT_PROFILE);
    flags = glutGet(GLUT_INIT_FLAGS);
    lua_pushinteger(L, major);
    lua_pushinteger(L, minor);
    
    if(profile & GLUT_CORE_PROFILE)
        {
        if(flags & GLUT_FORWARD_COMPATIBLE)
            lua_pushstring(L, "forward compatible");
        else
            lua_pushstring(L, "core");
        }
    else if(profile & GLUT_COMPATIBILITY_PROFILE)
        lua_pushstring(L, "compatible");
    else
        lua_pushstring(L, "default");
    lua_pushboolean(L, (flags & GLUT_DEBUG));
    return 4;
    }
Beispiel #23
0
static void badoption(lua_State *L, int i, const char *what, int option)
{
	luaL_argerror(L, 2,
		lua_pushfstring(L, "unknown %s option `%c'", what, option));
}
Beispiel #24
0
static lz_stream *lzstream_get(lua_State *L, int index) {
    lz_stream *s = (lz_stream*)luaL_checkudata(L, index, ZSTREAMMETA);
    if (s == NULL) luaL_argerror(L, index, "bad zlib stream");
    return s;
}
static int
log_wrapper(ngx_http_request_t *r, const char *ident, ngx_uint_t level,
        lua_State *L)
{
    u_char              *buf;
    u_char              *p;
    u_char              *q;
    int                  nargs, i;
    size_t               size, len;
    int                  type;
    const char          *msg;

    if (level > r->connection->log->log_level) {
        return 0;
    }

    nargs = lua_gettop(L);
    if (nargs == 0) {
        buf = NULL;
        goto done;
    }

    size = 0;

    for (i = 1; i <= nargs; i++) {
        type = lua_type(L, i);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                lua_tolstring(L, i, &len);
                size += len;
                break;

            case LUA_TNIL:
                size += sizeof("nil") - 1;
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, i)) {
                    size += sizeof("true") - 1;

                } else {
                    size += sizeof("false") - 1;
                }

                break;

            case LUA_TLIGHTUSERDATA:
                if (lua_touserdata(L, i) == NULL) {
                    size += sizeof("null") - 1;
                    break;
                }

                continue;

            default:
                msg = lua_pushfstring(L, "string, number, boolean, or nil "
                         "expected, got %s", lua_typename(L, type));
                return luaL_argerror(L, i, msg);
        }
    }

    buf = ngx_palloc(r->pool, size + 1);
    if (buf == NULL) {
        return luaL_error(L, "out of memory");
    }

    p = buf;
    for (i = 1; i <= nargs; i++) {
        type = lua_type(L, i);
        switch (type) {
            case LUA_TNUMBER:
            case LUA_TSTRING:
                q = (u_char *) lua_tolstring(L, i, &len);
                p = ngx_copy(p, q, len);
                break;

            case LUA_TNIL:
                *p++ = 'n';
                *p++ = 'i';
                *p++ = 'l';
                break;

            case LUA_TBOOLEAN:
                if (lua_toboolean(L, i)) {
                    *p++ = 't';
                    *p++ = 'r';
                    *p++ = 'u';
                    *p++ = 'e';

                } else {
                    *p++ = 'f';
                    *p++ = 'a';
                    *p++ = 'l';
                    *p++ = 's';
                    *p++ = 'e';
                }

                break;

            case LUA_TLIGHTUSERDATA:
                *p++ = 'n';
                *p++ = 'u';
                *p++ = 'l';
                *p++ = 'l';

                break;

            default:
                return luaL_error(L, "impossible to reach here");
        }
    }

    *p++ = '\0';

done:
    ngx_log_error(level, r->connection->log, 0,
            "%s%s", ident, (buf == NULL) ? (u_char *) "(null)" : buf);
    return 0;
}
static void py_object_index(lua_State *L) {
    py_object *obj = get_py_object(L, 1);
    if (!obj) luaL_argerror(L, 1, "not a python object");
    _p_object_index_get(L, obj, 2);
}
Beispiel #27
0
LUALIB_API 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);
}
Beispiel #28
0
static void
badoption(lua_State *L, int i, const char *what, int option)
{
	luaL_argerror(L, i,
		lua_pushfstring(L, "invalid %s option '%c'", what, option));
}
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);
    }

    lua_getglobal(L, GLOBALS_SYMBOL_REQUEST);
    r = lua_touserdata(L, -1);
    lua_pop(L, 1);

    if (r == NULL) {
        return luaL_error(L, "no request object found");
    }

    args.data = NULL;
    args.len = 0;

    /* 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, "out of memory");
    }

    ngx_memcpy(uri.data, p, len);

    uri.len = len;

    ctx = ngx_http_get_module_ctx(r, ngx_http_lua_module);

    if (ngx_http_parse_unsafe_uri(r, &uri, &args, &flags)
        != NGX_OK)
    {
        ctx->headers_sent = 1;
        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, "out of 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;

        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, "out of memory");
            }

            q = ngx_copy(p, args.data, args.len);
            *q++ = '&';
            q = ngx_copy(q, user_args.data, user_args.len);

            args.data = p;
            args.len += user_args.len + 1;
        }
    }

    if (ctx->headers_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);
}
Beispiel #30
0
EC_GROUP* openssl_get_ec_group(lua_State* L, int ec_name_idx, int param_enc_idx,
  int conv_form_idx)
{
  int nid = NID_undef;
  EC_GROUP* g = NULL;
  if (lua_isnumber(L, ec_name_idx))
    nid = lua_tointeger(L, ec_name_idx);
  else if (lua_isstring(L, ec_name_idx))
  {
    const char* name = luaL_checkstring(L, ec_name_idx);
    nid = OBJ_sn2nid(name);
  } else if (lua_isuserdata(L, ec_name_idx))
  {
    if (auxiliar_isclass(L, "openssl.evp_pkey", ec_name_idx))
    {
      EVP_PKEY* pkey = CHECK_OBJECT(1, EVP_PKEY, "openssl.evp_pkey");
      EC_KEY* ec_key = EVP_PKEY_get1_EC_KEY(pkey);
      if (ec_key)
      {
        g = (EC_GROUP*)EC_KEY_get0_group(ec_key);
        EC_KEY_free(ec_key);
      }
    } else if (auxiliar_isclass(L, "openssl.ec_key", ec_name_idx))
    {
      EC_KEY* ec_key = CHECK_OBJECT(1, EC_KEY, "openssl.ec_key");
      g = (EC_GROUP*)EC_KEY_get0_group(ec_key);
    }
    if (g)
      g = EC_GROUP_dup(g);
  }

  if (g == NULL && nid != NID_undef)
    g = EC_GROUP_new_by_curve_name(nid);

  if (g)
  {
    if (param_enc_idx)
    {
      int form = 0;
      if (lua_isstring(L, param_enc_idx))
      {
        const char* options[] = {"compressed", "uncompressed", "hybrid", NULL};
        int f = luaL_checkoption(L, param_enc_idx, NULL, options);
        if (f == 0)
          form = POINT_CONVERSION_COMPRESSED;
        else if (f == 1)
          form = POINT_CONVERSION_UNCOMPRESSED;
        else if (f == 2)
          form = POINT_CONVERSION_HYBRID;
        else
          luaL_argerror(L, param_enc_idx, "not accept value point_conversion_form");
        EC_GROUP_set_point_conversion_form(g, form);
      } else if (lua_isnumber(L, param_enc_idx))
      {
        form = luaL_checkint(L, param_enc_idx);
        EC_GROUP_set_point_conversion_form(g, form);
      } else if (lua_isnoneornil(L, param_enc_idx))
      {
        EC_GROUP_set_point_conversion_form(g, POINT_CONVERSION_UNCOMPRESSED);
      }
      else
        luaL_argerror(L, param_enc_idx, "not accept type of point_conversion_form");
    }else
      EC_GROUP_set_point_conversion_form(g, POINT_CONVERSION_UNCOMPRESSED);

    if (conv_form_idx)
    {
      int asn1_flag = 0;
      if (lua_isstring(L, conv_form_idx))
      {           /* OPENSSL_EC_NAMED_CURVE,   0 */
        const char* const options[] = {"named_curve", "explicit", NULL};
        asn1_flag = luaL_checkoption(L, conv_form_idx, NULL, options);
        EC_GROUP_set_asn1_flag(g, asn1_flag);
      } else if (lua_isnumber(L, conv_form_idx))
      {
        asn1_flag = luaL_checkint(L, conv_form_idx);
        EC_GROUP_set_asn1_flag(g, asn1_flag);
      } else if (lua_isnoneornil(L, conv_form_idx))
      {
        EC_GROUP_set_asn1_flag(g, OPENSSL_EC_NAMED_CURVE);
      }
      else
        luaL_argerror(L, conv_form_idx, "not accept type of asn1 flag");
    }else
      EC_GROUP_set_asn1_flag(g, OPENSSL_EC_NAMED_CURVE);
  }

  return g;
}