readsocket expansion: response caching
[exim.git] / src / src / expand.c
index 55aaf53cab2c49e5bb745a6fc1552f8ba053e068..5ae74ef52c3555a92f437b260aa041d70eaf3d75 100644 (file)
@@ -117,6 +117,7 @@ static uschar *item_table[] = {
 #endif
   US"length",
   US"listextract",
+  US"listquote",
   US"lookup",
   US"map",
   US"nhash",
@@ -151,6 +152,7 @@ enum {
 #endif
   EITEM_LENGTH,
   EITEM_LISTEXTRACT,
+  EITEM_LISTQUOTE,
   EITEM_LOOKUP,
   EITEM_MAP,
   EITEM_NHASH,
@@ -466,6 +468,7 @@ typedef struct {
 
 static uschar * fn_recipients(void);
 typedef uschar * stringptr_fn_t(void);
+static uschar * fn_queue_size(void);
 
 /* This table must be kept in alphabetical order. */
 
@@ -588,7 +591,9 @@ static var_entry var_table[] = {
   { "local_part",          vtype_stringptr,   &deliver_localpart },
   { "local_part_data",     vtype_stringptr,   &deliver_localpart_data },
   { "local_part_prefix",   vtype_stringptr,   &deliver_localpart_prefix },
+  { "local_part_prefix_v", vtype_stringptr,   &deliver_localpart_prefix_v },
   { "local_part_suffix",   vtype_stringptr,   &deliver_localpart_suffix },
+  { "local_part_suffix_v", vtype_stringptr,   &deliver_localpart_suffix_v },
   { "local_part_verified", vtype_stringptr,   &deliver_localpart_verified },
 #ifdef HAVE_LOCAL_SCAN
   { "local_scan_data",     vtype_stringptr,   &local_scan_data },
@@ -669,6 +674,7 @@ static var_entry var_table[] = {
   { "qualify_domain",      vtype_stringptr,   &qualify_domain_sender },
   { "qualify_recipient",   vtype_stringptr,   &qualify_domain_recipient },
   { "queue_name",          vtype_stringptr,   &queue_name },
+  { "queue_size",          vtype_string_func, &fn_queue_size },
   { "rcpt_count",          vtype_int,         &rcpt_count },
   { "rcpt_defer_count",    vtype_int,         &rcpt_defer_count },
   { "rcpt_fail_count",     vtype_int,         &rcpt_fail_count },
@@ -1170,7 +1176,7 @@ static uschar *
 expand_getkeyed(uschar * key, const uschar * s)
 {
 int length = Ustrlen(key);
-while (isspace(*s)) s++;
+Uskip_whitespace(&s);
 
 /* Loop to search for the key */
 
@@ -1182,14 +1188,13 @@ while (*s)
 
   while (*s && *s != '=' && !isspace(*s)) s++;
   dkeylength = s - dkey;
-  while (isspace(*s)) s++;
-  if (*s == '=') while (isspace((*(++s))));
+  if (Uskip_whitespace(&s) == '=') while (isspace(*++s));
 
   data = string_dequote(&s);
   if (length == dkeylength && strncmpic(key, dkey, length) == 0)
     return data;
 
-  while (isspace(*s)) s++;
+  Uskip_whitespace(&s);
   }
 
 return NULL;
@@ -1609,7 +1614,7 @@ for (header_line * h = header_list; h; h = h->next)
       found = TRUE;
       s = h->text + len;               /* text to insert */
       if (!(flags & FH_WANT_RAW))      /* unless wanted raw, */
-       while (isspace(*s)) s++;        /* remove leading white space */
+       Uskip_whitespace(&s);           /* remove leading white space */
       t = h->text + h->slen;           /* end-point */
 
       /* Unless wanted raw, remove trailing whitespace, including the
@@ -1630,8 +1635,8 @@ for (header_line * h = header_list; h; h = h->next)
 
       /* Trim the header roughly if we're approaching limits */
       inc = t - s;
-      if ((g ? g->ptr : 0) + inc > header_insert_maxlen)
-       inc = header_insert_maxlen - (g ? g->ptr : 0);
+      if (gstring_length(g) + inc > header_insert_maxlen)
+       inc = header_insert_maxlen - gstring_length(g);
 
       /* For raw just copy the data; for a list, add the data as a colon-sep
       list-element; for comma-list add as an unchecked comma,newline sep
@@ -1643,17 +1648,12 @@ for (header_line * h = header_list; h; h = h->next)
       if (flags & FH_WANT_LIST)
         g = string_append_listele_n(g, ':', s, (unsigned)inc);
       else if (flags & FH_WANT_RAW)
-       {
        g = string_catn(g, s, (unsigned)inc);
-       (void) string_from_gstring(g);
-       }
       else if (inc > 0)
-       if (comma)
-         g = string_append2_listele_n(g, US",\n", s, (unsigned)inc);
-       else
-         g = string_append2_listele_n(g, US"\n", s, (unsigned)inc);
+       g = string_append2_listele_n(g, comma ? US",\n" : US"\n",
+         s, (unsigned)inc);
 
-      if (g && g->ptr >= header_insert_maxlen) break;
+      if (gstring_length(g) >= header_insert_maxlen) break;
       }
 
 if (!found) return NULL;       /* No header found */
@@ -1663,7 +1663,7 @@ if (!g) return US"";
 
 *newsize = g->size;
 if (flags & FH_WANT_RAW)
-  return g->s;
+  return string_from_gstring(g);
 
 /* Otherwise do RFC 2047 decoding, translating the charset if requested.
 The rfc2047_decode2() function can return an error with decoded data if the
@@ -1671,16 +1671,12 @@ charset translation fails. If decoding fails, it returns NULL. */
 
 else
   {
-  uschar *decoded, *error;
-
-  decoded = rfc2047_decode2(g->s, check_rfc2047_length, charset, '?', NULL,
-    newsize, &error);
+  uschar * error, * decoded = rfc2047_decode2(string_from_gstring(g),
+    check_rfc2047_length, charset, '?', NULL, newsize, &error);
   if (error)
-    {
     DEBUG(D_any) debug_printf("*** error in RFC 2047 decoding: %s\n"
       "    input was: %s\n", error, g->s);
-    }
-  return decoded ? decoded : g->s;
+  return decoded ? decoded : string_from_gstring(g);
   }
 }
 
@@ -1749,6 +1745,94 @@ return g ? g->s : NULL;
 }
 
 
+/*************************************************
+*               Return size of queue             *
+*************************************************/
+/* Ask the daemon for the queue size */
+
+static uschar *
+fn_queue_size(void)
+{
+struct sockaddr_un sa_un = {.sun_family = AF_UNIX};
+uschar buf[16];
+int fd;
+ssize_t len;
+const uschar * where;
+#ifndef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
+uschar * sname;
+#endif
+fd_set fds;
+struct timeval tv;
+
+if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
+  {
+  DEBUG(D_expand) debug_printf(" socket: %s\n", strerror(errno));
+  return NULL;
+  }
+
+#ifdef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
+sa_un.sun_path[0] = 0; /* Abstract local socket addr - Linux-specific? */
+len = offsetof(struct sockaddr_un, sun_path) + 1
+  + snprintf(sa_un.sun_path+1, sizeof(sa_un.sun_path)-1, "exim_%d", getpid());
+#else
+sname = string_sprintf("%s/p_%d", spool_directory, getpid());
+len = offsetof(struct sockaddr_un, sun_path)
+  + snprintf(sa_un.sun_path, sizeof(sa_un.sun_path), "%s", sname);
+#endif
+
+if (bind(fd, (const struct sockaddr *)&sa_un, len) < 0)
+  { where = US"bind"; goto bad; }
+
+#ifdef notdef
+debug_printf("local addr '%s%s'\n",
+  *sa_un.sun_path ? "" : "@",
+  sa_un.sun_path + (*sa_un.sun_path ? 0 : 1));
+#endif
+
+#ifdef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
+sa_un.sun_path[0] = 0; /* Abstract local socket addr - Linux-specific? */
+len = offsetof(struct sockaddr_un, sun_path) + 1
+  + snprintf(sa_un.sun_path+1, sizeof(sa_un.sun_path)-1, "%s",
+             expand_string(notifier_socket));
+#else
+len = offsetof(struct sockaddr_un, sun_path)
+  + snprintf(sa_un.sun_path, sizeof(sa_un.sun_path), "%s",
+             expand_string(notifier_socket));
+#endif
+
+if (connect(fd, (const struct sockaddr *)&sa_un, len) < 0)
+  { where = US"connect"; goto bad2; }
+
+buf[0] = NOTIFY_QUEUE_SIZE_REQ;
+if (send(fd, buf, 1, 0) < 0) { where = US"send"; goto bad; }
+
+FD_ZERO(&fds); FD_SET(fd, &fds);
+tv.tv_sec = 2; tv.tv_usec = 0;
+if (select(fd + 1, (SELECT_ARG2_TYPE *)&fds, NULL, NULL, &tv) != 1)
+  {
+  DEBUG(D_expand) debug_printf("no daemon response; using local evaluation\n");
+  len = snprintf(CS buf, sizeof(buf), "%u", queue_count_cached());
+  }
+else if ((len = recv(fd, buf, sizeof(buf), 0)) < 0)
+  { where = US"recv"; goto bad2; }
+
+close(fd);
+#ifndef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
+Uunlink(sname);
+#endif
+return string_copyn(buf, len);
+
+bad2:
+#ifndef EXIM_HAVE_ABSTRACT_UNIX_SOCKETS
+  Uunlink(sname);
+#endif
+bad:
+  close(fd);
+  DEBUG(D_expand) debug_printf(" %s: %s\n", where, strerror(errno));
+  return NULL;
+}
+
+
 /*************************************************
 *               Find value of a variable         *
 *************************************************/
@@ -1961,7 +2045,7 @@ switch (vp->type)
     s = find_header(US"reply-to:", newsize,
                exists_only ? FH_EXISTS_ONLY|FH_WANT_RAW : FH_WANT_RAW,
                headers_charset);
-    if (s) while (isspace(*s)) s++;
+    if (s) Uskip_whitespace(&s);
     if (!s || !*s)
       {
       *newsize = 0;                            /* For the *s==0 case */
@@ -1972,8 +2056,8 @@ switch (vp->type)
     if (s)
       {
       uschar *t;
-      while (isspace(*s)) s++;
-      for (t = s; *t != 0; t++) if (*t == '\n') *t = ' ';
+      Uskip_whitespace(&s);
+      for (t = s; *t; t++) if (*t == '\n') *t = ' ';
       while (t > s && isspace(t[-1])) t--;
       *t = 0;
       }
@@ -2061,7 +2145,7 @@ read_subs(uschar **sub, int n, int m, const uschar **sptr, BOOL skipping,
 {
 const uschar *s = *sptr;
 
-while (isspace(*s)) s++;
+Uskip_whitespace(&s);
 for (int i = 0; i < n; i++)
   {
   if (*s != '{')
@@ -2078,7 +2162,7 @@ for (int i = 0; i < n; i++)
   if (!(sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, resetok)))
     return 3;
   if (*s++ != '}') return 1;
-  while (isspace(*s)) s++;
+  Uskip_whitespace(&s);
   }
 if (check_end && *s++ != '}')
   {
@@ -2201,9 +2285,7 @@ uschar * p = s;
 unsigned depth = 0;
 BOOL quotesmode = wrap[0] == wrap[1];
 
-while (isspace(*p)) p++;
-
-if (*p == *wrap)
+if (Uskip_whitespace(&p) == *wrap)
   {
   s = ++p;
   wrap++;
@@ -2240,7 +2322,7 @@ json_nextinlist(const uschar ** list)
 unsigned array_depth = 0, object_depth = 0;
 const uschar * s = *list, * item;
 
-while (isspace(*s)) s++;
+skip_whitespace(&s);
 
 for (item = s;
      *s && (*s != ',' || array_depth != 0 || object_depth != 0);
@@ -2470,10 +2552,7 @@ const pcre *re;
 const uschar *rerror;
 
 for (;;)
-  {
-  while (isspace(*s)) s++;
-  if (*s == '!') { testfor = !testfor; s++; } else break;
-  }
+  if (Uskip_whitespace(&s) == '!') { testfor = !testfor; s++; } else break;
 
 switch(cond_type = identify_operator(&s, &opname))
   {
@@ -2562,8 +2641,7 @@ switch(cond_type = identify_operator(&s, &opname))
   case ECOND_LDAPAUTH:
   case ECOND_PWCHECK:
 
-  while (isspace(*s)) s++;
-  if (*s != '{') goto COND_FAILED_CURLY_START;         /* }-for-text-editors */
+  if (Uskip_whitespace(&s) != '{') goto COND_FAILED_CURLY_START; /* }-for-text-editors */
 
   sub[0] = expand_string_internal(s+1, TRUE, &s, yield == NULL, TRUE, resetok);
   if (!sub[0]) return NULL;
@@ -2660,11 +2738,11 @@ switch(cond_type = identify_operator(&s, &opname))
     uschar *user_msg;
     BOOL cond = FALSE;
 
-    while (isspace(*s)) s++;
+    Uskip_whitespace(&s);
     if (*s++ != '{') goto COND_FAILED_CURLY_START;     /*}*/
 
     switch(read_subs(sub, nelem(sub), 1,
-      &s, yield == NULL, TRUE, US"acl", resetok))
+      &s, yield == NULL, TRUE, name, resetok))
       {
       case 1: expand_string_message = US"too few arguments or bracketing "
         "error for acl";
@@ -2713,9 +2791,9 @@ switch(cond_type = identify_operator(&s, &opname))
 #else
     {
     uschar *sub[4];
-    while (isspace(*s)) s++;
+    Uskip_whitespace(&s);
     if (*s++ != '{') goto COND_FAILED_CURLY_START;     /* }-for-text-editors */
-    switch(read_subs(sub, nelem(sub), 2, &s, yield == NULL, TRUE, US"saslauthd",
+    switch(read_subs(sub, nelem(sub), 2, &s, yield == NULL, TRUE, name,
                    resetok))
       {
       case 1: expand_string_message = US"too few arguments or bracketing "
@@ -2791,8 +2869,7 @@ switch(cond_type = identify_operator(&s, &opname))
     if ((i > 0) && !sub2_honour_dollar)
       honour_dollar = FALSE;
 
-    while (isspace(*s)) s++;
-    if (*s != '{')
+    if (Uskip_whitespace(&s) != '{')
       {
       if (i == 0) goto COND_FAILED_CURLY_START;
       expand_string_message = string_sprintf("missing 2nd string in {} "
@@ -3153,14 +3230,13 @@ switch(cond_type = identify_operator(&s, &opname))
   subcondptr = (yield == NULL) ? NULL : &tempcond;
   combined_cond = (cond_type == ECOND_AND);
 
-  while (isspace(*s)) s++;
+  Uskip_whitespace(&s);
   if (*s++ != '{') goto COND_FAILED_CURLY_START;       /* }-for-text-editors */
 
   for (;;)
     {
-    while (isspace(*s)) s++;
     /* {-for-text-editors */
-    if (*s == '}') break;
+    if (Uskip_whitespace(&s) == '}') break;
     if (*s != '{')                                     /* }-for-text-editors */
       {
       expand_string_message = string_sprintf("each subcondition "
@@ -3174,7 +3250,7 @@ switch(cond_type = identify_operator(&s, &opname))
         expand_string_message, opname);
       return NULL;
       }
-    while (isspace(*s)) s++;
+    Uskip_whitespace(&s);
 
     /* {-for-text-editors */
     if (*s++ != '}')
@@ -3219,14 +3295,14 @@ switch(cond_type = identify_operator(&s, &opname))
 
     DEBUG(D_expand) debug_printf_indent("condition: %s\n", opname);
 
-    while (isspace(*s)) s++;
+    Uskip_whitespace(&s);
     if (*s++ != '{') goto COND_FAILED_CURLY_START;     /* }-for-text-editors */
     if (!(sub[0] = expand_string_internal(s, TRUE, &s, yield == NULL, TRUE, resetok)))
       return NULL;
     /* {-for-text-editors */
     if (*s++ != '}') goto COND_FAILED_CURLY_END;
 
-    while (isspace(*s)) s++;
+    Uskip_whitespace(&s);
     if (*s++ != '{') goto COND_FAILED_CURLY_START;     /* }-for-text-editors */
 
     sub[1] = s;
@@ -3241,7 +3317,7 @@ switch(cond_type = identify_operator(&s, &opname))
         expand_string_message, opname);
       return NULL;
       }
-    while (isspace(*s)) s++;
+    Uskip_whitespace(&s);
 
     /* {-for-text-editors */
     if (*s++ != '}')
@@ -3306,8 +3382,8 @@ switch(cond_type = identify_operator(&s, &opname))
     uschar *ourname;
     size_t len;
     BOOL boolvalue = FALSE;
-    while (isspace(*s)) s++;
-    if (*s != '{') goto COND_FAILED_CURLY_START;       /* }-for-text-editors */
+
+    if (Uskip_whitespace(&s) != '{') goto COND_FAILED_CURLY_START;     /* }-for-text-editors */
     ourname = cond_type == ECOND_BOOL_LAX ? US"bool_lax" : US"bool";
     switch(read_subs(sub_arg, 1, 1, &s, yield == NULL, FALSE, ourname, resetok))
       {
@@ -3319,9 +3395,8 @@ switch(cond_type = identify_operator(&s, &opname))
       case 3: return NULL;
       }
     t = sub_arg[0];
-    while (isspace(*t)) t++;
-    len = Ustrlen(t);
-    if (len)
+    Uskip_whitespace(&t);
+    if ((len = Ustrlen(t)))
       {
       /* trailing whitespace: seems like a good idea to ignore it too */
       t2 = t + len - 1;
@@ -3377,7 +3452,7 @@ switch(cond_type = identify_operator(&s, &opname))
     uschar cksum[4];
     BOOL boolvalue = FALSE;
 
-    switch(read_subs(sub, 2, 2, CUSS &s, yield == NULL, FALSE, US"inbound_srs", resetok))
+    switch(read_subs(sub, 2, 2, CUSS &s, yield == NULL, FALSE, name, resetok))
       {
       case 1: expand_string_message = US"too few arguments or bracketing "
        "error for inbound_srs";
@@ -3591,8 +3666,7 @@ lookups and for extractions in the success case. For the ${if item, the string
 "true" is substituted. In the fail case, nothing is substituted for all three
 items. */
 
-while (isspace(*s)) s++;
-if (*s == '}')
+if (skip_whitespace(&s) == '}')
   {
   if (type[0] == 'i')
     {
@@ -3648,8 +3722,7 @@ time, forced failures are noticed only if we want the second string. We must
 set skipping in the nested call if we don't want this string, or if we were
 already skipping. */
 
-while (isspace(*s)) s++;
-if (*s == '{')
+if (skip_whitespace(&s) == '{')
   {
   sub2 = expand_string_internal(s+1, TRUE, &s, yes || skipping, TRUE, resetok);
   if (sub2 == NULL && (!yes || !f.expand_string_forcedfail)) goto FAILED;
@@ -3680,7 +3753,7 @@ else if (*s != '}')
     {
     if (!yes && !skipping)
       {
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '}')
         {
        errwhere = US"did not close with '}' after forcedfail";
@@ -3702,7 +3775,7 @@ else if (*s != '}')
 
 /* All we have to do now is to check on the final closing brace. */
 
-while (isspace(*s)) s++;
+skip_whitespace(&s);
 if (*s++ != '}')
   {
   errwhere = US"did not close with '}'";
@@ -3854,7 +3927,7 @@ Arguments:
 Returns:       new pointer for expandable string, terminated if non-null
 */
 
-static gstring *
+gstring *
 cat_file(FILE *f, gstring *yield, uschar *eol)
 {
 uschar buffer[1024];
@@ -3874,7 +3947,7 @@ return yield;
 
 
 #ifndef DISABLE_TLS
-static gstring *
+gstring *
 cat_file_tls(void * tls_ctx, gstring * yield, uschar * eol)
 {
 int rc;
@@ -3928,7 +4001,7 @@ if (!*error)
     if (*s != ')')
       *error = US"expecting closing parenthesis";
     else
-      while (isspace(*(++s)));
+      while (isspace(*++s));
   else if (*s)
     *error = US"expecting operator";
 *sptr = s;
@@ -3943,8 +4016,7 @@ int c;
 int_eximarith_t n;
 uschar *s = *sptr;
 
-while (isspace(*s)) s++;
-if (isdigit((c = *s)))
+if (isdigit((c = Uskip_whitespace(&s))))
   {
   int count;
   (void)sscanf(CS s, (decimal? SC_EXIM_DEC "%n" : SC_EXIM_ARITH "%n"), &n, &count);
@@ -3956,7 +4028,7 @@ if (isdigit((c = *s)))
     case 'm': n *= 1024*1024; s++; break;
     case 'g': n *= 1024*1024*1024; s++; break;
     }
-  while (isspace (*s)) s++;
+  Uskip_whitespace(&s);
   }
 else if (c == '(')
   {
@@ -3978,7 +4050,7 @@ eval_op_unary(uschar **sptr, BOOL decimal, uschar **error)
 {
 uschar *s = *sptr;
 int_eximarith_t x;
-while (isspace(*s)) s++;
+Uskip_whitespace(&s);
 if (*s == '+' || *s == '-' || *s == '~')
   {
   int op = *s++;
@@ -4520,7 +4592,7 @@ while (*s != 0)
       uschar *user_msg;
       int rc;
 
-      switch(read_subs(sub, nelem(sub), 1, &s, skipping, TRUE, US"acl",
+      switch(read_subs(sub, nelem(sub), 1, &s, skipping, TRUE, name,
                      &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
@@ -4597,7 +4669,7 @@ while (*s != 0)
       int save_expand_nmax =
         save_expand_strings(save_expand_nstring, save_expand_nlength);
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (!(next_s = eval_condition(s, &resetok, skipping ? NULL : &cond)))
        goto EXPAND_FAILED;  /* message already set */
 
@@ -4696,7 +4768,7 @@ while (*s != 0)
       int expand_setup = 0;
       int nameptr = 0;
       uschar *key, *filename;
-      const uschar *affix;
+      const uschar * affix, * opts;
       uschar *save_lookup_value = lookup_value;
       int save_expand_nmax =
         save_expand_strings(save_expand_nstring, save_expand_nlength);
@@ -4710,8 +4782,7 @@ while (*s != 0)
       /* Get the key we are to look up for single-key+file style lookups.
       Otherwise set the key NULL pro-tem. */
 
-      while (isspace(*s)) s++;
-      if (*s == '{')                                   /*}*/
+      if (Uskip_whitespace(&s) == '{')                                 /*}*/
         {
         key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
         if (!key) goto EXPAND_FAILED;                  /*{{*/
@@ -4720,7 +4791,7 @@ while (*s != 0)
          expand_string_message = US"missing '}' after lookup key";
          goto EXPAND_FAILED_CURLY;
          }
-        while (isspace(*s)) s++;
+        Uskip_whitespace(&s);
         }
       else key = NULL;
 
@@ -4736,20 +4807,19 @@ while (*s != 0)
       kinds. Allow everything except space or { to appear; the actual content
       is checked by search_findtype_partial. */                /*}*/
 
-      while (*s != 0 && *s != '{' && !isspace(*s))     /*}*/
+      while (*s && *s != '{' && !isspace(*s))          /*}*/
         {
         if (nameptr < sizeof(name) - 1) name[nameptr++] = *s;
         s++;
         }
-      name[nameptr] = 0;
-      while (isspace(*s)) s++;
+      name[nameptr] = '\0';
+      Uskip_whitespace(&s);
 
       /* Now check for the individual search type and any partial or default
       options. Only those types that are actually in the binary are valid. */
 
-      stype = search_findtype_partial(name, &partial, &affix, &affixlen,
-        &starflags);
-      if (stype < 0)
+      if ((stype = search_findtype_partial(name, &partial, &affix, &affixlen,
+         &starflags, &opts)) < 0)
         {
         expand_string_message = search_error_message;
         goto EXPAND_FAILED;
@@ -4794,7 +4864,7 @@ while (*s != 0)
        expand_string_message = US"missing '}' closing lookup file-or-query arg";
        goto EXPAND_FAILED_CURLY;
        }
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
 
       /* If this isn't a single-key+file lookup, re-arrange the variables
       to be appropriate for the search_ functions. For query-style lookups,
@@ -4803,22 +4873,19 @@ while (*s != 0)
 
       if (!key)
         {
-        while (isspace(*filename)) filename++;
+       Uskip_whitespace(&filename);
         key = filename;
 
         if (mac_islookup(stype, lookup_querystyle))
           filename = NULL;
         else
-          {
-          if (*filename != '/')
-            {
-            expand_string_message = string_sprintf(
-              "absolute file name expected for \"%s\" lookup", name);
-            goto EXPAND_FAILED;
-            }
-          while (*key != 0 && !isspace(*key)) key++;
-          if (*key != 0) *key++ = 0;
-          }
+          if (*filename == '/')
+           {
+           while (*key && !isspace(*key)) key++;
+           if (*key) *key++ = '\0';
+           }
+         else
+           filename = NULL;
         }
 
       /* If skipping, don't do the next bit - just lookup_value == NULL, as if
@@ -4845,7 +4912,7 @@ while (*s != 0)
           goto EXPAND_FAILED;
           }
         lookup_value = search_find(handle, filename, key, partial, affix,
-          affixlen, starflags, &expand_setup);
+          affixlen, starflags, &expand_setup, opts);
         if (f.search_find_defer)
           {
           expand_string_message =
@@ -4905,7 +4972,7 @@ while (*s != 0)
         }
 
       switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE,
-           US"perl", &resetok))
+           name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:
@@ -4976,7 +5043,7 @@ while (*s != 0)
       uschar *sub_arg[3];
       uschar *p,*domain;
 
-      switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs", &resetok))
+      switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:
@@ -5050,7 +5117,7 @@ while (*s != 0)
       prvscheck_address = NULL;
       prvscheck_keynum = NULL;
 
-      switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok))
+      switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:
@@ -5082,7 +5149,7 @@ while (*s != 0)
         prvscheck_keynum = string_copy(key_num);
 
         /* Now expand the second argument */
-        switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok))
+        switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, name, &resetok))
           {
           case 1: goto EXPAND_FAILED_CURLY;
           case 2:
@@ -5136,7 +5203,7 @@ while (*s != 0)
         /* Now expand the final argument. We leave this till now so that
         it can include $prvscheck_result. */
 
-        switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs", &resetok))
+        switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, name, &resetok))
           {
           case 1: goto EXPAND_FAILED_CURLY;
           case 2:
@@ -5157,7 +5224,7 @@ while (*s != 0)
            We need to make sure all subs are expanded first, so as to skip over
            the entire item. */
 
-        switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs", &resetok))
+        switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, name, &resetok))
           {
           case 1: goto EXPAND_FAILED_CURLY;
           case 2:
@@ -5180,7 +5247,7 @@ while (*s != 0)
         goto EXPAND_FAILED;
         }
 
-      switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile", &resetok))
+      switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:
@@ -5211,7 +5278,7 @@ while (*s != 0)
       {
       client_conn_ctx cctx;
       int timeout = 5;
-      int save_ptr = yield->ptr;
+      int save_ptr = gstring_length(yield);
       FILE * fp = NULL;
       uschar * arg;
       uschar * sub_arg[4];
@@ -5219,7 +5286,6 @@ while (*s != 0)
       host_item host;
       BOOL do_shutdown = TRUE;
       BOOL do_tls = FALSE;     /* Only set under ! DISABLE_TLS */
-      blob reqstr;
 
       if (expand_forbid & RDO_READSOCK)
         {
@@ -5230,224 +5296,84 @@ while (*s != 0)
       /* Read up to 4 arguments, but don't do the end of item check afterwards,
       because there may be a string for expansion on failure. */
 
-      switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket", &resetok))
+      switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:                             /* Won't occur: no end check */
         case 3: goto EXPAND_FAILED;
         }
 
-      /* Grab the request string, if any */
-
-      reqstr.data = sub_arg[1];
-      reqstr.len = Ustrlen(sub_arg[1]);
-
-      /* Sort out timeout, if given.  The second arg is a list with the first element
-      being a time value.  Any more are options of form "name=value".  Currently the
-      only option recognised is "shutdown". */
-
-      if (sub_arg[2])
-        {
-       const uschar * list = sub_arg[2];
-       uschar * item;
-       int sep = 0;
-
-       item = string_nextinlist(&list, &sep, NULL, 0);
-        if ((timeout = readconf_readtime(item, 0, FALSE)) < 0)
-          {
-          expand_string_message = string_sprintf("bad time value %s", item);
-          goto EXPAND_FAILED;
-          }
-
-       while ((item = string_nextinlist(&list, &sep, NULL, 0)))
-         if (Ustrncmp(item, US"shutdown=", 9) == 0)
-           { if (Ustrcmp(item + 9, US"no") == 0) do_shutdown = FALSE; }
-#ifndef DISABLE_TLS
-         else if (Ustrncmp(item, US"tls=", 4) == 0)
-           { if (Ustrcmp(item + 9, US"no") != 0) do_tls = TRUE; }
-#endif
-        }
-      else
-       sub_arg[3] = NULL;                     /* No eol if no timeout */
-
       /* If skipping, we don't actually do anything. Otherwise, arrange to
       connect to either an IP or a Unix socket. */
 
       if (!skipping)
         {
-        /* Handle an IP (internet) domain */
-
-        if (Ustrncmp(sub_arg[0], "inet:", 5) == 0)
-          {
-          int port;
-          uschar * port_name;
-
-          server_name = sub_arg[0] + 5;
-          port_name = Ustrrchr(server_name, ':');
-
-          /* Sort out the port */
+       int stype = search_findtype(US"readsock", 8);
+       gstring * g = NULL;
+       void * handle;
+       int expand_setup = -1;
+       uschar * s;
 
-          if (!port_name)
-            {
-            expand_string_message =
-              string_sprintf("missing port for readsocket %s", sub_arg[0]);
-            goto EXPAND_FAILED;
-            }
-          *port_name++ = 0;           /* Terminate server name */
+       /* If the reqstr is empty, flag that and set a dummy */
 
-          if (isdigit(*port_name))
-            {
-            uschar *end;
-            port = Ustrtol(port_name, &end, 0);
-            if (end != port_name + Ustrlen(port_name))
-              {
-              expand_string_message =
-                string_sprintf("invalid port number %s", port_name);
-              goto EXPAND_FAILED;
-              }
-            }
-          else
-            {
-            struct servent *service_info = getservbyname(CS port_name, "tcp");
-            if (!service_info)
-              {
-              expand_string_message = string_sprintf("unknown port \"%s\"",
-                port_name);
-              goto EXPAND_FAILED;
-              }
-            port = ntohs(service_info->s_port);
-            }
+       if (!sub_arg[1][0])
+         {
+         g = string_append_listele(g, ',', US"send=no");
+         sub_arg[1] = US"DUMMY";
+         }
 
-         /*XXX we trust that the request is idempotent for TFO.  Hmm. */
-         cctx.sock = ip_connectedsocket(SOCK_STREAM, server_name, port, port,
-                 timeout, &host, &expand_string_message,
-                 do_tls ? NULL : &reqstr);
-         callout_address = NULL;
-         if (cctx.sock < 0)
-           goto SOCK_FAIL;
-         if (!do_tls)
-           reqstr.len = 0;
-          }
+       /* Re-marshall the options */
 
-        /* Handle a Unix domain socket */
+       if (sub_arg[2])
+         {
+         const uschar * list = sub_arg[2];
+         uschar * item;
+         int sep = 0;
 
-        else
-          {
-         struct sockaddr_un sockun;         /* don't call this "sun" ! */
-          int rc;
+         /* First option has no tag and is timeout */
+         if ((item = string_nextinlist(&list, &sep, NULL, 0)))
+           g = string_append_listele(g, ',',
+                 string_sprintf("timeout=%s", item));
 
-          if ((cctx.sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
-            {
-            expand_string_message = string_sprintf("failed to create socket: %s",
-              strerror(errno));
-            goto SOCK_FAIL;
-            }
+         /* The rest of the options from the expansion */
+         while ((item = string_nextinlist(&list, &sep, NULL, 0)))
+           g = string_append_listele(g, ',', item);
 
-          sockun.sun_family = AF_UNIX;
-          sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1),
-            sub_arg[0]);
-         server_name = US sockun.sun_path;
+         /* possibly plus an EOL string */
+         if (sub_arg[3] && *sub_arg[3])
+           g = string_append_listele(g, ',',
+                 string_sprintf("eol=%s", sub_arg[3]));
 
-          sigalrm_seen = FALSE;
-          ALARM(timeout);
-          rc = connect(cctx.sock, (struct sockaddr *)(&sockun), sizeof(sockun));
-          ALARM_CLR(0);
-          if (sigalrm_seen)
-            {
-            expand_string_message = US "socket connect timed out";
-            goto SOCK_FAIL;
-            }
-          if (rc < 0)
-            {
-            expand_string_message = string_sprintf("failed to connect to socket "
-              "%s: %s", sub_arg[0], strerror(errno));
-            goto SOCK_FAIL;
-            }
-         host.name = server_name;
-         host.address = US"";
-          }
+         }
 
-        DEBUG(D_expand) debug_printf_indent("connected to socket %s\n", sub_arg[0]);
+       /* Gat a (possibly cached) handle for the connection */
 
-#ifndef DISABLE_TLS
-       if (do_tls)
+       if (!(handle = search_open(sub_arg[0], stype, 0, NULL, NULL)))
          {
-         smtp_connect_args conn_args = {.host = &host };
-         tls_support tls_dummy = {.sni=NULL};
-         uschar * errstr;
-
-         if (!tls_client_start(&cctx, &conn_args, NULL, &tls_dummy, &errstr))
-           {
-           expand_string_message = string_sprintf("TLS connect failed: %s", errstr);
-           goto SOCK_FAIL;
-           }
+         if (*expand_string_message) goto EXPAND_FAILED;
+         expand_string_message = search_error_message;
+         search_error_message = NULL;
+         goto SOCK_FAIL;
          }
-#endif
-
-       /* Allow sequencing of test actions */
-       testharness_pause_ms(100);
-
-        /* Write the request string, if not empty or already done */
-
-        if (reqstr.len)
-          {
-          DEBUG(D_expand) debug_printf_indent("writing \"%s\" to socket\n",
-            reqstr.data);
-          if ( (
-#ifndef DISABLE_TLS
-             do_tls ? tls_write(cctx.tls_ctx, reqstr.data, reqstr.len, FALSE) :
-#endif
-                       write(cctx.sock, reqstr.data, reqstr.len)) != reqstr.len)
-            {
-            expand_string_message = string_sprintf("request write to socket "
-              "failed: %s", strerror(errno));
-            goto SOCK_FAIL;
-            }
-          }
 
-        /* Shut down the sending side of the socket. This helps some servers to
-        recognise that it is their turn to do some work. Just in case some
-        system doesn't have this function, make it conditional. */
+       /* Get (possibly cached) results for the lookup */
+       /* sspec: sub_arg[0]  req: sub_arg[1]  opts: g */
 
-#ifdef SHUT_WR
-       if (!do_tls && do_shutdown) shutdown(cctx.sock, SHUT_WR);
-#endif
-
-       testharness_pause_ms(100);
-
-        /* Now we need to read from the socket, under a timeout. The function
-        that reads a file can be used. */
-
-       if (!do_tls)
-         fp = fdopen(cctx.sock, "rb");
-        sigalrm_seen = FALSE;
-        ALARM(timeout);
-        yield =
-#ifndef DISABLE_TLS
-         do_tls ? cat_file_tls(cctx.tls_ctx, yield, sub_arg[3]) :
-#endif
-                   cat_file(fp, yield, sub_arg[3]);
-        ALARM_CLR(0);
-
-#ifndef DISABLE_TLS
-       if (do_tls)
+       if ((s = search_find(handle, sub_arg[0], sub_arg[1], -1, NULL, 0, 0,
+                                   &expand_setup, string_from_gstring(g))))
+         yield = string_cat(yield, s);
+       else if (f.search_find_defer)
          {
-         tls_close(cctx.tls_ctx, TRUE);
-         close(cctx.sock);
+         expand_string_message = search_error_message;
+         search_error_message = NULL;
+         goto SOCK_FAIL;
          }
        else
-#endif
-         (void)fclose(fp);
-
-        /* After a timeout, we restore the pointer in the result, that is,
-        make sure we add nothing from the socket. */
-
-        if (sigalrm_seen)
-          {
-          yield->ptr = save_ptr;
-          expand_string_message = US "socket read timed out";
-          goto SOCK_FAIL;
-          }
+         {     /* should not happen, at present */
+         expand_string_message = search_error_message;
+         search_error_message = NULL;
+         goto SOCK_FAIL;
+         }
         }
 
       /* The whole thing has worked (or we were skipping). If there is a
@@ -5462,7 +5388,7 @@ while (*s != 0)
          expand_string_message = US"missing '}' closing failstring for readsocket";
          goto EXPAND_FAILED_CURLY;
          }
-        while (isspace(*s)) s++;
+        Uskip_whitespace(&s);
         }
 
     READSOCK_DONE:
@@ -5488,7 +5414,7 @@ while (*s != 0)
        expand_string_message = US"missing '}' closing failstring for readsocket";
        goto EXPAND_FAILED_CURLY;
        }
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       goto READSOCK_DONE;
       }
 
@@ -5508,7 +5434,7 @@ while (*s != 0)
         goto EXPAND_FAILED;
         }
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s != '{')
         {
        expand_string_message = US"missing '{' for command arg of run";
@@ -5516,7 +5442,7 @@ while (*s != 0)
        }
       if (!(arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok)))
        goto EXPAND_FAILED;
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '}')
         {
        expand_string_message = US"missing '}' closing command arg of run";
@@ -5541,7 +5467,8 @@ while (*s != 0)
 
         /* Create the child process, making it a group leader. */
 
-        if ((pid = child_open(USS argv, NULL, 0077, &fd_in, &fd_out, TRUE)) < 0)
+        if ((pid = child_open(USS argv, NULL, 0077, &fd_in, &fd_out, TRUE,
+                             US"expand-run")) < 0)
           {
           expand_string_message =
             string_sprintf("couldn't create child process: %s", strerror(errno));
@@ -5611,11 +5538,11 @@ while (*s != 0)
 
     case EITEM_TR:
       {
-      int oldptr = yield->ptr;
+      int oldptr = gstring_length(yield);
       int o2m;
       uschar *sub[3];
 
-      switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr", &resetok))
+      switch(read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:
@@ -5827,7 +5754,7 @@ while (*s != 0)
       int save_expand_nmax =
         save_expand_strings(save_expand_nstring, save_expand_nlength);
 
-      switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg", &resetok))
+      switch(read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:
@@ -5941,11 +5868,9 @@ while (*s != 0)
 
       enum {extract_basic, extract_json, extract_jsons} fmt = extract_basic;
 
-      while (isspace(*s)) s++;
-
       /* Check for a format-variant specifier */
 
-      if (*s != '{')                                   /*}*/
+      if (Uskip_whitespace(&s) != '{')                                 /*}*/
        if (Ustrncmp(s, "json", 4) == 0)
          if (*(s += 4) == 's')
            {fmt = extract_jsons; s++;}
@@ -5967,14 +5892,14 @@ while (*s != 0)
            expand_string_message = US"missing '{' for arg of extract";
            goto EXPAND_FAILED_CURLY;
            }
-         while (isspace(*s)) s++;
+         Uskip_whitespace(&s);
          }
        if (  Ustrncmp(s, "fail", 4) == 0                       /*'{'*/
           && (s[4] == '}' || s[4] == ' ' || s[4] == '\t' || !s[4])
           )
          {
          s += 4;
-         while (isspace(*s)) s++;
+         Uskip_whitespace(&s);
          }                                                     /*'{'*/
        if (*s != '}')
          {
@@ -5985,8 +5910,7 @@ while (*s != 0)
 
       else for (int i = 0, j = 2; i < j; i++) /* Read the proper number of arguments */
         {
-       while (isspace(*s)) s++;
-        if (*s == '{')                                                 /*'}'*/
+       if (Uskip_whitespace(&s) == '{')                                                /*'}'*/
           {
           if (!(sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok)))
            goto EXPAND_FAILED;                                 /*'{'*/
@@ -6008,7 +5932,7 @@ while (*s != 0)
             int x = 0;
             uschar *p = sub[0];
 
-            while (isspace(*p)) p++;
+            Uskip_whitespace(&p);
             sub[0] = p;
 
             len = Ustrlen(p);
@@ -6110,15 +6034,14 @@ while (*s != 0)
              if (Ustrcmp(item, sub[0]) == 0)   /*XXX should be a UTF8-compare */
                {
                s = item + Ustrlen(item) + 1;
-               while (isspace(*s)) s++;
-               if (*s != ':')
+               if (Uskip_whitespace(&s) != ':')
                  {
                  expand_string_message =
                    US"missing object value-separator for extract json";
                  goto EXPAND_FAILED_CURLY;
                  }
                s++;
-               while (isspace(*s)) s++;
+               Uskip_whitespace(&s);
                lookup_value = s;
                break;
                }
@@ -6176,8 +6099,7 @@ while (*s != 0)
 
       for (int i = 0; i < 2; i++)
         {
-        while (isspace(*s)) s++;
-        if (*s != '{')                                 /*'}'*/
+        if (Uskip_whitespace(&s) != '{')                                       /*'}'*/
          {
          expand_string_message = string_sprintf(
            "missing '{' for arg %d of listextract", i+1);
@@ -6202,7 +6124,7 @@ while (*s != 0)
          int x = 0;
          uschar *p = sub[0];
 
-         while (isspace(*p)) p++;
+         Uskip_whitespace(&p);
          sub[0] = p;
 
          len = Ustrlen(p);
@@ -6261,6 +6183,23 @@ while (*s != 0)
       continue;
       }
 
+    case EITEM_LISTQUOTE:
+      {
+      uschar * sub[2];
+      switch(read_subs(sub, 2, 2, &s, skipping, TRUE, name, &resetok))
+        {
+        case 1: goto EXPAND_FAILED_CURLY;
+        case 2:
+        case 3: goto EXPAND_FAILED;
+        }
+      for (uschar sep = *sub[0], c; c = *sub[1]; sub[1]++)
+       {
+       if (c == sep) yield = string_catn(yield, sub[1], 1);
+       yield = string_catn(yield, sub[1], 1);
+       }
+      continue;
+      }
+
 #ifndef DISABLE_TLS
     case EITEM_CERTEXTRACT:
       {
@@ -6270,8 +6209,7 @@ while (*s != 0)
         save_expand_strings(save_expand_nstring, save_expand_nlength);
 
       /* Read the field argument */
-      while (isspace(*s)) s++;
-      if (*s != '{')                                   /*}*/
+      if (Uskip_whitespace(&s) != '{')                                 /*}*/
        {
        expand_string_message = US"missing '{' for field arg of certextract";
        goto EXPAND_FAILED_CURLY;
@@ -6288,7 +6226,7 @@ while (*s != 0)
       int len;
       uschar *p = sub[0];
 
-      while (isspace(*p)) p++;
+      Uskip_whitespace(&p);
       sub[0] = p;
 
       len = Ustrlen(p);
@@ -6297,8 +6235,7 @@ while (*s != 0)
       }
 
       /* inspect the cert argument */
-      while (isspace(*s)) s++;
-      if (*s != '{')                                   /*}*/
+      if (Uskip_whitespace(&s) != '{')                                 /*}*/
        {
        expand_string_message = US"missing '{' for cert variable arg of certextract";
        goto EXPAND_FAILED_CURLY;
@@ -6350,13 +6287,13 @@ while (*s != 0)
     case EITEM_REDUCE:
       {
       int sep = 0;
-      int save_ptr = yield->ptr;
+      int save_ptr = gstring_length(yield);
       uschar outsep[2] = { '\0', '\0' };
       const uschar *list, *expr, *temp;
       uschar *save_iterate_item = iterate_item;
       uschar *save_lookup_value = lookup_value;
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '{')
         {
        expand_string_message =
@@ -6376,7 +6313,7 @@ while (*s != 0)
       if (item_type == EITEM_REDUCE)
         {
        uschar * t;
-        while (isspace(*s)) s++;
+        Uskip_whitespace(&s);
         if (*s++ != '{')
          {
          expand_string_message = US"missing '{' for second arg of reduce";
@@ -6392,7 +6329,7 @@ while (*s != 0)
          }
         }
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '{')
         {
        expand_string_message =
@@ -6423,7 +6360,7 @@ while (*s != 0)
         goto EXPAND_FAILED;
         }
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '}')
         {                                              /*{*/
         expand_string_message = string_sprintf("missing } at end of condition "
@@ -6432,7 +6369,7 @@ while (*s != 0)
         goto EXPAND_FAILED;
         }
 
-      while (isspace(*s)) s++;                         /*{*/
+      Uskip_whitespace(&s);                            /*{*/
       if (*s++ != '}')
         {                                              /*{*/
         expand_string_message = string_sprintf("missing } at end of \"%s\"",
@@ -6497,7 +6434,8 @@ while (*s != 0)
         item of the output list, add in a space if the new item begins with the
         separator character, or is an empty string. */
 
-        if (yield->ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0))
+        if (  yield && yield->ptr != save_ptr
+          && (temp[0] == *outsep || temp[0] == 0))
           yield = string_catn(yield, US" ", 1);
 
         /* Add the string in "temp" to the output list that we are building,
@@ -6537,7 +6475,7 @@ while (*s != 0)
       the redundant final separator. Even though an empty item at the end of a
       list does not count, this is tidier. */
 
-      else if (yield->ptr != save_ptr) yield->ptr--;
+      else if (yield && yield->ptr != save_ptr) yield->ptr--;
 
       /* Restore preserved $item */
 
@@ -6555,7 +6493,7 @@ while (*s != 0)
       uschar * tmp;
       uschar *save_iterate_item = iterate_item;
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '{')
         {
         expand_string_message = US"missing '{' for list arg of sort";
@@ -6570,7 +6508,7 @@ while (*s != 0)
        goto EXPAND_FAILED_CURLY;
        }
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '{')
         {
         expand_string_message = US"missing '{' for comparator arg of sort";
@@ -6604,7 +6542,7 @@ while (*s != 0)
          goto EXPAND_FAILED;
        }
 
-      while (isspace(*s)) s++;
+      Uskip_whitespace(&s);
       if (*s++ != '{')
         {
         expand_string_message = US"missing '{' for extractor arg of sort";
@@ -6747,7 +6685,7 @@ while (*s != 0)
         }
 
       switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping,
-           TRUE, US"dlfunc", &resetok))
+           TRUE, name, &resetok))
         {
         case 1: goto EXPAND_FAILED_CURLY;
         case 2:
@@ -6823,8 +6761,7 @@ while (*s != 0)
       uschar * key;
       uschar *save_lookup_value = lookup_value;
 
-      while (isspace(*s)) s++;
-      if (*s != '{')                                   /*}*/
+      if (Uskip_whitespace(&s) != '{')                                 /*}*/
        goto EXPAND_FAILED;
 
       key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok);
@@ -7367,6 +7304,8 @@ while (*s != 0)
         continue;
        }
 
+      /* quote a list-item for the given list-separator */
+
       /* mask applies a mask to an IP address; for example the result of
       ${mask:131.111.10.206/28} is 131.111.10.192/28. */
 
@@ -7469,11 +7408,10 @@ while (*s != 0)
         {
         uschar outsep[2] = { ':', '\0' };
         uschar *address, *error;
-        int save_ptr = yield->ptr;
+        int save_ptr = gstring_length(yield);
         int start, end, domain;  /* Not really used */
 
-        while (isspace(*sub)) sub++;
-        if (*sub == '>')
+       if (Uskip_whitespace(&sub) == '>')
           if (*outsep = *++sub) ++sub;
           else
            {
@@ -7500,7 +7438,7 @@ while (*s != 0)
 
           if (address)
             {
-            if (yield->ptr != save_ptr && address[0] == *outsep)
+            if (yield && yield->ptr != save_ptr && address[0] == *outsep)
               yield = string_catn(yield, US" ", 1);
 
             for (;;)
@@ -7529,7 +7467,7 @@ while (*s != 0)
         /* If we have generated anything, remove the redundant final
         separator. */
 
-        if (yield->ptr != save_ptr) yield->ptr--;
+        if (yield && yield->ptr != save_ptr) yield->ptr--;
         f.parse_allow_group = FALSE;
         continue;
         }
@@ -7548,7 +7486,7 @@ while (*s != 0)
       case EOP_QUOTE_LOCAL_PART:
       if (!arg)
         {
-        BOOL needs_quote = (*sub == 0);      /* TRUE for empty string */
+        BOOL needs_quote = (!*sub);      /* TRUE for empty string */
         uschar *t = sub - 1;
 
         if (c == EOP_QUOTE)
@@ -7668,10 +7606,10 @@ while (*s != 0)
 
       case EOP_FROM_UTF8:
         {
-        while (*sub != 0)
+       uschar * buff = store_get(4, is_tainted(sub));
+        while (*sub)
           {
           int c;
-          uschar buff[4];
           GETUTF8INC(c, sub);
           if (c > 255) c = '_';
           buff[0] = c;
@@ -7680,7 +7618,7 @@ while (*s != 0)
         continue;
         }
 
-         /* replace illegal UTF-8 sequences by replacement character  */
+      /* replace illegal UTF-8 sequences by replacement character  */
 
       #define UTF8_REPLACEMENT_CHAR US"?"
 
@@ -7692,7 +7630,17 @@ while (*s != 0)
         int complete;
         uschar seq_buff[4];                    /* accumulate utf-8 here */
 
-        while (*sub != 0)
+       /* Manually track tainting, as we deal in individual chars below */
+
+       if (is_tainted(sub))
+         if (yield->s && yield->ptr)
+           gstring_rebuffer(yield);
+         else
+           yield->s = store_get(yield->size = Ustrlen(sub), TRUE);
+
+       /* Check the UTF-8, byte-by-byte */
+
+        while (*sub)
          {
          complete = 0;
          uschar c = *sub++;
@@ -7718,7 +7666,7 @@ while (*s != 0)
            }
          else  /* no bytes left: new sequence */
            {
-           if((c & 0x80) == 0) /* 1-byte sequence, US-ASCII, keep it */
+           if(!(c & 0x80))     /* 1-byte sequence, US-ASCII, keep it */
              {
              yield = string_catn(yield, &c, 1);
              continue;
@@ -7763,9 +7711,8 @@ while (*s != 0)
         * Eg, ${length_1:フィル} is one byte, not one character, so we expect
         * ${utf8clean:${length_1:フィル}} to yield '?' */
         if (bytes_left != 0)
-          {
           yield = string_catn(yield, UTF8_REPLACEMENT_CHAR, 1);
-          }
+
         continue;
         }
 
@@ -8399,26 +8346,19 @@ the behaviour explicitly.  Stripping leading whitespace is a harmless
 noop change since strtol skips it anyway (provided that there is a number
 to find at all). */
 if (isspace(*s))
-  {
-  while (isspace(*s)) ++s;
-  if (*s == '\0')
+  if (Uskip_whitespace(&s) == '\0')
     {
       DEBUG(D_expand)
        debug_printf_indent("treating blank string as number 0\n");
       return 0;
     }
-  }
 
 value = strtoll(CS s, CSS &endptr, 10);
 
 if (endptr == s)
-  {
   msg = US"integer expected but \"%s\" found";
-  }
 else if (value < 0 && isplus)
-  {
   msg = US"non-negative integer expected but \"%s\" found";
-  }
 else
   {
   switch (tolower(*endptr))
@@ -8444,10 +8384,7 @@ else
   if (errno == ERANGE)
     msg = US"absolute value of integer \"%s\" is too large (overflow)";
   else
-    {
-    while (isspace(*endptr)) endptr++;
-    if (*endptr == 0) return value;
-    }
+    if (Uskip_whitespace(&endptr) == 0) return value;
   }
 
 expand_string_message = string_sprintf(CS msg, s);