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