Coverage Report

Created: 2026-11-20 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pdns/ext/yahttp/yahttp/utility.hpp
Line
Count
Source
1
#pragma once
2
3
#ifndef YAHTTP_MAX_REQUEST_LINE_SIZE
4
3.97k
#define YAHTTP_MAX_REQUEST_LINE_SIZE 8192
5
#endif
6
7
#ifndef YAHTTP_MAX_REQUEST_FIELDS
8
13.5k
#define YAHTTP_MAX_REQUEST_FIELDS 100
9
#endif
10
11
namespace YaHTTP {
12
  static const char *MONTHS[] = {0,"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",0}; //<! List of months 
13
14
  bool isspace(char c);
15
  bool isspace(char c, const std::locale& loc);
16
  bool isxdigit(char c);
17
  bool isxdigit(char c, const std::locale& loc);
18
  bool isdigit(char c);
19
  bool isdigit(char c, const std::locale& loc);
20
  bool isalnum(char c);
21
  bool isalnum(char c, const std::locale& loc);
22
23
  /*! Case-Insensitive NULL safe comparator for string maps */
24
  struct ASCIICINullSafeComparator {
25
674k
    bool operator() (const std::string& lhs, const std::string& rhs) const {
26
674k
      int v;
27
674k
      std::string::const_iterator lhi = lhs.begin();
28
674k
      std::string::const_iterator rhi = rhs.begin();
29
1.47M
      for(;lhi != lhs.end() && rhi != rhs.end(); lhi++, rhi++)
30
1.15M
        if ((v = ::tolower(*lhi) - ::tolower(*rhi)) != 0) return v<0; 
31
323k
      if (lhi == lhs.end() && rhi != rhs.end()) return true;
32
239k
      if (lhi != lhs.end() && rhi == rhs.end()) return false;
33
227k
      return false; // they are equal
34
239k
    }
35
  };
36
37
  typedef std::map<std::string,std::string,ASCIICINullSafeComparator> strstr_map_t; //<! String to String map
38
39
  /*! Represents a date/time with utc offset */
40
  class DateTime {
41
  public:
42
     bool isSet; //<! if this is initialized yet
43
44
     int year; //<! year, 0 is year 0, not 1900
45
46
     int month; //<! month, range 1-12
47
     int day; //<! day, range 1-31
48
     int wday; //<! week day, range 1-7
49
50
     int hours; //<! hours, range 0-23
51
     int minutes; //<! minutes, range 0-59
52
     int seconds; //<! seconds, range 0-60
53
54
     int utc_offset; //<! UTC offset with minutes (hhmm)
55
56
224k
     DateTime() { 
57
224k
       initialize();
58
224k
     }; //<! Construct and initialize
59
60
224k
     void initialize() {
61
224k
       isSet = false; 
62
224k
       year = month = day = wday = hours = minutes = seconds = utc_offset = 0;
63
224k
       month = 1; // it's invalid otherwise
64
224k
     }; //<! Creates year 0 date
65
66
0
     void fromTm(const struct tm *tm) {
67
0
       year = tm->tm_year + 1900;
68
0
       month = tm->tm_mon + 1;
69
0
       day = tm->tm_mday;
70
0
       hours = tm->tm_hour;
71
0
       minutes = tm->tm_min;
72
0
       seconds = tm->tm_sec;
73
0
       wday = tm->tm_wday;
74
#ifdef HAVE_TM_GMTOFF
75
       utc_offset = tm->tm_gmtoff;
76
#endif
77
0
       isSet = true;
78
0
     }; //<! parses date from struct tm 
79
80
0
     void validate() const {
81
0
       if (wday < 0 || wday > 6) throw std::range_error("Invalid date");
82
0
       if (month < 1 || month > 12) throw std::range_error("Invalid date");
83
0
       if (year < 0) throw std::range_error("Invalid date");
84
0
       if (hours < 0 || hours > 23 ||
85
0
           minutes < 0 || minutes > 59 ||
86
0
           seconds < 0 || seconds > 60) throw std::range_error("Invalid date");
87
0
     }; //<! make sure we are within ranges (not a *REAL* validation, just range check)
88
89
0
     std::string cookie_str() const {
90
0
       std::ostringstream oss;
91
0
       validate();
92
0
       oss << std::setfill('0') << std::setw(2) << day << "-" << MONTHS[month] << "-" << year << " " <<
93
0
         std::setfill('0') << std::setw(2) << hours << ":" << 
94
0
         std::setfill('0') << std::setw(2) << minutes << ":" << 
95
0
         std::setfill('0') << std::setw(2) << seconds << " GMT";
96
0
       return oss.str();
97
0
     }; //<! converts this date into a HTTP Cookie date
98
 
99
0
     void parseCookie(const std::string &cookie_date) {
100
0
       struct tm tm;
101
0
       const char *ptr;
102
0
       if ( (ptr = strptime(cookie_date.c_str(), "%d-%b-%Y %T", &tm)) != NULL
103
#ifdef HAVE_TM_GMTOFF
104
          || (ptr = strptime(cookie_date.c_str(), "%d-%b-%Y %T %z", &tm)) != NULL
105
          || (ptr = strptime(cookie_date.c_str(), "%a, %d-%b-%Y %T %Z", &tm)) != NULL
106
#endif
107
0
          ) {
108
0
          while(*ptr != '\0' && ( YaHTTP::isspace(*ptr) || YaHTTP::isalnum(*ptr) )) ptr++;
109
0
          if (*ptr != '\0') throw YaHTTP::ParseError("Unparseable date (non-final)"); // must be final.
110
0
          fromTm(&tm);
111
0
          this->utc_offset = 0;
112
0
       } else {
113
0
          std::cout << cookie_date << std::endl;
114
0
          throw YaHTTP::ParseError("Unparseable date (did not match pattern cookie)");
115
0
       }
116
0
     }; //<! parses HTTP Cookie date
117
  };
118
119
  /*! Various helpers needed in the code */ 
120
  class Utility {
121
  public:
122
450k
    static std::string decodeURL(const std::string& component) {
123
450k
        std::string result = component;
124
450k
        size_t pos1,pos2;
125
450k
        pos2 = 0;
126
738k
        while((pos1 = result.find_first_of("%", pos2))!=std::string::npos) {
127
292k
           std::string code;
128
292k
           char a,b,c;
129
292k
           if (pos1 + 2 > result.length()) return result; // end of result
130
287k
           code = result.substr(pos1+1, 2);
131
287k
           a = std::tolower(code[0]); b = std::tolower(code[1]);
132
133
287k
           if ((( '0' > a || a > '9') && ('a' > a || a > 'f')) ||
134
222k
              (( '0' > b || b > '9') && ('a' > b || b > 'f'))) {
135
222k
              pos2 = pos1+3;
136
222k
              continue;
137
222k
           }
138
139
64.9k
           if ('0' <= a && a <= '9') a = a - '0';
140
58.8k
           else if ('a' <= a && a <= 'f') a = a - 'a' + 0x0a;
141
64.9k
           if ('0' <= b && b <= '9') b = b - '0';
142
58.8k
           else if ('a' <= b && b <= 'f') b = b - 'a' + 0x0a;
143
144
64.9k
           c = (a<<4)+b;
145
64.9k
           result = result.replace(pos1,3,1,c);
146
64.9k
           pos2=pos1;
147
64.9k
        }
148
445k
        return result;
149
450k
    }; //<! Decodes %xx from string into bytes
150
    
151
0
    static std::string encodeURL(const std::string& component, bool asUrl = true) {
152
0
      std::string result = component;
153
0
      std::string skip = "+-.:,&;_#%[]?/@(){}=";
154
0
      char repl[3];
155
0
      size_t pos;
156
0
      for(std::string::iterator iter = result.begin(); iter != result.end(); iter++) {
157
0
        if (!YaHTTP::isalnum(*iter) && (!asUrl || skip.find(*iter) == std::string::npos)) {
158
          // replace with different thing
159
0
          pos = std::distance(result.begin(), iter);
160
0
          ::snprintf(repl,3,"%02x", static_cast<unsigned char>(*iter));
161
0
          result = result.replace(pos, 1, "%", 1).insert(pos+1, repl, 2);
162
0
          iter = result.begin() + pos + 2;
163
0
        }
164
0
      }
165
0
      return result;
166
0
    }; //<! Escapes any characters into %xx representation when necessary, set asUrl to false to fully encode the url
167
168
0
    static std::string status2text(int status) {
169
0
       switch(status) {
170
0
       case 200:
171
0
           return "OK";
172
0
       case 201:
173
0
           return "Created";
174
0
       case 202:
175
0
           return "Accepted";
176
0
       case 203:
177
0
           return "Non-Authoritative Information";
178
0
       case 204:
179
0
           return "No Content";
180
0
       case 205:
181
0
           return "Reset Content";
182
0
       case 206:
183
0
           return "Partial Content";
184
0
       case 300:
185
0
           return "Multiple Choices";
186
0
       case 301:
187
0
           return "Moved Permanently";
188
0
       case 302:
189
0
           return "Found";
190
0
       case 303:
191
0
           return "See Other";
192
0
       case 304:
193
0
           return "Not Modified";
194
0
       case 305:
195
0
           return "Use Proxy";
196
0
       case 307:
197
0
           return "Temporary Redirect";
198
0
       case 400:
199
0
           return "Bad Request";
200
0
       case 401:
201
0
           return "Unauthorized";
202
0
       case 402:
203
0
           return "Payment Required";
204
0
       case 403: 
205
0
           return "Forbidden";
206
0
       case 404:
207
0
           return "Not Found";
208
0
       case 405:
209
0
           return "Method Not Allowed";
210
0
       case 406:
211
0
           return "Not Acceptable";
212
0
       case 407:
213
0
           return "Proxy Authentication Required";
214
0
       case 408:
215
0
           return "Request Time-out";
216
0
       case 409:
217
0
           return "Conflict";
218
0
       case 410:
219
0
           return "Gone";
220
0
       case 411:
221
0
           return "Length Required";
222
0
       case 412:
223
0
           return "Precondition Failed";
224
0
       case 413:
225
0
           return "Request Entity Too Large";
226
0
       case 414:
227
0
           return "Request-URI Too Large";
228
0
       case 415:
229
0
           return "Unsupported Media Type";
230
0
       case 416:
231
0
           return "Requested range not satisfiable";
232
0
       case 417:
233
0
           return "Expectation Failed";
234
0
       case 422:
235
0
           return "Unprocessable Entity";
236
0
       case 500:
237
0
           return "Internal Server Error";
238
0
       case 501:
239
0
           return "Not Implemented";
240
0
       case 502:
241
0
           return "Bad Gateway";
242
0
       case 503:
243
0
           return "Service Unavailable";
244
0
       case 504:
245
0
           return "Gateway Time-out";
246
0
       case 505:
247
0
           return "HTTP Version not supported";
248
0
       default:
249
0
           return "Unknown Status";
250
0
       }
251
0
    }; //<! static HTTP codes to text mappings
252
253
3.97k
    static strstr_map_t parseUrlParameters(const std::string& parameters) {
254
3.97k
      if (parameters.size() > YAHTTP_MAX_REQUEST_LINE_SIZE) {
255
1
        return {};
256
1
      }
257
3.97k
      std::string::size_type pos = 0;
258
3.97k
      strstr_map_t parameter_map;
259
17.5k
      while (pos != std::string::npos) {
260
        // find next parameter start
261
17.5k
        std::string::size_type nextpos = parameters.find('&', pos);
262
17.5k
        std::string::size_type delim = parameters.find('=', pos);
263
17.5k
        if (delim > nextpos) {
264
12.0k
          delim = nextpos;
265
12.0k
        }
266
17.5k
        std::string key;
267
17.5k
        std::string value;
268
17.5k
        if (delim == std::string::npos) {
269
3.75k
          key = parameters.substr(pos);
270
13.7k
        } else {
271
13.7k
          key = parameters.substr(pos, delim-pos);
272
13.7k
          if (nextpos == std::string::npos) {
273
108
            value = parameters.substr(delim+1);
274
13.6k
          } else {
275
13.6k
            value = parameters.substr(delim+1, nextpos-delim-1);
276
13.6k
          }
277
13.7k
        }
278
17.5k
        if (key.empty()) {
279
          // no parameters at all
280
3.30k
          break;
281
3.30k
        }
282
14.2k
        parameter_map[decodeURL(key)] = decodeURL(value);
283
14.2k
        if (nextpos == std::string::npos) {
284
          // no more parameters left
285
668
          break;
286
668
        }
287
13.5k
        if (parameter_map.size() >= YAHTTP_MAX_REQUEST_FIELDS) {
288
5
          break;
289
5
        }
290
291
13.5k
        pos = nextpos+1;
292
13.5k
      }
293
3.97k
      return parameter_map;
294
3.97k
    }; //<! parses URL parameters into string map 
295
296
122
    static bool iequals(const std::string& a, const std::string& b, size_t length) {
297
122
      std::string::const_iterator ai, bi;
298
122
      size_t i;
299
3.25k
      for(ai = a.begin(), bi = b.begin(), i = 0; ai != a.end() && bi != b.end() && i < length; ai++,bi++,i++) {
300
3.14k
        if (::toupper(*ai) != ::toupper(*bi)) return false;
301
3.14k
      }
302
303
110
      if (ai == a.end() && bi == b.end()) return true;
304
110
      if ((ai == a.end() && bi != b.end()) ||
305
92
          (ai != a.end() && bi == b.end())) return false;
306
      
307
92
      return ::toupper(*ai) == ::toupper(*bi);
308
110
    }; //<! case-insensitive comparison with length
309
310
0
    static bool iequals(const std::string& a, const std::string& b) {
311
0
      if (a.size() != b.size()) return false;
312
0
      return iequals(a,b,a.size());
313
0
    }; //<! case-insensitive comparison
314
315
27.2k
    static void trimLeft(std::string &str) {
316
27.2k
       const std::locale &loc = std::locale::classic();
317
27.2k
       std::string::iterator iter = str.begin();
318
28.2k
       while(iter != str.end() && YaHTTP::isspace(*iter, loc)) iter++;
319
27.2k
       str.erase(str.begin(), iter);
320
27.2k
    }; //<! removes whitespace from left
321
322
27.2k
    static void trimRight(std::string &str) {
323
27.2k
       const std::locale &loc = std::locale::classic();
324
27.2k
       std::string::reverse_iterator iter = str.rbegin();
325
29.9k
       while(iter != str.rend() && YaHTTP::isspace(*iter, loc)) iter++;
326
27.2k
       str.erase(iter.base(), str.end());
327
27.2k
    }; //<! removes whitespace from right
328
329
27.2k
    static void trim(std::string &str) {
330
27.2k
       trimLeft(str);
331
27.2k
       trimRight(str);
332
27.2k
    }; //<! removes whitespace from left and right
333
334
0
    static std::string camelizeHeader(const std::string &str) {
335
0
       std::string::const_iterator iter = str.begin();
336
0
       std::string result;
337
0
       const std::locale &loc = std::locale::classic();
338
339
0
       bool doNext = true;
340
341
0
       while(iter != str.end()) {
342
0
         if (doNext) 
343
0
            result.insert(result.end(), std::toupper(*iter, loc));
344
0
         else 
345
0
            result.insert(result.end(), std::tolower(*iter, loc)); 
346
0
         doNext = (*(iter++) == '-');
347
0
       }
348
349
0
       return result;
350
0
   }; //<! camelizes headers, such as, content-type => Content-Type
351
  };
352
};