SPDX: license tags (mostly by guesswork)
[exim.git] / src / src / lookups / lf_quote.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
7 /* SPDX-License-Identifier: GPL-2.0-only */
8
9
10 #include "../exim.h"
11 #include "lf_functions.h"
12
13
14 /*************************************************
15 *   Add string to result, quoting if necessary   *
16 *************************************************/
17
18 /* This function is called by some lookups that create name=value result
19 strings, to handle the quoting of the data. It adds "name=" to the result,
20 followed by appropriately quoted data, followed by a single space.
21
22 Arguments:
23   name           the field name
24   value          the data value
25   vlength        the data length
26   result         the result expanding-string
27
28 Returns:         the result pointer (possibly updated)
29 */
30
31 gstring *
32 lf_quote(uschar *name, uschar *value, int vlength, gstring * result)
33 {
34 result = string_append(result, 2, name, US"=");
35
36 /* NULL is handled as an empty string */
37
38 if (!value)
39   {
40   value = US"";
41   vlength = 0;
42   }
43
44 /* Quote the value if it is empty, contains white space, or starts with a quote
45 character. */
46
47 if (value[0] == 0 || Ustrpbrk(value, " \t\n\r") != NULL || value[0] == '\"')
48   {
49   result = string_catn(result, US"\"", 1);
50   for (int j = 0; j < vlength; j++)
51     {
52     if (value[j] == '\"' || value[j] == '\\')
53       result = string_catn(result, US"\\", 1);
54     result = string_catn(result, US value+j, 1);
55     }
56   result = string_catn(result, US"\"", 1);
57   }
58 else
59   result = string_catn(result, US value, vlength);
60
61 return string_catn(result, US" ", 1);
62 }
63
64 /* End of lf_quote.c */