+#include <ctype.h>
+
+char *redisProtocolToLuaType_Int(lua_State *lua, char *reply);
+char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply);
+char *redisProtocolToLuaType_Status(lua_State *lua, char *reply);
+char *redisProtocolToLuaType_Error(lua_State *lua, char *reply);
+char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply);
+
+/* Take a Redis reply in the Redis protocol format and convert it into a
+ * Lua type. Thanks to this function, and the introduction of not connected
+ * clients, it is trvial to implement the redis() lua function.
+ *
+ * Basically we take the arguments, execute the Redis command in the context
+ * of a non connected client, then take the generated reply and convert it
+ * into a suitable Lua type. With this trick the scripting feature does not
+ * need the introduction of a full Redis internals API. Basically the script
+ * is like a normal client that bypasses all the slow I/O paths.
+ *
+ * Note: in this function we do not do any sanity check as the reply is
+ * generated by Redis directly. This allows use to go faster.
+ * The reply string can be altered during the parsing as it is discared
+ * after the conversion is completed.
+ *
+ * Errors are returned as a table with a single 'err' field set to the
+ * error string.
+ */
+
+char *redisProtocolToLuaType(lua_State *lua, char* reply) {
+ char *p = reply;
+
+ switch(*p) {
+ case ':':
+ p = redisProtocolToLuaType_Int(lua,reply);
+ break;
+ case '$':
+ p = redisProtocolToLuaType_Bulk(lua,reply);
+ break;
+ case '+':
+ p = redisProtocolToLuaType_Status(lua,reply);
+ break;
+ case '-':
+ p = redisProtocolToLuaType_Error(lua,reply);
+ break;
+ case '*':
+ p = redisProtocolToLuaType_MultiBulk(lua,reply);
+ break;
+ }
+ return p;
+}
+
+char *redisProtocolToLuaType_Int(lua_State *lua, char *reply) {
+ char *p = strchr(reply+1,'\r');
+ long long value;
+
+ string2ll(reply+1,p-reply-1,&value);
+ lua_pushnumber(lua,(lua_Number)value);
+ return p+2;
+}
+
+char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply) {
+ char *p = strchr(reply+1,'\r');
+ long long bulklen;
+
+ string2ll(reply+1,p-reply-1,&bulklen);
+ if (bulklen == -1) {
+ lua_pushboolean(lua,0);
+ return p+2;
+ } else {
+ lua_pushlstring(lua,p+2,bulklen);
+ return p+2+bulklen+2;
+ }
+}
+
+char *redisProtocolToLuaType_Status(lua_State *lua, char *reply) {
+ char *p = strchr(reply+1,'\r');
+
+ lua_newtable(lua);
+ lua_pushstring(lua,"ok");
+ lua_pushlstring(lua,reply+1,p-reply-1);
+ lua_settable(lua,-3);
+ return p+2;
+}
+
+char *redisProtocolToLuaType_Error(lua_State *lua, char *reply) {
+ char *p = strchr(reply+1,'\r');
+
+ lua_newtable(lua);
+ lua_pushstring(lua,"err");
+ lua_pushlstring(lua,reply+1,p-reply-1);
+ lua_settable(lua,-3);
+ return p+2;
+}
+
+char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply) {
+ char *p = strchr(reply+1,'\r');
+ long long mbulklen;
+ int j = 0;
+
+ string2ll(reply+1,p-reply-1,&mbulklen);
+ p += 2;
+ if (mbulklen == -1) {
+ lua_pushboolean(lua,0);
+ return p;
+ }
+ lua_newtable(lua);
+ for (j = 0; j < mbulklen; j++) {
+ lua_pushnumber(lua,j+1);
+ p = redisProtocolToLuaType(lua,p);
+ lua_settable(lua,-3);
+ }
+ return p;
+}
+
+void luaPushError(lua_State *lua, char *error) {
+ lua_newtable(lua);
+ lua_pushstring(lua,"err");
+ lua_pushstring(lua, error);
+ lua_settable(lua,-3);
+}
+
+int luaRedisCommand(lua_State *lua) {
+ int j, argc = lua_gettop(lua);
+ struct redisCommand *cmd;
+ robj **argv;
+ redisClient *c = server.lua_client;
+ sds reply;
+
+ /* Build the arguments vector */
+ argv = zmalloc(sizeof(robj*)*argc);
+ for (j = 0; j < argc; j++) {
+ if (!lua_isstring(lua,j+1)) break;
+ argv[j] = createStringObject((char*)lua_tostring(lua,j+1),
+ lua_strlen(lua,j+1));
+ }
+
+ /* Check if one of the arguments passed by the Lua script
+ * is not a string or an integer (lua_isstring() return true for
+ * integers as well). */
+ if (j != argc) {
+ j--;
+ while (j >= 0) {
+ decrRefCount(argv[j]);
+ j--;
+ }
+ zfree(argv);
+ luaPushError(lua,
+ "Lua redis() command arguments must be strings or integers");
+ return 1;
+ }
+
+ /* Command lookup */
+ cmd = lookupCommand(argv[0]->ptr);
+ if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) ||
+ (argc < -cmd->arity)))
+ {
+ for (j = 0; j < argc; j++) decrRefCount(argv[j]);
+ zfree(argv);
+ if (cmd)
+ luaPushError(lua,
+ "Wrong number of args calling Redis command From Lua script");
+ else
+ luaPushError(lua,"Unknown Redis command called from Lua script");
+ return 1;
+ }
+
+ /* Run the command in the context of a fake client */
+ c->argv = argv;
+ c->argc = argc;
+ cmd->proc(c);
+
+ /* Convert the result of the Redis command into a suitable Lua type.
+ * The first thing we need is to create a single string from the client
+ * output buffers. */
+ reply = sdsempty();
+ if (c->bufpos) {
+ reply = sdscatlen(reply,c->buf,c->bufpos);
+ c->bufpos = 0;
+ }
+ while(listLength(c->reply)) {
+ robj *o = listNodeValue(listFirst(c->reply));
+
+ reply = sdscatlen(reply,o->ptr,sdslen(o->ptr));
+ listDelNode(c->reply,listFirst(c->reply));
+ }
+ redisProtocolToLuaType(lua,reply);
+ sdsfree(reply);
+
+ /* Clean up. Command code may have changed argv/argc so we use the
+ * argv/argc of the client instead of the local variables. */
+ for (j = 0; j < c->argc; j++)
+ decrRefCount(c->argv[j]);
+ zfree(c->argv);
+
+ return 1;
+}
+
+int luaLogCommand(lua_State *lua) {
+ int j, argc = lua_gettop(lua);
+ int level;
+ sds log;
+
+ if (argc < 2) {
+ luaPushError(lua, "redis.log() requires two arguments or more.");
+ return 1;
+ } else if (!lua_isnumber(lua,-argc)) {
+ luaPushError(lua, "First argument must be a number (log level).");
+ return 1;
+ }
+ level = lua_tonumber(lua,-argc);
+ if (level < REDIS_DEBUG || level > REDIS_WARNING) {
+ luaPushError(lua, "Invalid debug level.");
+ return 1;
+ }
+
+ /* Glue together all the arguments */
+ log = sdsempty();
+ for (j = 1; j < argc; j++) {
+ size_t len;
+ char *s;
+
+ s = (char*)lua_tolstring(lua,(-argc)+j,&len);
+ if (s) {
+ if (j != 1) log = sdscatlen(log," ",1);
+ log = sdscatlen(log,s,len);
+ }
+ }
+ redisLogRaw(level,log);
+ sdsfree(log);
+ return 0;
+}
+
+void luaMaskCountHook(lua_State *lua, lua_Debug *ar) {
+ long long elapsed;
+ REDIS_NOTUSED(ar);
+
+ elapsed = (ustime()/1000) - server.lua_time_start;
+ if (elapsed >= server.lua_time_limit) {
+ redisLog(REDIS_NOTICE,"Lua script aborted for max execution time after %lld milliseconds of running time.",elapsed);
+ lua_pushstring(lua,"Script aborted for max execution time.");
+ lua_error(lua);
+ }
+}