This repository was archived by the owner on Sep 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 207
/
Copy pathnet_util.cc
2415 lines (2148 loc) · 84.3 KB
/
net_util.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
#include "net/base/net_util.h"
#include <algorithm>
#include <iterator>
#include <map>
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi.lib")
#elif defined(OS_POSIX)
#include <fcntl.h>
#if !defined(OS_ANDROID)
#include <ifaddrs.h>
#endif
#include <netdb.h>
#include <net/if.h>
#include <netinet/in.h>
#endif
#include "base/base64.h"
#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/file_util_icu.h"
#include "base/i18n/icu_string_conversions.h"
#include "base/i18n/time_formatting.h"
#include "base/json/string_escape.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/stl_util.h"
#include "base/string_number_conversions.h"
#include "base/string_piece.h"
#include "base/string_split.h"
#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/sys_string_conversions.h"
#include "base/sys_byteorder.h"
#include "base/time.h"
#include "base/utf_offset_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "googleurl/src/url_canon.h"
#include "googleurl/src/url_canon_ip.h"
#include "googleurl/src/url_parse.h"
#include "grit/net_resources.h"
#include "net/base/dns_util.h"
#include "net/base/escape.h"
#include "net/base/mime_util.h"
#include "net/base/net_module.h"
#if defined(OS_WIN)
#include "net/base/winsock_init.h"
#endif
#include "net/http/http_content_disposition.h"
#include "unicode/datefmt.h"
#include "unicode/regex.h"
#include "unicode/ucnv.h"
#include "unicode/uidna.h"
#include "unicode/ulocdata.h"
#include "unicode/uniset.h"
#include "unicode/uscript.h"
#include "unicode/uset.h"
using base::Time;
namespace net {
namespace {
// what we prepend to get a file URL
static const FilePath::CharType kFileURLPrefix[] =
FILE_PATH_LITERAL("file:///");
// The general list of blocked ports. Will be blocked unless a specific
// protocol overrides it. (Ex: ftp can use ports 20 and 21)
static const int kRestrictedPorts[] = {
1, // tcpmux
7, // echo
9, // discard
11, // systat
13, // daytime
15, // netstat
17, // qotd
19, // chargen
20, // ftp data
21, // ftp access
22, // ssh
23, // telnet
25, // smtp
37, // time
42, // name
43, // nicname
53, // domain
77, // priv-rjs
79, // finger
87, // ttylink
95, // supdup
101, // hostriame
102, // iso-tsap
103, // gppitnp
104, // acr-nema
109, // pop2
110, // pop3
111, // sunrpc
113, // auth
115, // sftp
117, // uucp-path
119, // nntp
123, // NTP
135, // loc-srv /epmap
139, // netbios
143, // imap2
179, // BGP
389, // ldap
465, // smtp+ssl
512, // print / exec
513, // login
514, // shell
515, // printer
526, // tempo
530, // courier
531, // chat
532, // netnews
540, // uucp
556, // remotefs
563, // nntp+ssl
587, // stmp?
601, // ??
636, // ldap+ssl
993, // ldap+ssl
995, // pop3+ssl
2049, // nfs
3659, // apple-sasl / PasswordServer
4045, // lockd
6000, // X11
6665, // Alternate IRC [Apple addition]
6666, // Alternate IRC [Apple addition]
6667, // Standard IRC [Apple addition]
6668, // Alternate IRC [Apple addition]
6669, // Alternate IRC [Apple addition]
0xFFFF, // Used to block all invalid port numbers (see
// third_party/WebKit/Source/WebCore/platform/KURLGoogle.cpp, port())
};
// FTP overrides the following restricted ports.
static const int kAllowedFtpPorts[] = {
21, // ftp data
22, // ssh
};
std::string::size_type CountTrailingChars(
const std::string& input,
const std::string::value_type trailing_chars[]) {
const size_t last_good_char = input.find_last_not_of(trailing_chars);
return (last_good_char == std::string::npos) ?
input.length() : (input.length() - last_good_char - 1);
}
// Similar to Base64Decode. Decodes a Q-encoded string to a sequence
// of bytes. If input is invalid, return false.
bool QPDecode(const std::string& input, std::string* output) {
std::string temp;
temp.reserve(input.size());
for (std::string::const_iterator it = input.begin(); it != input.end();
++it) {
if (*it == '_') {
temp.push_back(' ');
} else if (*it == '=') {
if ((input.end() - it < 3) ||
!IsHexDigit(static_cast<unsigned char>(*(it + 1))) ||
!IsHexDigit(static_cast<unsigned char>(*(it + 2))))
return false;
unsigned char ch = HexDigitToInt(*(it + 1)) * 16 +
HexDigitToInt(*(it + 2));
temp.push_back(static_cast<char>(ch));
++it;
++it;
} else if (0x20 < *it && *it < 0x7F) {
// In a Q-encoded word, only printable ASCII characters
// represent themselves. Besides, space, '=', '_' and '?' are
// not allowed, but they're already filtered out.
DCHECK_NE('=', *it);
DCHECK_NE('?', *it);
DCHECK_NE('_', *it);
temp.push_back(*it);
} else {
return false;
}
}
output->swap(temp);
return true;
}
enum RFC2047EncodingType {Q_ENCODING, B_ENCODING};
bool DecodeBQEncoding(const std::string& part,
RFC2047EncodingType enc_type,
const std::string& charset,
std::string* output) {
std::string decoded;
if (!((enc_type == B_ENCODING) ?
base::Base64Decode(part, &decoded) : QPDecode(part, &decoded)))
return false;
if (decoded.empty()) {
output->clear();
return true;
}
UErrorCode err = U_ZERO_ERROR;
UConverter* converter(ucnv_open(charset.c_str(), &err));
if (U_FAILURE(err))
return false;
// A single byte in a legacy encoding can be expanded to 3 bytes in UTF-8.
// A 'two-byte character' in a legacy encoding can be expanded to 4 bytes
// in UTF-8. Therefore, the expansion ratio is 3 at most. Add one for a
// trailing '\0'.
size_t output_length = decoded.length() * 3 + 1;
char* buf = WriteInto(output, output_length);
output_length = ucnv_toAlgorithmic(UCNV_UTF8, converter, buf, output_length,
decoded.data(), decoded.length(), &err);
ucnv_close(converter);
if (U_FAILURE(err))
return false;
output->resize(output_length);
return true;
}
bool DecodeWord(const std::string& encoded_word,
const std::string& referrer_charset,
bool* is_rfc2047,
std::string* output) {
*is_rfc2047 = false;
output->clear();
if (encoded_word.empty())
return true;
if (!IsStringASCII(encoded_word)) {
// Try UTF-8, referrer_charset and the native OS default charset in turn.
if (IsStringUTF8(encoded_word)) {
*output = encoded_word;
} else {
string16 utf16_output;
if (!referrer_charset.empty() &&
base::CodepageToUTF16(encoded_word, referrer_charset.c_str(),
base::OnStringConversionError::FAIL,
&utf16_output)) {
*output = UTF16ToUTF8(utf16_output);
} else {
*output = WideToUTF8(base::SysNativeMBToWide(encoded_word));
}
}
return true;
}
// RFC 2047 : one of encoding methods supported by Firefox and relatively
// widely used by web servers.
// =?charset?<E>?<encoded string>?= where '<E>' is either 'B' or 'Q'.
// We don't care about the length restriction (72 bytes) because
// many web servers generate encoded words longer than the limit.
std::string tmp;
*is_rfc2047 = true;
int part_index = 0;
std::string charset;
StringTokenizer t(encoded_word, "?");
RFC2047EncodingType enc_type = Q_ENCODING;
while (*is_rfc2047 && t.GetNext()) {
std::string part = t.token();
switch (part_index) {
case 0:
if (part != "=") {
*is_rfc2047 = false;
break;
}
++part_index;
break;
case 1:
// Do we need charset validity check here?
charset = part;
++part_index;
break;
case 2:
if (part.size() > 1 ||
part.find_first_of("bBqQ") == std::string::npos) {
*is_rfc2047 = false;
break;
}
if (part[0] == 'b' || part[0] == 'B') {
enc_type = B_ENCODING;
}
++part_index;
break;
case 3:
*is_rfc2047 = DecodeBQEncoding(part, enc_type, charset, &tmp);
if (!*is_rfc2047) {
// Last minute failure. Invalid B/Q encoding. Rather than
// passing it through, return now.
return false;
}
++part_index;
break;
case 4:
if (part != "=") {
// Another last minute failure !
// Likely to be a case of two encoded-words in a row or
// an encoded word followed by a non-encoded word. We can be
// generous, but it does not help much in terms of compatibility,
// I believe. Return immediately.
*is_rfc2047 = false;
return false;
}
++part_index;
break;
default:
*is_rfc2047 = false;
return false;
}
}
if (*is_rfc2047) {
if (*(encoded_word.end() - 1) == '=') {
output->swap(tmp);
return true;
}
// encoded_word ending prematurelly with '?' or extra '?'
*is_rfc2047 = false;
return false;
}
// We're not handling 'especial' characters quoted with '\', but
// it should be Ok because we're not an email client but a
// web browser.
// What IE6/7 does: %-escaped UTF-8.
tmp = UnescapeURLComponent(encoded_word, UnescapeRule::SPACES);
if (IsStringUTF8(tmp)) {
output->swap(tmp);
return true;
// We can try either the OS default charset or 'origin charset' here,
// As far as I can tell, IE does not support it. However, I've seen
// web servers emit %-escaped string in a legacy encoding (usually
// origin charset).
// TODO(jungshik) : Test IE further and consider adding a fallback here.
}
return false;
}
// Does some simple normalization of scripts so we can allow certain scripts
// to exist together.
// TODO(brettw) bug 880223: we should allow some other languages to be
// oombined such as Chinese and Latin. We will probably need a more
// complicated system of language pairs to have more fine-grained control.
UScriptCode NormalizeScript(UScriptCode code) {
switch (code) {
case USCRIPT_KATAKANA:
case USCRIPT_HIRAGANA:
case USCRIPT_KATAKANA_OR_HIRAGANA:
case USCRIPT_HANGUL: // This one is arguable.
return USCRIPT_HAN;
default:
return code;
}
}
bool IsIDNComponentInSingleScript(const char16* str, int str_len) {
UScriptCode first_script = USCRIPT_INVALID_CODE;
bool is_first = true;
int i = 0;
while (i < str_len) {
unsigned code_point;
U16_NEXT(str, i, str_len, code_point);
UErrorCode err = U_ZERO_ERROR;
UScriptCode cur_script = uscript_getScript(code_point, &err);
if (err != U_ZERO_ERROR)
return false; // Report mixed on error.
cur_script = NormalizeScript(cur_script);
// TODO(brettw) We may have to check for USCRIPT_INHERENT as well.
if (is_first && cur_script != USCRIPT_COMMON) {
first_script = cur_script;
is_first = false;
} else {
if (cur_script != USCRIPT_COMMON && cur_script != first_script)
return false;
}
}
return true;
}
// Check if the script of a language can be 'safely' mixed with
// Latin letters in the ASCII range.
bool IsCompatibleWithASCIILetters(const std::string& lang) {
// For now, just list Chinese, Japanese and Korean (positive list).
// An alternative is negative-listing (languages using Greek and
// Cyrillic letters), but it can be more dangerous.
return !lang.substr(0, 2).compare("zh") ||
!lang.substr(0, 2).compare("ja") ||
!lang.substr(0, 2).compare("ko");
}
typedef std::map<std::string, icu::UnicodeSet*> LangToExemplarSetMap;
class LangToExemplarSet {
public:
static LangToExemplarSet* GetInstance() {
return Singleton<LangToExemplarSet>::get();
}
private:
LangToExemplarSetMap map;
LangToExemplarSet() { }
~LangToExemplarSet() {
STLDeleteContainerPairSecondPointers(map.begin(), map.end());
}
friend class Singleton<LangToExemplarSet>;
friend struct DefaultSingletonTraits<LangToExemplarSet>;
friend bool GetExemplarSetForLang(const std::string&, icu::UnicodeSet**);
friend void SetExemplarSetForLang(const std::string&, icu::UnicodeSet*);
DISALLOW_COPY_AND_ASSIGN(LangToExemplarSet);
};
bool GetExemplarSetForLang(const std::string& lang,
icu::UnicodeSet** lang_set) {
const LangToExemplarSetMap& map = LangToExemplarSet::GetInstance()->map;
LangToExemplarSetMap::const_iterator pos = map.find(lang);
if (pos != map.end()) {
*lang_set = pos->second;
return true;
}
return false;
}
void SetExemplarSetForLang(const std::string& lang,
icu::UnicodeSet* lang_set) {
LangToExemplarSetMap& map = LangToExemplarSet::GetInstance()->map;
map.insert(std::make_pair(lang, lang_set));
}
static base::LazyInstance<base::Lock>::Leaky
g_lang_set_lock = LAZY_INSTANCE_INITIALIZER;
// Returns true if all the characters in component_characters are used by
// the language |lang|.
bool IsComponentCoveredByLang(const icu::UnicodeSet& component_characters,
const std::string& lang) {
CR_DEFINE_STATIC_LOCAL(
const icu::UnicodeSet, kASCIILetters, ('a', 'z'));
icu::UnicodeSet* lang_set;
// We're called from both the UI thread and the history thread.
{
base::AutoLock lock(g_lang_set_lock.Get());
if (!GetExemplarSetForLang(lang, &lang_set)) {
UErrorCode status = U_ZERO_ERROR;
ULocaleData* uld = ulocdata_open(lang.c_str(), &status);
// TODO(jungshik) Turn this check on when the ICU data file is
// rebuilt with the minimal subset of locale data for languages
// to which Chrome is not localized but which we offer in the list
// of languages selectable for Accept-Languages. With the rebuilt ICU
// data, ulocdata_open never should fall back to the default locale.
// (issue 2078)
// DCHECK(U_SUCCESS(status) && status != U_USING_DEFAULT_WARNING);
if (U_SUCCESS(status) && status != U_USING_DEFAULT_WARNING) {
lang_set = reinterpret_cast<icu::UnicodeSet *>(
ulocdata_getExemplarSet(uld, NULL, 0,
ULOCDATA_ES_STANDARD, &status));
// If |lang| is compatible with ASCII Latin letters, add them.
if (IsCompatibleWithASCIILetters(lang))
lang_set->addAll(kASCIILetters);
} else {
lang_set = new icu::UnicodeSet(1, 0);
}
lang_set->freeze();
SetExemplarSetForLang(lang, lang_set);
ulocdata_close(uld);
}
}
return !lang_set->isEmpty() && lang_set->containsAll(component_characters);
}
// Returns true if the given Unicode host component is safe to display to the
// user.
bool IsIDNComponentSafe(const char16* str,
int str_len,
const std::string& languages) {
// Most common cases (non-IDN) do not reach here so that we don't
// need a fast return path.
// TODO(jungshik) : Check if there's any character inappropriate
// (although allowed) for domain names.
// See http://www.unicode.org/reports/tr39/#IDN_Security_Profiles and
// http://www.unicode.org/reports/tr39/data/xidmodifications.txt
// For now, we borrow the list from Mozilla and tweaked it slightly.
// (e.g. Characters like U+00A0, U+3000, U+3002 are omitted because
// they're gonna be canonicalized to U+0020 and full stop before
// reaching here.)
// The original list is available at
// http://kb.mozillazine.org/Network.IDN.blacklist_chars and
// at http://mxr.mozilla.org/seamonkey/source/modules/libpref/src/init/all.js#703
UErrorCode status = U_ZERO_ERROR;
#ifdef U_WCHAR_IS_UTF16
icu::UnicodeSet dangerous_characters(icu::UnicodeString(
L"[[\\ \u00bc\u00bd\u01c3\u0337\u0338"
L"\u05c3\u05f4\u06d4\u0702\u115f\u1160][\u2000-\u200b]"
L"[\u2024\u2027\u2028\u2029\u2039\u203a\u2044\u205f]"
L"[\u2154-\u2156][\u2159-\u215b][\u215f\u2215\u23ae"
L"\u29f6\u29f8\u2afb\u2afd][\u2ff0-\u2ffb][\u3014"
L"\u3015\u3033\u3164\u321d\u321e\u33ae\u33af\u33c6\u33df\ufe14"
L"\ufe15\ufe3f\ufe5d\ufe5e\ufeff\uff0e\uff06\uff61\uffa0\ufff9]"
L"[\ufffa-\ufffd]]"), status);
DCHECK(U_SUCCESS(status));
icu::RegexMatcher dangerous_patterns(icu::UnicodeString(
// Lone katakana no, so, or n
L"[^\\p{Katakana}][\u30ce\u30f3\u30bd][^\\p{Katakana}]"
// Repeating Japanese accent characters
L"|[\u3099\u309a\u309b\u309c][\u3099\u309a\u309b\u309c]"),
0, status);
#else
icu::UnicodeSet dangerous_characters(icu::UnicodeString(
"[[\\u0020\\u00bc\\u00bd\\u01c3\\u0337\\u0338"
"\\u05c3\\u05f4\\u06d4\\u0702\\u115f\\u1160][\\u2000-\\u200b]"
"[\\u2024\\u2027\\u2028\\u2029\\u2039\\u203a\\u2044\\u205f]"
"[\\u2154-\\u2156][\\u2159-\\u215b][\\u215f\\u2215\\u23ae"
"\\u29f6\\u29f8\\u2afb\\u2afd][\\u2ff0-\\u2ffb][\\u3014"
"\\u3015\\u3033\\u3164\\u321d\\u321e\\u33ae\\u33af\\u33c6\\u33df\\ufe14"
"\\ufe15\\ufe3f\\ufe5d\\ufe5e\\ufeff\\uff0e\\uff06\\uff61\\uffa0\\ufff9]"
"[\\ufffa-\\ufffd]]", -1, US_INV), status);
DCHECK(U_SUCCESS(status));
icu::RegexMatcher dangerous_patterns(icu::UnicodeString(
// Lone katakana no, so, or n
"[^\\p{Katakana}][\\u30ce\\u30f3\u30bd][^\\p{Katakana}]"
// Repeating Japanese accent characters
"|[\\u3099\\u309a\\u309b\\u309c][\\u3099\\u309a\\u309b\\u309c]"),
0, status);
#endif
DCHECK(U_SUCCESS(status));
icu::UnicodeSet component_characters;
icu::UnicodeString component_string(str, str_len);
component_characters.addAll(component_string);
if (dangerous_characters.containsSome(component_characters))
return false;
DCHECK(U_SUCCESS(status));
dangerous_patterns.reset(component_string);
if (dangerous_patterns.find())
return false;
// If the language list is empty, the result is completely determined
// by whether a component is a single script or not. This will block
// even "safe" script mixing cases like <Chinese, Latin-ASCII> that are
// allowed with |languages| (while it blocks Chinese + Latin letters with
// an accent as should be the case), but we want to err on the safe side
// when |languages| is empty.
if (languages.empty())
return IsIDNComponentInSingleScript(str, str_len);
// |common_characters| is made up of ASCII numbers, hyphen, plus and
// underscore that are used across scripts and allowed in domain names.
// (sync'd with characters allowed in url_canon_host with square
// brackets excluded.) See kHostCharLookup[] array in url_canon_host.cc.
icu::UnicodeSet common_characters(UNICODE_STRING_SIMPLE("[[0-9]\\-_+\\ ]"),
status);
DCHECK(U_SUCCESS(status));
// Subtract common characters because they're always allowed so that
// we just have to check if a language-specific set contains
// the remainder.
component_characters.removeAll(common_characters);
StringTokenizer t(languages, ",");
while (t.GetNext()) {
if (IsComponentCoveredByLang(component_characters, t.token()))
return true;
}
return false;
}
// Converts one component of a host (between dots) to IDN if safe. The result
// will be APPENDED to the given output string and will be the same as the input
// if it is not IDN or the IDN is unsafe to display. Returns whether any
// conversion was performed.
bool IDNToUnicodeOneComponent(const char16* comp,
size_t comp_len,
const std::string& languages,
string16* out) {
DCHECK(out);
if (comp_len == 0)
return false;
// Only transform if the input can be an IDN component.
static const char16 kIdnPrefix[] = {'x', 'n', '-', '-'};
if ((comp_len > arraysize(kIdnPrefix)) &&
!memcmp(comp, kIdnPrefix, arraysize(kIdnPrefix) * sizeof(char16))) {
// Repeatedly expand the output string until it's big enough. It looks like
// ICU will return the required size of the buffer, but that's not
// documented, so we'll just grow by 2x. This should be rare and is not on a
// critical path.
size_t original_length = out->length();
for (int extra_space = 64; ; extra_space *= 2) {
UErrorCode status = U_ZERO_ERROR;
out->resize(out->length() + extra_space);
int output_chars = uidna_IDNToUnicode(comp,
static_cast<int32_t>(comp_len), &(*out)[original_length], extra_space,
UIDNA_DEFAULT, NULL, &status);
if (status == U_ZERO_ERROR) {
// Converted successfully.
out->resize(original_length + output_chars);
if (IsIDNComponentSafe(out->data() + original_length, output_chars,
languages))
return true;
}
if (status != U_BUFFER_OVERFLOW_ERROR)
break;
}
// Failed, revert back to original string.
out->resize(original_length);
}
// We get here with no IDN or on error, in which case we just append the
// literal input.
out->append(comp, comp_len);
return false;
}
// Clamps the offsets in |offsets_for_adjustment| to the length of |str|.
void LimitOffsets(const string16& str,
std::vector<size_t>* offsets_for_adjustment) {
if (offsets_for_adjustment) {
std::for_each(offsets_for_adjustment->begin(),
offsets_for_adjustment->end(),
LimitOffset<string16>(str.length()));
}
}
// TODO(brettw) bug 734373: check the scripts for each host component and
// don't un-IDN-ize if there is more than one. Alternatively, only IDN for
// scripts that the user has installed. For now, just put the entire
// path through IDN. Maybe this feature can be implemented in ICU itself?
//
// We may want to skip this step in the case of file URLs to allow unicode
// UNC hostnames regardless of encodings.
string16 IDNToUnicodeWithOffsets(const std::string& host,
const std::string& languages,
std::vector<size_t>* offsets_for_adjustment) {
// Convert the ASCII input to a string16 for ICU.
string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
// Do each component of the host separately, since we enforce script matching
// on a per-component basis.
string16 out16;
{
OffsetAdjuster offset_adjuster(offsets_for_adjustment);
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
// Find the end of the component.
component_end = input16.find('.', component_start);
if (component_end == string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
// Add the substring that we just found.
converted_idn = IDNToUnicodeOneComponent(
input16.data() + component_start, component_length, languages,
&out16);
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && offsets_for_adjustment) {
offset_adjuster.Add(OffsetAdjuster::Adjustment(component_start,
component_length, new_component_length));
}
// Need to add the dot we just found (if we found one).
if (component_end < input16.length())
out16.push_back('.');
}
}
LimitOffsets(out16, offsets_for_adjustment);
return out16;
}
// Transforms |original_offsets| by subtracting |component_begin| from all
// offsets. Any offset which was not at least this large to begin with is set
// to std::string::npos.
std::vector<size_t> OffsetsIntoComponent(
const std::vector<size_t>& original_offsets,
size_t component_begin) {
DCHECK_NE(std::string::npos, component_begin);
std::vector<size_t> offsets_into_component(original_offsets);
for (std::vector<size_t>::iterator i(offsets_into_component.begin());
i != offsets_into_component.end(); ++i) {
if (*i != std::string::npos)
*i = (*i < component_begin) ? std::string::npos : (*i - component_begin);
}
return offsets_into_component;
}
// Called after we transform a component and append it to an output string.
// Maps |transformed_offsets|, which represent offsets into the transformed
// component itself, into appropriate offsets for the output string, by adding
// |output_component_begin| to each. Determines which offsets need mapping by
// checking to see which of the |original_offsets| were within the designated
// original component, using its provided endpoints.
void AdjustForComponentTransform(
const std::vector<size_t>& original_offsets,
size_t original_component_begin,
size_t original_component_end,
const std::vector<size_t>& transformed_offsets,
size_t output_component_begin,
std::vector<size_t>* offsets_for_adjustment) {
if (!offsets_for_adjustment)
return;
DCHECK_NE(std::string::npos, original_component_begin);
DCHECK_NE(std::string::npos, original_component_end);
DCHECK_NE(string16::npos, output_component_begin);
size_t offsets_size = offsets_for_adjustment->size();
DCHECK_EQ(offsets_size, original_offsets.size());
DCHECK_EQ(offsets_size, transformed_offsets.size());
for (size_t i = 0; i < offsets_size; ++i) {
size_t original_offset = original_offsets[i];
if ((original_offset >= original_component_begin) &&
(original_offset < original_component_end)) {
size_t transformed_offset = transformed_offsets[i];
(*offsets_for_adjustment)[i] = (transformed_offset == string16::npos) ?
string16::npos : (output_component_begin + transformed_offset);
}
}
}
// If |component| is valid, its begin is incremented by |delta|.
void AdjustComponent(int delta, url_parse::Component* component) {
if (!component->is_valid())
return;
DCHECK(delta >= 0 || component->begin >= -delta);
component->begin += delta;
}
// Adjusts all the components of |parsed| by |delta|, except for the scheme.
void AdjustComponents(int delta, url_parse::Parsed* parsed) {
AdjustComponent(delta, &(parsed->username));
AdjustComponent(delta, &(parsed->password));
AdjustComponent(delta, &(parsed->host));
AdjustComponent(delta, &(parsed->port));
AdjustComponent(delta, &(parsed->path));
AdjustComponent(delta, &(parsed->query));
AdjustComponent(delta, &(parsed->ref));
}
// Helper for FormatUrlWithOffsets().
string16 FormatViewSourceUrl(const GURL& url,
const std::vector<size_t>& original_offsets,
const std::string& languages,
FormatUrlTypes format_types,
UnescapeRule::Type unescape_rules,
url_parse::Parsed* new_parsed,
size_t* prefix_end,
std::vector<size_t>* offsets_for_adjustment) {
DCHECK(new_parsed);
const char kViewSource[] = "view-source:";
const size_t kViewSourceLength = arraysize(kViewSource) - 1;
std::vector<size_t> offsets_into_url(
OffsetsIntoComponent(original_offsets, kViewSourceLength));
GURL real_url(url.possibly_invalid_spec().substr(kViewSourceLength));
string16 result(ASCIIToUTF16(kViewSource) +
FormatUrlWithOffsets(real_url, languages, format_types, unescape_rules,
new_parsed, prefix_end, &offsets_into_url));
// Adjust position values.
if (new_parsed->scheme.is_nonempty()) {
// Assume "view-source:real-scheme" as a scheme.
new_parsed->scheme.len += kViewSourceLength;
} else {
new_parsed->scheme.begin = 0;
new_parsed->scheme.len = kViewSourceLength - 1;
}
AdjustComponents(kViewSourceLength, new_parsed);
if (prefix_end)
*prefix_end += kViewSourceLength;
AdjustForComponentTransform(original_offsets, kViewSourceLength,
url.possibly_invalid_spec().length(), offsets_into_url, kViewSourceLength,
offsets_for_adjustment);
LimitOffsets(result, offsets_for_adjustment);
return result;
}
class AppendComponentTransform {
public:
AppendComponentTransform() {}
virtual ~AppendComponentTransform() {}
virtual string16 Execute(
const std::string& component_text,
std::vector<size_t>* offsets_into_component) const = 0;
// NOTE: No DISALLOW_COPY_AND_ASSIGN here, since gcc < 4.3.0 requires an
// accessible copy constructor in order to call AppendFormattedComponent()
// with an inline temporary (see http://gcc.gnu.org/bugs/#cxx%5Frvalbind ).
};
class HostComponentTransform : public AppendComponentTransform {
public:
explicit HostComponentTransform(const std::string& languages)
: languages_(languages) {
}
private:
virtual string16 Execute(
const std::string& component_text,
std::vector<size_t>* offsets_into_component) const {
return IDNToUnicodeWithOffsets(component_text, languages_,
offsets_into_component);
}
const std::string& languages_;
};
class NonHostComponentTransform : public AppendComponentTransform {
public:
explicit NonHostComponentTransform(UnescapeRule::Type unescape_rules)
: unescape_rules_(unescape_rules) {
}
private:
virtual string16 Execute(
const std::string& component_text,
std::vector<size_t>* offsets_into_component) const {
return (unescape_rules_ == UnescapeRule::NONE) ?
UTF8ToUTF16AndAdjustOffsets(component_text, offsets_into_component) :
UnescapeAndDecodeUTF8URLComponentWithOffsets(component_text,
unescape_rules_, offsets_into_component);
}
const UnescapeRule::Type unescape_rules_;
};
void AppendFormattedComponent(const std::string& spec,
const url_parse::Component& original_component,
const std::vector<size_t>& original_offsets,
const AppendComponentTransform& transform,
string16* output,
url_parse::Component* output_component,
std::vector<size_t>* offsets_for_adjustment) {
DCHECK(output);
if (original_component.is_nonempty()) {
size_t original_component_begin =
static_cast<size_t>(original_component.begin);
size_t output_component_begin = output->length();
if (output_component)
output_component->begin = static_cast<int>(output_component_begin);
std::vector<size_t> offsets_into_component =
OffsetsIntoComponent(original_offsets, original_component_begin);
output->append(transform.Execute(std::string(spec, original_component_begin,
static_cast<size_t>(original_component.len)), &offsets_into_component));
if (output_component) {
output_component->len =
static_cast<int>(output->length() - output_component_begin);
}
AdjustForComponentTransform(original_offsets, original_component_begin,
static_cast<size_t>(original_component.end()),
offsets_into_component, output_component_begin,
offsets_for_adjustment);
} else if (output_component) {
output_component->reset();
}
}
void SanitizeGeneratedFileName(std::string& filename) {
if (!filename.empty()) {
// Remove "." from the beginning and end of the file name to avoid tricks
// with hidden files, "..", and "."
TrimString(filename, ".", &filename);
#if defined(OS_WIN)
// Handle CreateFile() stripping trailing dots and spaces on filenames
// http://support.microsoft.com/kb/115827
std::string::size_type pos = filename.find_last_not_of(" .");
if (pos == std::string::npos)
filename.resize(0);
else
filename.resize(++pos);
#endif
// Replace any path information by changing path separators with
// underscores.
ReplaceSubstringsAfterOffset(&filename, 0, "/", "_");
ReplaceSubstringsAfterOffset(&filename, 0, "\\", "_");
}
}
// Returns the filename determined from the last component of the path portion
// of the URL. Returns an empty string if the URL doesn't have a path or is
// invalid. If the generated filename is not reliable,
// |should_overwrite_extension| will be set to true, in which case a better
// extension should be determined based on the content type.
std::string GetFileNameFromURL(const GURL& url,
const std::string& referrer_charset,
bool* should_overwrite_extension) {
// about: and data: URLs don't have file names, but esp. data: URLs may
// contain parts that look like ones (i.e., contain a slash). Therefore we
// don't attempt to divine a file name out of them.
if (!url.is_valid() || url.SchemeIs("about") || url.SchemeIs("data"))
return std::string();
const std::string unescaped_url_filename = UnescapeURLComponent(
url.ExtractFileName(),
UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS);
// The URL's path should be escaped UTF-8, but may not be.
std::string decoded_filename = unescaped_url_filename;
if (!IsStringASCII(decoded_filename)) {
bool ignore;
// TODO(jshin): this is probably not robust enough. To be sure, we need
// encoding detection.
DecodeWord(unescaped_url_filename, referrer_charset, &ignore,
&decoded_filename);
}
// If the URL contains a (possibly empty) query, assume it is a generator, and
// allow the determined extension to be overwritten.
*should_overwrite_extension = !decoded_filename.empty() && url.has_query();
return decoded_filename;
}
#if defined(OS_WIN)
// Returns whether the specified extension is automatically integrated into the
// windows shell.
bool IsShellIntegratedExtension(const string16& extension) {
string16 extension_lower = StringToLowerASCII(extension);
static const wchar_t* const integrated_extensions[] = {
// See <http://msdn.microsoft.com/en-us/library/ms811694.aspx>.
L"local",
// Right-clicking on shortcuts can be magical.
L"lnk",
};
for (int i = 0; i < arraysize(integrated_extensions); ++i) {
if (extension_lower == integrated_extensions[i])
return true;
}
// See <http://www.juniper.net/security/auto/vulnerabilities/vuln2612.html>.
// That vulnerability report is not exactly on point, but files become magical
// if their end in a CLSID. Here we block extensions that look like CLSIDs.
if (!extension_lower.empty() && extension_lower[0] == L'{' &&
extension_lower[extension_lower.length() - 1] == L'}')
return true;
return false;
}
// Returns whether the specified file name is a reserved name on windows.
// This includes names like "com2.zip" (which correspond to devices) and
// desktop.ini and thumbs.db which have special meaning to the windows shell.
bool IsReservedName(const string16& filename) {
// This list is taken from the MSDN article "Naming a file"
// http://msdn2.microsoft.com/en-us/library/aa365247(VS.85).aspx
// I also added clock$ because GetSaveFileName seems to consider it as a
// reserved name too.
static const wchar_t* const known_devices[] = {
L"con", L"prn", L"aux", L"nul", L"com1", L"com2", L"com3", L"com4", L"com5",
L"com6", L"com7", L"com8", L"com9", L"lpt1", L"lpt2", L"lpt3", L"lpt4",
L"lpt5", L"lpt6", L"lpt7", L"lpt8", L"lpt9", L"clock$"
};
string16 filename_lower = StringToLowerASCII(filename);
for (int i = 0; i < arraysize(known_devices); ++i) {
// Exact match.
if (filename_lower == known_devices[i])
return true;
// Starts with "DEVICE.".
if (filename_lower.find(string16(known_devices[i]) + L".") == 0)
return true;
}