xref: /redis-3.2.3/src/scripting.c (revision 95def3ae)
14365e5b2Santirez /*
24365e5b2Santirez  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
34365e5b2Santirez  * All rights reserved.
44365e5b2Santirez  *
54365e5b2Santirez  * Redistribution and use in source and binary forms, with or without
64365e5b2Santirez  * modification, are permitted provided that the following conditions are met:
74365e5b2Santirez  *
84365e5b2Santirez  *   * Redistributions of source code must retain the above copyright notice,
94365e5b2Santirez  *     this list of conditions and the following disclaimer.
104365e5b2Santirez  *   * Redistributions in binary form must reproduce the above copyright
114365e5b2Santirez  *     notice, this list of conditions and the following disclaimer in the
124365e5b2Santirez  *     documentation and/or other materials provided with the distribution.
134365e5b2Santirez  *   * Neither the name of Redis nor the names of its contributors may be used
144365e5b2Santirez  *     to endorse or promote products derived from this software without
154365e5b2Santirez  *     specific prior written permission.
164365e5b2Santirez  *
174365e5b2Santirez  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
184365e5b2Santirez  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
194365e5b2Santirez  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
204365e5b2Santirez  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
214365e5b2Santirez  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
224365e5b2Santirez  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
234365e5b2Santirez  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
244365e5b2Santirez  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
254365e5b2Santirez  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
264365e5b2Santirez  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
274365e5b2Santirez  * POSSIBILITY OF SUCH DAMAGE.
284365e5b2Santirez  */
294365e5b2Santirez 
30cef054e8Santirez #include "server.h"
317585836eSantirez #include "sha1.h"
32e108bab0Santirez #include "rand.h"
33da95d22aSantirez #include "cluster.h"
347585836eSantirez 
357585836eSantirez #include <lua.h>
367585836eSantirez #include <lauxlib.h>
377585836eSantirez #include <lualib.h>
387229d60dSantirez #include <ctype.h>
39e108bab0Santirez #include <math.h>
407585836eSantirez 
41532e0f5dSantirez char *redisProtocolToLuaType_Int(lua_State *lua, char *reply);
42532e0f5dSantirez char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply);
43532e0f5dSantirez char *redisProtocolToLuaType_Status(lua_State *lua, char *reply);
443791000fSantirez char *redisProtocolToLuaType_Error(lua_State *lua, char *reply);
453791000fSantirez char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply);
46e108bab0Santirez int redis_math_random (lua_State *L);
47e108bab0Santirez int redis_math_randomseed (lua_State *L);
48def31636Santirez void ldbInit(void);
49def31636Santirez void ldbDisable(client *c);
50def31636Santirez void ldbEnable(client *c);
51def31636Santirez void evalGenericCommandWithDebugging(client *c, int evalsha);
52def31636Santirez void luaLdbLineHook(lua_State *lua, lua_Debug *ar);
5389bf9696Santirez void ldbLog(sds entry);
5479c6e689Santirez void ldbLogRedisReply(char *reply);
558f8c6b3bSantirez sds ldbCatStackValue(sds s, lua_State *lua, int idx);
56def31636Santirez 
57def31636Santirez /* Debugger shared state is stored inside this global structure. */
588a0020f1Santirez #define LDB_BREAKPOINTS_MAX 64  /* Max number of breakpoints. */
5979c6e689Santirez #define LDB_MAX_LEN_DEFAULT 256 /* Default len limit for replies / var dumps. */
60def31636Santirez struct ldbState {
61def31636Santirez     int fd;     /* Socket of the debugging client. */
62def31636Santirez     int active; /* Are we debugging EVAL right now? */
63def31636Santirez     int forked; /* Is this a fork()ed debugging session? */
64def31636Santirez     list *logs; /* List of messages to send to the client. */
65def31636Santirez     list *traces; /* Messages about Redis commands executed since last stop.*/
66cdb92412Santirez     list *children; /* All forked debugging sessions pids. */
67def31636Santirez     int bp[LDB_BREAKPOINTS_MAX]; /* An array of breakpoints line numbers. */
68def31636Santirez     int bpcount; /* Number of valid entries inside bp. */
69def31636Santirez     int step;   /* Stop at next line ragardless of breakpoints. */
7051de527aSantirez     int luabp;  /* Stop at next line because redis.breakpoint() was called. */
7102de5d99Santirez     sds *src;   /* Lua script source code split by line. */
7202de5d99Santirez     int lines;  /* Number of lines in 'src'. */
7389bf9696Santirez     int currentline;    /* Current line number. */
7402de5d99Santirez     sds cbuf;   /* Debugger client command buffer. */
7579c6e689Santirez     size_t maxlen;  /* Max var dump / reply length. */
7679c6e689Santirez     int maxlen_hint_sent; /* Did we already hint about "set maxlen"? */
77def31636Santirez } ldb;
781fb2b91aSantirez 
791fb2b91aSantirez /* ---------------------------------------------------------------------------
801fb2b91aSantirez  * Utility functions.
811fb2b91aSantirez  * ------------------------------------------------------------------------- */
821fb2b91aSantirez 
831fb2b91aSantirez /* Perform the SHA1 of the input string. We use this both for hashing script
841fb2b91aSantirez  * bodies in order to obtain the Lua function name, and in the implementation
851fb2b91aSantirez  * of redis.sha1().
861fb2b91aSantirez  *
871fb2b91aSantirez  * 'digest' should point to a 41 bytes buffer: 40 for SHA1 converted into an
881fb2b91aSantirez  * hexadecimal number, plus 1 byte for null term. */
sha1hex(char * digest,char * script,size_t len)891fb2b91aSantirez void sha1hex(char *digest, char *script, size_t len) {
901fb2b91aSantirez     SHA1_CTX ctx;
911fb2b91aSantirez     unsigned char hash[20];
921fb2b91aSantirez     char *cset = "0123456789abcdef";
931fb2b91aSantirez     int j;
941fb2b91aSantirez 
951fb2b91aSantirez     SHA1Init(&ctx);
961fb2b91aSantirez     SHA1Update(&ctx,(unsigned char*)script,len);
971fb2b91aSantirez     SHA1Final(hash,&ctx);
981fb2b91aSantirez 
991fb2b91aSantirez     for (j = 0; j < 20; j++) {
1001fb2b91aSantirez         digest[j*2] = cset[((hash[j]&0xF0)>>4)];
1011fb2b91aSantirez         digest[j*2+1] = cset[(hash[j]&0xF)];
1021fb2b91aSantirez     }
1031fb2b91aSantirez     digest[40] = '\0';
1041fb2b91aSantirez }
1051fb2b91aSantirez 
1061fb2b91aSantirez /* ---------------------------------------------------------------------------
1071fb2b91aSantirez  * Redis reply to Lua type conversion functions.
1081fb2b91aSantirez  * ------------------------------------------------------------------------- */
109532e0f5dSantirez 
110532e0f5dSantirez /* Take a Redis reply in the Redis protocol format and convert it into a
111532e0f5dSantirez  * Lua type. Thanks to this function, and the introduction of not connected
1129d09ce39Sguiquanz  * clients, it is trivial to implement the redis() lua function.
113532e0f5dSantirez  *
114532e0f5dSantirez  * Basically we take the arguments, execute the Redis command in the context
115532e0f5dSantirez  * of a non connected client, then take the generated reply and convert it
116532e0f5dSantirez  * into a suitable Lua type. With this trick the scripting feature does not
1178a0020f1Santirez  * need the introduction of a full Redis internals API. The script
118532e0f5dSantirez  * is like a normal client that bypasses all the slow I/O paths.
119532e0f5dSantirez  *
120532e0f5dSantirez  * Note: in this function we do not do any sanity check as the reply is
121548efd91Santirez  * generated by Redis directly. This allows us to go faster.
122532e0f5dSantirez  *
123532e0f5dSantirez  * Errors are returned as a table with a single 'err' field set to the
124532e0f5dSantirez  * error string.
125532e0f5dSantirez  */
126532e0f5dSantirez 
redisProtocolToLuaType(lua_State * lua,char * reply)127532e0f5dSantirez char *redisProtocolToLuaType(lua_State *lua, char* reply) {
128532e0f5dSantirez     char *p = reply;
129532e0f5dSantirez 
130532e0f5dSantirez     switch(*p) {
1318a0020f1Santirez     case ':': p = redisProtocolToLuaType_Int(lua,reply); break;
1328a0020f1Santirez     case '$': p = redisProtocolToLuaType_Bulk(lua,reply); break;
1338a0020f1Santirez     case '+': p = redisProtocolToLuaType_Status(lua,reply); break;
1348a0020f1Santirez     case '-': p = redisProtocolToLuaType_Error(lua,reply); break;
1358a0020f1Santirez     case '*': p = redisProtocolToLuaType_MultiBulk(lua,reply); break;
136532e0f5dSantirez     }
137532e0f5dSantirez     return p;
138532e0f5dSantirez }
139532e0f5dSantirez 
redisProtocolToLuaType_Int(lua_State * lua,char * reply)140532e0f5dSantirez char *redisProtocolToLuaType_Int(lua_State *lua, char *reply) {
141532e0f5dSantirez     char *p = strchr(reply+1,'\r');
142532e0f5dSantirez     long long value;
143532e0f5dSantirez 
144532e0f5dSantirez     string2ll(reply+1,p-reply-1,&value);
145532e0f5dSantirez     lua_pushnumber(lua,(lua_Number)value);
146532e0f5dSantirez     return p+2;
147532e0f5dSantirez }
148532e0f5dSantirez 
redisProtocolToLuaType_Bulk(lua_State * lua,char * reply)149532e0f5dSantirez char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply) {
150532e0f5dSantirez     char *p = strchr(reply+1,'\r');
151532e0f5dSantirez     long long bulklen;
152532e0f5dSantirez 
153532e0f5dSantirez     string2ll(reply+1,p-reply-1,&bulklen);
154379789ccSantirez     if (bulklen == -1) {
15582c6b825Santirez         lua_pushboolean(lua,0);
156532e0f5dSantirez         return p+2;
157532e0f5dSantirez     } else {
158532e0f5dSantirez         lua_pushlstring(lua,p+2,bulklen);
159532e0f5dSantirez         return p+2+bulklen+2;
160532e0f5dSantirez     }
161532e0f5dSantirez }
162532e0f5dSantirez 
redisProtocolToLuaType_Status(lua_State * lua,char * reply)163532e0f5dSantirez char *redisProtocolToLuaType_Status(lua_State *lua, char *reply) {
164532e0f5dSantirez     char *p = strchr(reply+1,'\r');
165532e0f5dSantirez 
1660d916763Santirez     lua_newtable(lua);
1670d916763Santirez     lua_pushstring(lua,"ok");
168532e0f5dSantirez     lua_pushlstring(lua,reply+1,p-reply-1);
1690d916763Santirez     lua_settable(lua,-3);
170532e0f5dSantirez     return p+2;
171532e0f5dSantirez }
172532e0f5dSantirez 
redisProtocolToLuaType_Error(lua_State * lua,char * reply)1733791000fSantirez char *redisProtocolToLuaType_Error(lua_State *lua, char *reply) {
1743791000fSantirez     char *p = strchr(reply+1,'\r');
1753791000fSantirez 
1763791000fSantirez     lua_newtable(lua);
1773791000fSantirez     lua_pushstring(lua,"err");
1783791000fSantirez     lua_pushlstring(lua,reply+1,p-reply-1);
1793791000fSantirez     lua_settable(lua,-3);
1803791000fSantirez     return p+2;
1813791000fSantirez }
1823791000fSantirez 
redisProtocolToLuaType_MultiBulk(lua_State * lua,char * reply)1833791000fSantirez char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply) {
1843791000fSantirez     char *p = strchr(reply+1,'\r');
1853791000fSantirez     long long mbulklen;
1863791000fSantirez     int j = 0;
1873791000fSantirez 
1883791000fSantirez     string2ll(reply+1,p-reply-1,&mbulklen);
1893791000fSantirez     p += 2;
1903791000fSantirez     if (mbulklen == -1) {
19182c6b825Santirez         lua_pushboolean(lua,0);
1923791000fSantirez         return p;
1933791000fSantirez     }
1943791000fSantirez     lua_newtable(lua);
1953791000fSantirez     for (j = 0; j < mbulklen; j++) {
19610a6da7aSantirez         lua_pushnumber(lua,j+1);
1973791000fSantirez         p = redisProtocolToLuaType(lua,p);
1983791000fSantirez         lua_settable(lua,-3);
1993791000fSantirez     }
2003791000fSantirez     return p;
2013791000fSantirez }
2023791000fSantirez 
203a89a3543Santirez /* This function is used in order to push an error on the Lua stack in the
204a89a3543Santirez  * format used by redis.pcall to return errors, which is a lua table
205a89a3543Santirez  * with a single "err" field set to the error string. Note that this
206a89a3543Santirez  * table is never a valid reply by proper commands, since the returned
207a89a3543Santirez  * tables are otherwise always indexed by integers, never by strings. */
luaPushError(lua_State * lua,char * error)208379789ccSantirez void luaPushError(lua_State *lua, char *error) {
209c3229c33Sioddly     lua_Debug dbg;
210c3229c33Sioddly 
21189bf9696Santirez     /* If debugging is active and in step mode, log errors resulting from
21289bf9696Santirez      * Redis commands. */
21389bf9696Santirez     if (ldb.active && ldb.step) {
21489bf9696Santirez         ldbLog(sdscatprintf(sdsempty(),"<error> %s",error));
21589bf9696Santirez     }
21689bf9696Santirez 
217379789ccSantirez     lua_newtable(lua);
218379789ccSantirez     lua_pushstring(lua,"err");
219c3229c33Sioddly 
220c3229c33Sioddly     /* Attempt to figure out where this function was called, if possible */
221c3229c33Sioddly     if(lua_getstack(lua, 1, &dbg) && lua_getinfo(lua, "nSl", &dbg)) {
222c3229c33Sioddly         sds msg = sdscatprintf(sdsempty(), "%s: %d: %s",
223c3229c33Sioddly             dbg.source, dbg.currentline, error);
224c3229c33Sioddly         lua_pushstring(lua, msg);
225c3229c33Sioddly         sdsfree(msg);
226c3229c33Sioddly     } else {
227379789ccSantirez         lua_pushstring(lua, error);
228c3229c33Sioddly     }
229379789ccSantirez     lua_settable(lua,-3);
230379789ccSantirez }
231379789ccSantirez 
232a89a3543Santirez /* In case the error set into the Lua stack by luaPushError() was generated
233a89a3543Santirez  * by the non-error-trapping version of redis.pcall(), which is redis.call(),
234a89a3543Santirez  * this function will raise the Lua error so that the execution of the
235a89a3543Santirez  * script will be halted. */
luaRaiseError(lua_State * lua)236a89a3543Santirez int luaRaiseError(lua_State *lua) {
237a89a3543Santirez     lua_pushstring(lua,"err");
238a89a3543Santirez     lua_gettable(lua,-2);
239a89a3543Santirez     return lua_error(lua);
240a89a3543Santirez }
241a89a3543Santirez 
242548efd91Santirez /* Sort the array currently in the stack. We do this to make the output
243548efd91Santirez  * of commands like KEYS or SMEMBERS something deterministic when called
244548efd91Santirez  * from Lua (to play well with AOf/replication).
245548efd91Santirez  *
246548efd91Santirez  * The array is sorted using table.sort itself, and assuming all the
247548efd91Santirez  * list elements are strings. */
luaSortArray(lua_State * lua)248548efd91Santirez void luaSortArray(lua_State *lua) {
249548efd91Santirez     /* Initial Stack: array */
250548efd91Santirez     lua_getglobal(lua,"table");
251548efd91Santirez     lua_pushstring(lua,"sort");
252548efd91Santirez     lua_gettable(lua,-2);       /* Stack: array, table, table.sort */
253548efd91Santirez     lua_pushvalue(lua,-3);      /* Stack: array, table, table.sort, array */
2542c861050Santirez     if (lua_pcall(lua,1,0,0)) {
2552c861050Santirez         /* Stack: array, table, error */
2562c861050Santirez 
2572c861050Santirez         /* We are not interested in the error, we assume that the problem is
2582c861050Santirez          * that there are 'false' elements inside the array, so we try
2592c861050Santirez          * again with a slower function but able to handle this case, that
2602c861050Santirez          * is: table.sort(table, __redis__compare_helper) */
2612c861050Santirez         lua_pop(lua,1);             /* Stack: array, table */
2622c861050Santirez         lua_pushstring(lua,"sort"); /* Stack: array, table, sort */
2632c861050Santirez         lua_gettable(lua,-2);       /* Stack: array, table, table.sort */
2642c861050Santirez         lua_pushvalue(lua,-3);      /* Stack: array, table, table.sort, array */
2652c861050Santirez         lua_getglobal(lua,"__redis__compare_helper");
2662c861050Santirez         /* Stack: array, table, table.sort, array, __redis__compare_helper */
2672c861050Santirez         lua_call(lua,2,0);
2682c861050Santirez     }
2692c861050Santirez     /* Stack: array (sorted), table */
270548efd91Santirez     lua_pop(lua,1);             /* Stack: array (sorted) */
271548efd91Santirez }
272548efd91Santirez 
2731fb2b91aSantirez /* ---------------------------------------------------------------------------
2741fb2b91aSantirez  * Lua reply to Redis reply conversion functions.
2751fb2b91aSantirez  * ------------------------------------------------------------------------- */
2761fb2b91aSantirez 
luaReplyToRedisReply(client * c,lua_State * lua)2771fb2b91aSantirez void luaReplyToRedisReply(client *c, lua_State *lua) {
2781fb2b91aSantirez     int t = lua_type(lua,-1);
2791fb2b91aSantirez 
2801fb2b91aSantirez     switch(t) {
2811fb2b91aSantirez     case LUA_TSTRING:
2821fb2b91aSantirez         addReplyBulkCBuffer(c,(char*)lua_tostring(lua,-1),lua_strlen(lua,-1));
2831fb2b91aSantirez         break;
2841fb2b91aSantirez     case LUA_TBOOLEAN:
2851fb2b91aSantirez         addReply(c,lua_toboolean(lua,-1) ? shared.cone : shared.nullbulk);
2861fb2b91aSantirez         break;
2871fb2b91aSantirez     case LUA_TNUMBER:
2881fb2b91aSantirez         addReplyLongLong(c,(long long)lua_tonumber(lua,-1));
2891fb2b91aSantirez         break;
2901fb2b91aSantirez     case LUA_TTABLE:
2911fb2b91aSantirez         /* We need to check if it is an array, an error, or a status reply.
2921fb2b91aSantirez          * Error are returned as a single element table with 'err' field.
2931fb2b91aSantirez          * Status replies are returned as single element table with 'ok'
2941fb2b91aSantirez          * field. */
2951fb2b91aSantirez         lua_pushstring(lua,"err");
2961fb2b91aSantirez         lua_gettable(lua,-2);
2971fb2b91aSantirez         t = lua_type(lua,-1);
2981fb2b91aSantirez         if (t == LUA_TSTRING) {
2991fb2b91aSantirez             sds err = sdsnew(lua_tostring(lua,-1));
3001fb2b91aSantirez             sdsmapchars(err,"\r\n","  ",2);
3011fb2b91aSantirez             addReplySds(c,sdscatprintf(sdsempty(),"-%s\r\n",err));
3021fb2b91aSantirez             sdsfree(err);
3031fb2b91aSantirez             lua_pop(lua,2);
3041fb2b91aSantirez             return;
3051fb2b91aSantirez         }
3061fb2b91aSantirez 
3071fb2b91aSantirez         lua_pop(lua,1);
3081fb2b91aSantirez         lua_pushstring(lua,"ok");
3091fb2b91aSantirez         lua_gettable(lua,-2);
3101fb2b91aSantirez         t = lua_type(lua,-1);
3111fb2b91aSantirez         if (t == LUA_TSTRING) {
3121fb2b91aSantirez             sds ok = sdsnew(lua_tostring(lua,-1));
3131fb2b91aSantirez             sdsmapchars(ok,"\r\n","  ",2);
3141fb2b91aSantirez             addReplySds(c,sdscatprintf(sdsempty(),"+%s\r\n",ok));
3151fb2b91aSantirez             sdsfree(ok);
3161fb2b91aSantirez             lua_pop(lua,1);
3171fb2b91aSantirez         } else {
3181fb2b91aSantirez             void *replylen = addDeferredMultiBulkLength(c);
3191fb2b91aSantirez             int j = 1, mbulklen = 0;
3201fb2b91aSantirez 
3211fb2b91aSantirez             lua_pop(lua,1); /* Discard the 'ok' field value we popped */
3221fb2b91aSantirez             while(1) {
3231fb2b91aSantirez                 lua_pushnumber(lua,j++);
3241fb2b91aSantirez                 lua_gettable(lua,-2);
3251fb2b91aSantirez                 t = lua_type(lua,-1);
3261fb2b91aSantirez                 if (t == LUA_TNIL) {
3271fb2b91aSantirez                     lua_pop(lua,1);
3281fb2b91aSantirez                     break;
3291fb2b91aSantirez                 }
3301fb2b91aSantirez                 luaReplyToRedisReply(c, lua);
3311fb2b91aSantirez                 mbulklen++;
3321fb2b91aSantirez             }
3331fb2b91aSantirez             setDeferredMultiBulkLength(c,replylen,mbulklen);
3341fb2b91aSantirez         }
3351fb2b91aSantirez         break;
3361fb2b91aSantirez     default:
3371fb2b91aSantirez         addReply(c,shared.nullbulk);
3381fb2b91aSantirez     }
3391fb2b91aSantirez     lua_pop(lua,1);
3401fb2b91aSantirez }
3411fb2b91aSantirez 
3421fb2b91aSantirez /* ---------------------------------------------------------------------------
3431fb2b91aSantirez  * Lua redis.* functions implementations.
3441fb2b91aSantirez  * ------------------------------------------------------------------------- */
3451fb2b91aSantirez 
3464f686555Santirez #define LUA_CMD_OBJCACHE_SIZE 32
3474f686555Santirez #define LUA_CMD_OBJCACHE_MAX_LEN 64
luaRedisGenericCommand(lua_State * lua,int raise_error)3489ed32ba0Santirez int luaRedisGenericCommand(lua_State *lua, int raise_error) {
3490f1d64caSantirez     int j, argc = lua_gettop(lua);
3500f1d64caSantirez     struct redisCommand *cmd;
351554bd0e7Santirez     client *c = server.lua_client;
3520f1d64caSantirez     sds reply;
3530f1d64caSantirez 
35448c49c48Santirez     /* Cached across calls. */
35548c49c48Santirez     static robj **argv = NULL;
35648c49c48Santirez     static int argv_size = 0;
3574f686555Santirez     static robj *cached_objects[LUA_CMD_OBJCACHE_SIZE];
358edca2b14Santirez     static size_t cached_objects_len[LUA_CMD_OBJCACHE_SIZE];
359839767adSantirez     static int inuse = 0;   /* Recursive calls detection. */
360839767adSantirez 
361839767adSantirez     /* By using Lua debug hooks it is possible to trigger a recursive call
362839767adSantirez      * to luaRedisGenericCommand(), which normally should never happen.
363839767adSantirez      * To make this function reentrant is futile and makes it slower, but
364839767adSantirez      * we should at least detect such a misuse, and abort. */
365839767adSantirez     if (inuse) {
366e467cf5dSantirez         char *recursion_warning =
367e467cf5dSantirez             "luaRedisGenericCommand() recursive call detected. "
368e467cf5dSantirez             "Are you doing funny stuff with Lua debug hooks?";
36932f80e2fSantirez         serverLog(LL_WARNING,"%s",recursion_warning);
370e467cf5dSantirez         luaPushError(lua,recursion_warning);
371bc867561Santirez         return 1;
372839767adSantirez     }
373839767adSantirez     inuse++;
37448c49c48Santirez 
37546c31a15Santirez     /* Require at least one argument */
37646c31a15Santirez     if (argc == 0) {
37746c31a15Santirez         luaPushError(lua,
37846c31a15Santirez             "Please specify at least one argument for redis.call()");
379839767adSantirez         inuse--;
380a89a3543Santirez         return raise_error ? luaRaiseError(lua) : 1;
38146c31a15Santirez     }
38246c31a15Santirez 
383532e0f5dSantirez     /* Build the arguments vector */
38412b56a96Santirez     if (argv_size < argc) {
38548c49c48Santirez         argv = zrealloc(argv,sizeof(robj*)*argc);
38648c49c48Santirez         argv_size = argc;
38748c49c48Santirez     }
38848c49c48Santirez 
389379789ccSantirez     for (j = 0; j < argc; j++) {
3901e4ba6e7Santirez         char *obj_s;
3911e4ba6e7Santirez         size_t obj_len;
3923758f27bSantirez         char dbuf[64];
3931e4ba6e7Santirez 
39473fefd0bSantirez         if (lua_type(lua,j+1) == LUA_TNUMBER) {
395072982d8Santirez             /* We can't use lua_tolstring() for number -> string conversion
396072982d8Santirez              * since Lua uses a format specifier that loses precision. */
397072982d8Santirez             lua_Number num = lua_tonumber(lua,j+1);
398072982d8Santirez 
399072982d8Santirez             obj_len = snprintf(dbuf,sizeof(dbuf),"%.17g",(double)num);
400072982d8Santirez             obj_s = dbuf;
401072982d8Santirez         } else {
4021e4ba6e7Santirez             obj_s = (char*)lua_tolstring(lua,j+1,&obj_len);
4031e4ba6e7Santirez             if (obj_s == NULL) break; /* Not a string. */
404072982d8Santirez         }
4054f686555Santirez 
4064f686555Santirez         /* Try to use a cached object. */
407ea0e2524Smichael-grunder         if (j < LUA_CMD_OBJCACHE_SIZE && cached_objects[j] &&
408ea0e2524Smichael-grunder             cached_objects_len[j] >= obj_len)
409ea0e2524Smichael-grunder         {
410f15df8baSOran Agra             sds s = cached_objects[j]->ptr;
4114f686555Santirez             argv[j] = cached_objects[j];
4124f686555Santirez             cached_objects[j] = NULL;
4134f686555Santirez             memcpy(s,obj_s,obj_len+1);
414f15df8baSOran Agra             sdssetlen(s, obj_len);
4154f686555Santirez         } else {
4161e4ba6e7Santirez             argv[j] = createStringObject(obj_s, obj_len);
417379789ccSantirez         }
4184f686555Santirez     }
419379789ccSantirez 
420379789ccSantirez     /* Check if one of the arguments passed by the Lua script
421379789ccSantirez      * is not a string or an integer (lua_isstring() return true for
422379789ccSantirez      * integers as well). */
423379789ccSantirez     if (j != argc) {
424379789ccSantirez         j--;
425379789ccSantirez         while (j >= 0) {
426379789ccSantirez             decrRefCount(argv[j]);
427379789ccSantirez             j--;
428379789ccSantirez         }
429379789ccSantirez         luaPushError(lua,
430379789ccSantirez             "Lua redis() command arguments must be strings or integers");
431839767adSantirez         inuse--;
432a89a3543Santirez         return raise_error ? luaRaiseError(lua) : 1;
433379789ccSantirez     }
4340f1d64caSantirez 
43515ef6053Santirez     /* Setup our fake client for command execution */
43615ef6053Santirez     c->argv = argv;
43715ef6053Santirez     c->argc = argc;
43815ef6053Santirez 
43989bf9696Santirez     /* Log the command if debugging is active. */
44089bf9696Santirez     if (ldb.active && ldb.step) {
44189bf9696Santirez         sds cmdlog = sdsnew("<redis>");
44289bf9696Santirez         for (j = 0; j < c->argc; j++) {
44389bf9696Santirez             if (j == 10) {
44489bf9696Santirez                 cmdlog = sdscatprintf(cmdlog," ... (%d more)",
44589bf9696Santirez                     c->argc-j-1);
44689bf9696Santirez             } else {
44789bf9696Santirez                 cmdlog = sdscatlen(cmdlog," ",1);
44889bf9696Santirez                 cmdlog = sdscatsds(cmdlog,c->argv[j]->ptr);
44989bf9696Santirez             }
45089bf9696Santirez         }
45189bf9696Santirez         ldbLog(cmdlog);
45289bf9696Santirez     }
45389bf9696Santirez 
4540f1d64caSantirez     /* Command lookup */
4550f1d64caSantirez     cmd = lookupCommand(argv[0]->ptr);
4563791000fSantirez     if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) ||
4573791000fSantirez                    (argc < -cmd->arity)))
4583791000fSantirez     {
4593791000fSantirez         if (cmd)
460379789ccSantirez             luaPushError(lua,
4613791000fSantirez                 "Wrong number of args calling Redis command From Lua script");
4623791000fSantirez         else
463379789ccSantirez             luaPushError(lua,"Unknown Redis command called from Lua script");
46415ef6053Santirez         goto cleanup;
4650f1d64caSantirez     }
466ba9154d7Santirez     c->cmd = c->lastcmd = cmd;
467532e0f5dSantirez 
468f3fd419fSantirez     /* There are commands that are not allowed inside scripts. */
46932f80e2fSantirez     if (cmd->flags & CMD_NOSCRIPT) {
47015ef6053Santirez         luaPushError(lua, "This Redis command is not allowed from scripts");
47115ef6053Santirez         goto cleanup;
47215ef6053Santirez     }
47315ef6053Santirez 
474f3fd419fSantirez     /* Write commands are forbidden against read-only slaves, or if a
475f3fd419fSantirez      * command marked as non-deterministic was already called in the context
476f3fd419fSantirez      * of this script. */
47732f80e2fSantirez     if (cmd->flags & CMD_WRITE) {
478cbbfaf6aSantirez         if (server.lua_random_dirty && !server.lua_replicate_commands) {
4799f772cc2Santirez             luaPushError(lua,
480cbbfaf6aSantirez                 "Write commands not allowed after non deterministic commands. Call redis.replicate_commands() at the start of your script in order to switch to single commands replication mode.");
4819f772cc2Santirez             goto cleanup;
482f3fd419fSantirez         } else if (server.masterhost && server.repl_slave_ro &&
483d363299aSantirez                    !server.loading &&
48432f80e2fSantirez                    !(server.lua_caller->flags & CLIENT_MASTER))
485f3fd419fSantirez         {
486f3fd419fSantirez             luaPushError(lua, shared.roslaveerr->ptr);
487f3fd419fSantirez             goto cleanup;
488f3fd419fSantirez         } else if (server.stop_writes_on_bgsave_err &&
489f3fd419fSantirez                    server.saveparamslen > 0 &&
49040eb548aSantirez                    server.lastbgsave_status == C_ERR)
491f3fd419fSantirez         {
492f3fd419fSantirez             luaPushError(lua, shared.bgsaveerr->ptr);
493f3fd419fSantirez             goto cleanup;
494f3fd419fSantirez         }
495f3fd419fSantirez     }
496f3fd419fSantirez 
497f3fd419fSantirez     /* If we reached the memory limit configured via maxmemory, commands that
498f3fd419fSantirez      * could enlarge the memory usage are not allowed, but only if this is the
499f3fd419fSantirez      * first write in the context of this script, otherwise we can't stop
500f3fd419fSantirez      * in the middle. */
501f3fd419fSantirez     if (server.maxmemory && server.lua_write_dirty == 0 &&
50232f80e2fSantirez         (cmd->flags & CMD_DENYOOM))
503f3fd419fSantirez     {
50440eb548aSantirez         if (freeMemoryIfNeeded() == C_ERR) {
505f3fd419fSantirez             luaPushError(lua, shared.oomerr->ptr);
506f3fd419fSantirez             goto cleanup;
507f3fd419fSantirez         }
5089f772cc2Santirez     }
5099f772cc2Santirez 
51032f80e2fSantirez     if (cmd->flags & CMD_RANDOM) server.lua_random_dirty = 1;
51132f80e2fSantirez     if (cmd->flags & CMD_WRITE) server.lua_write_dirty = 1;
5129f772cc2Santirez 
513da95d22aSantirez     /* If this is a Redis Cluster node, we need to make sure Lua is not
5142f4240b9Santirez      * trying to access non-local keys, with the exception of commands
515746e1bebSantirez      * received from our master or when loading the AOF back in memory. */
516746e1bebSantirez     if (server.cluster_enabled && !server.loading &&
517746e1bebSantirez         !(server.lua_caller->flags & CLIENT_MASTER))
518746e1bebSantirez     {
519da95d22aSantirez         /* Duplicate relevant flags in the lua client. */
52032f80e2fSantirez         c->flags &= ~(CLIENT_READONLY|CLIENT_ASKING);
52132f80e2fSantirez         c->flags |= server.lua_caller->flags & (CLIENT_READONLY|CLIENT_ASKING);
522da95d22aSantirez         if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) !=
523da95d22aSantirez                            server.cluster->myself)
524da95d22aSantirez         {
525da95d22aSantirez             luaPushError(lua,
526da95d22aSantirez                 "Lua script attempted to access a non local key in a "
527da95d22aSantirez                 "cluster node");
528da95d22aSantirez             goto cleanup;
529da95d22aSantirez         }
530da95d22aSantirez     }
531da95d22aSantirez 
532cbbfaf6aSantirez     /* If we are using single commands replication, we need to wrap what
533cbbfaf6aSantirez      * we propagate into a MULTI/EXEC block, so that it will be atomic like
534cbbfaf6aSantirez      * a Lua script in the context of AOF and slaves. */
535cbbfaf6aSantirez     if (server.lua_replicate_commands &&
536cbbfaf6aSantirez         !server.lua_multi_emitted &&
537a1d1ca14Santirez         server.lua_write_dirty &&
538a1d1ca14Santirez         server.lua_repl != PROPAGATE_NONE)
539cbbfaf6aSantirez     {
540cbbfaf6aSantirez         execCommandPropagateMulti(server.lua_caller);
541cbbfaf6aSantirez         server.lua_multi_emitted = 1;
542cbbfaf6aSantirez     }
543cbbfaf6aSantirez 
54415ef6053Santirez     /* Run the command */
545cbbfaf6aSantirez     int call_flags = CMD_CALL_SLOWLOG | CMD_CALL_STATS;
546a1d1ca14Santirez     if (server.lua_replicate_commands) {
547dfe7f797Santirez         /* Set flags according to redis.set_repl() settings. */
548dfe7f797Santirez         if (server.lua_repl & PROPAGATE_AOF)
549dfe7f797Santirez             call_flags |= CMD_CALL_PROPAGATE_AOF;
550dfe7f797Santirez         if (server.lua_repl & PROPAGATE_REPL)
551dfe7f797Santirez             call_flags |= CMD_CALL_PROPAGATE_REPL;
552a1d1ca14Santirez     }
553cbbfaf6aSantirez     call(c,call_flags);
5540f1d64caSantirez 
5550f1d64caSantirez     /* Convert the result of the Redis command into a suitable Lua type.
5560f1d64caSantirez      * The first thing we need is to create a single string from the client
5570f1d64caSantirez      * output buffers. */
55832f80e2fSantirez     if (listLength(c->reply) == 0 && c->bufpos < PROTO_REPLY_CHUNK_BYTES) {
5590ef4f44cSantirez         /* This is a fast path for the common case of a reply inside the
5600ef4f44cSantirez          * client static buffer. Don't create an SDS string but just use
5610ef4f44cSantirez          * the client buffer directly. */
5620ef4f44cSantirez         c->buf[c->bufpos] = '\0';
5630ef4f44cSantirez         reply = c->buf;
5643318b747Santirez         c->bufpos = 0;
5650ef4f44cSantirez     } else {
56640abeb1fSantirez         reply = sdsnewlen(c->buf,c->bufpos);
5670f1d64caSantirez         c->bufpos = 0;
5680f1d64caSantirez         while(listLength(c->reply)) {
5690f1d64caSantirez             robj *o = listNodeValue(listFirst(c->reply));
5700f1d64caSantirez 
57109ab5591Santirez             reply = sdscatlen(reply,o->ptr,sdslen(o->ptr));
5720f1d64caSantirez             listDelNode(c->reply,listFirst(c->reply));
5730f1d64caSantirez         }
5740ef4f44cSantirez     }
5759ed32ba0Santirez     if (raise_error && reply[0] != '-') raise_error = 0;
576532e0f5dSantirez     redisProtocolToLuaType(lua,reply);
57789bf9696Santirez 
57889bf9696Santirez     /* If the debugger is active, log the reply from Redis. */
5798a0020f1Santirez     if (ldb.active && ldb.step)
58079c6e689Santirez         ldbLogRedisReply(reply);
58189bf9696Santirez 
582548efd91Santirez     /* Sort the output array if needed, assuming it is a non-null multi bulk
583548efd91Santirez      * reply as expected. */
58432f80e2fSantirez     if ((cmd->flags & CMD_SORT_FOR_SCRIPT) &&
585cbbfaf6aSantirez         (server.lua_replicate_commands == 0) &&
586548efd91Santirez         (reply[0] == '*' && reply[1] != '-')) {
587548efd91Santirez             luaSortArray(lua);
588548efd91Santirez     }
5890ef4f44cSantirez     if (reply != c->buf) sdsfree(reply);
590e323635cSantirez     c->reply_bytes = 0;
5910f1d64caSantirez 
59215ef6053Santirez cleanup:
5930f1d64caSantirez     /* Clean up. Command code may have changed argv/argc so we use the
5940f1d64caSantirez      * argv/argc of the client instead of the local variables. */
5954f686555Santirez     for (j = 0; j < c->argc; j++) {
5964f686555Santirez         robj *o = c->argv[j];
5974f686555Santirez 
5984f686555Santirez         /* Try to cache the object in the cached_objects array.
5994f686555Santirez          * The object must be small, SDS-encoded, and with refcount = 1
6004f686555Santirez          * (we must be the only owner) for us to cache it. */
6014f686555Santirez         if (j < LUA_CMD_OBJCACHE_SIZE &&
6024f686555Santirez             o->refcount == 1 &&
60314ff5724Santirez             (o->encoding == OBJ_ENCODING_RAW ||
60414ff5724Santirez              o->encoding == OBJ_ENCODING_EMBSTR) &&
6054f686555Santirez             sdslen(o->ptr) <= LUA_CMD_OBJCACHE_MAX_LEN)
6064f686555Santirez         {
607f15df8baSOran Agra             sds s = o->ptr;
6084f686555Santirez             if (cached_objects[j]) decrRefCount(cached_objects[j]);
6094f686555Santirez             cached_objects[j] = o;
610f15df8baSOran Agra             cached_objects_len[j] = sdsalloc(s);
6114f686555Santirez         } else {
6124f686555Santirez             decrRefCount(o);
6134f686555Santirez         }
6144f686555Santirez     }
6154f686555Santirez 
61648c49c48Santirez     if (c->argv != argv) {
6170f1d64caSantirez         zfree(c->argv);
61848c49c48Santirez         argv = NULL;
61912b56a96Santirez         argv_size = 0;
62048c49c48Santirez     }
6210f1d64caSantirez 
6229ed32ba0Santirez     if (raise_error) {
6239ed32ba0Santirez         /* If we are here we should have an error in the stack, in the
6249ed32ba0Santirez          * form of a table with an "err" field. Extract the string to
6259ed32ba0Santirez          * return the plain error. */
626839767adSantirez         inuse--;
627a89a3543Santirez         return luaRaiseError(lua);
6289ed32ba0Santirez     }
629839767adSantirez     inuse--;
6300f1d64caSantirez     return 1;
6310f1d64caSantirez }
6320f1d64caSantirez 
633cbbfaf6aSantirez /* redis.call() */
luaRedisCallCommand(lua_State * lua)6349ed32ba0Santirez int luaRedisCallCommand(lua_State *lua) {
6359ed32ba0Santirez     return luaRedisGenericCommand(lua,1);
6369ed32ba0Santirez }
6379ed32ba0Santirez 
638cbbfaf6aSantirez /* redis.pcall() */
luaRedisPCallCommand(lua_State * lua)6399ed32ba0Santirez int luaRedisPCallCommand(lua_State *lua) {
6409ed32ba0Santirez     return luaRedisGenericCommand(lua,0);
6419ed32ba0Santirez }
6429ed32ba0Santirez 
64352ae8af8SNathan Fritz /* This adds redis.sha1hex(string) to Lua scripts using the same hashing
64452ae8af8SNathan Fritz  * function used for sha1ing lua scripts. */
luaRedisSha1hexCommand(lua_State * lua)64552ae8af8SNathan Fritz int luaRedisSha1hexCommand(lua_State *lua) {
64652ae8af8SNathan Fritz     int argc = lua_gettop(lua);
64752ae8af8SNathan Fritz     char digest[41];
64852ae8af8SNathan Fritz     size_t len;
64952ae8af8SNathan Fritz     char *s;
65052ae8af8SNathan Fritz 
65152ae8af8SNathan Fritz     if (argc != 1) {
65261fb0545Santirez         lua_pushstring(lua, "wrong number of arguments");
65361fb0545Santirez         return lua_error(lua);
65452ae8af8SNathan Fritz     }
65552ae8af8SNathan Fritz 
65652ae8af8SNathan Fritz     s = (char*)lua_tolstring(lua,1,&len);
65752ae8af8SNathan Fritz     sha1hex(digest,s,len);
65852ae8af8SNathan Fritz     lua_pushstring(lua,digest);
65952ae8af8SNathan Fritz     return 1;
66052ae8af8SNathan Fritz }
66152ae8af8SNathan Fritz 
6629c21b72bSantirez /* Returns a table with a single field 'field' set to the string value
6639c21b72bSantirez  * passed as argument. This helper function is handy when returning
6649c21b72bSantirez  * a Redis Protocol error or status reply from Lua:
6659c21b72bSantirez  *
6669c21b72bSantirez  * return redis.error_reply("ERR Some Error")
6679c21b72bSantirez  * return redis.status_reply("ERR Some Error")
6689c21b72bSantirez  */
luaRedisReturnSingleFieldTable(lua_State * lua,char * field)6699c21b72bSantirez int luaRedisReturnSingleFieldTable(lua_State *lua, char *field) {
6709c21b72bSantirez     if (lua_gettop(lua) != 1 || lua_type(lua,-1) != LUA_TSTRING) {
6719c21b72bSantirez         luaPushError(lua, "wrong number or type of arguments");
6729c21b72bSantirez         return 1;
6739c21b72bSantirez     }
6749c21b72bSantirez 
6759c21b72bSantirez     lua_newtable(lua);
6769c21b72bSantirez     lua_pushstring(lua, field);
6779c21b72bSantirez     lua_pushvalue(lua, -3);
6789c21b72bSantirez     lua_settable(lua, -3);
6799c21b72bSantirez     return 1;
6809c21b72bSantirez }
6819c21b72bSantirez 
682cbbfaf6aSantirez /* redis.error_reply() */
luaRedisErrorReplyCommand(lua_State * lua)6839c21b72bSantirez int luaRedisErrorReplyCommand(lua_State *lua) {
6849c21b72bSantirez     return luaRedisReturnSingleFieldTable(lua,"err");
6859c21b72bSantirez }
6869c21b72bSantirez 
687cbbfaf6aSantirez /* redis.status_reply() */
luaRedisStatusReplyCommand(lua_State * lua)6889c21b72bSantirez int luaRedisStatusReplyCommand(lua_State *lua) {
6899c21b72bSantirez     return luaRedisReturnSingleFieldTable(lua,"ok");
6909c21b72bSantirez }
6919c21b72bSantirez 
692cbbfaf6aSantirez /* redis.replicate_commands()
693cbbfaf6aSantirez  *
694cbbfaf6aSantirez  * Turn on single commands replication if the script never called
695cbbfaf6aSantirez  * a write command so far, and returns true. Otherwise if the script
696cbbfaf6aSantirez  * already started to write, returns false and stick to whole scripts
697cbbfaf6aSantirez  * replication, which is our default. */
luaRedisReplicateCommandsCommand(lua_State * lua)698cbbfaf6aSantirez int luaRedisReplicateCommandsCommand(lua_State *lua) {
699cbbfaf6aSantirez     if (server.lua_write_dirty) {
700cbbfaf6aSantirez         lua_pushboolean(lua,0);
701cbbfaf6aSantirez     } else {
702cbbfaf6aSantirez         server.lua_replicate_commands = 1;
703cbbfaf6aSantirez         /* When we switch to single commands replication, we can provide
704cbbfaf6aSantirez          * different math.random() sequences at every call, which is what
705cbbfaf6aSantirez          * the user normally expects. */
706cbbfaf6aSantirez         redisSrand48(rand());
707cbbfaf6aSantirez         lua_pushboolean(lua,1);
708cbbfaf6aSantirez     }
709cbbfaf6aSantirez     return 1;
710cbbfaf6aSantirez }
711cbbfaf6aSantirez 
71251de527aSantirez /* redis.breakpoint()
71351de527aSantirez  *
71451de527aSantirez  * Allows to stop execution during a debuggign session from within
71551de527aSantirez  * the Lua code implementation, like if a breakpoint was set in the code
71651de527aSantirez  * immediately after the function. */
luaRedisBreakpointCommand(lua_State * lua)71751de527aSantirez int luaRedisBreakpointCommand(lua_State *lua) {
71851de527aSantirez     if (ldb.active) {
71951de527aSantirez         ldb.luabp = 1;
72051de527aSantirez         lua_pushboolean(lua,1);
72151de527aSantirez     } else {
72251de527aSantirez         lua_pushboolean(lua,0);
72351de527aSantirez     }
72451de527aSantirez     return 1;
72551de527aSantirez }
72651de527aSantirez 
7278f8c6b3bSantirez /* redis.debug()
7288f8c6b3bSantirez  *
7298f8c6b3bSantirez  * Log a string message into the output console.
7308f8c6b3bSantirez  * Can take multiple arguments that will be separated by commas.
7318f8c6b3bSantirez  * Nothing is returned to the caller. */
luaRedisDebugCommand(lua_State * lua)7328f8c6b3bSantirez int luaRedisDebugCommand(lua_State *lua) {
7338f8c6b3bSantirez     if (!ldb.active) return 0;
7348f8c6b3bSantirez     int argc = lua_gettop(lua);
7358f8c6b3bSantirez     sds log = sdscatprintf(sdsempty(),"<debug> line %d: ", ldb.currentline);
7368f8c6b3bSantirez     while(argc--) {
7378f8c6b3bSantirez         log = ldbCatStackValue(log,lua,-1 - argc);
7388f8c6b3bSantirez         if (argc != 0) log = sdscatlen(log,", ",2);
7398f8c6b3bSantirez     }
7408f8c6b3bSantirez     ldbLog(log);
7418f8c6b3bSantirez     return 0;
7428f8c6b3bSantirez }
7438f8c6b3bSantirez 
744a1d1ca14Santirez /* redis.set_repl()
745a1d1ca14Santirez  *
746a1d1ca14Santirez  * Set the propagation of write commands executed in the context of the
747a1d1ca14Santirez  * script to on/off for AOF and slaves. */
luaRedisSetReplCommand(lua_State * lua)748a1d1ca14Santirez int luaRedisSetReplCommand(lua_State *lua) {
749a1d1ca14Santirez     int argc = lua_gettop(lua);
750a1d1ca14Santirez     int flags;
751a1d1ca14Santirez 
752a1d1ca14Santirez     if (server.lua_replicate_commands == 0) {
75361fb0545Santirez         lua_pushstring(lua, "You can set the replication behavior only after turning on single commands replication with redis.replicate_commands().");
75461fb0545Santirez         return lua_error(lua);
755a1d1ca14Santirez     } else if (argc != 1) {
75661fb0545Santirez         lua_pushstring(lua, "redis.set_repl() requires two arguments.");
75761fb0545Santirez         return lua_error(lua);
758a1d1ca14Santirez     }
759a1d1ca14Santirez 
760a1d1ca14Santirez     flags = lua_tonumber(lua,-1);
761a1d1ca14Santirez     if ((flags & ~(PROPAGATE_AOF|PROPAGATE_REPL)) != 0) {
76261fb0545Santirez         lua_pushstring(lua, "Invalid replication flags. Use REPL_AOF, REPL_SLAVE, REPL_ALL or REPL_NONE.");
76361fb0545Santirez         return lua_error(lua);
764a1d1ca14Santirez     }
765a1d1ca14Santirez     server.lua_repl = flags;
766a1d1ca14Santirez     return 0;
767a1d1ca14Santirez }
768a1d1ca14Santirez 
769cbbfaf6aSantirez /* redis.log() */
luaLogCommand(lua_State * lua)770288f811fSantirez int luaLogCommand(lua_State *lua) {
771288f811fSantirez     int j, argc = lua_gettop(lua);
772288f811fSantirez     int level;
773288f811fSantirez     sds log;
774288f811fSantirez 
775288f811fSantirez     if (argc < 2) {
77661fb0545Santirez         lua_pushstring(lua, "redis.log() requires two arguments or more.");
77761fb0545Santirez         return lua_error(lua);
778288f811fSantirez     } else if (!lua_isnumber(lua,-argc)) {
77961fb0545Santirez         lua_pushstring(lua, "First argument must be a number (log level).");
78061fb0545Santirez         return lua_error(lua);
781288f811fSantirez     }
782288f811fSantirez     level = lua_tonumber(lua,-argc);
78332f80e2fSantirez     if (level < LL_DEBUG || level > LL_WARNING) {
78461fb0545Santirez         lua_pushstring(lua, "Invalid debug level.");
78561fb0545Santirez         return lua_error(lua);
786288f811fSantirez     }
787288f811fSantirez 
788288f811fSantirez     /* Glue together all the arguments */
789288f811fSantirez     log = sdsempty();
790288f811fSantirez     for (j = 1; j < argc; j++) {
791288f811fSantirez         size_t len;
792288f811fSantirez         char *s;
793288f811fSantirez 
794288f811fSantirez         s = (char*)lua_tolstring(lua,(-argc)+j,&len);
795288f811fSantirez         if (s) {
796288f811fSantirez             if (j != 1) log = sdscatlen(log," ",1);
797288f811fSantirez             log = sdscatlen(log,s,len);
798288f811fSantirez         }
799288f811fSantirez     }
800424fe9afSantirez     serverLogRaw(level,log);
801288f811fSantirez     sdsfree(log);
802288f811fSantirez     return 0;
803288f811fSantirez }
804288f811fSantirez 
8051fb2b91aSantirez /* ---------------------------------------------------------------------------
8061fb2b91aSantirez  * Lua engine initialization and reset.
8071fb2b91aSantirez  * ------------------------------------------------------------------------- */
808eeffcf38Santirez 
luaLoadLib(lua_State * lua,const char * libname,lua_CFunction luafunc)809002d5626Santirez void luaLoadLib(lua_State *lua, const char *libname, lua_CFunction luafunc) {
810002d5626Santirez   lua_pushcfunction(lua, luafunc);
811002d5626Santirez   lua_pushstring(lua, libname);
812002d5626Santirez   lua_call(lua, 1, 0);
813002d5626Santirez }
814002d5626Santirez 
81515108778Santirez LUALIB_API int (luaopen_cjson) (lua_State *L);
8162f75bbabSlsbardel LUALIB_API int (luaopen_struct) (lua_State *L);
81763505e0bSantirez LUALIB_API int (luaopen_cmsgpack) (lua_State *L);
8183fecb961SMatt Stancliff LUALIB_API int (luaopen_bit) (lua_State *L);
81915108778Santirez 
luaLoadLibraries(lua_State * lua)820002d5626Santirez void luaLoadLibraries(lua_State *lua) {
821002d5626Santirez     luaLoadLib(lua, "", luaopen_base);
822002d5626Santirez     luaLoadLib(lua, LUA_TABLIBNAME, luaopen_table);
823002d5626Santirez     luaLoadLib(lua, LUA_STRLIBNAME, luaopen_string);
824002d5626Santirez     luaLoadLib(lua, LUA_MATHLIBNAME, luaopen_math);
825002d5626Santirez     luaLoadLib(lua, LUA_DBLIBNAME, luaopen_debug);
82615108778Santirez     luaLoadLib(lua, "cjson", luaopen_cjson);
8272f75bbabSlsbardel     luaLoadLib(lua, "struct", luaopen_struct);
82863505e0bSantirez     luaLoadLib(lua, "cmsgpack", luaopen_cmsgpack);
8293fecb961SMatt Stancliff     luaLoadLib(lua, "bit", luaopen_bit);
830002d5626Santirez 
831002d5626Santirez #if 0 /* Stuff that we don't load currently, for sandboxing concerns. */
832002d5626Santirez     luaLoadLib(lua, LUA_LOADLIBNAME, luaopen_package);
833002d5626Santirez     luaLoadLib(lua, LUA_OSLIBNAME, luaopen_os);
834002d5626Santirez #endif
835002d5626Santirez }
836002d5626Santirez 
837a3f99081Santirez /* Remove a functions that we don't want to expose to the Redis scripting
838a3f99081Santirez  * environment. */
luaRemoveUnsupportedFunctions(lua_State * lua)839a3f99081Santirez void luaRemoveUnsupportedFunctions(lua_State *lua) {
840a3f99081Santirez     lua_pushnil(lua);
841a3f99081Santirez     lua_setglobal(lua,"loadfile");
842*95def3aeSAdam Baldwin     lua_pushnil(lua);
843*95def3aeSAdam Baldwin     lua_setglobal(lua,"dofile");
844a3f99081Santirez }
845a3f99081Santirez 
84637b29ef2Santirez /* This function installs metamethods in the global table _G that prevent
84737b29ef2Santirez  * the creation of globals accidentally.
84837b29ef2Santirez  *
84937b29ef2Santirez  * It should be the last to be called in the scripting engine initialization
8506663653fSantirez  * sequence, because it may interact with creation of globals. */
scriptingEnableGlobalsProtection(lua_State * lua)85137b29ef2Santirez void scriptingEnableGlobalsProtection(lua_State *lua) {
85237b29ef2Santirez     char *s[32];
8530cdecca1Santirez     sds code = sdsempty();
85437b29ef2Santirez     int j = 0;
8550cdecca1Santirez 
85637b29ef2Santirez     /* strict.lua from: http://metalua.luaforge.net/src/lib/strict.lua.html.
85737b29ef2Santirez      * Modified to be adapted to Redis. */
858ffd6637eSBen Murphy     s[j++]="local dbg=debug\n";
859c9edd1b2Santirez     s[j++]="local mt = {}\n";
86037b29ef2Santirez     s[j++]="setmetatable(_G, mt)\n";
86137b29ef2Santirez     s[j++]="mt.__newindex = function (t, n, v)\n";
862ffd6637eSBen Murphy     s[j++]="  if dbg.getinfo(2) then\n";
863ffd6637eSBen Murphy     s[j++]="    local w = dbg.getinfo(2, \"S\").what\n";
86437b29ef2Santirez     s[j++]="    if w ~= \"main\" and w ~= \"C\" then\n";
8656663653fSantirez     s[j++]="      error(\"Script attempted to create global variable '\"..tostring(n)..\"'\", 2)\n";
86637b29ef2Santirez     s[j++]="    end\n";
86737b29ef2Santirez     s[j++]="  end\n";
86837b29ef2Santirez     s[j++]="  rawset(t, n, v)\n";
86937b29ef2Santirez     s[j++]="end\n";
87037b29ef2Santirez     s[j++]="mt.__index = function (t, n)\n";
871ffd6637eSBen Murphy     s[j++]="  if dbg.getinfo(2) and dbg.getinfo(2, \"S\").what ~= \"C\" then\n";
8723a021404Santirez     s[j++]="    error(\"Script attempted to access unexisting global variable '\"..tostring(n)..\"'\", 2)\n";
87337b29ef2Santirez     s[j++]="  end\n";
87437b29ef2Santirez     s[j++]="  return rawget(t, n)\n";
87537b29ef2Santirez     s[j++]="end\n";
876ffd6637eSBen Murphy     s[j++]="debug = nil\n";
87737b29ef2Santirez     s[j++]=NULL;
8780cdecca1Santirez 
87937b29ef2Santirez     for (j = 0; s[j] != NULL; j++) code = sdscatlen(code,s[j],strlen(s[j]));
8806f659f34Santirez     luaL_loadbuffer(lua,code,sdslen(code),"@enable_strict_lua");
8810cdecca1Santirez     lua_pcall(lua,0,0,0);
8820cdecca1Santirez     sdsfree(code);
8830cdecca1Santirez }
8840cdecca1Santirez 
885070e3945Santirez /* Initialize the scripting environment.
886d6c24ff6Santirez  *
887d6c24ff6Santirez  * This function is called the first time at server startup with
888d6c24ff6Santirez  * the 'setup' argument set to 1.
889d6c24ff6Santirez  *
890d6c24ff6Santirez  * It can be called again multiple times during the lifetime of the Redis
891d6c24ff6Santirez  * process, with 'setup' set to 0, and following a scriptingRelease() call,
892d6c24ff6Santirez  * in order to reset the Lua scripting environment.
893d6c24ff6Santirez  *
894d6c24ff6Santirez  * However it is simpler to just call scriptingReset() that does just that. */
scriptingInit(int setup)895d6c24ff6Santirez void scriptingInit(int setup) {
8967585836eSantirez     lua_State *lua = lua_open();
897a3f99081Santirez 
898d6c24ff6Santirez     if (setup) {
899d6c24ff6Santirez         server.lua_client = NULL;
900d6c24ff6Santirez         server.lua_caller = NULL;
901d6c24ff6Santirez         server.lua_timedout = 0;
902d6c24ff6Santirez         server.lua_always_replicate_commands = 0; /* Only DEBUG can change it.*/
903d6c24ff6Santirez         server.lua_time_limit = LUA_SCRIPT_TIME_LIMIT;
904def31636Santirez         ldbInit();
905d6c24ff6Santirez     }
906d6c24ff6Santirez 
907002d5626Santirez     luaLoadLibraries(lua);
908a3f99081Santirez     luaRemoveUnsupportedFunctions(lua);
9090f1d64caSantirez 
9104dd444bbSantirez     /* Initialize a dictionary we use to map SHAs to scripts.
9114dd444bbSantirez      * This is useful for replication, as we need to replicate EVALSHA
9124dd444bbSantirez      * as EVAL, so we need to remember the associated script. */
91395f68f7bSantirez     server.lua_scripts = dictCreate(&shaScriptObjectDictType,NULL);
9144dd444bbSantirez 
915288f811fSantirez     /* Register the redis commands table and fields */
916288f811fSantirez     lua_newtable(lua);
917288f811fSantirez 
918288f811fSantirez     /* redis.call */
919288f811fSantirez     lua_pushstring(lua,"call");
9209ed32ba0Santirez     lua_pushcfunction(lua,luaRedisCallCommand);
9219ed32ba0Santirez     lua_settable(lua,-3);
9229ed32ba0Santirez 
9239ed32ba0Santirez     /* redis.pcall */
9249ed32ba0Santirez     lua_pushstring(lua,"pcall");
9259ed32ba0Santirez     lua_pushcfunction(lua,luaRedisPCallCommand);
926288f811fSantirez     lua_settable(lua,-3);
927288f811fSantirez 
928288f811fSantirez     /* redis.log and log levels. */
929288f811fSantirez     lua_pushstring(lua,"log");
930288f811fSantirez     lua_pushcfunction(lua,luaLogCommand);
931288f811fSantirez     lua_settable(lua,-3);
932288f811fSantirez 
93347daa9b0SItamar Haber     lua_pushstring(lua,"LOG_DEBUG");
93432f80e2fSantirez     lua_pushnumber(lua,LL_DEBUG);
935288f811fSantirez     lua_settable(lua,-3);
936288f811fSantirez 
93747daa9b0SItamar Haber     lua_pushstring(lua,"LOG_VERBOSE");
93832f80e2fSantirez     lua_pushnumber(lua,LL_VERBOSE);
939288f811fSantirez     lua_settable(lua,-3);
940288f811fSantirez 
94147daa9b0SItamar Haber     lua_pushstring(lua,"LOG_NOTICE");
94232f80e2fSantirez     lua_pushnumber(lua,LL_NOTICE);
943288f811fSantirez     lua_settable(lua,-3);
944288f811fSantirez 
94547daa9b0SItamar Haber     lua_pushstring(lua,"LOG_WARNING");
94632f80e2fSantirez     lua_pushnumber(lua,LL_WARNING);
947288f811fSantirez     lua_settable(lua,-3);
948288f811fSantirez 
94952ae8af8SNathan Fritz     /* redis.sha1hex */
95052ae8af8SNathan Fritz     lua_pushstring(lua, "sha1hex");
95152ae8af8SNathan Fritz     lua_pushcfunction(lua, luaRedisSha1hexCommand);
95252ae8af8SNathan Fritz     lua_settable(lua, -3);
95352ae8af8SNathan Fritz 
9549c21b72bSantirez     /* redis.error_reply and redis.status_reply */
9559c21b72bSantirez     lua_pushstring(lua, "error_reply");
9569c21b72bSantirez     lua_pushcfunction(lua, luaRedisErrorReplyCommand);
9579c21b72bSantirez     lua_settable(lua, -3);
9589c21b72bSantirez     lua_pushstring(lua, "status_reply");
9599c21b72bSantirez     lua_pushcfunction(lua, luaRedisStatusReplyCommand);
9609c21b72bSantirez     lua_settable(lua, -3);
9619c21b72bSantirez 
962cbbfaf6aSantirez     /* redis.replicate_commands */
963cbbfaf6aSantirez     lua_pushstring(lua, "replicate_commands");
964cbbfaf6aSantirez     lua_pushcfunction(lua, luaRedisReplicateCommandsCommand);
965cbbfaf6aSantirez     lua_settable(lua, -3);
966cbbfaf6aSantirez 
967a1d1ca14Santirez     /* redis.set_repl and associated flags. */
968a1d1ca14Santirez     lua_pushstring(lua,"set_repl");
969a1d1ca14Santirez     lua_pushcfunction(lua,luaRedisSetReplCommand);
970a1d1ca14Santirez     lua_settable(lua,-3);
971a1d1ca14Santirez 
972a1d1ca14Santirez     lua_pushstring(lua,"REPL_NONE");
973a1d1ca14Santirez     lua_pushnumber(lua,PROPAGATE_NONE);
974a1d1ca14Santirez     lua_settable(lua,-3);
975a1d1ca14Santirez 
976a1d1ca14Santirez     lua_pushstring(lua,"REPL_AOF");
977a1d1ca14Santirez     lua_pushnumber(lua,PROPAGATE_AOF);
978a1d1ca14Santirez     lua_settable(lua,-3);
979a1d1ca14Santirez 
980a1d1ca14Santirez     lua_pushstring(lua,"REPL_SLAVE");
981a1d1ca14Santirez     lua_pushnumber(lua,PROPAGATE_REPL);
982a1d1ca14Santirez     lua_settable(lua,-3);
983a1d1ca14Santirez 
984a1d1ca14Santirez     lua_pushstring(lua,"REPL_ALL");
985a1d1ca14Santirez     lua_pushnumber(lua,PROPAGATE_AOF|PROPAGATE_REPL);
986a1d1ca14Santirez     lua_settable(lua,-3);
987a1d1ca14Santirez 
98851de527aSantirez     /* redis.breakpoint */
98951de527aSantirez     lua_pushstring(lua,"breakpoint");
99051de527aSantirez     lua_pushcfunction(lua,luaRedisBreakpointCommand);
99151de527aSantirez     lua_settable(lua,-3);
99251de527aSantirez 
9938f8c6b3bSantirez     /* redis.debug */
9948f8c6b3bSantirez     lua_pushstring(lua,"debug");
9958f8c6b3bSantirez     lua_pushcfunction(lua,luaRedisDebugCommand);
9968f8c6b3bSantirez     lua_settable(lua,-3);
9978f8c6b3bSantirez 
998288f811fSantirez     /* Finally set the table as 'redis' global var. */
99900b7541bSantirez     lua_setglobal(lua,"redis");
10000f1d64caSantirez 
1001e108bab0Santirez     /* Replace math.random and math.randomseed with our implementations. */
1002e108bab0Santirez     lua_getglobal(lua,"math");
1003e108bab0Santirez 
1004e108bab0Santirez     lua_pushstring(lua,"random");
1005e108bab0Santirez     lua_pushcfunction(lua,redis_math_random);
1006e108bab0Santirez     lua_settable(lua,-3);
1007e108bab0Santirez 
1008e108bab0Santirez     lua_pushstring(lua,"randomseed");
1009e108bab0Santirez     lua_pushcfunction(lua,redis_math_randomseed);
1010e108bab0Santirez     lua_settable(lua,-3);
1011e108bab0Santirez 
1012e108bab0Santirez     lua_setglobal(lua,"math");
1013e108bab0Santirez 
10149d09ce39Sguiquanz     /* Add a helper function that we use to sort the multi bulk output of non
10152c861050Santirez      * deterministic commands, when containing 'false' elements. */
10162c861050Santirez     {
10172c861050Santirez         char *compare_func =    "function __redis__compare_helper(a,b)\n"
10182c861050Santirez                                 "  if a == false then a = '' end\n"
10192c861050Santirez                                 "  if b == false then b = '' end\n"
10202c861050Santirez                                 "  return a<b\n"
10212c861050Santirez                                 "end\n";
10226f659f34Santirez         luaL_loadbuffer(lua,compare_func,strlen(compare_func),"@cmp_func_def");
10232c861050Santirez         lua_pcall(lua,0,0,0);
10242c861050Santirez     }
10252c861050Santirez 
102651adc6e1Santirez     /* Add a helper function we use for pcall error reporting.
102751adc6e1Santirez      * Note that when the error is in the C function we want to report the
102851adc6e1Santirez      * information about the caller, that's what makes sense from the point
102951adc6e1Santirez      * of view of the user debugging a script. */
103051adc6e1Santirez     {
1031ffd6637eSBen Murphy         char *errh_func =       "local dbg = debug\n"
1032ffd6637eSBen Murphy                                 "function __redis__err__handler(err)\n"
1033ffd6637eSBen Murphy                                 "  local i = dbg.getinfo(2,'nSl')\n"
103451adc6e1Santirez                                 "  if i and i.what == 'C' then\n"
1035ffd6637eSBen Murphy                                 "    i = dbg.getinfo(3,'nSl')\n"
103651adc6e1Santirez                                 "  end\n"
103751adc6e1Santirez                                 "  if i then\n"
10389c2c878eSantirez                                 "    return i.source .. ':' .. i.currentline .. ': ' .. err\n"
103951adc6e1Santirez                                 "  else\n"
104051adc6e1Santirez                                 "    return err\n"
104151adc6e1Santirez                                 "  end\n"
104251adc6e1Santirez                                 "end\n";
104351adc6e1Santirez         luaL_loadbuffer(lua,errh_func,strlen(errh_func),"@err_handler_def");
104451adc6e1Santirez         lua_pcall(lua,0,0,0);
104551adc6e1Santirez     }
104651adc6e1Santirez 
10470f1d64caSantirez     /* Create the (non connected) client that we use to execute Redis commands
1048070e3945Santirez      * inside the Lua interpreter.
1049070e3945Santirez      * Note: there is no need to create it again when this function is called
1050070e3945Santirez      * by scriptingReset(). */
1051070e3945Santirez     if (server.lua_client == NULL) {
10520f1d64caSantirez         server.lua_client = createClient(-1);
105332f80e2fSantirez         server.lua_client->flags |= CLIENT_LUA;
1054070e3945Santirez     }
10550f1d64caSantirez 
1056a63b9c24SJuarez Bochi     /* Lua beginners often don't use "local", this is likely to introduce
10570cdecca1Santirez      * subtle bugs in their code. To prevent problems we protect accesses
10580cdecca1Santirez      * to global variables. */
105937b29ef2Santirez     scriptingEnableGlobalsProtection(lua);
10600cdecca1Santirez 
10617585836eSantirez     server.lua = lua;
10627585836eSantirez }
10637585836eSantirez 
1064070e3945Santirez /* Release resources related to Lua scripting.
1065070e3945Santirez  * This function is used in order to reset the scripting environment. */
scriptingRelease(void)1066070e3945Santirez void scriptingRelease(void) {
1067070e3945Santirez     dictRelease(server.lua_scripts);
1068070e3945Santirez     lua_close(server.lua);
1069070e3945Santirez }
1070070e3945Santirez 
scriptingReset(void)1071070e3945Santirez void scriptingReset(void) {
1072070e3945Santirez     scriptingRelease();
1073d6c24ff6Santirez     scriptingInit(0);
1074070e3945Santirez }
1075070e3945Santirez 
10764ae5b5e1Santirez /* Set an array of Redis String Objects as a Lua array (table) stored into a
10774ae5b5e1Santirez  * global variable. */
luaSetGlobalArray(lua_State * lua,char * var,robj ** elev,int elec)10784ae5b5e1Santirez void luaSetGlobalArray(lua_State *lua, char *var, robj **elev, int elec) {
10794ae5b5e1Santirez     int j;
10804ae5b5e1Santirez 
10814ae5b5e1Santirez     lua_newtable(lua);
10824ae5b5e1Santirez     for (j = 0; j < elec; j++) {
10834ae5b5e1Santirez         lua_pushlstring(lua,(char*)elev[j]->ptr,sdslen(elev[j]->ptr));
10844ae5b5e1Santirez         lua_rawseti(lua,-2,j+1);
10854ae5b5e1Santirez     }
10864ae5b5e1Santirez     lua_setglobal(lua,var);
10874ae5b5e1Santirez }
10884ae5b5e1Santirez 
10891fb2b91aSantirez /* ---------------------------------------------------------------------------
10901fb2b91aSantirez  * Redis provided math.random
10911fb2b91aSantirez  * ------------------------------------------------------------------------- */
10921fb2b91aSantirez 
10931fb2b91aSantirez /* We replace math.random() with our implementation that is not affected
10941fb2b91aSantirez  * by specific libc random() implementations and will output the same sequence
10951fb2b91aSantirez  * (for the same seed) in every arch. */
10961fb2b91aSantirez 
10971fb2b91aSantirez /* The following implementation is the one shipped with Lua itself but with
10981fb2b91aSantirez  * rand() replaced by redisLrand48(). */
redis_math_random(lua_State * L)10991fb2b91aSantirez int redis_math_random (lua_State *L) {
11001fb2b91aSantirez   /* the `%' avoids the (rare) case of r==1, and is needed also because on
11011fb2b91aSantirez      some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
11021fb2b91aSantirez   lua_Number r = (lua_Number)(redisLrand48()%REDIS_LRAND48_MAX) /
11031fb2b91aSantirez                                 (lua_Number)REDIS_LRAND48_MAX;
11041fb2b91aSantirez   switch (lua_gettop(L)) {  /* check number of arguments */
11051fb2b91aSantirez     case 0: {  /* no arguments */
11061fb2b91aSantirez       lua_pushnumber(L, r);  /* Number between 0 and 1 */
11071fb2b91aSantirez       break;
11081fb2b91aSantirez     }
11091fb2b91aSantirez     case 1: {  /* only upper limit */
11101fb2b91aSantirez       int u = luaL_checkint(L, 1);
11111fb2b91aSantirez       luaL_argcheck(L, 1<=u, 1, "interval is empty");
11121fb2b91aSantirez       lua_pushnumber(L, floor(r*u)+1);  /* int between 1 and `u' */
11131fb2b91aSantirez       break;
11141fb2b91aSantirez     }
11151fb2b91aSantirez     case 2: {  /* lower and upper limits */
11161fb2b91aSantirez       int l = luaL_checkint(L, 1);
11171fb2b91aSantirez       int u = luaL_checkint(L, 2);
11181fb2b91aSantirez       luaL_argcheck(L, l<=u, 2, "interval is empty");
11191fb2b91aSantirez       lua_pushnumber(L, floor(r*(u-l+1))+l);  /* int between `l' and `u' */
11201fb2b91aSantirez       break;
11211fb2b91aSantirez     }
11221fb2b91aSantirez     default: return luaL_error(L, "wrong number of arguments");
11231fb2b91aSantirez   }
11241fb2b91aSantirez   return 1;
11251fb2b91aSantirez }
11261fb2b91aSantirez 
redis_math_randomseed(lua_State * L)11271fb2b91aSantirez int redis_math_randomseed (lua_State *L) {
11281fb2b91aSantirez   redisSrand48(luaL_checkint(L, 1));
11291fb2b91aSantirez   return 0;
11301fb2b91aSantirez }
11311fb2b91aSantirez 
11321fb2b91aSantirez /* ---------------------------------------------------------------------------
11331fb2b91aSantirez  * EVAL and SCRIPT commands implementation
11341fb2b91aSantirez  * ------------------------------------------------------------------------- */
11351fb2b91aSantirez 
1136a9b07ac4Santirez /* Define a lua function with the specified function name and body.
113792c146dfSJiahao Huang  * The function name musts be a 42 characters long string, since all the
1138a9b07ac4Santirez  * functions we defined in the Lua context are in the form:
1139a9b07ac4Santirez  *
1140a9b07ac4Santirez  *   f_<hex sha1 sum>
1141a9b07ac4Santirez  *
114240eb548aSantirez  * On success C_OK is returned, and nothing is left on the Lua stack.
114340eb548aSantirez  * On error C_ERR is returned and an appropriate error is set in the
1144a9b07ac4Santirez  * client context. */
luaCreateFunction(client * c,lua_State * lua,char * funcname,robj * body)1145554bd0e7Santirez int luaCreateFunction(client *c, lua_State *lua, char *funcname, robj *body) {
1146a9b07ac4Santirez     sds funcdef = sdsempty();
1147a9b07ac4Santirez 
1148a9b07ac4Santirez     funcdef = sdscat(funcdef,"function ");
1149a9b07ac4Santirez     funcdef = sdscatlen(funcdef,funcname,42);
11504d776dbaSJakub Wieczorek     funcdef = sdscatlen(funcdef,"() ",3);
1151a9b07ac4Santirez     funcdef = sdscatlen(funcdef,body->ptr,sdslen(body->ptr));
11525fd61c95Santirez     funcdef = sdscatlen(funcdef,"\nend",4);
1153a9b07ac4Santirez 
11546f659f34Santirez     if (luaL_loadbuffer(lua,funcdef,sdslen(funcdef),"@user_script")) {
1155a9b07ac4Santirez         addReplyErrorFormat(c,"Error compiling script (new function): %s\n",
1156a9b07ac4Santirez             lua_tostring(lua,-1));
1157a9b07ac4Santirez         lua_pop(lua,1);
1158a9b07ac4Santirez         sdsfree(funcdef);
115940eb548aSantirez         return C_ERR;
1160a9b07ac4Santirez     }
1161a9b07ac4Santirez     sdsfree(funcdef);
1162a9b07ac4Santirez     if (lua_pcall(lua,0,0,0)) {
1163a9b07ac4Santirez         addReplyErrorFormat(c,"Error running script (new function): %s\n",
1164a9b07ac4Santirez             lua_tostring(lua,-1));
1165a9b07ac4Santirez         lua_pop(lua,1);
116640eb548aSantirez         return C_ERR;
1167a9b07ac4Santirez     }
1168a9b07ac4Santirez 
1169a9b07ac4Santirez     /* We also save a SHA1 -> Original script map in a dictionary
1170a9b07ac4Santirez      * so that we can replicate / write in the AOF all the
1171a9b07ac4Santirez      * EVALSHA commands as EVAL using the original script. */
1172a9b07ac4Santirez     {
1173a9b07ac4Santirez         int retval = dictAdd(server.lua_scripts,
1174a9b07ac4Santirez                              sdsnewlen(funcname+2,40),body);
11752d9e3eb1Santirez         serverAssertWithInfo(c,NULL,retval == DICT_OK);
1176a9b07ac4Santirez         incrRefCount(body);
1177a9b07ac4Santirez     }
117840eb548aSantirez     return C_OK;
1179a9b07ac4Santirez }
1180a9b07ac4Santirez 
11811fb2b91aSantirez /* This is the Lua script "count" hook that we use to detect scripts timeout. */
luaMaskCountHook(lua_State * lua,lua_Debug * ar)11821fb2b91aSantirez void luaMaskCountHook(lua_State *lua, lua_Debug *ar) {
11831fb2b91aSantirez     long long elapsed;
11841fb2b91aSantirez     UNUSED(ar);
11851fb2b91aSantirez     UNUSED(lua);
11861fb2b91aSantirez 
11871fb2b91aSantirez     elapsed = mstime() - server.lua_time_start;
11881fb2b91aSantirez     if (elapsed >= server.lua_time_limit && server.lua_timedout == 0) {
11891fb2b91aSantirez         serverLog(LL_WARNING,"Lua slow script detected: still in execution after %lld milliseconds. You can try killing the script using the SCRIPT KILL command.",elapsed);
11901fb2b91aSantirez         server.lua_timedout = 1;
11911fb2b91aSantirez         /* Once the script timeouts we reenter the event loop to permit others
11921fb2b91aSantirez          * to call SCRIPT KILL or SHUTDOWN NOSAVE if needed. For this reason
11931fb2b91aSantirez          * we need to mask the client executing the script from the event loop.
11941fb2b91aSantirez          * If we don't do that the client may disconnect and could no longer be
11951fb2b91aSantirez          * here when the EVAL command will return. */
11961fb2b91aSantirez          aeDeleteFileEvent(server.el, server.lua_caller->fd, AE_READABLE);
11971fb2b91aSantirez     }
11981fb2b91aSantirez     if (server.lua_timedout) processEventsWhileBlocked();
11991fb2b91aSantirez     if (server.lua_kill) {
12001fb2b91aSantirez         serverLog(LL_WARNING,"Lua script killed by user with SCRIPT KILL.");
12011fb2b91aSantirez         lua_pushstring(lua,"Script killed by user with SCRIPT KILL...");
12021fb2b91aSantirez         lua_error(lua);
12031fb2b91aSantirez     }
12041fb2b91aSantirez }
12051fb2b91aSantirez 
evalGenericCommand(client * c,int evalsha)1206554bd0e7Santirez void evalGenericCommand(client *c, int evalsha) {
12077585836eSantirez     lua_State *lua = server.lua;
12087585836eSantirez     char funcname[43];
12094ae5b5e1Santirez     long long numkeys;
1210baee5650Santirez     int delhook = 0, err;
12114ae5b5e1Santirez 
1212cbbfaf6aSantirez     /* When we replicate whole scripts, we want the same PRNG sequence at
1213cbbfaf6aSantirez      * every call so that our PRNG is not affected by external state. */
1214e108bab0Santirez     redisSrand48(0);
1215e108bab0Santirez 
12169f772cc2Santirez     /* We set this flag to zero to remember that so far no random command
12179f772cc2Santirez      * was called. This way we can allow the user to call commands like
12189f772cc2Santirez      * SRANDMEMBER or RANDOMKEY from Lua scripts as far as no write command
12199f772cc2Santirez      * is called (otherwise the replication and AOF would end with non
12209f772cc2Santirez      * deterministic sequences).
12219f772cc2Santirez      *
12229f772cc2Santirez      * Thanks to this flag we'll raise an error every time a write command
12239f772cc2Santirez      * is called after a random command was used. */
12249f772cc2Santirez     server.lua_random_dirty = 0;
12254ab8695dSantirez     server.lua_write_dirty = 0;
12268695d960Santirez     server.lua_replicate_commands = server.lua_always_replicate_commands;
1227cbbfaf6aSantirez     server.lua_multi_emitted = 0;
1228a1d1ca14Santirez     server.lua_repl = PROPAGATE_AOF|PROPAGATE_REPL;
12299f772cc2Santirez 
12304ae5b5e1Santirez     /* Get the number of arguments that are keys */
123140eb548aSantirez     if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != C_OK)
12324ae5b5e1Santirez         return;
12334ae5b5e1Santirez     if (numkeys > (c->argc - 3)) {
12344ae5b5e1Santirez         addReplyError(c,"Number of keys can't be greater than number of args");
12354ae5b5e1Santirez         return;
1236f17f8521SMatt Stancliff     } else if (numkeys < 0) {
1237f17f8521SMatt Stancliff         addReplyError(c,"Number of keys can't be negative");
1238f17f8521SMatt Stancliff         return;
12394ae5b5e1Santirez     }
12407585836eSantirez 
12417585836eSantirez     /* We obtain the script SHA1, then check if this function is already
12427585836eSantirez      * defined into the Lua state */
12437585836eSantirez     funcname[0] = 'f';
12447585836eSantirez     funcname[1] = '_';
12457229d60dSantirez     if (!evalsha) {
12467229d60dSantirez         /* Hash the code if this is an EVAL call */
124752ae8af8SNathan Fritz         sha1hex(funcname+2,c->argv[1]->ptr,sdslen(c->argv[1]->ptr));
12487229d60dSantirez     } else {
12497229d60dSantirez         /* We already have the SHA if it is a EVALSHA */
12507229d60dSantirez         int j;
12517229d60dSantirez         char *sha = c->argv[1]->ptr;
12527229d60dSantirez 
1253c49955fdSantirez         /* Convert to lowercase. We don't use tolower since the function
1254c49955fdSantirez          * managed to always show up in the profiler output consuming
1255c49955fdSantirez          * a non trivial amount of time. */
12567229d60dSantirez         for (j = 0; j < 40; j++)
1257c49955fdSantirez             funcname[j+2] = (sha[j] >= 'A' && sha[j] <= 'Z') ?
1258c49955fdSantirez                 sha[j]+('a'-'A') : sha[j];
12597229d60dSantirez         funcname[42] = '\0';
12607229d60dSantirez     }
12617229d60dSantirez 
126251adc6e1Santirez     /* Push the pcall error handler function on the stack. */
126351adc6e1Santirez     lua_getglobal(lua, "__redis__err__handler");
126451adc6e1Santirez 
1265a9b07ac4Santirez     /* Try to lookup the Lua function */
12667585836eSantirez     lua_getglobal(lua, funcname);
126751adc6e1Santirez     if (lua_isnil(lua,-1)) {
1268e8c993f0Santirez         lua_pop(lua,1); /* remove the nil from the stack */
12697229d60dSantirez         /* Function not defined... let's define it if we have the
12709d09ce39Sguiquanz          * body of the function. If this is an EVALSHA call we can just
12717229d60dSantirez          * return an error. */
12727229d60dSantirez         if (evalsha) {
127351adc6e1Santirez             lua_pop(lua,1); /* remove the error handler from the stack. */
12747229d60dSantirez             addReply(c, shared.noscripterr);
12757229d60dSantirez             return;
12767229d60dSantirez         }
127740eb548aSantirez         if (luaCreateFunction(c,lua,funcname,c->argv[1]) == C_ERR) {
127841d31473Santirez             lua_pop(lua,1); /* remove the error handler from the stack. */
127941d31473Santirez             /* The error is sent to the client by luaCreateFunction()
128040eb548aSantirez              * itself when it returns C_ERR. */
128141d31473Santirez             return;
128241d31473Santirez         }
1283a9b07ac4Santirez         /* Now the following is guaranteed to return non nil */
12847585836eSantirez         lua_getglobal(lua, funcname);
12852d9e3eb1Santirez         serverAssert(!lua_isnil(lua,-1));
12867585836eSantirez     }
12877585836eSantirez 
12884ae5b5e1Santirez     /* Populate the argv and keys table accordingly to the arguments that
12894ae5b5e1Santirez      * EVAL received. */
12904ae5b5e1Santirez     luaSetGlobalArray(lua,"KEYS",c->argv+3,numkeys);
12914ae5b5e1Santirez     luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys);
12924ae5b5e1Santirez 
1293c2a7dd85Santirez     /* Select the right DB in the context of the Lua client */
1294c2a7dd85Santirez     selectDb(server.lua_client,c->db->id);
1295c2a7dd85Santirez 
129611e81a1eSantirez     /* Set a hook in order to be able to stop the script execution if it
1297da386cdfSantirez      * is running for too much time.
1298da386cdfSantirez      * We set the hook only if the time limit is enabled as the hook will
1299def31636Santirez      * make the Lua script execution slower.
1300def31636Santirez      *
1301def31636Santirez      * If we are debugging, we set instead a "line" hook so that the
1302def31636Santirez      * debugger is call-back at every line executed by the script. */
13030ad10db2Santirez     server.lua_caller = c;
130489884e8fSantirez     server.lua_time_start = mstime();
13050ad10db2Santirez     server.lua_kill = 0;
1306def31636Santirez     if (server.lua_time_limit > 0 && server.masterhost == NULL &&
1307def31636Santirez         ldb.active == 0)
1308def31636Santirez     {
1309da386cdfSantirez         lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000);
13100ad10db2Santirez         delhook = 1;
1311def31636Santirez     } else if (ldb.active) {
131200eb8a63Santirez         lua_sethook(server.lua,luaLdbLineHook,LUA_MASKLINE|LUA_MASKCOUNT,100000);
1313def31636Santirez         delhook = 1;
1314da386cdfSantirez     }
1315da386cdfSantirez 
1316c3229c33Sioddly     /* At this point whether this script was never seen before or if it was
13177585836eSantirez      * already defined, we can call it. We have zero arguments and expect
13187585836eSantirez      * a single return value. */
131951adc6e1Santirez     err = lua_pcall(lua,0,1,-2);
1320baee5650Santirez 
1321baee5650Santirez     /* Perform some cleanup that we need to do both on error and success. */
1322def31636Santirez     if (delhook) lua_sethook(lua,NULL,0,0); /* Disable hook */
13234ab8695dSantirez     if (server.lua_timedout) {
1324115e3ff3Santirez         server.lua_timedout = 0;
13254ab8695dSantirez         /* Restore the readable handler that was unregistered when the
13264ab8695dSantirez          * script timeout was detected. */
13274ab8695dSantirez         aeCreateFileEvent(server.el,c->fd,AE_READABLE,
13284ab8695dSantirez                           readQueryFromClient,c);
13294ab8695dSantirez     }
13304ab8695dSantirez     server.lua_caller = NULL;
133176fda9f8Santirez 
133276fda9f8Santirez     /* Call the Lua garbage collector from time to time to avoid a
133376fda9f8Santirez      * full cycle performed by Lua, which adds too latency.
133476fda9f8Santirez      *
133576fda9f8Santirez      * The call is performed every LUA_GC_CYCLE_PERIOD executed commands
133676fda9f8Santirez      * (and for LUA_GC_CYCLE_PERIOD collection steps) because calling it
133776fda9f8Santirez      * for every command uses too much CPU. */
133876fda9f8Santirez     #define LUA_GC_CYCLE_PERIOD 50
133976fda9f8Santirez     {
134076fda9f8Santirez         static long gc_count = 0;
134176fda9f8Santirez 
134276fda9f8Santirez         gc_count++;
134376fda9f8Santirez         if (gc_count == LUA_GC_CYCLE_PERIOD) {
134476fda9f8Santirez             lua_gc(lua,LUA_GCSTEP,LUA_GC_CYCLE_PERIOD);
134576fda9f8Santirez             gc_count = 0;
134676fda9f8Santirez         }
134776fda9f8Santirez     }
1348baee5650Santirez 
1349baee5650Santirez     if (err) {
13507585836eSantirez         addReplyErrorFormat(c,"Error running script (call to %s): %s\n",
13517585836eSantirez             funcname, lua_tostring(lua,-1));
135241d31473Santirez         lua_pop(lua,2); /* Consume the Lua reply and remove error handler. */
1353baee5650Santirez     } else {
1354baee5650Santirez         /* On success convert the Lua return value into Redis protocol, and
1355baee5650Santirez          * send it to * the client. */
135641d31473Santirez         luaReplyToRedisReply(c,lua); /* Convert and consume the reply. */
135741d31473Santirez         lua_pop(lua,1); /* Remove the error handler. */
1358baee5650Santirez     }
13594dd444bbSantirez 
1360e9d2329cSantirez     /* If we are using single commands replication, emit EXEC if there
1361e9d2329cSantirez      * was at least a write. */
1362e9d2329cSantirez     if (server.lua_replicate_commands) {
1363e9d2329cSantirez         preventCommandPropagation(c);
1364e9d2329cSantirez         if (server.lua_multi_emitted) {
1365e9d2329cSantirez             robj *propargv[1];
1366e9d2329cSantirez             propargv[0] = createStringObject("EXEC",4);
1367e9d2329cSantirez             alsoPropagate(server.execCommand,c->db->id,propargv,1,
1368e9d2329cSantirez                 PROPAGATE_AOF|PROPAGATE_REPL);
1369e9d2329cSantirez             decrRefCount(propargv[0]);
1370e9d2329cSantirez         }
1371e9d2329cSantirez     }
1372e9d2329cSantirez 
1373f0bf5fd8Santirez     /* EVALSHA should be propagated to Slave and AOF file as full EVAL, unless
1374f0bf5fd8Santirez      * we are sure that the script was already in the context of all the
1375f0bf5fd8Santirez      * attached slaves *and* the current AOF file if enabled.
13764dd444bbSantirez      *
1377f0bf5fd8Santirez      * To do so we use a cache of SHA1s of scripts that we already propagated
1378f0bf5fd8Santirez      * as full EVAL, that's called the Replication Script Cache.
1379f0bf5fd8Santirez      *
1380f0bf5fd8Santirez      * For repliation, everytime a new slave attaches to the master, we need to
1381f0bf5fd8Santirez      * flush our cache of scripts that can be replicated as EVALSHA, while
1382f0bf5fd8Santirez      * for AOF we need to do so every time we rewrite the AOF file. */
1383cbbfaf6aSantirez     if (evalsha && !server.lua_replicate_commands) {
1384f0bf5fd8Santirez         if (!replicationScriptCacheExists(c->argv[1]->ptr)) {
1385f0bf5fd8Santirez             /* This script is not in our script cache, replicate it as
1386f0bf5fd8Santirez              * EVAL, then add it into the script cache, as from now on
1387f0bf5fd8Santirez              * slaves and AOF know about it. */
13884dd444bbSantirez             robj *script = dictFetchValue(server.lua_scripts,c->argv[1]->ptr);
13894dd444bbSantirez 
1390f0bf5fd8Santirez             replicationScriptCacheAdd(c->argv[1]->ptr);
13912d9e3eb1Santirez             serverAssertWithInfo(c,NULL,script != NULL);
13924dd444bbSantirez             rewriteClientCommandArgument(c,0,
13934dd444bbSantirez                 resetRefCount(createStringObject("EVAL",4)));
13944dd444bbSantirez             rewriteClientCommandArgument(c,1,script);
139532f80e2fSantirez             forceCommandPropagation(c,PROPAGATE_REPL|PROPAGATE_AOF);
13964dd444bbSantirez         }
13977585836eSantirez     }
1398f0bf5fd8Santirez }
13997229d60dSantirez 
evalCommand(client * c)1400554bd0e7Santirez void evalCommand(client *c) {
1401def31636Santirez     if (!(c->flags & CLIENT_LUA_DEBUG))
14027229d60dSantirez         evalGenericCommand(c,0);
1403def31636Santirez     else
1404def31636Santirez         evalGenericCommandWithDebugging(c,0);
14057229d60dSantirez }
14067229d60dSantirez 
evalShaCommand(client * c)1407554bd0e7Santirez void evalShaCommand(client *c) {
14087229d60dSantirez     if (sdslen(c->argv[1]->ptr) != 40) {
14097229d60dSantirez         /* We know that a match is not possible if the provided SHA is
14107229d60dSantirez          * not the right length. So we return an error ASAP, this way
14117229d60dSantirez          * evalGenericCommand() can be implemented without string length
14127229d60dSantirez          * sanity check */
14137229d60dSantirez         addReply(c, shared.noscripterr);
14147229d60dSantirez         return;
14157229d60dSantirez     }
1416def31636Santirez     if (!(c->flags & CLIENT_LUA_DEBUG))
14177229d60dSantirez         evalGenericCommand(c,1);
1418def31636Santirez     else {
1419def31636Santirez         addReplyError(c,"Please use EVAL instead of EVALSHA for debugging");
1420def31636Santirez         return;
1421def31636Santirez     }
14227229d60dSantirez }
1423e108bab0Santirez 
scriptCommand(client * c)1424554bd0e7Santirez void scriptCommand(client *c) {
1425070e3945Santirez     if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"flush")) {
1426070e3945Santirez         scriptingReset();
1427070e3945Santirez         addReply(c,shared.ok);
142873d7955cSantirez         replicationScriptCacheFlush();
1429e27b1360Santirez         server.dirty++; /* Propagating this command is a good idea. */
1430070e3945Santirez     } else if (c->argc >= 2 && !strcasecmp(c->argv[1]->ptr,"exists")) {
1431070e3945Santirez         int j;
1432070e3945Santirez 
1433070e3945Santirez         addReplyMultiBulkLen(c, c->argc-2);
1434070e3945Santirez         for (j = 2; j < c->argc; j++) {
1435070e3945Santirez             if (dictFind(server.lua_scripts,c->argv[j]->ptr))
1436070e3945Santirez                 addReply(c,shared.cone);
1437070e3945Santirez             else
1438070e3945Santirez                 addReply(c,shared.czero);
1439070e3945Santirez         }
1440a9b07ac4Santirez     } else if (c->argc == 3 && !strcasecmp(c->argv[1]->ptr,"load")) {
1441a9b07ac4Santirez         char funcname[43];
1442e8c993f0Santirez         sds sha;
1443a9b07ac4Santirez 
1444a9b07ac4Santirez         funcname[0] = 'f';
1445a9b07ac4Santirez         funcname[1] = '_';
144652ae8af8SNathan Fritz         sha1hex(funcname+2,c->argv[2]->ptr,sdslen(c->argv[2]->ptr));
1447e8c993f0Santirez         sha = sdsnewlen(funcname+2,40);
1448e8c993f0Santirez         if (dictFind(server.lua_scripts,sha) == NULL) {
1449e8c993f0Santirez             if (luaCreateFunction(c,server.lua,funcname,c->argv[2])
145040eb548aSantirez                     == C_ERR) {
1451e8c993f0Santirez                 sdsfree(sha);
1452a9b07ac4Santirez                 return;
1453e8c993f0Santirez             }
1454e8c993f0Santirez         }
1455e5abf6efSantirez         addReplyBulkCBuffer(c,funcname+2,40);
1456e8c993f0Santirez         sdsfree(sha);
145732f80e2fSantirez         forceCommandPropagation(c,PROPAGATE_REPL|PROPAGATE_AOF);
14584ab8695dSantirez     } else if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"kill")) {
14594ab8695dSantirez         if (server.lua_caller == NULL) {
1460acfe3675Santirez             addReplySds(c,sdsnew("-NOTBUSY No scripts in execution right now.\r\n"));
14614ab8695dSantirez         } else if (server.lua_write_dirty) {
146211e81a1eSantirez             addReplySds(c,sdsnew("-UNKILLABLE Sorry the script already executed write commands against the dataset. You can either wait the script termination or kill the server in a hard way using the SHUTDOWN NOSAVE command.\r\n"));
14634ab8695dSantirez         } else {
14644ab8695dSantirez             server.lua_kill = 1;
14654ab8695dSantirez             addReply(c,shared.ok);
14664ab8695dSantirez         }
1467def31636Santirez     } else if (c->argc == 3 && !strcasecmp(c->argv[1]->ptr,"debug")) {
1468def31636Santirez         if (clientHasPendingReplies(c)) {
1469def31636Santirez             addReplyError(c,"SCRIPT DEBUG must be called outside a pipeline");
1470def31636Santirez             return;
1471def31636Santirez         }
1472def31636Santirez         if (!strcasecmp(c->argv[2]->ptr,"no")) {
1473def31636Santirez             ldbDisable(c);
1474c62b66fdSantirez             addReply(c,shared.ok);
1475def31636Santirez         } else if (!strcasecmp(c->argv[2]->ptr,"yes")) {
1476d6c24ff6Santirez             ldbEnable(c);
1477d6c24ff6Santirez             addReply(c,shared.ok);
1478def31636Santirez         } else if (!strcasecmp(c->argv[2]->ptr,"sync")) {
1479def31636Santirez             ldbEnable(c);
1480def31636Santirez             addReply(c,shared.ok);
1481def31636Santirez             c->flags |= CLIENT_LUA_DEBUG_SYNC;
1482def31636Santirez         } else {
1483bcc49136Santirez             addReplyError(c,"Use SCRIPT DEBUG yes/sync/no");
1484def31636Santirez         }
1485070e3945Santirez     } else {
1486070e3945Santirez         addReplyError(c, "Unknown SCRIPT subcommand or wrong # of args.");
1487070e3945Santirez     }
1488070e3945Santirez }
14891fb2b91aSantirez 
1490def31636Santirez /* ---------------------------------------------------------------------------
1491def31636Santirez  * LDB: Redis Lua debugging facilities
1492def31636Santirez  * ------------------------------------------------------------------------- */
1493def31636Santirez 
1494def31636Santirez /* Initialize Lua debugger data structures. */
ldbInit(void)1495def31636Santirez void ldbInit(void) {
1496def31636Santirez     ldb.fd = -1;
1497def31636Santirez     ldb.active = 0;
1498def31636Santirez     ldb.logs = listCreate();
1499def31636Santirez     listSetFreeMethod(ldb.logs,(void (*)(void*))sdsfree);
1500cdb92412Santirez     ldb.children = listCreate();
1501def31636Santirez     ldb.src = NULL;
150202de5d99Santirez     ldb.lines = 0;
150302de5d99Santirez     ldb.cbuf = sdsempty();
1504def31636Santirez }
1505def31636Santirez 
1506def31636Santirez /* Remove all the pending messages in the specified list. */
ldbFlushLog(list * log)1507def31636Santirez void ldbFlushLog(list *log) {
1508def31636Santirez     listNode *ln;
1509def31636Santirez 
1510def31636Santirez     while((ln = listFirst(log)) != NULL)
1511def31636Santirez         listDelNode(log,ln);
1512def31636Santirez }
1513def31636Santirez 
1514def31636Santirez /* Enable debug mode of Lua scripts for this client. */
ldbEnable(client * c)1515def31636Santirez void ldbEnable(client *c) {
1516def31636Santirez     c->flags |= CLIENT_LUA_DEBUG;
1517def31636Santirez     ldbFlushLog(ldb.logs);
1518def31636Santirez     ldb.fd = c->fd;
151902de5d99Santirez     ldb.step = 1;
1520def31636Santirez     ldb.bpcount = 0;
152151de527aSantirez     ldb.luabp = 0;
152202de5d99Santirez     sdsfree(ldb.cbuf);
152302de5d99Santirez     ldb.cbuf = sdsempty();
152479c6e689Santirez     ldb.maxlen = LDB_MAX_LEN_DEFAULT;
152579c6e689Santirez     ldb.maxlen_hint_sent = 0;
1526def31636Santirez }
1527def31636Santirez 
152879c6e689Santirez /* Exit debugging mode from the POV of client. This function is not enough
152979c6e689Santirez  * to properly shut down a client debugging session, see ldbEndSession()
153079c6e689Santirez  * for more information. */
ldbDisable(client * c)1531def31636Santirez void ldbDisable(client *c) {
1532def31636Santirez     c->flags &= ~(CLIENT_LUA_DEBUG|CLIENT_LUA_DEBUG_SYNC);
1533def31636Santirez }
1534def31636Santirez 
1535def31636Santirez /* Append a log entry to the specified LDB log. */
ldbLog(sds entry)153602de5d99Santirez void ldbLog(sds entry) {
153702de5d99Santirez     listAddNodeTail(ldb.logs,entry);
1538def31636Santirez }
1539def31636Santirez 
154079c6e689Santirez /* A version of ldbLog() which prevents producing logs greater than
154179c6e689Santirez  * ldb.maxlen. The first time the limit is reached an hint is generated
154279c6e689Santirez  * to inform the user that reply trimming can be disabled using the
154379c6e689Santirez  * debugger "maxlen" command. */
ldbLogWithMaxLen(sds entry)154479c6e689Santirez void ldbLogWithMaxLen(sds entry) {
154579c6e689Santirez     int trimmed = 0;
154679c6e689Santirez     if (ldb.maxlen && sdslen(entry) > ldb.maxlen) {
154779c6e689Santirez         sdsrange(entry,0,ldb.maxlen-1);
154879c6e689Santirez         entry = sdscatlen(entry," ...",4);
154979c6e689Santirez         trimmed = 1;
155079c6e689Santirez     }
155179c6e689Santirez     ldbLog(entry);
155279c6e689Santirez     if (trimmed && ldb.maxlen_hint_sent == 0) {
155379c6e689Santirez         ldb.maxlen_hint_sent = 1;
155479c6e689Santirez         ldbLog(sdsnew(
155579c6e689Santirez         "<hint> The above reply was trimmed. Use 'maxlen 0' to disable trimming."));
155679c6e689Santirez     }
155779c6e689Santirez }
155879c6e689Santirez 
155902de5d99Santirez /* Send ldb.logs to the debugging client as a multi-bulk reply
156002de5d99Santirez  * consisting of simple strings. Log entries which include newlines have them
156102de5d99Santirez  * replaced with spaces. The entries sent are also consumed. */
ldbSendLogs(void)156202de5d99Santirez void ldbSendLogs(void) {
156302de5d99Santirez     sds proto = sdsempty();
156402de5d99Santirez     proto = sdscatfmt(proto,"*%i\r\n", (int)listLength(ldb.logs));
156502de5d99Santirez     while(listLength(ldb.logs)) {
156602de5d99Santirez         listNode *ln = listFirst(ldb.logs);
156702de5d99Santirez         proto = sdscatlen(proto,"+",1);
156802de5d99Santirez         sdsmapchars(ln->value,"\r\n","  ",2);
156902de5d99Santirez         proto = sdscatsds(proto,ln->value);
157002de5d99Santirez         proto = sdscatlen(proto,"\r\n",2);
157102de5d99Santirez         listDelNode(ldb.logs,ln);
157202de5d99Santirez     }
1573ef92f90dSantirez     if (write(ldb.fd,proto,sdslen(proto)) == -1) {
1574ef92f90dSantirez         /* Avoid warning. We don't check the return value of write()
1575ef92f90dSantirez          * since the next read() will catch the I/O error and will
1576ef92f90dSantirez          * close the debugging session. */
1577ef92f90dSantirez     }
15784a00bccfSantirez     sdsfree(proto);
1579def31636Santirez }
1580def31636Santirez 
1581def31636Santirez /* Start a debugging session before calling EVAL implementation.
1582def31636Santirez  * The techique we use is to capture the client socket file descriptor,
1583def31636Santirez  * in order to perform direct I/O with it from within Lua hooks. This
1584def31636Santirez  * way we don't have to re-enter Redis in order to handle I/O.
1585def31636Santirez  *
1586def31636Santirez  * The function returns 1 if the caller should proceed to call EVAL,
1587def31636Santirez  * and 0 if instead the caller should abort the operation (this happens
1588def31636Santirez  * for the parent in a forked session, since it's up to the children
1589def31636Santirez  * to continue, or when fork returned an error).
1590def31636Santirez  *
1591def31636Santirez  * The caller should call ldbEndSession() only if ldbStartSession()
1592def31636Santirez  * returned 1. */
ldbStartSession(client * c)1593def31636Santirez int ldbStartSession(client *c) {
1594def31636Santirez     ldb.forked = (c->flags & CLIENT_LUA_DEBUG_SYNC) == 0;
1595def31636Santirez     if (ldb.forked) {
1596def31636Santirez         pid_t cp = fork();
1597def31636Santirez         if (cp == -1) {
1598def31636Santirez             addReplyError(c,"Fork() failed: can't run EVAL in debugging mode.");
1599def31636Santirez             return 0;
1600def31636Santirez         } else if (cp == 0) {
1601cdb92412Santirez             /* Child. Let's ignore important signals handled by the parent. */
1602cdb92412Santirez             struct sigaction act;
1603cdb92412Santirez             sigemptyset(&act.sa_mask);
1604cdb92412Santirez             act.sa_flags = 0;
1605cdb92412Santirez             act.sa_handler = SIG_IGN;
1606cdb92412Santirez             sigaction(SIGTERM, &act, NULL);
1607cdb92412Santirez             sigaction(SIGINT, &act, NULL);
1608cdb92412Santirez 
1609cdb92412Santirez             /* Log the creation of the child and close the listening
1610cdb92412Santirez              * socket to make sure if the parent crashes a reset is sent
1611cdb92412Santirez              * to the clients. */
1612def31636Santirez             serverLog(LL_WARNING,"Redis forked for debugging eval");
1613def31636Santirez             closeListeningSockets(0);
1614def31636Santirez         } else {
1615def31636Santirez             /* Parent */
1616cdb92412Santirez             listAddNodeTail(ldb.children,(void*)(unsigned long)cp);
1617def31636Santirez             freeClientAsync(c); /* Close the client in the parent side. */
1618def31636Santirez             return 0;
1619def31636Santirez         }
162075788d6aSantirez     } else {
162175788d6aSantirez         serverLog(LL_WARNING,
162275788d6aSantirez             "Redis synchronous debugging eval session started");
1623def31636Santirez     }
1624def31636Santirez 
1625def31636Santirez     /* Setup our debugging session. */
1626def31636Santirez     anetBlock(NULL,ldb.fd);
162702de5d99Santirez     anetSendTimeout(NULL,ldb.fd,5000);
1628def31636Santirez     ldb.active = 1;
162989bf9696Santirez 
163002de5d99Santirez     /* First argument of EVAL is the script itself. We split it into different
163102de5d99Santirez      * lines since this is the way the debugger accesses the source code. */
163289bf9696Santirez     sds srcstring = sdsdup(c->argv[1]->ptr);
163389bf9696Santirez     size_t srclen = sdslen(srcstring);
163489bf9696Santirez     while(srclen && (srcstring[srclen-1] == '\n' ||
163589bf9696Santirez                      srcstring[srclen-1] == '\r'))
163689bf9696Santirez     {
163789bf9696Santirez         srcstring[--srclen] = '\0';
163889bf9696Santirez     }
163989bf9696Santirez     sdssetlen(srcstring,srclen);
164002de5d99Santirez     ldb.src = sdssplitlen(srcstring,sdslen(srcstring),"\n",1,&ldb.lines);
164189bf9696Santirez     sdsfree(srcstring);
1642def31636Santirez     return 1;
1643def31636Santirez }
1644def31636Santirez 
1645def31636Santirez /* End a debugging session after the EVAL call with debugging enabled
1646def31636Santirez  * returned. */
ldbEndSession(client * c)1647def31636Santirez void ldbEndSession(client *c) {
1648629acd61Santirez     /* Emit the remaining logs and an <endsession> mark. */
1649629acd61Santirez     ldbLog(sdsnew("<endsession>"));
1650629acd61Santirez     ldbSendLogs();
1651629acd61Santirez 
1652def31636Santirez     /* If it's a fork()ed session, we just exit. */
1653def31636Santirez     if (ldb.forked) {
1654def31636Santirez         writeToClient(c->fd, c, 0);
1655def31636Santirez         serverLog(LL_WARNING,"Lua debugging session child exiting");
1656def31636Santirez         exitFromChild(0);
165775788d6aSantirez     } else {
165875788d6aSantirez         serverLog(LL_WARNING,
165975788d6aSantirez             "Redis synchronous debugging eval session ended");
1660def31636Santirez     }
1661def31636Santirez 
1662def31636Santirez     /* Otherwise let's restore client's state. */
1663def31636Santirez     anetNonBlock(NULL,ldb.fd);
166402de5d99Santirez     anetSendTimeout(NULL,ldb.fd,0);
166502de5d99Santirez 
166602de5d99Santirez     /* Close the client connectin after sending the final EVAL reply
166702de5d99Santirez      * in order to signal the end of the debugging session. */
166802de5d99Santirez     c->flags |= CLIENT_CLOSE_AFTER_REPLY;
166902de5d99Santirez 
167002de5d99Santirez     /* Cleanup. */
167102de5d99Santirez     sdsfreesplitres(ldb.src,ldb.lines);
167202de5d99Santirez     ldb.lines = 0;
1673def31636Santirez     ldb.active = 0;
1674def31636Santirez }
1675def31636Santirez 
1676cdb92412Santirez /* If the specified pid is among the list of children spawned for
1677cdb92412Santirez  * forked debugging sessions, it is removed from the children list.
1678cdb92412Santirez  * If the pid was found non-zero is returned. */
ldbRemoveChild(pid_t pid)1679cdb92412Santirez int ldbRemoveChild(pid_t pid) {
1680cdb92412Santirez     listNode *ln = listSearchKey(ldb.children,(void*)(unsigned long)pid);
1681cdb92412Santirez     if (ln) {
1682cdb92412Santirez         listDelNode(ldb.children,ln);
1683cdb92412Santirez         return 1;
1684cdb92412Santirez     }
1685cdb92412Santirez     return 0;
1686cdb92412Santirez }
1687cdb92412Santirez 
1688c912df9aSantirez /* Return the number of children we still did not received termination
1689c912df9aSantirez  * acknowledge via wait() in the parent process. */
ldbPendingChildren(void)1690c912df9aSantirez int ldbPendingChildren(void) {
1691c912df9aSantirez     return listLength(ldb.children);
1692c912df9aSantirez }
1693c912df9aSantirez 
1694cdb92412Santirez /* Kill all the forked sessions. */
ldbKillForkedSessions(void)1695cdb92412Santirez void ldbKillForkedSessions(void) {
1696cdb92412Santirez     listIter li;
1697cdb92412Santirez     listNode *ln;
1698cdb92412Santirez 
1699cdb92412Santirez     listRewind(ldb.children,&li);
1700cdb92412Santirez     while((ln = listNext(&li))) {
1701cdb92412Santirez         pid_t pid = (unsigned long) ln->value;
1702cdb92412Santirez         serverLog(LL_WARNING,"Killing debugging session %ld",(long)pid);
1703cdb92412Santirez         kill(pid,SIGKILL);
1704cdb92412Santirez     }
1705cdb92412Santirez     listRelease(ldb.children);
1706cdb92412Santirez     ldb.children = listCreate();
1707cdb92412Santirez }
1708cdb92412Santirez 
1709def31636Santirez /* Wrapper for EVAL / EVALSHA that enables debugging, and makes sure
1710def31636Santirez  * that when EVAL returns, whatever happened, the session is ended. */
evalGenericCommandWithDebugging(client * c,int evalsha)1711def31636Santirez void evalGenericCommandWithDebugging(client *c, int evalsha) {
1712def31636Santirez     if (ldbStartSession(c)) {
1713def31636Santirez         evalGenericCommand(c,evalsha);
1714def31636Santirez         ldbEndSession(c);
1715def31636Santirez     } else {
1716def31636Santirez         ldbDisable(c);
1717def31636Santirez     }
1718def31636Santirez }
1719def31636Santirez 
172002de5d99Santirez /* Return a pointer to ldb.src source code line, considering line to be
172102de5d99Santirez  * one-based, and returning a special string for out of range lines. */
ldbGetSourceLine(int line)172202de5d99Santirez char *ldbGetSourceLine(int line) {
172302de5d99Santirez     int idx = line-1;
172402de5d99Santirez     if (idx < 0 || idx >= ldb.lines) return "<out of range source code line>";
172589bf9696Santirez     return ldb.src[idx];
172602de5d99Santirez }
172702de5d99Santirez 
17280d43a421Santirez /* Return true if there is a breakpoint in the specified line. */
ldbIsBreakpoint(int line)172944686bf9Santirez int ldbIsBreakpoint(int line) {
17300d43a421Santirez     int j;
17310d43a421Santirez 
17320d43a421Santirez     for (j = 0; j < ldb.bpcount; j++)
17330d43a421Santirez         if (ldb.bp[j] == line) return 1;
17340d43a421Santirez     return 0;
17350d43a421Santirez }
17360d43a421Santirez 
17370d43a421Santirez /* Add the specified breakpoint. Ignore it if we already reached the max.
17380d43a421Santirez  * Returns 1 if the breakpoint was added (or was already set). 0 if there is
17390d43a421Santirez  * no space for the breakpoint or if the line is invalid. */
ldbAddBreakpoint(int line)17400d43a421Santirez int ldbAddBreakpoint(int line) {
17410d43a421Santirez     if (line <= 0 || line > ldb.lines) return 0;
17420d43a421Santirez     if (!ldbIsBreakpoint(line) && ldb.bpcount != LDB_BREAKPOINTS_MAX) {
17430d43a421Santirez         ldb.bp[ldb.bpcount++] = line;
17440d43a421Santirez         return 1;
17450d43a421Santirez     }
17460d43a421Santirez     return 0;
17470d43a421Santirez }
17480d43a421Santirez 
17490d43a421Santirez /* Remove the specified breakpoint, returning 1 if the operation was
17500d43a421Santirez  * performed or 0 if there was no such breakpoint. */
ldbDelBreakpoint(int line)17510d43a421Santirez int ldbDelBreakpoint(int line) {
17520d43a421Santirez     int j;
17530d43a421Santirez 
17540d43a421Santirez     for (j = 0; j < ldb.bpcount; j++) {
17550d43a421Santirez         if (ldb.bp[j] == line) {
17560d43a421Santirez             ldb.bpcount--;
17570d43a421Santirez             memmove(ldb.bp+j,ldb.bp+j+1,ldb.bpcount-j);
17580d43a421Santirez             return 1;
17590d43a421Santirez         }
17600d43a421Santirez     }
176144686bf9Santirez     return 0;
176244686bf9Santirez }
176344686bf9Santirez 
176402de5d99Santirez /* Expect a valid multi-bulk command in the debugging client query buffer.
176502de5d99Santirez  * On success the command is parsed and returned as an array of SDS strings,
176602de5d99Santirez  * otherwise NULL is returned and there is to read more buffer. */
ldbReplParseCommand(int * argcp)176702de5d99Santirez sds *ldbReplParseCommand(int *argcp) {
176802de5d99Santirez     sds *argv = NULL;
176902de5d99Santirez     int argc = 0;
177002de5d99Santirez     if (sdslen(ldb.cbuf) == 0) return NULL;
177102de5d99Santirez 
177202de5d99Santirez     /* Working on a copy is simpler in this case. We can modify it freely
177302de5d99Santirez      * for the sake of simpler parsing. */
177402de5d99Santirez     sds copy = sdsdup(ldb.cbuf);
177502de5d99Santirez     char *p = copy;
177602de5d99Santirez 
177702de5d99Santirez     /* This Redis protocol parser is a joke... just the simplest thing that
177802de5d99Santirez      * works in this context. It is also very forgiving regarding broken
177902de5d99Santirez      * protocol. */
178002de5d99Santirez 
178102de5d99Santirez     /* Seek and parse *<count>\r\n. */
178202de5d99Santirez     p = strchr(p,'*'); if (!p) goto protoerr;
178302de5d99Santirez     char *plen = p+1; /* Multi bulk len pointer. */
178402de5d99Santirez     p = strstr(p,"\r\n"); if (!p) goto protoerr;
178502de5d99Santirez     *p = '\0'; p += 2;
178602de5d99Santirez     *argcp = atoi(plen);
178702de5d99Santirez     if (*argcp <= 0 || *argcp > 1024) goto protoerr;
178802de5d99Santirez 
178902de5d99Santirez     /* Parse each argument. */
179002de5d99Santirez     argv = zmalloc(sizeof(sds)*(*argcp));
179102de5d99Santirez     argc = 0;
179202de5d99Santirez     while(argc < *argcp) {
179302de5d99Santirez         if (*p != '$') goto protoerr;
179402de5d99Santirez         plen = p+1; /* Bulk string len pointer. */
179502de5d99Santirez         p = strstr(p,"\r\n"); if (!p) goto protoerr;
179602de5d99Santirez         *p = '\0'; p += 2;
179702de5d99Santirez         int slen = atoi(plen); /* Length of this arg. */
179802de5d99Santirez         if (slen <= 0 || slen > 1024) goto protoerr;
179902de5d99Santirez         argv[argc++] = sdsnewlen(p,slen);
180002de5d99Santirez         p += slen; /* Skip the already parsed argument. */
180102de5d99Santirez         if (p[0] != '\r' || p[1] != '\n') goto protoerr;
180202de5d99Santirez         p += 2; /* Skip \r\n. */
180302de5d99Santirez     }
180402de5d99Santirez     sdsfree(copy);
180502de5d99Santirez     return argv;
180602de5d99Santirez 
180702de5d99Santirez protoerr:
180802de5d99Santirez     sdsfreesplitres(argv,argc);
180902de5d99Santirez     sdsfree(copy);
181002de5d99Santirez     return NULL;
181102de5d99Santirez }
181202de5d99Santirez 
18138a0020f1Santirez /* Log the specified line in the Lua debugger output. */
ldbLogSourceLine(int lnum)18148a0020f1Santirez void ldbLogSourceLine(int lnum) {
18158a0020f1Santirez     char *line = ldbGetSourceLine(lnum);
18168a0020f1Santirez     char *prefix;
18178a0020f1Santirez     int bp = ldbIsBreakpoint(lnum);
18188a0020f1Santirez     int current = ldb.currentline == lnum;
18198a0020f1Santirez 
18208a0020f1Santirez     if (current && bp)
18218a0020f1Santirez         prefix = "->#";
18228a0020f1Santirez     else if (current)
18238a0020f1Santirez         prefix = "-> ";
18248a0020f1Santirez     else if (bp)
18258a0020f1Santirez         prefix = "  #";
18268a0020f1Santirez     else
18278a0020f1Santirez         prefix = "   ";
18288a0020f1Santirez     sds thisline = sdscatprintf(sdsempty(),"%s%-3d %s", prefix, lnum, line);
18298a0020f1Santirez     ldbLog(thisline);
18308a0020f1Santirez }
18318a0020f1Santirez 
183289bf9696Santirez /* Implement the "list" command of the Lua debugger. If around is 0
183389bf9696Santirez  * the whole file is listed, otherwise only a small portion of the file
183489bf9696Santirez  * around the specified line is shown. When a line number is specified
183589bf9696Santirez  * the amonut of context (lines before/after) is specified via the
183689bf9696Santirez  * 'context' argument. */
ldbList(int around,int context)183789bf9696Santirez void ldbList(int around, int context) {
183889bf9696Santirez     int j;
183989bf9696Santirez 
184089bf9696Santirez     for (j = 1; j <= ldb.lines; j++) {
184189bf9696Santirez         if (around != 0 && abs(around-j) > context) continue;
18428a0020f1Santirez         ldbLogSourceLine(j);
184389bf9696Santirez     }
184489bf9696Santirez }
184589bf9696Santirez 
1846878725deSantirez /* Append an human readable representation of the Lua value at position 'idx'
1847878725deSantirez  * on the stack of the 'lua' state, to the SDS string passed as argument.
1848878725deSantirez  * The new SDS string with the represented value attached is returned.
1849878725deSantirez  * Used in order to implement ldbLogStackValue().
1850878725deSantirez  *
1851878725deSantirez  * The element is not automatically removed from the stack, nor it is
1852878725deSantirez  * converted to a different type. */
18538cc1a49eSantirez #define LDB_MAX_VALUES_DEPTH (LUA_MINSTACK/2)
ldbCatStackValueRec(sds s,lua_State * lua,int idx,int level)18548cc1a49eSantirez sds ldbCatStackValueRec(sds s, lua_State *lua, int idx, int level) {
1855878725deSantirez     int t = lua_type(lua,idx);
185644686bf9Santirez 
18578cc1a49eSantirez     if (level++ == LDB_MAX_VALUES_DEPTH)
18588cc1a49eSantirez         return sdscat(s,"<max recursion level reached! Nested table?>");
18598cc1a49eSantirez 
186044686bf9Santirez     switch(t) {
186144686bf9Santirez     case LUA_TSTRING:
1862878725deSantirez         {
1863878725deSantirez         size_t strl;
1864878725deSantirez         char *strp = (char*)lua_tolstring(lua,idx,&strl);
1865878725deSantirez         s = sdscatrepr(s,strp,strl);
1866878725deSantirez         }
186744686bf9Santirez         break;
186844686bf9Santirez     case LUA_TBOOLEAN:
1869878725deSantirez         s = sdscat(s,lua_toboolean(lua,idx) ? "true" : "false");
187044686bf9Santirez         break;
187144686bf9Santirez     case LUA_TNUMBER:
1872878725deSantirez         s = sdscatprintf(s,"%g",(double)lua_tonumber(lua,idx));
187344686bf9Santirez         break;
187444686bf9Santirez     case LUA_TNIL:
1875878725deSantirez         s = sdscatlen(s,"nil",3);
187644686bf9Santirez         break;
187744686bf9Santirez     case LUA_TTABLE:
1878878725deSantirez         {
1879878725deSantirez         int expected_index = 1; /* First index we expect in an array. */
1880878725deSantirez         int is_array = 1; /* Will be set to null if check fails. */
1881878725deSantirez         /* Note: we create two representations at the same time, one
1882878725deSantirez          * assuming the table is an array, one assuming it is not. At the
1883878725deSantirez          * end we know what is true and select the right one. */
1884878725deSantirez         sds repr1 = sdsempty();
1885878725deSantirez         sds repr2 = sdsempty();
1886878725deSantirez         lua_pushnil(lua); /* The first key to start the iteration is nil. */
1887878725deSantirez         while (lua_next(lua,idx-1)) {
1888878725deSantirez             /* Test if so far the table looks like an array. */
1889878725deSantirez             if (is_array &&
1890878725deSantirez                 (lua_type(lua,-2) != LUA_TNUMBER ||
1891878725deSantirez                  lua_tonumber(lua,-2) != expected_index)) is_array = 0;
1892878725deSantirez             /* Stack now: table, key, value */
1893878725deSantirez             /* Array repr. */
18948cc1a49eSantirez             repr1 = ldbCatStackValueRec(repr1,lua,-1,level);
1895878725deSantirez             repr1 = sdscatlen(repr1,"; ",2);
1896878725deSantirez             /* Full repr. */
1897c428066aSPaul Kulchenko             repr2 = sdscatlen(repr2,"[",1);
18988cc1a49eSantirez             repr2 = ldbCatStackValueRec(repr2,lua,-2,level);
1899c428066aSPaul Kulchenko             repr2 = sdscatlen(repr2,"]=",2);
19008cc1a49eSantirez             repr2 = ldbCatStackValueRec(repr2,lua,-1,level);
1901878725deSantirez             repr2 = sdscatlen(repr2,"; ",2);
1902878725deSantirez             lua_pop(lua,1); /* Stack: table, key. Ready for next iteration. */
1903878725deSantirez             expected_index++;
1904878725deSantirez         }
1905878725deSantirez         /* Strip the last " ;" from both the representations. */
1906878725deSantirez         if (sdslen(repr1)) sdsrange(repr1,0,-3);
1907878725deSantirez         if (sdslen(repr2)) sdsrange(repr2,0,-3);
1908878725deSantirez         /* Select the right one and discard the other. */
1909878725deSantirez         s = sdscatlen(s,"{",1);
1910878725deSantirez         s = sdscatsds(s,is_array ? repr1 : repr2);
1911878725deSantirez         s = sdscatlen(s,"}",1);
1912878725deSantirez         sdsfree(repr1);
1913878725deSantirez         sdsfree(repr2);
1914878725deSantirez         }
1915878725deSantirez         break;
191644686bf9Santirez     case LUA_TFUNCTION:
191744686bf9Santirez     case LUA_TUSERDATA:
191844686bf9Santirez     case LUA_TTHREAD:
191944686bf9Santirez     case LUA_TLIGHTUSERDATA:
192044686bf9Santirez         {
1921878725deSantirez         const void *p = lua_topointer(lua,idx);
192244686bf9Santirez         char *typename = "unknown";
1923878725deSantirez         if (t == LUA_TFUNCTION) typename = "function";
192444686bf9Santirez         else if (t == LUA_TUSERDATA) typename = "userdata";
192544686bf9Santirez         else if (t == LUA_TTHREAD) typename = "thread";
192644686bf9Santirez         else if (t == LUA_TLIGHTUSERDATA) typename = "light-userdata";
1927db1df454SPaul Kulchenko         s = sdscatprintf(s,"\"%s@%p\"",typename,p);
192844686bf9Santirez         }
192944686bf9Santirez         break;
193044686bf9Santirez     default:
1931db1df454SPaul Kulchenko         s = sdscat(s,"\"<unknown-lua-type>\"");
193244686bf9Santirez         break;
193344686bf9Santirez     }
1934878725deSantirez     return s;
1935878725deSantirez }
1936878725deSantirez 
19378cc1a49eSantirez /* Higher level wrapper for ldbCatStackValueRec() that just uses an initial
19388cc1a49eSantirez  * recursion level of '0'. */
ldbCatStackValue(sds s,lua_State * lua,int idx)19398cc1a49eSantirez sds ldbCatStackValue(sds s, lua_State *lua, int idx) {
19408cc1a49eSantirez     return ldbCatStackValueRec(s,lua,idx,0);
19418cc1a49eSantirez }
19428cc1a49eSantirez 
1943878725deSantirez /* Produce a debugger log entry representing the value of the Lua object
1944878725deSantirez  * currently on the top of the stack. The element is ot popped nor modified.
1945878725deSantirez  * Check ldbCatStackValue() for the actual implementation. */
ldbLogStackValue(lua_State * lua,char * prefix)1946878725deSantirez void ldbLogStackValue(lua_State *lua, char *prefix) {
1947878725deSantirez     sds s = sdsnew(prefix);
1948878725deSantirez     s = ldbCatStackValue(s,lua,-1);
194979c6e689Santirez     ldbLogWithMaxLen(s);
195044686bf9Santirez }
195144686bf9Santirez 
19528a0020f1Santirez char *ldbRedisProtocolToHuman_Int(sds *o, char *reply);
19538a0020f1Santirez char *ldbRedisProtocolToHuman_Bulk(sds *o, char *reply);
19548a0020f1Santirez char *ldbRedisProtocolToHuman_Status(sds *o, char *reply);
19558a0020f1Santirez char *ldbRedisProtocolToHuman_MultiBulk(sds *o, char *reply);
19568a0020f1Santirez 
19578a0020f1Santirez /* Get Redis protocol from 'reply' and appends it in human readable form to
19588a0020f1Santirez  * the passed SDS string 'o'.
19598a0020f1Santirez  *
19608a0020f1Santirez  * Note that the SDS string is passed by reference (pointer of pointer to
19618a0020f1Santirez  * char*) so that we can return a modified pointer, as for SDS semantics. */
ldbRedisProtocolToHuman(sds * o,char * reply)19628a0020f1Santirez char *ldbRedisProtocolToHuman(sds *o, char *reply) {
19638a0020f1Santirez     char *p = reply;
19648a0020f1Santirez     switch(*p) {
19658a0020f1Santirez     case ':': p = ldbRedisProtocolToHuman_Int(o,reply); break;
19668a0020f1Santirez     case '$': p = ldbRedisProtocolToHuman_Bulk(o,reply); break;
19678a0020f1Santirez     case '+': p = ldbRedisProtocolToHuman_Status(o,reply); break;
19688a0020f1Santirez     case '-': p = ldbRedisProtocolToHuman_Status(o,reply); break;
19698a0020f1Santirez     case '*': p = ldbRedisProtocolToHuman_MultiBulk(o,reply); break;
19708a0020f1Santirez     }
19718a0020f1Santirez     return p;
19728a0020f1Santirez }
19738a0020f1Santirez 
197485668579Santirez /* The following functions are helpers for ldbRedisProtocolToHuman(), each
197585668579Santirez  * take care of a given Redis return type. */
197685668579Santirez 
ldbRedisProtocolToHuman_Int(sds * o,char * reply)19778a0020f1Santirez char *ldbRedisProtocolToHuman_Int(sds *o, char *reply) {
19788a0020f1Santirez     char *p = strchr(reply+1,'\r');
19798a0020f1Santirez     *o = sdscatlen(*o,reply+1,p-reply-1);
19808a0020f1Santirez     return p+2;
19818a0020f1Santirez }
19828a0020f1Santirez 
ldbRedisProtocolToHuman_Bulk(sds * o,char * reply)19838a0020f1Santirez char *ldbRedisProtocolToHuman_Bulk(sds *o, char *reply) {
19848a0020f1Santirez     char *p = strchr(reply+1,'\r');
19858a0020f1Santirez     long long bulklen;
19868a0020f1Santirez 
19878a0020f1Santirez     string2ll(reply+1,p-reply-1,&bulklen);
19888a0020f1Santirez     if (bulklen == -1) {
19898a0020f1Santirez         *o = sdscatlen(*o,"NULL",4);
19908a0020f1Santirez         return p+2;
19918a0020f1Santirez     } else {
19928a0020f1Santirez         *o = sdscatrepr(*o,p+2,bulklen);
19938a0020f1Santirez         return p+2+bulklen+2;
19948a0020f1Santirez     }
19958a0020f1Santirez }
19968a0020f1Santirez 
ldbRedisProtocolToHuman_Status(sds * o,char * reply)19978a0020f1Santirez char *ldbRedisProtocolToHuman_Status(sds *o, char *reply) {
19988a0020f1Santirez     char *p = strchr(reply+1,'\r');
19998a0020f1Santirez 
20008a0020f1Santirez     *o = sdscatrepr(*o,reply,p-reply);
20018a0020f1Santirez     return p+2;
20028a0020f1Santirez }
20038a0020f1Santirez 
ldbRedisProtocolToHuman_MultiBulk(sds * o,char * reply)20048a0020f1Santirez char *ldbRedisProtocolToHuman_MultiBulk(sds *o, char *reply) {
20058a0020f1Santirez     char *p = strchr(reply+1,'\r');
20068a0020f1Santirez     long long mbulklen;
20078a0020f1Santirez     int j = 0;
20088a0020f1Santirez 
20098a0020f1Santirez     string2ll(reply+1,p-reply-1,&mbulklen);
20108a0020f1Santirez     p += 2;
20118a0020f1Santirez     if (mbulklen == -1) {
20128a0020f1Santirez         *o = sdscatlen(*o,"NULL",4);
20138a0020f1Santirez         return p;
20148a0020f1Santirez     }
20158a0020f1Santirez     *o = sdscatlen(*o,"[",1);
20168a0020f1Santirez     for (j = 0; j < mbulklen; j++) {
20178a0020f1Santirez         p = ldbRedisProtocolToHuman(o,p);
20188a0020f1Santirez         if (j != mbulklen-1) *o = sdscatlen(*o,",",1);
20198a0020f1Santirez     }
20208a0020f1Santirez     *o = sdscatlen(*o,"]",1);
20218a0020f1Santirez     return p;
20228a0020f1Santirez }
20238a0020f1Santirez 
20248a0020f1Santirez /* Log a Redis reply as debugger output, in an human readable format.
20258a0020f1Santirez  * If the resulting string is longer than 'len' plus a few more chars
20268a0020f1Santirez  * used as prefix, it gets truncated. */
ldbLogRedisReply(char * reply)202779c6e689Santirez void ldbLogRedisReply(char *reply) {
20288a0020f1Santirez     sds log = sdsnew("<reply> ");
20298a0020f1Santirez     ldbRedisProtocolToHuman(&log,reply);
203079c6e689Santirez     ldbLogWithMaxLen(log);
20318a0020f1Santirez }
20328a0020f1Santirez 
2033971571baSantirez /* Implements the "print <var>" command of the Lua debugger. It scans for Lua
203444686bf9Santirez  * var "varname" starting from the current stack frame up to the top stack
203544686bf9Santirez  * frame. The first matching variable is printed. */
ldbPrint(lua_State * lua,char * varname)20360d43a421Santirez void ldbPrint(lua_State *lua, char *varname) {
203744686bf9Santirez     lua_Debug ar;
20380d43a421Santirez 
203944686bf9Santirez     int l = 0; /* Stack level. */
204044686bf9Santirez     while (lua_getstack(lua,l,&ar) != 0) {
204144686bf9Santirez         l++;
204244686bf9Santirez         const char *name;
204344686bf9Santirez         int i = 1; /* Variable index. */
204444686bf9Santirez         while((name = lua_getlocal(lua,&ar,i)) != NULL) {
204544686bf9Santirez             i++;
204644686bf9Santirez             if (strcmp(varname,name) == 0) {
20478a0020f1Santirez                 ldbLogStackValue(lua,"<value> ");
2048878725deSantirez                 lua_pop(lua,1);
204944686bf9Santirez                 return;
205044686bf9Santirez             } else {
205144686bf9Santirez                 lua_pop(lua,1); /* Discard the var name on the stack. */
205244686bf9Santirez             }
205344686bf9Santirez         }
205444686bf9Santirez     }
2055435f9500Santirez 
2056435f9500Santirez     /* Let's try with global vars in two selected cases */
2057435f9500Santirez     if (!strcmp(varname,"ARGV") || !strcmp(varname,"KEYS")) {
2058435f9500Santirez         lua_getglobal(lua, varname);
2059435f9500Santirez         ldbLogStackValue(lua,"<value> ");
2060435f9500Santirez         lua_pop(lua,1);
2061435f9500Santirez     } else {
206244686bf9Santirez         ldbLog(sdsnew("No such variable."));
206344686bf9Santirez     }
2064435f9500Santirez }
206544686bf9Santirez 
2066971571baSantirez /* Implements the "print" command (without arguments) of the Lua debugger.
2067971571baSantirez  * Prints all the variables in the current stack frame. */
ldbPrintAll(lua_State * lua)2068971571baSantirez void ldbPrintAll(lua_State *lua) {
2069971571baSantirez     lua_Debug ar;
2070971571baSantirez     int vars = 0;
2071971571baSantirez 
2072971571baSantirez     if (lua_getstack(lua,0,&ar) != 0) {
2073971571baSantirez         const char *name;
2074971571baSantirez         int i = 1; /* Variable index. */
2075971571baSantirez         while((name = lua_getlocal(lua,&ar,i)) != NULL) {
2076971571baSantirez             i++;
2077971571baSantirez             if (!strstr(name,"(*temporary)")) {
2078971571baSantirez                 sds prefix = sdscatprintf(sdsempty(),"<value> %s = ",name);
2079971571baSantirez                 ldbLogStackValue(lua,prefix);
2080971571baSantirez                 sdsfree(prefix);
2081971571baSantirez                 vars++;
2082971571baSantirez             }
2083971571baSantirez             lua_pop(lua,1);
2084971571baSantirez         }
2085971571baSantirez     }
2086971571baSantirez 
2087971571baSantirez     if (vars == 0) {
2088971571baSantirez         ldbLog(sdsnew("No local variables in the current context."));
2089971571baSantirez     }
2090971571baSantirez }
2091971571baSantirez 
20920d43a421Santirez /* Implements the break command to list, add and remove breakpoints. */
ldbBreak(sds * argv,int argc)20930d43a421Santirez void ldbBreak(sds *argv, int argc) {
20940d43a421Santirez     if (argc == 1) {
20950d43a421Santirez         if (ldb.bpcount == 0) {
20960d43a421Santirez             ldbLog(sdsnew("No breakpoints set. Use 'b <line>' to add one."));
20970d43a421Santirez             return;
20980d43a421Santirez         } else {
20990d43a421Santirez             ldbLog(sdscatfmt(sdsempty(),"%i breakpoints set:",ldb.bpcount));
21000d43a421Santirez             int j;
21018a0020f1Santirez             for (j = 0; j < ldb.bpcount; j++)
21028a0020f1Santirez                 ldbLogSourceLine(ldb.bp[j]);
21030d43a421Santirez         }
21040d43a421Santirez     } else {
21050d43a421Santirez         int j;
21060d43a421Santirez         for (j = 1; j < argc; j++) {
21070d43a421Santirez             char *arg = argv[j];
21080d43a421Santirez             long line;
21090d43a421Santirez             if (!string2l(arg,sdslen(arg),&line)) {
21100d43a421Santirez                 ldbLog(sdscatfmt(sdsempty(),"Invalid argument:'%s'",arg));
21110d43a421Santirez             } else {
21120d43a421Santirez                 if (line == 0) {
21130d43a421Santirez                     ldb.bpcount = 0;
21140d43a421Santirez                     ldbLog(sdsnew("All breakpoints removed."));
21150d43a421Santirez                 } else if (line > 0) {
21160d43a421Santirez                     if (ldb.bpcount == LDB_BREAKPOINTS_MAX) {
21170d43a421Santirez                         ldbLog(sdsnew("Too many breakpoints set."));
21180d43a421Santirez                     } else if (ldbAddBreakpoint(line)) {
21190d43a421Santirez                         ldbList(line,1);
21200d43a421Santirez                     } else {
21210d43a421Santirez                         ldbLog(sdsnew("Wrong line number."));
21220d43a421Santirez                     }
21230d43a421Santirez                 } else if (line < 0) {
21242cb10191Santirez                     if (ldbDelBreakpoint(-line))
21250d43a421Santirez                         ldbLog(sdsnew("Breakpoint removed."));
21260d43a421Santirez                     else
21270d43a421Santirez                         ldbLog(sdsnew("No breakpoint in the specified line."));
21280d43a421Santirez                 }
21290d43a421Santirez             }
21300d43a421Santirez         }
21310d43a421Santirez     }
21320d43a421Santirez }
21330d43a421Santirez 
21348a0020f1Santirez /* Implements the Lua debugger "eval" command. It just compiles the user
21358a0020f1Santirez  * passed fragment of code and executes it, showing the result left on
21368a0020f1Santirez  * the stack. */
ldbEval(lua_State * lua,sds * argv,int argc)21378a0020f1Santirez void ldbEval(lua_State *lua, sds *argv, int argc) {
21388a0020f1Santirez     /* Glue the script together if it is composed of multiple arguments. */
21398a0020f1Santirez     sds code = sdsjoinsds(argv+1,argc-1," ",1);
2140bc9b2093Santirez     sds expr = sdscatsds(sdsnew("return "),code);
21418a0020f1Santirez 
2142bc9b2093Santirez     /* Try to compile it as an expression, prepending "return ". */
2143bc9b2093Santirez     if (luaL_loadbuffer(lua,expr,sdslen(expr),"@ldb_eval")) {
2144bc9b2093Santirez         lua_pop(lua,1);
2145bc9b2093Santirez         /* Failed? Try as a statement. */
21468a0020f1Santirez         if (luaL_loadbuffer(lua,code,sdslen(code),"@ldb_eval")) {
21478a0020f1Santirez             ldbLog(sdscatfmt(sdsempty(),"<error> %s",lua_tostring(lua,-1)));
21488a0020f1Santirez             lua_pop(lua,1);
21498a0020f1Santirez             sdsfree(code);
21508a0020f1Santirez             return;
21518a0020f1Santirez         }
2152bc9b2093Santirez     }
2153bc9b2093Santirez 
2154bc9b2093Santirez     /* Call it. */
21558a0020f1Santirez     sdsfree(code);
2156bc9b2093Santirez     sdsfree(expr);
21578a0020f1Santirez     if (lua_pcall(lua,0,1,0)) {
21588a0020f1Santirez         ldbLog(sdscatfmt(sdsempty(),"<error> %s",lua_tostring(lua,-1)));
21598a0020f1Santirez         lua_pop(lua,1);
21608a0020f1Santirez         return;
21618a0020f1Santirez     }
21628a0020f1Santirez     ldbLogStackValue(lua,"<retval> ");
2163878725deSantirez     lua_pop(lua,1);
21648a0020f1Santirez }
21658a0020f1Santirez 
2166649904e2Santirez /* Implement the debugger "redis" command. We use a trick in order to make
2167649904e2Santirez  * the implementation very simple: we just call the Lua redis.call() command
2168649904e2Santirez  * implementation, with ldb.step enabled, so as a side effect the Redis command
2169649904e2Santirez  * and its reply are logged. */
ldbRedis(lua_State * lua,sds * argv,int argc)2170649904e2Santirez void ldbRedis(lua_State *lua, sds *argv, int argc) {
2171649904e2Santirez     int j, saved_rc = server.lua_replicate_commands;
2172649904e2Santirez 
2173649904e2Santirez     lua_getglobal(lua,"redis");
2174649904e2Santirez     lua_pushstring(lua,"call");
2175649904e2Santirez     lua_gettable(lua,-2);       /* Stack: redis, redis.call */
2176649904e2Santirez     for (j = 1; j < argc; j++)
2177649904e2Santirez         lua_pushlstring(lua,argv[j],sdslen(argv[j]));
2178649904e2Santirez     ldb.step = 1;               /* Force redis.call() to log. */
2179649904e2Santirez     server.lua_replicate_commands = 1;
2180649904e2Santirez     lua_pcall(lua,argc-1,1,0);  /* Stack: redis, result */
2181649904e2Santirez     ldb.step = 0;               /* Disable logging. */
2182649904e2Santirez     server.lua_replicate_commands = saved_rc;
2183649904e2Santirez     lua_pop(lua,2);             /* Discard the result and clean the stack. */
2184649904e2Santirez }
2185649904e2Santirez 
2186714dc0c4Santirez /* Implements "trace" command of the Lua debugger. It just prints a backtrace
2187714dc0c4Santirez  * querying Lua starting from the current callframe back to the outer one. */
ldbTrace(lua_State * lua)2188714dc0c4Santirez void ldbTrace(lua_State *lua) {
2189714dc0c4Santirez     lua_Debug ar;
2190714dc0c4Santirez     int level = 0;
2191714dc0c4Santirez 
2192714dc0c4Santirez     while(lua_getstack(lua,level,&ar)) {
2193714dc0c4Santirez         lua_getinfo(lua,"Snl",&ar);
2194cd840bf0Santirez         if(strstr(ar.short_src,"user_script") != NULL) {
2195714dc0c4Santirez             ldbLog(sdscatprintf(sdsempty(),"%s %s:",
2196714dc0c4Santirez                 (level == 0) ? "In" : "From",
2197714dc0c4Santirez                 ar.name ? ar.name : "top level"));
2198714dc0c4Santirez             ldbLogSourceLine(ar.currentline);
2199cd840bf0Santirez         }
2200714dc0c4Santirez         level++;
2201714dc0c4Santirez     }
2202714dc0c4Santirez     if (level == 0) {
2203714dc0c4Santirez         ldbLog(sdsnew("<error> Can't retrieve Lua stack."));
2204714dc0c4Santirez     }
2205714dc0c4Santirez }
2206714dc0c4Santirez 
220779c6e689Santirez /* Impleemnts the debugger "maxlen" command. It just queries or sets the
220879c6e689Santirez  * ldb.maxlen variable. */
ldbMaxlen(sds * argv,int argc)220979c6e689Santirez void ldbMaxlen(sds *argv, int argc) {
221079c6e689Santirez     if (argc == 2) {
221179c6e689Santirez         int newval = atoi(argv[1]);
221279c6e689Santirez         ldb.maxlen_hint_sent = 1; /* User knows about this command. */
221379c6e689Santirez         if (newval != 0 && newval <= 60) newval = 60;
221479c6e689Santirez         ldb.maxlen = newval;
221579c6e689Santirez     }
221679c6e689Santirez     if (ldb.maxlen) {
221779c6e689Santirez         ldbLog(sdscatprintf(sdsempty(),"<value> replies are truncated at %d bytes.",(int)ldb.maxlen));
221879c6e689Santirez     } else {
221979c6e689Santirez         ldbLog(sdscatprintf(sdsempty(),"<value> replies are unlimited."));
222079c6e689Santirez     }
222179c6e689Santirez }
222279c6e689Santirez 
222300eb8a63Santirez /* Read debugging commands from client.
222400eb8a63Santirez  * Return C_OK if the debugging session is continuing, otherwise
222500eb8a63Santirez  * C_ERR if the client closed the connection or is timing out. */
ldbRepl(lua_State * lua)222600eb8a63Santirez int ldbRepl(lua_State *lua) {
222702de5d99Santirez     sds *argv;
222802de5d99Santirez     int argc;
222902de5d99Santirez 
223002de5d99Santirez     /* We continue processing commands until a command that should return
223102de5d99Santirez      * to the Lua interpreter is found. */
223202de5d99Santirez     while(1) {
223302de5d99Santirez         while((argv = ldbReplParseCommand(&argc)) == NULL) {
223402de5d99Santirez             char buf[1024];
223502de5d99Santirez             int nread = read(ldb.fd,buf,sizeof(buf));
223602de5d99Santirez             if (nread <= 0) {
223702de5d99Santirez                 /* Make sure the script runs without user input since the
223802de5d99Santirez                  * client is no longer connected. */
223902de5d99Santirez                 ldb.step = 0;
224002de5d99Santirez                 ldb.bpcount = 0;
224100eb8a63Santirez                 return C_ERR;
224202de5d99Santirez             }
224302de5d99Santirez             ldb.cbuf = sdscatlen(ldb.cbuf,buf,nread);
224402de5d99Santirez         }
224502de5d99Santirez 
224602de5d99Santirez         /* Flush the old buffer. */
224702de5d99Santirez         sdsfree(ldb.cbuf);
224802de5d99Santirez         ldb.cbuf = sdsempty();
224902de5d99Santirez 
225002de5d99Santirez         /* Execute the command. */
22518a0020f1Santirez         if (!strcasecmp(argv[0],"h") || !strcasecmp(argv[0],"help")) {
225202de5d99Santirez ldbLog(sdsnew("Redis Lua debugger help:"));
22538a0020f1Santirez ldbLog(sdsnew("[h]elp               Show this help."));
225444686bf9Santirez ldbLog(sdsnew("[s]tep               Run current line and stop again."));
225544686bf9Santirez ldbLog(sdsnew("[n]ext               Alias for step."));
225644686bf9Santirez ldbLog(sdsnew("[c]continue          Run till next breakpoint."));
2257185b2dcbSantirez ldbLog(sdsnew("[l]list              List source code around current line."));
2258185b2dcbSantirez ldbLog(sdsnew("[l]list [line]       List source code around [line]."));
2259185b2dcbSantirez ldbLog(sdsnew("                     line = 0 means: current position."));
2260185b2dcbSantirez ldbLog(sdsnew("[l]list [line] [ctx] In this form [ctx] specifies how many lines"));
2261185b2dcbSantirez ldbLog(sdsnew("                     to show before/after [line]."));
2262185b2dcbSantirez ldbLog(sdsnew("[w]hole              List all source code. Alias for 'list 1 1000000'."));
2263971571baSantirez ldbLog(sdsnew("[p]rint              Show all the local variables."));
2264435f9500Santirez ldbLog(sdsnew("[p]rint <var>        Show the value of the specified variable."));
2265971571baSantirez ldbLog(sdsnew("                     Can also show global vars KEYS and ARGV."));
2266d530cbd1Santirez ldbLog(sdsnew("[b]reak              Show all breakpoints."));
2267d530cbd1Santirez ldbLog(sdsnew("[b]reak <line>       Add a breakpoint to the specified line."));
2268d530cbd1Santirez ldbLog(sdsnew("[b]reak -<line>      Remove breakpoint from the specified line."));
2269d530cbd1Santirez ldbLog(sdsnew("[b]reak 0            Remove all breakpoints."));
2270714dc0c4Santirez ldbLog(sdsnew("[t]race              Show a backtrace."));
2271649904e2Santirez ldbLog(sdsnew("[e]eval <code>       Execute some Lua code (in a different callframe)."));
2272649904e2Santirez ldbLog(sdsnew("[r]edis <cmd>        Execute a Redis command."));
227379c6e689Santirez ldbLog(sdsnew("[m]axlen [len]       Trim logged Redis replies and Lua var dumps to len."));
227479c6e689Santirez ldbLog(sdsnew("                     Specifying zero as <len> means unlimited."));
2275e132b20fSantirez ldbLog(sdsnew("[a]abort             Stop the execution of the script. In sync"));
2276e132b20fSantirez ldbLog(sdsnew("                     mode dataset changes will be retained."));
22778f8c6b3bSantirez ldbLog(sdsnew(""));
22788f8c6b3bSantirez ldbLog(sdsnew("Debugger functions you can call from Lua scripts:"));
22798f8c6b3bSantirez ldbLog(sdsnew("redis.debug()        Produce logs in the debugger console."));
22808f8c6b3bSantirez ldbLog(sdsnew("redis.breakpoint()   Stop execution like if there was a breakpoing."));
22818f8c6b3bSantirez ldbLog(sdsnew("                     in the next line of code."));
228202de5d99Santirez             ldbSendLogs();
228389bf9696Santirez         } else if (!strcasecmp(argv[0],"s") || !strcasecmp(argv[0],"step") ||
228489bf9696Santirez                    !strcasecmp(argv[0],"n") || !strcasecmp(argv[0],"next")) {
228502de5d99Santirez             ldb.step = 1;
228602de5d99Santirez             break;
228702de5d99Santirez         } else if (!strcasecmp(argv[0],"c") || !strcasecmp(argv[0],"continue")){
228802de5d99Santirez             break;
2289714dc0c4Santirez         } else if (!strcasecmp(argv[0],"t") || !strcasecmp(argv[0],"trace")) {
2290714dc0c4Santirez             ldbTrace(lua);
2291714dc0c4Santirez             ldbSendLogs();
229279c6e689Santirez         } else if (!strcasecmp(argv[0],"m") || !strcasecmp(argv[0],"maxlen")) {
229379c6e689Santirez             ldbMaxlen(argv,argc);
229479c6e689Santirez             ldbSendLogs();
22950d43a421Santirez         } else if (!strcasecmp(argv[0],"b") || !strcasecmp(argv[0],"break")) {
22960d43a421Santirez             ldbBreak(argv,argc);
22970d43a421Santirez             ldbSendLogs();
22988a0020f1Santirez         } else if (!strcasecmp(argv[0],"e") || !strcasecmp(argv[0],"eval")) {
22998a0020f1Santirez             ldbEval(lua,argv,argc);
23008a0020f1Santirez             ldbSendLogs();
2301e132b20fSantirez         } else if (!strcasecmp(argv[0],"a") || !strcasecmp(argv[0],"abort")) {
2302e132b20fSantirez             lua_pushstring(lua, "script aborted for user request");
2303e132b20fSantirez             lua_error(lua);
2304649904e2Santirez         } else if (argc > 1 &&
2305649904e2Santirez                    (!strcasecmp(argv[0],"r") || !strcasecmp(argv[0],"redis"))) {
2306649904e2Santirez             ldbRedis(lua,argv,argc);
2307649904e2Santirez             ldbSendLogs();
2308971571baSantirez         } else if ((!strcasecmp(argv[0],"p") || !strcasecmp(argv[0],"print"))) {
2309971571baSantirez             if (argc == 2)
23100d43a421Santirez                 ldbPrint(lua,argv[1]);
2311971571baSantirez             else
2312971571baSantirez                 ldbPrintAll(lua);
231344686bf9Santirez             ldbSendLogs();
231489bf9696Santirez         } else if (!strcasecmp(argv[0],"l") || !strcasecmp(argv[0],"list")){
2315185b2dcbSantirez             int around = ldb.currentline, ctx = 5;
2316185b2dcbSantirez             if (argc > 1) {
2317185b2dcbSantirez                 int num = atoi(argv[1]);
2318185b2dcbSantirez                 if (num > 0) around = num;
2319185b2dcbSantirez             }
232089bf9696Santirez             if (argc > 2) ctx = atoi(argv[2]);
232189bf9696Santirez             ldbList(around,ctx);
232289bf9696Santirez             ldbSendLogs();
2323185b2dcbSantirez         } else if (!strcasecmp(argv[0],"w") || !strcasecmp(argv[0],"whole")){
2324185b2dcbSantirez             ldbList(1,1000000);
2325185b2dcbSantirez             ldbSendLogs();
232602de5d99Santirez         } else {
23278a0020f1Santirez             ldbLog(sdsnew("<error> Unknown Redis Lua debugger command or "
232844686bf9Santirez                           "wrong number of arguments."));
232902de5d99Santirez             ldbSendLogs();
233002de5d99Santirez         }
233102de5d99Santirez 
233202de5d99Santirez         /* Free the command vector. */
233302de5d99Santirez         sdsfreesplitres(argv,argc);
233402de5d99Santirez     }
233502de5d99Santirez 
233602de5d99Santirez     /* Free the current command argv if we break inside the while loop. */
233702de5d99Santirez     sdsfreesplitres(argv,argc);
233800eb8a63Santirez     return C_OK;
233902de5d99Santirez }
234002de5d99Santirez 
2341def31636Santirez /* This is the core of our Lua debugger, called each time Lua is about
2342def31636Santirez  * to start executing a new line. */
luaLdbLineHook(lua_State * lua,lua_Debug * ar)2343def31636Santirez void luaLdbLineHook(lua_State *lua, lua_Debug *ar) {
2344def31636Santirez     lua_getstack(lua,0,ar);
2345def31636Santirez     lua_getinfo(lua,"Sl",ar);
234600eb8a63Santirez     ldb.currentline = ar->currentline;
234700eb8a63Santirez 
234800eb8a63Santirez     int bp = ldbIsBreakpoint(ldb.currentline) || ldb.luabp;
234900eb8a63Santirez     int timeout = 0;
235000eb8a63Santirez 
235100eb8a63Santirez     /* Events outside our script are not interesting. */
235202de5d99Santirez     if(strstr(ar->short_src,"user_script") == NULL) return;
235302de5d99Santirez 
235400eb8a63Santirez     /* Check if a timeout occurred. */
235500eb8a63Santirez     if (ar->event == LUA_HOOKCOUNT && ldb.step == 0 && bp == 0) {
235600eb8a63Santirez         mstime_t elapsed = mstime() - server.lua_time_start;
235700eb8a63Santirez         mstime_t timelimit = server.lua_time_limit ?
235800eb8a63Santirez                              server.lua_time_limit : 5000;
235900eb8a63Santirez         if (elapsed >= timelimit) {
236000eb8a63Santirez             timeout = 1;
236100eb8a63Santirez             ldb.step = 1;
236200eb8a63Santirez         } else {
236300eb8a63Santirez             return; /* No timeout, ignore the COUNT event. */
236400eb8a63Santirez         }
236500eb8a63Santirez     }
236600eb8a63Santirez 
23678a0020f1Santirez     if (ldb.step || bp) {
236851de527aSantirez         char *reason = "step over";
236951de527aSantirez         if (bp) reason = ldb.luabp ? "redis.breakpoint() called" :
237051de527aSantirez                                      "break point";
237100eb8a63Santirez         else if (timeout) reason = "timeout reached, infinite loop?";
237202de5d99Santirez         ldb.step = 0;
237351de527aSantirez         ldb.luabp = 0;
23748a0020f1Santirez         ldbLog(sdscatprintf(sdsempty(),
23758a0020f1Santirez             "* Stopped at %d, stop reason = %s",
23768a0020f1Santirez             ldb.currentline, reason));
23778a0020f1Santirez         ldbLogSourceLine(ldb.currentline);
237802de5d99Santirez         ldbSendLogs();
237900eb8a63Santirez         if (ldbRepl(lua) == C_ERR && timeout) {
238000eb8a63Santirez             /* If the client closed the connection and we have a timeout
238100eb8a63Santirez              * connection, let's kill the script otherwise the process
238200eb8a63Santirez              * will remain blocked indefinitely. */
238300eb8a63Santirez             lua_pushstring(lua, "timeout during Lua debugging with client closing connection");
238400eb8a63Santirez             lua_error(lua);
238500eb8a63Santirez         }
238600eb8a63Santirez         server.lua_time_start = mstime();
2387def31636Santirez     }
238802de5d99Santirez }
23891fb2b91aSantirez 
2390