File: JavaScriptObjectDeserializer.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (411 lines) | stat: -rw-r--r-- 15,872 bytes parent folder | download | duplicates (7)
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
//------------------------------------------------------------------------------
// <copyright file="JavaScriptObjectDeserializer.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.Script.Serialization {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web.Resources;
    
    using AppSettings = System.Web.Util.AppSettings;
    using Debug = System.Web.Util.Debug;
    using Utf16StringValidator = System.Web.Util.Utf16StringValidator;

    internal class JavaScriptObjectDeserializer {
        private const string DateTimePrefix = @"""\/Date(";
        private const int DateTimePrefixLength = 8;

        private const string DateTimeSuffix = @"\/""";
        private const int DateTimeSuffixLength = 3;

        internal JavaScriptString _s;
        private JavaScriptSerializer _serializer;
        private int _depthLimit;

        internal static object BasicDeserialize(string input, int depthLimit, JavaScriptSerializer serializer) {
            JavaScriptObjectDeserializer jsod = new JavaScriptObjectDeserializer(input, depthLimit, serializer);
            object result = jsod.DeserializeInternal(0);
            if (jsod._s.GetNextNonEmptyChar() != null) {
                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_IllegalPrimitive, jsod._s.ToString()));
            }
            return result;
        }

        private JavaScriptObjectDeserializer(string input, int depthLimit, JavaScriptSerializer serializer) {
            _s = new JavaScriptString(input);
            _depthLimit = depthLimit;
            _serializer = serializer;
        }

        private object DeserializeInternal(int depth) {
            if (++depth > _depthLimit) {
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_DepthLimitExceeded));
            }

            Nullable<Char> c = _s.GetNextNonEmptyChar();
            if (c == null) {
                return null;
            }

            _s.MovePrev();

            if (IsNextElementDateTime()) {
                return DeserializeStringIntoDateTime();
            }

            if (IsNextElementObject(c)) {
                IDictionary<string, object> dict = DeserializeDictionary(depth);
                // Try to coerce objects to the right type if they have the __serverType
                if (dict.ContainsKey(JavaScriptSerializer.ServerTypeFieldName)) {
                    return ObjectConverter.ConvertObjectToType(dict, null, _serializer);
                }
                return dict;
            }

            if (IsNextElementArray(c)) {
                return DeserializeList(depth);
            }

            if (IsNextElementString(c)) {
                return DeserializeString();
            }

            return DeserializePrimitiveObject();
        }

        private IList DeserializeList(int depth) {
            IList list = new ArrayList();
            Nullable<Char> c = _s.MoveNext();
            if (c != '[') {
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidArrayStart));
            }

            bool expectMore = false;
            while ((c = _s.GetNextNonEmptyChar()) != null && c != ']') {
                _s.MovePrev();
                object o = DeserializeInternal(depth);
                list.Add(o);

                expectMore = false;
                // we might be done here.
                c = _s.GetNextNonEmptyChar();
                if (c == ']') {
                    break;
                }

                expectMore = true;
                if (c != ',') {
                    throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidArrayExpectComma));
                }
            }
            if (expectMore) {
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidArrayExtraComma));
            }
            if (c != ']') {
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidArrayEnd));
            }
            return list;
        }

        private IDictionary<string, object> DeserializeDictionary(int depth) {
            IDictionary<string, object> dictionary = null;
            Nullable<Char> c = _s.MoveNext();
            if (c != '{') {
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_ExpectedOpenBrace));
            }

            // Loop through each JSON entry in the input object
            while ((c = _s.GetNextNonEmptyChar()) != null) {
                _s.MovePrev();

                if (c == ':') {
                    throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidMemberName));
                }

                string memberName = null;
                if (c != '}') {
                    // Find the member name
                    memberName = DeserializeMemberName();
                    c = _s.GetNextNonEmptyChar();
                    if (c != ':') {
                        throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidObject));
                    }
                }

                if (dictionary == null) {
                    dictionary = new Dictionary<string, object>();

                    // If the object contains nothing (i.e. {}), we're done
                    if (memberName == null) {
                        // Move the cursor to the '}' character.
                        c = _s.GetNextNonEmptyChar();
                        Debug.Assert(c == '}');
                        break;
                    }
                }

                ThrowIfMaxJsonDeserializerMembersExceeded(dictionary.Count);

                // Deserialize the property value.  Here, we don't know its type
                object propVal = DeserializeInternal(depth);
                dictionary[memberName] = propVal;
                c = _s.GetNextNonEmptyChar();
                if (c == '}') {
                    break;
                }

                if (c != ',') {
                    throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidObject));
                }
            }

            if (c != '}') {
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_InvalidObject));
            }

            return dictionary;
        }

        // MSRC 12038: limit the maximum number of entries that can be added to a Json deserialized dictionary,
        // as a large number of entries potentially can result in too many hash collisions that may cause DoS
        private void ThrowIfMaxJsonDeserializerMembersExceeded(int count) {
            if (count >= AppSettings.MaxJsonDeserializerMembers) {
                throw new InvalidOperationException(SR.GetString(SR.CollectionCountExceeded_JavaScriptObjectDeserializer, AppSettings.MaxJsonDeserializerMembers));
            }
        }

        // Deserialize a member name.
        // e.g. { MemberName: ... }
        // e.g. { 'MemberName': ... }
        // e.g. { "MemberName": ... }
        private string DeserializeMemberName() {

            // It could be double quoted, single quoted, or not quoted at all
            Nullable<Char> c = _s.GetNextNonEmptyChar();
            if (c == null) {
                return null;
            }

            _s.MovePrev();

            // If it's quoted, treat it as a string
            if (IsNextElementString(c)) {
                return DeserializeString();
            }

            // Non-quoted token
            return DeserializePrimitiveToken();
        }

        private object DeserializePrimitiveObject() {
            string input = DeserializePrimitiveToken();
            if (input.Equals("null")) {
                return null;
            }

            if (input.Equals("true")) {
                return true;
            }

            if (input.Equals("false")) {
                return false;
            }

            // Is it a floating point value
            bool hasDecimalPoint = input.IndexOf('.') >= 0;
            // DevDiv 56892: don't try to parse to Int32/64/Decimal if it has an exponent sign
            bool hasExponent = input.LastIndexOf("e", StringComparison.OrdinalIgnoreCase) >= 0;
            // [Last]IndexOf(char, StringComparison) overload doesn't exist, so search for "e" as a string not a char
            // Use 'Last'IndexOf since if there is an exponent it would be more quickly found starting from the end of the string
            // since 'e' is always toward the end of the number. e.g. 1.238907598768972987E82

            if (!hasExponent) {
                // when no exponent, could be Int32, Int64, Decimal, and may fall back to Double
                // otherwise it must be Double

                if (!hasDecimalPoint) {
                    // No decimal or exponent. All Int32 and Int64s fall into this category, so try them first
                    // First try int
                    int n;
                    if (Int32.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out n)) {
                        // NumberStyles.Integer: AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign
                        return n;
                    }

                    // Then try a long
                    long l;
                    if (Int64.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out l)) {
                        // NumberStyles.Integer: AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign
                        return l;
                    }
                }

                // No exponent, may or may not have a decimal (if it doesn't it couldn't be parsed into Int32/64)
                decimal dec;
                if (decimal.TryParse(input, NumberStyles.Number, CultureInfo.InvariantCulture, out dec)) {
                    // NumberStyles.Number: AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign,
                    //                      AllowTrailingSign, AllowDecimalPoint, AllowThousands
                    return dec;
                }
            }

            // either we have an exponent or the number couldn't be parsed into any previous type. 
            Double d;
            if (Double.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out d)) {
                // NumberStyles.Float: AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowDecimalPoint, AllowExponent
                return d;
            }

            // must be an illegal primitive
            throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.JSON_IllegalPrimitive, input));
        }

        private string DeserializePrimitiveToken() {
            StringBuilder sb = new StringBuilder();
            Nullable<Char> c = null;
            while ((c = _s.MoveNext()) != null) {
                if (Char.IsLetterOrDigit(c.Value) || c.Value == '.' ||
                    c.Value == '-' || c.Value == '_' || c.Value == '+') {

                    sb.Append(c.Value);
                }
                else {
                    _s.MovePrev();
                    break;
                }
            }

            return sb.ToString();
        }

        private string DeserializeString() {
            StringBuilder sb = new StringBuilder();
            bool escapedChar = false;

            Nullable<Char> c = _s.MoveNext();

            // First determine which quote is used by the string.
            Char quoteChar = CheckQuoteChar(c);
            while ((c = _s.MoveNext()) != null) {
                if (c == '\\') {
                    if (escapedChar) {
                        sb.Append('\\');
                        escapedChar = false;
                    }
                    else {
                        escapedChar = true;
                    }

                    continue;
                }

                if (escapedChar) {
                    AppendCharToBuilder(c, sb);
                    escapedChar = false;
                }
                else {
                    if (c == quoteChar) {
                        return Utf16StringValidator.ValidateString(sb.ToString());
                    }

                    sb.Append(c.Value);
                }
            }

            throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_UnterminatedString));
        }

        private void AppendCharToBuilder(char? c, StringBuilder sb) {
            if (c == '"' || c == '\'' || c == '/') {
                sb.Append(c.Value);
            }
            else if (c == 'b') {
                sb.Append('\b');
            }
            else if (c == 'f') {
                sb.Append('\f');
            }
            else if (c == 'n') {
                sb.Append('\n');
            }
            else if (c == 'r') {
                sb.Append('\r');
            }
            else if (c == 't') {
                sb.Append('\t');
            }
            else if (c == 'u') {
                sb.Append((char)int.Parse(_s.MoveNext(4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
            }
            else {
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_BadEscape));
            }
        }

        private char CheckQuoteChar(char? c) {
            Char quoteChar = '"';
            if (c == '\'') {
                quoteChar = c.Value;
            }
            else if (c != '"') {
                // Fail if the string is not quoted.
                throw new ArgumentException(_s.GetDebugString(AtlasWeb.JSON_StringNotQuoted));
            }

            return quoteChar;
        }

        private object DeserializeStringIntoDateTime() {
            // DivDiv 41127: Never confuse atlas serialized strings with dates.
            // DevDiv 74430: JavasciptSerializer will need to handle date time offset - following WCF design
            // serialized dates look like: "\/Date(123)\/" or "\/Date(123A)" or "Date(123+4567)" or Date(123-4567)"
            // the A, +14567, -4567 portion in the above example is ignored 
            int pos = _s.IndexOf(DateTimeSuffix);
            Match match = Regex.Match(_s.Substring(pos + DateTimeSuffixLength),
                @"^""\\/Date\((?<ticks>-?[0-9]+)(?:[a-zA-Z]|(?:\+|-)[0-9]{4})?\)\\/""");
            string ticksStr = match.Groups["ticks"].Value;

            long ticks;
            if (long.TryParse(ticksStr, out ticks)) {
                _s.MoveNext(match.Length);

                // The javascript ticks start from 1/1/1970 but FX DateTime ticks start from 1/1/0001
                DateTime dt = new DateTime(ticks * 10000 + JavaScriptSerializer.DatetimeMinTimeTicks, DateTimeKind.Utc);
                return dt;
            }
            else {
                // If we failed to get a DateTime, treat it as a string
                return DeserializeString();
            }
        }

        private static bool IsNextElementArray(Nullable<Char> c) {
            return c == '[';
        }

        private bool IsNextElementDateTime() {
            String next = _s.MoveNext(DateTimePrefixLength);
            if (next != null) {
                _s.MovePrev(DateTimePrefixLength);
                return String.Equals(next, DateTimePrefix, StringComparison.Ordinal);
            }

            return false;
        }

        private static bool IsNextElementObject(Nullable<Char> c) {
            return c == '{';
        }

        private static bool IsNextElementString(Nullable<Char> c) {
            return c == '"' || c == '\'';
        }
    }
}