AccessLogger.java 24 KB
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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.scene7.is.util.callbacks.Prox2
 *  javax.servlet.http.Cookie
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  javax.servlet.http.HttpSession
 */
package com.adobe.cq.dam.s7imaging.impl.ps.access_log;

import com.adobe.cq.dam.s7imaging.impl.ps.access_log.HttpResponseWrapper;
import com.adobe.cq.dam.s7imaging.impl.ps.access_log.TimeStamper;
import com.scene7.is.util.callbacks.Prox2;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AccessLogger {
    public static final String COMMON_ALIAS = "common";
    public static final String COMMON_PATTERN = "%h %l %u %t \"%r\" %s %b";
    public static final String COMBINED_ALIAS = "combined";
    public static final String COMBINED_PATTERN = "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"";
    private final AtomicInteger overlap = new AtomicInteger();
    private static final String DEFAULT_LOG_DIR = "logs";
    private static final String DEFAULT_TRACE_SUFFIX = ".log";
    private static final String DEFAULT_ACCESS_PREFIX = "access-";
    private static final String REFERER = "referer";
    private static final String USER_AGENT = "user-agent";
    private long timeThreshold = -1;
    private Set<Integer> statusFilter = new HashSet<Integer>();
    private String dateStamp = "";
    private String directory = "logs";
    private int maxDays = 10;
    protected static final String info = "org.apache.catalina.valves.AccessLogValve/1.0";
    protected static final String[] months = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    private boolean enabled = true;
    private boolean common;
    private boolean combined;
    private String pattern;
    private String prefix = "access-";
    private boolean rotatable = true;
    private boolean started;
    private String suffix = ".log";
    private PrintWriter writer;
    private SimpleDateFormat dateFormatter;
    private SimpleDateFormat dayFormatter;
    private SimpleDateFormat monthFormatter;
    private DecimalFormat timeTakenFormatter;
    private SimpleDateFormat yearFormatter;
    private SimpleDateFormat timeFormatter;
    private TimeZone timezone;
    private String timeZoneNoDST;
    private String timeZoneDST;
    private Date currentDate;
    private String space = " ";
    private boolean resolveHosts;
    private long rotationLastChecked;
    private String condition;
    private String fileDateFormat;
    private final TimeStamper timeStamper = new TimeStamper();

    public AccessLogger() {
        this.setPattern("common");
    }

    public void setTimeThreshold(long timeThreshold) {
        this.timeThreshold = timeThreshold;
    }

    public long getTimeThreshold() {
        return this.timeThreshold;
    }

    public String getTimedStatuses() {
        if (this.statusFilter.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        Iterator<Integer> i$ = this.statusFilter.iterator();
        while (i$.hasNext()) {
            int v = i$.next();
            builder.append(String.valueOf(v)).append(',');
        }
        builder.setLength(builder.length() - 1);
        return builder.toString();
    }

    public void setTimedStatuses(String value) {
        String[] values = value.split(",");
        this.statusFilter.clear();
        for (String v : values) {
            this.statusFilter.add(Integer.parseInt(v.trim()));
        }
    }

    public void setMaxDays(int maxDays) {
        this.maxDays = maxDays;
    }

    public int getMaxDays() {
        return this.maxDays;
    }

    public String getDirectory() {
        return this.directory;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }

    public String getInfo() {
        return "org.apache.catalina.valves.AccessLogValve/1.0";
    }

    public String getPattern() {
        return this.pattern;
    }

    public void setPattern(String pattern) {
        if (pattern == null) {
            pattern = "";
        }
        if (pattern.equals("common")) {
            pattern = "%h %l %u %t \"%r\" %s %b";
        }
        if (pattern.equals("combined")) {
            pattern = "%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"";
        }
        this.pattern = pattern;
        this.common = this.pattern.equals("%h %l %u %t \"%r\" %s %b");
        this.combined = this.pattern.equals("%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-Agent}i\"");
    }

    public String getPrefix() {
        return this.prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public boolean isRotatable() {
        return this.rotatable;
    }

    public void setRotatable(boolean rotatable) {
        this.rotatable = rotatable;
    }

    public String getSuffix() {
        return this.suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public void setResolveHosts(boolean resolveHosts) {
        this.resolveHosts = resolveHosts;
    }

    public boolean isResolveHosts() {
        return this.resolveHosts;
    }

    public String getCondition() {
        return this.condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public String getFileDateFormat() {
        return this.fileDateFormat;
    }

    public void setFileDateFormat(String fileDateFormat) {
        this.fileDateFormat = fileDateFormat;
    }

    public boolean isEnabled() {
        return this.enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void invoke(Prox2<HttpServletRequest, HttpServletResponse, Exception> forward, HttpServletRequest request, HttpServletResponse resp) throws Exception {
        HttpResponseWrapper response = new HttpResponseWrapper(resp);
        long startTime = System.currentTimeMillis();
        int currentOverlap = this.overlap.incrementAndGet();
        try {
            forward.call((Object)request, (Object)response);
        }
        finally {
            this.overlap.decrementAndGet();
        }
        long endTime = System.currentTimeMillis();
        if (!this.enabled) {
            return;
        }
        if (this.condition != null && request.getAttribute(this.condition) != null) {
            return;
        }
        long elapsedTime = endTime - startTime;
        if (elapsedTime < this.timeThreshold && !this.statusFilter.isEmpty() && this.statusFilter.contains(response.getStatus())) {
            return;
        }
        Date date = this.getDate();
        String result = this.common || this.combined ? this.resolveStandard(request, date, response) : this.resolveCustom(request, response, date, elapsedTime, currentOverlap);
        this.log(result);
    }

    private String resolveCustom(HttpServletRequest request, HttpResponseWrapper response, Date date, long time, int overlap) throws IOException {
        StringBuilder result = new StringBuilder();
        boolean replace = false;
        for (int i = 0; i < this.pattern.length(); ++i) {
            char ch = this.pattern.charAt(i);
            if (replace) {
                if ('{' == ch) {
                    int j;
                    StringBuilder name = new StringBuilder();
                    for (j = i + 1; j < this.pattern.length() && '}' != this.pattern.charAt(j); ++j) {
                        name.append(this.pattern.charAt(j));
                    }
                    if (j + 1 < this.pattern.length()) {
                        String str = AccessLogger.getValue(this.pattern.charAt(++j), request, response, name.toString());
                        str = AccessLogger.encodeWhiteSpace(str);
                        result.append(str);
                        i = j;
                    } else {
                        result.append(this.replace(ch, date, request, response, time, overlap));
                    }
                } else {
                    result.append(this.replace(ch, date, request, response, time, overlap));
                }
                replace = false;
                continue;
            }
            if (ch == '%') {
                replace = true;
                continue;
            }
            result.append(ch);
        }
        return result.toString();
    }

    private String resolveStandard(HttpServletRequest request, Date date, HttpResponseWrapper response) throws IOException {
        StringBuilder result = new StringBuilder();
        if (this.isResolveHosts()) {
            result.append(request.getRemoteHost());
        } else {
            result.append(request.getRemoteAddr());
        }
        result.append(" - ");
        String value = request.getRemoteUser();
        if (value == null) {
            result.append("- ");
        } else {
            result.append(value);
            result.append(this.space);
        }
        result.append("[");
        result.append(this.dayFormatter.format(date));
        result.append('/');
        result.append(AccessLogger.lookup(this.monthFormatter.format(date)));
        result.append('/');
        result.append(this.yearFormatter.format(date));
        result.append(':');
        result.append(this.timeFormatter.format(date));
        result.append(this.space);
        result.append(this.getTimeZone(date));
        result.append("] \"");
        result.append(request.getMethod());
        result.append(this.space);
        result.append(request.getRequestURI());
        if (request.getQueryString() != null) {
            result.append('?');
            result.append(request.getQueryString());
        }
        result.append(this.space);
        result.append(this.getProtocol(request));
        result.append("\" ");
        result.append(response.getStatus());
        result.append(this.space);
        long length = response.getContentWritten();
        value = length <= 0 ? "-" : "" + length;
        result.append(value);
        if (this.combined) {
            result.append(this.space);
            result.append("\"");
            String referer = AccessLogger.getRequestHeader(request, "referer");
            if (referer != null) {
                result.append(referer);
            } else {
                result.append("-");
            }
            result.append("\"");
            result.append(this.space);
            result.append("\"");
            String ua = AccessLogger.getRequestHeader(request, "user-agent");
            if (ua != null) {
                result.append(ua);
            } else {
                result.append("-");
            }
            result.append("\"");
        }
        return result.toString();
    }

    private synchronized void close() {
        if (this.writer == null) {
            return;
        }
        this.writer.flush();
        this.writer.close();
        this.writer = null;
        this.dateStamp = "";
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void log(String message) {
        long sysTime;
        if (this.rotatable && (sysTime = System.currentTimeMillis()) - this.rotationLastChecked > 1000) {
            this.currentDate = new Date(sysTime);
            this.rotationLastChecked = sysTime;
            String tsDate = this.dateFormatter.format(this.currentDate);
            if (!this.dateStamp.equals(tsDate)) {
                AccessLogger accessLogger = this;
                synchronized (accessLogger) {
                    if (!this.dateStamp.equals(tsDate)) {
                        this.close();
                        this.dateStamp = tsDate;
                        this.open();
                    }
                }
            }
        }
        if (this.writer != null) {
            this.writer.println(message);
        }
    }

    private static String lookup(String month) {
        int index;
        try {
            index = Integer.parseInt(month) - 1;
        }
        catch (Throwable t) {
            index = 0;
        }
        return months[index];
    }

    private synchronized void open() {
        File dir = this.getLogRoot();
        try {
            String prefix = dir.getAbsolutePath() + File.separator + this.prefix;
            String pathName = this.rotatable ? prefix + this.dateStamp + this.suffix : prefix + this.suffix;
            this.writer = new PrintWriter(new FileWriter(pathName, true), true);
        }
        catch (IOException e) {
            this.writer = null;
        }
    }

    private String replace(char pattern, Date date, HttpServletRequest request, HttpResponseWrapper response, long time, int overlap) throws IOException {
        String value = null;
        if (pattern == 'a') {
            value = request.getRemoteAddr();
        } else if (pattern == 'A') {
            try {
                value = InetAddress.getLocalHost().getHostAddress();
            }
            catch (Throwable e) {
                value = "127.0.0.1";
            }
        } else if (pattern == 'b') {
            long length = response.getContentWritten();
            value = length <= 0 ? "-" : "" + length;
        } else if (pattern == 'B') {
            int length = response.getContentLength();
            value = length >= 0 ? String.valueOf(length) : "-";
        } else if (pattern == 'h') {
            value = request.getRemoteHost();
        } else if (pattern == 'H') {
            value = this.getProtocol(request);
        } else if (pattern == 'l') {
            value = "-";
        } else if (pattern == 'm') {
            value = request != null ? request.getMethod() : "";
        } else if (pattern == 'p') {
            value = "" + request.getServerPort();
        } else if (pattern == 'D') {
            value = "" + time;
        } else if (pattern == 'q') {
            String query = null;
            if (request != null) {
                query = request.getQueryString();
            }
            value = query != null ? "?" + query : "";
        } else if (pattern == 'r') {
            StringBuilder sb = new StringBuilder();
            if (request != null) {
                sb.append(request.getMethod());
                sb.append(this.space);
                sb.append(request.getRequestURI());
                if (request.getQueryString() != null) {
                    sb.append('?');
                    sb.append(request.getQueryString());
                }
                sb.append(this.space);
                sb.append(this.getProtocol(request));
            } else {
                sb.append("- - ");
                sb.append(this.getProtocol(request));
            }
            value = sb.toString();
        } else if (pattern == 'R') {
            StringBuilder sb = new StringBuilder();
            if (request != null) {
                sb.append(request.getMethod());
                sb.append(this.space);
                sb.append(request.getRequestURI());
                if (request.getQueryString() != null) {
                    sb.append('?');
                    sb.append(request.getQueryString());
                } else if (request.getAttribute("Query") != null) {
                    sb.append('?');
                    sb.append(AccessLogger.encodeWhiteSpace((String)request.getAttribute("Query")));
                }
                sb.append(this.space);
                sb.append(this.getProtocol(request));
            } else {
                sb.append("- - ");
                sb.append(this.getProtocol(request));
            }
            value = sb.toString();
        } else if (pattern == 'S') {
            value = request != null ? (request.getSession(false) != null ? request.getSession(false).getId() : "-") : "-";
        } else if (pattern == 's') {
            value = response != null ? "" + response.getStatus() : "-";
        } else if (pattern == 'G') {
            value = this.timeStamper.getTimeStamp(System.currentTimeMillis());
        } else if (pattern == 'I') {
            value = Long.toHexString(Thread.currentThread().getId());
        } else if (pattern == 't') {
            StringBuilder temp = new StringBuilder("[");
            temp.append(this.dayFormatter.format(date));
            temp.append('/');
            temp.append(AccessLogger.lookup(this.monthFormatter.format(date)));
            temp.append('/');
            temp.append(this.yearFormatter.format(date));
            temp.append(':');
            temp.append(this.timeFormatter.format(date));
            temp.append(' ');
            temp.append(this.getTimeZone(date));
            temp.append(']');
            value = temp.toString();
        } else if (pattern == 'T') {
            value = this.timeTakenFormatter.format((double)time / 1000.0);
        } else if (pattern == 'u') {
            if (request != null) {
                value = request.getRemoteUser();
            }
            if (value == null) {
                value = "-";
            }
        } else {
            value = pattern == 'U' ? (request != null ? request.getRequestURI() : "-") : (pattern == 'v' ? request.getServerName() : (pattern == 'O' ? String.valueOf(overlap) : "???" + pattern + "???"));
        }
        if (value == null) {
            return "";
        }
        return value;
    }

    private String getProtocol(HttpServletRequest request) {
        String result = request.getProtocol();
        if (result == null || result.length() == 0) {
            return "-";
        }
        return result;
    }

    private static String convertToString(Object value) {
        try {
            if (value == null) {
                return "-";
            }
            if (value instanceof String) {
                return (String)value;
            }
            return value.toString();
        }
        catch (Throwable e) {
            return "-";
        }
    }

    private static String encodeWhiteSpace(String s) {
        StringBuilder buffer = new StringBuilder(s.length());
        block7 : for (int i = 0; i < s.length(); ++i) {
            char c = s.charAt(i);
            switch (c) {
                case '\n': {
                    buffer.append("%10");
                    continue block7;
                }
                case '\r': {
                    buffer.append("%13");
                    continue block7;
                }
                case '\t': {
                    buffer.append("%09");
                    continue block7;
                }
                case ' ': {
                    buffer.append("%20");
                    continue block7;
                }
                case '%': {
                    buffer.append("%25");
                    continue block7;
                }
                default: {
                    buffer.append(c);
                }
            }
        }
        return buffer.toString();
    }

    private static String getValue(char type, HttpServletRequest request, HttpResponseWrapper response, String header) throws IOException {
        if (request == null) {
            return "??";
        }
        switch (type) {
            case 'i': {
                return AccessLogger.getRequestHeader(request, header);
            }
            case 'c': {
                return AccessLogger.getCookie(request, header);
            }
            case 'r': {
                return AccessLogger.getRequestAttribute(request, response, header);
            }
            case 's': {
                return AccessLogger.getSessionAttribute(request, header);
            }
        }
        return "???";
    }

    private static String getRequestAttribute(HttpServletRequest request, HttpResponseWrapper response, String header) throws IOException {
        Object value = request.getAttribute(header);
        if (value == null && "Size".equals(header)) {
            value = response.getContentWritten();
        }
        return AccessLogger.convertToString(value);
    }

    private static String getRequestHeader(HttpServletRequest request, String header) {
        String value = request.getHeader(header);
        return AccessLogger.convertToString(value);
    }

    private static String getSessionAttribute(HttpServletRequest request, String header) {
        HttpSession sess = request.getSession(false);
        if (sess == null) {
            return "-";
        }
        Object attr = sess.getAttribute(header);
        return AccessLogger.convertToString(attr);
    }

    private static String getCookie(HttpServletRequest request, String header) {
        Cookie[] c = request.getCookies();
        for (int i = 0; c != null && i < c.length; ++i) {
            String name = c[i].getName();
            if (!header.equals(name)) continue;
            return c[i].getValue();
        }
        return "-";
    }

    private Date getDate() {
        if (this.currentDate == null) {
            this.currentDate = new Date();
        } else {
            long sysTime = System.currentTimeMillis();
            if (sysTime - this.currentDate.getTime() > 1000) {
                this.currentDate = new Date(sysTime);
            }
        }
        return this.currentDate;
    }

    private String getTimeZone(Date date) {
        if (this.timezone.inDaylightTime(date)) {
            return this.timeZoneDST;
        }
        return this.timeZoneNoDST;
    }

    private static String calculateTimeZoneOffset(long offset) {
        StringBuilder tz = new StringBuilder();
        if (offset < 0) {
            tz.append("-");
            offset = - offset;
        } else {
            tz.append("+");
        }
        long hourOffset = offset / 3600000;
        long minuteOffset = offset / 60000 % 60;
        if (hourOffset < 10) {
            tz.append("0");
        }
        tz.append(hourOffset);
        if (minuteOffset < 10) {
            tz.append("0");
        }
        tz.append(minuteOffset);
        return tz.toString();
    }

    private File getLogRoot() {
        File dir = new File(this.directory);
        if (!dir.isAbsolute()) {
            String catalinaHome = System.getProperty("catalina.home");
            dir = new File(System.getProperty("com.scene7.isHome", catalinaHome), this.directory);
        }
        dir.mkdirs();
        return dir;
    }

    public void start() {
        this.started = true;
        this.timezone = TimeZone.getDefault();
        this.timeZoneNoDST = AccessLogger.calculateTimeZoneOffset(this.timezone.getRawOffset());
        Calendar calendar = Calendar.getInstance(this.timezone);
        int offset = calendar.get(16);
        this.timeZoneDST = AccessLogger.calculateTimeZoneOffset(this.timezone.getRawOffset() + offset);
        if (this.fileDateFormat == null || this.fileDateFormat.length() == 0) {
            this.fileDateFormat = "yyyy-MM-dd";
        }
        this.dateFormatter = new SimpleDateFormat(this.fileDateFormat);
        this.dateFormatter.setTimeZone(this.timezone);
        this.dayFormatter = new SimpleDateFormat("dd");
        this.dayFormatter.setTimeZone(this.timezone);
        this.monthFormatter = new SimpleDateFormat("MM");
        this.monthFormatter.setTimeZone(this.timezone);
        this.yearFormatter = new SimpleDateFormat("yyyy");
        this.yearFormatter.setTimeZone(this.timezone);
        this.timeFormatter = new SimpleDateFormat("HH:mm:ss");
        this.timeFormatter.setTimeZone(this.timezone);
        this.currentDate = new Date();
        this.dateStamp = this.dateFormatter.format(this.currentDate);
        this.timeTakenFormatter = new DecimalFormat("0.000");
        this.open();
    }

    public void stop() {
        this.started = false;
        this.close();
    }
}