Quoting.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
3  *
4  * Squid software is distributed under GPLv2+ license and includes
5  * contributions from numerous individuals and organizations.
6  * Please see the COPYING and CONTRIBUTORS files for details.
7  */
8 
9 #include "squid.h"
10 #include "html/Quoting.h"
11 #include "sbuf/SBuf.h"
12 
13 #include <array>
14 #include <cstring>
15 
16 static const auto &
18 {
19  static auto escapeMap = new std::array<SBuf, 256> {};
20  auto &em = *escapeMap;
21  if (!em['<'].isEmpty())
22  return em;
23 
24  // Encode control chars just to be on the safe side and make sure all 8-bit
25  // characters are encoded to protect from buggy clients.
26  for (int ch = 0; ch < 256; ++ch) {
27  if ((ch <= 0x1F || ch >= 0x7f) && ch != '\n' && ch != '\r' && ch != '\t') {
28  em[ch] = SBuf().Printf("&#%d;", ch);
29  }
30  }
31 
32  em['<'] = "&lt;";
33  em['>'] = "&gt;";
34  em['"'] = "&quot;";
35  em['&'] = "&amp;";
36  em['\''] = "&apos;";
37 
38  return em;
39 }
40 
41 char *
42 html_quote(const char *string)
43 {
44  static const auto &escapeSequences = EscapeSequences();
45  static char *buf = nullptr;
46  static size_t bufsize = 0;
47  const char *src;
48  char *dst;
49 
50  /* XXX This really should be implemented using a MemPool, but
51  * MemPools are not yet available in lib...
52  */
53  if (!buf || strlen(string) * 6 > bufsize) {
54  xfree(buf);
55  bufsize = strlen(string) * 6 + 1;
56  buf = static_cast<char *>(xcalloc(bufsize, 1));
57  }
58  for (src = string, dst = buf; *src; src++) {
59  const unsigned char ch = *src;
60 
61  const auto &escape = escapeSequences[ch];
62  if (!escape.isEmpty()) {
63  /* Ok, An escaped form was found above. Use it */
64  escape.copy(dst, 7);
65  dst += escape.length();
66  } else {
67  /* Apparently there is no need to escape this character */
68  *dst++ = ch;
69  }
70  }
71  /* Nullterminate and return the result */
72  *dst = '\0';
73  return (buf);
74 }
75 
void * xcalloc(size_t n, size_t sz)
Definition: xalloc.cc:71
static const auto & EscapeSequences()
Definition: Quoting.cc:17
Definition: SBuf.h:93
char * html_quote(const char *string)
Definition: Quoting.cc:42
SBuf & Printf(const char *fmt,...) PRINTF_FORMAT_ARG2
Definition: SBuf.cc:214
#define xfree

 

Introduction

Documentation

Support

Miscellaneous