1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // TODO(eroman): put these methods into a namespace.
7 var printLogEntriesAsText
;
8 var searchLogEntriesForText
;
9 var proxySettingsToString
;
10 var stripCookiesAndLoginInfo
;
12 // Start of anonymous namespace.
16 function canCollapseBeginWithEnd(beginEntry
) {
18 beginEntry
.isBegin() &&
20 beginEntry
.end
.index
== beginEntry
.index
+ 1 &&
21 (!beginEntry
.orig
.params
|| !beginEntry
.end
.orig
.params
);
25 * Adds a child pre element to the end of |parent|, and writes the
26 * formatted contents of |logEntries| to it.
28 printLogEntriesAsText = function(logEntries
, parent
, privacyStripping
,
30 var tablePrinter
= createTablePrinter(logEntries
, privacyStripping
,
33 // Format the table for fixed-width text.
34 tablePrinter
.toText(0, parent
);
38 * Searches the table that would be output by printLogEntriesAsText for
39 * |searchString|. Returns true if |searchString| would appear entirely within
40 * any field in the table. |searchString| must be lowercase.
42 * Seperate function from printLogEntriesAsText since TablePrinter.toText
45 searchLogEntriesForText = function(searchString
, logEntries
, privacyStripping
) {
47 createTablePrinter(logEntries
, privacyStripping
, undefined);
49 // Format the table for fixed-width text.
50 return tablePrinter
.search(searchString
);
54 * Creates a TablePrinter for use by the above two functions.
56 function createTablePrinter(logEntries
, privacyStripping
, logCreationTime
) {
57 var entries
= LogGroupEntry
.createArrayFrom(logEntries
);
58 var tablePrinter
= new TablePrinter();
59 var parameterOutputter
= new ParameterOutputter(tablePrinter
);
61 if (entries
.length
== 0)
64 var startTime
= timeutil
.convertTimeTicksToTime(entries
[0].orig
.time
);
66 for (var i
= 0; i
< entries
.length
; ++i
) {
67 var entry
= entries
[i
];
69 // Avoid printing the END for a BEGIN that was immediately before, unless
70 // both have extra parameters.
71 if (!entry
.isEnd() || !canCollapseBeginWithEnd(entry
.begin
)) {
72 var entryTime
= timeutil
.convertTimeTicksToTime(entry
.orig
.time
);
73 addRowWithTime(tablePrinter
, entryTime
, startTime
);
75 for (var j
= entry
.getDepth(); j
> 0; --j
)
76 tablePrinter
.addCell(' ');
78 var eventText
= getTextForEvent(entry
);
79 // Get the elapsed time, and append it to the event text.
80 if (entry
.isBegin()) {
84 dt
= entry
.end
.orig
.time
- entry
.orig
.time
;
85 } else if (logCreationTime
!= undefined) {
86 dt
= (logCreationTime
- entryTime
) + '+';
88 eventText
+= ' [dt=' + dt
+ ']';
91 var mainCell
= tablePrinter
.addCell(eventText
);
92 mainCell
.allowOverflow
= true;
95 // Output the extra parameters.
96 if (typeof entry
.orig
.params
== 'object') {
97 // Those 5 skipped cells are: two for "t=", and three for "st=".
98 tablePrinter
.setNewRowCellIndent(5 + entry
.getDepth());
99 writeParameters(entry
.orig
, privacyStripping
, parameterOutputter
);
101 tablePrinter
.setNewRowCellIndent(0);
105 // If viewing a saved log file, add row with just the time the log was
106 // created, if the event never completed.
107 if (logCreationTime
!= undefined &&
108 entries
[entries
.length
- 1].getDepth() > 0) {
109 addRowWithTime(tablePrinter
, logCreationTime
, startTime
);
116 * Adds a new row to the given TablePrinter, and adds five cells containing
117 * information about the time an event occured.
118 * Format is '[t=<UTC time in ms>] [st=<ms since the source started>]'.
119 * @param {TablePrinter} tablePrinter The table printer to add the cells to.
120 * @param {number} eventTime The time the event occured, as a UTC time in
122 * @param {number} startTime The time the first event for the source occured,
123 * as a UTC time in milliseconds.
125 function addRowWithTime(tablePrinter
, eventTime
, startTime
) {
126 tablePrinter
.addRow();
127 tablePrinter
.addCell('t=');
128 var tCell
= tablePrinter
.addCell(eventTime
);
129 tCell
.alignRight
= true;
130 tablePrinter
.addCell(' [st=');
131 var stCell
= tablePrinter
.addCell(eventTime
- startTime
);
132 stCell
.alignRight
= true;
133 tablePrinter
.addCell('] ');
137 * |hexString| must be a string of hexadecimal characters with no whitespace,
138 * whose length is a multiple of two. Writes multiple lines to |out| with
139 * the hexadecimal characters from |hexString| on the left, in groups of
140 * two, and their corresponding ASCII characters on the right.
142 * |asciiCharsPerLine| specifies how many ASCII characters will be put on each
143 * line of the output string.
145 function writeHexString(hexString
, asciiCharsPerLine
, out
) {
146 // Number of transferred bytes in a line of output. Length of a
147 // line is roughly 4 times larger.
148 var hexCharsPerLine
= 2 * asciiCharsPerLine
;
149 for (var i
= 0; i
< hexString
.length
; i
+= hexCharsPerLine
) {
152 for (var j
= i
; j
< i
+ hexCharsPerLine
&& j
< hexString
.length
; j
+= 2) {
153 var hex
= hexString
.substr(j
, 2);
154 hexLine
+= hex
+ ' ';
155 var charCode
= parseInt(hex
, 16);
156 // For ASCII codes 32 though 126, display the corresponding
157 // characters. Use a space for nulls, and a period for
159 if (charCode
>= 0x20 && charCode
<= 0x7E) {
160 asciiLine
+= String
.fromCharCode(charCode
);
161 } else if (charCode
== 0x00) {
168 // Make the ASCII text for the last line of output align with the previous
170 hexLine
+= makeRepeatedString(' ', 3 * asciiCharsPerLine
- hexLine
.length
);
171 out
.writeLine(' ' + hexLine
+ ' ' + asciiLine
);
176 * Wrapper around a TablePrinter to simplify outputting lines of text for event
179 var ParameterOutputter
= (function() {
183 function ParameterOutputter(tablePrinter
) {
184 this.tablePrinter_
= tablePrinter
;
187 ParameterOutputter
.prototype = {
189 * Outputs a single line.
191 writeLine: function(line
) {
192 this.tablePrinter_
.addRow();
193 var cell
= this.tablePrinter_
.addCell(line
);
194 cell
.allowOverflow
= true;
199 * Outputs a key=value line which looks like:
203 writeArrowKeyValue: function(key
, value
, link
) {
204 var cell
= this.writeLine(kArrow
+ key
+ ' = ' + value
);
209 * Outputs a key= line which looks like:
213 writeArrowKey: function(key
) {
214 this.writeLine(kArrow
+ key
+ ' =');
218 * Outputs multiple lines, each indented by numSpaces.
219 * For instance if numSpaces=8 it might look like this:
225 writeSpaceIndentedLines: function(numSpaces
, lines
) {
226 var prefix
= makeRepeatedString(' ', numSpaces
);
227 for (var i
= 0; i
< lines
.length
; ++i
)
228 this.writeLine(prefix
+ lines
[i
]);
232 * Outputs multiple lines such that the first line has
233 * an arrow pointing at it, and subsequent lines
234 * align with the first one. For example:
240 writeArrowIndentedLines: function(lines
) {
241 if (lines
.length
== 0)
244 this.writeLine(kArrow
+ lines
[0]);
246 for (var i
= 1; i
< lines
.length
; ++i
)
247 this.writeLine(kArrowIndentation
+ lines
[i
]);
251 var kArrow
= ' --> ';
252 var kArrowIndentation
= ' ';
254 return ParameterOutputter
;
255 })(); // end of ParameterOutputter
258 * Formats the parameters for |entry| and writes them to |out|.
259 * Certain event types have custom pretty printers. Everything else will
260 * default to a JSON-like format.
262 function writeParameters(entry
, privacyStripping
, out
) {
263 if (privacyStripping
) {
264 // If privacy stripping is enabled, remove data as needed.
265 entry
= stripCookiesAndLoginInfo(entry
);
267 // If headers are in an object, convert them to an array for better display.
268 entry
= reformatHeaders(entry
);
271 // Use any parameter writer available for this event type.
272 var paramsWriter
= getParamaterWriterForEventType(entry
.type
);
273 var consumedParams
= {};
275 paramsWriter(entry
, out
, consumedParams
);
277 // Write any un-consumed parameters.
278 for (var k
in entry
.params
) {
279 if (consumedParams
[k
])
281 defaultWriteParameter(k
, entry
.params
[k
], out
);
286 * Finds a writer to format the parameters for events of type |eventType|.
288 * @return {function} The returned function "writer" can be invoked
289 * as |writer(entry, writer, consumedParams)|. It will
290 * output the parameters of |entry| to |out|, and fill
291 * |consumedParams| with the keys of the parameters
292 * consumed. If no writer is available for |eventType| then
295 function getParamaterWriterForEventType(eventType
) {
297 case EventType
.HTTP_TRANSACTION_SEND_REQUEST_HEADERS
:
298 case EventType
.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS
:
299 return writeParamsForRequestHeaders
;
301 case EventType
.PROXY_CONFIG_CHANGED
:
302 return writeParamsForProxyConfigChanged
;
304 case EventType
.CERT_VERIFIER_JOB
:
305 case EventType
.SSL_CERTIFICATES_RECEIVED
:
306 return writeParamsForCertificates
;
308 case EventType
.SSL_VERSION_FALLBACK
:
309 return writeParamsForSSLVersionFallback
;
315 * Default parameter writer that outputs a visualization of field named |key|
316 * with value |value| to |out|.
318 function defaultWriteParameter(key
, value
, out
) {
319 if (key
== 'headers' && value
instanceof Array
) {
320 out
.writeArrowIndentedLines(value
);
324 // For transferred bytes, display the bytes in hex and ASCII.
325 if (key
== 'hex_encoded_bytes' && typeof value
== 'string') {
326 out
.writeArrowKey(key
);
327 writeHexString(value
, 20, out
);
331 // Handle source_dependency entries - add link and map source type to
333 if (key
== 'source_dependency' && typeof value
== 'object') {
334 var link
= '#events&s=' + value
.id
;
335 var valueStr
= value
.id
+ ' (' + EventSourceTypeNames
[value
.type
] + ')';
336 out
.writeArrowKeyValue(key
, valueStr
, link
);
340 if (key
== 'net_error' && typeof value
== 'number') {
341 var valueStr
= value
+ ' (' + netErrorToString(value
) + ')';
342 out
.writeArrowKeyValue(key
, valueStr
);
346 if (key
== 'load_flags' && typeof value
== 'number') {
347 var valueStr
= value
+ ' (' + getLoadFlagSymbolicString(value
) + ')';
348 out
.writeArrowKeyValue(key
, valueStr
);
352 if (key
== 'load_state' && typeof value
== 'number') {
353 var valueStr
= value
+ ' (' + getKeyWithValue(LoadState
, value
) + ')';
354 out
.writeArrowKeyValue(key
, valueStr
);
358 // Otherwise just default to JSON formatting of the value.
359 out
.writeArrowKeyValue(key
, JSON
.stringify(value
));
363 * Returns the set of LoadFlags that make up the integer |loadFlag|.
364 * For example: getLoadFlagSymbolicString(
366 function getLoadFlagSymbolicString(loadFlag
) {
367 // Load flag of 0 means "NORMAL". Special case this, since and-ing with
368 // 0 is always going to be false.
370 return getKeyWithValue(LoadFlag
, loadFlag
);
372 var matchingLoadFlagNames
= [];
374 for (var k
in LoadFlag
) {
375 if (loadFlag
& LoadFlag
[k
])
376 matchingLoadFlagNames
.push(k
);
379 return matchingLoadFlagNames
.join(' | ');
383 * Converts an SSL version number to a textual representation.
384 * For instance, SSLVersionNumberToName(0x0301) returns 'TLS 1.0'.
386 function SSLVersionNumberToName(version
) {
387 if ((version
& 0xFFFF) != version
) {
388 // If the version number is more than 2 bytes long something is wrong.
390 return 'SSL 0x' + version
.toString(16);
393 // See if it is a known TLS name.
399 var name
= kTLSNames
[version
];
403 // Otherwise label it as an SSL version.
404 var major
= (version
& 0xFF00) >> 8;
405 var minor
= version
& 0x00FF;
407 return 'SSL ' + major
+ '.' + minor
;
411 * TODO(eroman): get rid of this, as it is only used by 1 callsite.
413 * Indent |lines| by |start|.
415 * For example, if |start| = ' -> ' and |lines| = ['line1', 'line2', 'line3']
416 * the output will be:
422 function indentLines(start
, lines
) {
423 return start
+ lines
.join('\n' + makeRepeatedString(' ', start
.length
));
427 * If entry.param.headers exists and is an object other than an array, converts
428 * it into an array and returns a new entry. Otherwise, just returns the
431 function reformatHeaders(entry
) {
432 // If there are no headers, or it is not an object other than an array,
433 // return |entry| without modification.
434 if (!entry
.params
|| entry
.params
.headers
=== undefined ||
435 typeof entry
.params
.headers
!= 'object' ||
436 entry
.params
.headers
instanceof Array
) {
440 // Duplicate the top level object, and |entry.params|, so the original object
441 // will not be modified.
442 entry
= shallowCloneObject(entry
);
443 entry
.params
= shallowCloneObject(entry
.params
);
445 // Convert headers to an array.
447 for (var key
in entry
.params
.headers
)
448 headers
.push(key
+ ': ' + entry
.params
.headers
[key
]);
449 entry
.params
.headers
= headers
;
455 * Removes a cookie or unencrypted login information from a single HTTP header
456 * line, if present, and returns the modified line. Otherwise, just returns
459 function stripCookieOrLoginInfo(line
) {
466 // Unencrypted authentication patterns
467 /^authorization: \S*\s*/i,
468 /^proxy-authorization: \S*\s*/i];
470 // Prefix will hold the first part of the string that contains no private
471 // information. If null, no part of the string contains private information.
473 for (var i
= 0; i
< patterns
.length
; i
++) {
474 var match
= patterns
[i
].exec(line
);
481 // Look for authentication information from data received from the server in
482 // multi-round Negotiate authentication.
483 if (prefix
=== null) {
484 var challengePatterns
= [
485 /^www-authenticate: (\S*)\s*/i,
486 /^proxy-authenticate: (\S*)\s*/i];
487 for (var i
= 0; i
< challengePatterns
.length
; i
++) {
488 var match
= challengePatterns
[i
].exec(line
);
492 // If there's no data after the scheme name, do nothing.
493 if (match
[0].length
== line
.length
)
496 // Ignore lines with commas, as they may contain lists of schemes, and
497 // the information we want to hide is Base64 encoded, so has no commas.
498 if (line
.indexOf(',') >= 0)
501 // Ignore Basic and Digest authentication challenges, as they contain
502 // public information.
503 if (/^basic$/i.test(match
[1]) || /^digest$/i.test(match
[1]))
512 var suffix
= line
.slice(prefix
.length
);
513 // If private information has already been removed, keep the line as-is.
514 // This is often the case when viewing a loaded log.
515 // TODO(mmenke): Remove '[value was stripped]' check once M24 hits stable.
516 if (suffix
.search(/^\[[0-9]+ bytes were stripped\]$/) == -1 &&
517 suffix
!= '[value was stripped]') {
518 return prefix
+ '[' + suffix
.length
+ ' bytes were stripped]';
526 * If |entry| has headers, returns a copy of |entry| with all cookie and
527 * unencrypted login text removed. Otherwise, returns original |entry| object.
528 * This is needed so that JSON log dumps can be made without affecting the
529 * source data. Converts headers stored in objects to arrays.
531 stripCookiesAndLoginInfo = function(entry
) {
532 if (!entry
.params
|| entry
.params
.headers
=== undefined ||
533 !(entry
.params
.headers
instanceof Object
)) {
537 // Make sure entry's headers are in an array.
538 entry
= reformatHeaders(entry
);
540 // Duplicate the top level object, and |entry.params|. All other fields are
541 // just pointers to the original values, as they won't be modified, other than
542 // |entry.params.headers|.
543 entry
= shallowCloneObject(entry
);
544 entry
.params
= shallowCloneObject(entry
.params
);
546 entry
.params
.headers
= entry
.params
.headers
.map(stripCookieOrLoginInfo
);
551 * Outputs the request header parameters of |entry| to |out|.
553 function writeParamsForRequestHeaders(entry
, out
, consumedParams
) {
554 var params
= entry
.params
;
556 if (!(typeof params
.line
== 'string') || !(params
.headers
instanceof Array
)) {
557 // Unrecognized params.
561 // Strip the trailing CRLF that params.line contains.
562 var lineWithoutCRLF
= params
.line
.replace(/\r\n$/g, '');
563 out
.writeArrowIndentedLines([lineWithoutCRLF
].concat(params
.headers
));
565 consumedParams
.line
= true;
566 consumedParams
.headers
= true;
570 * Outputs the certificate parameters of |entry| to |out|.
572 function writeParamsForCertificates(entry
, out
, consumedParams
) {
573 if (!(entry
.params
.certificates
instanceof Array
)) {
574 // Unrecognized params.
578 var certs
= entry
.params
.certificates
.reduce(function(previous
, current
) {
579 return previous
.concat(current
.split('\n'));
582 out
.writeArrowKey('certificates');
583 out
.writeSpaceIndentedLines(8, certs
);
585 consumedParams
.certificates
= true;
589 * Outputs the SSL version fallback parameters of |entry| to |out|.
591 function writeParamsForSSLVersionFallback(entry
, out
, consumedParams
) {
592 var params
= entry
.params
;
594 if (typeof params
.version_before
!= 'number' ||
595 typeof params
.version_after
!= 'number') {
596 // Unrecognized params.
600 var line
= SSLVersionNumberToName(params
.version_before
) +
602 SSLVersionNumberToName(params
.version_after
);
603 out
.writeArrowIndentedLines([line
]);
605 consumedParams
.version_before
= true;
606 consumedParams
.version_after
= true;
609 function writeParamsForProxyConfigChanged(entry
, out
, consumedParams
) {
610 var params
= entry
.params
;
612 if (typeof params
.new_config
!= 'object') {
613 // Unrecognized params.
617 if (typeof params
.old_config
== 'object') {
618 var oldConfigString
= proxySettingsToString(params
.old_config
);
619 // The previous configuration may not be present in the case of
620 // the initial proxy settings fetch.
621 out
.writeArrowKey('old_config');
623 out
.writeSpaceIndentedLines(8, oldConfigString
.split('\n'));
625 consumedParams
.old_config
= true;
628 var newConfigString
= proxySettingsToString(params
.new_config
);
629 out
.writeArrowKey('new_config');
630 out
.writeSpaceIndentedLines(8, newConfigString
.split('\n'));
632 consumedParams
.new_config
= true;
635 function getTextForEvent(entry
) {
638 if (entry
.isBegin() && canCollapseBeginWithEnd(entry
)) {
639 // Don't prefix with '+' if we are going to collapse the END event.
641 } else if (entry
.isBegin()) {
643 } else if (entry
.isEnd()) {
649 text
+= EventTypeNames
[entry
.orig
.type
];
653 proxySettingsToString = function(config
) {
657 // The proxy settings specify up to three major fallback choices
658 // (auto-detect, custom pac url, or manual settings).
659 // We enumerate these to a list so we can later number them.
662 // Output any automatic settings.
663 if (config
.auto_detect
)
664 modes
.push(['Auto-detect']);
666 modes
.push(['PAC script: ' + config
.pac_url
]);
668 // Output any manual settings.
669 if (config
.single_proxy
|| config
.proxy_per_scheme
) {
672 if (config
.single_proxy
) {
673 lines
.push('Proxy server: ' + config
.single_proxy
);
674 } else if (config
.proxy_per_scheme
) {
675 for (var urlScheme
in config
.proxy_per_scheme
) {
676 if (urlScheme
!= 'fallback') {
677 lines
.push('Proxy server for ' + urlScheme
.toUpperCase() + ': ' +
678 config
.proxy_per_scheme
[urlScheme
]);
681 if (config
.proxy_per_scheme
.fallback
) {
682 lines
.push('Proxy server for everything else: ' +
683 config
.proxy_per_scheme
.fallback
);
687 // Output any proxy bypass rules.
688 if (config
.bypass_list
) {
689 if (config
.reverse_bypass
) {
690 lines
.push('Reversed bypass list: ');
692 lines
.push('Bypass list: ');
695 for (var i
= 0; i
< config
.bypass_list
.length
; ++i
)
696 lines
.push(' ' + config
.bypass_list
[i
]);
703 if (modes
.length
< 1) {
704 // If we didn't find any proxy settings modes, we are using DIRECT.
705 result
.push('Use DIRECT connections.');
706 } else if (modes
.length
== 1) {
707 // If there was just one mode, don't bother numbering it.
708 result
.push(modes
[0].join('\n'));
710 // Otherwise concatenate all of the modes into a numbered list
711 // (which correspond with the fallback order).
712 for (var i
= 0; i
< modes
.length
; ++i
)
713 result
.push(indentLines('(' + (i
+ 1) + ') ', modes
[i
]));
716 if (config
.source
!= undefined && config
.source
!= 'UNKNOWN')
717 result
.push('Source: ' + config
.source
);
719 return result
.join('\n');
722 // End of anonymous namespace.