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, with the exception of commands 361 * received from our master. */ 362 if (server.cluster_enabled && !(server.lua_caller->flags & REDIS_MASTER)) { 363 /* Duplicate relevant flags in the lua client. */ 364 c->flags &= ~(REDIS_READONLY|REDIS_ASKING); 365 c->flags |= server.lua_caller->flags & (REDIS_READONLY|REDIS_ASKING); 366 if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) != 367 server.cluster->myself) 368 { 369 luaPushError(lua, 370 "Lua script attempted to access a non local key in a " 371 "cluster node"); 372 goto cleanup; 373 } 374 } 375 376 /* Run the command */ 377 call(c,REDIS_CALL_SLOWLOG | REDIS_CALL_STATS); 378 379 /* Convert the result of the Redis command into a suitable Lua type. 380 * The first thing we need is to create a single string from the client 381 * output buffers. */ 382 if (listLength(c->reply) == 0 && c->bufpos < REDIS_REPLY_CHUNK_BYTES) { 383 /* This is a fast path for the common case of a reply inside the 384 * client static buffer. Don't create an SDS string but just use 385 * the client buffer directly. */ 386 c->buf[c->bufpos] = '\0'; 387 reply = c->buf; 388 c->bufpos = 0; 389 } else { 390 reply = sdsnewlen(c->buf,c->bufpos); 391 c->bufpos = 0; 392 while(listLength(c->reply)) { 393 robj *o = listNodeValue(listFirst(c->reply)); 394 395 reply = sdscatlen(reply,o->ptr,sdslen(o->ptr)); 396 listDelNode(c->reply,listFirst(c->reply)); 397 } 398 } 399 if (raise_error && reply[0] != '-') raise_error = 0; 400 redisProtocolToLuaType(lua,reply); 401 /* Sort the output array if needed, assuming it is a non-null multi bulk 402 * reply as expected. */ 403 if ((cmd->flags & REDIS_CMD_SORT_FOR_SCRIPT) && 404 (reply[0] == '*' && reply[1] != '-')) { 405 luaSortArray(lua); 406 } 407 if (reply != c->buf) sdsfree(reply); 408 c->reply_bytes = 0; 409 410 cleanup: 411 /* Clean up. Command code may have changed argv/argc so we use the 412 * argv/argc of the client instead of the local variables. */ 413 for (j = 0; j < c->argc; j++) { 414 robj *o = c->argv[j]; 415 416 /* Try to cache the object in the cached_objects array. 417 * The object must be small, SDS-encoded, and with refcount = 1 418 * (we must be the only owner) for us to cache it. */ 419 if (j < LUA_CMD_OBJCACHE_SIZE && 420 o->refcount == 1 && 421 (o->encoding == REDIS_ENCODING_RAW || 422 o->encoding == REDIS_ENCODING_EMBSTR) && 423 sdslen(o->ptr) <= LUA_CMD_OBJCACHE_MAX_LEN) 424 { 425 struct sdshdr *sh = (void*)(((char*)(o->ptr))-(sizeof(struct sdshdr))); 426 427 if (cached_objects[j]) decrRefCount(cached_objects[j]); 428 cached_objects[j] = o; 429 cached_objects_len[j] = sh->free + sh->len; 430 } else { 431 decrRefCount(o); 432 } 433 } 434 435 if (c->argv != argv) { 436 zfree(c->argv); 437 argv = NULL; 438 argv_size = 0; 439 } 440 441 if (raise_error) { 442 /* If we are here we should have an error in the stack, in the 443 * form of a table with an "err" field. Extract the string to 444 * return the plain error. */ 445 lua_pushstring(lua,"err"); 446 lua_gettable(lua,-2); 447 inuse--; 448 return lua_error(lua); 449 } 450 inuse--; 451 return 1; 452 } 453 454 int luaRedisCallCommand(lua_State *lua) { 455 return luaRedisGenericCommand(lua,1); 456 } 457 458 int luaRedisPCallCommand(lua_State *lua) { 459 return luaRedisGenericCommand(lua,0); 460 } 461 462 /* This adds redis.sha1hex(string) to Lua scripts using the same hashing 463 * function used for sha1ing lua scripts. */ 464 int luaRedisSha1hexCommand(lua_State *lua) { 465 int argc = lua_gettop(lua); 466 char digest[41]; 467 size_t len; 468 char *s; 469 470 if (argc != 1) { 471 luaPushError(lua, "wrong number of arguments"); 472 return 1; 473 } 474 475 s = (char*)lua_tolstring(lua,1,&len); 476 sha1hex(digest,s,len); 477 lua_pushstring(lua,digest); 478 return 1; 479 } 480 481 /* Returns a table with a single field 'field' set to the string value 482 * passed as argument. This helper function is handy when returning 483 * a Redis Protocol error or status reply from Lua: 484 * 485 * return redis.error_reply("ERR Some Error") 486 * return redis.status_reply("ERR Some Error") 487 */ 488 int luaRedisReturnSingleFieldTable(lua_State *lua, char *field) { 489 if (lua_gettop(lua) != 1 || lua_type(lua,-1) != LUA_TSTRING) { 490 luaPushError(lua, "wrong number or type of arguments"); 491 return 1; 492 } 493 494 lua_newtable(lua); 495 lua_pushstring(lua, field); 496 lua_pushvalue(lua, -3); 497 lua_settable(lua, -3); 498 return 1; 499 } 500 501 int luaRedisErrorReplyCommand(lua_State *lua) { 502 return luaRedisReturnSingleFieldTable(lua,"err"); 503 } 504 505 int luaRedisStatusReplyCommand(lua_State *lua) { 506 return luaRedisReturnSingleFieldTable(lua,"ok"); 507 } 508 509 int luaLogCommand(lua_State *lua) { 510 int j, argc = lua_gettop(lua); 511 int level; 512 sds log; 513 514 if (argc < 2) { 515 luaPushError(lua, "redis.log() requires two arguments or more."); 516 return 1; 517 } else if (!lua_isnumber(lua,-argc)) { 518 luaPushError(lua, "First argument must be a number (log level)."); 519 return 1; 520 } 521 level = lua_tonumber(lua,-argc); 522 if (level < REDIS_DEBUG || level > REDIS_WARNING) { 523 luaPushError(lua, "Invalid debug level."); 524 return 1; 525 } 526 527 /* Glue together all the arguments */ 528 log = sdsempty(); 529 for (j = 1; j < argc; j++) { 530 size_t len; 531 char *s; 532 533 s = (char*)lua_tolstring(lua,(-argc)+j,&len); 534 if (s) { 535 if (j != 1) log = sdscatlen(log," ",1); 536 log = sdscatlen(log,s,len); 537 } 538 } 539 redisLogRaw(level,log); 540 sdsfree(log); 541 return 0; 542 } 543 544 void luaMaskCountHook(lua_State *lua, lua_Debug *ar) { 545 long long elapsed; 546 REDIS_NOTUSED(ar); 547 REDIS_NOTUSED(lua); 548 549 elapsed = mstime() - server.lua_time_start; 550 if (elapsed >= server.lua_time_limit && server.lua_timedout == 0) { 551 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); 552 server.lua_timedout = 1; 553 /* Once the script timeouts we reenter the event loop to permit others 554 * to call SCRIPT KILL or SHUTDOWN NOSAVE if needed. For this reason 555 * we need to mask the client executing the script from the event loop. 556 * If we don't do that the client may disconnect and could no longer be 557 * here when the EVAL command will return. */ 558 aeDeleteFileEvent(server.el, server.lua_caller->fd, AE_READABLE); 559 } 560 if (server.lua_timedout) processEventsWhileBlocked(); 561 if (server.lua_kill) { 562 redisLog(REDIS_WARNING,"Lua script killed by user with SCRIPT KILL."); 563 lua_pushstring(lua,"Script killed by user with SCRIPT KILL..."); 564 lua_error(lua); 565 } 566 } 567 568 void luaLoadLib(lua_State *lua, const char *libname, lua_CFunction luafunc) { 569 lua_pushcfunction(lua, luafunc); 570 lua_pushstring(lua, libname); 571 lua_call(lua, 1, 0); 572 } 573 574 LUALIB_API int (luaopen_cjson) (lua_State *L); 575 LUALIB_API int (luaopen_struct) (lua_State *L); 576 LUALIB_API int (luaopen_cmsgpack) (lua_State *L); 577 LUALIB_API int (luaopen_bit) (lua_State *L); 578 579 void luaLoadLibraries(lua_State *lua) { 580 luaLoadLib(lua, "", luaopen_base); 581 luaLoadLib(lua, LUA_TABLIBNAME, luaopen_table); 582 luaLoadLib(lua, LUA_STRLIBNAME, luaopen_string); 583 luaLoadLib(lua, LUA_MATHLIBNAME, luaopen_math); 584 luaLoadLib(lua, LUA_DBLIBNAME, luaopen_debug); 585 luaLoadLib(lua, "cjson", luaopen_cjson); 586 luaLoadLib(lua, "struct", luaopen_struct); 587 luaLoadLib(lua, "cmsgpack", luaopen_cmsgpack); 588 luaLoadLib(lua, "bit", luaopen_bit); 589 590 #if 0 /* Stuff that we don't load currently, for sandboxing concerns. */ 591 luaLoadLib(lua, LUA_LOADLIBNAME, luaopen_package); 592 luaLoadLib(lua, LUA_OSLIBNAME, luaopen_os); 593 #endif 594 } 595 596 /* Remove a functions that we don't want to expose to the Redis scripting 597 * environment. */ 598 void luaRemoveUnsupportedFunctions(lua_State *lua) { 599 lua_pushnil(lua); 600 lua_setglobal(lua,"loadfile"); 601 } 602 603 /* This function installs metamethods in the global table _G that prevent 604 * the creation of globals accidentally. 605 * 606 * It should be the last to be called in the scripting engine initialization 607 * sequence, because it may interact with creation of globals. */ 608 void scriptingEnableGlobalsProtection(lua_State *lua) { 609 char *s[32]; 610 sds code = sdsempty(); 611 int j = 0; 612 613 /* strict.lua from: http://metalua.luaforge.net/src/lib/strict.lua.html. 614 * Modified to be adapted to Redis. */ 615 s[j++]="local mt = {}\n"; 616 s[j++]="setmetatable(_G, mt)\n"; 617 s[j++]="mt.__newindex = function (t, n, v)\n"; 618 s[j++]=" if debug.getinfo(2) then\n"; 619 s[j++]=" local w = debug.getinfo(2, \"S\").what\n"; 620 s[j++]=" if w ~= \"main\" and w ~= \"C\" then\n"; 621 s[j++]=" error(\"Script attempted to create global variable '\"..tostring(n)..\"'\", 2)\n"; 622 s[j++]=" end\n"; 623 s[j++]=" end\n"; 624 s[j++]=" rawset(t, n, v)\n"; 625 s[j++]="end\n"; 626 s[j++]="mt.__index = function (t, n)\n"; 627 s[j++]=" if debug.getinfo(2) and debug.getinfo(2, \"S\").what ~= \"C\" then\n"; 628 s[j++]=" error(\"Script attempted to access unexisting global variable '\"..tostring(n)..\"'\", 2)\n"; 629 s[j++]=" end\n"; 630 s[j++]=" return rawget(t, n)\n"; 631 s[j++]="end\n"; 632 s[j++]=NULL; 633 634 for (j = 0; s[j] != NULL; j++) code = sdscatlen(code,s[j],strlen(s[j])); 635 luaL_loadbuffer(lua,code,sdslen(code),"@enable_strict_lua"); 636 lua_pcall(lua,0,0,0); 637 sdsfree(code); 638 } 639 640 /* Initialize the scripting environment. 641 * It is possible to call this function to reset the scripting environment 642 * assuming that we call scriptingRelease() before. 643 * See scriptingReset() for more information. */ 644 void scriptingInit(void) { 645 lua_State *lua = lua_open(); 646 647 luaLoadLibraries(lua); 648 luaRemoveUnsupportedFunctions(lua); 649 650 /* Initialize a dictionary we use to map SHAs to scripts. 651 * This is useful for replication, as we need to replicate EVALSHA 652 * as EVAL, so we need to remember the associated script. */ 653 server.lua_scripts = dictCreate(&shaScriptObjectDictType,NULL); 654 655 /* Register the redis commands table and fields */ 656 lua_newtable(lua); 657 658 /* redis.call */ 659 lua_pushstring(lua,"call"); 660 lua_pushcfunction(lua,luaRedisCallCommand); 661 lua_settable(lua,-3); 662 663 /* redis.pcall */ 664 lua_pushstring(lua,"pcall"); 665 lua_pushcfunction(lua,luaRedisPCallCommand); 666 lua_settable(lua,-3); 667 668 /* redis.log and log levels. */ 669 lua_pushstring(lua,"log"); 670 lua_pushcfunction(lua,luaLogCommand); 671 lua_settable(lua,-3); 672 673 lua_pushstring(lua,"LOG_DEBUG"); 674 lua_pushnumber(lua,REDIS_DEBUG); 675 lua_settable(lua,-3); 676 677 lua_pushstring(lua,"LOG_VERBOSE"); 678 lua_pushnumber(lua,REDIS_VERBOSE); 679 lua_settable(lua,-3); 680 681 lua_pushstring(lua,"LOG_NOTICE"); 682 lua_pushnumber(lua,REDIS_NOTICE); 683 lua_settable(lua,-3); 684 685 lua_pushstring(lua,"LOG_WARNING"); 686 lua_pushnumber(lua,REDIS_WARNING); 687 lua_settable(lua,-3); 688 689 /* redis.sha1hex */ 690 lua_pushstring(lua, "sha1hex"); 691 lua_pushcfunction(lua, luaRedisSha1hexCommand); 692 lua_settable(lua, -3); 693 694 /* redis.error_reply and redis.status_reply */ 695 lua_pushstring(lua, "error_reply"); 696 lua_pushcfunction(lua, luaRedisErrorReplyCommand); 697 lua_settable(lua, -3); 698 lua_pushstring(lua, "status_reply"); 699 lua_pushcfunction(lua, luaRedisStatusReplyCommand); 700 lua_settable(lua, -3); 701 702 /* Finally set the table as 'redis' global var. */ 703 lua_setglobal(lua,"redis"); 704 705 /* Replace math.random and math.randomseed with our implementations. */ 706 lua_getglobal(lua,"math"); 707 708 lua_pushstring(lua,"random"); 709 lua_pushcfunction(lua,redis_math_random); 710 lua_settable(lua,-3); 711 712 lua_pushstring(lua,"randomseed"); 713 lua_pushcfunction(lua,redis_math_randomseed); 714 lua_settable(lua,-3); 715 716 lua_setglobal(lua,"math"); 717 718 /* Add a helper function that we use to sort the multi bulk output of non 719 * deterministic commands, when containing 'false' elements. */ 720 { 721 char *compare_func = "function __redis__compare_helper(a,b)\n" 722 " if a == false then a = '' end\n" 723 " if b == false then b = '' end\n" 724 " return a<b\n" 725 "end\n"; 726 luaL_loadbuffer(lua,compare_func,strlen(compare_func),"@cmp_func_def"); 727 lua_pcall(lua,0,0,0); 728 } 729 730 /* Add a helper function we use for pcall error reporting. 731 * Note that when the error is in the C function we want to report the 732 * information about the caller, that's what makes sense from the point 733 * of view of the user debugging a script. */ 734 { 735 char *errh_func = "function __redis__err__handler(err)\n" 736 " local i = debug.getinfo(2,'nSl')\n" 737 " if i and i.what == 'C' then\n" 738 " i = debug.getinfo(3,'nSl')\n" 739 " end\n" 740 " if i then\n" 741 " return i.source .. ':' .. i.currentline .. ': ' .. err\n" 742 " else\n" 743 " return err\n" 744 " end\n" 745 "end\n"; 746 luaL_loadbuffer(lua,errh_func,strlen(errh_func),"@err_handler_def"); 747 lua_pcall(lua,0,0,0); 748 } 749 750 /* Create the (non connected) client that we use to execute Redis commands 751 * inside the Lua interpreter. 752 * Note: there is no need to create it again when this function is called 753 * by scriptingReset(). */ 754 if (server.lua_client == NULL) { 755 server.lua_client = createClient(-1); 756 server.lua_client->flags |= REDIS_LUA_CLIENT; 757 } 758 759 /* Lua beginners often don't use "local", this is likely to introduce 760 * subtle bugs in their code. To prevent problems we protect accesses 761 * to global variables. */ 762 scriptingEnableGlobalsProtection(lua); 763 764 server.lua = lua; 765 } 766 767 /* Release resources related to Lua scripting. 768 * This function is used in order to reset the scripting environment. */ 769 void scriptingRelease(void) { 770 dictRelease(server.lua_scripts); 771 lua_close(server.lua); 772 } 773 774 void scriptingReset(void) { 775 scriptingRelease(); 776 scriptingInit(); 777 } 778 779 /* Perform the SHA1 of the input string. We use this both for hashing script 780 * bodies in order to obtain the Lua function name, and in the implementation 781 * of redis.sha1(). 782 * 783 * 'digest' should point to a 41 bytes buffer: 40 for SHA1 converted into an 784 * hexadecimal number, plus 1 byte for null term. */ 785 void sha1hex(char *digest, char *script, size_t len) { 786 SHA1_CTX ctx; 787 unsigned char hash[20]; 788 char *cset = "0123456789abcdef"; 789 int j; 790 791 SHA1Init(&ctx); 792 SHA1Update(&ctx,(unsigned char*)script,len); 793 SHA1Final(hash,&ctx); 794 795 for (j = 0; j < 20; j++) { 796 digest[j*2] = cset[((hash[j]&0xF0)>>4)]; 797 digest[j*2+1] = cset[(hash[j]&0xF)]; 798 } 799 digest[40] = '\0'; 800 } 801 802 void luaReplyToRedisReply(redisClient *c, lua_State *lua) { 803 int t = lua_type(lua,-1); 804 805 switch(t) { 806 case LUA_TSTRING: 807 addReplyBulkCBuffer(c,(char*)lua_tostring(lua,-1),lua_strlen(lua,-1)); 808 break; 809 case LUA_TBOOLEAN: 810 addReply(c,lua_toboolean(lua,-1) ? shared.cone : shared.nullbulk); 811 break; 812 case LUA_TNUMBER: 813 addReplyLongLong(c,(long long)lua_tonumber(lua,-1)); 814 break; 815 case LUA_TTABLE: 816 /* We need to check if it is an array, an error, or a status reply. 817 * Error are returned as a single element table with 'err' field. 818 * Status replies are returned as single element table with 'ok' field */ 819 lua_pushstring(lua,"err"); 820 lua_gettable(lua,-2); 821 t = lua_type(lua,-1); 822 if (t == LUA_TSTRING) { 823 sds err = sdsnew(lua_tostring(lua,-1)); 824 sdsmapchars(err,"\r\n"," ",2); 825 addReplySds(c,sdscatprintf(sdsempty(),"-%s\r\n",err)); 826 sdsfree(err); 827 lua_pop(lua,2); 828 return; 829 } 830 831 lua_pop(lua,1); 832 lua_pushstring(lua,"ok"); 833 lua_gettable(lua,-2); 834 t = lua_type(lua,-1); 835 if (t == LUA_TSTRING) { 836 sds ok = sdsnew(lua_tostring(lua,-1)); 837 sdsmapchars(ok,"\r\n"," ",2); 838 addReplySds(c,sdscatprintf(sdsempty(),"+%s\r\n",ok)); 839 sdsfree(ok); 840 lua_pop(lua,1); 841 } else { 842 void *replylen = addDeferredMultiBulkLength(c); 843 int j = 1, mbulklen = 0; 844 845 lua_pop(lua,1); /* Discard the 'ok' field value we popped */ 846 while(1) { 847 lua_pushnumber(lua,j++); 848 lua_gettable(lua,-2); 849 t = lua_type(lua,-1); 850 if (t == LUA_TNIL) { 851 lua_pop(lua,1); 852 break; 853 } 854 luaReplyToRedisReply(c, lua); 855 mbulklen++; 856 } 857 setDeferredMultiBulkLength(c,replylen,mbulklen); 858 } 859 break; 860 default: 861 addReply(c,shared.nullbulk); 862 } 863 lua_pop(lua,1); 864 } 865 866 /* Set an array of Redis String Objects as a Lua array (table) stored into a 867 * global variable. */ 868 void luaSetGlobalArray(lua_State *lua, char *var, robj **elev, int elec) { 869 int j; 870 871 lua_newtable(lua); 872 for (j = 0; j < elec; j++) { 873 lua_pushlstring(lua,(char*)elev[j]->ptr,sdslen(elev[j]->ptr)); 874 lua_rawseti(lua,-2,j+1); 875 } 876 lua_setglobal(lua,var); 877 } 878 879 /* Define a lua function with the specified function name and body. 880 * The function name musts be a 2 characters long string, since all the 881 * functions we defined in the Lua context are in the form: 882 * 883 * f_<hex sha1 sum> 884 * 885 * On success REDIS_OK is returned, and nothing is left on the Lua stack. 886 * On error REDIS_ERR is returned and an appropriate error is set in the 887 * client context. */ 888 int luaCreateFunction(redisClient *c, lua_State *lua, char *funcname, robj *body) { 889 sds funcdef = sdsempty(); 890 891 funcdef = sdscat(funcdef,"function "); 892 funcdef = sdscatlen(funcdef,funcname,42); 893 funcdef = sdscatlen(funcdef,"() ",3); 894 funcdef = sdscatlen(funcdef,body->ptr,sdslen(body->ptr)); 895 funcdef = sdscatlen(funcdef," end",4); 896 897 if (luaL_loadbuffer(lua,funcdef,sdslen(funcdef),"@user_script")) { 898 addReplyErrorFormat(c,"Error compiling script (new function): %s\n", 899 lua_tostring(lua,-1)); 900 lua_pop(lua,1); 901 sdsfree(funcdef); 902 return REDIS_ERR; 903 } 904 sdsfree(funcdef); 905 if (lua_pcall(lua,0,0,0)) { 906 addReplyErrorFormat(c,"Error running script (new function): %s\n", 907 lua_tostring(lua,-1)); 908 lua_pop(lua,1); 909 return REDIS_ERR; 910 } 911 912 /* We also save a SHA1 -> Original script map in a dictionary 913 * so that we can replicate / write in the AOF all the 914 * EVALSHA commands as EVAL using the original script. */ 915 { 916 int retval = dictAdd(server.lua_scripts, 917 sdsnewlen(funcname+2,40),body); 918 redisAssertWithInfo(c,NULL,retval == DICT_OK); 919 incrRefCount(body); 920 } 921 return REDIS_OK; 922 } 923 924 void evalGenericCommand(redisClient *c, int evalsha) { 925 lua_State *lua = server.lua; 926 char funcname[43]; 927 long long numkeys; 928 int delhook = 0, err; 929 930 /* We want the same PRNG sequence at every call so that our PRNG is 931 * not affected by external state. */ 932 redisSrand48(0); 933 934 /* We set this flag to zero to remember that so far no random command 935 * was called. This way we can allow the user to call commands like 936 * SRANDMEMBER or RANDOMKEY from Lua scripts as far as no write command 937 * is called (otherwise the replication and AOF would end with non 938 * deterministic sequences). 939 * 940 * Thanks to this flag we'll raise an error every time a write command 941 * is called after a random command was used. */ 942 server.lua_random_dirty = 0; 943 server.lua_write_dirty = 0; 944 945 /* Get the number of arguments that are keys */ 946 if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != REDIS_OK) 947 return; 948 if (numkeys > (c->argc - 3)) { 949 addReplyError(c,"Number of keys can't be greater than number of args"); 950 return; 951 } else if (numkeys < 0) { 952 addReplyError(c,"Number of keys can't be negative"); 953 return; 954 } 955 956 /* We obtain the script SHA1, then check if this function is already 957 * defined into the Lua state */ 958 funcname[0] = 'f'; 959 funcname[1] = '_'; 960 if (!evalsha) { 961 /* Hash the code if this is an EVAL call */ 962 sha1hex(funcname+2,c->argv[1]->ptr,sdslen(c->argv[1]->ptr)); 963 } else { 964 /* We already have the SHA if it is a EVALSHA */ 965 int j; 966 char *sha = c->argv[1]->ptr; 967 968 /* Convert to lowercase. We don't use tolower since the function 969 * managed to always show up in the profiler output consuming 970 * a non trivial amount of time. */ 971 for (j = 0; j < 40; j++) 972 funcname[j+2] = (sha[j] >= 'A' && sha[j] <= 'Z') ? 973 sha[j]+('a'-'A') : sha[j]; 974 funcname[42] = '\0'; 975 } 976 977 /* Push the pcall error handler function on the stack. */ 978 lua_getglobal(lua, "__redis__err__handler"); 979 980 /* Try to lookup the Lua function */ 981 lua_getglobal(lua, funcname); 982 if (lua_isnil(lua,-1)) { 983 lua_pop(lua,1); /* remove the nil from the stack */ 984 /* Function not defined... let's define it if we have the 985 * body of the function. If this is an EVALSHA call we can just 986 * return an error. */ 987 if (evalsha) { 988 lua_pop(lua,1); /* remove the error handler from the stack. */ 989 addReply(c, shared.noscripterr); 990 return; 991 } 992 if (luaCreateFunction(c,lua,funcname,c->argv[1]) == REDIS_ERR) { 993 lua_pop(lua,1); /* remove the error handler from the stack. */ 994 /* The error is sent to the client by luaCreateFunction() 995 * itself when it returns REDIS_ERR. */ 996 return; 997 } 998 /* Now the following is guaranteed to return non nil */ 999 lua_getglobal(lua, funcname); 1000 redisAssert(!lua_isnil(lua,-1)); 1001 } 1002 1003 /* Populate the argv and keys table accordingly to the arguments that 1004 * EVAL received. */ 1005 luaSetGlobalArray(lua,"KEYS",c->argv+3,numkeys); 1006 luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys); 1007 1008 /* Select the right DB in the context of the Lua client */ 1009 selectDb(server.lua_client,c->db->id); 1010 1011 /* Set a hook in order to be able to stop the script execution if it 1012 * is running for too much time. 1013 * We set the hook only if the time limit is enabled as the hook will 1014 * make the Lua script execution slower. */ 1015 server.lua_caller = c; 1016 server.lua_time_start = mstime(); 1017 server.lua_kill = 0; 1018 if (server.lua_time_limit > 0 && server.masterhost == NULL) { 1019 lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000); 1020 delhook = 1; 1021 } 1022 1023 /* At this point whether this script was never seen before or if it was 1024 * already defined, we can call it. We have zero arguments and expect 1025 * a single return value. */ 1026 err = lua_pcall(lua,0,1,-2); 1027 1028 /* Perform some cleanup that we need to do both on error and success. */ 1029 if (delhook) lua_sethook(lua,luaMaskCountHook,0,0); /* Disable hook */ 1030 if (server.lua_timedout) { 1031 server.lua_timedout = 0; 1032 /* Restore the readable handler that was unregistered when the 1033 * script timeout was detected. */ 1034 aeCreateFileEvent(server.el,c->fd,AE_READABLE, 1035 readQueryFromClient,c); 1036 } 1037 server.lua_caller = NULL; 1038 1039 /* Call the Lua garbage collector from time to time to avoid a 1040 * full cycle performed by Lua, which adds too latency. 1041 * 1042 * The call is performed every LUA_GC_CYCLE_PERIOD executed commands 1043 * (and for LUA_GC_CYCLE_PERIOD collection steps) because calling it 1044 * for every command uses too much CPU. */ 1045 #define LUA_GC_CYCLE_PERIOD 50 1046 { 1047 static long gc_count = 0; 1048 1049 gc_count++; 1050 if (gc_count == LUA_GC_CYCLE_PERIOD) { 1051 lua_gc(lua,LUA_GCSTEP,LUA_GC_CYCLE_PERIOD); 1052 gc_count = 0; 1053 } 1054 } 1055 1056 if (err) { 1057 addReplyErrorFormat(c,"Error running script (call to %s): %s\n", 1058 funcname, lua_tostring(lua,-1)); 1059 lua_pop(lua,2); /* Consume the Lua reply and remove error handler. */ 1060 } else { 1061 /* On success convert the Lua return value into Redis protocol, and 1062 * send it to * the client. */ 1063 luaReplyToRedisReply(c,lua); /* Convert and consume the reply. */ 1064 lua_pop(lua,1); /* Remove the error handler. */ 1065 } 1066 1067 /* EVALSHA should be propagated to Slave and AOF file as full EVAL, unless 1068 * we are sure that the script was already in the context of all the 1069 * attached slaves *and* the current AOF file if enabled. 1070 * 1071 * To do so we use a cache of SHA1s of scripts that we already propagated 1072 * as full EVAL, that's called the Replication Script Cache. 1073 * 1074 * For repliation, everytime a new slave attaches to the master, we need to 1075 * flush our cache of scripts that can be replicated as EVALSHA, while 1076 * for AOF we need to do so every time we rewrite the AOF file. */ 1077 if (evalsha) { 1078 if (!replicationScriptCacheExists(c->argv[1]->ptr)) { 1079 /* This script is not in our script cache, replicate it as 1080 * EVAL, then add it into the script cache, as from now on 1081 * slaves and AOF know about it. */ 1082 robj *script = dictFetchValue(server.lua_scripts,c->argv[1]->ptr); 1083 1084 replicationScriptCacheAdd(c->argv[1]->ptr); 1085 redisAssertWithInfo(c,NULL,script != NULL); 1086 rewriteClientCommandArgument(c,0, 1087 resetRefCount(createStringObject("EVAL",4))); 1088 rewriteClientCommandArgument(c,1,script); 1089 forceCommandPropagation(c,REDIS_PROPAGATE_REPL|REDIS_PROPAGATE_AOF); 1090 } 1091 } 1092 } 1093 1094 void evalCommand(redisClient *c) { 1095 evalGenericCommand(c,0); 1096 } 1097 1098 void evalShaCommand(redisClient *c) { 1099 if (sdslen(c->argv[1]->ptr) != 40) { 1100 /* We know that a match is not possible if the provided SHA is 1101 * not the right length. So we return an error ASAP, this way 1102 * evalGenericCommand() can be implemented without string length 1103 * sanity check */ 1104 addReply(c, shared.noscripterr); 1105 return; 1106 } 1107 evalGenericCommand(c,1); 1108 } 1109 1110 /* We replace math.random() with our implementation that is not affected 1111 * by specific libc random() implementations and will output the same sequence 1112 * (for the same seed) in every arch. */ 1113 1114 /* The following implementation is the one shipped with Lua itself but with 1115 * rand() replaced by redisLrand48(). */ 1116 int redis_math_random (lua_State *L) { 1117 /* the `%' avoids the (rare) case of r==1, and is needed also because on 1118 some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */ 1119 lua_Number r = (lua_Number)(redisLrand48()%REDIS_LRAND48_MAX) / 1120 (lua_Number)REDIS_LRAND48_MAX; 1121 switch (lua_gettop(L)) { /* check number of arguments */ 1122 case 0: { /* no arguments */ 1123 lua_pushnumber(L, r); /* Number between 0 and 1 */ 1124 break; 1125 } 1126 case 1: { /* only upper limit */ 1127 int u = luaL_checkint(L, 1); 1128 luaL_argcheck(L, 1<=u, 1, "interval is empty"); 1129 lua_pushnumber(L, floor(r*u)+1); /* int between 1 and `u' */ 1130 break; 1131 } 1132 case 2: { /* lower and upper limits */ 1133 int l = luaL_checkint(L, 1); 1134 int u = luaL_checkint(L, 2); 1135 luaL_argcheck(L, l<=u, 2, "interval is empty"); 1136 lua_pushnumber(L, floor(r*(u-l+1))+l); /* int between `l' and `u' */ 1137 break; 1138 } 1139 default: return luaL_error(L, "wrong number of arguments"); 1140 } 1141 return 1; 1142 } 1143 1144 int redis_math_randomseed (lua_State *L) { 1145 redisSrand48(luaL_checkint(L, 1)); 1146 return 0; 1147 } 1148 1149 /* --------------------------------------------------------------------------- 1150 * SCRIPT command for script environment introspection and control 1151 * ------------------------------------------------------------------------- */ 1152 1153 void scriptCommand(redisClient *c) { 1154 if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"flush")) { 1155 scriptingReset(); 1156 addReply(c,shared.ok); 1157 replicationScriptCacheFlush(); 1158 server.dirty++; /* Propagating this command is a good idea. */ 1159 } else if (c->argc >= 2 && !strcasecmp(c->argv[1]->ptr,"exists")) { 1160 int j; 1161 1162 addReplyMultiBulkLen(c, c->argc-2); 1163 for (j = 2; j < c->argc; j++) { 1164 if (dictFind(server.lua_scripts,c->argv[j]->ptr)) 1165 addReply(c,shared.cone); 1166 else 1167 addReply(c,shared.czero); 1168 } 1169 } else if (c->argc == 3 && !strcasecmp(c->argv[1]->ptr,"load")) { 1170 char funcname[43]; 1171 sds sha; 1172 1173 funcname[0] = 'f'; 1174 funcname[1] = '_'; 1175 sha1hex(funcname+2,c->argv[2]->ptr,sdslen(c->argv[2]->ptr)); 1176 sha = sdsnewlen(funcname+2,40); 1177 if (dictFind(server.lua_scripts,sha) == NULL) { 1178 if (luaCreateFunction(c,server.lua,funcname,c->argv[2]) 1179 == REDIS_ERR) { 1180 sdsfree(sha); 1181 return; 1182 } 1183 } 1184 addReplyBulkCBuffer(c,funcname+2,40); 1185 sdsfree(sha); 1186 forceCommandPropagation(c,REDIS_PROPAGATE_REPL|REDIS_PROPAGATE_AOF); 1187 } else if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"kill")) { 1188 if (server.lua_caller == NULL) { 1189 addReplySds(c,sdsnew("-NOTBUSY No scripts in execution right now.\r\n")); 1190 } else if (server.lua_write_dirty) { 1191 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")); 1192 } else { 1193 server.lua_kill = 1; 1194 addReply(c,shared.ok); 1195 } 1196 } else { 1197 addReplyError(c, "Unknown SCRIPT subcommand or wrong # of args."); 1198 } 1199 } 1200