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