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