lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Luiz Henrique de Figueiredo wrote:
>> I guess I don't consider that a use case for s:format("%q") but rather a
>> use case for io.write('[[' .. s .. ']]').

> If s comes from user input, then this is unsafe if later loaded back into Lua:
> s might be "]]; MALICIOUS CODE HERE ; [[" or something like that.

It would be too complex to have a '%Q' format that automatically escaped
'[-*[', otherwise Q could be q's big sister, just like [[]] are to '".

For anyone interested I've attached a patch for lstrlib.c that will
allow use of '%Q' to mean "escape newlines, too".

Doug

-- 
Innovative Concepts, Inc. www.innocon.com 703-893-2007 x220
diff -r -u lua-5.1.3-orig/src/lstrlib.c lua-5.1.3/src/lstrlib.c
--- lua-5.1.3-orig/src/lstrlib.c	2007-12-28 10:32:23.000000000 -0500
+++ lua-5.1.3/src/lstrlib.c	2008-02-21 14:01:20.000000000 -0500
@@ -692,7 +692,7 @@
 #define MAX_FORMAT	(sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
 
 
-static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
+static void addquoted (lua_State *L, luaL_Buffer *b, int arg, int nlescape) {
   size_t l;
   const char *s = luaL_checklstring(L, arg, &l);
   luaL_addchar(b, '"');
@@ -700,7 +700,7 @@
     switch (*s) {
       case '"': case '\\': case '\n': {
         luaL_addchar(b, '\\');
-        luaL_addchar(b, *s);
+        luaL_addchar(b, nlescape ? 'n' : *s);
         break;
       }
       case '\r': {
@@ -789,8 +789,8 @@
           sprintf(buff, form, (double)luaL_checknumber(L, arg));
           break;
         }
-        case 'q': {
-          addquoted(L, &b, arg);
+        case 'q': case 'Q': {
+          addquoted(L, &b, arg, *(strfrmt-1) == 'Q');
           continue;  /* skip the 'addsize' at the end */
         }
         case 's': {