xref: /redis-3.2.3/src/scripting.c (revision d75e0fdb)
1 /*
2  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *   * Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *   * Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  *   * Neither the name of Redis nor the names of its contributors may be used
14  *     to endorse or promote products derived from this software without
15  *     specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "server.h"
31 #include "sha1.h"
32 #include "rand.h"
33 #include "cluster.h"
34 
35 #include <lua.h>
36 #include <lauxlib.h>
37 #include <lualib.h>
38 #include <ctype.h>
39 #include <math.h>
40 
41 char *redisProtocolToLuaType_Int(lua_State *lua, char *reply);
42 char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply);
43 char *redisProtocolToLuaType_Status(lua_State *lua, char *reply);
44 char *redisProtocolToLuaType_Error(lua_State *lua, char *reply);
45 char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply);
46 int redis_math_random (lua_State *L);
47 int redis_math_randomseed (lua_State *L);
48 void ldbInit(void);
49 void ldbDisable(client *c);
50 void ldbEnable(client *c);
51 void evalGenericCommandWithDebugging(client *c, int evalsha);
52 void luaLdbLineHook(lua_State *lua, lua_Debug *ar);
53 void ldbLog(sds entry);
54 void ldbLogRedisReply(char *reply);
55 sds ldbCatStackValue(sds s, lua_State *lua, int idx);
56 
57 /* Debugger shared state is stored inside this global structure. */
58 #define LDB_BREAKPOINTS_MAX 64  /* Max number of breakpoints. */
59 #define LDB_MAX_LEN_DEFAULT 256 /* Default len limit for replies / var dumps. */
60 struct ldbState {
61     int fd;     /* Socket of the debugging client. */
62     int active; /* Are we debugging EVAL right now? */
63     int forked; /* Is this a fork()ed debugging session? */
64     list *logs; /* List of messages to send to the client. */
65     list *traces; /* Messages about Redis commands executed since last stop.*/
66     list *children; /* All forked debugging sessions pids. */
67     int bp[LDB_BREAKPOINTS_MAX]; /* An array of breakpoints line numbers. */
68     int bpcount; /* Number of valid entries inside bp. */
69     int step;   /* Stop at next line ragardless of breakpoints. */
70     int luabp;  /* Stop at next line because redis.breakpoint() was called. */
71     sds *src;   /* Lua script source code split by line. */
72     int lines;  /* Number of lines in 'src'. */
73     int currentline;    /* Current line number. */
74     sds cbuf;   /* Debugger client command buffer. */
75     size_t maxlen;  /* Max var dump / reply length. */
76     int maxlen_hint_sent; /* Did we already hint about "set maxlen"? */
77 } ldb;
78 
79 /* ---------------------------------------------------------------------------
80  * Utility functions.
81  * ------------------------------------------------------------------------- */
82 
83 /* Perform the SHA1 of the input string. We use this both for hashing script
84  * bodies in order to obtain the Lua function name, and in the implementation
85  * of redis.sha1().
86  *
87  * 'digest' should point to a 41 bytes buffer: 40 for SHA1 converted into an
88  * hexadecimal number, plus 1 byte for null term. */
89 void sha1hex(char *digest, char *script, size_t len) {
90     SHA1_CTX ctx;
91     unsigned char hash[20];
92     char *cset = "0123456789abcdef";
93     int j;
94 
95     SHA1Init(&ctx);
96     SHA1Update(&ctx,(unsigned char*)script,len);
97     SHA1Final(hash,&ctx);
98 
99     for (j = 0; j < 20; j++) {
100         digest[j*2] = cset[((hash[j]&0xF0)>>4)];
101         digest[j*2+1] = cset[(hash[j]&0xF)];
102     }
103     digest[40] = '\0';
104 }
105 
106 /* ---------------------------------------------------------------------------
107  * Redis reply to Lua type conversion functions.
108  * ------------------------------------------------------------------------- */
109 
110 /* Take a Redis reply in the Redis protocol format and convert it into a
111  * Lua type. Thanks to this function, and the introduction of not connected
112  * clients, it is trivial to implement the redis() lua function.
113  *
114  * Basically we take the arguments, execute the Redis command in the context
115  * of a non connected client, then take the generated reply and convert it
116  * into a suitable Lua type. With this trick the scripting feature does not
117  * need the introduction of a full Redis internals API. The script
118  * is like a normal client that bypasses all the slow I/O paths.
119  *
120  * Note: in this function we do not do any sanity check as the reply is
121  * generated by Redis directly. This allows us to go faster.
122  *
123  * Errors are returned as a table with a single 'err' field set to the
124  * error string.
125  */
126 
127 char *redisProtocolToLuaType(lua_State *lua, char* reply) {
128     char *p = reply;
129 
130     switch(*p) {
131     case ':': p = redisProtocolToLuaType_Int(lua,reply); break;
132     case '$': p = redisProtocolToLuaType_Bulk(lua,reply); break;
133     case '+': p = redisProtocolToLuaType_Status(lua,reply); break;
134     case '-': p = redisProtocolToLuaType_Error(lua,reply); break;
135     case '*': p = redisProtocolToLuaType_MultiBulk(lua,reply); break;
136     }
137     return p;
138 }
139 
140 char *redisProtocolToLuaType_Int(lua_State *lua, char *reply) {
141     char *p = strchr(reply+1,'\r');
142     long long value;
143 
144     string2ll(reply+1,p-reply-1,&value);
145     lua_pushnumber(lua,(lua_Number)value);
146     return p+2;
147 }
148 
149 char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply) {
150     char *p = strchr(reply+1,'\r');
151     long long bulklen;
152 
153     string2ll(reply+1,p-reply-1,&bulklen);
154     if (bulklen == -1) {
155         lua_pushboolean(lua,0);
156         return p+2;
157     } else {
158         lua_pushlstring(lua,p+2,bulklen);
159         return p+2+bulklen+2;
160     }
161 }
162 
163 char *redisProtocolToLuaType_Status(lua_State *lua, char *reply) {
164     char *p = strchr(reply+1,'\r');
165 
166     lua_newtable(lua);
167     lua_pushstring(lua,"ok");
168     lua_pushlstring(lua,reply+1,p-reply-1);
169     lua_settable(lua,-3);
170     return p+2;
171 }
172 
173 char *redisProtocolToLuaType_Error(lua_State *lua, char *reply) {
174     char *p = strchr(reply+1,'\r');
175 
176     lua_newtable(lua);
177     lua_pushstring(lua,"err");
178     lua_pushlstring(lua,reply+1,p-reply-1);
179     lua_settable(lua,-3);
180     return p+2;
181 }
182 
183 char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply) {
184     char *p = strchr(reply+1,'\r');
185     long long mbulklen;
186     int j = 0;
187 
188     string2ll(reply+1,p-reply-1,&mbulklen);
189     p += 2;
190     if (mbulklen == -1) {
191         lua_pushboolean(lua,0);
192         return p;
193     }
194     lua_newtable(lua);
195     for (j = 0; j < mbulklen; j++) {
196         lua_pushnumber(lua,j+1);
197         p = redisProtocolToLuaType(lua,p);
198         lua_settable(lua,-3);
199     }
200     return p;
201 }
202 
203 /* This function is used in order to push an error on the Lua stack in the
204  * format used by redis.pcall to return errors, which is a lua table
205  * with a single "err" field set to the error string. Note that this
206  * table is never a valid reply by proper commands, since the returned
207  * tables are otherwise always indexed by integers, never by strings. */
208 void luaPushError(lua_State *lua, char *error) {
209     lua_Debug dbg;
210 
211     /* If debugging is active and in step mode, log errors resulting from
212      * Redis commands. */
213     if (ldb.active && ldb.step) {
214         ldbLog(sdscatprintf(sdsempty(),"<error> %s",error));
215     }
216 
217     lua_newtable(lua);
218     lua_pushstring(lua,"err");
219 
220     /* Attempt to figure out where this function was called, if possible */
221     if(lua_getstack(lua, 1, &dbg) && lua_getinfo(lua, "nSl", &dbg)) {
222         sds msg = sdscatprintf(sdsempty(), "%s: %d: %s",
223             dbg.source, dbg.currentline, error);
224         lua_pushstring(lua, msg);
225         sdsfree(msg);
226     } else {
227         lua_pushstring(lua, error);
228     }
229     lua_settable(lua,-3);
230 }
231 
232 /* In case the error set into the Lua stack by luaPushError() was generated
233  * by the non-error-trapping version of redis.pcall(), which is redis.call(),
234  * this function will raise the Lua error so that the execution of the
235  * script will be halted. */
236 int luaRaiseError(lua_State *lua) {
237     lua_pushstring(lua,"err");
238     lua_gettable(lua,-2);
239     return lua_error(lua);
240 }
241 
242 /* Sort the array currently in the stack. We do this to make the output
243  * of commands like KEYS or SMEMBERS something deterministic when called
244  * from Lua (to play well with AOf/replication).
245  *
246  * The array is sorted using table.sort itself, and assuming all the
247  * list elements are strings. */
248 void luaSortArray(lua_State *lua) {
249     /* Initial Stack: array */
250     lua_getglobal(lua,"table");
251     lua_pushstring(lua,"sort");
252     lua_gettable(lua,-2);       /* Stack: array, table, table.sort */
253     lua_pushvalue(lua,-3);      /* Stack: array, table, table.sort, array */
254     if (lua_pcall(lua,1,0,0)) {
255         /* Stack: array, table, error */
256 
257         /* We are not interested in the error, we assume that the problem is
258          * that there are 'false' elements inside the array, so we try
259          * again with a slower function but able to handle this case, that
260          * is: table.sort(table, __redis__compare_helper) */
261         lua_pop(lua,1);             /* Stack: array, table */
262         lua_pushstring(lua,"sort"); /* Stack: array, table, sort */
263         lua_gettable(lua,-2);       /* Stack: array, table, table.sort */
264         lua_pushvalue(lua,-3);      /* Stack: array, table, table.sort, array */
265         lua_getglobal(lua,"__redis__compare_helper");
266         /* Stack: array, table, table.sort, array, __redis__compare_helper */
267         lua_call(lua,2,0);
268     }
269     /* Stack: array (sorted), table */
270     lua_pop(lua,1);             /* Stack: array (sorted) */
271 }
272 
273 /* ---------------------------------------------------------------------------
274  * Lua reply to Redis reply conversion functions.
275  * ------------------------------------------------------------------------- */
276 
277 void luaReplyToRedisReply(client *c, lua_State *lua) {
278     int t = lua_type(lua,-1);
279 
280     switch(t) {
281     case LUA_TSTRING:
282         addReplyBulkCBuffer(c,(char*)lua_tostring(lua,-1),lua_strlen(lua,-1));
283         break;
284     case LUA_TBOOLEAN:
285         addReply(c,lua_toboolean(lua,-1) ? shared.cone : shared.nullbulk);
286         break;
287     case LUA_TNUMBER:
288         addReplyLongLong(c,(long long)lua_tonumber(lua,-1));
289         break;
290     case LUA_TTABLE:
291         /* We need to check if it is an array, an error, or a status reply.
292          * Error are returned as a single element table with 'err' field.
293          * Status replies are returned as single element table with 'ok'
294          * field. */
295         lua_pushstring(lua,"err");
296         lua_gettable(lua,-2);
297         t = lua_type(lua,-1);
298         if (t == LUA_TSTRING) {
299             sds err = sdsnew(lua_tostring(lua,-1));
300             sdsmapchars(err,"\r\n","  ",2);
301             addReplySds(c,sdscatprintf(sdsempty(),"-%s\r\n",err));
302             sdsfree(err);
303             lua_pop(lua,2);
304             return;
305         }
306 
307         lua_pop(lua,1);
308         lua_pushstring(lua,"ok");
309         lua_gettable(lua,-2);
310         t = lua_type(lua,-1);
311         if (t == LUA_TSTRING) {
312             sds ok = sdsnew(lua_tostring(lua,-1));
313             sdsmapchars(ok,"\r\n","  ",2);
314             addReplySds(c,sdscatprintf(sdsempty(),"+%s\r\n",ok));
315             sdsfree(ok);
316             lua_pop(lua,1);
317         } else {
318             void *replylen = addDeferredMultiBulkLength(c);
319             int j = 1, mbulklen = 0;
320 
321             lua_pop(lua,1); /* Discard the 'ok' field value we popped */
322             while(1) {
323                 lua_pushnumber(lua,j++);
324                 lua_gettable(lua,-2);
325                 t = lua_type(lua,-1);
326                 if (t == LUA_TNIL) {
327                     lua_pop(lua,1);
328                     break;
329                 }
330                 luaReplyToRedisReply(c, lua);
331                 mbulklen++;
332             }
333             setDeferredMultiBulkLength(c,replylen,mbulklen);
334         }
335         break;
336     default:
337         addReply(c,shared.nullbulk);
338     }
339     lua_pop(lua,1);
340 }
341 
342 /* ---------------------------------------------------------------------------
343  * Lua redis.* functions implementations.
344  * ------------------------------------------------------------------------- */
345 
346 #define LUA_CMD_OBJCACHE_SIZE 32
347 #define LUA_CMD_OBJCACHE_MAX_LEN 64
348 int luaRedisGenericCommand(lua_State *lua, int raise_error) {
349     int j, argc = lua_gettop(lua);
350     struct redisCommand *cmd;
351     client *c = server.lua_client;
352     sds reply;
353 
354     /* Cached across calls. */
355     static robj **argv = NULL;
356     static int argv_size = 0;
357     static robj *cached_objects[LUA_CMD_OBJCACHE_SIZE];
358     static size_t cached_objects_len[LUA_CMD_OBJCACHE_SIZE];
359     static int inuse = 0;   /* Recursive calls detection. */
360 
361     /* By using Lua debug hooks it is possible to trigger a recursive call
362      * to luaRedisGenericCommand(), which normally should never happen.
363      * To make this function reentrant is futile and makes it slower, but
364      * we should at least detect such a misuse, and abort. */
365     if (inuse) {
366         char *recursion_warning =
367             "luaRedisGenericCommand() recursive call detected. "
368             "Are you doing funny stuff with Lua debug hooks?";
369         serverLog(LL_WARNING,"%s",recursion_warning);
370         luaPushError(lua,recursion_warning);
371         return 1;
372     }
373     inuse++;
374 
375     /* Require at least one argument */
376     if (argc == 0) {
377         luaPushError(lua,
378             "Please specify at least one argument for redis.call()");
379         inuse--;
380         return raise_error ? luaRaiseError(lua) : 1;
381     }
382 
383     /* Build the arguments vector */
384     if (argv_size < argc) {
385         argv = zrealloc(argv,sizeof(robj*)*argc);
386         argv_size = argc;
387     }
388 
389     for (j = 0; j < argc; j++) {
390         char *obj_s;
391         size_t obj_len;
392         char dbuf[64];
393 
394         if (lua_type(lua,j+1) == LUA_TNUMBER) {
395             /* We can't use lua_tolstring() for number -> string conversion
396              * since Lua uses a format specifier that loses precision. */
397             lua_Number num = lua_tonumber(lua,j+1);
398 
399             obj_len = snprintf(dbuf,sizeof(dbuf),"%.17g",(double)num);
400             obj_s = dbuf;
401         } else {
402             obj_s = (char*)lua_tolstring(lua,j+1,&obj_len);
403             if (obj_s == NULL) break; /* Not a string. */
404         }
405 
406         /* Try to use a cached object. */
407         if (j < LUA_CMD_OBJCACHE_SIZE && cached_objects[j] &&
408             cached_objects_len[j] >= obj_len)
409         {
410             sds s = cached_objects[j]->ptr;
411             argv[j] = cached_objects[j];
412             cached_objects[j] = NULL;
413             memcpy(s,obj_s,obj_len+1);
414             sdssetlen(s, obj_len);
415         } else {
416             argv[j] = createStringObject(obj_s, obj_len);
417         }
418     }
419 
420     /* Check if one of the arguments passed by the Lua script
421      * is not a string or an integer (lua_isstring() return true for
422      * integers as well). */
423     if (j != argc) {
424         j--;
425         while (j >= 0) {
426             decrRefCount(argv[j]);
427             j--;
428         }
429         luaPushError(lua,
430             "Lua redis() command arguments must be strings or integers");
431         inuse--;
432         return raise_error ? luaRaiseError(lua) : 1;
433     }
434 
435     /* Setup our fake client for command execution */
436     c->argv = argv;
437     c->argc = argc;
438 
439     /* Log the command if debugging is active. */
440     if (ldb.active && ldb.step) {
441         sds cmdlog = sdsnew("<redis>");
442         for (j = 0; j < c->argc; j++) {
443             if (j == 10) {
444                 cmdlog = sdscatprintf(cmdlog," ... (%d more)",
445                     c->argc-j-1);
446             } else {
447                 cmdlog = sdscatlen(cmdlog," ",1);
448                 cmdlog = sdscatsds(cmdlog,c->argv[j]->ptr);
449             }
450         }
451         ldbLog(cmdlog);
452     }
453 
454     /* Command lookup */
455     cmd = lookupCommand(argv[0]->ptr);
456     if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) ||
457                    (argc < -cmd->arity)))
458     {
459         if (cmd)
460             luaPushError(lua,
461                 "Wrong number of args calling Redis command From Lua script");
462         else
463             luaPushError(lua,"Unknown Redis command called from Lua script");
464         goto cleanup;
465     }
466     c->cmd = c->lastcmd = cmd;
467 
468     /* There are commands that are not allowed inside scripts. */
469     if (cmd->flags & CMD_NOSCRIPT) {
470         luaPushError(lua, "This Redis command is not allowed from scripts");
471         goto cleanup;
472     }
473 
474     /* Write commands are forbidden against read-only slaves, or if a
475      * command marked as non-deterministic was already called in the context
476      * of this script. */
477     if (cmd->flags & CMD_WRITE) {
478         if (server.lua_random_dirty && !server.lua_replicate_commands) {
479             luaPushError(lua,
480                 "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.");
481             goto cleanup;
482         } else if (server.masterhost && server.repl_slave_ro &&
483                    !server.loading &&
484                    !(server.lua_caller->flags & CLIENT_MASTER))
485         {
486             luaPushError(lua, shared.roslaveerr->ptr);
487             goto cleanup;
488         } else if (server.stop_writes_on_bgsave_err &&
489                    server.saveparamslen > 0 &&
490                    server.lastbgsave_status == C_ERR)
491         {
492             luaPushError(lua, shared.bgsaveerr->ptr);
493             goto cleanup;
494         }
495     }
496 
497     /* If we reached the memory limit configured via maxmemory, commands that
498      * could enlarge the memory usage are not allowed, but only if this is the
499      * first write in the context of this script, otherwise we can't stop
500      * in the middle. */
501     if (server.maxmemory && server.lua_write_dirty == 0 &&
502         (cmd->flags & CMD_DENYOOM))
503     {
504         if (freeMemoryIfNeeded() == C_ERR) {
505             luaPushError(lua, shared.oomerr->ptr);
506             goto cleanup;
507         }
508     }
509 
510     if (cmd->flags & CMD_RANDOM) server.lua_random_dirty = 1;
511     if (cmd->flags & CMD_WRITE) server.lua_write_dirty = 1;
512 
513     /* If this is a Redis Cluster node, we need to make sure Lua is not
514      * trying to access non-local keys, with the exception of commands
515      * received from our master. */
516     if (server.cluster_enabled && !(server.lua_caller->flags & CLIENT_MASTER)) {
517         /* Duplicate relevant flags in the lua client. */
518         c->flags &= ~(CLIENT_READONLY|CLIENT_ASKING);
519         c->flags |= server.lua_caller->flags & (CLIENT_READONLY|CLIENT_ASKING);
520         if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) !=
521                            server.cluster->myself)
522         {
523             luaPushError(lua,
524                 "Lua script attempted to access a non local key in a "
525                 "cluster node");
526             goto cleanup;
527         }
528     }
529 
530     /* If we are using single commands replication, we need to wrap what
531      * we propagate into a MULTI/EXEC block, so that it will be atomic like
532      * a Lua script in the context of AOF and slaves. */
533     if (server.lua_replicate_commands &&
534         !server.lua_multi_emitted &&
535         server.lua_write_dirty &&
536         server.lua_repl != PROPAGATE_NONE)
537     {
538         execCommandPropagateMulti(server.lua_caller);
539         server.lua_multi_emitted = 1;
540     }
541 
542     /* Run the command */
543     int call_flags = CMD_CALL_SLOWLOG | CMD_CALL_STATS;
544     if (server.lua_replicate_commands) {
545         /* Set flags according to redis.set_repl() settings. */
546         if (server.lua_repl & PROPAGATE_AOF)
547             call_flags |= CMD_CALL_PROPAGATE_AOF;
548         if (server.lua_repl & PROPAGATE_REPL)
549             call_flags |= CMD_CALL_PROPAGATE_REPL;
550     }
551     call(c,call_flags);
552 
553     /* Convert the result of the Redis command into a suitable Lua type.
554      * The first thing we need is to create a single string from the client
555      * output buffers. */
556     if (listLength(c->reply) == 0 && c->bufpos < PROTO_REPLY_CHUNK_BYTES) {
557         /* This is a fast path for the common case of a reply inside the
558          * client static buffer. Don't create an SDS string but just use
559          * the client buffer directly. */
560         c->buf[c->bufpos] = '\0';
561         reply = c->buf;
562         c->bufpos = 0;
563     } else {
564         reply = sdsnewlen(c->buf,c->bufpos);
565         c->bufpos = 0;
566         while(listLength(c->reply)) {
567             robj *o = listNodeValue(listFirst(c->reply));
568 
569             reply = sdscatlen(reply,o->ptr,sdslen(o->ptr));
570             listDelNode(c->reply,listFirst(c->reply));
571         }
572     }
573     if (raise_error && reply[0] != '-') raise_error = 0;
574     redisProtocolToLuaType(lua,reply);
575 
576     /* If the debugger is active, log the reply from Redis. */
577     if (ldb.active && ldb.step)
578         ldbLogRedisReply(reply);
579 
580     /* Sort the output array if needed, assuming it is a non-null multi bulk
581      * reply as expected. */
582     if ((cmd->flags & CMD_SORT_FOR_SCRIPT) &&
583         (server.lua_replicate_commands == 0) &&
584         (reply[0] == '*' && reply[1] != '-')) {
585             luaSortArray(lua);
586     }
587     if (reply != c->buf) sdsfree(reply);
588     c->reply_bytes = 0;
589 
590 cleanup:
591     /* Clean up. Command code may have changed argv/argc so we use the
592      * argv/argc of the client instead of the local variables. */
593     for (j = 0; j < c->argc; j++) {
594         robj *o = c->argv[j];
595 
596         /* Try to cache the object in the cached_objects array.
597          * The object must be small, SDS-encoded, and with refcount = 1
598          * (we must be the only owner) for us to cache it. */
599         if (j < LUA_CMD_OBJCACHE_SIZE &&
600             o->refcount == 1 &&
601             (o->encoding == OBJ_ENCODING_RAW ||
602              o->encoding == OBJ_ENCODING_EMBSTR) &&
603             sdslen(o->ptr) <= LUA_CMD_OBJCACHE_MAX_LEN)
604         {
605             sds s = o->ptr;
606             if (cached_objects[j]) decrRefCount(cached_objects[j]);
607             cached_objects[j] = o;
608             cached_objects_len[j] = sdsalloc(s);
609         } else {
610             decrRefCount(o);
611         }
612     }
613 
614     if (c->argv != argv) {
615         zfree(c->argv);
616         argv = NULL;
617         argv_size = 0;
618     }
619 
620     if (raise_error) {
621         /* If we are here we should have an error in the stack, in the
622          * form of a table with an "err" field. Extract the string to
623          * return the plain error. */
624         inuse--;
625         return luaRaiseError(lua);
626     }
627     inuse--;
628     return 1;
629 }
630 
631 /* redis.call() */
632 int luaRedisCallCommand(lua_State *lua) {
633     return luaRedisGenericCommand(lua,1);
634 }
635 
636 /* redis.pcall() */
637 int luaRedisPCallCommand(lua_State *lua) {
638     return luaRedisGenericCommand(lua,0);
639 }
640 
641 /* This adds redis.sha1hex(string) to Lua scripts using the same hashing
642  * function used for sha1ing lua scripts. */
643 int luaRedisSha1hexCommand(lua_State *lua) {
644     int argc = lua_gettop(lua);
645     char digest[41];
646     size_t len;
647     char *s;
648 
649     if (argc != 1) {
650         lua_pushstring(lua, "wrong number of arguments");
651         return lua_error(lua);
652     }
653 
654     s = (char*)lua_tolstring(lua,1,&len);
655     sha1hex(digest,s,len);
656     lua_pushstring(lua,digest);
657     return 1;
658 }
659 
660 /* Returns a table with a single field 'field' set to the string value
661  * passed as argument. This helper function is handy when returning
662  * a Redis Protocol error or status reply from Lua:
663  *
664  * return redis.error_reply("ERR Some Error")
665  * return redis.status_reply("ERR Some Error")
666  */
667 int luaRedisReturnSingleFieldTable(lua_State *lua, char *field) {
668     if (lua_gettop(lua) != 1 || lua_type(lua,-1) != LUA_TSTRING) {
669         luaPushError(lua, "wrong number or type of arguments");
670         return 1;
671     }
672 
673     lua_newtable(lua);
674     lua_pushstring(lua, field);
675     lua_pushvalue(lua, -3);
676     lua_settable(lua, -3);
677     return 1;
678 }
679 
680 /* redis.error_reply() */
681 int luaRedisErrorReplyCommand(lua_State *lua) {
682     return luaRedisReturnSingleFieldTable(lua,"err");
683 }
684 
685 /* redis.status_reply() */
686 int luaRedisStatusReplyCommand(lua_State *lua) {
687     return luaRedisReturnSingleFieldTable(lua,"ok");
688 }
689 
690 /* redis.replicate_commands()
691  *
692  * Turn on single commands replication if the script never called
693  * a write command so far, and returns true. Otherwise if the script
694  * already started to write, returns false and stick to whole scripts
695  * replication, which is our default. */
696 int luaRedisReplicateCommandsCommand(lua_State *lua) {
697     if (server.lua_write_dirty) {
698         lua_pushboolean(lua,0);
699     } else {
700         server.lua_replicate_commands = 1;
701         /* When we switch to single commands replication, we can provide
702          * different math.random() sequences at every call, which is what
703          * the user normally expects. */
704         redisSrand48(rand());
705         lua_pushboolean(lua,1);
706     }
707     return 1;
708 }
709 
710 /* redis.breakpoint()
711  *
712  * Allows to stop execution during a debuggign session from within
713  * the Lua code implementation, like if a breakpoint was set in the code
714  * immediately after the function. */
715 int luaRedisBreakpointCommand(lua_State *lua) {
716     if (ldb.active) {
717         ldb.luabp = 1;
718         lua_pushboolean(lua,1);
719     } else {
720         lua_pushboolean(lua,0);
721     }
722     return 1;
723 }
724 
725 /* redis.debug()
726  *
727  * Log a string message into the output console.
728  * Can take multiple arguments that will be separated by commas.
729  * Nothing is returned to the caller. */
730 int luaRedisDebugCommand(lua_State *lua) {
731     if (!ldb.active) return 0;
732     int argc = lua_gettop(lua);
733     sds log = sdscatprintf(sdsempty(),"<debug> line %d: ", ldb.currentline);
734     while(argc--) {
735         log = ldbCatStackValue(log,lua,-1 - argc);
736         if (argc != 0) log = sdscatlen(log,", ",2);
737     }
738     ldbLog(log);
739     return 0;
740 }
741 
742 /* redis.set_repl()
743  *
744  * Set the propagation of write commands executed in the context of the
745  * script to on/off for AOF and slaves. */
746 int luaRedisSetReplCommand(lua_State *lua) {
747     int argc = lua_gettop(lua);
748     int flags;
749 
750     if (server.lua_replicate_commands == 0) {
751         lua_pushstring(lua, "You can set the replication behavior only after turning on single commands replication with redis.replicate_commands().");
752         return lua_error(lua);
753     } else if (argc != 1) {
754         lua_pushstring(lua, "redis.set_repl() requires two arguments.");
755         return lua_error(lua);
756     }
757 
758     flags = lua_tonumber(lua,-1);
759     if ((flags & ~(PROPAGATE_AOF|PROPAGATE_REPL)) != 0) {
760         lua_pushstring(lua, "Invalid replication flags. Use REPL_AOF, REPL_SLAVE, REPL_ALL or REPL_NONE.");
761         return lua_error(lua);
762     }
763     server.lua_repl = flags;
764     return 0;
765 }
766 
767 /* redis.log() */
768 int luaLogCommand(lua_State *lua) {
769     int j, argc = lua_gettop(lua);
770     int level;
771     sds log;
772 
773     if (argc < 2) {
774         lua_pushstring(lua, "redis.log() requires two arguments or more.");
775         return lua_error(lua);
776     } else if (!lua_isnumber(lua,-argc)) {
777         lua_pushstring(lua, "First argument must be a number (log level).");
778         return lua_error(lua);
779     }
780     level = lua_tonumber(lua,-argc);
781     if (level < LL_DEBUG || level > LL_WARNING) {
782         lua_pushstring(lua, "Invalid debug level.");
783         return lua_error(lua);
784     }
785 
786     /* Glue together all the arguments */
787     log = sdsempty();
788     for (j = 1; j < argc; j++) {
789         size_t len;
790         char *s;
791 
792         s = (char*)lua_tolstring(lua,(-argc)+j,&len);
793         if (s) {
794             if (j != 1) log = sdscatlen(log," ",1);
795             log = sdscatlen(log,s,len);
796         }
797     }
798     serverLogRaw(level,log);
799     sdsfree(log);
800     return 0;
801 }
802 
803 /* ---------------------------------------------------------------------------
804  * Lua engine initialization and reset.
805  * ------------------------------------------------------------------------- */
806 
807 void luaLoadLib(lua_State *lua, const char *libname, lua_CFunction luafunc) {
808   lua_pushcfunction(lua, luafunc);
809   lua_pushstring(lua, libname);
810   lua_call(lua, 1, 0);
811 }
812 
813 LUALIB_API int (luaopen_cjson) (lua_State *L);
814 LUALIB_API int (luaopen_struct) (lua_State *L);
815 LUALIB_API int (luaopen_cmsgpack) (lua_State *L);
816 LUALIB_API int (luaopen_bit) (lua_State *L);
817 
818 void luaLoadLibraries(lua_State *lua) {
819     luaLoadLib(lua, "", luaopen_base);
820     luaLoadLib(lua, LUA_TABLIBNAME, luaopen_table);
821     luaLoadLib(lua, LUA_STRLIBNAME, luaopen_string);
822     luaLoadLib(lua, LUA_MATHLIBNAME, luaopen_math);
823     luaLoadLib(lua, LUA_DBLIBNAME, luaopen_debug);
824     luaLoadLib(lua, "cjson", luaopen_cjson);
825     luaLoadLib(lua, "struct", luaopen_struct);
826     luaLoadLib(lua, "cmsgpack", luaopen_cmsgpack);
827     luaLoadLib(lua, "bit", luaopen_bit);
828 
829 #if 0 /* Stuff that we don't load currently, for sandboxing concerns. */
830     luaLoadLib(lua, LUA_LOADLIBNAME, luaopen_package);
831     luaLoadLib(lua, LUA_OSLIBNAME, luaopen_os);
832 #endif
833 }
834 
835 /* Remove a functions that we don't want to expose to the Redis scripting
836  * environment. */
837 void luaRemoveUnsupportedFunctions(lua_State *lua) {
838     lua_pushnil(lua);
839     lua_setglobal(lua,"loadfile");
840 }
841 
842 /* This function installs metamethods in the global table _G that prevent
843  * the creation of globals accidentally.
844  *
845  * It should be the last to be called in the scripting engine initialization
846  * sequence, because it may interact with creation of globals. */
847 void scriptingEnableGlobalsProtection(lua_State *lua) {
848     char *s[32];
849     sds code = sdsempty();
850     int j = 0;
851 
852     /* strict.lua from: http://metalua.luaforge.net/src/lib/strict.lua.html.
853      * Modified to be adapted to Redis. */
854     s[j++]="local dbg=debug\n";
855     s[j++]="local mt = {}\n";
856     s[j++]="setmetatable(_G, mt)\n";
857     s[j++]="mt.__newindex = function (t, n, v)\n";
858     s[j++]="  if dbg.getinfo(2) then\n";
859     s[j++]="    local w = dbg.getinfo(2, \"S\").what\n";
860     s[j++]="    if w ~= \"main\" and w ~= \"C\" then\n";
861     s[j++]="      error(\"Script attempted to create global variable '\"..tostring(n)..\"'\", 2)\n";
862     s[j++]="    end\n";
863     s[j++]="  end\n";
864     s[j++]="  rawset(t, n, v)\n";
865     s[j++]="end\n";
866     s[j++]="mt.__index = function (t, n)\n";
867     s[j++]="  if dbg.getinfo(2) and dbg.getinfo(2, \"S\").what ~= \"C\" then\n";
868     s[j++]="    error(\"Script attempted to access unexisting global variable '\"..tostring(n)..\"'\", 2)\n";
869     s[j++]="  end\n";
870     s[j++]="  return rawget(t, n)\n";
871     s[j++]="end\n";
872     s[j++]="debug = nil\n";
873     s[j++]=NULL;
874 
875     for (j = 0; s[j] != NULL; j++) code = sdscatlen(code,s[j],strlen(s[j]));
876     luaL_loadbuffer(lua,code,sdslen(code),"@enable_strict_lua");
877     lua_pcall(lua,0,0,0);
878     sdsfree(code);
879 }
880 
881 /* Initialize the scripting environment.
882  *
883  * This function is called the first time at server startup with
884  * the 'setup' argument set to 1.
885  *
886  * It can be called again multiple times during the lifetime of the Redis
887  * process, with 'setup' set to 0, and following a scriptingRelease() call,
888  * in order to reset the Lua scripting environment.
889  *
890  * However it is simpler to just call scriptingReset() that does just that. */
891 void scriptingInit(int setup) {
892     lua_State *lua = lua_open();
893 
894     if (setup) {
895         server.lua_client = NULL;
896         server.lua_caller = NULL;
897         server.lua_timedout = 0;
898         server.lua_always_replicate_commands = 0; /* Only DEBUG can change it.*/
899         server.lua_time_limit = LUA_SCRIPT_TIME_LIMIT;
900         ldbInit();
901     }
902 
903     luaLoadLibraries(lua);
904     luaRemoveUnsupportedFunctions(lua);
905 
906     /* Initialize a dictionary we use to map SHAs to scripts.
907      * This is useful for replication, as we need to replicate EVALSHA
908      * as EVAL, so we need to remember the associated script. */
909     server.lua_scripts = dictCreate(&shaScriptObjectDictType,NULL);
910 
911     /* Register the redis commands table and fields */
912     lua_newtable(lua);
913 
914     /* redis.call */
915     lua_pushstring(lua,"call");
916     lua_pushcfunction(lua,luaRedisCallCommand);
917     lua_settable(lua,-3);
918 
919     /* redis.pcall */
920     lua_pushstring(lua,"pcall");
921     lua_pushcfunction(lua,luaRedisPCallCommand);
922     lua_settable(lua,-3);
923 
924     /* redis.log and log levels. */
925     lua_pushstring(lua,"log");
926     lua_pushcfunction(lua,luaLogCommand);
927     lua_settable(lua,-3);
928 
929     lua_pushstring(lua,"LOG_DEBUG");
930     lua_pushnumber(lua,LL_DEBUG);
931     lua_settable(lua,-3);
932 
933     lua_pushstring(lua,"LOG_VERBOSE");
934     lua_pushnumber(lua,LL_VERBOSE);
935     lua_settable(lua,-3);
936 
937     lua_pushstring(lua,"LOG_NOTICE");
938     lua_pushnumber(lua,LL_NOTICE);
939     lua_settable(lua,-3);
940 
941     lua_pushstring(lua,"LOG_WARNING");
942     lua_pushnumber(lua,LL_WARNING);
943     lua_settable(lua,-3);
944 
945     /* redis.sha1hex */
946     lua_pushstring(lua, "sha1hex");
947     lua_pushcfunction(lua, luaRedisSha1hexCommand);
948     lua_settable(lua, -3);
949 
950     /* redis.error_reply and redis.status_reply */
951     lua_pushstring(lua, "error_reply");
952     lua_pushcfunction(lua, luaRedisErrorReplyCommand);
953     lua_settable(lua, -3);
954     lua_pushstring(lua, "status_reply");
955     lua_pushcfunction(lua, luaRedisStatusReplyCommand);
956     lua_settable(lua, -3);
957 
958     /* redis.replicate_commands */
959     lua_pushstring(lua, "replicate_commands");
960     lua_pushcfunction(lua, luaRedisReplicateCommandsCommand);
961     lua_settable(lua, -3);
962 
963     /* redis.set_repl and associated flags. */
964     lua_pushstring(lua,"set_repl");
965     lua_pushcfunction(lua,luaRedisSetReplCommand);
966     lua_settable(lua,-3);
967 
968     lua_pushstring(lua,"REPL_NONE");
969     lua_pushnumber(lua,PROPAGATE_NONE);
970     lua_settable(lua,-3);
971 
972     lua_pushstring(lua,"REPL_AOF");
973     lua_pushnumber(lua,PROPAGATE_AOF);
974     lua_settable(lua,-3);
975 
976     lua_pushstring(lua,"REPL_SLAVE");
977     lua_pushnumber(lua,PROPAGATE_REPL);
978     lua_settable(lua,-3);
979 
980     lua_pushstring(lua,"REPL_ALL");
981     lua_pushnumber(lua,PROPAGATE_AOF|PROPAGATE_REPL);
982     lua_settable(lua,-3);
983 
984     /* redis.breakpoint */
985     lua_pushstring(lua,"breakpoint");
986     lua_pushcfunction(lua,luaRedisBreakpointCommand);
987     lua_settable(lua,-3);
988 
989     /* redis.debug */
990     lua_pushstring(lua,"debug");
991     lua_pushcfunction(lua,luaRedisDebugCommand);
992     lua_settable(lua,-3);
993 
994     /* Finally set the table as 'redis' global var. */
995     lua_setglobal(lua,"redis");
996 
997     /* Replace math.random and math.randomseed with our implementations. */
998     lua_getglobal(lua,"math");
999 
1000     lua_pushstring(lua,"random");
1001     lua_pushcfunction(lua,redis_math_random);
1002     lua_settable(lua,-3);
1003 
1004     lua_pushstring(lua,"randomseed");
1005     lua_pushcfunction(lua,redis_math_randomseed);
1006     lua_settable(lua,-3);
1007 
1008     lua_setglobal(lua,"math");
1009 
1010     /* Add a helper function that we use to sort the multi bulk output of non
1011      * deterministic commands, when containing 'false' elements. */
1012     {
1013         char *compare_func =    "function __redis__compare_helper(a,b)\n"
1014                                 "  if a == false then a = '' end\n"
1015                                 "  if b == false then b = '' end\n"
1016                                 "  return a<b\n"
1017                                 "end\n";
1018         luaL_loadbuffer(lua,compare_func,strlen(compare_func),"@cmp_func_def");
1019         lua_pcall(lua,0,0,0);
1020     }
1021 
1022     /* Add a helper function we use for pcall error reporting.
1023      * Note that when the error is in the C function we want to report the
1024      * information about the caller, that's what makes sense from the point
1025      * of view of the user debugging a script. */
1026     {
1027         char *errh_func =       "local dbg = debug\n"
1028                                 "function __redis__err__handler(err)\n"
1029                                 "  local i = dbg.getinfo(2,'nSl')\n"
1030                                 "  if i and i.what == 'C' then\n"
1031                                 "    i = dbg.getinfo(3,'nSl')\n"
1032                                 "  end\n"
1033                                 "  if i then\n"
1034                                 "    return i.source .. ':' .. i.currentline .. ': ' .. err\n"
1035                                 "  else\n"
1036                                 "    return err\n"
1037                                 "  end\n"
1038                                 "end\n";
1039         luaL_loadbuffer(lua,errh_func,strlen(errh_func),"@err_handler_def");
1040         lua_pcall(lua,0,0,0);
1041     }
1042 
1043     /* Create the (non connected) client that we use to execute Redis commands
1044      * inside the Lua interpreter.
1045      * Note: there is no need to create it again when this function is called
1046      * by scriptingReset(). */
1047     if (server.lua_client == NULL) {
1048         server.lua_client = createClient(-1);
1049         server.lua_client->flags |= CLIENT_LUA;
1050     }
1051 
1052     /* Lua beginners often don't use "local", this is likely to introduce
1053      * subtle bugs in their code. To prevent problems we protect accesses
1054      * to global variables. */
1055     scriptingEnableGlobalsProtection(lua);
1056 
1057     server.lua = lua;
1058 }
1059 
1060 /* Release resources related to Lua scripting.
1061  * This function is used in order to reset the scripting environment. */
1062 void scriptingRelease(void) {
1063     dictRelease(server.lua_scripts);
1064     lua_close(server.lua);
1065 }
1066 
1067 void scriptingReset(void) {
1068     scriptingRelease();
1069     scriptingInit(0);
1070 }
1071 
1072 /* Set an array of Redis String Objects as a Lua array (table) stored into a
1073  * global variable. */
1074 void luaSetGlobalArray(lua_State *lua, char *var, robj **elev, int elec) {
1075     int j;
1076 
1077     lua_newtable(lua);
1078     for (j = 0; j < elec; j++) {
1079         lua_pushlstring(lua,(char*)elev[j]->ptr,sdslen(elev[j]->ptr));
1080         lua_rawseti(lua,-2,j+1);
1081     }
1082     lua_setglobal(lua,var);
1083 }
1084 
1085 /* ---------------------------------------------------------------------------
1086  * Redis provided math.random
1087  * ------------------------------------------------------------------------- */
1088 
1089 /* We replace math.random() with our implementation that is not affected
1090  * by specific libc random() implementations and will output the same sequence
1091  * (for the same seed) in every arch. */
1092 
1093 /* The following implementation is the one shipped with Lua itself but with
1094  * rand() replaced by redisLrand48(). */
1095 int redis_math_random (lua_State *L) {
1096   /* the `%' avoids the (rare) case of r==1, and is needed also because on
1097      some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
1098   lua_Number r = (lua_Number)(redisLrand48()%REDIS_LRAND48_MAX) /
1099                                 (lua_Number)REDIS_LRAND48_MAX;
1100   switch (lua_gettop(L)) {  /* check number of arguments */
1101     case 0: {  /* no arguments */
1102       lua_pushnumber(L, r);  /* Number between 0 and 1 */
1103       break;
1104     }
1105     case 1: {  /* only upper limit */
1106       int u = luaL_checkint(L, 1);
1107       luaL_argcheck(L, 1<=u, 1, "interval is empty");
1108       lua_pushnumber(L, floor(r*u)+1);  /* int between 1 and `u' */
1109       break;
1110     }
1111     case 2: {  /* lower and upper limits */
1112       int l = luaL_checkint(L, 1);
1113       int u = luaL_checkint(L, 2);
1114       luaL_argcheck(L, l<=u, 2, "interval is empty");
1115       lua_pushnumber(L, floor(r*(u-l+1))+l);  /* int between `l' and `u' */
1116       break;
1117     }
1118     default: return luaL_error(L, "wrong number of arguments");
1119   }
1120   return 1;
1121 }
1122 
1123 int redis_math_randomseed (lua_State *L) {
1124   redisSrand48(luaL_checkint(L, 1));
1125   return 0;
1126 }
1127 
1128 /* ---------------------------------------------------------------------------
1129  * EVAL and SCRIPT commands implementation
1130  * ------------------------------------------------------------------------- */
1131 
1132 /* Define a lua function with the specified function name and body.
1133  * The function name musts be a 42 characters long string, since all the
1134  * functions we defined in the Lua context are in the form:
1135  *
1136  *   f_<hex sha1 sum>
1137  *
1138  * On success C_OK is returned, and nothing is left on the Lua stack.
1139  * On error C_ERR is returned and an appropriate error is set in the
1140  * client context. */
1141 int luaCreateFunction(client *c, lua_State *lua, char *funcname, robj *body) {
1142     sds funcdef = sdsempty();
1143 
1144     funcdef = sdscat(funcdef,"function ");
1145     funcdef = sdscatlen(funcdef,funcname,42);
1146     funcdef = sdscatlen(funcdef,"() ",3);
1147     funcdef = sdscatlen(funcdef,body->ptr,sdslen(body->ptr));
1148     funcdef = sdscatlen(funcdef,"\nend",4);
1149 
1150     if (luaL_loadbuffer(lua,funcdef,sdslen(funcdef),"@user_script")) {
1151         addReplyErrorFormat(c,"Error compiling script (new function): %s\n",
1152             lua_tostring(lua,-1));
1153         lua_pop(lua,1);
1154         sdsfree(funcdef);
1155         return C_ERR;
1156     }
1157     sdsfree(funcdef);
1158     if (lua_pcall(lua,0,0,0)) {
1159         addReplyErrorFormat(c,"Error running script (new function): %s\n",
1160             lua_tostring(lua,-1));
1161         lua_pop(lua,1);
1162         return C_ERR;
1163     }
1164 
1165     /* We also save a SHA1 -> Original script map in a dictionary
1166      * so that we can replicate / write in the AOF all the
1167      * EVALSHA commands as EVAL using the original script. */
1168     {
1169         int retval = dictAdd(server.lua_scripts,
1170                              sdsnewlen(funcname+2,40),body);
1171         serverAssertWithInfo(c,NULL,retval == DICT_OK);
1172         incrRefCount(body);
1173     }
1174     return C_OK;
1175 }
1176 
1177 /* This is the Lua script "count" hook that we use to detect scripts timeout. */
1178 void luaMaskCountHook(lua_State *lua, lua_Debug *ar) {
1179     long long elapsed;
1180     UNUSED(ar);
1181     UNUSED(lua);
1182 
1183     elapsed = mstime() - server.lua_time_start;
1184     if (elapsed >= server.lua_time_limit && server.lua_timedout == 0) {
1185         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);
1186         server.lua_timedout = 1;
1187         /* Once the script timeouts we reenter the event loop to permit others
1188          * to call SCRIPT KILL or SHUTDOWN NOSAVE if needed. For this reason
1189          * we need to mask the client executing the script from the event loop.
1190          * If we don't do that the client may disconnect and could no longer be
1191          * here when the EVAL command will return. */
1192          aeDeleteFileEvent(server.el, server.lua_caller->fd, AE_READABLE);
1193     }
1194     if (server.lua_timedout) processEventsWhileBlocked();
1195     if (server.lua_kill) {
1196         serverLog(LL_WARNING,"Lua script killed by user with SCRIPT KILL.");
1197         lua_pushstring(lua,"Script killed by user with SCRIPT KILL...");
1198         lua_error(lua);
1199     }
1200 }
1201 
1202 void evalGenericCommand(client *c, int evalsha) {
1203     lua_State *lua = server.lua;
1204     char funcname[43];
1205     long long numkeys;
1206     int delhook = 0, err;
1207 
1208     /* When we replicate whole scripts, we want the same PRNG sequence at
1209      * every call so that our PRNG is not affected by external state. */
1210     redisSrand48(0);
1211 
1212     /* We set this flag to zero to remember that so far no random command
1213      * was called. This way we can allow the user to call commands like
1214      * SRANDMEMBER or RANDOMKEY from Lua scripts as far as no write command
1215      * is called (otherwise the replication and AOF would end with non
1216      * deterministic sequences).
1217      *
1218      * Thanks to this flag we'll raise an error every time a write command
1219      * is called after a random command was used. */
1220     server.lua_random_dirty = 0;
1221     server.lua_write_dirty = 0;
1222     server.lua_replicate_commands = server.lua_always_replicate_commands;
1223     server.lua_multi_emitted = 0;
1224     server.lua_repl = PROPAGATE_AOF|PROPAGATE_REPL;
1225 
1226     /* Get the number of arguments that are keys */
1227     if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != C_OK)
1228         return;
1229     if (numkeys > (c->argc - 3)) {
1230         addReplyError(c,"Number of keys can't be greater than number of args");
1231         return;
1232     } else if (numkeys < 0) {
1233         addReplyError(c,"Number of keys can't be negative");
1234         return;
1235     }
1236 
1237     /* We obtain the script SHA1, then check if this function is already
1238      * defined into the Lua state */
1239     funcname[0] = 'f';
1240     funcname[1] = '_';
1241     if (!evalsha) {
1242         /* Hash the code if this is an EVAL call */
1243         sha1hex(funcname+2,c->argv[1]->ptr,sdslen(c->argv[1]->ptr));
1244     } else {
1245         /* We already have the SHA if it is a EVALSHA */
1246         int j;
1247         char *sha = c->argv[1]->ptr;
1248 
1249         /* Convert to lowercase. We don't use tolower since the function
1250          * managed to always show up in the profiler output consuming
1251          * a non trivial amount of time. */
1252         for (j = 0; j < 40; j++)
1253             funcname[j+2] = (sha[j] >= 'A' && sha[j] <= 'Z') ?
1254                 sha[j]+('a'-'A') : sha[j];
1255         funcname[42] = '\0';
1256     }
1257 
1258     /* Push the pcall error handler function on the stack. */
1259     lua_getglobal(lua, "__redis__err__handler");
1260 
1261     /* Try to lookup the Lua function */
1262     lua_getglobal(lua, funcname);
1263     if (lua_isnil(lua,-1)) {
1264         lua_pop(lua,1); /* remove the nil from the stack */
1265         /* Function not defined... let's define it if we have the
1266          * body of the function. If this is an EVALSHA call we can just
1267          * return an error. */
1268         if (evalsha) {
1269             lua_pop(lua,1); /* remove the error handler from the stack. */
1270             addReply(c, shared.noscripterr);
1271             return;
1272         }
1273         if (luaCreateFunction(c,lua,funcname,c->argv[1]) == C_ERR) {
1274             lua_pop(lua,1); /* remove the error handler from the stack. */
1275             /* The error is sent to the client by luaCreateFunction()
1276              * itself when it returns C_ERR. */
1277             return;
1278         }
1279         /* Now the following is guaranteed to return non nil */
1280         lua_getglobal(lua, funcname);
1281         serverAssert(!lua_isnil(lua,-1));
1282     }
1283 
1284     /* Populate the argv and keys table accordingly to the arguments that
1285      * EVAL received. */
1286     luaSetGlobalArray(lua,"KEYS",c->argv+3,numkeys);
1287     luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys);
1288 
1289     /* Select the right DB in the context of the Lua client */
1290     selectDb(server.lua_client,c->db->id);
1291 
1292     /* Set a hook in order to be able to stop the script execution if it
1293      * is running for too much time.
1294      * We set the hook only if the time limit is enabled as the hook will
1295      * make the Lua script execution slower.
1296      *
1297      * If we are debugging, we set instead a "line" hook so that the
1298      * debugger is call-back at every line executed by the script. */
1299     server.lua_caller = c;
1300     server.lua_time_start = mstime();
1301     server.lua_kill = 0;
1302     if (server.lua_time_limit > 0 && server.masterhost == NULL &&
1303         ldb.active == 0)
1304     {
1305         lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000);
1306         delhook = 1;
1307     } else if (ldb.active) {
1308         lua_sethook(server.lua,luaLdbLineHook,LUA_MASKLINE|LUA_MASKCOUNT,100000);
1309         delhook = 1;
1310     }
1311 
1312     /* At this point whether this script was never seen before or if it was
1313      * already defined, we can call it. We have zero arguments and expect
1314      * a single return value. */
1315     err = lua_pcall(lua,0,1,-2);
1316 
1317     /* Perform some cleanup that we need to do both on error and success. */
1318     if (delhook) lua_sethook(lua,NULL,0,0); /* Disable hook */
1319     if (server.lua_timedout) {
1320         server.lua_timedout = 0;
1321         /* Restore the readable handler that was unregistered when the
1322          * script timeout was detected. */
1323         aeCreateFileEvent(server.el,c->fd,AE_READABLE,
1324                           readQueryFromClient,c);
1325     }
1326     server.lua_caller = NULL;
1327 
1328     /* Call the Lua garbage collector from time to time to avoid a
1329      * full cycle performed by Lua, which adds too latency.
1330      *
1331      * The call is performed every LUA_GC_CYCLE_PERIOD executed commands
1332      * (and for LUA_GC_CYCLE_PERIOD collection steps) because calling it
1333      * for every command uses too much CPU. */
1334     #define LUA_GC_CYCLE_PERIOD 50
1335     {
1336         static long gc_count = 0;
1337 
1338         gc_count++;
1339         if (gc_count == LUA_GC_CYCLE_PERIOD) {
1340             lua_gc(lua,LUA_GCSTEP,LUA_GC_CYCLE_PERIOD);
1341             gc_count = 0;
1342         }
1343     }
1344 
1345     if (err) {
1346         addReplyErrorFormat(c,"Error running script (call to %s): %s\n",
1347             funcname, lua_tostring(lua,-1));
1348         lua_pop(lua,2); /* Consume the Lua reply and remove error handler. */
1349     } else {
1350         /* On success convert the Lua return value into Redis protocol, and
1351          * send it to * the client. */
1352         luaReplyToRedisReply(c,lua); /* Convert and consume the reply. */
1353         lua_pop(lua,1); /* Remove the error handler. */
1354     }
1355 
1356     /* If we are using single commands replication, emit EXEC if there
1357      * was at least a write. */
1358     if (server.lua_replicate_commands) {
1359         preventCommandPropagation(c);
1360         if (server.lua_multi_emitted) {
1361             robj *propargv[1];
1362             propargv[0] = createStringObject("EXEC",4);
1363             alsoPropagate(server.execCommand,c->db->id,propargv,1,
1364                 PROPAGATE_AOF|PROPAGATE_REPL);
1365             decrRefCount(propargv[0]);
1366         }
1367     }
1368 
1369     /* EVALSHA should be propagated to Slave and AOF file as full EVAL, unless
1370      * we are sure that the script was already in the context of all the
1371      * attached slaves *and* the current AOF file if enabled.
1372      *
1373      * To do so we use a cache of SHA1s of scripts that we already propagated
1374      * as full EVAL, that's called the Replication Script Cache.
1375      *
1376      * For repliation, everytime a new slave attaches to the master, we need to
1377      * flush our cache of scripts that can be replicated as EVALSHA, while
1378      * for AOF we need to do so every time we rewrite the AOF file. */
1379     if (evalsha && !server.lua_replicate_commands) {
1380         if (!replicationScriptCacheExists(c->argv[1]->ptr)) {
1381             /* This script is not in our script cache, replicate it as
1382              * EVAL, then add it into the script cache, as from now on
1383              * slaves and AOF know about it. */
1384             robj *script = dictFetchValue(server.lua_scripts,c->argv[1]->ptr);
1385 
1386             replicationScriptCacheAdd(c->argv[1]->ptr);
1387             serverAssertWithInfo(c,NULL,script != NULL);
1388             rewriteClientCommandArgument(c,0,
1389                 resetRefCount(createStringObject("EVAL",4)));
1390             rewriteClientCommandArgument(c,1,script);
1391             forceCommandPropagation(c,PROPAGATE_REPL|PROPAGATE_AOF);
1392         }
1393     }
1394 }
1395 
1396 void evalCommand(client *c) {
1397     if (!(c->flags & CLIENT_LUA_DEBUG))
1398         evalGenericCommand(c,0);
1399     else
1400         evalGenericCommandWithDebugging(c,0);
1401 }
1402 
1403 void evalShaCommand(client *c) {
1404     if (sdslen(c->argv[1]->ptr) != 40) {
1405         /* We know that a match is not possible if the provided SHA is
1406          * not the right length. So we return an error ASAP, this way
1407          * evalGenericCommand() can be implemented without string length
1408          * sanity check */
1409         addReply(c, shared.noscripterr);
1410         return;
1411     }
1412     if (!(c->flags & CLIENT_LUA_DEBUG))
1413         evalGenericCommand(c,1);
1414     else {
1415         addReplyError(c,"Please use EVAL instead of EVALSHA for debugging");
1416         return;
1417     }
1418 }
1419 
1420 void scriptCommand(client *c) {
1421     if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"flush")) {
1422         scriptingReset();
1423         addReply(c,shared.ok);
1424         replicationScriptCacheFlush();
1425         server.dirty++; /* Propagating this command is a good idea. */
1426     } else if (c->argc >= 2 && !strcasecmp(c->argv[1]->ptr,"exists")) {
1427         int j;
1428 
1429         addReplyMultiBulkLen(c, c->argc-2);
1430         for (j = 2; j < c->argc; j++) {
1431             if (dictFind(server.lua_scripts,c->argv[j]->ptr))
1432                 addReply(c,shared.cone);
1433             else
1434                 addReply(c,shared.czero);
1435         }
1436     } else if (c->argc == 3 && !strcasecmp(c->argv[1]->ptr,"load")) {
1437         char funcname[43];
1438         sds sha;
1439 
1440         funcname[0] = 'f';
1441         funcname[1] = '_';
1442         sha1hex(funcname+2,c->argv[2]->ptr,sdslen(c->argv[2]->ptr));
1443         sha = sdsnewlen(funcname+2,40);
1444         if (dictFind(server.lua_scripts,sha) == NULL) {
1445             if (luaCreateFunction(c,server.lua,funcname,c->argv[2])
1446                     == C_ERR) {
1447                 sdsfree(sha);
1448                 return;
1449             }
1450         }
1451         addReplyBulkCBuffer(c,funcname+2,40);
1452         sdsfree(sha);
1453         forceCommandPropagation(c,PROPAGATE_REPL|PROPAGATE_AOF);
1454     } else if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"kill")) {
1455         if (server.lua_caller == NULL) {
1456             addReplySds(c,sdsnew("-NOTBUSY No scripts in execution right now.\r\n"));
1457         } else if (server.lua_write_dirty) {
1458             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"));
1459         } else {
1460             server.lua_kill = 1;
1461             addReply(c,shared.ok);
1462         }
1463     } else if (c->argc == 3 && !strcasecmp(c->argv[1]->ptr,"debug")) {
1464         if (clientHasPendingReplies(c)) {
1465             addReplyError(c,"SCRIPT DEBUG must be called outside a pipeline");
1466             return;
1467         }
1468         if (!strcasecmp(c->argv[2]->ptr,"no")) {
1469             ldbDisable(c);
1470             addReply(c,shared.ok);
1471         } else if (!strcasecmp(c->argv[2]->ptr,"yes")) {
1472             ldbEnable(c);
1473             addReply(c,shared.ok);
1474         } else if (!strcasecmp(c->argv[2]->ptr,"sync")) {
1475             ldbEnable(c);
1476             addReply(c,shared.ok);
1477             c->flags |= CLIENT_LUA_DEBUG_SYNC;
1478         } else {
1479             addReplyError(c,"Use SCRIPT DEBUG yes/sync/no");
1480         }
1481     } else {
1482         addReplyError(c, "Unknown SCRIPT subcommand or wrong # of args.");
1483     }
1484 }
1485 
1486 /* ---------------------------------------------------------------------------
1487  * LDB: Redis Lua debugging facilities
1488  * ------------------------------------------------------------------------- */
1489 
1490 /* Initialize Lua debugger data structures. */
1491 void ldbInit(void) {
1492     ldb.fd = -1;
1493     ldb.active = 0;
1494     ldb.logs = listCreate();
1495     listSetFreeMethod(ldb.logs,(void (*)(void*))sdsfree);
1496     ldb.children = listCreate();
1497     ldb.src = NULL;
1498     ldb.lines = 0;
1499     ldb.cbuf = sdsempty();
1500 }
1501 
1502 /* Remove all the pending messages in the specified list. */
1503 void ldbFlushLog(list *log) {
1504     listNode *ln;
1505 
1506     while((ln = listFirst(log)) != NULL)
1507         listDelNode(log,ln);
1508 }
1509 
1510 /* Enable debug mode of Lua scripts for this client. */
1511 void ldbEnable(client *c) {
1512     c->flags |= CLIENT_LUA_DEBUG;
1513     ldbFlushLog(ldb.logs);
1514     ldb.fd = c->fd;
1515     ldb.step = 1;
1516     ldb.bpcount = 0;
1517     ldb.luabp = 0;
1518     sdsfree(ldb.cbuf);
1519     ldb.cbuf = sdsempty();
1520     ldb.maxlen = LDB_MAX_LEN_DEFAULT;
1521     ldb.maxlen_hint_sent = 0;
1522 }
1523 
1524 /* Exit debugging mode from the POV of client. This function is not enough
1525  * to properly shut down a client debugging session, see ldbEndSession()
1526  * for more information. */
1527 void ldbDisable(client *c) {
1528     c->flags &= ~(CLIENT_LUA_DEBUG|CLIENT_LUA_DEBUG_SYNC);
1529 }
1530 
1531 /* Append a log entry to the specified LDB log. */
1532 void ldbLog(sds entry) {
1533     listAddNodeTail(ldb.logs,entry);
1534 }
1535 
1536 /* A version of ldbLog() which prevents producing logs greater than
1537  * ldb.maxlen. The first time the limit is reached an hint is generated
1538  * to inform the user that reply trimming can be disabled using the
1539  * debugger "maxlen" command. */
1540 void ldbLogWithMaxLen(sds entry) {
1541     int trimmed = 0;
1542     if (ldb.maxlen && sdslen(entry) > ldb.maxlen) {
1543         sdsrange(entry,0,ldb.maxlen-1);
1544         entry = sdscatlen(entry," ...",4);
1545         trimmed = 1;
1546     }
1547     ldbLog(entry);
1548     if (trimmed && ldb.maxlen_hint_sent == 0) {
1549         ldb.maxlen_hint_sent = 1;
1550         ldbLog(sdsnew(
1551         "<hint> The above reply was trimmed. Use 'maxlen 0' to disable trimming."));
1552     }
1553 }
1554 
1555 /* Send ldb.logs to the debugging client as a multi-bulk reply
1556  * consisting of simple strings. Log entries which include newlines have them
1557  * replaced with spaces. The entries sent are also consumed. */
1558 void ldbSendLogs(void) {
1559     sds proto = sdsempty();
1560     proto = sdscatfmt(proto,"*%i\r\n", (int)listLength(ldb.logs));
1561     while(listLength(ldb.logs)) {
1562         listNode *ln = listFirst(ldb.logs);
1563         proto = sdscatlen(proto,"+",1);
1564         sdsmapchars(ln->value,"\r\n","  ",2);
1565         proto = sdscatsds(proto,ln->value);
1566         proto = sdscatlen(proto,"\r\n",2);
1567         listDelNode(ldb.logs,ln);
1568     }
1569     if (write(ldb.fd,proto,sdslen(proto)) == -1) {
1570         /* Avoid warning. We don't check the return value of write()
1571          * since the next read() will catch the I/O error and will
1572          * close the debugging session. */
1573     }
1574     sdsfree(proto);
1575 }
1576 
1577 /* Start a debugging session before calling EVAL implementation.
1578  * The techique we use is to capture the client socket file descriptor,
1579  * in order to perform direct I/O with it from within Lua hooks. This
1580  * way we don't have to re-enter Redis in order to handle I/O.
1581  *
1582  * The function returns 1 if the caller should proceed to call EVAL,
1583  * and 0 if instead the caller should abort the operation (this happens
1584  * for the parent in a forked session, since it's up to the children
1585  * to continue, or when fork returned an error).
1586  *
1587  * The caller should call ldbEndSession() only if ldbStartSession()
1588  * returned 1. */
1589 int ldbStartSession(client *c) {
1590     ldb.forked = (c->flags & CLIENT_LUA_DEBUG_SYNC) == 0;
1591     if (ldb.forked) {
1592         pid_t cp = fork();
1593         if (cp == -1) {
1594             addReplyError(c,"Fork() failed: can't run EVAL in debugging mode.");
1595             return 0;
1596         } else if (cp == 0) {
1597             /* Child. Let's ignore important signals handled by the parent. */
1598             struct sigaction act;
1599             sigemptyset(&act.sa_mask);
1600             act.sa_flags = 0;
1601             act.sa_handler = SIG_IGN;
1602             sigaction(SIGTERM, &act, NULL);
1603             sigaction(SIGINT, &act, NULL);
1604 
1605             /* Log the creation of the child and close the listening
1606              * socket to make sure if the parent crashes a reset is sent
1607              * to the clients. */
1608             serverLog(LL_WARNING,"Redis forked for debugging eval");
1609             closeListeningSockets(0);
1610         } else {
1611             /* Parent */
1612             listAddNodeTail(ldb.children,(void*)(unsigned long)cp);
1613             freeClientAsync(c); /* Close the client in the parent side. */
1614             return 0;
1615         }
1616     } else {
1617         serverLog(LL_WARNING,
1618             "Redis synchronous debugging eval session started");
1619     }
1620 
1621     /* Setup our debugging session. */
1622     anetBlock(NULL,ldb.fd);
1623     anetSendTimeout(NULL,ldb.fd,5000);
1624     ldb.active = 1;
1625 
1626     /* First argument of EVAL is the script itself. We split it into different
1627      * lines since this is the way the debugger accesses the source code. */
1628     sds srcstring = sdsdup(c->argv[1]->ptr);
1629     size_t srclen = sdslen(srcstring);
1630     while(srclen && (srcstring[srclen-1] == '\n' ||
1631                      srcstring[srclen-1] == '\r'))
1632     {
1633         srcstring[--srclen] = '\0';
1634     }
1635     sdssetlen(srcstring,srclen);
1636     ldb.src = sdssplitlen(srcstring,sdslen(srcstring),"\n",1,&ldb.lines);
1637     sdsfree(srcstring);
1638     return 1;
1639 }
1640 
1641 /* End a debugging session after the EVAL call with debugging enabled
1642  * returned. */
1643 void ldbEndSession(client *c) {
1644     /* Emit the remaining logs and an <endsession> mark. */
1645     ldbLog(sdsnew("<endsession>"));
1646     ldbSendLogs();
1647 
1648     /* If it's a fork()ed session, we just exit. */
1649     if (ldb.forked) {
1650         writeToClient(c->fd, c, 0);
1651         serverLog(LL_WARNING,"Lua debugging session child exiting");
1652         exitFromChild(0);
1653     } else {
1654         serverLog(LL_WARNING,
1655             "Redis synchronous debugging eval session ended");
1656     }
1657 
1658     /* Otherwise let's restore client's state. */
1659     anetNonBlock(NULL,ldb.fd);
1660     anetSendTimeout(NULL,ldb.fd,0);
1661 
1662     /* Close the client connectin after sending the final EVAL reply
1663      * in order to signal the end of the debugging session. */
1664     c->flags |= CLIENT_CLOSE_AFTER_REPLY;
1665 
1666     /* Cleanup. */
1667     sdsfreesplitres(ldb.src,ldb.lines);
1668     ldb.lines = 0;
1669     ldb.active = 0;
1670 }
1671 
1672 /* If the specified pid is among the list of children spawned for
1673  * forked debugging sessions, it is removed from the children list.
1674  * If the pid was found non-zero is returned. */
1675 int ldbRemoveChild(pid_t pid) {
1676     listNode *ln = listSearchKey(ldb.children,(void*)(unsigned long)pid);
1677     if (ln) {
1678         listDelNode(ldb.children,ln);
1679         return 1;
1680     }
1681     return 0;
1682 }
1683 
1684 /* Return the number of children we still did not received termination
1685  * acknowledge via wait() in the parent process. */
1686 int ldbPendingChildren(void) {
1687     return listLength(ldb.children);
1688 }
1689 
1690 /* Kill all the forked sessions. */
1691 void ldbKillForkedSessions(void) {
1692     listIter li;
1693     listNode *ln;
1694 
1695     listRewind(ldb.children,&li);
1696     while((ln = listNext(&li))) {
1697         pid_t pid = (unsigned long) ln->value;
1698         serverLog(LL_WARNING,"Killing debugging session %ld",(long)pid);
1699         kill(pid,SIGKILL);
1700     }
1701     listRelease(ldb.children);
1702     ldb.children = listCreate();
1703 }
1704 
1705 /* Wrapper for EVAL / EVALSHA that enables debugging, and makes sure
1706  * that when EVAL returns, whatever happened, the session is ended. */
1707 void evalGenericCommandWithDebugging(client *c, int evalsha) {
1708     if (ldbStartSession(c)) {
1709         evalGenericCommand(c,evalsha);
1710         ldbEndSession(c);
1711     } else {
1712         ldbDisable(c);
1713     }
1714 }
1715 
1716 /* Return a pointer to ldb.src source code line, considering line to be
1717  * one-based, and returning a special string for out of range lines. */
1718 char *ldbGetSourceLine(int line) {
1719     int idx = line-1;
1720     if (idx < 0 || idx >= ldb.lines) return "<out of range source code line>";
1721     return ldb.src[idx];
1722 }
1723 
1724 /* Return true if there is a breakpoint in the specified line. */
1725 int ldbIsBreakpoint(int line) {
1726     int j;
1727 
1728     for (j = 0; j < ldb.bpcount; j++)
1729         if (ldb.bp[j] == line) return 1;
1730     return 0;
1731 }
1732 
1733 /* Add the specified breakpoint. Ignore it if we already reached the max.
1734  * Returns 1 if the breakpoint was added (or was already set). 0 if there is
1735  * no space for the breakpoint or if the line is invalid. */
1736 int ldbAddBreakpoint(int line) {
1737     if (line <= 0 || line > ldb.lines) return 0;
1738     if (!ldbIsBreakpoint(line) && ldb.bpcount != LDB_BREAKPOINTS_MAX) {
1739         ldb.bp[ldb.bpcount++] = line;
1740         return 1;
1741     }
1742     return 0;
1743 }
1744 
1745 /* Remove the specified breakpoint, returning 1 if the operation was
1746  * performed or 0 if there was no such breakpoint. */
1747 int ldbDelBreakpoint(int line) {
1748     int j;
1749 
1750     for (j = 0; j < ldb.bpcount; j++) {
1751         if (ldb.bp[j] == line) {
1752             ldb.bpcount--;
1753             memmove(ldb.bp+j,ldb.bp+j+1,ldb.bpcount-j);
1754             return 1;
1755         }
1756     }
1757     return 0;
1758 }
1759 
1760 /* Expect a valid multi-bulk command in the debugging client query buffer.
1761  * On success the command is parsed and returned as an array of SDS strings,
1762  * otherwise NULL is returned and there is to read more buffer. */
1763 sds *ldbReplParseCommand(int *argcp) {
1764     sds *argv = NULL;
1765     int argc = 0;
1766     if (sdslen(ldb.cbuf) == 0) return NULL;
1767 
1768     /* Working on a copy is simpler in this case. We can modify it freely
1769      * for the sake of simpler parsing. */
1770     sds copy = sdsdup(ldb.cbuf);
1771     char *p = copy;
1772 
1773     /* This Redis protocol parser is a joke... just the simplest thing that
1774      * works in this context. It is also very forgiving regarding broken
1775      * protocol. */
1776 
1777     /* Seek and parse *<count>\r\n. */
1778     p = strchr(p,'*'); if (!p) goto protoerr;
1779     char *plen = p+1; /* Multi bulk len pointer. */
1780     p = strstr(p,"\r\n"); if (!p) goto protoerr;
1781     *p = '\0'; p += 2;
1782     *argcp = atoi(plen);
1783     if (*argcp <= 0 || *argcp > 1024) goto protoerr;
1784 
1785     /* Parse each argument. */
1786     argv = zmalloc(sizeof(sds)*(*argcp));
1787     argc = 0;
1788     while(argc < *argcp) {
1789         if (*p != '$') goto protoerr;
1790         plen = p+1; /* Bulk string len pointer. */
1791         p = strstr(p,"\r\n"); if (!p) goto protoerr;
1792         *p = '\0'; p += 2;
1793         int slen = atoi(plen); /* Length of this arg. */
1794         if (slen <= 0 || slen > 1024) goto protoerr;
1795         argv[argc++] = sdsnewlen(p,slen);
1796         p += slen; /* Skip the already parsed argument. */
1797         if (p[0] != '\r' || p[1] != '\n') goto protoerr;
1798         p += 2; /* Skip \r\n. */
1799     }
1800     sdsfree(copy);
1801     return argv;
1802 
1803 protoerr:
1804     sdsfreesplitres(argv,argc);
1805     sdsfree(copy);
1806     return NULL;
1807 }
1808 
1809 /* Log the specified line in the Lua debugger output. */
1810 void ldbLogSourceLine(int lnum) {
1811     char *line = ldbGetSourceLine(lnum);
1812     char *prefix;
1813     int bp = ldbIsBreakpoint(lnum);
1814     int current = ldb.currentline == lnum;
1815 
1816     if (current && bp)
1817         prefix = "->#";
1818     else if (current)
1819         prefix = "-> ";
1820     else if (bp)
1821         prefix = "  #";
1822     else
1823         prefix = "   ";
1824     sds thisline = sdscatprintf(sdsempty(),"%s%-3d %s", prefix, lnum, line);
1825     ldbLog(thisline);
1826 }
1827 
1828 /* Implement the "list" command of the Lua debugger. If around is 0
1829  * the whole file is listed, otherwise only a small portion of the file
1830  * around the specified line is shown. When a line number is specified
1831  * the amonut of context (lines before/after) is specified via the
1832  * 'context' argument. */
1833 void ldbList(int around, int context) {
1834     int j;
1835 
1836     for (j = 1; j <= ldb.lines; j++) {
1837         if (around != 0 && abs(around-j) > context) continue;
1838         ldbLogSourceLine(j);
1839     }
1840 }
1841 
1842 /* Append an human readable representation of the Lua value at position 'idx'
1843  * on the stack of the 'lua' state, to the SDS string passed as argument.
1844  * The new SDS string with the represented value attached is returned.
1845  * Used in order to implement ldbLogStackValue().
1846  *
1847  * The element is not automatically removed from the stack, nor it is
1848  * converted to a different type. */
1849 #define LDB_MAX_VALUES_DEPTH (LUA_MINSTACK/2)
1850 sds ldbCatStackValueRec(sds s, lua_State *lua, int idx, int level) {
1851     int t = lua_type(lua,idx);
1852 
1853     if (level++ == LDB_MAX_VALUES_DEPTH)
1854         return sdscat(s,"<max recursion level reached! Nested table?>");
1855 
1856     switch(t) {
1857     case LUA_TSTRING:
1858         {
1859         size_t strl;
1860         char *strp = (char*)lua_tolstring(lua,idx,&strl);
1861         s = sdscatrepr(s,strp,strl);
1862         }
1863         break;
1864     case LUA_TBOOLEAN:
1865         s = sdscat(s,lua_toboolean(lua,idx) ? "true" : "false");
1866         break;
1867     case LUA_TNUMBER:
1868         s = sdscatprintf(s,"%g",(double)lua_tonumber(lua,idx));
1869         break;
1870     case LUA_TNIL:
1871         s = sdscatlen(s,"nil",3);
1872         break;
1873     case LUA_TTABLE:
1874         {
1875         int expected_index = 1; /* First index we expect in an array. */
1876         int is_array = 1; /* Will be set to null if check fails. */
1877         /* Note: we create two representations at the same time, one
1878          * assuming the table is an array, one assuming it is not. At the
1879          * end we know what is true and select the right one. */
1880         sds repr1 = sdsempty();
1881         sds repr2 = sdsempty();
1882         lua_pushnil(lua); /* The first key to start the iteration is nil. */
1883         while (lua_next(lua,idx-1)) {
1884             /* Test if so far the table looks like an array. */
1885             if (is_array &&
1886                 (lua_type(lua,-2) != LUA_TNUMBER ||
1887                  lua_tonumber(lua,-2) != expected_index)) is_array = 0;
1888             /* Stack now: table, key, value */
1889             /* Array repr. */
1890             repr1 = ldbCatStackValueRec(repr1,lua,-1,level);
1891             repr1 = sdscatlen(repr1,"; ",2);
1892             /* Full repr. */
1893             repr2 = sdscatlen(repr2,"[",1);
1894             repr2 = ldbCatStackValueRec(repr2,lua,-2,level);
1895             repr2 = sdscatlen(repr2,"]=",2);
1896             repr2 = ldbCatStackValueRec(repr2,lua,-1,level);
1897             repr2 = sdscatlen(repr2,"; ",2);
1898             lua_pop(lua,1); /* Stack: table, key. Ready for next iteration. */
1899             expected_index++;
1900         }
1901         /* Strip the last " ;" from both the representations. */
1902         if (sdslen(repr1)) sdsrange(repr1,0,-3);
1903         if (sdslen(repr2)) sdsrange(repr2,0,-3);
1904         /* Select the right one and discard the other. */
1905         s = sdscatlen(s,"{",1);
1906         s = sdscatsds(s,is_array ? repr1 : repr2);
1907         s = sdscatlen(s,"}",1);
1908         sdsfree(repr1);
1909         sdsfree(repr2);
1910         }
1911         break;
1912     case LUA_TFUNCTION:
1913     case LUA_TUSERDATA:
1914     case LUA_TTHREAD:
1915     case LUA_TLIGHTUSERDATA:
1916         {
1917         const void *p = lua_topointer(lua,idx);
1918         char *typename = "unknown";
1919         if (t == LUA_TFUNCTION) typename = "function";
1920         else if (t == LUA_TUSERDATA) typename = "userdata";
1921         else if (t == LUA_TTHREAD) typename = "thread";
1922         else if (t == LUA_TLIGHTUSERDATA) typename = "light-userdata";
1923         s = sdscatprintf(s,"\"%s@%p\"",typename,p);
1924         }
1925         break;
1926     default:
1927         s = sdscat(s,"\"<unknown-lua-type>\"");
1928         break;
1929     }
1930     return s;
1931 }
1932 
1933 /* Higher level wrapper for ldbCatStackValueRec() that just uses an initial
1934  * recursion level of '0'. */
1935 sds ldbCatStackValue(sds s, lua_State *lua, int idx) {
1936     return ldbCatStackValueRec(s,lua,idx,0);
1937 }
1938 
1939 /* Produce a debugger log entry representing the value of the Lua object
1940  * currently on the top of the stack. The element is ot popped nor modified.
1941  * Check ldbCatStackValue() for the actual implementation. */
1942 void ldbLogStackValue(lua_State *lua, char *prefix) {
1943     sds s = sdsnew(prefix);
1944     s = ldbCatStackValue(s,lua,-1);
1945     ldbLogWithMaxLen(s);
1946 }
1947 
1948 char *ldbRedisProtocolToHuman_Int(sds *o, char *reply);
1949 char *ldbRedisProtocolToHuman_Bulk(sds *o, char *reply);
1950 char *ldbRedisProtocolToHuman_Status(sds *o, char *reply);
1951 char *ldbRedisProtocolToHuman_MultiBulk(sds *o, char *reply);
1952 
1953 /* Get Redis protocol from 'reply' and appends it in human readable form to
1954  * the passed SDS string 'o'.
1955  *
1956  * Note that the SDS string is passed by reference (pointer of pointer to
1957  * char*) so that we can return a modified pointer, as for SDS semantics. */
1958 char *ldbRedisProtocolToHuman(sds *o, char *reply) {
1959     char *p = reply;
1960     switch(*p) {
1961     case ':': p = ldbRedisProtocolToHuman_Int(o,reply); break;
1962     case '$': p = ldbRedisProtocolToHuman_Bulk(o,reply); break;
1963     case '+': p = ldbRedisProtocolToHuman_Status(o,reply); break;
1964     case '-': p = ldbRedisProtocolToHuman_Status(o,reply); break;
1965     case '*': p = ldbRedisProtocolToHuman_MultiBulk(o,reply); break;
1966     }
1967     return p;
1968 }
1969 
1970 /* The following functions are helpers for ldbRedisProtocolToHuman(), each
1971  * take care of a given Redis return type. */
1972 
1973 char *ldbRedisProtocolToHuman_Int(sds *o, char *reply) {
1974     char *p = strchr(reply+1,'\r');
1975     *o = sdscatlen(*o,reply+1,p-reply-1);
1976     return p+2;
1977 }
1978 
1979 char *ldbRedisProtocolToHuman_Bulk(sds *o, char *reply) {
1980     char *p = strchr(reply+1,'\r');
1981     long long bulklen;
1982 
1983     string2ll(reply+1,p-reply-1,&bulklen);
1984     if (bulklen == -1) {
1985         *o = sdscatlen(*o,"NULL",4);
1986         return p+2;
1987     } else {
1988         *o = sdscatrepr(*o,p+2,bulklen);
1989         return p+2+bulklen+2;
1990     }
1991 }
1992 
1993 char *ldbRedisProtocolToHuman_Status(sds *o, char *reply) {
1994     char *p = strchr(reply+1,'\r');
1995 
1996     *o = sdscatrepr(*o,reply,p-reply);
1997     return p+2;
1998 }
1999 
2000 char *ldbRedisProtocolToHuman_MultiBulk(sds *o, char *reply) {
2001     char *p = strchr(reply+1,'\r');
2002     long long mbulklen;
2003     int j = 0;
2004 
2005     string2ll(reply+1,p-reply-1,&mbulklen);
2006     p += 2;
2007     if (mbulklen == -1) {
2008         *o = sdscatlen(*o,"NULL",4);
2009         return p;
2010     }
2011     *o = sdscatlen(*o,"[",1);
2012     for (j = 0; j < mbulklen; j++) {
2013         p = ldbRedisProtocolToHuman(o,p);
2014         if (j != mbulklen-1) *o = sdscatlen(*o,",",1);
2015     }
2016     *o = sdscatlen(*o,"]",1);
2017     return p;
2018 }
2019 
2020 /* Log a Redis reply as debugger output, in an human readable format.
2021  * If the resulting string is longer than 'len' plus a few more chars
2022  * used as prefix, it gets truncated. */
2023 void ldbLogRedisReply(char *reply) {
2024     sds log = sdsnew("<reply> ");
2025     ldbRedisProtocolToHuman(&log,reply);
2026     ldbLogWithMaxLen(log);
2027 }
2028 
2029 /* Implements the "print <var>" command of the Lua debugger. It scans for Lua
2030  * var "varname" starting from the current stack frame up to the top stack
2031  * frame. The first matching variable is printed. */
2032 void ldbPrint(lua_State *lua, char *varname) {
2033     lua_Debug ar;
2034 
2035     int l = 0; /* Stack level. */
2036     while (lua_getstack(lua,l,&ar) != 0) {
2037         l++;
2038         const char *name;
2039         int i = 1; /* Variable index. */
2040         while((name = lua_getlocal(lua,&ar,i)) != NULL) {
2041             i++;
2042             if (strcmp(varname,name) == 0) {
2043                 ldbLogStackValue(lua,"<value> ");
2044                 lua_pop(lua,1);
2045                 return;
2046             } else {
2047                 lua_pop(lua,1); /* Discard the var name on the stack. */
2048             }
2049         }
2050     }
2051 
2052     /* Let's try with global vars in two selected cases */
2053     if (!strcmp(varname,"ARGV") || !strcmp(varname,"KEYS")) {
2054         lua_getglobal(lua, varname);
2055         ldbLogStackValue(lua,"<value> ");
2056         lua_pop(lua,1);
2057     } else {
2058         ldbLog(sdsnew("No such variable."));
2059     }
2060 }
2061 
2062 /* Implements the "print" command (without arguments) of the Lua debugger.
2063  * Prints all the variables in the current stack frame. */
2064 void ldbPrintAll(lua_State *lua) {
2065     lua_Debug ar;
2066     int vars = 0;
2067 
2068     if (lua_getstack(lua,0,&ar) != 0) {
2069         const char *name;
2070         int i = 1; /* Variable index. */
2071         while((name = lua_getlocal(lua,&ar,i)) != NULL) {
2072             i++;
2073             if (!strstr(name,"(*temporary)")) {
2074                 sds prefix = sdscatprintf(sdsempty(),"<value> %s = ",name);
2075                 ldbLogStackValue(lua,prefix);
2076                 sdsfree(prefix);
2077                 vars++;
2078             }
2079             lua_pop(lua,1);
2080         }
2081     }
2082 
2083     if (vars == 0) {
2084         ldbLog(sdsnew("No local variables in the current context."));
2085     }
2086 }
2087 
2088 /* Implements the break command to list, add and remove breakpoints. */
2089 void ldbBreak(sds *argv, int argc) {
2090     if (argc == 1) {
2091         if (ldb.bpcount == 0) {
2092             ldbLog(sdsnew("No breakpoints set. Use 'b <line>' to add one."));
2093             return;
2094         } else {
2095             ldbLog(sdscatfmt(sdsempty(),"%i breakpoints set:",ldb.bpcount));
2096             int j;
2097             for (j = 0; j < ldb.bpcount; j++)
2098                 ldbLogSourceLine(ldb.bp[j]);
2099         }
2100     } else {
2101         int j;
2102         for (j = 1; j < argc; j++) {
2103             char *arg = argv[j];
2104             long line;
2105             if (!string2l(arg,sdslen(arg),&line)) {
2106                 ldbLog(sdscatfmt(sdsempty(),"Invalid argument:'%s'",arg));
2107             } else {
2108                 if (line == 0) {
2109                     ldb.bpcount = 0;
2110                     ldbLog(sdsnew("All breakpoints removed."));
2111                 } else if (line > 0) {
2112                     if (ldb.bpcount == LDB_BREAKPOINTS_MAX) {
2113                         ldbLog(sdsnew("Too many breakpoints set."));
2114                     } else if (ldbAddBreakpoint(line)) {
2115                         ldbList(line,1);
2116                     } else {
2117                         ldbLog(sdsnew("Wrong line number."));
2118                     }
2119                 } else if (line < 0) {
2120                     if (ldbDelBreakpoint(-line))
2121                         ldbLog(sdsnew("Breakpoint removed."));
2122                     else
2123                         ldbLog(sdsnew("No breakpoint in the specified line."));
2124                 }
2125             }
2126         }
2127     }
2128 }
2129 
2130 /* Implements the Lua debugger "eval" command. It just compiles the user
2131  * passed fragment of code and executes it, showing the result left on
2132  * the stack. */
2133 void ldbEval(lua_State *lua, sds *argv, int argc) {
2134     /* Glue the script together if it is composed of multiple arguments. */
2135     sds code = sdsjoinsds(argv+1,argc-1," ",1);
2136     sds expr = sdscatsds(sdsnew("return "),code);
2137 
2138     /* Try to compile it as an expression, prepending "return ". */
2139     if (luaL_loadbuffer(lua,expr,sdslen(expr),"@ldb_eval")) {
2140         lua_pop(lua,1);
2141         /* Failed? Try as a statement. */
2142         if (luaL_loadbuffer(lua,code,sdslen(code),"@ldb_eval")) {
2143             ldbLog(sdscatfmt(sdsempty(),"<error> %s",lua_tostring(lua,-1)));
2144             lua_pop(lua,1);
2145             sdsfree(code);
2146             return;
2147         }
2148     }
2149 
2150     /* Call it. */
2151     sdsfree(code);
2152     sdsfree(expr);
2153     if (lua_pcall(lua,0,1,0)) {
2154         ldbLog(sdscatfmt(sdsempty(),"<error> %s",lua_tostring(lua,-1)));
2155         lua_pop(lua,1);
2156         return;
2157     }
2158     ldbLogStackValue(lua,"<retval> ");
2159     lua_pop(lua,1);
2160 }
2161 
2162 /* Implement the debugger "redis" command. We use a trick in order to make
2163  * the implementation very simple: we just call the Lua redis.call() command
2164  * implementation, with ldb.step enabled, so as a side effect the Redis command
2165  * and its reply are logged. */
2166 void ldbRedis(lua_State *lua, sds *argv, int argc) {
2167     int j, saved_rc = server.lua_replicate_commands;
2168 
2169     lua_getglobal(lua,"redis");
2170     lua_pushstring(lua,"call");
2171     lua_gettable(lua,-2);       /* Stack: redis, redis.call */
2172     for (j = 1; j < argc; j++)
2173         lua_pushlstring(lua,argv[j],sdslen(argv[j]));
2174     ldb.step = 1;               /* Force redis.call() to log. */
2175     server.lua_replicate_commands = 1;
2176     lua_pcall(lua,argc-1,1,0);  /* Stack: redis, result */
2177     ldb.step = 0;               /* Disable logging. */
2178     server.lua_replicate_commands = saved_rc;
2179     lua_pop(lua,2);             /* Discard the result and clean the stack. */
2180 }
2181 
2182 /* Implements "trace" command of the Lua debugger. It just prints a backtrace
2183  * querying Lua starting from the current callframe back to the outer one. */
2184 void ldbTrace(lua_State *lua) {
2185     lua_Debug ar;
2186     int level = 0;
2187 
2188     while(lua_getstack(lua,level,&ar)) {
2189         lua_getinfo(lua,"Snl",&ar);
2190         if(strstr(ar.short_src,"user_script") != NULL) {
2191             ldbLog(sdscatprintf(sdsempty(),"%s %s:",
2192                 (level == 0) ? "In" : "From",
2193                 ar.name ? ar.name : "top level"));
2194             ldbLogSourceLine(ar.currentline);
2195         }
2196         level++;
2197     }
2198     if (level == 0) {
2199         ldbLog(sdsnew("<error> Can't retrieve Lua stack."));
2200     }
2201 }
2202 
2203 /* Impleemnts the debugger "maxlen" command. It just queries or sets the
2204  * ldb.maxlen variable. */
2205 void ldbMaxlen(sds *argv, int argc) {
2206     if (argc == 2) {
2207         int newval = atoi(argv[1]);
2208         ldb.maxlen_hint_sent = 1; /* User knows about this command. */
2209         if (newval != 0 && newval <= 60) newval = 60;
2210         ldb.maxlen = newval;
2211     }
2212     if (ldb.maxlen) {
2213         ldbLog(sdscatprintf(sdsempty(),"<value> replies are truncated at %d bytes.",(int)ldb.maxlen));
2214     } else {
2215         ldbLog(sdscatprintf(sdsempty(),"<value> replies are unlimited."));
2216     }
2217 }
2218 
2219 /* Read debugging commands from client.
2220  * Return C_OK if the debugging session is continuing, otherwise
2221  * C_ERR if the client closed the connection or is timing out. */
2222 int ldbRepl(lua_State *lua) {
2223     sds *argv;
2224     int argc;
2225 
2226     /* We continue processing commands until a command that should return
2227      * to the Lua interpreter is found. */
2228     while(1) {
2229         while((argv = ldbReplParseCommand(&argc)) == NULL) {
2230             char buf[1024];
2231             int nread = read(ldb.fd,buf,sizeof(buf));
2232             if (nread <= 0) {
2233                 /* Make sure the script runs without user input since the
2234                  * client is no longer connected. */
2235                 ldb.step = 0;
2236                 ldb.bpcount = 0;
2237                 return C_ERR;
2238             }
2239             ldb.cbuf = sdscatlen(ldb.cbuf,buf,nread);
2240         }
2241 
2242         /* Flush the old buffer. */
2243         sdsfree(ldb.cbuf);
2244         ldb.cbuf = sdsempty();
2245 
2246         /* Execute the command. */
2247         if (!strcasecmp(argv[0],"h") || !strcasecmp(argv[0],"help")) {
2248 ldbLog(sdsnew("Redis Lua debugger help:"));
2249 ldbLog(sdsnew("[h]elp               Show this help."));
2250 ldbLog(sdsnew("[s]tep               Run current line and stop again."));
2251 ldbLog(sdsnew("[n]ext               Alias for step."));
2252 ldbLog(sdsnew("[c]continue          Run till next breakpoint."));
2253 ldbLog(sdsnew("[l]list              List source code around current line."));
2254 ldbLog(sdsnew("[l]list [line]       List source code around [line]."));
2255 ldbLog(sdsnew("                     line = 0 means: current position."));
2256 ldbLog(sdsnew("[l]list [line] [ctx] In this form [ctx] specifies how many lines"));
2257 ldbLog(sdsnew("                     to show before/after [line]."));
2258 ldbLog(sdsnew("[w]hole              List all source code. Alias for 'list 1 1000000'."));
2259 ldbLog(sdsnew("[p]rint              Show all the local variables."));
2260 ldbLog(sdsnew("[p]rint <var>        Show the value of the specified variable."));
2261 ldbLog(sdsnew("                     Can also show global vars KEYS and ARGV."));
2262 ldbLog(sdsnew("[b]reak              Show all breakpoints."));
2263 ldbLog(sdsnew("[b]reak <line>       Add a breakpoint to the specified line."));
2264 ldbLog(sdsnew("[b]reak -<line>      Remove breakpoint from the specified line."));
2265 ldbLog(sdsnew("[b]reak 0            Remove all breakpoints."));
2266 ldbLog(sdsnew("[t]race              Show a backtrace."));
2267 ldbLog(sdsnew("[e]eval <code>       Execute some Lua code (in a different callframe)."));
2268 ldbLog(sdsnew("[r]edis <cmd>        Execute a Redis command."));
2269 ldbLog(sdsnew("[m]axlen [len]       Trim logged Redis replies and Lua var dumps to len."));
2270 ldbLog(sdsnew("                     Specifying zero as <len> means unlimited."));
2271 ldbLog(sdsnew("[a]abort             Stop the execution of the script. In sync"));
2272 ldbLog(sdsnew("                     mode dataset changes will be retained."));
2273 ldbLog(sdsnew(""));
2274 ldbLog(sdsnew("Debugger functions you can call from Lua scripts:"));
2275 ldbLog(sdsnew("redis.debug()        Produce logs in the debugger console."));
2276 ldbLog(sdsnew("redis.breakpoint()   Stop execution like if there was a breakpoing."));
2277 ldbLog(sdsnew("                     in the next line of code."));
2278             ldbSendLogs();
2279         } else if (!strcasecmp(argv[0],"s") || !strcasecmp(argv[0],"step") ||
2280                    !strcasecmp(argv[0],"n") || !strcasecmp(argv[0],"next")) {
2281             ldb.step = 1;
2282             break;
2283         } else if (!strcasecmp(argv[0],"c") || !strcasecmp(argv[0],"continue")){
2284             break;
2285         } else if (!strcasecmp(argv[0],"t") || !strcasecmp(argv[0],"trace")) {
2286             ldbTrace(lua);
2287             ldbSendLogs();
2288         } else if (!strcasecmp(argv[0],"m") || !strcasecmp(argv[0],"maxlen")) {
2289             ldbMaxlen(argv,argc);
2290             ldbSendLogs();
2291         } else if (!strcasecmp(argv[0],"b") || !strcasecmp(argv[0],"break")) {
2292             ldbBreak(argv,argc);
2293             ldbSendLogs();
2294         } else if (!strcasecmp(argv[0],"e") || !strcasecmp(argv[0],"eval")) {
2295             ldbEval(lua,argv,argc);
2296             ldbSendLogs();
2297         } else if (!strcasecmp(argv[0],"a") || !strcasecmp(argv[0],"abort")) {
2298             lua_pushstring(lua, "script aborted for user request");
2299             lua_error(lua);
2300         } else if (argc > 1 &&
2301                    (!strcasecmp(argv[0],"r") || !strcasecmp(argv[0],"redis"))) {
2302             ldbRedis(lua,argv,argc);
2303             ldbSendLogs();
2304         } else if ((!strcasecmp(argv[0],"p") || !strcasecmp(argv[0],"print"))) {
2305             if (argc == 2)
2306                 ldbPrint(lua,argv[1]);
2307             else
2308                 ldbPrintAll(lua);
2309             ldbSendLogs();
2310         } else if (!strcasecmp(argv[0],"l") || !strcasecmp(argv[0],"list")){
2311             int around = ldb.currentline, ctx = 5;
2312             if (argc > 1) {
2313                 int num = atoi(argv[1]);
2314                 if (num > 0) around = num;
2315             }
2316             if (argc > 2) ctx = atoi(argv[2]);
2317             ldbList(around,ctx);
2318             ldbSendLogs();
2319         } else if (!strcasecmp(argv[0],"w") || !strcasecmp(argv[0],"whole")){
2320             ldbList(1,1000000);
2321             ldbSendLogs();
2322         } else {
2323             ldbLog(sdsnew("<error> Unknown Redis Lua debugger command or "
2324                           "wrong number of arguments."));
2325             ldbSendLogs();
2326         }
2327 
2328         /* Free the command vector. */
2329         sdsfreesplitres(argv,argc);
2330     }
2331 
2332     /* Free the current command argv if we break inside the while loop. */
2333     sdsfreesplitres(argv,argc);
2334     return C_OK;
2335 }
2336 
2337 /* This is the core of our Lua debugger, called each time Lua is about
2338  * to start executing a new line. */
2339 void luaLdbLineHook(lua_State *lua, lua_Debug *ar) {
2340     lua_getstack(lua,0,ar);
2341     lua_getinfo(lua,"Sl",ar);
2342     ldb.currentline = ar->currentline;
2343 
2344     int bp = ldbIsBreakpoint(ldb.currentline) || ldb.luabp;
2345     int timeout = 0;
2346 
2347     /* Events outside our script are not interesting. */
2348     if(strstr(ar->short_src,"user_script") == NULL) return;
2349 
2350     /* Check if a timeout occurred. */
2351     if (ar->event == LUA_HOOKCOUNT && ldb.step == 0 && bp == 0) {
2352         mstime_t elapsed = mstime() - server.lua_time_start;
2353         mstime_t timelimit = server.lua_time_limit ?
2354                              server.lua_time_limit : 5000;
2355         if (elapsed >= timelimit) {
2356             timeout = 1;
2357             ldb.step = 1;
2358         } else {
2359             return; /* No timeout, ignore the COUNT event. */
2360         }
2361     }
2362 
2363     if (ldb.step || bp) {
2364         char *reason = "step over";
2365         if (bp) reason = ldb.luabp ? "redis.breakpoint() called" :
2366                                      "break point";
2367         else if (timeout) reason = "timeout reached, infinite loop?";
2368         ldb.step = 0;
2369         ldb.luabp = 0;
2370         ldbLog(sdscatprintf(sdsempty(),
2371             "* Stopped at %d, stop reason = %s",
2372             ldb.currentline, reason));
2373         ldbLogSourceLine(ldb.currentline);
2374         ldbSendLogs();
2375         if (ldbRepl(lua) == C_ERR && timeout) {
2376             /* If the client closed the connection and we have a timeout
2377              * connection, let's kill the script otherwise the process
2378              * will remain blocked indefinitely. */
2379             lua_pushstring(lua, "timeout during Lua debugging with client closing connection");
2380             lua_error(lua);
2381         }
2382         server.lua_time_start = mstime();
2383     }
2384 }
2385 
2386