From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on inbox.vuxu.org X-Spam-Level: X-Spam-Status: No, score=0.0 required=5.0 tests=none autolearn=ham autolearn_force=no version=3.4.4 Received: (qmail 3929 invoked from network); 18 Nov 2022 04:34:17 -0000 Received: from 9front.inri.net (168.235.81.73) by inbox.vuxu.org with ESMTPUTF8; 18 Nov 2022 04:34:17 -0000 Received: from mimir.eigenstate.org ([206.124.132.107]) by 9front; Thu Nov 17 23:30:15 -0500 2022 Received: from abbatoir (pool-108-27-53-161.nycmny.fios.verizon.net [108.27.53.161]) by mimir.eigenstate.org (OpenSMTPD) with ESMTPSA id c4d32079 (TLSv1.2:ECDHE-RSA-AES256-SHA:256:NO) for <9front@9front.org>; Thu, 17 Nov 2022 20:30:14 -0800 (PST) Message-ID: <4F579BAA82A5A3386F286262ED2A7806@eigenstate.org> To: 9front@9front.org Date: Thu, 17 Nov 2022 23:30:12 -0500 From: ori@eigenstate.org In-Reply-To: <923270033661C2AB404C7473549B4808@driusan.net> MIME-Version: 1.0 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit List-ID: <9front.9front.org> List-Help: X-Glyph: ➈ X-Bullshit: RESTful API-based database Subject: Re: [9front] libjson can print invalid json Reply-To: 9front@9front.org Precedence: bulk Quoth Dave MacFarlane : > print("%J", json); can print invalid json if a JSON string in the object has a quotation mark in it. > > I just threw together this patch to try and escape the strings from printjson() if anyone's interested > in it. > > diff 30c5296f32b87d83529d772732726891e1261c9c uncommitted > --- a/sys/src/libjson/printjson.c > +++ b/sys/src/libjson/printjson.c > @@ -52,6 +52,38 @@ > } > > static int > +printstring(Fmt *f, char *s) > +{ > + int slen = strlen(s); > + int i, nq=0; > + int r; > + char *dup, lastq; > + for(i = 0; i < slen; i++) > + if (s[i] == '"') nq++; > + > + if (nq == 0) > + return fmtprint(f, "\"%s\"", s); > + > + r = fmtprint(f, "\""); > + > + dup = strdup(s); > + lastq = -1; > + for(i = 0; i < slen; i++){ > + if(dup[i] == '"') { > + dup[i] = 0; > + r += fmtprint(f, "%s\\\"", &dup[lastq+1]); > + lastq = i; > + } > + } > + > + if (lastq != slen-1) > + r += fmtprint(f, "%s", &dup[lastq+1]); > + r += fmtprint(f, "\""); > + free(dup); > + return r; > +} > + I think we have a problem with more than just quotes; we're not allowed any control characters, and we need to escape '\'; how's something like this (untested)? static int printstring(Fmt *f, char *s) { int n; n = 0; for(; *s; s++){ switch(*s){ case '\\': n += fmtstrcpy(f, "\\\\"); break; case '\f': n += fmtstrcpy(f, "\\f"); break; case '\b': n += fmtstrcpy(f, "\\b"); break; case '\n': n += fmtstrcpy(f, "\\n"); break; case '\r': n += fmtstrcpy(f, "\\r"); break; case '\"': n += fmtstrcpy(f, "\\\""); break; default: if(*s < 0x20) n += fmtprint(f, "\\u%04x", *s); else n += fmtrune(f, *s); } } return n; }