summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/net_internals/log_view_painter.js
blob: 5969699e9adf79077644e132463159f70b820587 (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// TODO(eroman): put these methods into a namespace.

var createLogEntryTablePrinter;
var proxySettingsToString;
var stripPrivacyInfo;

// Start of anonymous namespace.
(function() {
'use strict';

function canCollapseBeginWithEnd(beginEntry) {
  return beginEntry &&
         beginEntry.isBegin() &&
         beginEntry.end &&
         beginEntry.end.index == beginEntry.index + 1 &&
         (!beginEntry.orig.params || !beginEntry.end.orig.params);
}

/**
 * Creates a TablePrinter for use by the above two functions.  baseTime is
 * the time relative to which other times are displayed.
 */
createLogEntryTablePrinter = function(logEntries, privacyStripping,
                                      baseTime, logCreationTime) {
  var entries = LogGroupEntry.createArrayFrom(logEntries);
  var tablePrinter = new TablePrinter();
  var parameterOutputter = new ParameterOutputter(tablePrinter);

  if (entries.length == 0)
    return tablePrinter;

  var startTime = timeutil.convertTimeTicksToTime(entries[0].orig.time);

  for (var i = 0; i < entries.length; ++i) {
    var entry = entries[i];

    // Avoid printing the END for a BEGIN that was immediately before, unless
    // both have extra parameters.
    if (!entry.isEnd() || !canCollapseBeginWithEnd(entry.begin)) {
      var entryTime = timeutil.convertTimeTicksToTime(entry.orig.time);
      addRowWithTime(tablePrinter, entryTime - baseTime, startTime - baseTime);

      for (var j = entry.getDepth(); j > 0; --j)
        tablePrinter.addCell('  ');

      var eventText = getTextForEvent(entry);
      // Get the elapsed time, and append it to the event text.
      if (entry.isBegin()) {
        var dt = '?';
        // Definite time.
        if (entry.end) {
          dt = entry.end.orig.time - entry.orig.time;
        } else if (logCreationTime != undefined) {
          dt = (logCreationTime - entryTime) + '+';
        }
        eventText += '  [dt=' + dt + ']';
      }

      var mainCell = tablePrinter.addCell(eventText);
      mainCell.allowOverflow = true;
    }

    // Output the extra parameters.
    if (typeof entry.orig.params == 'object') {
      // Those 5 skipped cells are: two for "t=", and three for "st=".
      tablePrinter.setNewRowCellIndent(5 + entry.getDepth());
      writeParameters(entry.orig, privacyStripping, parameterOutputter);

      tablePrinter.setNewRowCellIndent(0);
    }
  }

  // If viewing a saved log file, add row with just the time the log was
  // created, if the event never completed.
  var lastEntry = entries[entries.length - 1];
  // If the last entry has a non-zero depth or is a begin event, the source is
  // still active.
  var isSourceActive = lastEntry.getDepth() != 0 || lastEntry.isBegin();
  if (logCreationTime != undefined && isSourceActive) {
    addRowWithTime(tablePrinter,
                   logCreationTime - baseTime,
                   startTime - baseTime);
  }

  return tablePrinter;
};

/**
 * Adds a new row to the given TablePrinter, and adds five cells containing
 * information about the time an event occured.
 * Format is '[t=<time of the event in ms>] [st=<ms since the source started>]'.
 * @param {TablePrinter} tablePrinter The table printer to add the cells to.
 * @param {number} eventTime The time the event occured, in milliseconds,
 *     relative to some base time.
 * @param {number} startTime The time the first event for the source occured,
 *     relative to the same base time as eventTime.
 */
function addRowWithTime(tablePrinter, eventTime, startTime) {
  tablePrinter.addRow();
  tablePrinter.addCell('t=');
  var tCell = tablePrinter.addCell(eventTime);
  tCell.alignRight = true;
  tablePrinter.addCell(' [st=');
  var stCell = tablePrinter.addCell(eventTime - startTime);
  stCell.alignRight = true;
  tablePrinter.addCell('] ');
}

/**
 * |hexString| must be a string of hexadecimal characters with no whitespace,
 * whose length is a multiple of two.  Writes multiple lines to |out| with
 * the hexadecimal characters from |hexString| on the left, in groups of
 * two, and their corresponding ASCII characters on the right.
 *
 * 16 bytes will be placed on each line of the output string, split into two
 * columns of 8.
 */
function writeHexString(hexString, out) {
  var asciiCharsPerLine = 16;
  // Number of transferred bytes in a line of output.  Length of a
  // line is roughly 4 times larger.
  var hexCharsPerLine = 2 * asciiCharsPerLine;
  for (var i = 0; i < hexString.length; i += hexCharsPerLine) {
    var hexLine = '';
    var asciiLine = '';
    for (var j = i; j < i + hexCharsPerLine && j < hexString.length; j += 2) {
      // Split into two columns of 8 bytes each.
      if (j == i + hexCharsPerLine / 2)
        hexLine += ' ';
      var hex = hexString.substr(j, 2);
      hexLine += hex + ' ';
      var charCode = parseInt(hex, 16);
      // For ASCII codes 32 though 126, display the corresponding
      // characters.  Use a space for nulls, and a period for
      // everything else.
      if (charCode >= 0x20 && charCode <= 0x7E) {
        asciiLine += String.fromCharCode(charCode);
      } else if (charCode == 0x00) {
        asciiLine += ' ';
      } else {
        asciiLine += '.';
      }
    }

    // Make the ASCII text for the last line of output align with the previous
    // lines.
    hexLine += makeRepeatedString(' ',
                                  3 * asciiCharsPerLine + 1 - hexLine.length);
    out.writeLine('   ' + hexLine + '  ' + asciiLine);
  }
}

/**
 * Wrapper around a TablePrinter to simplify outputting lines of text for event
 * parameters.
 */
var ParameterOutputter = (function() {
  /**
   * @constructor
   */
  function ParameterOutputter(tablePrinter) {
    this.tablePrinter_ = tablePrinter;
  }

  ParameterOutputter.prototype = {
    /**
     * Outputs a single line.
     */
    writeLine: function(line) {
      this.tablePrinter_.addRow();
      var cell = this.tablePrinter_.addCell(line);
      cell.allowOverflow = true;
      return cell;
    },

    /**
     * Outputs a key=value line which looks like:
     *
     *   --> key = value
     */
    writeArrowKeyValue: function(key, value, link) {
      var cell = this.writeLine(kArrow + key + ' = ' + value);
      cell.link = link;
    },

    /**
     * Outputs a key= line which looks like:
     *
     *   --> key =
     */
    writeArrowKey: function(key) {
      this.writeLine(kArrow + key + ' =');
    },

    /**
     * Outputs multiple lines, each indented by numSpaces.
     * For instance if numSpaces=8 it might look like this:
     *
     *         line 1
     *         line 2
     *         line 3
     */
    writeSpaceIndentedLines: function(numSpaces, lines) {
      var prefix = makeRepeatedString(' ', numSpaces);
      for (var i = 0; i < lines.length; ++i)
        this.writeLine(prefix + lines[i]);
    },

    /**
     * Outputs multiple lines such that the first line has
     * an arrow pointing at it, and subsequent lines
     * align with the first one. For example:
     *
     *   --> line 1
     *       line 2
     *       line 3
     */
    writeArrowIndentedLines: function(lines) {
      if (lines.length == 0)
        return;

      this.writeLine(kArrow + lines[0]);

      for (var i = 1; i < lines.length; ++i)
        this.writeLine(kArrowIndentation + lines[i]);
    }
  };

  var kArrow = ' --> ';
  var kArrowIndentation = '     ';

  return ParameterOutputter;
})();  // end of ParameterOutputter

/**
 * Formats the parameters for |entry| and writes them to |out|.
 * Certain event types have custom pretty printers. Everything else will
 * default to a JSON-like format.
 */
function writeParameters(entry, privacyStripping, out) {
  if (privacyStripping) {
    // If privacy stripping is enabled, remove data as needed.
    entry = stripPrivacyInfo(entry);
  } else {
    // If headers are in an object, convert them to an array for better display.
    entry = reformatHeaders(entry);
  }

  // Use any parameter writer available for this event type.
  var paramsWriter = getParamaterWriterForEventType(entry.type);
  var consumedParams = {};
  if (paramsWriter)
    paramsWriter(entry, out, consumedParams);

  // Write any un-consumed parameters.
  for (var k in entry.params) {
    if (consumedParams[k])
      continue;
    defaultWriteParameter(k, entry.params[k], out);
  }
}

/**
 * Finds a writer to format the parameters for events of type |eventType|.
 *
 * @return {function} The returned function "writer" can be invoked
 *                    as |writer(entry, writer, consumedParams)|. It will
 *                    output the parameters of |entry| to |out|, and fill
 *                    |consumedParams| with the keys of the parameters
 *                    consumed. If no writer is available for |eventType| then
 *                    returns null.
 */
function getParamaterWriterForEventType(eventType) {
  switch (eventType) {
    case EventType.HTTP_TRANSACTION_SEND_REQUEST_HEADERS:
    case EventType.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS:
    case EventType.TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS:
      return writeParamsForRequestHeaders;

    case EventType.PROXY_CONFIG_CHANGED:
      return writeParamsForProxyConfigChanged;

    case EventType.CERT_VERIFIER_JOB:
    case EventType.SSL_CERTIFICATES_RECEIVED:
      return writeParamsForCertificates;
    case EventType.EV_CERT_CT_COMPLIANCE_CHECKED:
      return writeParamsForCheckedEVCertificates;

    case EventType.SSL_VERSION_FALLBACK:
      return writeParamsForSSLVersionFallback;
  }
  return null;
}

/**
 * Default parameter writer that outputs a visualization of field named |key|
 * with value |value| to |out|.
 */
function defaultWriteParameter(key, value, out) {
  if (key == 'headers' && value instanceof Array) {
    out.writeArrowIndentedLines(value);
    return;
  }

  // For transferred bytes, display the bytes in hex and ASCII.
  if (key == 'hex_encoded_bytes' && typeof value == 'string') {
    out.writeArrowKey(key);
    writeHexString(value, out);
    return;
  }

  // Handle source_dependency entries - add link and map source type to
  // string.
  if (key == 'source_dependency' && typeof value == 'object') {
    var link = '#events&s=' + value.id;
    var valueStr = value.id + ' (' + EventSourceTypeNames[value.type] + ')';
    out.writeArrowKeyValue(key, valueStr, link);
    return;
  }

  if (key == 'net_error' && typeof value == 'number') {
    var valueStr = value + ' (' + netErrorToString(value) + ')';
    out.writeArrowKeyValue(key, valueStr);
    return;
  }

  if (key == 'quic_error' && typeof value == 'number') {
    var valueStr = value + ' (' + quicErrorToString(value) + ')';
    out.writeArrowKeyValue(key, valueStr);
    return;
  }

  if (key == 'quic_crypto_handshake_message' && typeof value == 'string') {
    var lines = value.split('\n');
    out.writeArrowIndentedLines(lines);
    return;
  }

  if (key == 'quic_rst_stream_error' && typeof value == 'number') {
    var valueStr = value + ' (' + quicRstStreamErrorToString(value) + ')';
    out.writeArrowKeyValue(key, valueStr);
    return;
  }

  if (key == 'load_flags' && typeof value == 'number') {
    var valueStr = value + ' (' + getLoadFlagSymbolicString(value) + ')';
    out.writeArrowKeyValue(key, valueStr);
    return;
  }

  if (key == 'load_state' && typeof value == 'number') {
    var valueStr = value + ' (' + getKeyWithValue(LoadState, value) + ')';
    out.writeArrowKeyValue(key, valueStr);
    return;
  }

  if (key == 'sdch_problem_code' && typeof value == 'number') {
    var valueStr = value + ' (' + sdchProblemCodeToString(value) + ')';
    out.writeArrowKeyValue(key, valueStr);
    return;
  }

  // Otherwise just default to JSON formatting of the value.
  out.writeArrowKeyValue(key, JSON.stringify(value));
}

/**
 * Returns the set of LoadFlags that make up the integer |loadFlag|.
 * For example: getLoadFlagSymbolicString(
 */
function getLoadFlagSymbolicString(loadFlag) {

  return getSymbolicString(loadFlag, LoadFlag,
                           getKeyWithValue(LoadFlag, loadFlag));
}

/**
 * Returns the set of CertStatusFlags that make up the integer |certStatusFlag|
 */
function getCertStatusFlagSymbolicString(certStatusFlag) {
  return getSymbolicString(certStatusFlag, CertStatusFlag, '');
}

/**
 * Returns a string representing the flags composing the given bitmask.
 */
function getSymbolicString(bitmask, valueToName, zeroName) {
  var matchingFlagNames = [];

  for (var k in valueToName) {
    if (bitmask & valueToName[k])
      matchingFlagNames.push(k);
  }

  // If no flags were matched, returns a special value.
  if (matchingFlagNames.length == 0)
    return zeroName;

  return matchingFlagNames.join(' | ');
}

/**
 * Converts an SSL version number to a textual representation.
 * For instance, SSLVersionNumberToName(0x0301) returns 'TLS 1.0'.
 */
function SSLVersionNumberToName(version) {
  if ((version & 0xFFFF) != version) {
    // If the version number is more than 2 bytes long something is wrong.
    // Print it as hex.
    return 'SSL 0x' + version.toString(16);
  }

  // See if it is a known TLS name.
  var kTLSNames = {
    0x0301: 'TLS 1.0',
    0x0302: 'TLS 1.1',
    0x0303: 'TLS 1.2'
  };
  var name = kTLSNames[version];
  if (name)
    return name;

  // Otherwise label it as an SSL version.
  var major = (version & 0xFF00) >> 8;
  var minor = version & 0x00FF;

  return 'SSL ' + major + '.' + minor;
}

/**
 * TODO(eroman): get rid of this, as it is only used by 1 callsite.
 *
 * Indent |lines| by |start|.
 *
 * For example, if |start| = ' -> ' and |lines| = ['line1', 'line2', 'line3']
 * the output will be:
 *
 *   " -> line1\n" +
 *   "    line2\n" +
 *   "    line3"
 */
function indentLines(start, lines) {
  return start + lines.join('\n' + makeRepeatedString(' ', start.length));
}

/**
 * If entry.param.headers exists and is an object other than an array, converts
 * it into an array and returns a new entry.  Otherwise, just returns the
 * original entry.
 */
function reformatHeaders(entry) {
  // If there are no headers, or it is not an object other than an array,
  // return |entry| without modification.
  if (!entry.params || entry.params.headers === undefined ||
      typeof entry.params.headers != 'object' ||
      entry.params.headers instanceof Array) {
    return entry;
  }

  // Duplicate the top level object, and |entry.params|, so the original object
  // will not be modified.
  entry = shallowCloneObject(entry);
  entry.params = shallowCloneObject(entry.params);

  // Convert headers to an array.
  var headers = [];
  for (var key in entry.params.headers)
    headers.push(key + ': ' + entry.params.headers[key]);
  entry.params.headers = headers;

  return entry;
}

/**
 * Removes a cookie or unencrypted login information from a single HTTP header
 * line, if present, and returns the modified line.  Otherwise, just returns
 * the original line.
 *
 * Note: this logic should be kept in sync with
 * net::ElideHeaderValueForNetLog in net/http/http_log_util.cc.
 */
function stripCookieOrLoginInfo(line) {
  var patterns = [
      // Cookie patterns
      /^set-cookie: /i,
      /^set-cookie2: /i,
      /^cookie: /i,

      // Unencrypted authentication patterns
      /^authorization: \S*\s*/i,
      /^proxy-authorization: \S*\s*/i];

  // Prefix will hold the first part of the string that contains no private
  // information.  If null, no part of the string contains private information.
  var prefix = null;
  for (var i = 0; i < patterns.length; i++) {
    var match = patterns[i].exec(line);
    if (match != null) {
      prefix = match[0];
      break;
    }
  }

  // Look for authentication information from data received from the server in
  // multi-round Negotiate authentication.
  if (prefix === null) {
    var challengePatterns = [
        /^www-authenticate: (\S*)\s*/i,
        /^proxy-authenticate: (\S*)\s*/i];
    for (var i = 0; i < challengePatterns.length; i++) {
      var match = challengePatterns[i].exec(line);
      if (!match)
        continue;

      // If there's no data after the scheme name, do nothing.
      if (match[0].length == line.length)
        break;

      // Ignore lines with commas, as they may contain lists of schemes, and
      // the information we want to hide is Base64 encoded, so has no commas.
      if (line.indexOf(',') >= 0)
        break;

      // Ignore Basic and Digest authentication challenges, as they contain
      // public information.
      if (/^basic$/i.test(match[1]) || /^digest$/i.test(match[1]))
        break;

      prefix = match[0];
      break;
    }
  }

  if (prefix) {
    var suffix = line.slice(prefix.length);
    // If private information has already been removed, keep the line as-is.
    // This is often the case when viewing a loaded log.
    if (suffix.search(/^\[[0-9]+ bytes were stripped\]$/) == -1) {
      return prefix + '[' + suffix.length + ' bytes were stripped]';
    }
  }

  return line;
}

/**
 * Remove debug data from HTTP/2 GOAWAY frame due to privacy considerations, see
 * https://httpwg.github.io/specs/rfc7540.html#GOAWAY.
 *
 * Note: this logic should be kept in sync with
 * net::ElideGoAwayDebugDataForNetLog in net/http/http_log_util.cc.
 */
function stripGoAwayDebugData(value) {
  return '[' + value.length + ' bytes were stripped]';
}

/**
 * If |entry| has headers, returns a copy of |entry| with all cookie and
 * unencrypted login text removed.  Otherwise, returns original |entry| object.
 * This is needed so that JSON log dumps can be made without affecting the
 * source data.  Converts headers stored in objects to arrays.
 */
stripPrivacyInfo = function(entry) {
  if (!entry.params) {
    return entry;
  }

  if (entry.type == EventType.HTTP2_SESSION_GOAWAY &&
      entry.params.debug_data != undefined) {
    // Duplicate the top level object, and |entry.params|.  All other fields are
    // just pointers to the original values, as they won't be modified, other
    // than |entry.params.debug_data|.
    entry = shallowCloneObject(entry);
    entry.params = shallowCloneObject(entry.params);
    entry.params.debug_data =
        stripGoAwayDebugData(entry.params.debug_data);
    return entry;
  }

  if (entry.params.headers === undefined ||
      !(entry.params.headers instanceof Object)) {
    return entry;
  }

  // Make sure entry's headers are in an array.
  entry = reformatHeaders(entry);

  // Duplicate the top level object, and |entry.params|.  All other fields are
  // just pointers to the original values, as they won't be modified, other than
  // |entry.params.headers|.
  entry = shallowCloneObject(entry);
  entry.params = shallowCloneObject(entry.params);

  entry.params.headers = entry.params.headers.map(stripCookieOrLoginInfo);
  return entry;
};

/**
 * Outputs the request header parameters of |entry| to |out|.
 */
function writeParamsForRequestHeaders(entry, out, consumedParams) {
  var params = entry.params;

  if (!(typeof params.line == 'string') || !(params.headers instanceof Array)) {
    // Unrecognized params.
    return;
  }

  // Strip the trailing CRLF that params.line contains.
  var lineWithoutCRLF = params.line.replace(/\r\n$/g, '');
  out.writeArrowIndentedLines([lineWithoutCRLF].concat(params.headers));

  consumedParams.line = true;
  consumedParams.headers = true;
}

function writeCertificateParam(
    certs_container, out, consumedParams, paramName) {
  if (certs_container.certificates instanceof Array) {
    var certs = certs_container.certificates.reduce(
        function(previous, current) {
          return previous.concat(current.split('\n'));
        }, new Array());
    out.writeArrowKey(paramName);
    out.writeSpaceIndentedLines(8, certs);
    consumedParams[paramName] = true;
  }
}

/**
 * Outputs the certificate parameters of |entry| to |out|.
 */
function writeParamsForCertificates(entry, out, consumedParams) {
  writeCertificateParam(entry.params, out, consumedParams, 'certificates');

  if (typeof(entry.params.verified_cert) == 'object')
    writeCertificateParam(
        entry.params.verified_cert, out, consumedParams, 'verified_cert');

  if (typeof(entry.params.cert_status) == 'number') {
    var valueStr = entry.params.cert_status + ' (' +
        getCertStatusFlagSymbolicString(entry.params.cert_status) + ')';
    out.writeArrowKeyValue('cert_status', valueStr);
    consumedParams.cert_status = true;
  }

}

function writeParamsForCheckedEVCertificates(entry, out, consumedParams) {
  if (typeof(entry.params.certificate) == 'object')
    writeCertificateParam(
        entry.params.certificate, out, consumedParams, 'certificate');
}

/**
 * Outputs the SSL version fallback parameters of |entry| to |out|.
 */
function writeParamsForSSLVersionFallback(entry, out, consumedParams) {
  var params = entry.params;

  if (typeof params.version_before != 'number' ||
      typeof params.version_after != 'number') {
    // Unrecognized params.
    return;
  }

  var line = SSLVersionNumberToName(params.version_before) +
             ' ==> ' +
             SSLVersionNumberToName(params.version_after);
  out.writeArrowIndentedLines([line]);

  consumedParams.version_before = true;
  consumedParams.version_after = true;
}

function writeParamsForProxyConfigChanged(entry, out, consumedParams) {
  var params = entry.params;

  if (typeof params.new_config != 'object') {
    // Unrecognized params.
    return;
  }

  if (typeof params.old_config == 'object') {
    var oldConfigString = proxySettingsToString(params.old_config);
    // The previous configuration may not be present in the case of
    // the initial proxy settings fetch.
    out.writeArrowKey('old_config');

    out.writeSpaceIndentedLines(8, oldConfigString.split('\n'));

    consumedParams.old_config = true;
  }

  var newConfigString = proxySettingsToString(params.new_config);
  out.writeArrowKey('new_config');
  out.writeSpaceIndentedLines(8, newConfigString.split('\n'));

  consumedParams.new_config = true;
}

function getTextForEvent(entry) {
  var text = '';

  if (entry.isBegin() && canCollapseBeginWithEnd(entry)) {
    // Don't prefix with '+' if we are going to collapse the END event.
    text = ' ';
  } else if (entry.isBegin()) {
    text = '+' + text;
  } else if (entry.isEnd()) {
    text = '-' + text;
  } else {
    text = ' ';
  }

  text += EventTypeNames[entry.orig.type];
  return text;
}

proxySettingsToString = function(config) {
  if (!config)
    return '';

  // TODO(eroman): if |config| has unexpected properties, print it as JSON
  //               rather than hide them.

  function getProxyListString(proxies) {
    // Older versions of Chrome would set these values as strings, whereas newer
    // logs use arrays.
    // TODO(eroman): This behavior changed in M27. Support for older logs can
    //               safely be removed circa M29.
    if (Array.isArray(proxies)) {
      var listString = proxies.join(', ');
      if (proxies.length > 1)
        return '[' + listString + ']';
      return listString;
    }
    return proxies;
  }

  // The proxy settings specify up to three major fallback choices
  // (auto-detect, custom pac url, or manual settings).
  // We enumerate these to a list so we can later number them.
  var modes = [];

  // Output any automatic settings.
  if (config.auto_detect)
    modes.push(['Auto-detect']);
  if (config.pac_url)
    modes.push(['PAC script: ' + config.pac_url]);

  // Output any manual settings.
  if (config.single_proxy || config.proxy_per_scheme) {
    var lines = [];

    if (config.single_proxy) {
      lines.push('Proxy server: ' + getProxyListString(config.single_proxy));
    } else if (config.proxy_per_scheme) {
      for (var urlScheme in config.proxy_per_scheme) {
        if (urlScheme != 'fallback') {
          lines.push('Proxy server for ' + urlScheme.toUpperCase() + ': ' +
                     getProxyListString(config.proxy_per_scheme[urlScheme]));
        }
      }
      if (config.proxy_per_scheme.fallback) {
        lines.push('Proxy server for everything else: ' +
                   getProxyListString(config.proxy_per_scheme.fallback));
      }
    }

    // Output any proxy bypass rules.
    if (config.bypass_list) {
      if (config.reverse_bypass) {
        lines.push('Reversed bypass list: ');
      } else {
        lines.push('Bypass list: ');
      }

      for (var i = 0; i < config.bypass_list.length; ++i)
        lines.push('  ' + config.bypass_list[i]);
    }

    modes.push(lines);
  }

  var result = [];
  if (modes.length < 1) {
    // If we didn't find any proxy settings modes, we are using DIRECT.
    result.push('Use DIRECT connections.');
  } else if (modes.length == 1) {
    // If there was just one mode, don't bother numbering it.
    result.push(modes[0].join('\n'));
  } else {
    // Otherwise concatenate all of the modes into a numbered list
    // (which correspond with the fallback order).
    for (var i = 0; i < modes.length; ++i)
      result.push(indentLines('(' + (i + 1) + ') ', modes[i]));
  }

  if (config.source != undefined && config.source != 'UNKNOWN')
    result.push('Source: ' + config.source);

  return result.join('\n');
};

// End of anonymous namespace.
})();