ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / resources / net_internals / log_view_painter.js
blob05d85eb040f64332a008acaddb889e6c1894daf7
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 createLogEntryTablePrinter;
8 var proxySettingsToString;
9 var stripCookiesAndLoginInfo;
11 // Start of anonymous namespace.
12 (function() {
13 'use strict';
15 function canCollapseBeginWithEnd(beginEntry) {
16 return beginEntry &&
17 beginEntry.isBegin() &&
18 beginEntry.end &&
19 beginEntry.end.index == beginEntry.index + 1 &&
20 (!beginEntry.orig.params || !beginEntry.end.orig.params);
23 /**
24 * Creates a TablePrinter for use by the above two functions. baseTime is
25 * the time relative to which other times are displayed.
27 createLogEntryTablePrinter = function(logEntries, privacyStripping,
28 baseTime, logCreationTime) {
29 var entries = LogGroupEntry.createArrayFrom(logEntries);
30 var tablePrinter = new TablePrinter();
31 var parameterOutputter = new ParameterOutputter(tablePrinter);
33 if (entries.length == 0)
34 return tablePrinter;
36 var startTime = timeutil.convertTimeTicksToTime(entries[0].orig.time);
38 for (var i = 0; i < entries.length; ++i) {
39 var entry = entries[i];
41 // Avoid printing the END for a BEGIN that was immediately before, unless
42 // both have extra parameters.
43 if (!entry.isEnd() || !canCollapseBeginWithEnd(entry.begin)) {
44 var entryTime = timeutil.convertTimeTicksToTime(entry.orig.time);
45 addRowWithTime(tablePrinter, entryTime - baseTime, startTime - baseTime);
47 for (var j = entry.getDepth(); j > 0; --j)
48 tablePrinter.addCell(' ');
50 var eventText = getTextForEvent(entry);
51 // Get the elapsed time, and append it to the event text.
52 if (entry.isBegin()) {
53 var dt = '?';
54 // Definite time.
55 if (entry.end) {
56 dt = entry.end.orig.time - entry.orig.time;
57 } else if (logCreationTime != undefined) {
58 dt = (logCreationTime - entryTime) + '+';
60 eventText += ' [dt=' + dt + ']';
63 var mainCell = tablePrinter.addCell(eventText);
64 mainCell.allowOverflow = true;
67 // Output the extra parameters.
68 if (typeof entry.orig.params == 'object') {
69 // Those 5 skipped cells are: two for "t=", and three for "st=".
70 tablePrinter.setNewRowCellIndent(5 + entry.getDepth());
71 writeParameters(entry.orig, privacyStripping, parameterOutputter);
73 tablePrinter.setNewRowCellIndent(0);
77 // If viewing a saved log file, add row with just the time the log was
78 // created, if the event never completed.
79 var lastEntry = entries[entries.length - 1];
80 // If the last entry has a non-zero depth or is a begin event, the source is
81 // still active.
82 var isSourceActive = lastEntry.getDepth() != 0 || lastEntry.isBegin();
83 if (logCreationTime != undefined && isSourceActive) {
84 addRowWithTime(tablePrinter,
85 logCreationTime - baseTime,
86 startTime - baseTime);
89 return tablePrinter;
92 /**
93 * Adds a new row to the given TablePrinter, and adds five cells containing
94 * information about the time an event occured.
95 * Format is '[t=<time of the event in ms>] [st=<ms since the source started>]'.
96 * @param {TablePrinter} tablePrinter The table printer to add the cells to.
97 * @param {number} eventTime The time the event occured, in milliseconds,
98 * relative to some base time.
99 * @param {number} startTime The time the first event for the source occured,
100 * relative to the same base time as eventTime.
102 function addRowWithTime(tablePrinter, eventTime, startTime) {
103 tablePrinter.addRow();
104 tablePrinter.addCell('t=');
105 var tCell = tablePrinter.addCell(eventTime);
106 tCell.alignRight = true;
107 tablePrinter.addCell(' [st=');
108 var stCell = tablePrinter.addCell(eventTime - startTime);
109 stCell.alignRight = true;
110 tablePrinter.addCell('] ');
114 * |hexString| must be a string of hexadecimal characters with no whitespace,
115 * whose length is a multiple of two. Writes multiple lines to |out| with
116 * the hexadecimal characters from |hexString| on the left, in groups of
117 * two, and their corresponding ASCII characters on the right.
119 * |asciiCharsPerLine| specifies how many ASCII characters will be put on each
120 * line of the output string.
122 function writeHexString(hexString, asciiCharsPerLine, out) {
123 // Number of transferred bytes in a line of output. Length of a
124 // line is roughly 4 times larger.
125 var hexCharsPerLine = 2 * asciiCharsPerLine;
126 for (var i = 0; i < hexString.length; i += hexCharsPerLine) {
127 var hexLine = '';
128 var asciiLine = '';
129 for (var j = i; j < i + hexCharsPerLine && j < hexString.length; j += 2) {
130 var hex = hexString.substr(j, 2);
131 hexLine += hex + ' ';
132 var charCode = parseInt(hex, 16);
133 // For ASCII codes 32 though 126, display the corresponding
134 // characters. Use a space for nulls, and a period for
135 // everything else.
136 if (charCode >= 0x20 && charCode <= 0x7E) {
137 asciiLine += String.fromCharCode(charCode);
138 } else if (charCode == 0x00) {
139 asciiLine += ' ';
140 } else {
141 asciiLine += '.';
145 // Make the ASCII text for the last line of output align with the previous
146 // lines.
147 hexLine += makeRepeatedString(' ', 3 * asciiCharsPerLine - hexLine.length);
148 out.writeLine(' ' + hexLine + ' ' + asciiLine);
153 * Wrapper around a TablePrinter to simplify outputting lines of text for event
154 * parameters.
156 var ParameterOutputter = (function() {
158 * @constructor
160 function ParameterOutputter(tablePrinter) {
161 this.tablePrinter_ = tablePrinter;
164 ParameterOutputter.prototype = {
166 * Outputs a single line.
168 writeLine: function(line) {
169 this.tablePrinter_.addRow();
170 var cell = this.tablePrinter_.addCell(line);
171 cell.allowOverflow = true;
172 return cell;
176 * Outputs a key=value line which looks like:
178 * --> key = value
180 writeArrowKeyValue: function(key, value, link) {
181 var cell = this.writeLine(kArrow + key + ' = ' + value);
182 cell.link = link;
186 * Outputs a key= line which looks like:
188 * --> key =
190 writeArrowKey: function(key) {
191 this.writeLine(kArrow + key + ' =');
195 * Outputs multiple lines, each indented by numSpaces.
196 * For instance if numSpaces=8 it might look like this:
198 * line 1
199 * line 2
200 * line 3
202 writeSpaceIndentedLines: function(numSpaces, lines) {
203 var prefix = makeRepeatedString(' ', numSpaces);
204 for (var i = 0; i < lines.length; ++i)
205 this.writeLine(prefix + lines[i]);
209 * Outputs multiple lines such that the first line has
210 * an arrow pointing at it, and subsequent lines
211 * align with the first one. For example:
213 * --> line 1
214 * line 2
215 * line 3
217 writeArrowIndentedLines: function(lines) {
218 if (lines.length == 0)
219 return;
221 this.writeLine(kArrow + lines[0]);
223 for (var i = 1; i < lines.length; ++i)
224 this.writeLine(kArrowIndentation + lines[i]);
228 var kArrow = ' --> ';
229 var kArrowIndentation = ' ';
231 return ParameterOutputter;
232 })(); // end of ParameterOutputter
235 * Formats the parameters for |entry| and writes them to |out|.
236 * Certain event types have custom pretty printers. Everything else will
237 * default to a JSON-like format.
239 function writeParameters(entry, privacyStripping, out) {
240 if (privacyStripping) {
241 // If privacy stripping is enabled, remove data as needed.
242 entry = stripCookiesAndLoginInfo(entry);
243 } else {
244 // If headers are in an object, convert them to an array for better display.
245 entry = reformatHeaders(entry);
248 // Use any parameter writer available for this event type.
249 var paramsWriter = getParamaterWriterForEventType(entry.type);
250 var consumedParams = {};
251 if (paramsWriter)
252 paramsWriter(entry, out, consumedParams);
254 // Write any un-consumed parameters.
255 for (var k in entry.params) {
256 if (consumedParams[k])
257 continue;
258 defaultWriteParameter(k, entry.params[k], out);
263 * Finds a writer to format the parameters for events of type |eventType|.
265 * @return {function} The returned function "writer" can be invoked
266 * as |writer(entry, writer, consumedParams)|. It will
267 * output the parameters of |entry| to |out|, and fill
268 * |consumedParams| with the keys of the parameters
269 * consumed. If no writer is available for |eventType| then
270 * returns null.
272 function getParamaterWriterForEventType(eventType) {
273 switch (eventType) {
274 case EventType.HTTP_TRANSACTION_SEND_REQUEST_HEADERS:
275 case EventType.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS:
276 case EventType.TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS:
277 return writeParamsForRequestHeaders;
279 case EventType.PROXY_CONFIG_CHANGED:
280 return writeParamsForProxyConfigChanged;
282 case EventType.CERT_VERIFIER_JOB:
283 case EventType.SSL_CERTIFICATES_RECEIVED:
284 return writeParamsForCertificates;
285 case EventType.EV_CERT_CT_COMPLIANCE_CHECKED:
286 return writeParamsForCheckedEVCertificates;
288 case EventType.SSL_VERSION_FALLBACK:
289 return writeParamsForSSLVersionFallback;
291 return null;
295 * Default parameter writer that outputs a visualization of field named |key|
296 * with value |value| to |out|.
298 function defaultWriteParameter(key, value, out) {
299 if (key == 'headers' && value instanceof Array) {
300 out.writeArrowIndentedLines(value);
301 return;
304 // For transferred bytes, display the bytes in hex and ASCII.
305 if (key == 'hex_encoded_bytes' && typeof value == 'string') {
306 out.writeArrowKey(key);
307 writeHexString(value, 20, out);
308 return;
311 // Handle source_dependency entries - add link and map source type to
312 // string.
313 if (key == 'source_dependency' && typeof value == 'object') {
314 var link = '#events&s=' + value.id;
315 var valueStr = value.id + ' (' + EventSourceTypeNames[value.type] + ')';
316 out.writeArrowKeyValue(key, valueStr, link);
317 return;
320 if (key == 'net_error' && typeof value == 'number') {
321 var valueStr = value + ' (' + netErrorToString(value) + ')';
322 out.writeArrowKeyValue(key, valueStr);
323 return;
326 if (key == 'quic_error' && typeof value == 'number') {
327 var valueStr = value + ' (' + quicErrorToString(value) + ')';
328 out.writeArrowKeyValue(key, valueStr);
329 return;
332 if (key == 'quic_crypto_handshake_message' && typeof value == 'string') {
333 var lines = value.split('\n');
334 out.writeArrowIndentedLines(lines);
335 return;
338 if (key == 'quic_rst_stream_error' && typeof value == 'number') {
339 var valueStr = value + ' (' + quicRstStreamErrorToString(value) + ')';
340 out.writeArrowKeyValue(key, valueStr);
341 return;
344 if (key == 'load_flags' && typeof value == 'number') {
345 var valueStr = value + ' (' + getLoadFlagSymbolicString(value) + ')';
346 out.writeArrowKeyValue(key, valueStr);
347 return;
350 if (key == 'load_state' && typeof value == 'number') {
351 var valueStr = value + ' (' + getKeyWithValue(LoadState, value) + ')';
352 out.writeArrowKeyValue(key, valueStr);
353 return;
356 if (key == 'sdch_problem_code' && typeof value == 'number') {
357 var valueStr = value + ' (' + sdchProblemCodeToString(value) + ')';
358 out.writeArrowKeyValue(key, valueStr);
359 return;
362 // Otherwise just default to JSON formatting of the value.
363 out.writeArrowKeyValue(key, JSON.stringify(value));
367 * Returns the set of LoadFlags that make up the integer |loadFlag|.
368 * For example: getLoadFlagSymbolicString(
370 function getLoadFlagSymbolicString(loadFlag) {
372 return getSymbolicString(loadFlag, LoadFlag,
373 getKeyWithValue(LoadFlag, loadFlag));
377 * Returns the set of CertStatusFlags that make up the integer |certStatusFlag|
379 function getCertStatusFlagSymbolicString(certStatusFlag) {
380 return getSymbolicString(certStatusFlag, CertStatusFlag, '');
384 * Returns a string representing the flags composing the given bitmask.
386 function getSymbolicString(bitmask, valueToName, zeroName) {
387 var matchingFlagNames = [];
389 for (var k in valueToName) {
390 if (bitmask & valueToName[k])
391 matchingFlagNames.push(k);
394 // If no flags were matched, returns a special value.
395 if (matchingFlagNames.length == 0)
396 return zeroName;
398 return matchingFlagNames.join(' | ');
402 * Converts an SSL version number to a textual representation.
403 * For instance, SSLVersionNumberToName(0x0301) returns 'TLS 1.0'.
405 function SSLVersionNumberToName(version) {
406 if ((version & 0xFFFF) != version) {
407 // If the version number is more than 2 bytes long something is wrong.
408 // Print it as hex.
409 return 'SSL 0x' + version.toString(16);
412 // See if it is a known TLS name.
413 var kTLSNames = {
414 0x0301: 'TLS 1.0',
415 0x0302: 'TLS 1.1',
416 0x0303: 'TLS 1.2'
418 var name = kTLSNames[version];
419 if (name)
420 return name;
422 // Otherwise label it as an SSL version.
423 var major = (version & 0xFF00) >> 8;
424 var minor = version & 0x00FF;
426 return 'SSL ' + major + '.' + minor;
430 * TODO(eroman): get rid of this, as it is only used by 1 callsite.
432 * Indent |lines| by |start|.
434 * For example, if |start| = ' -> ' and |lines| = ['line1', 'line2', 'line3']
435 * the output will be:
437 * " -> line1\n" +
438 * " line2\n" +
439 * " line3"
441 function indentLines(start, lines) {
442 return start + lines.join('\n' + makeRepeatedString(' ', start.length));
446 * If entry.param.headers exists and is an object other than an array, converts
447 * it into an array and returns a new entry. Otherwise, just returns the
448 * original entry.
450 function reformatHeaders(entry) {
451 // If there are no headers, or it is not an object other than an array,
452 // return |entry| without modification.
453 if (!entry.params || entry.params.headers === undefined ||
454 typeof entry.params.headers != 'object' ||
455 entry.params.headers instanceof Array) {
456 return entry;
459 // Duplicate the top level object, and |entry.params|, so the original object
460 // will not be modified.
461 entry = shallowCloneObject(entry);
462 entry.params = shallowCloneObject(entry.params);
464 // Convert headers to an array.
465 var headers = [];
466 for (var key in entry.params.headers)
467 headers.push(key + ': ' + entry.params.headers[key]);
468 entry.params.headers = headers;
470 return entry;
474 * Removes a cookie or unencrypted login information from a single HTTP header
475 * line, if present, and returns the modified line. Otherwise, just returns
476 * the original line.
478 function stripCookieOrLoginInfo(line) {
479 var patterns = [
480 // Cookie patterns
481 /^set-cookie: /i,
482 /^set-cookie2: /i,
483 /^cookie: /i,
485 // Unencrypted authentication patterns
486 /^authorization: \S*\s*/i,
487 /^proxy-authorization: \S*\s*/i];
489 // Prefix will hold the first part of the string that contains no private
490 // information. If null, no part of the string contains private information.
491 var prefix = null;
492 for (var i = 0; i < patterns.length; i++) {
493 var match = patterns[i].exec(line);
494 if (match != null) {
495 prefix = match[0];
496 break;
500 // Look for authentication information from data received from the server in
501 // multi-round Negotiate authentication.
502 if (prefix === null) {
503 var challengePatterns = [
504 /^www-authenticate: (\S*)\s*/i,
505 /^proxy-authenticate: (\S*)\s*/i];
506 for (var i = 0; i < challengePatterns.length; i++) {
507 var match = challengePatterns[i].exec(line);
508 if (!match)
509 continue;
511 // If there's no data after the scheme name, do nothing.
512 if (match[0].length == line.length)
513 break;
515 // Ignore lines with commas, as they may contain lists of schemes, and
516 // the information we want to hide is Base64 encoded, so has no commas.
517 if (line.indexOf(',') >= 0)
518 break;
520 // Ignore Basic and Digest authentication challenges, as they contain
521 // public information.
522 if (/^basic$/i.test(match[1]) || /^digest$/i.test(match[1]))
523 break;
525 prefix = match[0];
526 break;
530 if (prefix) {
531 var suffix = line.slice(prefix.length);
532 // If private information has already been removed, keep the line as-is.
533 // This is often the case when viewing a loaded log.
534 // TODO(mmenke): Remove '[value was stripped]' check once M24 hits stable.
535 if (suffix.search(/^\[[0-9]+ bytes were stripped\]$/) == -1 &&
536 suffix != '[value was stripped]') {
537 return prefix + '[' + suffix.length + ' bytes were stripped]';
541 return line;
545 * If |entry| has headers, returns a copy of |entry| with all cookie and
546 * unencrypted login text removed. Otherwise, returns original |entry| object.
547 * This is needed so that JSON log dumps can be made without affecting the
548 * source data. Converts headers stored in objects to arrays.
550 * Note: this logic should be kept in sync with
551 * net::ElideHeaderForNetLog in net/http/http_log_util.cc.
553 stripCookiesAndLoginInfo = function(entry) {
554 if (!entry.params || entry.params.headers === undefined ||
555 !(entry.params.headers instanceof Object)) {
556 return entry;
559 // Make sure entry's headers are in an array.
560 entry = reformatHeaders(entry);
562 // Duplicate the top level object, and |entry.params|. All other fields are
563 // just pointers to the original values, as they won't be modified, other than
564 // |entry.params.headers|.
565 entry = shallowCloneObject(entry);
566 entry.params = shallowCloneObject(entry.params);
568 entry.params.headers = entry.params.headers.map(stripCookieOrLoginInfo);
569 return entry;
573 * Outputs the request header parameters of |entry| to |out|.
575 function writeParamsForRequestHeaders(entry, out, consumedParams) {
576 var params = entry.params;
578 if (!(typeof params.line == 'string') || !(params.headers instanceof Array)) {
579 // Unrecognized params.
580 return;
583 // Strip the trailing CRLF that params.line contains.
584 var lineWithoutCRLF = params.line.replace(/\r\n$/g, '');
585 out.writeArrowIndentedLines([lineWithoutCRLF].concat(params.headers));
587 consumedParams.line = true;
588 consumedParams.headers = true;
591 function writeCertificateParam(
592 certs_container, out, consumedParams, paramName) {
593 if (certs_container.certificates instanceof Array) {
594 var certs = certs_container.certificates.reduce(
595 function(previous, current) {
596 return previous.concat(current.split('\n'));
597 }, new Array());
598 out.writeArrowKey(paramName);
599 out.writeSpaceIndentedLines(8, certs);
600 consumedParams[paramName] = true;
605 * Outputs the certificate parameters of |entry| to |out|.
607 function writeParamsForCertificates(entry, out, consumedParams) {
608 writeCertificateParam(entry.params, out, consumedParams, 'certificates');
610 if (typeof(entry.params.verified_cert) == 'object')
611 writeCertificateParam(
612 entry.params.verified_cert, out, consumedParams, 'verified_cert');
614 if (typeof(entry.params.cert_status) == 'number') {
615 var valueStr = entry.params.cert_status + ' (' +
616 getCertStatusFlagSymbolicString(entry.params.cert_status) + ')';
617 out.writeArrowKeyValue('cert_status', valueStr);
618 consumedParams.cert_status = true;
623 function writeParamsForCheckedEVCertificates(entry, out, consumedParams) {
624 if (typeof(entry.params.certificate) == 'object')
625 writeCertificateParam(
626 entry.params.certificate, out, consumedParams, 'certificate');
630 * Outputs the SSL version fallback parameters of |entry| to |out|.
632 function writeParamsForSSLVersionFallback(entry, out, consumedParams) {
633 var params = entry.params;
635 if (typeof params.version_before != 'number' ||
636 typeof params.version_after != 'number') {
637 // Unrecognized params.
638 return;
641 var line = SSLVersionNumberToName(params.version_before) +
642 ' ==> ' +
643 SSLVersionNumberToName(params.version_after);
644 out.writeArrowIndentedLines([line]);
646 consumedParams.version_before = true;
647 consumedParams.version_after = true;
650 function writeParamsForProxyConfigChanged(entry, out, consumedParams) {
651 var params = entry.params;
653 if (typeof params.new_config != 'object') {
654 // Unrecognized params.
655 return;
658 if (typeof params.old_config == 'object') {
659 var oldConfigString = proxySettingsToString(params.old_config);
660 // The previous configuration may not be present in the case of
661 // the initial proxy settings fetch.
662 out.writeArrowKey('old_config');
664 out.writeSpaceIndentedLines(8, oldConfigString.split('\n'));
666 consumedParams.old_config = true;
669 var newConfigString = proxySettingsToString(params.new_config);
670 out.writeArrowKey('new_config');
671 out.writeSpaceIndentedLines(8, newConfigString.split('\n'));
673 consumedParams.new_config = true;
676 function getTextForEvent(entry) {
677 var text = '';
679 if (entry.isBegin() && canCollapseBeginWithEnd(entry)) {
680 // Don't prefix with '+' if we are going to collapse the END event.
681 text = ' ';
682 } else if (entry.isBegin()) {
683 text = '+' + text;
684 } else if (entry.isEnd()) {
685 text = '-' + text;
686 } else {
687 text = ' ';
690 text += EventTypeNames[entry.orig.type];
691 return text;
694 proxySettingsToString = function(config) {
695 if (!config)
696 return '';
698 // TODO(eroman): if |config| has unexpected properties, print it as JSON
699 // rather than hide them.
701 function getProxyListString(proxies) {
702 // Older versions of Chrome would set these values as strings, whereas newer
703 // logs use arrays.
704 // TODO(eroman): This behavior changed in M27. Support for older logs can
705 // safely be removed circa M29.
706 if (Array.isArray(proxies)) {
707 var listString = proxies.join(', ');
708 if (proxies.length > 1)
709 return '[' + listString + ']';
710 return listString;
712 return proxies;
715 // The proxy settings specify up to three major fallback choices
716 // (auto-detect, custom pac url, or manual settings).
717 // We enumerate these to a list so we can later number them.
718 var modes = [];
720 // Output any automatic settings.
721 if (config.auto_detect)
722 modes.push(['Auto-detect']);
723 if (config.pac_url)
724 modes.push(['PAC script: ' + config.pac_url]);
726 // Output any manual settings.
727 if (config.single_proxy || config.proxy_per_scheme) {
728 var lines = [];
730 if (config.single_proxy) {
731 lines.push('Proxy server: ' + getProxyListString(config.single_proxy));
732 } else if (config.proxy_per_scheme) {
733 for (var urlScheme in config.proxy_per_scheme) {
734 if (urlScheme != 'fallback') {
735 lines.push('Proxy server for ' + urlScheme.toUpperCase() + ': ' +
736 getProxyListString(config.proxy_per_scheme[urlScheme]));
739 if (config.proxy_per_scheme.fallback) {
740 lines.push('Proxy server for everything else: ' +
741 getProxyListString(config.proxy_per_scheme.fallback));
745 // Output any proxy bypass rules.
746 if (config.bypass_list) {
747 if (config.reverse_bypass) {
748 lines.push('Reversed bypass list: ');
749 } else {
750 lines.push('Bypass list: ');
753 for (var i = 0; i < config.bypass_list.length; ++i)
754 lines.push(' ' + config.bypass_list[i]);
757 modes.push(lines);
760 var result = [];
761 if (modes.length < 1) {
762 // If we didn't find any proxy settings modes, we are using DIRECT.
763 result.push('Use DIRECT connections.');
764 } else if (modes.length == 1) {
765 // If there was just one mode, don't bother numbering it.
766 result.push(modes[0].join('\n'));
767 } else {
768 // Otherwise concatenate all of the modes into a numbered list
769 // (which correspond with the fallback order).
770 for (var i = 0; i < modes.length; ++i)
771 result.push(indentLines('(' + (i + 1) + ') ', modes[i]));
774 if (config.source != undefined && config.source != 'UNKNOWN')
775 result.push('Source: ' + config.source);
777 return result.join('\n');
780 // End of anonymous namespace.
781 })();