Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/common/expr.c
blob: ce10f675042c56bbc8cd41975d2c91506108deaf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
   expr.c - limited shell-like expression parsing functions
   This file is part of the nss-pam-ldapd library.

   Copyright (C) 2009-2021 Arthur de Jong
   Copyright (c) 2012 Thorsten Glaser <t.glaser@tarent.de>
   Copyright (c) 2016 Giovanni Mascellani <gio@debian.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301 USA
*/

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

#include "expr.h"
#include "compat/attrs.h"

/* the maximum length of a variable name */
#define MAXVARLENGTH 30

static inline int my_isalpha(const char c)
{
  return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));
}

static inline int my_isdigit(const char c)
{
  return (c >= '0') && (c <= '9');
}

static inline int my_isalphanum(const char c)
{
  return my_isalpha(c) || my_isdigit(c);
}

/* return the part of the string that is a valid name */
MUST_USE static const char *parse_name(const char *str, int *ptr,
                                       char *buffer, size_t buflen, int extra_chars)
{
  int i = 0;
  /* clear the buffer */
  buffer[i] = '\0';
  /* look for an alpha + alphanumeric* string */
  if (!my_isalpha(str[*ptr]))
    return NULL;
  while (my_isalphanum(str[*ptr]) || (str[*ptr] == ';') || (extra_chars && ((str[*ptr] == '-') || (str[*ptr] == '.'))))
  {
    if ((size_t)i >= buflen)
      return NULL;
    buffer[i++] = str[(*ptr)++];
  }
  /* NULL-terminate the string */
  if ((size_t)i >= buflen)
    return NULL;
  buffer[i++] = '\0';
  return buffer;
}

/* dummy expander function to always return an empty string */
static const char *empty_expander(const char UNUSED(*name),
                                  void UNUSED(*expander_arg))
{
  return "";
}

/* definition of the parse functions (they call each other) */
MUST_USE static const char *parse_dollar_expression(
              const char *str, int *ptr, char *buffer, size_t buflen,
              expr_expander_func expander, void *expander_arg);
MUST_USE static const char *parse_expression(
              const char *str, int *ptr, int endat, char *buffer, size_t buflen,
              expr_expander_func expander, void *expander_arg);

/* handle ${attr:-word} expressions */
MUST_USE static const char *parse_dollar_default(
              const char *str, int *ptr, char *buffer, size_t buflen,
              expr_expander_func expander, void *expander_arg,
              const char *varvalue)
{
  if ((varvalue != NULL) && (*varvalue != '\0'))
  {
    /* value is set, skip rest of expression and use value */
    if (parse_expression(str, ptr, '}', buffer, buflen, empty_expander, NULL) == NULL)
      return NULL;
    if (strlen(varvalue) >= buflen)
      return NULL;
    strcpy(buffer, varvalue);
  }
  else
  {
    /* value is not set, evaluate rest of expression */
    if (parse_expression(str, ptr, '}', buffer, buflen, expander, expander_arg) == NULL)
      return NULL;
  }
  return buffer;
}

/* handle ${attr:+word} expressions */
MUST_USE static const char *parse_dollar_alternative(
              const char *str, int *ptr, char *buffer, size_t buflen,
              expr_expander_func expander, void *expander_arg,
              const char *varvalue)
{
  if ((varvalue != NULL) && (*varvalue != '\0'))
  {
    /* value is set, evaluate rest of expression */
    if (parse_expression(str, ptr, '}', buffer, buflen, expander, expander_arg) == NULL)
      return NULL;
  }
  else
  {
    /* value is not set, skip rest of expression and blank */
    if (parse_expression(str, ptr, '}', buffer, buflen, empty_expander, NULL) == NULL)
      return NULL;
    buffer[0] = '\0';
  }
  return buffer;
}

/* handle ${attr:offset:length} expressions */
MUST_USE static const char *parse_dollar_substring(
              const char *str, int *ptr, char *buffer, size_t buflen,
              const char *varvalue)
{
  char *tmp;
  unsigned long int offset, length;
  size_t varlen;
  /* parse input */
  tmp = (char *)str + *ptr;
  if (!my_isdigit(*tmp))
    return NULL;
  errno = 0;
  offset = strtoul(tmp, &tmp, 10);
  if ((*tmp != ':') || (errno != 0))
    return NULL;
  tmp += 1;
  errno = 0;
  length = strtoul(tmp, &tmp, 10);
  if ((*tmp != '}') || (errno != 0))
    return NULL;
  /* don't skip closing '}' here, because it will be skipped later */
  *ptr += tmp - (str + *ptr);
  varlen = strlen(varvalue);
  if (offset > varlen)
    offset = varlen;
  if (offset + length > varlen)
    length = varlen - offset;
  if (length >= buflen)
    return NULL;
  /* everything's ok, copy data; we use memcpy instead of strncpy
     because we already know the exact length in play */
  memcpy(buffer, varvalue + offset, length);
  buffer[length] = '\0';
  return buffer;
}

/* handle ${attr#word} expressions */
MUST_USE static const char *parse_dollar_match(
              const char *str, int *ptr, char *buffer, size_t buflen,
              const char *varvalue)
{
  char c;
  const char *cp, *vp;
  int ismatch;
  size_t vallen;
  cp = str + *ptr;
  vp = varvalue;
  ismatch = 1;
  while (((c = *cp++) != '\0') && (c != '}'))
  {
    if (ismatch && (*vp =='\0'))
      ismatch = 0; /* varvalue shorter than trim string */
    if (c == '?')
    {
      /* match any one character */
      vp++;
      continue;
    }
    if (c == '\\')
    {
      if ((c = *cp++) == '\0')
        return NULL; /* end of input: syntax error */
      /* escape the next character c */
    }
    if (ismatch && (*vp != c))
      ismatch = 0; /* they differ */
    vp++;
  }
  if (c == '\0')
    return NULL; /* end of input: syntax error */
  /* at this point, cp points to after the closing } */
  (*ptr) = cp - str - 1;
  /* if ismatch, vp points to the beginning of the
     data after trimming, otherwise vp is invalid */
  if (!ismatch)
    vp = varvalue;
  /* now copy the (trimmed or not) value to the buffer */
  if ((vallen = strlen(vp) + 1) > buflen)
    return NULL;
  memcpy(buffer, vp, vallen);
  return buffer;
}

MUST_USE static const char *parse_dollar_expression(
              const char *str, int *ptr, char *buffer, size_t buflen,
              expr_expander_func expander, void *expander_arg)
{
  char varname[MAXVARLENGTH];
  const char *varvalue;
  if ((buflen <= 0) || (buffer == NULL) || (str == NULL) || (ptr == NULL))
    return NULL;
  if (str[*ptr] == '{')
  {
    (*ptr)++;
    /* the first part is always a variable name */
    if (parse_name(str, ptr, varname, sizeof(varname), 1) == NULL)
      return NULL;
    varvalue = expander(varname, expander_arg);
    if (varvalue == NULL)
      varvalue = "";
    if (str[*ptr] == '}')
    {
      /* simple substitute */
      if (strlen(varvalue) >= buflen)
        return NULL;
      strcpy(buffer, varvalue);
    }
    else if (strncmp(str + *ptr, ":-", 2) == 0)
    {
      /* if variable is not set or empty, substitute remainder */
      (*ptr) += 2;
      if (parse_dollar_default(str, ptr, buffer, buflen, expander, expander_arg, varvalue) == NULL)
        return NULL;
    }
    else if (strncmp(str + *ptr, ":+", 2) == 0)
    {
      /* if variable is set, substitute remainder */
      (*ptr) += 2;
      if (parse_dollar_alternative(str, ptr, buffer, buflen, expander, expander_arg, varvalue) == NULL)
        return NULL;
    }
    else if (str[*ptr] == ':')
    {
      /* substitute substring of variable */
      (*ptr) += 1;
      if (parse_dollar_substring(str, ptr, buffer, buflen, varvalue) == NULL)
        return NULL;
    }
    else if (str[*ptr] == '#')
    {
      /* try to strip the remainder value from variable beginning */
      (*ptr) += 1;
      if (parse_dollar_match(str, ptr, buffer, buflen, varvalue) == NULL)
        return NULL;
    }
    else
      return NULL;
    (*ptr)++; /* skip closing } */
  }
  else
  {
    /* it is a simple reference to a variable, like $uidNumber */
    if (parse_name(str, ptr, varname, sizeof(varname), 0) == NULL)
      return NULL;
    varvalue = expander(varname, expander_arg);
    if (varvalue == NULL)
      varvalue = "";
    if (strlen(varvalue) >= buflen)
      return NULL;
    strcpy(buffer, varvalue);
  }
  return buffer;
}

MUST_USE static const char *parse_expression(
              const char *str, int *ptr, int endat, char *buffer, size_t buflen,
              expr_expander_func expander, void *expander_arg)
{
  int j = 0;
  /* go over string */
  while ((str[*ptr] != endat) && (str[*ptr] != '\0'))
  {
    switch (str[*ptr])
    {
      case '$': /* beginning of an expression */
        (*ptr)++;
        if ((size_t)j >= buflen)
          return NULL;
        if (parse_dollar_expression(str, ptr, buffer + j, buflen - j,
                                    expander, expander_arg) == NULL)
          return NULL;
        j = strlen(buffer);
        break;
      case '\\': /* escaped character, unescape */
        (*ptr)++;
        FALLTHROUGH; /* no break needed here */
      default: /* just copy the text */
        if ((size_t)j >= buflen)
          return NULL;
        buffer[j++] = str[*ptr];
        (*ptr)++;
    }
  }
  /* NULL-terminate buffer */
  if ((size_t)j >= buflen)
    return NULL;
  buffer[j++] = '\0';
  return buffer;
}

MUST_USE const char *expr_parse(const char *str, char *buffer, size_t buflen,
                                expr_expander_func expander, void *expander_arg)
{
  int i = 0;
  return parse_expression(str, &i, '\0', buffer, buflen,
                          expander, expander_arg);
}

SET *expr_vars(const char *str, SET *set)
{
  char varname[MAXVARLENGTH];
  int i = 0;
  /* allocate set if needed */
  if (set == NULL)
    set = set_new();
  if (set == NULL)
    return NULL;
  /* go over string */
  while (str[i] != '\0')
  {
    switch (str[i])
    {
      case '$': /* beginning of a $-expression */
        i++;
        if (str[i] == '{')
          i++;
        /* the rest should start with a variable name */
        if (parse_name(str, &i, varname, sizeof(varname), 0) != NULL)
          set_add(set, varname);
        break;
      case '\\': /* escaped character, unescape */
        i++;
        FALLTHROUGH; /* no break needed here */
      default: /* just skip */
        i++;
    }
  }
  return set;
}