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 "redis.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 sha1hex(char *digest, char *script, size_t len); 49 50 /* Take a Redis reply in the Redis protocol format and convert it into a 51 * Lua type. Thanks to this function, and the introduction of not connected 52 * clients, it is trivial to implement the redis() lua function. 53 * 54 * Basically we take the arguments, execute the Redis command in the context 55 * of a non connected client, then take the generated reply and convert it 56 * into a suitable Lua type. With this trick the scripting feature does not 57 * need the introduction of a full Redis internals API. Basically the script 58 * is like a normal client that bypasses all the slow I/O paths. 59 * 60 * Note: in this function we do not do any sanity check as the reply is 61 * generated by Redis directly. This allows us to go faster. 62 * The reply string can be altered during the parsing as it is discarded 63 * after the conversion is completed. 64 * 65 * Errors are returned as a table with a single 'err' field set to the 66 * error string. 67 */ 68 69 char *redisProtocolToLuaType(lua_State *lua, char* reply) { 70 char *p = reply; 71 72 switch(*p) { 73 case ':': 74 p = redisProtocolToLuaType_Int(lua,reply); 75 break; 76 case '$': 77 p = redisProtocolToLuaType_Bulk(lua,reply); 78 break; 79 case '+': 80 p = redisProtocolToLuaType_Status(lua,reply); 81 break; 82 case '-': 83 p = redisProtocolToLuaType_Error(lua,reply); 84 break; 85 case '*': 86 p = redisProtocolToLuaType_MultiBulk(lua,reply); 87 break; 88 } 89 return p; 90 } 91 92 char *redisProtocolToLuaType_Int(lua_State *lua, char *reply) { 93 char *p = strchr(reply+1,'\r'); 94 long long value; 95 96 string2ll(reply+1,p-reply-1,&value); 97 lua_pushnumber(lua,(lua_Number)value); 98 return p+2; 99 } 100 101 char *redisProtocolToLuaType_Bulk(lua_State *lua, char *reply) { 102 char *p = strchr(reply+1,'\r'); 103 long long bulklen; 104 105 string2ll(reply+1,p-reply-1,&bulklen); 106 if (bulklen == -1) { 107 lua_pushboolean(lua,0); 108 return p+2; 109 } else { 110 lua_pushlstring(lua,p+2,bulklen); 111 return p+2+bulklen+2; 112 } 113 } 114 115 char *redisProtocolToLuaType_Status(lua_State *lua, char *reply) { 116 char *p = strchr(reply+1,'\r'); 117 118 lua_newtable(lua); 119 lua_pushstring(lua,"ok"); 120 lua_pushlstring(lua,reply+1,p-reply-1); 121 lua_settable(lua,-3); 122 return p+2; 123 } 124 125 char *redisProtocolToLuaType_Error(lua_State *lua, char *reply) { 126 char *p = strchr(reply+1,'\r'); 127 128 lua_newtable(lua); 129 lua_pushstring(lua,"err"); 130 lua_pushlstring(lua,reply+1,p-reply-1); 131 lua_settable(lua,-3); 132 return p+2; 133 } 134 135 char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply) { 136 char *p = strchr(reply+1,'\r'); 137 long long mbulklen; 138 int j = 0; 139 140 string2ll(reply+1,p-reply-1,&mbulklen); 141 p += 2; 142 if (mbulklen == -1) { 143 lua_pushboolean(lua,0); 144 return p; 145 } 146 lua_newtable(lua); 147 for (j = 0; j < mbulklen; j++) { 148 lua_pushnumber(lua,j+1); 149 p = redisProtocolToLuaType(lua,p); 150 lua_settable(lua,-3); 151 } 152 return p; 153 } 154 155 void luaPushError(lua_State *lua, char *error) { 156 lua_Debug dbg; 157 158 lua_newtable(lua); 159 lua_pushstring(lua,"err"); 160 161 /* Attempt to figure out where this function was called, if possible */ 162 if(lua_getstack(lua, 1, &dbg) && lua_getinfo(lua, "nSl", &dbg)) { 163 sds msg = sdscatprintf(sdsempty(), "%s: %d: %s", 164 dbg.source, dbg.currentline, error); 165 lua_pushstring(lua, msg); 166 sdsfree(msg); 167 } else { 168 lua_pushstring(lua, error); 169 } 170 lua_settable(lua,-3); 171 } 172 173 /* Sort the array currently in the stack. We do this to make the output 174 * of commands like KEYS or SMEMBERS something deterministic when called 175 * from Lua (to play well with AOf/replication). 176 * 177 * The array is sorted using table.sort itself, and assuming all the 178 * list elements are strings. */ 179 void luaSortArray(lua_State *lua) { 180 /* Initial Stack: array */ 181 lua_getglobal(lua,"table"); 182 lua_pushstring(lua,"sort"); 183 lua_gettable(lua,-2); /* Stack: array, table, table.sort */ 184 lua_pushvalue(lua,-3); /* Stack: array, table, table.sort, array */ 185 if (lua_pcall(lua,1,0,0)) { 186 /* Stack: array, table, error */ 187 188 /* We are not interested in the error, we assume that the problem is 189 * that there are 'false' elements inside the array, so we try 190 * again with a slower function but able to handle this case, that 191 * is: table.sort(table, __redis__compare_helper) */ 192 lua_pop(lua,1); /* Stack: array, table */ 193 lua_pushstring(lua,"sort"); /* Stack: array, table, sort */ 194 lua_gettable(lua,-2); /* Stack: array, table, table.sort */ 195 lua_pushvalue(lua,-3); /* Stack: array, table, table.sort, array */ 196 lua_getglobal(lua,"__redis__compare_helper"); 197 /* Stack: array, table, table.sort, array, __redis__compare_helper */ 198 lua_call(lua,2,0); 199 } 200 /* Stack: array (sorted), table */ 201 lua_pop(lua,1); /* Stack: array (sorted) */ 202 } 203 204 #define LUA_CMD_OBJCACHE_SIZE 32 205 #define LUA_CMD_OBJCACHE_MAX_LEN 64 206 int luaRedisGenericCommand(lua_State *lua, int raise_error) { 207 int j, argc = lua_gettop(lua); 208 struct redisCommand *cmd; 209 redisClient *c = server.lua_client; 210 sds reply; 211 212 /* Cached across calls. */ 213 static robj **argv = NULL; 214 static int argv_size = 0; 215 static robj *cached_objects[LUA_CMD_OBJCACHE_SIZE]; 216 static size_t cached_objects_len[LUA_CMD_OBJCACHE_SIZE]; 217 static int inuse = 0; /* Recursive calls detection. */ 218 219 /* By using Lua debug hooks it is possible to trigger a recursive call 220 * to luaRedisGenericCommand(), which normally should never happen. 221 * To make this function reentrant is futile and makes it slower, but 222 * we should at least detect such a misuse, and abort. */ 223 if (inuse) { 224 char *recursion_warning = 225 "luaRedisGenericCommand() recursive call detected. " 226 "Are you doing funny stuff with Lua debug hooks?"; 227 redisLog(REDIS_WARNING,"%s",recursion_warning); 228 luaPushError(lua,recursion_warning); 229 return 1; 230 } 231 inuse++; 232 233 /* Require at least one argument */ 234 if (argc == 0) { 235 luaPushError(lua, 236 "Please specify at least one argument for redis.call()"); 237 inuse--; 238 return 1; 239 } 240 241 /* Build the arguments vector */ 242 if (argv_size < argc) { 243 argv = zrealloc(argv,sizeof(robj*)*argc); 244 argv_size = argc; 245 } 246 247 for (j = 0; j < argc; j++) { 248 char *obj_s; 249 size_t obj_len; 250 char dbuf[64]; 251 252 if (lua_type(lua,j+1) == LUA_TNUMBER) { 253 /* We can't use lua_tolstring() for number -> string conversion 254 * since Lua uses a format specifier that loses precision. */ 255 lua_Number num = lua_tonumber(lua,j+1); 256 257 obj_len = snprintf(dbuf,sizeof(dbuf),"%.17g",(double)num); 258 obj_s = dbuf; 259 } else { 260 obj_s = (char*)lua_tolstring(lua,j+1,&obj_len); 261 if (obj_s == NULL) break; /* Not a string. */ 262 } 263 264 /* Try to use a cached object. */ 265 if (j < LUA_CMD_OBJCACHE_SIZE && cached_objects[j] && 266 cached_objects_len[j] >= obj_len) 267 { 268 char *s = cached_objects[j]->ptr; 269 struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr))); 270 271 argv[j] = cached_objects[j]; 272 cached_objects[j] = NULL; 273 memcpy(s,obj_s,obj_len+1); 274 sh->free += sh->len - obj_len; 275 sh->len = obj_len; 276 } else { 277 argv[j] = createStringObject(obj_s, obj_len); 278 } 279 } 280 281 /* Check if one of the arguments passed by the Lua script 282 * is not a string or an integer (lua_isstring() return true for 283 * integers as well). */ 284 if (j != argc) { 285 j--; 286 while (j >= 0) { 287 decrRefCount(argv[j]); 288 j--; 289 } 290 luaPushError(lua, 291 "Lua redis() command arguments must be strings or integers"); 292 inuse--; 293 return 1; 294 } 295 296 /* Setup our fake client for command execution */ 297 c->argv = argv; 298 c->argc = argc; 299 300 /* Command lookup */ 301 cmd = lookupCommand(argv[0]->ptr); 302 if (!cmd || ((cmd->arity > 0 && cmd->arity != argc) || 303 (argc < -cmd->arity))) 304 { 305 if (cmd) 306 luaPushError(lua, 307 "Wrong number of args calling Redis command From Lua script"); 308 else 309 luaPushError(lua,"Unknown Redis command called from Lua script"); 310 goto cleanup; 311 } 312 c->cmd = cmd; 313 314 /* There are commands that are not allowed inside scripts. */ 315 if (cmd->flags & REDIS_CMD_NOSCRIPT) { 316 luaPushError(lua, "This Redis command is not allowed from scripts"); 317 goto cleanup; 318 } 319 320 /* Write commands are forbidden against read-only slaves, or if a 321 * command marked as non-deterministic was already called in the context 322 * of this script. */ 323 if (cmd->flags & REDIS_CMD_WRITE) { 324 if (server.lua_random_dirty) { 325 luaPushError(lua, 326 "Write commands not allowed after non deterministic commands"); 327 goto cleanup; 328 } else if (server.masterhost && server.repl_slave_ro && 329 !server.loading && 330 !(server.lua_caller->flags & REDIS_MASTER)) 331 { 332 luaPushError(lua, shared.roslaveerr->ptr); 333 goto cleanup; 334 } else if (server.stop_writes_on_bgsave_err && 335 server.saveparamslen > 0 && 336 server.lastbgsave_status == REDIS_ERR) 337 { 338 luaPushError(lua, shared.bgsaveerr->ptr); 339 goto cleanup; 340 } 341 } 342 343 /* If we reached the memory limit configured via maxmemory, commands that 344 * could enlarge the memory usage are not allowed, but only if this is the 345 * first write in the context of this script, otherwise we can't stop 346 * in the middle. */ 347 if (server.maxmemory && server.lua_write_dirty == 0 && 348 (cmd->flags & REDIS_CMD_DENYOOM)) 349 { 350 if (freeMemoryIfNeeded() == REDIS_ERR) { 351 luaPushError(lua, shared.oomerr->ptr); 352 goto cleanup; 353 } 354 } 355 356 if (cmd->flags & REDIS_CMD_RANDOM) server.lua_random_dirty = 1; 357 if (cmd->flags & REDIS_CMD_WRITE) server.lua_write_dirty = 1; 358 359 /* If this is a Redis Cluster node, we need to make sure Lua is not 360 * trying to access non-local keys. */ 361 if (server.cluster_enabled) { 362 /* Duplicate relevant flags in the lua client. */ 363 c->flags &= ~(REDIS_READONLY|REDIS_ASKING); 364 c->flags |= server.lua_caller->flags & (REDIS_READONLY|REDIS_ASKING); 365 if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) != 366 server.cluster->myself) 367 { 368 luaPushError(lua, 369 "Lua script attempted to access a non local key in a " 370 "cluster node"); 371 goto cleanup; 372 } 373 } 374 375 /* Run the command */ 376 call(c,REDIS_CALL_SLOWLOG | REDIS_CALL_STATS); 377 378 /* Convert the result of the Redis command into a suitable Lua type. 379 * The first thing we need is to create a single string from the client 380 * output buffers. */ 381 if (listLength(c->reply) == 0 && c->bufpos < REDIS_REPLY_CHUNK_BYTES) { 382 /* This is a fast path for the common case of a reply inside the 383 * client static buffer. Don't create an SDS string but just use 384 * the client buffer directly. */ 385 c->buf[c->bufpos] = '\0'; 386 reply = c->buf; 387 c->bufpos = 0; 388 } else { 389 reply = sdsnewlen(c->buf,c->bufpos); 390 c->bufpos = 0; 391 while(listLength(c->reply)) { 392 robj *o = listNodeValue(listFirst(c->reply)); 393 394 reply = sdscatlen(reply,o->ptr,sdslen(o->ptr)); 395 listDelNode(c->reply,listFirst(c->reply)); 396 } 397 } 398 if (raise_error && reply[0] != '-') raise_error = 0; 399 redisProtocolToLuaType(lua,reply); 400 /* Sort the output array if needed, assuming it is a non-null multi bulk 401 * reply as expected. */ 402 if ((cmd->flags & REDIS_CMD_SORT_FOR_SCRIPT) && 403 (reply[0] == '*' && reply[1] != '-')) { 404 luaSortArray(lua); 405 } 406 if (reply != c->buf) sdsfree(reply); 407 c->reply_bytes = 0; 408 409 cleanup: 410 /* Clean up. Command code may have changed argv/argc so we use the 411 * argv/argc of the client instead of the local variables. */ 412 for (j = 0; j < c->argc; j++) { 413 robj *o = c->argv[j]; 414 415 /* Try to cache the object in the cached_objects array. 416 * The object must be small, SDS-encoded, and with refcount = 1 417 * (we must be the only owner) for us to cache it. */ 418 if (j < LUA_CMD_OBJCACHE_SIZE && 419 o->refcount == 1 && 420 (o->encoding == REDIS_ENCODING_RAW || 421 o->encoding == REDIS_ENCODING_EMBSTR) && 422 sdslen(o->ptr) <= LUA_CMD_OBJCACHE_MAX_LEN) 423 { 424 struct sdshdr *sh = (void*)(((char*)(o->ptr))-(sizeof(struct sdshdr))); 425 426 if (cached_objects[j]) decrRefCount(cached_objects[j]); 427 cached_objects[j] = o; 428 cached_objects_len[j] = sh->free + sh->len; 429 } else { 430 decrRefCount(o); 431 } 432 } 433 434 if (c->argv != argv) { 435 zfree(c->argv); 436 argv = NULL; 437 argv_size = 0; 438 } 439 440 if (raise_error) { 441 /* If we are here we should have an error in the stack, in the 442 * form of a table with an "err" field. Extract the string to 443 * return the plain error. */ 444 lua_pushstring(lua,"err"); 445 lua_gettable(lua,-2); 446 inuse--; 447 return lua_error(lua); 448 } 449 inuse--; 450 return 1; 451 } 452 453 int luaRedisCallCommand(lua_State *lua) { 454 return luaRedisGenericCommand(lua,1); 455 } 456 457 int luaRedisPCallCommand(lua_State *lua) { 458 return luaRedisGenericCommand(lua,0); 459 } 460 461 /* This adds redis.sha1hex(string) to Lua scripts using the same hashing 462 * function used for sha1ing lua scripts. */ 463 int luaRedisSha1hexCommand(lua_State *lua) { 464 int argc = lua_gettop(lua); 465 char digest[41]; 466 size_t len; 467 char *s; 468 469 if (argc != 1) { 470 luaPushError(lua, "wrong number of arguments"); 471 return 1; 472 } 473 474 s = (char*)lua_tolstring(lua,1,&len); 475 sha1hex(digest,s,len); 476 lua_pushstring(lua,digest); 477 return 1; 478 } 479 480 /* Returns a table with a single field 'field' set to the string value 481 * passed as argument. This helper function is handy when returning 482 * a Redis Protocol error or status reply from Lua: 483 * 484 * return redis.error_reply("ERR Some Error") 485 * return redis.status_reply("ERR Some Error") 486 */ 487 int luaRedisReturnSingleFieldTable(lua_State *lua, char *field) { 488 if (lua_gettop(lua) != 1 || lua_type(lua,-1) != LUA_TSTRING) { 489 luaPushError(lua, "wrong number or type of arguments"); 490 return 1; 491 } 492 493 lua_newtable(lua); 494 lua_pushstring(lua, field); 495 lua_pushvalue(lua, -3); 496 lua_settable(lua, -3); 497 return 1; 498 } 499 500 int luaRedisErrorReplyCommand(lua_State *lua) { 501 return luaRedisReturnSingleFieldTable(lua,"err"); 502 } 503 504 int luaRedisStatusReplyCommand(lua_State *lua) { 505 return luaRedisReturnSingleFieldTable(lua,"ok"); 506 } 507 508 int luaLogCommand(lua_State *lua) { 509 int j, argc = lua_gettop(lua); 510 int level; 511 sds log; 512 513 if (argc < 2) { 514 luaPushError(lua, "redis.log() requires two arguments or more."); 515 return 1; 516 } else if (!lua_isnumber(lua,-argc)) { 517 luaPushError(lua, "First argument must be a number (log level)."); 518 return 1; 519 } 520 level = lua_tonumber(lua,-argc); 521 if (level < REDIS_DEBUG || level > REDIS_WARNING) { 522 luaPushError(lua, "Invalid debug level."); 523 return 1; 524 } 525 526 /* Glue together all the arguments */ 527 log = sdsempty(); 528 for (j = 1; j < argc; j++) { 529 size_t len; 530 char *s; 531 532 s = (char*)lua_tolstring(lua,(-argc)+j,&len); 533 if (s) { 534 if (j != 1) log = sdscatlen(log," ",1); 535 log = sdscatlen(log,s,len); 536 } 537 } 538 redisLogRaw(level,log); 539 sdsfree(log); 540 return 0; 541 } 542 543 void luaMaskCountHook(lua_State *lua, lua_Debug *ar) { 544 long long elapsed; 545 REDIS_NOTUSED(ar); 546 REDIS_NOTUSED(lua); 547 548 elapsed = mstime() - server.lua_time_start; 549 if (elapsed >= server.lua_time_limit && server.lua_timedout == 0) { 550 redisLog(REDIS_WARNING,"Lua slow script detected: still in execution after %lld milliseconds. You can try killing the script using the SCRIPT KILL command.",elapsed); 551 server.lua_timedout = 1; 552 /* Once the script timeouts we reenter the event loop to permit others 553 * to call SCRIPT KILL or SHUTDOWN NOSAVE if needed. For this reason 554 * we need to mask the client executing the script from the event loop. 555 * If we don't do that the client may disconnect and could no longer be 556 * here when the EVAL command will return. */ 557 aeDeleteFileEvent(server.el, server.lua_caller->fd, AE_READABLE); 558 } 559 if (server.lua_timedout) processEventsWhileBlocked(); 560 if (server.lua_kill) { 561 redisLog(REDIS_WARNING,"Lua script killed by user with SCRIPT KILL."); 562 lua_pushstring(lua,"Script killed by user with SCRIPT KILL..."); 563 lua_error(lua); 564 } 565 } 566 567 void luaLoadLib(lua_State *lua, const char *libname, lua_CFunction luafunc) { 568 lua_pushcfunction(lua, luafunc); 569 lua_pushstring(lua, libname); 570 lua_call(lua, 1, 0); 571 } 572 573 LUALIB_API int (luaopen_cjson) (lua_State *L); 574 LUALIB_API int (luaopen_struct) (lua_State *L); 575 LUALIB_API int (luaopen_cmsgpack) (lua_State *L); 576 LUALIB_API int (luaopen_bit) (lua_State *L); 577 578 void luaLoadLibraries(lua_State *lua) { 579 luaLoadLib(lua, "", luaopen_base); 580 luaLoadLib(lua, LUA_TABLIBNAME, luaopen_table); 581 luaLoadLib(lua, LUA_STRLIBNAME, luaopen_string); 582 luaLoadLib(lua, LUA_MATHLIBNAME, luaopen_math); 583 luaLoadLib(lua, LUA_DBLIBNAME, luaopen_debug); 584 luaLoadLib(lua, "cjson", luaopen_cjson); 585 luaLoadLib(lua, "struct", luaopen_struct); 586 luaLoadLib(lua, "cmsgpack", luaopen_cmsgpack); 587 luaLoadLib(lua, "bit", luaopen_bit); 588 589 #if 0 /* Stuff that we don't load currently, for sandboxing concerns. */ 590 luaLoadLib(lua, LUA_LOADLIBNAME, luaopen_package); 591 luaLoadLib(lua, LUA_OSLIBNAME, luaopen_os); 592 #endif 593 } 594 595 /* Remove a functions that we don't want to expose to the Redis scripting 596 * environment. */ 597 void luaRemoveUnsupportedFunctions(lua_State *lua) { 598 lua_pushnil(lua); 599 lua_setglobal(lua,"loadfile"); 600 } 601 602 /* This function installs metamethods in the global table _G that prevent 603 * the creation of globals accidentally. 604 * 605 * It should be the last to be called in the scripting engine initialization 606 * sequence, because it may interact with creation of globals. */ 607 void scriptingEnableGlobalsProtection(lua_State *lua) { 608 char *s[32]; 609 sds code = sdsempty(); 610 int j = 0; 611 612 /* strict.lua from: http://metalua.luaforge.net/src/lib/strict.lua.html. 613 * Modified to be adapted to Redis. */ 614 s[j++]="local mt = {}\n"; 615 s[j++]="setmetatable(_G, mt)\n"; 616 s[j++]="mt.__newindex = function (t, n, v)\n"; 617 s[j++]=" if debug.getinfo(2) then\n"; 618 s[j++]=" local w = debug.getinfo(2, \"S\").what\n"; 619 s[j++]=" if w ~= \"main\" and w ~= \"C\" then\n"; 620 s[j++]=" error(\"Script attempted to create global variable '\"..tostring(n)..\"'\", 2)\n"; 621 s[j++]=" end\n"; 622 s[j++]=" end\n"; 623 s[j++]=" rawset(t, n, v)\n"; 624 s[j++]="end\n"; 625 s[j++]="mt.__index = function (t, n)\n"; 626 s[j++]=" if debug.getinfo(2) and debug.getinfo(2, \"S\").what ~= \"C\" then\n"; 627 s[j++]=" error(\"Script attempted to access unexisting global variable '\"..tostring(n)..\"'\", 2)\n"; 628 s[j++]=" end\n"; 629 s[j++]=" return rawget(t, n)\n"; 630 s[j++]="end\n"; 631 s[j++]=NULL; 632 633 for (j = 0; s[j] != NULL; j++) code = sdscatlen(code,s[j],strlen(s[j])); 634 luaL_loadbuffer(lua,code,sdslen(code),"@enable_strict_lua"); 635 lua_pcall(lua,0,0,0); 636 sdsfree(code); 637 } 638 639 /* Initialize the scripting environment. 640 * It is possible to call this function to reset the scripting environment 641 * assuming that we call scriptingRelease() before. 642 * See scriptingReset() for more information. */ 643 void scriptingInit(void) { 644 lua_State *lua = lua_open(); 645 646 luaLoadLibraries(lua); 647 luaRemoveUnsupportedFunctions(lua); 648 649 /* Initialize a dictionary we use to map SHAs to scripts. 650 * This is useful for replication, as we need to replicate EVALSHA 651 * as EVAL, so we need to remember the associated script. */ 652 server.lua_scripts = dictCreate(&shaScriptObjectDictType,NULL); 653 654 /* Register the redis commands table and fields */ 655 lua_newtable(lua); 656 657 /* redis.call */ 658 lua_pushstring(lua,"call"); 659 lua_pushcfunction(lua,luaRedisCallCommand); 660 lua_settable(lua,-3); 661 662 /* redis.pcall */ 663 lua_pushstring(lua,"pcall"); 664 lua_pushcfunction(lua,luaRedisPCallCommand); 665 lua_settable(lua,-3); 666 667 /* redis.log and log levels. */ 668 lua_pushstring(lua,"log"); 669 lua_pushcfunction(lua,luaLogCommand); 670 lua_settable(lua,-3); 671 672 lua_pushstring(lua,"LOG_DEBUG"); 673 lua_pushnumber(lua,REDIS_DEBUG); 674 lua_settable(lua,-3); 675 676 lua_pushstring(lua,"LOG_VERBOSE"); 677 lua_pushnumber(lua,REDIS_VERBOSE); 678 lua_settable(lua,-3); 679 680 lua_pushstring(lua,"LOG_NOTICE"); 681 lua_pushnumber(lua,REDIS_NOTICE); 682 lua_settable(lua,-3); 683 684 lua_pushstring(lua,"LOG_WARNING"); 685 lua_pushnumber(lua,REDIS_WARNING); 686 lua_settable(lua,-3); 687 688 /* redis.sha1hex */ 689 lua_pushstring(lua, "sha1hex"); 690 lua_pushcfunction(lua, luaRedisSha1hexCommand); 691 lua_settable(lua, -3); 692 693 /* redis.error_reply and redis.status_reply */ 694 lua_pushstring(lua, "error_reply"); 695 lua_pushcfunction(lua, luaRedisErrorReplyCommand); 696 lua_settable(lua, -3); 697 lua_pushstring(lua, "status_reply"); 698 lua_pushcfunction(lua, luaRedisStatusReplyCommand); 699 lua_settable(lua, -3); 700 701 /* Finally set the table as 'redis' global var. */ 702 lua_setglobal(lua,"redis"); 703 704 /* Replace math.random and math.randomseed with our implementations. */ 705 lua_getglobal(lua,"math"); 706 707 lua_pushstring(lua,"random"); 708 lua_pushcfunction(lua,redis_math_random); 709 lua_settable(lua,-3); 710 711 lua_pushstring(lua,"randomseed"); 712 lua_pushcfunction(lua,redis_math_randomseed); 713 lua_settable(lua,-3); 714 715 lua_setglobal(lua,"math"); 716 717 /* Add a helper function that we use to sort the multi bulk output of non 718 * deterministic commands, when containing 'false' elements. */ 719 { 720 char *compare_func = "function __redis__compare_helper(a,b)\n" 721 " if a == false then a = '' end\n" 722 " if b == false then b = '' end\n" 723 " return a<b\n" 724 "end\n"; 725 luaL_loadbuffer(lua,compare_func,strlen(compare_func),"@cmp_func_def"); 726 lua_pcall(lua,0,0,0); 727 } 728 729 /* Add a helper function we use for pcall error reporting. 730 * Note that when the error is in the C function we want to report the 731 * information about the caller, that's what makes sense from the point 732 * of view of the user debugging a script. */ 733 { 734 char *errh_func = "function __redis__err__handler(err)\n" 735 " local i = debug.getinfo(2,'nSl')\n" 736 " if i and i.what == 'C' then\n" 737 " i = debug.getinfo(3,'nSl')\n" 738 " end\n" 739 " if i then\n" 740 " return i.source .. ':' .. i.currentline .. ': ' .. err\n" 741 " else\n" 742 " return err\n" 743 " end\n" 744 "end\n"; 745 luaL_loadbuffer(lua,errh_func,strlen(errh_func),"@err_handler_def"); 746 lua_pcall(lua,0,0,0); 747 } 748 749 /* Create the (non connected) client that we use to execute Redis commands 750 * inside the Lua interpreter. 751 * Note: there is no need to create it again when this function is called 752 * by scriptingReset(). */ 753 if (server.lua_client == NULL) { 754 server.lua_client = createClient(-1); 755 server.lua_client->flags |= REDIS_LUA_CLIENT; 756 } 757 758 /* Lua beginners often don't use "local", this is likely to introduce 759 * subtle bugs in their code. To prevent problems we protect accesses 760 * to global variables. */ 761 scriptingEnableGlobalsProtection(lua); 762 763 server.lua = lua; 764 } 765 766 /* Release resources related to Lua scripting. 767 * This function is used in order to reset the scripting environment. */ 768 void scriptingRelease(void) { 769 dictRelease(server.lua_scripts); 770 lua_close(server.lua); 771 } 772 773 void scriptingReset(void) { 774 scriptingRelease(); 775 scriptingInit(); 776 } 777 778 /* Perform the SHA1 of the input string. We use this both for hashing script 779 * bodies in order to obtain the Lua function name, and in the implementation 780 * of redis.sha1(). 781 * 782 * 'digest' should point to a 41 bytes buffer: 40 for SHA1 converted into an 783 * hexadecimal number, plus 1 byte for null term. */ 784 void sha1hex(char *digest, char *script, size_t len) { 785 SHA1_CTX ctx; 786 unsigned char hash[20]; 787 char *cset = "0123456789abcdef"; 788 int j; 789 790 SHA1Init(&ctx); 791 SHA1Update(&ctx,(unsigned char*)script,len); 792 SHA1Final(hash,&ctx); 793 794 for (j = 0; j < 20; j++) { 795 digest[j*2] = cset[((hash[j]&0xF0)>>4)]; 796 digest[j*2+1] = cset[(hash[j]&0xF)]; 797 } 798 digest[40] = '\0'; 799 } 800 801 void luaReplyToRedisReply(redisClient *c, lua_State *lua) { 802 int t = lua_type(lua,-1); 803 804 switch(t) { 805 case LUA_TSTRING: 806 addReplyBulkCBuffer(c,(char*)lua_tostring(lua,-1),lua_strlen(lua,-1)); 807 break; 808 case LUA_TBOOLEAN: 809 addReply(c,lua_toboolean(lua,-1) ? shared.cone : shared.nullbulk); 810 break; 811 case LUA_TNUMBER: 812 addReplyLongLong(c,(long long)lua_tonumber(lua,-1)); 813 break; 814 case LUA_TTABLE: 815 /* We need to check if it is an array, an error, or a status reply. 816 * Error are returned as a single element table with 'err' field. 817 * Status replies are returned as single element table with 'ok' field */ 818 lua_pushstring(lua,"err"); 819 lua_gettable(lua,-2); 820 t = lua_type(lua,-1); 821 if (t == LUA_TSTRING) { 822 sds err = sdsnew(lua_tostring(lua,-1)); 823 sdsmapchars(err,"\r\n"," ",2); 824 addReplySds(c,sdscatprintf(sdsempty(),"-%s\r\n",err)); 825 sdsfree(err); 826 lua_pop(lua,2); 827 return; 828 } 829 830 lua_pop(lua,1); 831 lua_pushstring(lua,"ok"); 832 lua_gettable(lua,-2); 833 t = lua_type(lua,-1); 834 if (t == LUA_TSTRING) { 835 sds ok = sdsnew(lua_tostring(lua,-1)); 836 sdsmapchars(ok,"\r\n"," ",2); 837 addReplySds(c,sdscatprintf(sdsempty(),"+%s\r\n",ok)); 838 sdsfree(ok); 839 lua_pop(lua,1); 840 } else { 841 void *replylen = addDeferredMultiBulkLength(c); 842 int j = 1, mbulklen = 0; 843 844 lua_pop(lua,1); /* Discard the 'ok' field value we popped */ 845 while(1) { 846 lua_pushnumber(lua,j++); 847 lua_gettable(lua,-2); 848 t = lua_type(lua,-1); 849 if (t == LUA_TNIL) { 850 lua_pop(lua,1); 851 break; 852 } 853 luaReplyToRedisReply(c, lua); 854 mbulklen++; 855 } 856 setDeferredMultiBulkLength(c,replylen,mbulklen); 857 } 858 break; 859 default: 860 addReply(c,shared.nullbulk); 861 } 862 lua_pop(lua,1); 863 } 864 865 /* Set an array of Redis String Objects as a Lua array (table) stored into a 866 * global variable. */ 867 void luaSetGlobalArray(lua_State *lua, char *var, robj **elev, int elec) { 868 int j; 869 870 lua_newtable(lua); 871 for (j = 0; j < elec; j++) { 872 lua_pushlstring(lua,(char*)elev[j]->ptr,sdslen(elev[j]->ptr)); 873 lua_rawseti(lua,-2,j+1); 874 } 875 lua_setglobal(lua,var); 876 } 877 878 /* Define a lua function with the specified function name and body. 879 * The function name musts be a 2 characters long string, since all the 880 * functions we defined in the Lua context are in the form: 881 * 882 * f_<hex sha1 sum> 883 * 884 * On success REDIS_OK is returned, and nothing is left on the Lua stack. 885 * On error REDIS_ERR is returned and an appropriate error is set in the 886 * client context. */ 887 int luaCreateFunction(redisClient *c, lua_State *lua, char *funcname, robj *body) { 888 sds funcdef = sdsempty(); 889 890 funcdef = sdscat(funcdef,"function "); 891 funcdef = sdscatlen(funcdef,funcname,42); 892 funcdef = sdscatlen(funcdef,"() ",3); 893 funcdef = sdscatlen(funcdef,body->ptr,sdslen(body->ptr)); 894 funcdef = sdscatlen(funcdef," end",4); 895 896 if (luaL_loadbuffer(lua,funcdef,sdslen(funcdef),"@user_script")) { 897 addReplyErrorFormat(c,"Error compiling script (new function): %s\n", 898 lua_tostring(lua,-1)); 899 lua_pop(lua,1); 900 sdsfree(funcdef); 901 return REDIS_ERR; 902 } 903 sdsfree(funcdef); 904 if (lua_pcall(lua,0,0,0)) { 905 addReplyErrorFormat(c,"Error running script (new function): %s\n", 906 lua_tostring(lua,-1)); 907 lua_pop(lua,1); 908 return REDIS_ERR; 909 } 910 911 /* We also save a SHA1 -> Original script map in a dictionary 912 * so that we can replicate / write in the AOF all the 913 * EVALSHA commands as EVAL using the original script. */ 914 { 915 int retval = dictAdd(server.lua_scripts, 916 sdsnewlen(funcname+2,40),body); 917 redisAssertWithInfo(c,NULL,retval == DICT_OK); 918 incrRefCount(body); 919 } 920 return REDIS_OK; 921 } 922 923 void evalGenericCommand(redisClient *c, int evalsha) { 924 lua_State *lua = server.lua; 925 char funcname[43]; 926 long long numkeys; 927 int delhook = 0, err; 928 929 /* We want the same PRNG sequence at every call so that our PRNG is 930 * not affected by external state. */ 931 redisSrand48(0); 932 933 /* We set this flag to zero to remember that so far no random command 934 * was called. This way we can allow the user to call commands like 935 * SRANDMEMBER or RANDOMKEY from Lua scripts as far as no write command 936 * is called (otherwise the replication and AOF would end with non 937 * deterministic sequences). 938 * 939 * Thanks to this flag we'll raise an error every time a write command 940 * is called after a random command was used. */ 941 server.lua_random_dirty = 0; 942 server.lua_write_dirty = 0; 943 944 /* Get the number of arguments that are keys */ 945 if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != REDIS_OK) 946 return; 947 if (numkeys > (c->argc - 3)) { 948 addReplyError(c,"Number of keys can't be greater than number of args"); 949 return; 950 } else if (numkeys < 0) { 951 addReplyError(c,"Number of keys can't be negative"); 952 return; 953 } 954 955 /* We obtain the script SHA1, then check if this function is already 956 * defined into the Lua state */ 957 funcname[0] = 'f'; 958 funcname[1] = '_'; 959 if (!evalsha) { 960 /* Hash the code if this is an EVAL call */ 961 sha1hex(funcname+2,c->argv[1]->ptr,sdslen(c->argv[1]->ptr)); 962 } else { 963 /* We already have the SHA if it is a EVALSHA */ 964 int j; 965 char *sha = c->argv[1]->ptr; 966 967 /* Convert to lowercase. We don't use tolower since the function 968 * managed to always show up in the profiler output consuming 969 * a non trivial amount of time. */ 970 for (j = 0; j < 40; j++) 971 funcname[j+2] = (sha[j] >= 'A' && sha[j] <= 'Z') ? 972 sha[j]+('a'-'A') : sha[j]; 973 funcname[42] = '\0'; 974 } 975 976 /* Push the pcall error handler function on the stack. */ 977 lua_getglobal(lua, "__redis__err__handler"); 978 979 /* Try to lookup the Lua function */ 980 lua_getglobal(lua, funcname); 981 if (lua_isnil(lua,-1)) { 982 lua_pop(lua,1); /* remove the nil from the stack */ 983 /* Function not defined... let's define it if we have the 984 * body of the function. If this is an EVALSHA call we can just 985 * return an error. */ 986 if (evalsha) { 987 lua_pop(lua,1); /* remove the error handler from the stack. */ 988 addReply(c, shared.noscripterr); 989 return; 990 } 991 if (luaCreateFunction(c,lua,funcname,c->argv[1]) == REDIS_ERR) { 992 lua_pop(lua,1); /* remove the error handler from the stack. */ 993 /* The error is sent to the client by luaCreateFunction() 994 * itself when it returns REDIS_ERR. */ 995 return; 996 } 997 /* Now the following is guaranteed to return non nil */ 998 lua_getglobal(lua, funcname); 999 redisAssert(!lua_isnil(lua,-1)); 1000 } 1001 1002 /* Populate the argv and keys table accordingly to the arguments that 1003 * EVAL received. */ 1004 luaSetGlobalArray(lua,"KEYS",c->argv+3,numkeys); 1005 luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys); 1006 1007 /* Select the right DB in the context of the Lua client */ 1008 selectDb(server.lua_client,c->db->id); 1009 1010 /* Set a hook in order to be able to stop the script execution if it 1011 * is running for too much time. 1012 * We set the hook only if the time limit is enabled as the hook will 1013 * make the Lua script execution slower. */ 1014 server.lua_caller = c; 1015 server.lua_time_start = mstime(); 1016 server.lua_kill = 0; 1017 if (server.lua_time_limit > 0 && server.masterhost == NULL) { 1018 lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000); 1019 delhook = 1; 1020 } 1021 1022 /* At this point whether this script was never seen before or if it was 1023 * already defined, we can call it. We have zero arguments and expect 1024 * a single return value. */ 1025 err = lua_pcall(lua,0,1,-2); 1026 1027 /* Perform some cleanup that we need to do both on error and success. */ 1028 if (delhook) lua_sethook(lua,luaMaskCountHook,0,0); /* Disable hook */ 1029 if (server.lua_timedout) { 1030 server.lua_timedout = 0; 1031 /* Restore the readable handler that was unregistered when the 1032 * script timeout was detected. */ 1033 aeCreateFileEvent(server.el,c->fd,AE_READABLE, 1034 readQueryFromClient,c); 1035 } 1036 server.lua_caller = NULL; 1037 1038 /* Call the Lua garbage collector from time to time to avoid a 1039 * full cycle performed by Lua, which adds too latency. 1040 * 1041 * The call is performed every LUA_GC_CYCLE_PERIOD executed commands 1042 * (and for LUA_GC_CYCLE_PERIOD collection steps) because calling it 1043 * for every command uses too much CPU. */ 1044 #define LUA_GC_CYCLE_PERIOD 50 1045 { 1046 static long gc_count = 0; 1047 1048 gc_count++; 1049 if (gc_count == LUA_GC_CYCLE_PERIOD) { 1050 lua_gc(lua,LUA_GCSTEP,LUA_GC_CYCLE_PERIOD); 1051 gc_count = 0; 1052 } 1053 } 1054 1055 if (err) { 1056 addReplyErrorFormat(c,"Error running script (call to %s): %s\n", 1057 funcname, lua_tostring(lua,-1)); 1058 lua_pop(lua,2); /* Consume the Lua reply and remove error handler. */ 1059 } else { 1060 /* On success convert the Lua return value into Redis protocol, and 1061 * send it to * the client. */ 1062 luaReplyToRedisReply(c,lua); /* Convert and consume the reply. */ 1063 lua_pop(lua,1); /* Remove the error handler. */ 1064 } 1065 1066 /* EVALSHA should be propagated to Slave and AOF file as full EVAL, unless 1067 * we are sure that the script was already in the context of all the 1068 * attached slaves *and* the current AOF file if enabled. 1069 * 1070 * To do so we use a cache of SHA1s of scripts that we already propagated 1071 * as full EVAL, that's called the Replication Script Cache. 1072 * 1073 * For repliation, everytime a new slave attaches to the master, we need to 1074 * flush our cache of scripts that can be replicated as EVALSHA, while 1075 * for AOF we need to do so every time we rewrite the AOF file. */ 1076 if (evalsha) { 1077 if (!replicationScriptCacheExists(c->argv[1]->ptr)) { 1078 /* This script is not in our script cache, replicate it as 1079 * EVAL, then add it into the script cache, as from now on 1080 * slaves and AOF know about it. */ 1081 robj *script = dictFetchValue(server.lua_scripts,c->argv[1]->ptr); 1082 1083 replicationScriptCacheAdd(c->argv[1]->ptr); 1084 redisAssertWithInfo(c,NULL,script != NULL); 1085 rewriteClientCommandArgument(c,0, 1086 resetRefCount(createStringObject("EVAL",4))); 1087 rewriteClientCommandArgument(c,1,script); 1088 forceCommandPropagation(c,REDIS_PROPAGATE_REPL|REDIS_PROPAGATE_AOF); 1089 } 1090 } 1091 } 1092 1093 void evalCommand(redisClient *c) { 1094 evalGenericCommand(c,0); 1095 } 1096 1097 void evalShaCommand(redisClient *c) { 1098 if (sdslen(c->argv[1]->ptr) != 40) { 1099 /* We know that a match is not possible if the provided SHA is 1100 * not the right length. So we return an error ASAP, this way 1101 * evalGenericCommand() can be implemented without string length 1102 * sanity check */ 1103 addReply(c, shared.noscripterr); 1104 return; 1105 } 1106 evalGenericCommand(c,1); 1107 } 1108 1109 /* We replace math.random() with our implementation that is not affected 1110 * by specific libc random() implementations and will output the same sequence 1111 * (for the same seed) in every arch. */ 1112 1113 /* The following implementation is the one shipped with Lua itself but with 1114 * rand() replaced by redisLrand48(). */ 1115 int redis_math_random (lua_State *L) { 1116 /* the `%' avoids the (rare) case of r==1, and is needed also because on 1117 some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */ 1118 lua_Number r = (lua_Number)(redisLrand48()%REDIS_LRAND48_MAX) / 1119 (lua_Number)REDIS_LRAND48_MAX; 1120 switch (lua_gettop(L)) { /* check number of arguments */ 1121 case 0: { /* no arguments */ 1122 lua_pushnumber(L, r); /* Number between 0 and 1 */ 1123 break; 1124 } 1125 case 1: { /* only upper limit */ 1126 int u = luaL_checkint(L, 1); 1127 luaL_argcheck(L, 1<=u, 1, "interval is empty"); 1128 lua_pushnumber(L, floor(r*u)+1); /* int between 1 and `u' */ 1129 break; 1130 } 1131 case 2: { /* lower and upper limits */ 1132 int l = luaL_checkint(L, 1); 1133 int u = luaL_checkint(L, 2); 1134 luaL_argcheck(L, l<=u, 2, "interval is empty"); 1135 lua_pushnumber(L, floor(r*(u-l+1))+l); /* int between `l' and `u' */ 1136 break; 1137 } 1138 default: return luaL_error(L, "wrong number of arguments"); 1139 } 1140 return 1; 1141 } 1142 1143 int redis_math_randomseed (lua_State *L) { 1144 redisSrand48(luaL_checkint(L, 1)); 1145 return 0; 1146 } 1147 1148 /* --------------------------------------------------------------------------- 1149 * SCRIPT command for script environment introspection and control 1150 * ------------------------------------------------------------------------- */ 1151 1152 void scriptCommand(redisClient *c) { 1153 if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"flush")) { 1154 scriptingReset(); 1155 addReply(c,shared.ok); 1156 replicationScriptCacheFlush(); 1157 server.dirty++; /* Propagating this command is a good idea. */ 1158 } else if (c->argc >= 2 && !strcasecmp(c->argv[1]->ptr,"exists")) { 1159 int j; 1160 1161 addReplyMultiBulkLen(c, c->argc-2); 1162 for (j = 2; j < c->argc; j++) { 1163 if (dictFind(server.lua_scripts,c->argv[j]->ptr)) 1164 addReply(c,shared.cone); 1165 else 1166 addReply(c,shared.czero); 1167 } 1168 } else if (c->argc == 3 && !strcasecmp(c->argv[1]->ptr,"load")) { 1169 char funcname[43]; 1170 sds sha; 1171 1172 funcname[0] = 'f'; 1173 funcname[1] = '_'; 1174 sha1hex(funcname+2,c->argv[2]->ptr,sdslen(c->argv[2]->ptr)); 1175 sha = sdsnewlen(funcname+2,40); 1176 if (dictFind(server.lua_scripts,sha) == NULL) { 1177 if (luaCreateFunction(c,server.lua,funcname,c->argv[2]) 1178 == REDIS_ERR) { 1179 sdsfree(sha); 1180 return; 1181 } 1182 } 1183 addReplyBulkCBuffer(c,funcname+2,40); 1184 sdsfree(sha); 1185 forceCommandPropagation(c,REDIS_PROPAGATE_REPL|REDIS_PROPAGATE_AOF); 1186 } else if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"kill")) { 1187 if (server.lua_caller == NULL) { 1188 addReplySds(c,sdsnew("-NOTBUSY No scripts in execution right now.\r\n")); 1189 } else if (server.lua_write_dirty) { 1190 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")); 1191 } else { 1192 server.lua_kill = 1; 1193 addReply(c,shared.ok); 1194 } 1195 } else { 1196 addReplyError(c, "Unknown SCRIPT subcommand or wrong # of args."); 1197 } 1198 } 1199