File: MatcherUtils.cc

package info (click to toggle)
trafficserver 6.2.0-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 45,456 kB
  • sloc: cpp: 271,894; ansic: 80,740; sh: 6,032; makefile: 3,364; python: 2,135; perl: 2,040; java: 277; lex: 128; sql: 94; yacc: 68; sed: 8
file content (610 lines) | stat: -rw-r--r-- 15,837 bytes parent folder | download | duplicates (2)
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

/*****************************************************************************
 *
 *  MatcherUtils.cc - Various helper routines used in ControlMatcher
 *                    and ReverseProxy
 *
 *
 ****************************************************************************/

#include "ts/ink_platform.h"
#include "ts/Diags.h"
#include "ts/ink_memory.h"
#include "ts/ink_inet.h"
#include "ts/ink_assert.h"
#include "ts/MatcherUtils.h"
#include "ts/Tokenizer.h"

config_parse_error::config_parse_error(const char *fmt, ...)
{
  va_list ap;
  int num;

  va_start(ap, fmt);
  num = vsnprintf(NULL, 0, fmt, ap);
  va_end(ap);

  this->msg = (char *)ats_malloc(num + 1);

  va_start(ap, fmt);
  vsnprintf(&this->msg[0], num + 1, fmt, ap);
  va_end(ap);
}

// char* readIntoBuffer(const char* file_path, const char* module_name,
//                          int* read_size_ptr)
//
//  Attempts to open and read arg file_path into a buffer allocated
//   off the heap (via malloc() )  Returns a pointer to the buffer
//   is successful and NULL otherwise.
//
//  CALLEE is responsibled for deallocating the buffer via free()
//
char *
readIntoBuffer(const char *file_path, const char *module_name, int *read_size_ptr)
{
  int fd;
  struct stat file_info;
  char *file_buf;
  int read_size = 0;

  if (read_size_ptr != NULL) {
    *read_size_ptr = 0;
  }
  // Open the file for Blocking IO.  We will be reading this
  //   at start up and infrequently afterward
  if ((fd = open(file_path, O_RDONLY)) < 0) {
    Error("%s Can not open %s file : %s", module_name, file_path, strerror(errno));
    return NULL;
  }

  if (fstat(fd, &file_info) < 0) {
    Error("%s Can not stat %s file : %s", module_name, file_path, strerror(errno));
    close(fd);
    return NULL;
  }

  if (file_info.st_size < 0) {
    Error("%s Can not get correct file size for %s file : %" PRId64 "", module_name, file_path, (int64_t)file_info.st_size);
    close(fd);
    return NULL;
  }
  // Allocate a buffer large enough to hold the entire file
  //   File size should be small and this makes it easy to
  //   do two passes on the file
  file_buf = (char *)ats_malloc(file_info.st_size + 1);
  // Null terminate the buffer so that string operations will work
  file_buf[file_info.st_size] = '\0';

  read_size = (file_info.st_size > 0) ? read(fd, file_buf, file_info.st_size) : 0;

  // Check to make sure that we got the whole file
  if (read_size < 0) {
    Error("%s Read of %s file failed : %s", module_name, file_path, strerror(errno));
    ats_free(file_buf);
    file_buf = NULL;
  } else if (read_size < file_info.st_size) {
    // We don't want to signal this error on WIN32 because the sizes
    // won't match if the file contains any CR/LF sequence.
    Error("%s Only able to read %d bytes out %d for %s file", module_name, read_size, (int)file_info.st_size, file_path);
    file_buf[read_size] = '\0';
  }

  if (file_buf && read_size_ptr) {
    *read_size_ptr = read_size;
  }

  close(fd);

  return file_buf;
}

// int unescapifyStr(char* buffer)
//
//   Unescapifies a URL without a making a copy.
//    The passed in string is modified
//
int
unescapifyStr(char *buffer)
{
  char *read  = buffer;
  char *write = buffer;
  char subStr[3];

  subStr[2] = '\0';
  while (*read != '\0') {
    if (*read == '%' && *(read + 1) != '\0' && *(read + 2) != '\0') {
      subStr[0] = *(++read);
      subStr[1] = *(++read);
      *write    = (char)strtol(subStr, (char **)NULL, 16);
      read++;
      write++;
    } else if (*read == '+') {
      *write = ' ';
      write++;
      read++;
    } else {
      *write = *read;
      write++;
      read++;
    }
  }
  *write = '\0';

  return (write - buffer);
}

char const *
ExtractIpRange(char *match_str, in_addr_t *min, in_addr_t *max)
{
  IpEndpoint ip_min, ip_max;
  char const *zret = ExtractIpRange(match_str, &ip_min.sa, &ip_max.sa);
  if (0 == zret) { // success
    if (ats_is_ip4(&ip_min) && ats_is_ip4(&ip_max)) {
      if (min)
        *min = ntohl(ats_ip4_addr_cast(&ip_min));
      if (max)
        *max = ntohl(ats_ip4_addr_cast(&ip_max));
    } else {
      zret = "The addresses were not IPv4 addresses.";
    }
  }
  return zret;
}

//   char* ExtractIpRange(char* match_str, sockaddr* addr1,
//                         sockaddr* addr2)
//
//   Attempts to extract either an Ip Address or an IP Range
//     from match_str.  The range should be two addresses
//     separated by a hyphen and no spaces
//
//   If the extraction is successful, sets addr1 and addr2
//     to the extracted values (in the case of a single
//     address addr2 = addr1) and returns NULL
//
//   If the extraction fails, returns a static string
//     that describes the reason for the error.
//
const char *
ExtractIpRange(char *match_str, sockaddr *addr1, sockaddr *addr2)
{
  Tokenizer rangeTok("-/");
  bool mask = strchr(match_str, '/') != NULL;
  int mask_bits;
  int mask_val;
  int numToks;
  IpEndpoint la1, la2;

  // Extract the IP addresses from match data
  numToks = rangeTok.Initialize(match_str, SHARE_TOKS);

  if (numToks < 0) {
    return "no IP address given";
  } else if (numToks > 2) {
    return "malformed IP range";
  }

  if (0 != ats_ip_pton(rangeTok[0], &la1.sa)) {
    return "malformed IP address";
  }

  // Handle a IP range
  if (numToks == 2) {
    if (mask) {
      if (!ats_is_ip4(&la1)) {
        return "Masks supported only for IPv4";
      }
      // coverity[secure_coding]
      if (sscanf(rangeTok[1], "%d", &mask_bits) != 1) {
        return "bad mask specification";
      }

      if (!(mask_bits >= 0 && mask_bits <= 32)) {
        return "invalid mask specification";
      }

      if (mask_bits == 32) {
        mask_val = 0;
      } else {
        mask_val = htonl(0xffffffff >> mask_bits);
      }
      in_addr_t a = ats_ip4_addr_cast(&la1);
      ats_ip4_set(&la2, a | mask_val);
      ats_ip4_set(&la1, a & (mask_val ^ 0xffffffff));

    } else {
      if (0 != ats_ip_pton(rangeTok[1], &la2)) {
        return "malformed ip address at range end";
      }
    }

    if (1 == ats_ip_addr_cmp(&la1.sa, &la2.sa)) {
      return "range start greater than range end";
    }

    ats_ip_copy(addr2, &la2);
  } else {
    ats_ip_copy(addr2, &la1);
  }

  ats_ip_copy(addr1, &la1);
  return NULL;
}

// char* tokLine(char* buf, char** last, char cont)
//
//  Similar to strtok_r but only tokenizes on '\n'
//   and will return tokens that are empty strings
//
char *
tokLine(char *buf, char **last, char cont)
{
  char *start;
  char *cur;
  char *prev = NULL;

  if (buf != NULL) {
    start = cur = buf;
    *last       = buf;
  } else {
    start = cur = (*last) + 1;
  }

  while (*cur != '\0') {
    if (*cur == '\n') {
      if (cont != '\0' && prev != NULL && *prev == cont) {
        *prev = ' ';
        *cur  = ' ';
      } else {
        *cur  = '\0';
        *last = cur;
        return start;
      }
    }
    prev = cur++;
  }

  // Return the last line even if it does
  //  not end in a newline
  if (cur > (*last + 1)) {
    *last = cur - 1;
    return start;
  }

  return NULL;
}

const char *matcher_type_str[] = {"invalid", "host", "domain", "ip", "url_regex", "url", "host_regex"};

// char* processDurationString(char* str, int* seconds)
//
//   Take a duration sting which is composed of
//      digits followed by a unit specifier
//         w - week
//         d - day
//         h - hour
//         m - min
//         s - sec
//
//   Trailing digits without a specifier are
//    assumed to be seconds
//
//   Returns NULL on success and a static
//    error string on failure
//
const char *
processDurationString(char *str, int *seconds)
{
  char *s       = str;
  char *current = str;
  char unit;
  int tmp;
  int multiplier;
  int result = 0;
  int len;

  if (str == NULL) {
    return "Missing time";
  }

  len = strlen(str);
  for (int i = 0; i < len; i++) {
    if (!ParseRules::is_digit(*current)) {
      // Make sure there is a time to proces
      if (current == s) {
        return "Malformed time";
      }

      unit = *current;

      switch (unit) {
      case 'w':
        multiplier = 7 * 24 * 60 * 60;
        break;
      case 'd':
        multiplier = 24 * 60 * 60;
        break;
      case 'h':
        multiplier = 60 * 60;
        break;
      case 'm':
        multiplier = 60;
        break;
      case 's':
        multiplier = 1;
        break;
      case '-':
        return "Negative time not permitted";
      default:
        return "Invalid time unit specified";
      }

      *current = '\0';

      // coverity[secure_coding]
      if (sscanf(s, "%d", &tmp) != 1) {
        // Really should not happen since everything
        //   in the string is digit
        ink_assert(0);
        return "Malformed time";
      }

      result += (multiplier * tmp);
      s = current + 1;
    }
    current++;
  }

  // Read any trailing seconds
  if (current != s) {
    // coverity[secure_coding]
    if (sscanf(s, "%d", &tmp) != 1) {
      // Really should not happen since everything
      //   in the string is digit
      ink_assert(0);
      return "Malformed time";
    } else {
      result += tmp;
    }
  }
  // We rolled over the int
  if (result < 0) {
    return "Time too big";
  }

  *seconds = result;
  return NULL;
}

const matcher_tags http_dest_tags = {"dest_host", "dest_domain", "dest_ip", "url_regex", "url", "host_regex", true};

const matcher_tags ip_allow_tags = {NULL, NULL, "src_ip", NULL, NULL, NULL, false};

const matcher_tags socks_server_tags = {NULL, NULL, "dest_ip", NULL, NULL, NULL, false};

// char* parseConfigLine(char* line, matcher_line* p_line,
//                       const matcher_tags* tags)
//
//   Parse out a config file line suitable for passing to
//    a ControlMatcher object
//
//   If successful, NULL is returned.  If unsuccessful,
//     a static error string is returned
//
const char *
parseConfigLine(char *line, matcher_line *p_line, const matcher_tags *tags)
{
  enum pState {
    FIND_LABEL,
    PARSE_LABEL,
    PARSE_VAL,
    START_PARSE_VAL,
    CONSUME,
  };

  pState state      = FIND_LABEL;
  bool inQuote      = false;
  char *copyForward = NULL;
  char *copyFrom    = NULL;
  char *s           = line;
  char *label       = NULL;
  char *val         = NULL;
  int num_el        = 0;
  matcher_type type = MATCH_NONE;

  // Zero out the parsed line structure
  memset(p_line, 0, sizeof(matcher_line));

  if (*s == '\0') {
    return NULL;
  }

  do {
    switch (state) {
    case FIND_LABEL:
      if (!isspace(*s)) {
        state = PARSE_LABEL;
        label = s;
      }
      s++;
      break;
    case PARSE_LABEL:
      if (*s == '=') {
        *s    = '\0';
        state = START_PARSE_VAL;
      }
      s++;
      break;
    case START_PARSE_VAL:
      // Init state needed for parsing values
      copyForward = NULL;
      copyFrom    = NULL;

      if (*s == '"') {
        inQuote = true;
        val     = s + 1;
      } else if (*s == '\\') {
        inQuote = false;
        val     = s + 1;
      } else {
        inQuote = false;
        val     = s;
      }

      if (inQuote == false && (isspace(*s) || *(s + 1) == '\0')) {
        state = CONSUME;
      } else {
        state = PARSE_VAL;
      }

      s++;
      break;
    case PARSE_VAL:
      if (inQuote == true) {
        if (*s == '\\') {
          // The next character is esacped
          //
          // To remove the escaped character
          // we need to copy
          //  the rest of the entry over it
          //  but since we do not know where the
          //  end is right now, defer the work
          //  into the future

          if (copyForward != NULL) {
            // Perform the prior copy forward
            int bytesCopy = s - copyFrom;
            memcpy(copyForward, copyFrom, s - copyFrom);
            ink_assert(bytesCopy > 0);

            copyForward += bytesCopy;
            copyFrom = s + 1;
          } else {
            copyForward = s;
            copyFrom    = s + 1;
          }

          // Scroll past the escape character
          s++;

          // Handle the case that places us
          //  at the end of the file
          if (*s == '\0') {
            break;
          }
        } else if (*s == '"') {
          state = CONSUME;
          *s    = '\0';
        }
      } else if ((*s == '\\' && ParseRules::is_digit(*(s + 1))) || !ParseRules::is_char(*s)) {
        // INKqa10511
        // traffic server need to handle unicode characters
        // right now ignore the entry
        return "Unrecognized encoding scheme";
      } else if (isspace(*s)) {
        state = CONSUME;
        *s    = '\0';
      }

      s++;

      // If we are now at the end of the line,
      //   we need to consume final data
      if (*s == '\0') {
        state = CONSUME;
      }
      break;
    case CONSUME:
      break;
    }

    if (state == CONSUME) {
      // See if there are any quote copy overs
      //   we've pushed into the future
      if (copyForward != NULL) {
        int toCopy = (s - 1) - copyFrom;
        memcpy(copyForward, copyFrom, toCopy);
        *(copyForward + toCopy) = '\0';
      }

      p_line->line[0][num_el] = label;
      p_line->line[1][num_el] = val;
      type                    = MATCH_NONE;

      // Check to see if this the primary specifier we are looking for
      if (tags->match_ip && strcasecmp(tags->match_ip, label) == 0) {
        type = MATCH_IP;
      } else if (tags->match_host && strcasecmp(tags->match_host, label) == 0) {
        type = MATCH_HOST;
      } else if (tags->match_domain && strcasecmp(tags->match_domain, label) == 0) {
        type = MATCH_DOMAIN;
      } else if (tags->match_regex && strcasecmp(tags->match_regex, label) == 0) {
        type = MATCH_REGEX;
      } else if (tags->match_url && strcasecmp(tags->match_url, label) == 0) {
        type = MATCH_URL;
      } else if (tags->match_host_regex && strcasecmp(tags->match_host_regex, label) == 0) {
        type = MATCH_HOST_REGEX;
      }
      // If this a destination tag, use it
      if (type != MATCH_NONE) {
        // Check to see if this second destination specifier
        if (p_line->type != MATCH_NONE) {
          if (tags->dest_error_msg == false) {
            return "Multiple Sources Specified";
          } else {
            return "Multiple Destinations Specified";
          }
        } else {
          p_line->dest_entry = num_el;
          p_line->type       = type;
        }
      }
      num_el++;

      if (num_el > MATCHER_MAX_TOKENS) {
        return "Malformed line: Too many tokens";
      }

      state = FIND_LABEL;
    }
  } while (*s != '\0');

  p_line->num_el = num_el;

  if (state != CONSUME && state != FIND_LABEL) {
    return "Malformed entry";
  }

  if (!tags->empty() && p_line->type == MATCH_NONE) {
    if (tags->dest_error_msg == false) {
      return "No source specifier";
    } else {
      return "No destination specifier";
    }
  }

  return NULL;
}