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 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
|
/*
* Phusion Passenger - http://www.modrails.com/
* Copyright (c) 2011 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _PASSENGER_FILTER_SUPPORT_H_
#define _PASSENGER_FILTER_SUPPORT_H_
#ifdef __cplusplus
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <oxt/tracable_exception.hpp>
#include <string>
#include <set>
#ifndef _PCREPOSIX_H
#include <regex.h>
#endif
#include <cstdio>
#include <cstring>
#include <StaticString.h>
#include <Exceptions.h>
#include <Utils/StrIntUtils.h>
namespace Passenger {
namespace FilterSupport {
using namespace std;
using namespace boost;
using namespace oxt;
class Tokenizer {
public:
enum TokenType {
NONE,
NOT,
AND,
OR,
MATCHES,
NOT_MATCHES,
EQUALS,
NOT_EQUALS,
GREATER_THAN,
GREATER_THAN_OR_EQUALS,
LESS_THAN,
LESS_THAN_OR_EQUALS,
LPARENTHESIS,
RPARENTHESIS,
COMMA,
REGEXP,
STRING,
INTEGER,
TRUE_LIT,
FALSE_LIT,
IDENTIFIER,
END_OF_DATA
};
enum TokenOptions {
NO_OPTIONS = 0,
REGEXP_OPTION_CASE_INSENSITIVE = 1
};
struct Token {
TokenType type;
int options;
unsigned int pos;
unsigned int size;
StaticString rawValue;
Token() {
type = NONE;
}
Token(TokenType _type, unsigned int _pos, unsigned int _size, const StaticString &_rawValue)
: type(_type),
options(NO_OPTIONS),
pos(_pos),
size(_size),
rawValue(_rawValue)
{ }
string toString() const {
return Tokenizer::typeToString(type);
}
};
private:
StaticString data;
bool debug;
unsigned int pos;
static bool isWhitespace(char ch) {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
}
void skipWhitespaces() {
while (pos < data.size() && isWhitespace(data[pos])) {
pos++;
}
}
unsigned int available() const {
return data.size() - pos;
}
char current() const {
return data[pos];
}
char next() const {
return data[pos + 1];
}
static bool isIdentifierChar(char ch) {
return (ch >= 'a' && ch <= 'z')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9')
|| ch == '_';
}
static bool isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
Token logToken(const Token &token) const {
if (debug) {
printf("# Token: %s\n", token.toString().c_str());
}
return token;
}
void raiseSyntaxError(const string &message = "") {
string msg = "Syntax error at character " + toString(pos + 1);
if (!message.empty()) {
msg.append(": ");
msg.append(message);
}
throw SyntaxError(msg);
}
void expectingAtLeast(unsigned int size) {
if (available() < size) {
raiseSyntaxError("at least " + toString(size) +
" more characters expected");
}
}
void expectingNextChar(char ch) {
expectingAtLeast(2);
if (next() != ch) {
raiseSyntaxError("expected '" + toString(ch) +
"', but found '" + toString(next()) +
"'");
}
}
Token matchToken(TokenType type, unsigned int size = 0) {
unsigned int oldPos = pos;
pos += size;
return Token(type, oldPos, size, data.substr(oldPos, size));
}
Token matchTokensStartingWithNegation() {
expectingAtLeast(2);
switch (next()) {
case '~':
return matchToken(NOT_MATCHES, 2);
case '=':
return matchToken(NOT_EQUALS, 2);
default:
raiseSyntaxError("unrecognized operator '" + data.substr(pos, 2) + "'");
return Token(); // Shut up compiler warning.
};
}
Token matchAnd() {
expectingNextChar('&');
return matchToken(AND, 2);
}
Token matchOr() {
expectingNextChar('|');
return matchToken(OR, 2);
}
Token matchTokensStartingWithEquals() {
expectingAtLeast(2);
switch (next()) {
case '~':
return matchToken(MATCHES, 2);
case '=':
return matchToken(EQUALS, 2);
default:
raiseSyntaxError("unrecognized operator '" + data.substr(pos, 2) + "'");
return Token(); // Shut up compiler warning.
}
}
Token matchTokensStartingWithGreaterThan() {
if (available() == 0 || next() != '=') {
return matchToken(GREATER_THAN, 1);
} else {
return matchToken(GREATER_THAN_OR_EQUALS, 2);
}
}
Token matchTokensStartingWithLessThan() {
if (available() == 0 || next() != '=') {
return matchToken(LESS_THAN, 1);
} else {
return matchToken(LESS_THAN_OR_EQUALS, 2);
}
}
Token matchRegexp(char terminator) {
unsigned int start = pos;
bool endFound = false;
// Match initial quote slash.
pos++;
// Match rest of regexp including terminating slash.
while (pos < data.size() && !endFound) {
char ch = current();
if (ch == '\\') {
pos++;
if (pos >= data.size()) {
raiseSyntaxError("unterminated regular expression");
} else {
pos++;
}
} else if (ch == terminator) {
pos++;
endFound = true;
} else {
pos++;
}
}
if (endFound) {
Token t(REGEXP, start, pos - start, data.substr(start, pos - start));
// Match regexp options.
endFound = false;
while (pos < data.size() && !endFound) {
char ch = current();
if (ch == 'i') {
t.options |= Tokenizer::REGEXP_OPTION_CASE_INSENSITIVE;
} else if (isWhitespace(ch)) {
endFound = true;
}
pos++;
}
return t;
} else {
raiseSyntaxError("unterminated regular expression");
return Token(); // Shut up compiler warning.
}
}
Token matchString(char terminator) {
unsigned int start = pos;
bool endFound = false;
// Match initial quote character.
pos++;
// Match rest of string including terminating quote.
while (pos < data.size() && !endFound) {
char ch = current();
if (ch == '\\') {
pos++;
if (pos >= data.size()) {
raiseSyntaxError("unterminated string");
} else {
pos++;
}
} else if (ch == terminator) {
pos++;
endFound = true;
} else {
pos++;
}
}
if (endFound) {
return Token(STRING, start, pos - start, data.substr(start, pos - start));
} else {
raiseSyntaxError("unterminated string");
return Token(); // Shut up compiler warning.
}
}
Token matchInteger() {
unsigned int start = pos;
// Accept initial minus or digit.
pos++;
while (pos < data.size() && isDigit(data[pos])) {
pos++;
}
return Token(INTEGER, start, pos - start, data.substr(start, pos - start));
}
Token matchIdentifier() {
char ch = current();
if ((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
ch == '_') {
unsigned int start = pos;
pos++;
while (pos < data.size() && isIdentifierChar(current())) {
pos++;
}
StaticString val = data.substr(start, pos - start);
if (val == "true") {
return Token(TRUE_LIT, start, pos - start, val);
} else if (val == "false") {
return Token(FALSE_LIT, start, pos - start, val);
} else {
return Token(IDENTIFIER, start, pos - start, val);
}
} else {
raiseSyntaxError("Identifier expected, but got an unknown token");
return Token(); // Shut up compiler warning.
}
}
public:
Tokenizer(const StaticString &data, bool debug = false) {
this->data = data;
this->debug = debug;
pos = 0;
}
Token getNext() {
skipWhitespaces();
if (pos >= data.size()) {
return logToken(Token(END_OF_DATA, data.size(), 0, ""));
}
switch (current()) {
case '!':
return logToken(matchTokensStartingWithNegation());
case '&':
return logToken(matchAnd());
case '|':
return logToken(matchOr());
case '=':
return logToken(matchTokensStartingWithEquals());
case '>':
return logToken(matchTokensStartingWithGreaterThan());
case '<':
return logToken(matchTokensStartingWithLessThan());
case '(':
return logToken(matchToken(LPARENTHESIS, 1));
case ')':
return logToken(matchToken(RPARENTHESIS, 1));
case ',':
return logToken(matchToken(COMMA, 1));
case '/':
return logToken(matchRegexp('/'));
case '%':
expectingAtLeast(3);
if (memcmp(data.data() + pos, "%r{", 3) != 0) {
raiseSyntaxError("expected '%r{', but found '" +
data.substr(pos, 3) + "'");
}
pos += 2;
return logToken(matchRegexp('}'));
case '"':
return logToken(matchString('"'));
case '\'':
return logToken(matchString('\''));
case '-':
return logToken(matchInteger());
default:
if (isDigit(current())) {
return logToken(matchInteger());
} else {
return logToken(matchIdentifier());
}
}
}
static string typeToString(TokenType type) {
switch (type) {
case NONE:
return "NONE";
case NOT:
return "NOT";
case AND:
return "AND";
case OR:
return "OR";
case MATCHES:
return "MATCHES";
case NOT_MATCHES:
return "NOT_MATCHES";
case EQUALS:
return "EQUALS";
case NOT_EQUALS:
return "NOT_EQUALS";
case GREATER_THAN:
return "GREATER_THAN";
case GREATER_THAN_OR_EQUALS:
return "GREATER_THAN_OR_EQUALS";
case LESS_THAN:
return "LESS_THAN";
case LESS_THAN_OR_EQUALS:
return "LESS_THAN_OR_EQUALS";
case LPARENTHESIS:
return "LPARENTHESIS";
case RPARENTHESIS:
return "RPARENTHESIS";
case COMMA:
return "COMMA";
case REGEXP:
return "REGEXP";
case STRING:
return "STRING";
case INTEGER:
return "INTEGER";
case TRUE_LIT:
return "TRUE";
case FALSE_LIT:
return "FALSE";
case IDENTIFIER:
return "IDENTIFIER";
case END_OF_DATA:
return "END_OF_DATA";
default:
return "(unknown)";
}
}
};
enum ValueType {
REGEXP_TYPE,
STRING_TYPE,
INTEGER_TYPE,
BOOLEAN_TYPE,
UNKNOWN_TYPE
};
class Context {
public:
enum FieldIdentifier {
URI,
CONTROLLER,
RESPONSE_TIME,
RESPONSE_TIME_WITHOUT_GC,
STATUS,
STATUS_CODE,
GC_TIME
};
virtual ~Context() { }
virtual string getURI() const = 0;
virtual string getController() const = 0;
virtual int getResponseTime() const = 0;
virtual string getStatus() const = 0;
virtual int getStatusCode() const = 0;
virtual int getGcTime() const = 0;
virtual bool hasHint(const string &name) const = 0;
int getResponseTimeWithoutGc() const {
return getResponseTime() - getGcTime();
}
string queryStringField(FieldIdentifier id) const {
switch (id) {
case URI:
return getURI();
case CONTROLLER:
return getController();
case RESPONSE_TIME:
return toString(getResponseTime());
case RESPONSE_TIME_WITHOUT_GC:
return toString(getResponseTimeWithoutGc());
case STATUS:
return getStatus();
case STATUS_CODE:
return toString(getStatusCode());
case GC_TIME:
return toString(getGcTime());
default:
return "";
}
}
int queryIntField(FieldIdentifier id) const {
switch (id) {
case RESPONSE_TIME:
return getResponseTime();
case RESPONSE_TIME_WITHOUT_GC:
return getResponseTimeWithoutGc();
case STATUS_CODE:
return getStatusCode();
case GC_TIME:
return getGcTime();
default:
return 0;
}
}
bool queryBoolField(FieldIdentifier id) const {
switch (id) {
case URI:
return !getURI().empty();
case CONTROLLER:
return !getController().empty();
case RESPONSE_TIME:
return getResponseTime() > 0;
case RESPONSE_TIME_WITHOUT_GC:
return getResponseTimeWithoutGc() > 0;
case STATUS:
return !getStatus().empty();
case STATUS_CODE:
return getStatusCode() > 0;
case GC_TIME:
return getGcTime() > 0;
default:
return false;
}
}
static ValueType getFieldType(FieldIdentifier id) {
switch (id) {
case URI:
case CONTROLLER:
case STATUS:
return STRING_TYPE;
case RESPONSE_TIME:
case RESPONSE_TIME_WITHOUT_GC:
case STATUS_CODE:
case GC_TIME:
return INTEGER_TYPE;
default:
return UNKNOWN_TYPE;
}
}
};
class SimpleContext: public Context {
public:
string uri;
string controller;
string status;
int responseTime;
int statusCode;
int gcTime;
set<string> hints;
SimpleContext() {
responseTime = 0;
statusCode = 0;
gcTime = 0;
}
virtual string getURI() const {
return uri;
}
virtual string getController() const {
return controller;
}
virtual int getResponseTime() const {
return responseTime;
}
virtual string getStatus() const {
return status;
}
virtual int getStatusCode() const {
return statusCode;
}
virtual int getGcTime() const {
return gcTime;
}
virtual bool hasHint(const string &name) const {
return hints.find(name) != hints.end();
}
};
class ContextFromLog: public Context {
private:
StaticString logData;
mutable SimpleContext *parsedData;
struct ParseState {
unsigned long long requestProcessingStart;
unsigned long long requestProcessingEnd;
unsigned long long smallestTimestamp;
unsigned long long largestTimestamp;
unsigned long long gcTimeStart;
unsigned long long gcTimeEnd;
};
static void parseLine(const StaticString &txnId, unsigned long long timestamp,
const StaticString &data, SimpleContext &ctx, ParseState &state)
{
if (startsWith(data, "BEGIN: request processing")) {
state.requestProcessingStart = extractEventTimestamp(data);
} else if (startsWith(data, "END: request processing")
|| startsWith(data, "FAIL: request processing")) {
state.requestProcessingEnd = extractEventTimestamp(data);
} else if (startsWith(data, "URI: ")) {
ctx.uri = data.substr(data.find(':') + 2);
} else if (startsWith(data, "Controller action: ")) {
StaticString value = data.substr(data.find(':') + 2);
size_t pos = value.find('#');
if (pos != string::npos) {
ctx.controller = value.substr(0, pos);
}
} else if (startsWith(data, "Status: ")) {
StaticString value = data.substr(data.find(':') + 2);
ctx.status = value;
ctx.statusCode = stringToInt(value);
} else if (startsWith(data, "Initial GC time: ")) {
StaticString value = data.substr(data.find(':') + 2);
state.gcTimeStart = stringToULL(value);
} else if (startsWith(data, "Final GC time: ")) {
StaticString value = data.substr(data.find(':') + 2);
state.gcTimeEnd = stringToULL(value);
}
if (state.smallestTimestamp == 0 || timestamp < state.smallestTimestamp) {
state.smallestTimestamp = timestamp;
}
if (timestamp > state.largestTimestamp) {
state.largestTimestamp = timestamp;
}
}
static void reallyParse(const StaticString &data, SimpleContext &ctx) {
const char *current = data.data();
const char *end = data.data() + data.size();
ParseState state;
memset(&state, 0, sizeof(state));
while (current < end) {
current = skipNewlines(current, end);
if (current < end) {
const char *endOfLine = findEndOfLine(current, end);
StaticString line(current, endOfLine - current);
if (!line.empty()) {
StaticString txnId;
unsigned long long timestamp;
unsigned int writeCount;
StaticString lineData;
// If we want to do more complicated analysis we should sort
// the lines but for the purposes of ContextFromLog
// analyzing the data without sorting is good enough.
if (splitLine(line, txnId, timestamp, writeCount, lineData)) {
parseLine(txnId, timestamp, lineData, ctx,
state);
}
}
current = endOfLine;
}
}
if (state.requestProcessingEnd != 0) {
ctx.responseTime = int(state.requestProcessingEnd -
state.requestProcessingStart);
} else if (state.smallestTimestamp != 0) {
ctx.responseTime = state.largestTimestamp - state.smallestTimestamp;
}
if (state.gcTimeEnd != 0) {
ctx.gcTime = state.gcTimeEnd - state.gcTimeStart;
}
}
static bool splitLine(const StaticString &line, StaticString &txnId,
unsigned long long ×tamp, unsigned int &writeCount,
StaticString &data)
{
size_t firstDelim = line.find(' ');
if (firstDelim == string::npos) {
return false;
}
size_t secondDelim = line.find(' ', firstDelim + 1);
if (secondDelim == string::npos) {
return false;
}
size_t thirdDelim = line.find(' ', secondDelim + 1);
if (thirdDelim == string::npos) {
return false;
}
txnId = line.substr(0, firstDelim);
timestamp = hexatriToULL(line.substr(firstDelim + 1, secondDelim - firstDelim - 1));
writeCount = (unsigned int) hexatriToULL(line.substr(secondDelim + 1,
thirdDelim - secondDelim - 1));
data = line.substr(thirdDelim + 1);
return true;
}
static unsigned long long extractEventTimestamp(const StaticString &data) {
size_t pos = data.find('(');
if (pos == string::npos) {
return 0;
} else {
pos++;
size_t start = pos;
while (pos < data.size() && isDigit(data[pos])) {
pos++;
}
if (pos >= data.size()) {
return 0;
} else {
return hexatriToULL(data.substr(start, pos - start));
}
}
}
static bool isNewline(char ch) {
return ch == '\n' || ch == '\r';
}
static bool isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
static const char *skipNewlines(const char *current, const char *end) {
while (current < end && isNewline(*current)) {
current++;
}
return current;
}
static const char *findEndOfLine(const char *current, const char *end) {
while (current < end && !isNewline(*current)) {
current++;
}
return current;
}
SimpleContext *parse() const {
if (parsedData == NULL) {
auto_ptr<SimpleContext> ctx(new SimpleContext());
reallyParse(logData, *ctx.get());
parsedData = ctx.release();
}
return parsedData;
}
public:
ContextFromLog(const StaticString &logData) {
this->logData = logData;
parsedData = NULL;
}
~ContextFromLog() {
delete parsedData;
}
virtual string getURI() const {
return parse()->uri;
}
virtual string getController() const {
return parse()->getController();
}
virtual int getResponseTime() const {
return parse()->getResponseTime();
}
virtual string getStatus() const {
return parse()->getStatus();
}
virtual int getStatusCode() const {
return parse()->getStatusCode();
}
virtual int getGcTime() const {
return parse()->getGcTime();
}
virtual bool hasHint(const string &name) const {
return parse()->hasHint(name);
}
};
class Filter {
private:
typedef Tokenizer::Token Token;
typedef Tokenizer::TokenType TokenType;
struct BooleanComponent;
struct MultiExpression;
struct Comparison;
struct FunctionCall;
typedef shared_ptr<BooleanComponent> BooleanComponentPtr;
typedef shared_ptr<MultiExpression> MultiExpressionPtr;
typedef shared_ptr<Comparison> ComparisonPtr;
typedef shared_ptr<FunctionCall> FunctionCallPtr;
struct BooleanComponent {
virtual ~BooleanComponent() { }
virtual bool evaluate(const Context &ctx) = 0;
};
enum LogicalOperator {
AND,
OR
};
enum Comparator {
MATCHES,
NOT_MATCHES,
EQUALS,
NOT_EQUALS,
GREATER_THAN,
GREATER_THAN_OR_EQUALS,
LESS_THAN,
LESS_THAN_OR_EQUALS,
UNKNOWN_COMPARATOR
};
struct MultiExpression: public BooleanComponent {
struct Part {
LogicalOperator theOperator;
BooleanComponentPtr expression;
};
BooleanComponentPtr firstExpression;
vector<Part> rest;
virtual bool evaluate(const Context &ctx) {
bool result = firstExpression->evaluate(ctx);
unsigned int i = 0;
bool done = i == rest.size();
while (!done) {
Part &nextPart = rest[i];
if (nextPart.theOperator == AND) {
result = result && nextPart.expression->evaluate(ctx);
done = !result;
} else {
result = result || nextPart.expression->evaluate(ctx);
}
i++;
done = done || i == rest.size();
}
return result;
}
};
struct Negation: public BooleanComponent {
BooleanComponentPtr expr;
Negation(const BooleanComponentPtr &e)
: expr(e)
{ }
virtual bool evaluate(const Context &ctx) {
return !expr->evaluate(ctx);
}
};
struct Value {
enum Source {
REGEXP_LITERAL,
STRING_LITERAL,
INTEGER_LITERAL,
BOOLEAN_LITERAL,
CONTEXT_FIELD_IDENTIFIER
};
Source source;
union {
struct {
char stringStorage[sizeof(string)];
struct {
regex_t regexp;
int options;
} regexp;
} stringOrRegexpValue;
int intValue;
bool boolValue;
Context::FieldIdentifier contextFieldIdentifier;
} u;
Value() {
source = INTEGER_LITERAL;
u.intValue = 0;
}
Value(const Value &other) {
initializeFrom(other);
}
Value(bool regexp, const StaticString &value, bool caseInsensitive = false) {
if (regexp) {
source = REGEXP_LITERAL;
} else {
source = STRING_LITERAL;
}
new (u.stringOrRegexpValue.stringStorage) string(value.data(), value.size());
if (regexp) {
int options = REG_EXTENDED;
u.stringOrRegexpValue.regexp.options = 0;
if (caseInsensitive) {
options |= REG_ICASE;
u.stringOrRegexpValue.regexp.options |=
Tokenizer::REGEXP_OPTION_CASE_INSENSITIVE;
}
regcomp(&u.stringOrRegexpValue.regexp.regexp,
value.toString().c_str(),
options);
}
}
Value(int val) {
source = INTEGER_LITERAL;
u.intValue = val;
}
Value(bool val) {
source = BOOLEAN_LITERAL;
u.boolValue = val;
}
Value(Context::FieldIdentifier identifier) {
source = CONTEXT_FIELD_IDENTIFIER;
u.contextFieldIdentifier = identifier;
}
~Value() {
freeStorage();
}
Value &operator=(const Value &other) {
freeStorage();
initializeFrom(other);
return *this;
}
regex_t *getRegexpValue(const Context &ctx) const {
if (source == REGEXP_LITERAL) {
return &storedRegexp();
} else {
return NULL;
}
}
string getStringValue(const Context &ctx) const {
switch (source) {
case REGEXP_LITERAL:
case STRING_LITERAL:
return storedString();
case INTEGER_LITERAL:
return toString(u.intValue);
case BOOLEAN_LITERAL:
if (u.boolValue) {
return "true";
} else {
return "false";
}
case CONTEXT_FIELD_IDENTIFIER:
return ctx.queryStringField(u.contextFieldIdentifier);
default:
return "";
}
}
int getIntegerValue(const Context &ctx) const {
switch (source) {
case REGEXP_LITERAL:
return 0;
case STRING_LITERAL:
return atoi(storedString());
case INTEGER_LITERAL:
return u.intValue;
case BOOLEAN_LITERAL:
return (int) u.boolValue;
case CONTEXT_FIELD_IDENTIFIER:
return ctx.queryIntField(u.contextFieldIdentifier);
default:
return 0;
}
}
bool getBooleanValue(const Context &ctx) const {
switch (source) {
case REGEXP_LITERAL:
return true;
case STRING_LITERAL:
return !storedString().empty();
case INTEGER_LITERAL:
return (bool) u.intValue;
case BOOLEAN_LITERAL:
return u.boolValue;
case CONTEXT_FIELD_IDENTIFIER:
return ctx.queryBoolField(u.contextFieldIdentifier);
default:
return 0;
}
}
ValueType getType() const {
switch (source) {
case REGEXP_LITERAL:
return REGEXP_TYPE;
case STRING_LITERAL:
return STRING_TYPE;
case INTEGER_LITERAL:
return INTEGER_TYPE;
case BOOLEAN_LITERAL:
return BOOLEAN_TYPE;
case CONTEXT_FIELD_IDENTIFIER:
return Context::getFieldType(u.contextFieldIdentifier);
default:
return UNKNOWN_TYPE;
}
}
private:
const string &storedString() const {
return *((string *) u.stringOrRegexpValue.stringStorage);
}
regex_t &storedRegexp() const {
return (regex_t &) u.stringOrRegexpValue.regexp.regexp;
}
void freeStorage() {
if (source == REGEXP_LITERAL || source == STRING_LITERAL) {
storedString().~string();
if (source == REGEXP_LITERAL) {
regfree(&storedRegexp());
}
}
}
void initializeFrom(const Value &other) {
int options;
source = other.source;
switch (source) {
case REGEXP_LITERAL:
new (u.stringOrRegexpValue.stringStorage) string(other.storedString());
options = REG_EXTENDED;
if (other.u.stringOrRegexpValue.regexp.options & Tokenizer::REGEXP_OPTION_CASE_INSENSITIVE) {
options |= REG_ICASE;
}
regcomp(&u.stringOrRegexpValue.regexp.regexp,
storedString().c_str(),
options);
u.stringOrRegexpValue.regexp.options = other.u.stringOrRegexpValue.regexp.options;
break;
case STRING_LITERAL:
new (u.stringOrRegexpValue.stringStorage) string(other.storedString());
break;
case INTEGER_LITERAL:
u.intValue = other.u.intValue;
break;
case BOOLEAN_LITERAL:
u.boolValue = other.u.boolValue;
break;
case CONTEXT_FIELD_IDENTIFIER:
u.contextFieldIdentifier = other.u.contextFieldIdentifier;
break;
}
}
};
struct SingleValueComponent: public BooleanComponent {
Value val;
SingleValueComponent(const Value &v)
: val(v)
{ }
virtual bool evaluate(const Context &ctx) {
return val.getBooleanValue(ctx);
}
};
struct Comparison: public BooleanComponent {
Value subject;
Comparator comparator;
Value object;
virtual bool evaluate(const Context &ctx) {
switch (subject.getType()) {
case STRING_TYPE:
return compareStringOrRegexp(subject.getStringValue(ctx), ctx);
case INTEGER_TYPE:
return compareInteger(subject.getIntegerValue(ctx), ctx);
case BOOLEAN_TYPE:
return compareBoolean(subject.getBooleanValue(ctx), ctx);
default:
// error
return false;
}
}
private:
bool compareStringOrRegexp(const string &str, const Context &ctx) {
switch (comparator) {
case MATCHES:
return regexec(object.getRegexpValue(ctx), str.c_str(), 0, NULL, 0) == 0;
case NOT_MATCHES:
return regexec(object.getRegexpValue(ctx), str.c_str(), 0, NULL, 0) != 0;
case EQUALS:
return str == object.getStringValue(ctx);
case NOT_EQUALS:
return str != object.getStringValue(ctx);
default:
// error
return false;
}
}
bool compareInteger(int value, const Context &ctx) {
int value2 = object.getIntegerValue(ctx);
switch (comparator) {
case EQUALS:
return value == value2;
case NOT_EQUALS:
return value != value2;
case GREATER_THAN:
return value > value2;
case GREATER_THAN_OR_EQUALS:
return value >= value2;
case LESS_THAN:
return value < value2;
case LESS_THAN_OR_EQUALS:
return value <= value2;
default:
// error
return false;
}
}
bool compareBoolean(bool value, const Context &ctx) {
bool value2 = object.getBooleanValue(ctx);
switch (comparator) {
case EQUALS:
return value == value2;
case NOT_EQUALS:
return value != value2;
default:
// error
return false;
}
}
};
struct FunctionCall: public BooleanComponent {
vector<Value> arguments;
virtual void checkArguments() const = 0;
};
struct StartsWithFunctionCall: public FunctionCall {
virtual bool evaluate(const Context &ctx) {
return startsWith(arguments[0].getStringValue(ctx),
arguments[1].getStringValue(ctx));
}
virtual void checkArguments() const {
if (arguments.size() != 2) {
throw SyntaxError("you passed " + toString(arguments.size()) +
" argument(s) to starts_with(), but it accepts exactly 2 arguments");
}
}
};
struct HasHintFunctionCall: public FunctionCall {
virtual bool evaluate(const Context &ctx) {
return ctx.hasHint(arguments[0].getStringValue(ctx));
}
virtual void checkArguments() const {
if (arguments.size() != 1) {
throw SyntaxError("you passed " + toString(arguments.size()) +
" argument(s) to has_hint(), but it accepts exactly 1 argument");
}
}
};
Tokenizer tokenizer;
BooleanComponentPtr root;
Token lookahead;
bool debug;
static bool isLiteralToken(const Token &token) {
return token.type == Tokenizer::REGEXP
|| token.type == Tokenizer::STRING
|| token.type == Tokenizer::INTEGER
|| token.type == Tokenizer::TRUE_LIT
|| token.type == Tokenizer::FALSE_LIT;
}
static bool isValueToken(const Token &token) {
return isLiteralToken(token) || token.type == Tokenizer::IDENTIFIER;
}
static bool isLogicalOperatorToken(const Token &token) {
return token.type == Tokenizer::AND
|| token.type == Tokenizer::OR;
}
static Comparator determineComparator(Tokenizer::TokenType type) {
switch (type) {
case Tokenizer::MATCHES:
return MATCHES;
case Tokenizer::NOT_MATCHES:
return NOT_MATCHES;
case Tokenizer::EQUALS:
return EQUALS;
case Tokenizer::NOT_EQUALS:
return NOT_EQUALS;
case Tokenizer::GREATER_THAN:
return GREATER_THAN;
case Tokenizer::GREATER_THAN_OR_EQUALS:
return GREATER_THAN_OR_EQUALS;
case Tokenizer::LESS_THAN:
return LESS_THAN;
case Tokenizer::LESS_THAN_OR_EQUALS:
return LESS_THAN_OR_EQUALS;
default:
return UNKNOWN_COMPARATOR;
}
}
static bool comparatorAcceptsValueTypes(Comparator cmp, ValueType subjectType, ValueType objectType) {
switch (cmp) {
case MATCHES:
case NOT_MATCHES:
return subjectType == STRING_TYPE && objectType == REGEXP_TYPE;
case EQUALS:
case NOT_EQUALS:
return (subjectType == STRING_TYPE || subjectType == INTEGER_TYPE || subjectType == BOOLEAN_TYPE)
&& subjectType == objectType;
case GREATER_THAN:
case GREATER_THAN_OR_EQUALS:
case LESS_THAN:
case LESS_THAN_OR_EQUALS:
return subjectType == INTEGER_TYPE && objectType == INTEGER_TYPE;
default:
abort();
return false; // Shut up compiler warning.
}
}
static string unescapeCString(const StaticString &data) {
string result;
result.reserve(data.size());
const char *current = data.data();
const char *end = data.data() + data.size();
while (current < end) {
char ch = *current;
if (ch == '\\') {
current++;
if (current < end) {
ch = *current;
switch (ch) {
case 'r':
result.append(1, '\r');
break;
case 'n':
result.append(1, '\n');
break;
case 't':
result.append(1, '\t');
break;
default:
result.append(1, ch);
break;
}
current++;
}
} else {
result.append(1, ch);
current++;
}
}
return result;
}
void logMatch(int level, const char *name) const {
if (level > 100) {
// If level is too deep then it's probably a bug.
abort();
}
if (debug) {
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("Matching: %s\n", name);
}
}
Token peek() const {
return lookahead;
}
bool peek(Tokenizer::TokenType type) const {
return lookahead.type == type;
}
Token match(TokenType type) {
if (lookahead.type == type) {
return match();
} else {
raiseSyntaxError("Expected a " + Tokenizer::typeToString(type) +
" token, but got " + lookahead.toString(),
lookahead);
return Token(); // Shut up compiler warning.
}
}
Token match() {
Token old = lookahead;
lookahead = tokenizer.getNext();
return old;
}
void raiseSyntaxError(const string &msg = "", const Token &token = Token()) {
if (token.type != Tokenizer::NONE) {
string message = "at character " + toString(token.pos + 1);
if (!msg.empty()) {
message.append(": ");
message.append(msg);
}
throw SyntaxError(message);
} else {
throw SyntaxError(msg);
}
}
BooleanComponentPtr matchMultiExpression(int level) {
logMatch(level, "matchMultiExpression()");
MultiExpressionPtr result = make_shared<MultiExpression>();
result->firstExpression = matchExpression(level + 1);
while (isLogicalOperatorToken(peek())) {
MultiExpression::Part part;
part.theOperator = matchOperator(level + 1);
part.expression = matchExpression(level + 1);
result->rest.push_back(part);
}
return result;
}
BooleanComponentPtr matchExpression(int level) {
logMatch(level, "matchExpression()");
bool negate = false;
if (peek(Tokenizer::NOT)) {
match();
negate = true;
}
Token next = peek();
if (next.type == Tokenizer::LPARENTHESIS) {
match();
BooleanComponentPtr expression = matchMultiExpression(level + 1);
match(Tokenizer::RPARENTHESIS);
if (negate) {
return make_shared<Negation>(expression);
} else {
return expression;
}
} else if (isValueToken(next)) {
BooleanComponentPtr component;
Token ¤t = next;
match();
if (peek(Tokenizer::LPARENTHESIS)) {
component = matchFunctionCall(level + 1, current);
} else if (determineComparator(peek().type) != UNKNOWN_COMPARATOR) {
component = matchComparison(level + 1, current);
} else if (current.type == Tokenizer::TRUE_LIT || current.type == Tokenizer::FALSE_LIT) {
component = matchSingleValueComponent(level + 1, current);
} else {
raiseSyntaxError("expected a function call, comparison or boolean literal", current);
}
if (negate) {
return make_shared<Negation>(component);
} else {
return component;
}
} else {
raiseSyntaxError("expected a left parenthesis or an identifier", next);
return BooleanComponentPtr(); // Shut up compiler warning.
}
}
BooleanComponentPtr matchSingleValueComponent(int level, const Token &token) {
logMatch(level, "matchSingleValueComponent()");
return make_shared<SingleValueComponent>(matchLiteral(level + 1, token));
}
ComparisonPtr matchComparison(int level, const Token &subjectToken) {
logMatch(level, "matchComparison()");
ComparisonPtr comparison = make_shared<Comparison>();
comparison->subject = matchValue(level + 1, subjectToken);
comparison->comparator = matchComparator(level + 1);
comparison->object = matchValue(level + 1, match());
if (!comparatorAcceptsValueTypes(comparison->comparator, comparison->subject.getType(), comparison->object.getType())) {
raiseSyntaxError("the comparator cannot operate on the given combination of types", subjectToken);
}
return comparison;
}
FunctionCallPtr matchFunctionCall(int level, const Token &id) {
logMatch(level, "matchFunctionCall()");
FunctionCallPtr function;
if (id.rawValue == "starts_with") {
function = make_shared<StartsWithFunctionCall>();
} else if (id.rawValue == "has_hint") {
function = make_shared<HasHintFunctionCall>();
} else {
raiseSyntaxError("unknown function '" + id.rawValue + "'", id);
}
match(Tokenizer::LPARENTHESIS);
if (isValueToken(peek())) {
function->arguments.push_back(matchValue(level + 1, match()));
while (peek(Tokenizer::COMMA)) {
match();
function->arguments.push_back(matchValue(level + 1, match()));
}
}
match(Tokenizer::RPARENTHESIS);
function->checkArguments();
return function;
}
Value matchValue(int level, const Token &token) {
logMatch(level, "matchValue()");
if (isLiteralToken(token)) {
return matchLiteral(level + 1, token);
} else if (token.type == Tokenizer::IDENTIFIER) {
return matchContextFieldIdentifier(level + 1, token);
} else {
raiseSyntaxError("Unrecognized value token " +
Tokenizer::typeToString(token.type), token);
return Value(); // Shut up compiler warning.
}
}
LogicalOperator matchOperator(int level) {
logMatch(level, "matchOperator()");
if (peek(Tokenizer::AND)) {
logMatch(level + 1, "AND");
match();
return AND;
} else if (peek(Tokenizer::OR)) {
logMatch(level + 1, "OR");
match();
return OR;
} else {
raiseSyntaxError("", peek());
return AND; // Shut up compiler warning.
}
}
Comparator matchComparator(int level) {
logMatch(level, "matchComparator()");
Comparator comparator = determineComparator(peek().type);
if (comparator == UNKNOWN_COMPARATOR) {
raiseSyntaxError("", peek());
return MATCHES; // Shut up compiler warning.
} else {
logMatch(level + 1, Tokenizer::typeToString(peek().type).c_str());
match();
return comparator;
}
}
Value matchLiteral(int level, const Token &token) {
logMatch(level, "matchLiteral()");
if (token.type == Tokenizer::REGEXP) {
logMatch(level + 1, "regexp");
return Value(true, unescapeCString(token.rawValue.substr(1, token.rawValue.size() - 2)),
token.options & Tokenizer::REGEXP_OPTION_CASE_INSENSITIVE);
} else if (token.type == Tokenizer::STRING) {
logMatch(level + 1, "string");
return Value(false, unescapeCString(token.rawValue.substr(1, token.rawValue.size() - 2)));
} else if (token.type == Tokenizer::INTEGER) {
logMatch(level + 1, "integer");
return Value(atoi(token.rawValue.toString()));
} else if (token.type == Tokenizer::TRUE_LIT) {
logMatch(level + 1, "true");
return Value(true);
} else if (token.type == Tokenizer::FALSE_LIT) {
logMatch(level + 1, "false");
return Value(false);
} else {
raiseSyntaxError("regular expression, string, integer or boolean expected", token);
return Value(); // Shut up compiler warning.
}
}
Value matchContextFieldIdentifier(int level, const Token &token) {
logMatch(level, "matchContextFieldIdentifier()");
if (token.rawValue == "uri") {
return Value(Context::URI);
} else if (token.rawValue == "controller") {
return Value(Context::CONTROLLER);
} else if (token.rawValue == "response_time") {
return Value(Context::RESPONSE_TIME);
} else if (token.rawValue == "response_time_without_gc") {
return Value(Context::RESPONSE_TIME_WITHOUT_GC);
} else if (token.rawValue == "status") {
return Value(Context::STATUS);
} else if (token.rawValue == "status_code") {
return Value(Context::STATUS_CODE);
} else if (token.rawValue == "gc_time") {
return Value(Context::GC_TIME);
} else {
raiseSyntaxError("unknown field '" + token.rawValue + "'", token);
return Value(); // Shut up compiler warning.
}
}
public:
Filter(const StaticString &source, bool debug = false)
: tokenizer(source, debug)
{
this->debug = debug;
lookahead = tokenizer.getNext();
root = matchMultiExpression(0);
logMatch(0, "end of data");
match(Tokenizer::END_OF_DATA);
}
bool run(const Context &ctx) {
return root->evaluate(ctx);
}
};
} // namespace FilterSupport
} // namespace Passenger
#endif /* __cplusplus */
/********* C bindings *********/
#ifdef __cplusplus
extern "C" {
#endif
typedef void *PassengerFilter;
PassengerFilter *passenger_filter_create(const char *source, int size, char **error);
void passenger_filter_free(PassengerFilter *filter);
char *passenger_filter_validate(const char *source, int size);
#ifdef __cplusplus
}
#endif
#endif /* _PASSENGER_FILTER_SUPPORT_H_ */
|