aboutsummaryrefslogtreecommitdiff
path: root/dep/CascLib/src/CascFiles.cpp
blob: d17d1bc02049aaecb7b66d56278453c8620f8e48 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
/*****************************************************************************/
/* CascFiles.cpp                          Copyright (c) Ladislav Zezula 2014 */
/*---------------------------------------------------------------------------*/
/* Various text file parsers                                                 */
/*---------------------------------------------------------------------------*/
/*   Date    Ver   Who  Comment                                              */
/* --------  ----  ---  -------                                              */
/* 29.04.14  1.00  Lad  The first version of CascBuildCfg.cpp                */
/* 30.10.15  1.00  Lad  Renamed to CascFiles.cpp                             */
/*****************************************************************************/

#define __CASCLIB_SELF__
#include "CascLib.h"
#include "CascCommon.h"

//-----------------------------------------------------------------------------
// Local functions

typedef int (*PARSEINFOFILE)(TCascStorage * hs, void * pvListFile);

//-----------------------------------------------------------------------------
// Local structures

struct TBuildFileInfo
{
    const TCHAR * szFileName;
    CBLD_TYPE BuildFileType;
};

struct TGameIdString
{
    const char * szGameInfo;
    size_t cchGameInfo;
    DWORD dwGameInfo;
};

static const TBuildFileInfo BuildTypes[] =
{
    {_T(".build.info"), CascBuildInfo},             // Since HOTS build 30027, the game uses .build.info file for storage info
    {_T(".build.db"),   CascBuildDb},               // Older CASC storages
    {NULL, CascBuildNone}
};

static const TCHAR * DataDirs[] =
{
    _T("SC2Data"),                                  // Starcraft II (Legacy of the Void) build 38749
    _T("Data\\Casc"),                               // Overwatch
    _T("Data"),                                     // World of Warcraft, Diablo
    _T("HeroesData"),                               // Heroes of the Storm
    _T("BNTData"),                                  // Heroes of the Storm, until build 30414
    NULL,
};

static const TGameIdString GameIds[] =
{
    {"Hero",       0x04, CASC_GAME_HOTS},           // Alpha build of Heroes of the Storm
    {"WoW",        0x03, CASC_GAME_WOW6},           // Alpha build of World of Warcraft - Warlords of Draenor
    {"Diablo3",    0x07, CASC_GAME_DIABLO3},        // Diablo III BETA 2.2.0
    {"Prometheus", 0x0A, CASC_GAME_OVERWATCH},      // Overwatch BETA since build 24919
    {"SC2",        0x03, CASC_GAME_STARCRAFT2},     // Starcraft II - Legacy of the Void
    {NULL, 0, 0},
};

//-----------------------------------------------------------------------------
// Local functions

static bool inline IsValueSeparator(const char * szVarValue)
{
    return ((0 <= szVarValue[0] && szVarValue[0] <= 0x20) || (szVarValue[0] == '|'));
}

static bool IsCharDigit(BYTE OneByte)
{
    return ('0' <= OneByte && OneByte <= '9');
}

static DWORD GetLocaleMask(const char * szTag)
{
    if(!strcmp(szTag, "enUS"))
        return CASC_LOCALE_ENUS;

    if(!strcmp(szTag, "koKR"))
        return CASC_LOCALE_KOKR;

    if(!strcmp(szTag, "frFR"))
        return CASC_LOCALE_FRFR;

    if(!strcmp(szTag, "deDE"))
        return CASC_LOCALE_DEDE;

    if(!strcmp(szTag, "zhCN"))
        return CASC_LOCALE_ZHCN;

    if(!strcmp(szTag, "esES"))
        return CASC_LOCALE_ESES;

    if(!strcmp(szTag, "zhTW"))
        return CASC_LOCALE_ZHTW;

    if(!strcmp(szTag, "enGB"))
        return CASC_LOCALE_ENGB;

    if(!strcmp(szTag, "enCN"))
        return CASC_LOCALE_ENCN;

    if(!strcmp(szTag, "enTW"))
        return CASC_LOCALE_ENTW;

    if(!strcmp(szTag, "esMX"))
        return CASC_LOCALE_ESMX;

    if(!strcmp(szTag, "ruRU"))
        return CASC_LOCALE_RURU;

    if(!strcmp(szTag, "ptBR"))
        return CASC_LOCALE_PTBR;

    if(!strcmp(szTag, "itIT"))
        return CASC_LOCALE_ITIT;

    if(!strcmp(szTag, "ptPT"))
        return CASC_LOCALE_PTPT;

    return 0;
}

static bool IsInfoVariable(const char * szLineBegin, const char * szLineEnd, const char * szVarName, const char * szVarType)
{
    size_t nLength;

    // Check the variable name
    nLength = strlen(szVarName);
    if((size_t)(szLineEnd - szLineBegin) > nLength)
    {
        // Check the variable name
        if(!_strnicmp(szLineBegin, szVarName, nLength))
        {
            // Skip variable name and the exclamation mark
            szLineBegin += nLength;
            if(szLineBegin < szLineEnd && szLineBegin[0] == '!')
            {
                // Skip the exclamation mark
                szLineBegin++;

                // Check the variable type
                nLength = strlen(szVarType);
                if((size_t)(szLineEnd - szLineBegin) > nLength)
                {
                    // Check the variable name
                    if(!_strnicmp(szLineBegin, szVarType, nLength))
                    {
                        // Skip variable type and the doublecolon
                        szLineBegin += nLength;
                        return (szLineBegin < szLineEnd && szLineBegin[0] == ':');
                    }
                }
            }
        }
    }

    return false;
}

static const char * SkipInfoVariable(const char * szLineBegin, const char * szLineEnd)
{
    while(szLineBegin < szLineEnd)
    {
        if(szLineBegin[0] == '|')
            return szLineBegin + 1;

        szLineBegin++;
    }

    return NULL;
}

static TCHAR * CheckForIndexDirectory(TCascStorage * hs, const TCHAR * szSubDir)
{
    TCHAR * szIndexPath;

    // Cpmbine the index path
    szIndexPath = CombinePath(hs->szDataPath, szSubDir);
    if(DirectoryExists(szIndexPath))
    {
        hs->szIndexPath = szIndexPath;
        return hs->szIndexPath;
    }

    CASC_FREE(szIndexPath);
    return NULL;
}

TCHAR * AppendBlobText(TCHAR * szBuffer, LPBYTE pbData, DWORD cbData, TCHAR chSeparator)
{
    // Put the separator, if any
    if(chSeparator != 0)
        *szBuffer++ = chSeparator;

    // Copy the blob data as text
    for(DWORD i = 0; i < cbData; i++)
    {
        *szBuffer++ = IntToHexChar[pbData[0] >> 0x04];
        *szBuffer++ = IntToHexChar[pbData[0] & 0x0F];
        pbData++;
    }

    // Terminate the string
    *szBuffer = 0;

    // Return new buffer position
    return szBuffer;
}

static const char * CheckLineVariable(const char * szLineBegin, const char * szLineEnd, const char * szVarName)
{
    size_t nLineLength = (size_t)(szLineEnd - szLineBegin);
    size_t nNameLength = strlen(szVarName);

    // If the line longer than the variable name?
    if(nLineLength > nNameLength)
    {
        if(!_strnicmp((const char *)szLineBegin, szVarName, nNameLength))
        {
            // Skip the variable name
            szLineBegin += nNameLength;

            // Skip the separator(s)
            while(szLineBegin < szLineEnd && IsValueSeparator(szLineBegin))
                szLineBegin++;

            // Check if there is "="
            if(szLineBegin >= szLineEnd || szLineBegin[0] != '=')
                return NULL;
            szLineBegin++;

            // Skip the separator(s)
            while(szLineBegin < szLineEnd && IsValueSeparator(szLineBegin))
                szLineBegin++;

            // Check if there is "="
            if(szLineBegin >= szLineEnd)
                return NULL;

            // Return the begin of the variable
            return szLineBegin;
        }
    }

    return NULL;
}

static int LoadInfoVariable(PQUERY_KEY pVarBlob, const char * szLineBegin, const char * szLineEnd, bool bHexaValue)
{
    const char * szLinePtr = szLineBegin;

    // Sanity checks
    assert(pVarBlob->pbData == NULL);
    assert(pVarBlob->cbData == 0);

    // Check length of the variable
    while(szLinePtr < szLineEnd && szLinePtr[0] != '|')
        szLinePtr++;

    // Allocate space for the blob
    if(bHexaValue)
    {
        // Initialize the blob
        pVarBlob->pbData = CASC_ALLOC(BYTE, (szLinePtr - szLineBegin) / 2);
        pVarBlob->cbData = (DWORD)((szLinePtr - szLineBegin) / 2);
        return ConvertStringToBinary(szLineBegin, (size_t)(szLinePtr - szLineBegin), pVarBlob->pbData);
    }

    // Initialize the blob
    pVarBlob->pbData = CASC_ALLOC(BYTE, (szLinePtr - szLineBegin) + 1);
    pVarBlob->cbData = (DWORD)(szLinePtr - szLineBegin);

    // Check for success
    if(pVarBlob->pbData == NULL)
        return ERROR_NOT_ENOUGH_MEMORY;

    // Copy the string
    memcpy(pVarBlob->pbData, szLineBegin, pVarBlob->cbData);
    pVarBlob->pbData[pVarBlob->cbData] = 0;
    return ERROR_SUCCESS;
}

static void AppendConfigFilePath(TCHAR * szFileName, PQUERY_KEY pFileKey)
{
    size_t nLength = _tcslen(szFileName);

    // If there is no slash, append if
    if(nLength > 0 && szFileName[nLength - 1] != '\\' && szFileName[nLength - 1] != '/')
        szFileName[nLength++] = _T('/');

    // Get to the end of the file name
    szFileName = szFileName + nLength;

    // Append the "config" directory
    _tcscpy(szFileName, _T("config"));
    szFileName += 6;

    // Append the first level directory
    szFileName = AppendBlobText(szFileName, pFileKey->pbData, 1, _T('/'));
    szFileName = AppendBlobText(szFileName, pFileKey->pbData + 1, 1, _T('/'));
    szFileName = AppendBlobText(szFileName, pFileKey->pbData, pFileKey->cbData, _T('/'));
}

static DWORD GetBlobCount(const char * szLineBegin, const char * szLineEnd)
{
    DWORD dwBlobCount = 0;

    // Until we find an end of the line
    while(szLineBegin < szLineEnd)
    {
        // Skip the blob
        while(szLineBegin < szLineEnd && IsValueSeparator(szLineBegin) == false)
            szLineBegin++;

        // Increment the number of blobs
        dwBlobCount++;

        // Skip the separator
        while(szLineBegin < szLineEnd && IsValueSeparator(szLineBegin))
            szLineBegin++;
    }

    return dwBlobCount;
}

static int LoadBlobArray(
    PQUERY_KEY pBlob,
    const char * szLineBegin,
    const char * szLineEnd,
    DWORD dwMaxBlobs)
{
    LPBYTE pbBufferEnd = pBlob->pbData + pBlob->cbData;
    LPBYTE pbBuffer = pBlob->pbData;
    int nError = ERROR_SUCCESS;

    // Sanity check
    assert(pBlob->pbData != NULL);
    assert(pBlob->cbData != 0);

    // Until we find an end of the line
    while(szLineBegin < szLineEnd && dwMaxBlobs > 0)
    {
        const char * szBlobEnd = szLineBegin;

        // Find the end of the text blob
        while(szBlobEnd < szLineEnd && IsValueSeparator(szBlobEnd) == false)
            szBlobEnd++;

        // Verify the length of the found blob
        if((szBlobEnd - szLineBegin) != MD5_STRING_SIZE)
            return ERROR_BAD_FORMAT;

        // Verify if there is enough space in the buffer
        if((pbBufferEnd - pbBuffer) < MD5_HASH_SIZE)
            return ERROR_NOT_ENOUGH_MEMORY;

        // Perform the conversion
        nError = ConvertStringToBinary(szLineBegin, MD5_STRING_SIZE, pbBuffer);
        if(nError != ERROR_SUCCESS)
            return nError;

        // Move pointers
        pbBuffer += MD5_HASH_SIZE;
        dwMaxBlobs--;

        // Skip the separator
        while(szBlobEnd < szLineEnd && IsValueSeparator(szBlobEnd))
            szBlobEnd++;
        szLineBegin = szBlobEnd;
    }

    return nError;
}

static int LoadMultipleBlobs(PQUERY_KEY pBlob, const char * szLineBegin, const char * szLineEnd, DWORD dwBlobCount)
{
    size_t nLength = (szLineEnd - szLineBegin);

    // We expect each blob to have length of the encoding key and one space between
    if(nLength > (dwBlobCount * MD5_STRING_SIZE) + ((dwBlobCount - 1) * sizeof(char)))
        return ERROR_INVALID_PARAMETER;

    // Allocate the blob buffer
    pBlob->pbData = CASC_ALLOC(BYTE, dwBlobCount * MD5_HASH_SIZE);
    if(pBlob->pbData == NULL)
        return ERROR_NOT_ENOUGH_MEMORY;

    // Set the buffer size and load the blob array
    pBlob->cbData = dwBlobCount * MD5_HASH_SIZE;
    return LoadBlobArray(pBlob, szLineBegin, szLineEnd, dwBlobCount);
}

static int LoadMultipleBlobs(PQUERY_KEY pBlob, const char * szLineBegin, const char * szLineEnd)
{
    return LoadMultipleBlobs(pBlob, szLineBegin, szLineEnd, GetBlobCount(szLineBegin, szLineEnd));
}

static int LoadSingleBlob(PQUERY_KEY pBlob, const char * szLineBegin, const char * szLineEnd)
{
    return LoadMultipleBlobs(pBlob, szLineBegin, szLineEnd, 1);
}

static int GetGameType(TCascStorage * hs, const char * szVarBegin, const char * szLineEnd)
{
    // Go through all games that we support
    for(size_t i = 0; GameIds[i].szGameInfo != NULL; i++)
    {
        // Check the length of the variable
        if((size_t)(szLineEnd - szVarBegin) == GameIds[i].cchGameInfo)
        {
            // Check the string
            if(!_strnicmp(szVarBegin, GameIds[i].szGameInfo, GameIds[i].cchGameInfo))
            {
                hs->dwGameInfo = GameIds[i].dwGameInfo;
                return ERROR_SUCCESS;
            }
        }
    }

    // Unknown/unsupported game
    assert(false);
    return ERROR_BAD_FORMAT;
}

// "B29049"
// "WOW-18125patch6.0.1"
// "30013_Win32_2_2_0_Ptr_ptr"
// "prometheus-0_8_0_0-24919"
static int GetBuildNumber(TCascStorage * hs, const char * szVarBegin, const char * szLineEnd)
{
    DWORD dwBuildNumber = 0;

    // Skip all non-digit characters
    while(szVarBegin < szLineEnd)
    {
        // There must be at least three digits (build 99 anyone?)
        if(IsCharDigit(szVarBegin[0]) && IsCharDigit(szVarBegin[1]) && IsCharDigit(szVarBegin[2]))
        {
            // Convert the build number string to value
            while(szVarBegin < szLineEnd && IsCharDigit(szVarBegin[0]))
                dwBuildNumber = (dwBuildNumber * 10) + (*szVarBegin++ - '0');
            break;
        }

        // Move to the next
        szVarBegin++;
    }

    assert(dwBuildNumber != 0);
    hs->dwBuildNumber = dwBuildNumber;
    return (dwBuildNumber != 0) ? ERROR_SUCCESS : ERROR_BAD_FORMAT;
}

static int GetDefaultLocaleMask(TCascStorage * hs, PQUERY_KEY pTagsString)
{
    char * szTagEnd = (char *)pTagsString->pbData + pTagsString->cbData;
    char * szTagPtr = (char *)pTagsString->pbData;
    char * szNext;
    DWORD dwLocaleMask = 0;

    while(szTagPtr < szTagEnd)
    {
        // Get the next part
        szNext = strchr(szTagPtr, ' ');
        if(szNext != NULL)
            *szNext++ = 0;

        // Check whether the current tag is a language identifier
        dwLocaleMask = dwLocaleMask | GetLocaleMask(szTagPtr);

        // Get the next part
        if(szNext == NULL)
            break;

        // Skip spaces
        while(szNext < szTagEnd && szNext[0] == ' ')
            szNext++;
        szTagPtr = szNext;
    }

    hs->dwDefaultLocale = dwLocaleMask;
    return ERROR_SUCCESS;
}

static void * FetchAndVerifyConfigFile(TCascStorage * hs, PQUERY_KEY pFileKey)
{
    TCHAR * szFileName;
    void * pvListFile = NULL;

    // Construct the local file name
    szFileName = CascNewStr(hs->szDataPath, 8 + 3 + 3 + 32);
    if(szFileName != NULL)
    {
        // Add the part where the config file path is
        AppendConfigFilePath(szFileName, pFileKey);

        // Load and verify the external listfile
        pvListFile = ListFile_OpenExternal(szFileName);
        if(pvListFile != NULL)
        {
            if(!ListFile_VerifyMD5(pvListFile, pFileKey->pbData))
            {
                ListFile_Free(pvListFile);
                pvListFile = NULL;
            }
        }

        // Free the file name
        CASC_FREE(szFileName);
    }

    return pvListFile;
}

static int ParseFile_BuildInfo(TCascStorage * hs, void * pvListFile)
{
    QUERY_KEY Active = {NULL, 0};
    QUERY_KEY TagString = {NULL, 0};
    QUERY_KEY CdnHost = {NULL, 0};
    QUERY_KEY CdnPath = {NULL, 0};
    const char * szLinePtr1;
    const char * szLineEnd1;
    const char * szLinePtr2;
    const char * szLineEnd2;
    size_t nLength1;
    size_t nLength2;
    int nError = ERROR_BAD_FORMAT;

    // Extract the first line, cotaining the headers
    nLength1 = ListFile_GetNextLine(pvListFile, &szLinePtr1, &szLineEnd1);
    if(nLength1 == 0)
        return ERROR_BAD_FORMAT;

    // Now parse the second and the next lines. We are looking for line
    // with "Active" set to 1
    for(;;)
    {
        // Read the next line
        nLength2 = ListFile_GetNextLine(pvListFile, &szLinePtr2, &szLineEnd2);
        if(nLength2 == 0)
            break;

        // Parse all variables
        while(szLinePtr1 < szLineEnd1)
        {
            // Check for variables we need
            if(IsInfoVariable(szLinePtr1, szLineEnd1, "Active", "DEC"))
                LoadInfoVariable(&Active, szLinePtr2, szLineEnd2, false);
            if(IsInfoVariable(szLinePtr1, szLineEnd1, "Build Key", "HEX"))
                LoadInfoVariable(&hs->CdnBuildKey, szLinePtr2, szLineEnd2, true);
            if(IsInfoVariable(szLinePtr1, szLineEnd1, "CDN Key", "HEX"))
                LoadInfoVariable(&hs->CdnConfigKey, szLinePtr2, szLineEnd2, true);
            if(IsInfoVariable(szLinePtr1, szLineEnd1, "CDN Hosts", "STRING"))
                LoadInfoVariable(&CdnHost, szLinePtr2, szLineEnd2, false);
            if(IsInfoVariable(szLinePtr1, szLineEnd1, "CDN Path", "STRING"))
                LoadInfoVariable(&CdnPath, szLinePtr2, szLineEnd2, false);
            if(IsInfoVariable(szLinePtr1, szLineEnd1, "Tags", "STRING"))
                LoadInfoVariable(&TagString, szLinePtr2, szLineEnd2, false);

            // Move both line pointers
            szLinePtr1 = SkipInfoVariable(szLinePtr1, szLineEnd1);
            if(szLinePtr1 == NULL)
                break;

            szLinePtr2 = SkipInfoVariable(szLinePtr2, szLineEnd2);
            if(szLinePtr2 == NULL)
                break;
        }

        // Stop parsing if found active config
        if(Active.pbData != NULL && *Active.pbData == '1')
            break;

        // Free the blobs
        FreeCascBlob(&Active);
        FreeCascBlob(&hs->CdnBuildKey);
        FreeCascBlob(&hs->CdnConfigKey);
        FreeCascBlob(&CdnHost);
        FreeCascBlob(&CdnPath);
        FreeCascBlob(&TagString);

        // Rewind column names pointer back to start of line
        szLinePtr1 = szLineEnd1 - nLength1;
    }

    // All four must be present
    if(hs->CdnBuildKey.pbData != NULL &&
       hs->CdnConfigKey.pbData != NULL &&
       CdnHost.pbData != NULL &&
       CdnPath.pbData != NULL)
    {
        // Merge the CDN host and CDN path
        hs->szUrlPath = CASC_ALLOC(TCHAR, CdnHost.cbData + CdnPath.cbData + 1);
        if(hs->szUrlPath != NULL)
        {
            CopyString(hs->szUrlPath, (char *)CdnHost.pbData, CdnHost.cbData);
            CopyString(hs->szUrlPath + CdnHost.cbData, (char *)CdnPath.pbData, CdnPath.cbData);
            nError = ERROR_SUCCESS;
        }
    }

    // If we found tags, we can extract language build from it
    if(TagString.pbData != NULL)
        GetDefaultLocaleMask(hs, &TagString);

    FreeCascBlob(&CdnHost);
    FreeCascBlob(&CdnPath);
    FreeCascBlob(&TagString);
    FreeCascBlob(&Active);
    return nError;
}

static int ParseFile_BuildDb(TCascStorage * hs, void * pvListFile)
{
    const char * szLinePtr;
    const char * szLineEnd;
    char szOneLine[0x200];
    size_t nLength;
    int nError;

    // Load the single line from the text file
    nLength = ListFile_GetNextLine(pvListFile, szOneLine, _maxchars(szOneLine));
    if(nLength == 0)
        return ERROR_BAD_FORMAT;

    // Set the line range
    szLinePtr = szOneLine;
    szLineEnd = szOneLine + nLength;

    // Extract the CDN build key
    nError = LoadInfoVariable(&hs->CdnBuildKey, szLinePtr, szLineEnd, true);
    if(nError == ERROR_SUCCESS)
    {
        // Skip the variable
        szLinePtr = SkipInfoVariable(szLinePtr, szLineEnd);

        // Load the CDN config hash
        nError = LoadInfoVariable(&hs->CdnConfigKey, szLinePtr, szLineEnd, true);
        if(nError == ERROR_SUCCESS)
        {
            // Skip the variable
            szLinePtr = SkipInfoVariable(szLinePtr, szLineEnd);

            // Skip the Locale/OS/code variable
            szLinePtr = SkipInfoVariable(szLinePtr, szLineEnd);

            // Load the URL
            hs->szUrlPath = CascNewStrFromAnsi(szLinePtr, szLineEnd);
            if(hs->szUrlPath == NULL)
                nError = ERROR_NOT_ENOUGH_MEMORY;
        }
    }

    // Verify all variables
    if(hs->CdnBuildKey.pbData == NULL || hs->CdnConfigKey.pbData == NULL || hs->szUrlPath == NULL)
        nError = ERROR_BAD_FORMAT;
    return nError;
}

static int LoadCdnConfigFile(TCascStorage * hs, void * pvListFile)
{
    const char * szLineBegin;
    const char * szVarBegin;
    const char * szLineEnd;
    int nError = ERROR_SUCCESS;

    // Keep parsing the listfile while there is something in there
    for(;;)
    {
        // Get the next line
        if(!ListFile_GetNextLine(pvListFile, &szLineBegin, &szLineEnd))
            break;

        // Archive group
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "archive-group");
        if(szVarBegin != NULL)
        {
            nError = LoadSingleBlob(&hs->ArchivesGroup, szVarBegin, szLineEnd);
            continue;
        }

        // Archives
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "archives");
        if(szVarBegin != NULL)
        {
            nError = LoadMultipleBlobs(&hs->ArchivesKey, szVarBegin, szLineEnd);
            continue;
        }

        // Patch archive group
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "patch-archive-group");
        if(szVarBegin != NULL)
        {
            LoadSingleBlob(&hs->PatchArchivesGroup, szVarBegin, szLineEnd);
            continue;
        }

        // Patch archives
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "patch-archives");
        if(szVarBegin != NULL)
        {
            nError = LoadMultipleBlobs(&hs->PatchArchivesKey, szVarBegin, szLineEnd);
            continue;
        }
    }

    // Check if all required fields are present
    if(hs->ArchivesKey.pbData == NULL || hs->ArchivesKey.cbData == 0)
        return ERROR_BAD_FORMAT;

    return nError;
}

static int LoadCdnBuildFile(TCascStorage * hs, void * pvListFile)
{
    const char * szLineBegin;
    const char * szVarBegin;
    const char * szLineEnd = NULL;
    int nError = ERROR_SUCCESS;

    for(;;)
    {
        // Get the next line
        if(!ListFile_GetNextLine(pvListFile, &szLineBegin, &szLineEnd))
            break;

        // Game name
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "build-product");
        if(szVarBegin != NULL)
        {
            GetGameType(hs, szVarBegin, szLineEnd);
            continue;
        }

        // Game build number
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "build-name");
        if(szVarBegin != NULL)
        {
            GetBuildNumber(hs, szVarBegin, szLineEnd);
            continue;
        }

        // Root
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "root");
        if(szVarBegin != NULL)
        {
            LoadSingleBlob(&hs->RootKey, szVarBegin, szLineEnd);
            continue;
        }

        // Patch
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "patch");
        if(szVarBegin != NULL)
        {
            LoadSingleBlob(&hs->PatchKey, szVarBegin, szLineEnd);
            continue;
        }

        // Download
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "download");
        if(szVarBegin != NULL)
        {
            LoadSingleBlob(&hs->DownloadKey, szVarBegin, szLineEnd);
            continue;
        }

        // Install
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "install");
        if(szVarBegin != NULL)
        {
            LoadSingleBlob(&hs->InstallKey, szVarBegin, szLineEnd);
            continue;
        }

        // Encoding keys
        szVarBegin = CheckLineVariable(szLineBegin, szLineEnd, "encoding");
        if(szVarBegin != NULL)
        {
            nError = LoadMultipleBlobs(&hs->EncodingKey, szVarBegin, szLineEnd, 2);
            continue;
        }
    }

    // Check the encoding keys
    if(hs->EncodingKey.pbData == NULL || hs->EncodingKey.cbData != MD5_HASH_SIZE * 2)
        return ERROR_BAD_FORMAT;
    return nError;
}

static int CheckDataDirectory(TCascStorage * hs, TCHAR * szDirectory)
{
    TCHAR * szDataPath;
    int nError = ERROR_FILE_NOT_FOUND;

    // Try all known subdirectories
    for(size_t i = 0; DataDirs[i] != NULL; i++)
    {
        // Create the eventual data path
        szDataPath = CombinePath(szDirectory, DataDirs[i]);
        if(szDataPath != NULL)
        {
            // Does that directory exist?
            if(DirectoryExists(szDataPath))
            {
                hs->szDataPath = szDataPath;
                return ERROR_SUCCESS;
            }

            // Free the data path
            CASC_FREE(szDataPath);
        }
    }

    return nError;
}


//-----------------------------------------------------------------------------
// Public functions

int LoadBuildInfo(TCascStorage * hs)
{
    PARSEINFOFILE PfnParseProc = NULL;
    void * pvListFile;
    int nError = ERROR_SUCCESS;

    switch(hs->BuildFileType)
    {
        case CascBuildInfo:
            PfnParseProc = ParseFile_BuildInfo;
            break;

        case CascBuildDb:
            PfnParseProc = ParseFile_BuildDb;
            break;

        default:
            nError = ERROR_NOT_SUPPORTED;
            break;
    }

    // Parse the appropriate build file
    if(nError == ERROR_SUCCESS)
    {
        pvListFile = ListFile_OpenExternal(hs->szBuildFile);
        if(pvListFile != NULL)
        {
            // Parse the info file
            nError = PfnParseProc(hs, pvListFile);
            ListFile_Free(pvListFile);
        }
        else
            nError = ERROR_FILE_NOT_FOUND;
    }

    // If the .build.info OR .build.db file has been loaded,
    // proceed with loading the CDN config file and CDN build file
    if(nError == ERROR_SUCCESS)
    {
        // Load the configuration file. Note that we don't
        // need it for anything, really, so we don't care if it fails
        pvListFile = FetchAndVerifyConfigFile(hs, &hs->CdnConfigKey);
        if(pvListFile != NULL)
        {
            nError = LoadCdnConfigFile(hs, pvListFile);
            ListFile_Free(pvListFile);
        }
    }

    // Load the build file
    if(nError == ERROR_SUCCESS)
    {
        pvListFile = FetchAndVerifyConfigFile(hs, &hs->CdnBuildKey);
        if(pvListFile != NULL)
        {
            nError = LoadCdnBuildFile(hs, pvListFile);
            ListFile_Free(pvListFile);
        }
        else
            nError = ERROR_FILE_NOT_FOUND;
    }

    // Fill the index directory
    if(nError == ERROR_SUCCESS)
    {
        // First, check for more common "data" subdirectory
        if((hs->szIndexPath = CheckForIndexDirectory(hs, _T("data"))) != NULL)
            return ERROR_SUCCESS;

        // Second, try the "darch" subdirectory (older builds of HOTS - Alpha)
        if((hs->szIndexPath = CheckForIndexDirectory(hs, _T("darch"))) != NULL)
            return ERROR_SUCCESS;

        nError = ERROR_FILE_NOT_FOUND;
    }

    return nError;
}

// Checks whether there is a ".build.info" or ".build.db".
// If yes, the function sets "szRootPath" and "szDataPath"
// in the storage structure and returns ERROR_SUCCESS
int CheckGameDirectory(TCascStorage * hs, TCHAR * szDirectory)
{
    TFileStream * pStream;
    TCHAR * szBuildFile;
    int nError = ERROR_FILE_NOT_FOUND;

    // Try to find any of the root files used in the history
    for(size_t i = 0; BuildTypes[i].szFileName != NULL; i++)
    {
        // Create the full name of the .agent.db file
        szBuildFile = CombinePath(szDirectory, BuildTypes[i].szFileName);
        if(szBuildFile != NULL)
        {
            // Attempt to open the file
            pStream = FileStream_OpenFile(szBuildFile, STREAM_FLAG_READ_ONLY);
            if(pStream != NULL)
            {
                // Free the stream
                FileStream_Close(pStream);

                // Check for the data directory
                nError = CheckDataDirectory(hs, szDirectory);
                if(nError == ERROR_SUCCESS)
                {
                    hs->szBuildFile = szBuildFile;
                    hs->BuildFileType = BuildTypes[i].BuildFileType;
                    return ERROR_SUCCESS;
                }
            }

            CASC_FREE(szBuildFile);
        }
    }

    return nError;
}

//-----------------------------------------------------------------------------
// Helpers for a config files that have multiple variables separated by "|"
// The line structure is (Overwatch 24919): "#MD5|CHUNK_ID|FILENAME|INSTALLPATH"
// The line structure is (Overwatch 27759): "#MD5|CHUNK_ID|PRIORITY|MPRIORITY|FILENAME|INSTALLPATH"
// The line has all preceding spaces removed

// Retrieves the index of a variable from the initial line
int GetRootVariableIndex(const char * szLinePtr, const char * szLineEnd, const char * szVariableName, int * PtrIndex)
{
    size_t nLength = strlen(szVariableName);
    int nIndex = 0;
    
    while(szLinePtr < szLineEnd)
    {
        // Check the variable there
        if(!_strnicmp(szLinePtr, szVariableName, nLength))
        {
            // Does the length match?
            if(szLinePtr[nLength] == '|' || szLinePtr[nLength] == '0')
            {
                PtrIndex[0] = nIndex;
                return ERROR_SUCCESS;
            }
        }

        // Get the next variable
        szLinePtr = SkipInfoVariable(szLinePtr, szLineEnd);
        if(szLinePtr == NULL)
            break;
        nIndex++;
    }

    return ERROR_BAD_FORMAT;
}

// Parses single line from Overwatch.
int ParseRootFileLine(const char * szLinePtr, const char * szLineEnd, int nFileNameIndex, PQUERY_KEY PtrEncodingKey, char * szFileName, size_t nMaxChars)
{
    int nIndex = 0;
    int nError;

    // Extract the MD5 (aka encoding key)
    if(szLinePtr[MD5_STRING_SIZE] != '|')
        return ERROR_BAD_FORMAT;

    // Convert the encoding key to binary
    PtrEncodingKey->cbData = MD5_HASH_SIZE;
    nError = ConvertStringToBinary(szLinePtr, MD5_STRING_SIZE, PtrEncodingKey->pbData);
    if(nError != ERROR_SUCCESS)
        return nError;

    // Skip the variable
    szLinePtr += MD5_STRING_SIZE + 1;
    nIndex = 1;

    // Skip the variables until we find the file name
    while(szLinePtr < szLineEnd && nIndex < nFileNameIndex)
    {
        if(szLinePtr[0] == '|')
            nIndex++;
        szLinePtr++;
    }

    // Extract the file name
    while(szLinePtr < szLineEnd && szLinePtr[0] != '|' && nMaxChars > 1)
    {
        *szFileName++ = *szLinePtr++;
        nMaxChars--;
    }

    *szFileName = 0;
    return ERROR_SUCCESS;
}