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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
|
/** @file
The implementation for the 'http' Shell command.
Copyright (c) 2015, ARM Ltd. All rights reserved.<BR>
Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved. <BR>
(C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
Copyright (c) 2020, Broadcom. All rights reserved. <BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "Http.h"
#define IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH 32
//
// Constant strings and definitions related to the message
// indicating the amount of progress in the dowloading of a HTTP file.
//
//
// Number of steps in the progression slider.
//
#define HTTP_PROGRESS_SLIDER_STEPS \
((sizeof (HTTP_PROGR_FRAME) / sizeof (CHAR16)) - 3)
//
// Size in number of characters plus one (final zero) of the message to
// indicate the progress of an HTTP download. The format is "[(progress slider:
// 40 characters)] (nb of KBytes downloaded so far: 7 characters) Kb". There
// are thus the number of characters in HTTP_PROGR_FRAME[] plus 11 characters
// (2 // spaces, "Kb" and seven characters for the number of KBytes).
//
#define HTTP_PROGRESS_MESSAGE_SIZE \
((sizeof (HTTP_PROGR_FRAME) / sizeof (CHAR16)) + 12)
//
// Buffer size. Note that larger buffer does not mean better speed.
//
#define DEFAULT_BUF_SIZE SIZE_32KB
#define MAX_BUF_SIZE SIZE_4MB
#define MIN_PARAM_COUNT 2
#define MAX_PARAM_COUNT 4
#define NEED_REDIRECTION(Code) \
(((Code >= HTTP_STATUS_300_MULTIPLE_CHOICES) \
&& (Code <= HTTP_STATUS_307_TEMPORARY_REDIRECT)) \
|| (Code == HTTP_STATUS_308_PERMANENT_REDIRECT))
#define CLOSE_HTTP_HANDLE(ControllerHandle, HttpChildHandle) \
do { \
if (HttpChildHandle) { \
CloseProtocolAndDestroyServiceChild ( \
ControllerHandle, \
&gEfiHttpServiceBindingProtocolGuid, \
&gEfiHttpProtocolGuid, \
HttpChildHandle \
); \
HttpChildHandle = NULL; \
} \
} while (0)
typedef enum {
HdrHost,
HdrConn,
HdrAgent,
HdrMax
} HDR_TYPE;
#define USER_AGENT_HDR "Mozilla/5.0 (EDK2; Linux) Gecko/20100101 Firefox/79.0"
#define TIMER_MAX_TIMEOUT_S 10
//
// File name to use when Uri ends with "/".
//
#define DEFAULT_HTML_FILE L"index.html"
#define DEFAULT_HTTP_PROTO L"http"
//
// String to delete the HTTP progress message to be able to update it :
// (HTTP_PROGRESS_MESSAGE_SIZE-1) '\b'.
//
#define HTTP_PROGRESS_DEL \
L"\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\
\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
#define HTTP_KB L"\b\b\b\b\b\b\b\b\b\b"
//
// Frame for the progression slider.
//
#define HTTP_PROGR_FRAME L"[ ]"
//
// Improve readability by using these macros.
//
#define PRINT_HII(token, ...) \
ShellPrintHiiEx (\
-1, -1, NULL, token, mHttpHiiHandle, __VA_ARGS__)
#define PRINT_HII_APP(token, value) \
PRINT_HII (token, HTTP_APP_NAME, value)
//
// TimeBaseLib.h constants.
// These will be removed once the library gets fixed.
//
//
// Define EPOCH (1970-JANUARY-01) in the Julian Date representation.
//
#define EPOCH_JULIAN_DATE 2440588
//
// Seconds per unit.
//
#define SEC_PER_MIN ((UINTN) 60)
#define SEC_PER_HOUR ((UINTN) 3600)
#define SEC_PER_DAY ((UINTN) 86400)
//
// String descriptions for server errors.
//
STATIC CONST CHAR16 *ErrStatusDesc[] =
{
L"400 Bad Request",
L"401 Unauthorized",
L"402 Payment required",
L"403 Forbidden",
L"404 Not Found",
L"405 Method not allowed",
L"406 Not acceptable",
L"407 Proxy authentication required",
L"408 Request time out",
L"409 Conflict",
L"410 Gone",
L"411 Length required",
L"412 Precondition failed",
L"413 Request entity too large",
L"414 Request URI to large",
L"415 Unsupported media type",
L"416 Requested range not satisfied",
L"417 Expectation failed",
L"500 Internal server error",
L"501 Not implemented",
L"502 Bad gateway",
L"503 Service unavailable",
L"504 Gateway timeout",
L"505 HTTP version not supported"
};
STATIC CONST SHELL_PARAM_ITEM ParamList[] = {
{ L"-i", TypeValue },
{ L"-k", TypeFlag },
{ L"-l", TypeValue },
{ L"-m", TypeFlag },
{ L"-s", TypeValue },
{ L"-t", TypeValue },
{ NULL, TypeMax }
};
//
// Local File Handle.
//
STATIC SHELL_FILE_HANDLE mFileHandle = NULL;
//
// Path of the local file, Unicode encoded.
//
STATIC CONST CHAR16 *mLocalFilePath;
STATIC BOOLEAN gRequestCallbackComplete = FALSE;
STATIC BOOLEAN gResponseCallbackComplete = FALSE;
STATIC BOOLEAN gHttpError;
EFI_HII_HANDLE mHttpHiiHandle;
//
// Functions declarations.
//
/**
Check and convert the UINT16 option values of the 'http' command.
@param[in] ValueStr Value as an Unicode encoded string.
@param[out] Value UINT16 value.
@retval TRUE The value was returned.
@retval FALSE A parsing error occured.
**/
STATIC
BOOLEAN
StringToUint16 (
IN CONST CHAR16 *ValueStr,
OUT UINT16 *Value
);
/**
Get the name of the NIC.
@param[in] ControllerHandle The network physical device handle.
@param[in] NicNumber The network physical device number.
@param[out] NicName Address where to store the NIC name.
The memory area has to be at least
IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH
double byte wide.
@retval EFI_SUCCESS The name of the NIC was returned.
@retval Others The creation of the child for the Managed
Network Service failed or the opening of
the Managed Network Protocol failed or
the operational parameters for the
Managed Network Protocol could not be
read.
**/
STATIC
EFI_STATUS
GetNicName (
IN EFI_HANDLE ControllerHandle,
IN UINTN NicNumber,
OUT CHAR16 *NicName
);
/**
Create a child for the service identified by its service binding protocol GUID
and get from the child the interface of the protocol identified by its GUID.
@param[in] ControllerHandle Controller handle.
@param[in] ServiceBindingProtocolGuid Service binding protocol GUID of the
service to be created.
@param[in] ProtocolGuid GUID of the protocol to be open.
@param[out] ChildHandle Address where the handler of the
created child is returned. NULL is
returned in case of error.
@param[out] Interface Address where a pointer to the
protocol interface is returned in
case of success.
@retval EFI_SUCCESS The child was created and the protocol opened.
@retval Others Either the creation of the child or the opening
of the protocol failed.
**/
STATIC
EFI_STATUS
CreateServiceChildAndOpenProtocol (
IN EFI_HANDLE ControllerHandle,
IN EFI_GUID *ServiceBindingProtocolGuid,
IN EFI_GUID *ProtocolGuid,
OUT EFI_HANDLE *ChildHandle,
OUT VOID **Interface
);
/**
Close the protocol identified by its GUID on the child handle of the service
identified by its service binding protocol GUID, then destroy the child
handle.
@param[in] ControllerHandle Controller handle.
@param[in] ServiceBindingProtocolGuid Service binding protocol GUID of the
service to be destroyed.
@param[in] ProtocolGuid GUID of the protocol to be closed.
@param[in] ChildHandle Handle of the child to be destroyed.
**/
STATIC
VOID
CloseProtocolAndDestroyServiceChild (
IN EFI_HANDLE ControllerHandle,
IN EFI_GUID *ServiceBindingProtocolGuid,
IN EFI_GUID *ProtocolGuid,
IN EFI_HANDLE ChildHandle
);
/**
Worker function that download the data of a file from an HTTP server given
the path of the file and its size.
@param[in] Context A pointer to the download context.
@retval EFI_SUCCESS The file was downloaded.
@retval EFI_OUT_OF_RESOURCES A memory allocation failed.
@retval Others The downloading of the file
from the server failed.
**/
STATIC
EFI_STATUS
DownloadFile (
IN HTTP_DOWNLOAD_CONTEXT *Context,
IN EFI_HANDLE ControllerHandle,
IN CHAR16 *NicName
);
/**
Cleans off leading and trailing spaces and tabs.
@param[in] String pointer to the string to trim them off.
@retval EFI_SUCCESS No errors.
@retval EFI_INVALID_PARAMETER String pointer is NULL.
**/
STATIC
EFI_STATUS
TrimSpaces (
IN CHAR16 *String
)
{
CHAR16 *Str;
UINTN Len;
ASSERT (String != NULL);
if (String == NULL) {
return EFI_INVALID_PARAMETER;
}
Str = String;
//
// Remove any whitespace at the beginning of the Str.
//
while (*Str == L' ' || *Str == L'\t') {
Str++;
}
//
// Remove any whitespace at the end of the Str.
//
do {
Len = StrLen (Str);
if (!Len || ((Str[Len - 1] != L' ') && (Str[Len - 1] != '\t'))) {
break;
}
Str[Len - 1] = CHAR_NULL;
} while (Len);
CopyMem (String, Str, StrSize (Str));
return EFI_SUCCESS;
}
//
// Callbacks for request and response.
// We just acknowledge that operation has completed here.
//
/**
Callback to set the request completion flag.
@param[in] Event: The event.
@param[in] Context: pointer to Notification Context.
**/
STATIC
VOID
EFIAPI
RequestCallback (
IN EFI_EVENT Event,
IN VOID *Context
)
{
gRequestCallbackComplete = TRUE;
}
/**
Callback to set the response completion flag.
@param[in] Event: The event.
@param[in] Context: pointer to Notification Context.
**/
STATIC
VOID
EFIAPI
ResponseCallback (
IN EFI_EVENT Event,
IN VOID *Context
)
{
gResponseCallbackComplete = TRUE;
}
//
// Set of functions from TimeBaseLib.
// This will be removed once TimeBaseLib is enabled for ShellPkg.
//
/**
Calculate Epoch days.
@param[in] Time - a pointer to the EFI_TIME abstraction.
@retval Number of days elapsed since EPOCH_JULIAN_DAY.
**/
STATIC
UINTN
EfiGetEpochDays (
IN EFI_TIME *Time
)
{
UINTN a;
UINTN y;
UINTN m;
//
// Absolute Julian Date representation of the supplied Time.
//
UINTN JulianDate;
//
// Number of days elapsed since EPOCH_JULIAN_DAY.
//
UINTN EpochDays;
a = (14 - Time->Month) / 12;
y = Time->Year + 4800 - a;
m = Time->Month + (12 * a) - 3;
JulianDate = Time->Day + ((153 * m + 2) / 5) + (365 * y) + (y / 4) -
(y / 100) + (y / 400) - 32045;
ASSERT (JulianDate >= EPOCH_JULIAN_DATE);
EpochDays = JulianDate - EPOCH_JULIAN_DATE;
return EpochDays;
}
/**
Converts EFI_TIME to Epoch seconds
(elapsed since 1970 JANUARY 01, 00:00:00 UTC).
@param[in] Time: a pointer to EFI_TIME abstraction.
**/
STATIC
UINTN
EFIAPI
EfiTimeToEpoch (
IN EFI_TIME *Time
)
{
//
// Number of days elapsed since EPOCH_JULIAN_DAY.
//
UINTN EpochDays;
UINTN EpochSeconds;
EpochDays = EfiGetEpochDays (Time);
EpochSeconds = (EpochDays * SEC_PER_DAY) +
((UINTN)Time->Hour * SEC_PER_HOUR) +
(Time->Minute * SEC_PER_MIN) + Time->Second;
return EpochSeconds;
}
/**
Function for 'http' command.
@param[in] ImageHandle Handle to the Image (NULL if Internal).
@param[in] SystemTable Pointer to the System Table (NULL if Internal).
@retval SHELL_SUCCESS The 'http' command completed successfully.
@retval SHELL_ABORTED The Shell Library initialization failed.
@retval SHELL_INVALID_PARAMETER At least one of the command's arguments is
not valid.
@retval SHELL_OUT_OF_RESOURCES A memory allocation failed.
@retval SHELL_NOT_FOUND Network Interface Card not found.
@retval SHELL_UNSUPPORTED Command was valid, but the server returned
a status code indicating some error.
Examine the file requested for error body.
**/
SHELL_STATUS
RunHttp (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
LIST_ENTRY *CheckPackage;
UINTN ParamCount;
UINTN HandleCount;
UINTN NicNumber;
UINTN InitialSize;
UINTN ParamOffset;
UINTN StartSize;
CHAR16 *ProblemParam;
CHAR16 NicName[IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH];
CHAR16 *Walker1;
CHAR16 *VStr;
CONST CHAR16 *UserNicName;
CONST CHAR16 *ValueStr;
CONST CHAR16 *RemoteFilePath;
CONST CHAR16 *Walker;
EFI_HTTPv4_ACCESS_POINT IPv4Node;
EFI_HANDLE *Handles;
EFI_HANDLE ControllerHandle;
HTTP_DOWNLOAD_CONTEXT Context;
BOOLEAN NicFound;
ProblemParam = NULL;
RemoteFilePath = NULL;
NicFound = FALSE;
Handles = NULL;
//
// Initialize the Shell library (we must be in non-auto-init...).
//
ParamOffset = 0;
gHttpError = FALSE;
Status = ShellInitialize ();
if (EFI_ERROR (Status)) {
ASSERT_EFI_ERROR (Status);
return SHELL_ABORTED;
}
ZeroMem (&Context, sizeof (Context));
//
// Parse the command line.
//
Status = ShellCommandLineParse (
ParamList,
&CheckPackage,
&ProblemParam,
TRUE
);
if (EFI_ERROR (Status)) {
if ( (Status == EFI_VOLUME_CORRUPTED)
&& (ProblemParam != NULL))
{
PRINT_HII_APP (STRING_TOKEN (STR_GEN_PROBLEM), ProblemParam);
SHELL_FREE_NON_NULL (ProblemParam);
} else {
ASSERT (FALSE);
}
goto Error;
}
//
// Check the number of parameters.
//
Status = EFI_INVALID_PARAMETER;
ParamCount = ShellCommandLineGetCount (CheckPackage);
if (ParamCount > MAX_PARAM_COUNT) {
PRINT_HII_APP (STRING_TOKEN (STR_GEN_TOO_MANY), NULL);
goto Error;
}
if (ParamCount < MIN_PARAM_COUNT) {
PRINT_HII_APP (STRING_TOKEN (STR_GEN_TOO_FEW), NULL);
goto Error;
}
ZeroMem (&Context.HttpConfigData, sizeof (Context.HttpConfigData));
ZeroMem (&IPv4Node, sizeof (IPv4Node));
IPv4Node.UseDefaultAddress = TRUE;
Context.HttpConfigData.HttpVersion = HttpVersion11;
Context.HttpConfigData.AccessPoint.IPv4Node = &IPv4Node;
//
// Get the host address (not necessarily IPv4 format).
//
ValueStr = ShellCommandLineGetRawValue (CheckPackage, 1);
if (!ValueStr) {
PRINT_HII_APP (STRING_TOKEN (STR_GEN_PARAM_INV), ValueStr);
goto Error;
} else {
StartSize = 0;
TrimSpaces ((CHAR16 *)ValueStr);
if (!StrStr (ValueStr, L"://")) {
Context.ServerAddrAndProto = StrnCatGrow (
&Context.ServerAddrAndProto,
&StartSize,
DEFAULT_HTTP_PROTO,
StrLen (DEFAULT_HTTP_PROTO)
);
Context.ServerAddrAndProto = StrnCatGrow (
&Context.ServerAddrAndProto,
&StartSize,
L"://",
StrLen (L"://")
);
VStr = (CHAR16 *)ValueStr;
} else {
VStr = StrStr (ValueStr, L"://") + StrLen (L"://");
}
for (Walker1 = VStr; *Walker1; Walker1++) {
if (*Walker1 == L'/') {
break;
}
}
if (*Walker1 == L'/') {
ParamOffset = 1;
RemoteFilePath = Walker1;
}
Context.ServerAddrAndProto = StrnCatGrow (
&Context.ServerAddrAndProto,
&StartSize,
ValueStr,
StrLen (ValueStr) - StrLen (Walker1)
);
if (!Context.ServerAddrAndProto) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
}
if (!RemoteFilePath) {
RemoteFilePath = ShellCommandLineGetRawValue (CheckPackage, 2);
if (!RemoteFilePath) {
//
// If no path given, assume just "/".
//
RemoteFilePath = L"/";
}
}
TrimSpaces ((CHAR16 *)RemoteFilePath);
if (ParamCount == MAX_PARAM_COUNT - ParamOffset) {
mLocalFilePath = ShellCommandLineGetRawValue (
CheckPackage,
MAX_PARAM_COUNT - 1 - ParamOffset
);
} else {
Walker = RemoteFilePath + StrLen (RemoteFilePath);
while ((--Walker) >= RemoteFilePath) {
if ((*Walker == L'\\') ||
(*Walker == L'/'))
{
break;
}
}
mLocalFilePath = Walker + 1;
}
if (!StrLen (mLocalFilePath)) {
mLocalFilePath = DEFAULT_HTML_FILE;
}
InitialSize = 0;
Context.Uri = StrnCatGrow (
&Context.Uri,
&InitialSize,
RemoteFilePath,
StrLen (RemoteFilePath)
);
if (!Context.Uri) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
//
// Get the name of the Network Interface Card to be used if any.
//
UserNicName = ShellCommandLineGetValue (CheckPackage, L"-i");
ValueStr = ShellCommandLineGetValue (CheckPackage, L"-l");
if ( (ValueStr != NULL)
&& (!StringToUint16 (
ValueStr,
&Context.HttpConfigData.AccessPoint.IPv4Node->LocalPort
)
))
{
goto Error;
}
Context.BufferSize = DEFAULT_BUF_SIZE;
ValueStr = ShellCommandLineGetValue (CheckPackage, L"-s");
if (ValueStr != NULL) {
Context.BufferSize = ShellStrToUintn (ValueStr);
if (!Context.BufferSize || (Context.BufferSize > MAX_BUF_SIZE)) {
PRINT_HII_APP (STRING_TOKEN (STR_GEN_PARAM_INV), ValueStr);
goto Error;
}
}
ValueStr = ShellCommandLineGetValue (CheckPackage, L"-t");
if (ValueStr != NULL) {
Context.HttpConfigData.TimeOutMillisec = (UINT32)ShellStrToUintn (ValueStr);
}
//
// Locate all HTTP Service Binding protocols.
//
Status = gBS->LocateHandleBuffer (
ByProtocol,
&gEfiManagedNetworkServiceBindingProtocolGuid,
NULL,
&HandleCount,
&Handles
);
if (EFI_ERROR (Status) || (HandleCount == 0)) {
PRINT_HII (STRING_TOKEN (STR_HTTP_ERR_NO_NIC), NULL);
if (!EFI_ERROR (Status)) {
Status = EFI_NOT_FOUND;
}
goto Error;
}
Status = EFI_NOT_FOUND;
Context.Flags = 0;
if (ShellCommandLineGetFlag (CheckPackage, L"-m")) {
Context.Flags |= DL_FLAG_TIME;
}
if (ShellCommandLineGetFlag (CheckPackage, L"-k")) {
Context.Flags |= DL_FLAG_KEEP_BAD;
}
for (NicNumber = 0;
(NicNumber < HandleCount) && (Status != EFI_SUCCESS);
NicNumber++)
{
ControllerHandle = Handles[NicNumber];
Status = GetNicName (ControllerHandle, NicNumber, NicName);
if (EFI_ERROR (Status)) {
PRINT_HII (STRING_TOKEN (STR_HTTP_ERR_NIC_NAME), NicNumber, Status);
continue;
}
if (UserNicName != NULL) {
if (StrCmp (NicName, UserNicName) != 0) {
Status = EFI_NOT_FOUND;
continue;
}
NicFound = TRUE;
}
Status = DownloadFile (&Context, ControllerHandle, NicName);
PRINT_HII (STRING_TOKEN (STR_GEN_CRLF), NULL);
if (EFI_ERROR (Status)) {
PRINT_HII (
STRING_TOKEN (STR_HTTP_ERR_DOWNLOAD),
RemoteFilePath,
NicName,
Status
);
//
// If a user aborted the operation,
// do not try another controller.
//
if (Status == EFI_ABORTED) {
goto Error;
}
}
if (gHttpError) {
//
// This is not related to connection, so no need to repeat with
// another interface.
//
break;
}
}
if ((UserNicName != NULL) && (!NicFound)) {
PRINT_HII (STRING_TOKEN (STR_HTTP_ERR_NIC_NOT_FOUND), UserNicName);
}
Error:
ShellCommandLineFreeVarList (CheckPackage);
SHELL_FREE_NON_NULL (Handles);
SHELL_FREE_NON_NULL (Context.ServerAddrAndProto);
SHELL_FREE_NON_NULL (Context.Uri);
return Status & ~MAX_BIT;
}
/**
Check and convert the UINT16 option values of the 'http' command
@param[in] ValueStr Value as an Unicode encoded string
@param[out] Value UINT16 value
@retval TRUE The value was returned.
@retval FALSE A parsing error occured.
**/
STATIC
BOOLEAN
StringToUint16 (
IN CONST CHAR16 *ValueStr,
OUT UINT16 *Value
)
{
UINTN Val;
Val = ShellStrToUintn (ValueStr);
if (Val > MAX_UINT16) {
PRINT_HII_APP (STRING_TOKEN (STR_GEN_PARAM_INV), ValueStr);
return FALSE;
}
*Value = (UINT16)Val;
return TRUE;
}
/**
Get the name of the NIC.
@param[in] ControllerHandle The network physical device handle.
@param[in] NicNumber The network physical device number.
@param[out] NicName Address where to store the NIC name.
The memory area has to be at least
IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH
double byte wide.
@retval EFI_SUCCESS The name of the NIC was returned.
@retval Others The creation of the child for the Managed
Network Service failed or the opening of
the Managed Network Protocol failed or
the operational parameters for the
Managed Network Protocol could not be
read.
**/
STATIC
EFI_STATUS
GetNicName (
IN EFI_HANDLE ControllerHandle,
IN UINTN NicNumber,
OUT CHAR16 *NicName
)
{
EFI_STATUS Status;
EFI_HANDLE MnpHandle;
EFI_MANAGED_NETWORK_PROTOCOL *Mnp;
EFI_SIMPLE_NETWORK_MODE SnpMode;
Status = CreateServiceChildAndOpenProtocol (
ControllerHandle,
&gEfiManagedNetworkServiceBindingProtocolGuid,
&gEfiManagedNetworkProtocolGuid,
&MnpHandle,
(VOID **)&Mnp
);
if (EFI_ERROR (Status)) {
goto Error;
}
Status = Mnp->GetModeData (Mnp, NULL, &SnpMode);
if (EFI_ERROR (Status) && (Status != EFI_NOT_STARTED)) {
goto Error;
}
UnicodeSPrint (
NicName,
IP4_CONFIG2_INTERFACE_INFO_NAME_LENGTH,
SnpMode.IfType == NET_IFTYPE_ETHERNET ? L"eth%d" : L"unk%d",
NicNumber
);
Status = EFI_SUCCESS;
Error:
if (MnpHandle != NULL) {
CloseProtocolAndDestroyServiceChild (
ControllerHandle,
&gEfiManagedNetworkServiceBindingProtocolGuid,
&gEfiManagedNetworkProtocolGuid,
MnpHandle
);
}
return Status;
}
/**
Create a child for the service identified by its service binding protocol GUID
and get from the child the interface of the protocol identified by its GUID.
@param[in] ControllerHandle Controller handle.
@param[in] ServiceBindingProtocolGuid Service binding protocol GUID of the
service to be created.
@param[in] ProtocolGuid GUID of the protocol to be open.
@param[out] ChildHandle Address where the handler of the
created child is returned. NULL is
returned in case of error.
@param[out] Interface Address where a pointer to the
protocol interface is returned in
case of success.
@retval EFI_SUCCESS The child was created and the protocol opened.
@retval Others Either the creation of the child or the opening
of the protocol failed.
**/
STATIC
EFI_STATUS
CreateServiceChildAndOpenProtocol (
IN EFI_HANDLE ControllerHandle,
IN EFI_GUID *ServiceBindingProtocolGuid,
IN EFI_GUID *ProtocolGuid,
OUT EFI_HANDLE *ChildHandle,
OUT VOID **Interface
)
{
EFI_STATUS Status;
*ChildHandle = NULL;
Status = NetLibCreateServiceChild (
ControllerHandle,
gImageHandle,
ServiceBindingProtocolGuid,
ChildHandle
);
if (!EFI_ERROR (Status)) {
Status = gBS->OpenProtocol (
*ChildHandle,
ProtocolGuid,
Interface,
gImageHandle,
ControllerHandle,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
NetLibDestroyServiceChild (
ControllerHandle,
gImageHandle,
ServiceBindingProtocolGuid,
*ChildHandle
);
*ChildHandle = NULL;
}
}
return Status;
}
/**
Close the protocol identified by its GUID on the child handle of the service
identified by its service binding protocol GUID, then destroy the child
handle.
@param[in] ControllerHandle Controller handle.
@param[in] ServiceBindingProtocolGuid Service binding protocol GUID of the
service to be destroyed.
@param[in] ProtocolGuid GUID of the protocol to be closed.
@param[in] ChildHandle Handle of the child to be destroyed.
**/
STATIC
VOID
CloseProtocolAndDestroyServiceChild (
IN EFI_HANDLE ControllerHandle,
IN EFI_GUID *ServiceBindingProtocolGuid,
IN EFI_GUID *ProtocolGuid,
IN EFI_HANDLE ChildHandle
)
{
gBS->CloseProtocol (
ChildHandle,
ProtocolGuid,
gImageHandle,
ControllerHandle
);
NetLibDestroyServiceChild (
ControllerHandle,
gImageHandle,
ServiceBindingProtocolGuid,
ChildHandle
);
}
/**
Wait until operation completes. Completion is indicated by
setting of an appropriate variable.
@param[in] Context A pointer to the HTTP download context.
@param[in, out] CallBackComplete A pointer to the callback completion
variable set by the callback.
@retval EFI_SUCCESS Callback signalled completion.
@retval EFI_TIMEOUT Timed out waiting for completion.
@retval Others Error waiting for completion.
**/
STATIC
EFI_STATUS
WaitForCompletion (
IN HTTP_DOWNLOAD_CONTEXT *Context,
IN OUT BOOLEAN *CallBackComplete
)
{
EFI_STATUS Status;
EFI_EVENT WaitEvt;
Status = EFI_SUCCESS;
//
// Use a timer to measure timeout. Cannot use Stall here!
//
Status = gBS->CreateEvent (
EVT_TIMER,
TPL_CALLBACK,
NULL,
NULL,
&WaitEvt
);
ASSERT_EFI_ERROR (Status);
if (!EFI_ERROR (Status)) {
Status = gBS->SetTimer (
WaitEvt,
TimerRelative,
EFI_TIMER_PERIOD_SECONDS (TIMER_MAX_TIMEOUT_S)
);
ASSERT_EFI_ERROR (Status);
}
while ( !*CallBackComplete
&& (!EFI_ERROR (Status))
&& EFI_ERROR (gBS->CheckEvent (WaitEvt)))
{
Status = Context->Http->Poll (Context->Http);
if ( !Context->ContentDownloaded
&& (CallBackComplete == &gResponseCallbackComplete))
{
//
// An HTTP server may just send a response redirection header.
// In this case, don't wait for the event as
// it might never happen and we waste 10s waiting.
// Note that at this point Response may not has been populated,
// so it needs to be checked first.
//
if ( Context->ResponseToken.Message
&& Context->ResponseToken.Message->Data.Response
&& (NEED_REDIRECTION (
Context->ResponseToken.Message->Data.Response->StatusCode
)
))
{
break;
}
}
}
gBS->SetTimer (WaitEvt, TimerCancel, 0);
gBS->CloseEvent (WaitEvt);
if (*CallBackComplete) {
return EFI_SUCCESS;
}
if (!EFI_ERROR (Status)) {
Status = EFI_TIMEOUT;
}
return Status;
}
/**
Generate and send a request to the http server.
@param[in] Context HTTP download context.
@param[in] DownloadUrl Fully qualified URL to be downloaded.
@retval EFI_SUCCESS Request has been sent successfully.
@retval EFI_INVALID_PARAMETER Invalid URL.
@retval EFI_OUT_OF_RESOURCES Out of memory.
@retval EFI_DEVICE_ERROR If HTTPS is used, this probably
means that TLS support either was not
installed or not configured.
@retval Others Error sending the request.
**/
STATIC
EFI_STATUS
SendRequest (
IN HTTP_DOWNLOAD_CONTEXT *Context,
IN CHAR16 *DownloadUrl
)
{
EFI_HTTP_REQUEST_DATA RequestData;
EFI_HTTP_HEADER RequestHeader[HdrMax];
EFI_HTTP_MESSAGE RequestMessage;
EFI_STATUS Status;
CHAR16 *Host;
UINTN StringSize;
ZeroMem (&RequestData, sizeof (RequestData));
ZeroMem (&RequestHeader, sizeof (RequestHeader));
ZeroMem (&RequestMessage, sizeof (RequestMessage));
ZeroMem (&Context->RequestToken, sizeof (Context->RequestToken));
RequestHeader[HdrHost].FieldName = "Host";
RequestHeader[HdrConn].FieldName = "Connection";
RequestHeader[HdrAgent].FieldName = "User-Agent";
Host = (CHAR16 *)Context->ServerAddrAndProto;
while (*Host != CHAR_NULL && *Host != L'/') {
Host++;
}
if (*Host == CHAR_NULL) {
return EFI_INVALID_PARAMETER;
}
//
// Get the next slash.
//
Host++;
//
// And now the host name.
//
Host++;
StringSize = StrLen (Host) + 1;
RequestHeader[HdrHost].FieldValue = AllocatePool (StringSize);
if (!RequestHeader[HdrHost].FieldValue) {
return EFI_OUT_OF_RESOURCES;
}
UnicodeStrToAsciiStrS (
Host,
RequestHeader[HdrHost].FieldValue,
StringSize
);
RequestHeader[HdrConn].FieldValue = "close";
RequestHeader[HdrAgent].FieldValue = USER_AGENT_HDR;
RequestMessage.HeaderCount = HdrMax;
RequestData.Method = HttpMethodGet;
RequestData.Url = DownloadUrl;
RequestMessage.Data.Request = &RequestData;
RequestMessage.Headers = RequestHeader;
RequestMessage.BodyLength = 0;
RequestMessage.Body = NULL;
Context->RequestToken.Event = NULL;
//
// Completion callback event to be set when Request completes.
//
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_CALLBACK,
RequestCallback,
Context,
&Context->RequestToken.Event
);
ASSERT_EFI_ERROR (Status);
Context->RequestToken.Status = EFI_SUCCESS;
Context->RequestToken.Message = &RequestMessage;
gRequestCallbackComplete = FALSE;
Status = Context->Http->Request (Context->Http, &Context->RequestToken);
if (EFI_ERROR (Status)) {
goto Error;
}
Status = WaitForCompletion (Context, &gRequestCallbackComplete);
if (EFI_ERROR (Status)) {
Context->Http->Cancel (Context->Http, &Context->RequestToken);
}
Error:
SHELL_FREE_NON_NULL (RequestHeader[HdrHost].FieldValue);
if (Context->RequestToken.Event) {
gBS->CloseEvent (Context->RequestToken.Event);
ZeroMem (&Context->RequestToken, sizeof (Context->RequestToken));
}
return Status;
}
/**
Update the progress of a file download
This procedure is called each time a new HTTP body portion is received.
@param[in] Context HTTP download context.
@param[in] DownloadLen Portion size, in bytes.
@param[in] Buffer The pointer to the parsed buffer.
@retval EFI_SUCCESS Portion saved.
@retval Other Error saving the portion.
**/
STATIC
EFI_STATUS
EFIAPI
SavePortion (
IN HTTP_DOWNLOAD_CONTEXT *Context,
IN UINTN DownloadLen,
IN CHAR8 *Buffer
)
{
CHAR16 Progress[HTTP_PROGRESS_MESSAGE_SIZE];
UINTN NbOfKb;
UINTN Index;
UINTN LastStep;
UINTN Step;
EFI_STATUS Status;
LastStep = 0;
Step = 0;
ShellSetFilePosition (mFileHandle, Context->LastReportedNbOfBytes);
Status = ShellWriteFile (mFileHandle, &DownloadLen, Buffer);
if (EFI_ERROR (Status)) {
if (Context->ContentDownloaded > 0) {
PRINT_HII (STRING_TOKEN (STR_GEN_CRLF), NULL);
}
PRINT_HII (STRING_TOKEN (STR_HTTP_ERR_WRITE), mLocalFilePath, Status);
return Status;
}
if (Context->ContentDownloaded == 0) {
ShellPrintEx (-1, -1, L"%s 0 Kb", HTTP_PROGR_FRAME);
}
Context->ContentDownloaded += DownloadLen;
NbOfKb = Context->ContentDownloaded >> 10;
Progress[0] = L'\0';
if (Context->ContentLength) {
LastStep = (Context->LastReportedNbOfBytes * HTTP_PROGRESS_SLIDER_STEPS) /
Context->ContentLength;
Step = (Context->ContentDownloaded * HTTP_PROGRESS_SLIDER_STEPS) /
Context->ContentLength;
}
Context->LastReportedNbOfBytes = Context->ContentDownloaded;
if (Step <= LastStep) {
if (!Context->ContentLength) {
//
// Update downloaded size, there is no length info available.
//
ShellPrintEx (-1, -1, L"%s", HTTP_KB);
ShellPrintEx (-1, -1, L"%7d Kb", NbOfKb);
}
return EFI_SUCCESS;
}
ShellPrintEx (-1, -1, L"%s", HTTP_PROGRESS_DEL);
Status = StrCpyS (Progress, HTTP_PROGRESS_MESSAGE_SIZE, HTTP_PROGR_FRAME);
if (EFI_ERROR (Status)) {
return Status;
}
for (Index = 1; Index < Step; Index++) {
Progress[Index] = L'=';
}
if (Step) {
Progress[Step] = L'>';
}
UnicodeSPrint (
Progress + (sizeof (HTTP_PROGR_FRAME) / sizeof (CHAR16)) - 1,
sizeof (Progress) - sizeof (HTTP_PROGR_FRAME),
L" %7d Kb",
NbOfKb
);
ShellPrintEx (-1, -1, L"%s", Progress);
return EFI_SUCCESS;
}
/**
Replace the original Host and Uri with Host and Uri returned by the
HTTP server in 'Location' header (redirection).
@param[in] Location A pointer to the 'Location' string
provided by HTTP server.
@param[in] Context A pointer to HTTP download context.
@param[in] DownloadUrl Fully qualified HTTP URL.
@retval EFI_SUCCESS Host and Uri were successfully set.
@retval EFI_OUT_OF_RESOURCES Error setting Host or Uri.
**/
STATIC
EFI_STATUS
SetHostURI (
IN CHAR8 *Location,
IN HTTP_DOWNLOAD_CONTEXT *Context,
IN CHAR16 *DownloadUrl
)
{
EFI_STATUS Status;
UINTN StringSize;
UINTN FirstStep;
UINTN Idx;
UINTN Step;
CHAR8 *Walker;
CHAR16 *Temp;
CHAR8 *Tmp;
CHAR16 *Url;
BOOLEAN IsAbEmptyUrl;
Tmp = NULL;
Url = NULL;
IsAbEmptyUrl = FALSE;
FirstStep = 0;
StringSize = (AsciiStrSize (Location) * sizeof (CHAR16));
Url = AllocateZeroPool (StringSize);
if (!Url) {
return EFI_OUT_OF_RESOURCES;
}
Status = AsciiStrToUnicodeStrS (
(CONST CHAR8 *)Location,
Url,
StringSize
);
if (EFI_ERROR (Status)) {
goto Error;
}
//
// If an HTTP server redirects to the same location more than once,
// then stop attempts and tell it is not reachable.
//
if (!StrCmp (Url, DownloadUrl)) {
Status = EFI_NO_MAPPING;
goto Error;
}
if (AsciiStrLen (Location) > 2) {
//
// Some servers return 'Location: //server/resource'
//
IsAbEmptyUrl = (Location[0] == '/') && (Location[1] == '/');
if (IsAbEmptyUrl) {
//
// Skip first "//"
//
Location += 2;
FirstStep = 1;
}
}
if (AsciiStrStr (Location, "://") || IsAbEmptyUrl) {
Idx = 0;
Walker = Location;
for (Step = FirstStep; Step < 2; Step++) {
for ( ; *Walker != '/' && *Walker != '\0'; Walker++) {
Idx++;
}
if (!Step) {
//
// Skip "//"
//
Idx += 2;
Walker += 2;
}
}
Tmp = AllocateZeroPool (Idx + 1);
if (!Tmp) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
CopyMem (Tmp, Location, Idx);
//
// Location now points to Uri
//
Location += Idx;
StringSize = (Idx + 1) * sizeof (CHAR16);
SHELL_FREE_NON_NULL (Context->ServerAddrAndProto);
Temp = AllocateZeroPool (StringSize);
if (!Temp) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
Status = AsciiStrToUnicodeStrS (
(CONST CHAR8 *)Tmp,
Temp,
StringSize
);
if (EFI_ERROR (Status)) {
SHELL_FREE_NON_NULL (Temp);
goto Error;
}
Idx = 0;
if (IsAbEmptyUrl) {
Context->ServerAddrAndProto = StrnCatGrow (
&Context->ServerAddrAndProto,
&Idx,
L"http://",
StrLen (L"http://")
);
}
Context->ServerAddrAndProto = StrnCatGrow (
&Context->ServerAddrAndProto,
&Idx,
Temp,
StrLen (Temp)
);
SHELL_FREE_NON_NULL (Temp);
if (!Context->ServerAddrAndProto) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
}
SHELL_FREE_NON_NULL (Context->Uri);
StringSize = AsciiStrSize (Location) * sizeof (CHAR16);
Context->Uri = AllocateZeroPool (StringSize);
if (!Context->Uri) {
Status = EFI_OUT_OF_RESOURCES;
goto Error;
}
//
// Now make changes to the Uri part.
//
Status = AsciiStrToUnicodeStrS (
(CONST CHAR8 *)Location,
Context->Uri,
StringSize
);
Error:
SHELL_FREE_NON_NULL (Tmp);
SHELL_FREE_NON_NULL (Url);
return Status;
}
/**
Message parser callback.
Save a portion of HTTP body.
@param[in] EventType Type of event. Can be either
OnComplete or OnData.
@param[in] Data A pointer to the buffer with data.
@param[in] Length Data length of this portion.
@param[in] Context A pointer to the HTTP download context.
@retval EFI_SUCCESS The portion was processed successfully.
@retval Other Error returned by SavePortion.
**/
STATIC
EFI_STATUS
EFIAPI
ParseMsg (
IN HTTP_BODY_PARSE_EVENT EventType,
IN CHAR8 *Data,
IN UINTN Length,
IN VOID *Context
)
{
if ( (Data == NULL)
|| (EventType == BodyParseEventOnComplete)
|| (Context == NULL))
{
return EFI_SUCCESS;
}
return SavePortion (Context, Length, Data);
}
/**
Get HTTP server response and collect the whole body as a file.
Set appropriate status in Context (REQ_OK, REQ_REPEAT, REQ_ERROR).
Note that even if HTTP server returns an error code, it might send
the body as well. This body will be collected in the resultant file.
@param[in] Context A pointer to the HTTP download context.
@param[in] DownloadUrl A pointer to the fully qualified URL to download.
@retval EFI_SUCCESS Valid file. Body successfully collected.
@retval EFI_HTTP_ERROR Response is a valid HTTP response, but the
HTTP server
indicated an error (HTTP code >= 400).
Response body MAY contain full
HTTP server response.
@retval Others Error getting the reponse from the HTTP server.
Response body is not collected.
**/
STATIC
EFI_STATUS
GetResponse (
IN HTTP_DOWNLOAD_CONTEXT *Context,
IN CHAR16 *DownloadUrl
)
{
EFI_HTTP_RESPONSE_DATA ResponseData;
EFI_HTTP_MESSAGE ResponseMessage;
EFI_HTTP_HEADER *Header;
EFI_STATUS Status;
VOID *MsgParser;
EFI_TIME StartTime;
EFI_TIME EndTime;
CONST CHAR16 *Desc;
UINTN ElapsedSeconds;
BOOLEAN IsTrunked;
BOOLEAN CanMeasureTime;
ZeroMem (&ResponseData, sizeof (ResponseData));
ZeroMem (&ResponseMessage, sizeof (ResponseMessage));
ZeroMem (&Context->ResponseToken, sizeof (Context->ResponseToken));
IsTrunked = FALSE;
ResponseMessage.Body = Context->Buffer;
Context->ResponseToken.Status = EFI_SUCCESS;
Context->ResponseToken.Message = &ResponseMessage;
Context->ContentLength = 0;
Context->Status = REQ_OK;
Status = EFI_SUCCESS;
MsgParser = NULL;
ResponseData.StatusCode = HTTP_STATUS_UNSUPPORTED_STATUS;
ResponseMessage.Data.Response = &ResponseData;
Context->ResponseToken.Event = NULL;
CanMeasureTime = FALSE;
if (Context->Flags & DL_FLAG_TIME) {
ZeroMem (&StartTime, sizeof (StartTime));
CanMeasureTime = !EFI_ERROR (gRT->GetTime (&StartTime, NULL));
}
do {
SHELL_FREE_NON_NULL (ResponseMessage.Headers);
ResponseMessage.HeaderCount = 0;
gResponseCallbackComplete = FALSE;
ResponseMessage.BodyLength = Context->BufferSize;
if (ShellGetExecutionBreakFlag ()) {
Status = EFI_ABORTED;
break;
}
if (!Context->ContentDownloaded && !Context->ResponseToken.Event) {
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_CALLBACK,
ResponseCallback,
Context,
&Context->ResponseToken.Event
);
ASSERT_EFI_ERROR (Status);
} else {
ResponseMessage.Data.Response = NULL;
}
if (EFI_ERROR (Status)) {
break;
}
Status = Context->Http->Response (Context->Http, &Context->ResponseToken);
if (EFI_ERROR (Status)) {
break;
}
Status = WaitForCompletion (Context, &gResponseCallbackComplete);
if (EFI_ERROR (Status) && ResponseMessage.HeaderCount) {
Status = EFI_SUCCESS;
}
if (EFI_ERROR (Status)) {
Context->Http->Cancel (Context->Http, &Context->ResponseToken);
break;
}
if (!Context->ContentDownloaded) {
if (NEED_REDIRECTION (ResponseData.StatusCode)) {
//
// Need to repeat the request with new Location (server redirected).
//
Context->Status = REQ_NEED_REPEAT;
Header = HttpFindHeader (
ResponseMessage.HeaderCount,
ResponseMessage.Headers,
"Location"
);
if (Header) {
Status = SetHostURI (Header->FieldValue, Context, DownloadUrl);
if (Status == EFI_NO_MAPPING) {
PRINT_HII (
STRING_TOKEN (STR_HTTP_ERR_STATUSCODE),
Context->ServerAddrAndProto,
L"Recursive HTTP server relocation",
Context->Uri
);
}
} else {
//
// Bad reply from the server. Server must specify the location.
// Indicate that resource was not found, and no body collected.
//
Status = EFI_NOT_FOUND;
}
Context->Http->Cancel (Context->Http, &Context->ResponseToken);
break;
}
//
// Init message-body parser by header information.
//
if (!MsgParser) {
Status = HttpInitMsgParser (
ResponseMessage.Data.Request->Method,
ResponseData.StatusCode,
ResponseMessage.HeaderCount,
ResponseMessage.Headers,
ParseMsg,
Context,
&MsgParser
);
if (EFI_ERROR (Status)) {
break;
}
}
//
// If it is a trunked message, rely on the parser.
//
Header = HttpFindHeader (
ResponseMessage.HeaderCount,
ResponseMessage.Headers,
"Transfer-Encoding"
);
IsTrunked = (Header && !AsciiStrCmp (Header->FieldValue, "chunked"));
HttpGetEntityLength (MsgParser, &Context->ContentLength);
if ( (ResponseData.StatusCode >= HTTP_STATUS_400_BAD_REQUEST)
&& (ResponseData.StatusCode != HTTP_STATUS_308_PERMANENT_REDIRECT))
{
//
// Server reported an error via Response code.
// Collect the body if any.
//
if (!gHttpError) {
gHttpError = TRUE;
Desc = ErrStatusDesc[ResponseData.StatusCode -
HTTP_STATUS_400_BAD_REQUEST];
PRINT_HII (
STRING_TOKEN (STR_HTTP_ERR_STATUSCODE),
Context->ServerAddrAndProto,
Desc,
Context->Uri
);
//
// This gives an RFC HTTP error.
//
Context->Status = ShellStrToUintn (Desc);
Status = ENCODE_ERROR (Context->Status);
}
}
}
//
// Do NOT try to parse an empty body.
//
if (ResponseMessage.BodyLength || IsTrunked) {
Status = HttpParseMessageBody (
MsgParser,
ResponseMessage.BodyLength,
ResponseMessage.Body
);
}
} while ( !HttpIsMessageComplete (MsgParser)
&& !EFI_ERROR (Status)
&& ResponseMessage.BodyLength);
if ( (Context->Status != REQ_NEED_REPEAT)
&& (Status == EFI_SUCCESS)
&& CanMeasureTime)
{
if (!EFI_ERROR (gRT->GetTime (&EndTime, NULL))) {
ElapsedSeconds = EfiTimeToEpoch (&EndTime) - EfiTimeToEpoch (&StartTime);
Print (
L",%a%Lus\n",
ElapsedSeconds ? " " : " < ",
ElapsedSeconds > 1 ? (UINT64)ElapsedSeconds : 1
);
}
}
SHELL_FREE_NON_NULL (MsgParser);
if (Context->ResponseToken.Event) {
gBS->CloseEvent (Context->ResponseToken.Event);
ZeroMem (&Context->ResponseToken, sizeof (Context->ResponseToken));
}
return Status;
}
/**
Worker function that downloads the data of a file from an HTTP server given
the path of the file and its size.
@param[in] Context A pointer to the HTTP download context.
@param[in] ControllerHandle The handle of the network interface controller
@param[in] NicName NIC name
@retval EFI_SUCCESS The file was downloaded.
@retval EFI_OUT_OF_RESOURCES A memory allocation failed.
#return EFI_HTTP_ERROR The server returned a valid HTTP error.
Examine the mLocalFilePath file
to get error body.
@retval Others The downloading of the file from the server
failed.
**/
STATIC
EFI_STATUS
DownloadFile (
IN HTTP_DOWNLOAD_CONTEXT *Context,
IN EFI_HANDLE ControllerHandle,
IN CHAR16 *NicName
)
{
EFI_STATUS Status;
CHAR16 *DownloadUrl;
UINTN UrlSize;
EFI_HANDLE HttpChildHandle;
ASSERT (Context);
if (Context == NULL) {
return EFI_INVALID_PARAMETER;
}
DownloadUrl = NULL;
HttpChildHandle = NULL;
Context->Buffer = AllocatePool (Context->BufferSize);
if (Context->Buffer == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto ON_EXIT;
}
//
// Open the file.
//
if (!EFI_ERROR (ShellFileExists (mLocalFilePath))) {
ShellDeleteFileByName (mLocalFilePath);
}
Status = ShellOpenFileByName (
mLocalFilePath,
&mFileHandle,
EFI_FILE_MODE_CREATE |
EFI_FILE_MODE_WRITE |
EFI_FILE_MODE_READ,
0
);
if (EFI_ERROR (Status)) {
PRINT_HII_APP (STRING_TOKEN (STR_GEN_FILE_OPEN_FAIL), mLocalFilePath);
goto ON_EXIT;
}
do {
SHELL_FREE_NON_NULL (DownloadUrl);
CLOSE_HTTP_HANDLE (ControllerHandle, HttpChildHandle);
Status = CreateServiceChildAndOpenProtocol (
ControllerHandle,
&gEfiHttpServiceBindingProtocolGuid,
&gEfiHttpProtocolGuid,
&HttpChildHandle,
(VOID **)&Context->Http
);
if (EFI_ERROR (Status)) {
PRINT_HII (STRING_TOKEN (STR_HTTP_ERR_OPEN_PROTOCOL), NicName, Status);
goto ON_EXIT;
}
Status = Context->Http->Configure (Context->Http, &Context->HttpConfigData);
if (EFI_ERROR (Status)) {
PRINT_HII (STRING_TOKEN (STR_HTTP_ERR_CONFIGURE), NicName, Status);
goto ON_EXIT;
}
UrlSize = 0;
DownloadUrl = StrnCatGrow (
&DownloadUrl,
&UrlSize,
Context->ServerAddrAndProto,
StrLen (Context->ServerAddrAndProto)
);
if (Context->Uri[0] != L'/') {
DownloadUrl = StrnCatGrow (
&DownloadUrl,
&UrlSize,
L"/",
StrLen (Context->ServerAddrAndProto)
);
}
DownloadUrl = StrnCatGrow (
&DownloadUrl,
&UrlSize,
Context->Uri,
StrLen (Context->Uri)
);
if (DownloadUrl == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto ON_EXIT;
}
PRINT_HII (STRING_TOKEN (STR_HTTP_DOWNLOADING), DownloadUrl);
Status = SendRequest (Context, DownloadUrl);
if (Status) {
goto ON_EXIT;
}
Status = GetResponse (Context, DownloadUrl);
if (Status) {
goto ON_EXIT;
}
} while (Context->Status == REQ_NEED_REPEAT);
if (Context->Status) {
Status = ENCODE_ERROR (Context->Status);
}
ON_EXIT:
//
// Close the file.
//
if (mFileHandle != NULL) {
if (EFI_ERROR (Status) && !(Context->Flags & DL_FLAG_KEEP_BAD)) {
ShellDeleteFile (&mFileHandle);
} else {
ShellCloseFile (&mFileHandle);
}
}
SHELL_FREE_NON_NULL (DownloadUrl);
SHELL_FREE_NON_NULL (Context->Buffer);
CLOSE_HTTP_HANDLE (ControllerHandle, HttpChildHandle);
return Status;
}
/**
Retrive HII package list from ImageHandle and publish to HII database.
@param[in] ImageHandle The image handle of the process.
@retval HII handle.
**/
EFI_HII_HANDLE
InitializeHiiPackage (
IN EFI_HANDLE ImageHandle
)
{
EFI_STATUS Status;
EFI_HII_PACKAGE_LIST_HEADER *PackageList;
EFI_HII_HANDLE HiiHandle;
//
// Retrieve HII package list from ImageHandle.
//
Status = gBS->OpenProtocol (
ImageHandle,
&gEfiHiiPackageListProtocolGuid,
(VOID **)&PackageList,
ImageHandle,
NULL,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
ASSERT_EFI_ERROR (Status);
if (EFI_ERROR (Status)) {
return NULL;
}
//
// Publish HII package list to HII Database.
//
Status = gHiiDatabase->NewPackageList (
gHiiDatabase,
PackageList,
NULL,
&HiiHandle
);
ASSERT_EFI_ERROR (Status);
if (EFI_ERROR (Status)) {
return NULL;
}
return HiiHandle;
}
|