[nginx] Core: improved JSON escaping.

Valentin Bartenev vbart at nginx.com
Wed Apr 12 19:48:13 UTC 2017


details:   http://hg.nginx.org/nginx/rev/289403abc84e
branches:  
changeset: 6974:289403abc84e
user:      Valentin Bartenev <vbart at nginx.com>
date:      Wed Apr 12 22:47:57 2017 +0300
description:
Core: improved JSON escaping.

Two-character representations are now used for \b, \f, \n, \r, and \t.

diffstat:

 src/core/ngx_string.c |  51 ++++++++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 44 insertions(+), 7 deletions(-)

diffs (68 lines):

diff -r 99934aade555 -r 289403abc84e src/core/ngx_string.c
--- a/src/core/ngx_string.c	Wed Apr 12 22:21:04 2017 +0300
+++ b/src/core/ngx_string.c	Wed Apr 12 22:47:57 2017 +0300
@@ -1808,7 +1808,19 @@ ngx_escape_json(u_char *dst, u_char *src
                 len++;
 
             } else if (ch <= 0x1f) {
-                len += sizeof("\\u001F") - 2;
+
+                switch (ch) {
+                case '\n':
+                case '\r':
+                case '\t':
+                case '\b':
+                case '\f':
+                    len++;
+                    break;
+
+                default:
+                    len += sizeof("\\u001F") - 2;
+                }
             }
 
             size--;
@@ -1829,12 +1841,37 @@ ngx_escape_json(u_char *dst, u_char *src
             *dst++ = ch;
 
         } else {
-            *dst++ = '\\'; *dst++ = 'u'; *dst++ = '0'; *dst++ = '0';
-            *dst++ = '0' + (ch >> 4);
-
-            ch &= 0xf;
-
-            *dst++ = (ch < 10) ? ('0' + ch) : ('A' + ch - 10);
+            *dst++ = '\\';
+
+            switch (ch) {
+            case '\n':
+                *dst++ = 'n';
+                break;
+
+            case '\r':
+                *dst++ = 'r';
+                break;
+
+            case '\t':
+                *dst++ = 't';
+                break;
+
+            case '\b':
+                *dst++ = 'b';
+                break;
+
+            case '\f':
+                *dst++ = 'f';
+                break;
+
+            default:
+                *dst++ = 'u'; *dst++ = '0'; *dst++ = '0';
+                *dst++ = '0' + (ch >> 4);
+
+                ch &= 0xf;
+
+                *dst++ = (ch < 10) ? ('0' + ch) : ('A' + ch - 10);
+            }
         }
 
         size--;


More information about the nginx-devel mailing list