Debian Codegraph @

src/String.cpp

raw
1 // String - guess what: it's a string class!
2
3 // For all support, instructions and copyright go to:
4 // http://e2guardian.org/
5 // Released under the GPL v2, with the OpenSSL exception described in the README file.
6
7 // INCLUDES
8
9 #ifdef HAVE_CONFIG_H
10 #include "e2config.h"
11 #endif
12 #include "String.hpp"
13 #include "md5.hpp"
14 #include "Logger.hpp"
15
16 #if defined(__GNUC__) && __GNUC__ < 3 && __GNUC_MINOR__ < 96
17 #warning "Using strstream instead of sstream"
18 #include <strstream>
19 #else
20 #include <sstream>
21 #endif
22
23 #include <cstdlib>
24 #include <cstring>
25 #include <memory>
26
27 extern thread_local std::string thread_id;
28
29
30 // construct string representations of ints/longs
31 #if defined(__GNUC__) && __GNUC__ < 3 && __GNUC_MINOR__ < 96
32 String::String(const int num)
33 {
34 std::ostrstream buf;
35 buf << num << std::ends;
36 *this = buf.str(); // with side effect: it calls buf.freeze()
37 }
38 String::String(const long num)
39 {
40 std::ostrstream buf;
41 buf << num << std::ends;
42 *this = buf.str();
43 }
44 String::String(const unsigned int num)
45 {
46 std::ostrstream buf;
47 buf << num << std::ends;
48 *this = buf.str();
49 }
50 String::String(const long unsigned int num)
51 {
52 std::ostrstream buf;
53 buf << num << std::ends;
54 *this = buf.str();
55 }
56 #ifndef OFFT_COLLISION
57 // If large file support is not enabled (and possibly even if it is),
58 // the type of off_t may be a typedef of a type for which we already
59 // have a constructor. In that case, don't define one which takes an
60 // off_t, or we get compiler errors.
61 String::String(const off_t num)
62 {
63 std::ostrstream buf;
64 buf << num << std::ends;
65 *this = buf.str();
66 }
67 #endif
68 #else
69 String::String(const int num)
70 {
71 std::stringstream buf;
72 buf << num << std::ends;
73 // std::string can contain a NULL byte within the counted length
74 // - this happens here. Add a byte to the length when allocating
75 // the buffer it's going to go into (to account for the appended
76 // NULL), but subtract one when updating our idea of what the string
77 // length is, since it counts the NULL byte in the stringstream's
78 // own buffer.
79 int l = buf.str().length();
80 char *data = new char[l + 1];
81 buf >> data;
82 *this = data;
83 delete[] data;
84 }
85 String::String(const long num)
86 {
87 std::stringstream buf;
88 buf << num << std::ends;
89 int l = buf.str().length();
90 char *data = new char[l + 1];
91 buf >> data;
92 *this = data;
93 delete[] data;
94 }
95 String::String(const unsigned int num)
96 {
97 std::stringstream buf;
98 buf << num << std::ends;
99 int l = buf.str().length();
100 char *data = new char[l + 1];
101 buf >> data;
102 *this = data;
103 delete[] data;
104 }
105 String::String(const long unsigned num)
106 {
107 std::stringstream buf;
108 buf << num << std::ends;
109 int l = buf.str().length();
110 char *data = new char[l + 1];
111 buf >> data;
112 *this = data;
113 delete[] data;
114 }
115
116 String::String(const bool flag)
117 {
118 if (flag) {
119 char buff[2] = "1";
120 *this = buff;
121 } else {
122 char buff[2] = "0";
123 *this = buff;
124 }
125 }
126
127 #ifndef OFFT_COLLISION
128 // If large file support is not enabled (and possibly even if it is),
129 // the type of off_t may be a typedef of a type for which we already
130 // have a constructor. In that case, don't define one which takes an
131 // off_t, or we get compiler errors.
132 String::String(const off_t num)
133 {
134 std::stringstream buf;
135 buf << num << std::ends;
136 int l = buf.str().length();
137 char *data = new char[l + 1];
138 buf >> data;
139 *this = data;
140 delete[] data;
141 }
142 #endif
143 #endif
144
145 void String::replaceall(const char *what, const char *with)
146 {
147 std::string::size_type pos = 0;
148 size_t whatlen = strlen(what);
149 size_t withlen = strlen(with);
150 while ((pos = this->find(what, pos)) != std::string::npos) {
151 // replace charactrs in original string
152 this->replace(pos, whatlen, with);
153 // increment search position
154 pos += withlen;
155 }
156 }
157
158 // string-to-off_t conversion
159 // This is horrible, horrible code, but the best I can come up with
160 // which will work in both 32 and 64-bit file offset modes. :(
161 off_t String::toOffset()
162 {
163 if (this->length() == 0)
164 return 0;
165 off_t t = 0;
166
167 this->removeWhiteSpace();
168
169 #if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
170 sscanf(this->c_str(), "%lld", &t);
171 #else
172 sscanf(this->c_str(), "%ld", &t);
173 #endif
174
175 return t;
176 }
177
178 // string-to-integer conversion
179 int String::toInteger()
180 {
181 if (this->length() == 0) {
182 return 0;
183 }
184 return (atoi(this->c_str()));
185 }
186
187 // string-to-long-int conversion
188 long int String::toLong()
189 {
190 if (this->length() == 0) {
191 return 0;
192 }
193 return (atol(this->c_str()));
194 }
195
196 // return integer from hex string
197 long int String::hexToInteger()
198 {
199 int n = 0; // position in string
200 int m = 0; // position in digit[] to shift
201 int count; // loop index
202 long int intValue = 0; // integer value of hex string
203 int digit[15]; // hold values to convert
204 while (n < 14) {
205 if ((*this)[n] == '\0')
206 break;
207 if ((*this)[n] >= '0' && (*this)[n] <= '9')
208 digit[n] = (*this)[n] & 0x0f;
209 else if (((*this)[n] >= 'a' && (*this)[n] <= 'f') || ((*this)[n] >= 'A' && (*this)[n] <= 'F'))
210 digit[n] = ((*this)[n] & 0x0f) + 9;
211 else
212 break;
213 n++;
214 }
215 count = n;
216 m = n - 1;
217 n = 0;
218 while (n < count) {
219 // digit[n] is value of hex digit at position n
220 // (m << 2) is the number of positions to shift
221 // OR the bits into return value
222 intValue = intValue | (digit[n] << (m << 2));
223 m--;
224 n++;
225 }
226 return (intValue);
227 }
228
229 // case conversions
230 void String::toLower()
231 {
232 unsigned int l = this->length();
233 char *c = new char[l + 1];
234 const char *d = this->c_str();
235 for (unsigned int i = 0; i < l; i++) {
236 c[i] = tolower(d[i]);
237 }
238 *this = String(c, l);
239 delete[] c;
240 }
241
242 void String::toUpper()
243 {
244 unsigned int l = this->length();
245 char *c = new char[l + 1];
246 const char *d = this->c_str();
247 for (unsigned int i = 0; i < l; i++) {
248 c[i] = toupper(d[i]);
249 }
250 *this = String(c, l);
251 delete[] c;
252 }
253
254 // swap chars
255 void String::swapChar(char old, char newc)
256 {
257 unsigned int l = this->length();
258 char *c = new char[l + 1];
259 const char *d = this->c_str();
260 for (unsigned int i = 0; i < l; i++) {
261 if (d[i] == old) {
262 c[i] = newc;
263 } else {
264 c[i] = d[i];
265 }
266 }
267 *this = String(c, l);
268 delete [] c;
269 }
270
271 void String::removeChar(char old)
272 {
273 unsigned int l = this->length();
274 char *c = new char[l + 1];
275 unsigned int j = 0;
276 const char *d = this->c_str();
277 for (unsigned int i = 0; i < l; i++) {
278 if (d[i] != old) {
279 c[j++] = d[i];
280 }
281 }
282 c[j] = 0;
283 *this = String(c);
284 delete [] c;
285 }
286
287 void String::baseDir()
288 {
289 size_t fnsize;
290 if ((fnsize = this->find_last_of("/")) > 0)
291 *this = this->subString(0,++fnsize);
292 }
293
294 void String::fullPath(String &base_dir) {
295 if(!this->startsWith("/"))
296 {
297 String temp(base_dir);
298 temp += *this;
299 *this = temp;
300 }
301 }
302
303 // decode %xx to individual characters (checkme: i'm sure this is duplicated elsewhere...)
304 void String::hexDecode() //TODO: make this more efficient - use similar login to hex2integer
305 {
306 if (this->length() < 3)
307 return;
308 char *temp = new char[this->length() + 1];
309 const char *t = this->c_str();
310 unsigned char c;
311 unsigned char c1;
312 unsigned char c2;
313 unsigned char c3;
314 char hexval[5] = "0x"; // Initializes a "hexadecimal string"
315 hexval[4] = '\0';
316 char *ptr; // pointer required by strtol
317 ptr = NULL;
318 unsigned int j = 0;
319 unsigned int end = this->length() - 2;
320 unsigned int i, k;
321 for (i = 0; i < end;) {
322 c1 = t[i];
323 c2 = t[i + 1];
324 c3 = t[i + 2];
325 if (c1 == '%' && (((c2 >= '0') && (c2 <= '9')) || ((c2 >= 'a') && (c2 <= 'f')) || ((c2 >= 'A') && (c2 <= 'F'))) && (((c3 >= '0') && (c3 <= '9')) || ((c3 >= 'a') && (c3 <= 'f')) || ((c3 >= 'A') && (c3 <= 'F')))) {
326 hexval[2] = c2;
327 hexval[3] = c3;
328 c = (unsigned char)strtol(hexval, &ptr, 0);
329 i += 3;
330 } else {
331 c = c1;
332 i++;
333 }
334 temp[j++] = c;
335 }
336 k = this->length();
337 for (; i < k; i++) {
338 temp[j++] = t[i]; // copy last 2 bytes if any//
339 }
340 temp[j] = '\0';
341 (*this) = String(temp, j);
342 delete[] temp;
343 }
344
345 // does this string start with the given text?
346 bool String::startsWith(const String &s) const
347 {
348 return (strncmp(this->c_str(), s.c_str(), s.length()) == 0);
349 }
350
351 // does this string end with the given text?
352 bool String::endsWith(const String &s) const
353 {
354 if (s.length() > this->length()) {
355 return false;
356 }
357 if (!strncmp((this->c_str() + this->length() - s.length()), s.c_str(), s.length())) {
358 return true;
359 }
360 return false;
361 }
362
363 // does this string start with the given text after conversion to lowercase?
364 // (pass the search string in in lowercase; only the text being searched
365 // is converted)
366 bool String::startsWithLower(const String &s) const
367 {
368 if (s.length() > this->length()) {
369 return false;
370 }
371 for (unsigned int i = 0; i < s.length(); i++) {
372 if (tolower((*this)[i]) != s[i])
373 return false;
374 }
375 return true;
376 }
377
378 // find the position of the given substring within the string
379 int String::indexOf(const char *s) const
380 {
381 size_type i = this->find(s);
382 if (i != std::string::npos)
383 return i;
384 return -1;
385 }
386
387 // does this string contain given substring?
388 bool String::contains(const char *s) const
389 {
390 if (this->length() >= strlen(s)) {
391 if (indexOf(s) != -1) {
392 return true;
393 }
394 }
395 return false;
396 }
397
398 // grab the part of the string that follows the first occurrence of given text
399 String String::after(const char *bs) const
400 {
401 if (this->length() < strlen(bs))
402 return "";
403 size_type i = this->find(bs);
404 if (i == std::string::npos)
405 return "";
406 return this->substr(i + strlen(bs));
407 }
408
409 // grab the part of the string that precedes the first occurrence of given text
410 String String::before(const char *bs) const
411 {
412 if (this->length() < strlen(bs))
413 return "";
414 size_type i = this->find(bs);
415 if (i == std::string::npos)
416 return "";
417 return this->substr(0, i);
418 }
419
420 bool String::headerVal()
421 {
422 *this = this->after(":");
423 this->removeWhiteSpace();
424 if (this->length() > 0)
425 return true;
426 else
427 return false;
428 };
429
430 // remove characters from end/beginning
431 void String::chop()
432 {
433 if (this->length() > 0)
434 *this = this->substr(0, this->length() - 1);
435 }
436
437 void String::lop()
438 {
439 if (this->length() > 0)
440 *this = this->substr(1);
441 }
442
443 // remove leading & trailing whitespace
444 void String::removeWhiteSpace()
445 {
446 size_type start = this->find_first_not_of(" \t\r\n");
447 if (start == std::string::npos)
448 start = 0;
449 size_type end = this->find_last_not_of(" \t\r\n");
450 if (end == std::string::npos)
451 end = this->length() - 1;
452 *this = this->substr(start, (end - start) + 1);
453 }
454
455 void String::removePunctuation() {
456 std::string temp;
457 bool lastspace = false;
458 unsigned char t;
459 unsigned int l = this->length();
460 for (unsigned int i = 0; i < l; i++) {
461 t = (*this)[i];
462 if (t < '/' || t == ':' || t == ';' || t == '=' || t == '?' || t == '@' || (t > 90 && t < 97)) {
463 t = 32; // convert all whitespace and most punctuation marks to a space
464 }
465 if (t == 32) {
466 if (lastspace) continue;
467 lastspace = true;
468 } else {
469 lastspace = false;
470 }
471 temp += t;
472 continue;
473 }
474 *this = temp;
475 }
476
477 // remove protocol specifier
478 void String::removePTP()
479 {
480 if (this->startsWith("http://") || this->startsWith("https://")
481 || this->startsWith("ftp://")) {
482 *this = this->after("://");
483 }
484 }
485 // get hostname from string as url
486 String String::getHostname()
487 {
488 String hostname;
489 hostname = this->substr(0);
490 if (hostname.contains("://"))
491 hostname = hostname.after("://");
492 if (hostname.contains("/"))
493 hostname = hostname.before("/");
494 if (hostname.contains("@")) // Contains a username:password combo
495 hostname = hostname.after("@");
496 return hostname;
497 }
498
499 // limit string to given length
500 int String::limitLength(unsigned int l)
501 {
502 *this = this->substr(0, l);
503 return this->length();
504 }
505
506 // remove repeated occurrences of given character
507 void String::removeMultiChar(unsigned char c)
508 {
509 std::string temp;
510 unsigned char t;
511 bool wasslash = false;
512 unsigned int l = this->length();
513 for (unsigned int i = 0; i < l; i++) {
514 t = (*this)[i];
515 if (t != c) {
516 // we didn't find the character - copy what we did find,
517 // and clear repetition flag
518 temp += t;
519 wasslash = false;
520 continue;
521 }
522 // we found the character
523 if (wasslash) {
524 // we found it repeated - don't copy it again
525 continue;
526 }
527 // we found the character, without repetition flag set
528 // - copy only first occurrence & set repetition flag
529 wasslash = true;
530 temp += t;
531 }
532 *this = temp;
533 }
534
535 // tidy up slashes, trailing dots, etc. in file paths
536 void String::realPath()
537 {
538 if (this->length() < 3) {
539 return;
540 }
541 char *temp = new char[this->length() + 1];
542 unsigned char b, c, d;
543 unsigned int offset = 0, l = this->length();
544 for (unsigned int i = 0; i < l; i++) {
545 b = (*this)[i];
546 if (b == '/') {
547 if ((*this)[i + 1] == '/') { // ignore multiple slashes
548 continue;
549 }
550 }
551 if (b == '.') {
552 c = (*this)[i + 1];
553 if (c == '\0' || c == '/') {
554 continue; // ignore just dot
555 }
556 if (c == '.') {
557 d = (*this)[i + 2];
558 if (d == '\0' || d == '/' || d == '\\') {
559 if (offset > 0) {
560 offset--;
561 }
562 while (offset > 0) {
563 if (temp[--offset] == '/') {
564 break;
565 }
566 if (temp[offset] == '\\') {
567 break;
568 }
569 }
570 i++;
571 continue;
572 }
573 }
574 }
575 temp[offset++] = b;
576 }
577 temp[offset] = '\0';
578 *this = temp;
579 delete[] temp;
580 }
581
582 // *
583 // *
584 // * Hashing functions
585 // *
586 // *
587
588 String String::md5(const char *salt)
589 {
590 String newValue(*this);
591 newValue += salt;
592 return newValue.md5();
593 }
594
595 String String::md5()
596 {
597 char *md5array = new char[16];
598 char *buf = new char[16];
599 int i;
600
601 String ret;
602
603 md5_buffer(this->c_str(), (size_t) this->length(), md5array);
604
605 for (i = 0; i < 16; i++) {
606 sprintf(buf, "%02X", (unsigned char)(md5array[i]));
607 ret += buf;
608 }
609
610 delete[] md5array;
611 delete[] buf;
612
613 return ret;
614 }
615
616 String String::sort_search()
617 {
618 this->toLower();
619 int ln = this->length();
620 if (ln < 3) {
621 return (*this);
622 }
623 //char *temp = new (std::nothrow) char[ln + 1];
624 //if (temp == NULL) {
625 // E2LOGGER_error("Unable to create temp char[%d] in sort_search", ln);
626 // return (*this);
627 //}
628 // strcpy(temp, (this)->c_str());
629 std::unique_ptr<char[ ]> temp(new char[ln + 1]);
630 std::strcpy(temp.get(), (this)->c_str());
631 int i = 0;
632 int c = 0;
633 // count '+' signs - gives number of words - 1
634 while (i < ln) {
635 if (temp[i++] == '+')
636 c++;
637 };
638 if (c == 0) { // only one word - nothing to do
639 //delete [] temp;
640 return (*this);
641 };
642 // split into words and index
643 char *p[c + 1];
644 i = 0;
645 int j = 0;
646 char *ind = temp.get();
647 while (i <= c) {
648 p[i] = ind + j;
649 while ((j < ln) & !(ind[j] == '+')) {
650 ++j;
651 };
652 if ( j < ln) ind[j++] = 0;
653 i++;
654 };
655 #ifdef DEBUG_LOW
656 int k = 0;
657 while (k <= c)
658 {
659 // std::cerr << thread_id << "Search word " << k << " is " << p[k] << std::endl;
660 DEBUG_debug("Search word ", k, " is ", p[k]);
661 k++;
662 }
663 #endif
664
665 // sort
666 char *t;
667 bool swap = true;
668 while (swap) {
669 swap = false;
670 j = 0;
671 while (j < c) {
672 if (strcmp(p[j], p[j + 1]) > 0) {
673 swap = true;
674 t = p[j];
675 p[j] = p[j + 1];
676 p[j + 1] = t;
677 }
678 j++;
679 };
680 };
681 #ifdef DEBUG_LOW
682 k = 0;
683 while (k <= c)
684 {
685 //std::cerr << thread_id << "Search word after sort" << k << " is " << p[k] << std::endl;
686 DEBUG_debug("Search word after sort", k, " is ", p[k]);
687 k++;
688 }
689 #endif
690
691 String ret(p[0]);
692 j = 1;
693 while (j <= c) {
694 if (ret.empty())
695 ret = p[j++];
696 else
697 ret = ret + "+" + p[j++];
698 }
699 DEBUG_debug("Search words after sort are ", ret);
700 // delete [] temp;
701 return ret;
702 };
703
704 String String::CN() {
705 if (this->length() < 64)
706 return (*this);
707 String ret = *this;
708 while (ret.length() > 62) {
709 ret = ret.after(".");
710 }
711 ret = "*." + ret;
712 return ret;
713 }
714
715 //bool String::isNull() {
716 // if (*this == NULL)
717 // return true;
718 // return false;
719 //}
720
721 String String::anonimise() {
722 std::string temp;
723 unsigned char t;
724 unsigned int l = this->length();
725 for (unsigned int i = 0; i < l; i++) {
726 t = (*this)[i];
727 if (!(t < '/' || t == ':' || t == ';' || t == '=' || t == '?' || t == '@' || (t > 90 && t < 97))) {
728 t = 'x'; // convert all alphanumeric to 'x'
729 }
730 temp += t;
731 continue;
732 }
733 String ts = temp;
734 return ts;
735 }
736
737 bool String::isIp() {
738 // Regex expression for validating IPv4
739 RegExp ipv4;
740 ipv4.comp("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])");
741
742 RegResult rs;
743
744 if(ipv4.match((*this).c_str(), rs))
745 return true;
746
747 return false;
748
749 // Regex expression for validating IPv6
750 // regex ipv6("((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}");
751 }
752
753 bool String::is_valid_domain() {
754 if (this->empty()) return false;
755 unsigned int l = this->length();
756 if(l < 4) return false; // too short - can not possibly be a valid domain!
757 const char *d = this->c_str();
758 if ((d[0] == '-')||(d[l - 1] == '-')) return false; // hyphens are not allowed at start or end of domain
759 for (unsigned int i = 0; i < l; i++) {
760 if (!((d[i] >= '0' && d[i] <= '9') || (d[i] >= 'A' && d[i] <= 'Z') || (d[i] >= 'a' && d[i] <= 'z') ||
761 (d[i] == '-')||(d[i] == '.'))) {
762 return false;
763 }
764 }
765 return true;
766 }