]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeNetLib/DxeNetLib.c
MdeModulePkg: Enhance error handling in NetLibGetMacAddress() of DxeNetLib.
[mirror_edk2.git] / MdeModulePkg / Library / DxeNetLib / DxeNetLib.c
1 /** @file
2 Network library.
3
4 Copyright (c) 2005 - 2011, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12 **/
13
14 #include <Uefi.h>
15
16 #include <IndustryStandard/SmBios.h>
17
18 #include <Protocol/DriverBinding.h>
19 #include <Protocol/ServiceBinding.h>
20 #include <Protocol/SimpleNetwork.h>
21 #include <Protocol/ManagedNetwork.h>
22 #include <Protocol/HiiConfigRouting.h>
23 #include <Protocol/ComponentName.h>
24 #include <Protocol/ComponentName2.h>
25 #include <Protocol/HiiConfigAccess.h>
26
27 #include <Guid/NicIp4ConfigNvData.h>
28 #include <Guid/SmBios.h>
29
30 #include <Library/NetLib.h>
31 #include <Library/BaseLib.h>
32 #include <Library/DebugLib.h>
33 #include <Library/BaseMemoryLib.h>
34 #include <Library/UefiBootServicesTableLib.h>
35 #include <Library/UefiRuntimeServicesTableLib.h>
36 #include <Library/MemoryAllocationLib.h>
37 #include <Library/DevicePathLib.h>
38 #include <Library/HiiLib.h>
39 #include <Library/PrintLib.h>
40 #include <Library/UefiLib.h>
41
42 #define NIC_ITEM_CONFIG_SIZE sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE
43
44 //
45 // All the supported IP4 maskes in host byte order.
46 //
47 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks[IP4_MASK_NUM] = {
48 0x00000000,
49 0x80000000,
50 0xC0000000,
51 0xE0000000,
52 0xF0000000,
53 0xF8000000,
54 0xFC000000,
55 0xFE000000,
56
57 0xFF000000,
58 0xFF800000,
59 0xFFC00000,
60 0xFFE00000,
61 0xFFF00000,
62 0xFFF80000,
63 0xFFFC0000,
64 0xFFFE0000,
65
66 0xFFFF0000,
67 0xFFFF8000,
68 0xFFFFC000,
69 0xFFFFE000,
70 0xFFFFF000,
71 0xFFFFF800,
72 0xFFFFFC00,
73 0xFFFFFE00,
74
75 0xFFFFFF00,
76 0xFFFFFF80,
77 0xFFFFFFC0,
78 0xFFFFFFE0,
79 0xFFFFFFF0,
80 0xFFFFFFF8,
81 0xFFFFFFFC,
82 0xFFFFFFFE,
83 0xFFFFFFFF,
84 };
85
86 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr = {{0, 0, 0, 0}};
87
88 //
89 // Any error level digitally larger than mNetDebugLevelMax
90 // will be silently discarded.
91 //
92 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax = NETDEBUG_LEVEL_ERROR;
93 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq = 0xDEADBEEF;
94
95 //
96 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
97 // here to direct the syslog packets to the syslog deamon. The
98 // default is broadcast to both the ethernet and IP.
99 //
100 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac[NET_ETHER_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
101 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp = 0xffffffff;
102 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp = 0;
103
104 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *mMonthName[] = {
105 "Jan",
106 "Feb",
107 "Mar",
108 "Apr",
109 "May",
110 "Jun",
111 "Jul",
112 "Aug",
113 "Sep",
114 "Oct",
115 "Nov",
116 "Dec"
117 };
118
119 //
120 // VLAN device path node template
121 //
122 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate = {
123 {
124 MESSAGING_DEVICE_PATH,
125 MSG_VLAN_DP,
126 {
127 (UINT8) (sizeof (VLAN_DEVICE_PATH)),
128 (UINT8) ((sizeof (VLAN_DEVICE_PATH)) >> 8)
129 }
130 },
131 0
132 };
133
134 /**
135 Locate the handles that support SNP, then open one of them
136 to send the syslog packets. The caller isn't required to close
137 the SNP after use because the SNP is opened by HandleProtocol.
138
139 @return The point to SNP if one is properly openned. Otherwise NULL
140
141 **/
142 EFI_SIMPLE_NETWORK_PROTOCOL *
143 SyslogLocateSnp (
144 VOID
145 )
146 {
147 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
148 EFI_STATUS Status;
149 EFI_HANDLE *Handles;
150 UINTN HandleCount;
151 UINTN Index;
152
153 //
154 // Locate the handles which has SNP installed.
155 //
156 Handles = NULL;
157 Status = gBS->LocateHandleBuffer (
158 ByProtocol,
159 &gEfiSimpleNetworkProtocolGuid,
160 NULL,
161 &HandleCount,
162 &Handles
163 );
164
165 if (EFI_ERROR (Status) || (HandleCount == 0)) {
166 return NULL;
167 }
168
169 //
170 // Try to open one of the ethernet SNP protocol to send packet
171 //
172 Snp = NULL;
173
174 for (Index = 0; Index < HandleCount; Index++) {
175 Status = gBS->HandleProtocol (
176 Handles[Index],
177 &gEfiSimpleNetworkProtocolGuid,
178 (VOID **) &Snp
179 );
180
181 if ((Status == EFI_SUCCESS) && (Snp != NULL) &&
182 (Snp->Mode->IfType == NET_IFTYPE_ETHERNET) &&
183 (Snp->Mode->MaxPacketSize >= NET_SYSLOG_PACKET_LEN)) {
184
185 break;
186 }
187
188 Snp = NULL;
189 }
190
191 FreePool (Handles);
192 return Snp;
193 }
194
195 /**
196 Transmit a syslog packet synchronously through SNP. The Packet
197 already has the ethernet header prepended. This function should
198 fill in the source MAC because it will try to locate a SNP each
199 time it is called to avoid the problem if SNP is unloaded.
200 This code snip is copied from MNP.
201
202 @param[in] Packet The Syslog packet
203 @param[in] Length The length of the packet
204
205 @retval EFI_DEVICE_ERROR Failed to locate a usable SNP protocol
206 @retval EFI_TIMEOUT Timeout happened to send the packet.
207 @retval EFI_SUCCESS Packet is sent.
208
209 **/
210 EFI_STATUS
211 SyslogSendPacket (
212 IN CHAR8 *Packet,
213 IN UINT32 Length
214 )
215 {
216 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
217 ETHER_HEAD *Ether;
218 EFI_STATUS Status;
219 EFI_EVENT TimeoutEvent;
220 UINT8 *TxBuf;
221
222 Snp = SyslogLocateSnp ();
223
224 if (Snp == NULL) {
225 return EFI_DEVICE_ERROR;
226 }
227
228 Ether = (ETHER_HEAD *) Packet;
229 CopyMem (Ether->SrcMac, Snp->Mode->CurrentAddress.Addr, NET_ETHER_ADDR_LEN);
230
231 //
232 // Start the timeout event.
233 //
234 Status = gBS->CreateEvent (
235 EVT_TIMER,
236 TPL_NOTIFY,
237 NULL,
238 NULL,
239 &TimeoutEvent
240 );
241
242 if (EFI_ERROR (Status)) {
243 return Status;
244 }
245
246 Status = gBS->SetTimer (TimeoutEvent, TimerRelative, NET_SYSLOG_TX_TIMEOUT);
247
248 if (EFI_ERROR (Status)) {
249 goto ON_EXIT;
250 }
251
252 for (;;) {
253 //
254 // Transmit the packet through SNP.
255 //
256 Status = Snp->Transmit (Snp, 0, Length, Packet, NULL, NULL, NULL);
257
258 if ((Status != EFI_SUCCESS) && (Status != EFI_NOT_READY)) {
259 Status = EFI_DEVICE_ERROR;
260 break;
261 }
262
263 //
264 // If Status is EFI_SUCCESS, the packet is put in the transmit queue.
265 // if Status is EFI_NOT_READY, the transmit engine of the network
266 // interface is busy. Both need to sync SNP.
267 //
268 TxBuf = NULL;
269
270 do {
271 //
272 // Get the recycled transmit buffer status.
273 //
274 Snp->GetStatus (Snp, NULL, (VOID **) &TxBuf);
275
276 if (!EFI_ERROR (gBS->CheckEvent (TimeoutEvent))) {
277 Status = EFI_TIMEOUT;
278 break;
279 }
280
281 } while (TxBuf == NULL);
282
283 if ((Status == EFI_SUCCESS) || (Status == EFI_TIMEOUT)) {
284 break;
285 }
286
287 //
288 // Status is EFI_NOT_READY. Restart the timer event and
289 // call Snp->Transmit again.
290 //
291 gBS->SetTimer (TimeoutEvent, TimerRelative, NET_SYSLOG_TX_TIMEOUT);
292 }
293
294 gBS->SetTimer (TimeoutEvent, TimerCancel, 0);
295
296 ON_EXIT:
297 gBS->CloseEvent (TimeoutEvent);
298 return Status;
299 }
300
301 /**
302 Build a syslog packet, including the Ethernet/Ip/Udp headers
303 and user's message.
304
305 @param[in] Level Syslog servity level
306 @param[in] Module The module that generates the log
307 @param[in] File The file that contains the current log
308 @param[in] Line The line of code in the File that contains the current log
309 @param[in] Message The log message
310 @param[in] BufLen The lenght of the Buf
311 @param[out] Buf The buffer to put the packet data
312
313 @return The length of the syslog packet built.
314
315 **/
316 UINT32
317 SyslogBuildPacket (
318 IN UINT32 Level,
319 IN UINT8 *Module,
320 IN UINT8 *File,
321 IN UINT32 Line,
322 IN UINT8 *Message,
323 IN UINT32 BufLen,
324 OUT CHAR8 *Buf
325 )
326 {
327 ETHER_HEAD *Ether;
328 IP4_HEAD *Ip4;
329 EFI_UDP_HEADER *Udp4;
330 EFI_TIME Time;
331 UINT32 Pri;
332 UINT32 Len;
333
334 //
335 // Fill in the Ethernet header. Leave alone the source MAC.
336 // SyslogSendPacket will fill in the address for us.
337 //
338 Ether = (ETHER_HEAD *) Buf;
339 CopyMem (Ether->DstMac, mSyslogDstMac, NET_ETHER_ADDR_LEN);
340 ZeroMem (Ether->SrcMac, NET_ETHER_ADDR_LEN);
341
342 Ether->EtherType = HTONS (0x0800); // IPv4 protocol
343
344 Buf += sizeof (ETHER_HEAD);
345 BufLen -= sizeof (ETHER_HEAD);
346
347 //
348 // Fill in the IP header
349 //
350 Ip4 = (IP4_HEAD *) Buf;
351 Ip4->HeadLen = 5;
352 Ip4->Ver = 4;
353 Ip4->Tos = 0;
354 Ip4->TotalLen = 0;
355 Ip4->Id = (UINT16) mSyslogPacketSeq;
356 Ip4->Fragment = 0;
357 Ip4->Ttl = 16;
358 Ip4->Protocol = 0x11;
359 Ip4->Checksum = 0;
360 Ip4->Src = mSyslogSrcIp;
361 Ip4->Dst = mSyslogDstIp;
362
363 Buf += sizeof (IP4_HEAD);
364 BufLen -= sizeof (IP4_HEAD);
365
366 //
367 // Fill in the UDP header, Udp checksum is optional. Leave it zero.
368 //
369 Udp4 = (EFI_UDP_HEADER *) Buf;
370 Udp4->SrcPort = HTONS (514);
371 Udp4->DstPort = HTONS (514);
372 Udp4->Length = 0;
373 Udp4->Checksum = 0;
374
375 Buf += sizeof (EFI_UDP_HEADER);
376 BufLen -= sizeof (EFI_UDP_HEADER);
377
378 //
379 // Build the syslog message body with <PRI> Timestamp machine module Message
380 //
381 Pri = ((NET_SYSLOG_FACILITY & 31) << 3) | (Level & 7);
382 gRT->GetTime (&Time, NULL);
383 ASSERT ((Time.Month <= 12) && (Time.Month >= 1));
384
385 //
386 // Use %a to format the ASCII strings, %s to format UNICODE strings
387 //
388 Len = 0;
389 Len += (UINT32) AsciiSPrint (
390 Buf,
391 BufLen,
392 "<%d> %a %d %d:%d:%d ",
393 Pri,
394 mMonthName [Time.Month-1],
395 Time.Day,
396 Time.Hour,
397 Time.Minute,
398 Time.Second
399 );
400 Len--;
401
402 Len += (UINT32) AsciiSPrint (
403 Buf + Len,
404 BufLen - Len,
405 "Tiano %a: %a (Line: %d File: %a)",
406 Module,
407 Message,
408 Line,
409 File
410 );
411 Len--;
412
413 //
414 // OK, patch the IP length/checksum and UDP length fields.
415 //
416 Len += sizeof (EFI_UDP_HEADER);
417 Udp4->Length = HTONS ((UINT16) Len);
418
419 Len += sizeof (IP4_HEAD);
420 Ip4->TotalLen = HTONS ((UINT16) Len);
421 Ip4->Checksum = (UINT16) (~NetblockChecksum ((UINT8 *) Ip4, sizeof (IP4_HEAD)));
422
423 return Len + sizeof (ETHER_HEAD);
424 }
425
426 /**
427 Allocate a buffer, then format the message to it. This is a
428 help function for the NET_DEBUG_XXX macros. The PrintArg of
429 these macros treats the variable length print parameters as a
430 single parameter, and pass it to the NetDebugASPrint. For
431 example, NET_DEBUG_TRACE ("Tcp", ("State transit to %a\n", Name))
432 if extracted to:
433
434 NetDebugOutput (
435 NETDEBUG_LEVEL_TRACE,
436 "Tcp",
437 __FILE__,
438 __LINE__,
439 NetDebugASPrint ("State transit to %a\n", Name)
440 )
441
442 @param Format The ASCII format string.
443 @param ... The variable length parameter whose format is determined
444 by the Format string.
445
446 @return The buffer containing the formatted message,
447 or NULL if failed to allocate memory.
448
449 **/
450 CHAR8 *
451 EFIAPI
452 NetDebugASPrint (
453 IN CHAR8 *Format,
454 ...
455 )
456 {
457 VA_LIST Marker;
458 CHAR8 *Buf;
459
460 Buf = (CHAR8 *) AllocatePool (NET_DEBUG_MSG_LEN);
461
462 if (Buf == NULL) {
463 return NULL;
464 }
465
466 VA_START (Marker, Format);
467 AsciiVSPrint (Buf, NET_DEBUG_MSG_LEN, Format, Marker);
468 VA_END (Marker);
469
470 return Buf;
471 }
472
473 /**
474 Builds an UDP4 syslog packet and send it using SNP.
475
476 This function will locate a instance of SNP then send the message through it.
477 Because it isn't open the SNP BY_DRIVER, apply caution when using it.
478
479 @param Level The servity level of the message.
480 @param Module The Moudle that generates the log.
481 @param File The file that contains the log.
482 @param Line The exact line that contains the log.
483 @param Message The user message to log.
484
485 @retval EFI_INVALID_PARAMETER Any input parameter is invalid.
486 @retval EFI_OUT_OF_RESOURCES Failed to allocate memory for the packet
487 @retval EFI_SUCCESS The log is discard because that it is more verbose
488 than the mNetDebugLevelMax. Or, it has been sent out.
489 **/
490 EFI_STATUS
491 EFIAPI
492 NetDebugOutput (
493 IN UINT32 Level,
494 IN UINT8 *Module,
495 IN UINT8 *File,
496 IN UINT32 Line,
497 IN UINT8 *Message
498 )
499 {
500 CHAR8 *Packet;
501 UINT32 Len;
502 EFI_STATUS Status;
503
504 //
505 // Check whether the message should be sent out
506 //
507 if (Message == NULL) {
508 return EFI_INVALID_PARAMETER;
509 }
510
511 if (Level > mNetDebugLevelMax) {
512 Status = EFI_SUCCESS;
513 goto ON_EXIT;
514 }
515
516 //
517 // Allocate a maxium of 1024 bytes, the caller should ensure
518 // that the message plus the ethernet/ip/udp header is shorter
519 // than this
520 //
521 Packet = (CHAR8 *) AllocatePool (NET_SYSLOG_PACKET_LEN);
522
523 if (Packet == NULL) {
524 Status = EFI_OUT_OF_RESOURCES;
525 goto ON_EXIT;
526 }
527
528 //
529 // Build the message: Ethernet header + IP header + Udp Header + user data
530 //
531 Len = SyslogBuildPacket (
532 Level,
533 Module,
534 File,
535 Line,
536 Message,
537 NET_SYSLOG_PACKET_LEN,
538 Packet
539 );
540
541 mSyslogPacketSeq++;
542 Status = SyslogSendPacket (Packet, Len);
543 FreePool (Packet);
544
545 ON_EXIT:
546 FreePool (Message);
547 return Status;
548 }
549 /**
550 Return the length of the mask.
551
552 Return the length of the mask, the correct value is from 0 to 32.
553 If the mask is invalid, return the invalid length 33, which is IP4_MASK_NUM.
554 NetMask is in the host byte order.
555
556 @param[in] NetMask The netmask to get the length from.
557
558 @return The length of the netmask, IP4_MASK_NUM if the mask is invalid.
559
560 **/
561 INTN
562 EFIAPI
563 NetGetMaskLength (
564 IN IP4_ADDR NetMask
565 )
566 {
567 INTN Index;
568
569 for (Index = 0; Index < IP4_MASK_NUM; Index++) {
570 if (NetMask == gIp4AllMasks[Index]) {
571 break;
572 }
573 }
574
575 return Index;
576 }
577
578
579
580 /**
581 Return the class of the IP address, such as class A, B, C.
582 Addr is in host byte order.
583
584 The address of class A starts with 0.
585 If the address belong to class A, return IP4_ADDR_CLASSA.
586 The address of class B starts with 10.
587 If the address belong to class B, return IP4_ADDR_CLASSB.
588 The address of class C starts with 110.
589 If the address belong to class C, return IP4_ADDR_CLASSC.
590 The address of class D starts with 1110.
591 If the address belong to class D, return IP4_ADDR_CLASSD.
592 The address of class E starts with 1111.
593 If the address belong to class E, return IP4_ADDR_CLASSE.
594
595
596 @param[in] Addr The address to get the class from.
597
598 @return IP address class, such as IP4_ADDR_CLASSA.
599
600 **/
601 INTN
602 EFIAPI
603 NetGetIpClass (
604 IN IP4_ADDR Addr
605 )
606 {
607 UINT8 ByteOne;
608
609 ByteOne = (UINT8) (Addr >> 24);
610
611 if ((ByteOne & 0x80) == 0) {
612 return IP4_ADDR_CLASSA;
613
614 } else if ((ByteOne & 0xC0) == 0x80) {
615 return IP4_ADDR_CLASSB;
616
617 } else if ((ByteOne & 0xE0) == 0xC0) {
618 return IP4_ADDR_CLASSC;
619
620 } else if ((ByteOne & 0xF0) == 0xE0) {
621 return IP4_ADDR_CLASSD;
622
623 } else {
624 return IP4_ADDR_CLASSE;
625
626 }
627 }
628
629
630 /**
631 Check whether the IP is a valid unicast address according to
632 the netmask. If NetMask is zero, use the IP address's class to get the default mask.
633
634 If Ip is 0, IP is not a valid unicast address.
635 Class D address is used for multicasting and class E address is reserved for future. If Ip
636 belongs to class D or class E, IP is not a valid unicast address.
637 If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address.
638
639 @param[in] Ip The IP to check against.
640 @param[in] NetMask The mask of the IP.
641
642 @return TRUE if IP is a valid unicast address on the network, otherwise FALSE.
643
644 **/
645 BOOLEAN
646 EFIAPI
647 NetIp4IsUnicast (
648 IN IP4_ADDR Ip,
649 IN IP4_ADDR NetMask
650 )
651 {
652 INTN Class;
653
654 Class = NetGetIpClass (Ip);
655
656 if ((Ip == 0) || (Class >= IP4_ADDR_CLASSD)) {
657 return FALSE;
658 }
659
660 if (NetMask == 0) {
661 NetMask = gIp4AllMasks[Class << 3];
662 }
663
664 if (((Ip &~NetMask) == ~NetMask) || ((Ip &~NetMask) == 0)) {
665 return FALSE;
666 }
667
668 return TRUE;
669 }
670
671 /**
672 Check whether the incoming IPv6 address is a valid unicast address.
673
674 If the address is a multicast address has binary 0xFF at the start, it is not
675 a valid unicast address. If the address is unspecified ::, it is not a valid
676 unicast address to be assigned to any node. If the address is loopback address
677 ::1, it is also not a valid unicast address to be assigned to any physical
678 interface.
679
680 @param[in] Ip6 The IPv6 address to check against.
681
682 @return TRUE if Ip6 is a valid unicast address on the network, otherwise FALSE.
683
684 **/
685 BOOLEAN
686 EFIAPI
687 NetIp6IsValidUnicast (
688 IN EFI_IPv6_ADDRESS *Ip6
689 )
690 {
691 UINT8 Byte;
692 UINT8 Index;
693
694 if (Ip6->Addr[0] == 0xFF) {
695 return FALSE;
696 }
697
698 for (Index = 0; Index < 15; Index++) {
699 if (Ip6->Addr[Index] != 0) {
700 return TRUE;
701 }
702 }
703
704 Byte = Ip6->Addr[Index];
705
706 if (Byte == 0x0 || Byte == 0x1) {
707 return FALSE;
708 }
709
710 return TRUE;
711 }
712
713 /**
714 Check whether the incoming Ipv6 address is the unspecified address or not.
715
716 @param[in] Ip6 - Ip6 address, in network order.
717
718 @retval TRUE - Yes, unspecified
719 @retval FALSE - No
720
721 **/
722 BOOLEAN
723 EFIAPI
724 NetIp6IsUnspecifiedAddr (
725 IN EFI_IPv6_ADDRESS *Ip6
726 )
727 {
728 UINT8 Index;
729
730 for (Index = 0; Index < 16; Index++) {
731 if (Ip6->Addr[Index] != 0) {
732 return FALSE;
733 }
734 }
735
736 return TRUE;
737 }
738
739 /**
740 Check whether the incoming Ipv6 address is a link-local address.
741
742 @param[in] Ip6 - Ip6 address, in network order.
743
744 @retval TRUE - Yes, link-local address
745 @retval FALSE - No
746
747 **/
748 BOOLEAN
749 EFIAPI
750 NetIp6IsLinkLocalAddr (
751 IN EFI_IPv6_ADDRESS *Ip6
752 )
753 {
754 UINT8 Index;
755
756 ASSERT (Ip6 != NULL);
757
758 if (Ip6->Addr[0] != 0xFE) {
759 return FALSE;
760 }
761
762 if (Ip6->Addr[1] != 0x80) {
763 return FALSE;
764 }
765
766 for (Index = 2; Index < 8; Index++) {
767 if (Ip6->Addr[Index] != 0) {
768 return FALSE;
769 }
770 }
771
772 return TRUE;
773 }
774
775 /**
776 Check whether the Ipv6 address1 and address2 are on the connected network.
777
778 @param[in] Ip1 - Ip6 address1, in network order.
779 @param[in] Ip2 - Ip6 address2, in network order.
780 @param[in] PrefixLength - The prefix length of the checking net.
781
782 @retval TRUE - Yes, connected.
783 @retval FALSE - No.
784
785 **/
786 BOOLEAN
787 EFIAPI
788 NetIp6IsNetEqual (
789 EFI_IPv6_ADDRESS *Ip1,
790 EFI_IPv6_ADDRESS *Ip2,
791 UINT8 PrefixLength
792 )
793 {
794 UINT8 Byte;
795 UINT8 Bit;
796 UINT8 Mask;
797
798 ASSERT ((Ip1 != NULL) && (Ip2 != NULL) && (PrefixLength < IP6_PREFIX_NUM));
799
800 if (PrefixLength == 0) {
801 return TRUE;
802 }
803
804 Byte = (UINT8) (PrefixLength / 8);
805 Bit = (UINT8) (PrefixLength % 8);
806
807 if (CompareMem (Ip1, Ip2, Byte) != 0) {
808 return FALSE;
809 }
810
811 if (Bit > 0) {
812 Mask = (UINT8) (0xFF << (8 - Bit));
813
814 ASSERT (Byte < 16);
815 if ((Ip1->Addr[Byte] & Mask) != (Ip2->Addr[Byte] & Mask)) {
816 return FALSE;
817 }
818 }
819
820 return TRUE;
821 }
822
823
824 /**
825 Switches the endianess of an IPv6 address
826
827 This function swaps the bytes in a 128-bit IPv6 address to switch the value
828 from little endian to big endian or vice versa. The byte swapped value is
829 returned.
830
831 @param Ip6 Points to an IPv6 address
832
833 @return The byte swapped IPv6 address.
834
835 **/
836 EFI_IPv6_ADDRESS *
837 EFIAPI
838 Ip6Swap128 (
839 EFI_IPv6_ADDRESS *Ip6
840 )
841 {
842 UINT64 High;
843 UINT64 Low;
844
845 CopyMem (&High, Ip6, sizeof (UINT64));
846 CopyMem (&Low, &Ip6->Addr[8], sizeof (UINT64));
847
848 High = SwapBytes64 (High);
849 Low = SwapBytes64 (Low);
850
851 CopyMem (Ip6, &Low, sizeof (UINT64));
852 CopyMem (&Ip6->Addr[8], &High, sizeof (UINT64));
853
854 return Ip6;
855 }
856
857 /**
858 Initialize a random seed using current time.
859
860 Get current time first. Then initialize a random seed based on some basic
861 mathematics operation on the hour, day, minute, second, nanosecond and year
862 of the current time.
863
864 @return The random seed initialized with current time.
865
866 **/
867 UINT32
868 EFIAPI
869 NetRandomInitSeed (
870 VOID
871 )
872 {
873 EFI_TIME Time;
874 UINT32 Seed;
875
876 gRT->GetTime (&Time, NULL);
877 Seed = (~Time.Hour << 24 | Time.Day << 16 | Time.Minute << 8 | Time.Second);
878 Seed ^= Time.Nanosecond;
879 Seed ^= Time.Year << 7;
880
881 return Seed;
882 }
883
884
885 /**
886 Extract a UINT32 from a byte stream.
887
888 Copy a UINT32 from a byte stream, then converts it from Network
889 byte order to host byte order. Use this function to avoid alignment error.
890
891 @param[in] Buf The buffer to extract the UINT32.
892
893 @return The UINT32 extracted.
894
895 **/
896 UINT32
897 EFIAPI
898 NetGetUint32 (
899 IN UINT8 *Buf
900 )
901 {
902 UINT32 Value;
903
904 CopyMem (&Value, Buf, sizeof (UINT32));
905 return NTOHL (Value);
906 }
907
908
909 /**
910 Put a UINT32 to the byte stream in network byte order.
911
912 Converts a UINT32 from host byte order to network byte order. Then copy it to the
913 byte stream.
914
915 @param[in, out] Buf The buffer to put the UINT32.
916 @param[in] Data The data to be converted and put into the byte stream.
917
918 **/
919 VOID
920 EFIAPI
921 NetPutUint32 (
922 IN OUT UINT8 *Buf,
923 IN UINT32 Data
924 )
925 {
926 Data = HTONL (Data);
927 CopyMem (Buf, &Data, sizeof (UINT32));
928 }
929
930
931 /**
932 Remove the first node entry on the list, and return the removed node entry.
933
934 Removes the first node Entry from a doubly linked list. It is up to the caller of
935 this function to release the memory used by the first node if that is required. On
936 exit, the removed node is returned.
937
938 If Head is NULL, then ASSERT().
939 If Head was not initialized, then ASSERT().
940 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
941 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
942 then ASSERT().
943
944 @param[in, out] Head The list header.
945
946 @return The first node entry that is removed from the list, NULL if the list is empty.
947
948 **/
949 LIST_ENTRY *
950 EFIAPI
951 NetListRemoveHead (
952 IN OUT LIST_ENTRY *Head
953 )
954 {
955 LIST_ENTRY *First;
956
957 ASSERT (Head != NULL);
958
959 if (IsListEmpty (Head)) {
960 return NULL;
961 }
962
963 First = Head->ForwardLink;
964 Head->ForwardLink = First->ForwardLink;
965 First->ForwardLink->BackLink = Head;
966
967 DEBUG_CODE (
968 First->ForwardLink = (LIST_ENTRY *) NULL;
969 First->BackLink = (LIST_ENTRY *) NULL;
970 );
971
972 return First;
973 }
974
975
976 /**
977 Remove the last node entry on the list and and return the removed node entry.
978
979 Removes the last node entry from a doubly linked list. It is up to the caller of
980 this function to release the memory used by the first node if that is required. On
981 exit, the removed node is returned.
982
983 If Head is NULL, then ASSERT().
984 If Head was not initialized, then ASSERT().
985 If PcdMaximumLinkedListLength is not zero, and the number of nodes in the
986 linked list including the head node is greater than or equal to PcdMaximumLinkedListLength,
987 then ASSERT().
988
989 @param[in, out] Head The list head.
990
991 @return The last node entry that is removed from the list, NULL if the list is empty.
992
993 **/
994 LIST_ENTRY *
995 EFIAPI
996 NetListRemoveTail (
997 IN OUT LIST_ENTRY *Head
998 )
999 {
1000 LIST_ENTRY *Last;
1001
1002 ASSERT (Head != NULL);
1003
1004 if (IsListEmpty (Head)) {
1005 return NULL;
1006 }
1007
1008 Last = Head->BackLink;
1009 Head->BackLink = Last->BackLink;
1010 Last->BackLink->ForwardLink = Head;
1011
1012 DEBUG_CODE (
1013 Last->ForwardLink = (LIST_ENTRY *) NULL;
1014 Last->BackLink = (LIST_ENTRY *) NULL;
1015 );
1016
1017 return Last;
1018 }
1019
1020
1021 /**
1022 Insert a new node entry after a designated node entry of a doubly linked list.
1023
1024 Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry
1025 of the doubly linked list.
1026
1027 @param[in, out] PrevEntry The previous entry to insert after.
1028 @param[in, out] NewEntry The new entry to insert.
1029
1030 **/
1031 VOID
1032 EFIAPI
1033 NetListInsertAfter (
1034 IN OUT LIST_ENTRY *PrevEntry,
1035 IN OUT LIST_ENTRY *NewEntry
1036 )
1037 {
1038 NewEntry->BackLink = PrevEntry;
1039 NewEntry->ForwardLink = PrevEntry->ForwardLink;
1040 PrevEntry->ForwardLink->BackLink = NewEntry;
1041 PrevEntry->ForwardLink = NewEntry;
1042 }
1043
1044
1045 /**
1046 Insert a new node entry before a designated node entry of a doubly linked list.
1047
1048 Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry
1049 of the doubly linked list.
1050
1051 @param[in, out] PostEntry The entry to insert before.
1052 @param[in, out] NewEntry The new entry to insert.
1053
1054 **/
1055 VOID
1056 EFIAPI
1057 NetListInsertBefore (
1058 IN OUT LIST_ENTRY *PostEntry,
1059 IN OUT LIST_ENTRY *NewEntry
1060 )
1061 {
1062 NewEntry->ForwardLink = PostEntry;
1063 NewEntry->BackLink = PostEntry->BackLink;
1064 PostEntry->BackLink->ForwardLink = NewEntry;
1065 PostEntry->BackLink = NewEntry;
1066 }
1067
1068
1069 /**
1070 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1071
1072 Initialize the forward and backward links of two head nodes donated by Map->Used
1073 and Map->Recycled of two doubly linked lists.
1074 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1075
1076 If Map is NULL, then ASSERT().
1077 If the address of Map->Used is NULL, then ASSERT().
1078 If the address of Map->Recycled is NULl, then ASSERT().
1079
1080 @param[in, out] Map The netmap to initialize.
1081
1082 **/
1083 VOID
1084 EFIAPI
1085 NetMapInit (
1086 IN OUT NET_MAP *Map
1087 )
1088 {
1089 ASSERT (Map != NULL);
1090
1091 InitializeListHead (&Map->Used);
1092 InitializeListHead (&Map->Recycled);
1093 Map->Count = 0;
1094 }
1095
1096
1097 /**
1098 To clean up the netmap, that is, release allocated memories.
1099
1100 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1101 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1102 The number of the <Key, Value> pairs in the netmap is set to be zero.
1103
1104 If Map is NULL, then ASSERT().
1105
1106 @param[in, out] Map The netmap to clean up.
1107
1108 **/
1109 VOID
1110 EFIAPI
1111 NetMapClean (
1112 IN OUT NET_MAP *Map
1113 )
1114 {
1115 NET_MAP_ITEM *Item;
1116 LIST_ENTRY *Entry;
1117 LIST_ENTRY *Next;
1118
1119 ASSERT (Map != NULL);
1120
1121 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Used) {
1122 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1123
1124 RemoveEntryList (&Item->Link);
1125 Map->Count--;
1126
1127 gBS->FreePool (Item);
1128 }
1129
1130 ASSERT ((Map->Count == 0) && IsListEmpty (&Map->Used));
1131
1132 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Recycled) {
1133 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1134
1135 RemoveEntryList (&Item->Link);
1136 gBS->FreePool (Item);
1137 }
1138
1139 ASSERT (IsListEmpty (&Map->Recycled));
1140 }
1141
1142
1143 /**
1144 Test whether the netmap is empty and return true if it is.
1145
1146 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1147
1148 If Map is NULL, then ASSERT().
1149
1150
1151 @param[in] Map The net map to test.
1152
1153 @return TRUE if the netmap is empty, otherwise FALSE.
1154
1155 **/
1156 BOOLEAN
1157 EFIAPI
1158 NetMapIsEmpty (
1159 IN NET_MAP *Map
1160 )
1161 {
1162 ASSERT (Map != NULL);
1163 return (BOOLEAN) (Map->Count == 0);
1164 }
1165
1166
1167 /**
1168 Return the number of the <Key, Value> pairs in the netmap.
1169
1170 @param[in] Map The netmap to get the entry number.
1171
1172 @return The entry number in the netmap.
1173
1174 **/
1175 UINTN
1176 EFIAPI
1177 NetMapGetCount (
1178 IN NET_MAP *Map
1179 )
1180 {
1181 return Map->Count;
1182 }
1183
1184
1185 /**
1186 Return one allocated item.
1187
1188 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1189 a batch of items if there are enough resources and add corresponding nodes to the begining
1190 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1191 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1192
1193 If Map is NULL, then ASSERT().
1194
1195 @param[in, out] Map The netmap to allocate item for.
1196
1197 @return The allocated item. If NULL, the
1198 allocation failed due to resource limit.
1199
1200 **/
1201 NET_MAP_ITEM *
1202 NetMapAllocItem (
1203 IN OUT NET_MAP *Map
1204 )
1205 {
1206 NET_MAP_ITEM *Item;
1207 LIST_ENTRY *Head;
1208 UINTN Index;
1209
1210 ASSERT (Map != NULL);
1211
1212 Head = &Map->Recycled;
1213
1214 if (IsListEmpty (Head)) {
1215 for (Index = 0; Index < NET_MAP_INCREAMENT; Index++) {
1216 Item = AllocatePool (sizeof (NET_MAP_ITEM));
1217
1218 if (Item == NULL) {
1219 if (Index == 0) {
1220 return NULL;
1221 }
1222
1223 break;
1224 }
1225
1226 InsertHeadList (Head, &Item->Link);
1227 }
1228 }
1229
1230 Item = NET_LIST_HEAD (Head, NET_MAP_ITEM, Link);
1231 NetListRemoveHead (Head);
1232
1233 return Item;
1234 }
1235
1236
1237 /**
1238 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1239
1240 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1241 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1242 pairs in the netmap increase by 1.
1243
1244 If Map is NULL, then ASSERT().
1245
1246 @param[in, out] Map The netmap to insert into.
1247 @param[in] Key The user's key.
1248 @param[in] Value The user's value for the key.
1249
1250 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1251 @retval EFI_SUCCESS The item is inserted to the head.
1252
1253 **/
1254 EFI_STATUS
1255 EFIAPI
1256 NetMapInsertHead (
1257 IN OUT NET_MAP *Map,
1258 IN VOID *Key,
1259 IN VOID *Value OPTIONAL
1260 )
1261 {
1262 NET_MAP_ITEM *Item;
1263
1264 ASSERT (Map != NULL);
1265
1266 Item = NetMapAllocItem (Map);
1267
1268 if (Item == NULL) {
1269 return EFI_OUT_OF_RESOURCES;
1270 }
1271
1272 Item->Key = Key;
1273 Item->Value = Value;
1274 InsertHeadList (&Map->Used, &Item->Link);
1275
1276 Map->Count++;
1277 return EFI_SUCCESS;
1278 }
1279
1280
1281 /**
1282 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1283
1284 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1285 to the tail of the Used doubly linked list. The number of the <Key, Value>
1286 pairs in the netmap increase by 1.
1287
1288 If Map is NULL, then ASSERT().
1289
1290 @param[in, out] Map The netmap to insert into.
1291 @param[in] Key The user's key.
1292 @param[in] Value The user's value for the key.
1293
1294 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1295 @retval EFI_SUCCESS The item is inserted to the tail.
1296
1297 **/
1298 EFI_STATUS
1299 EFIAPI
1300 NetMapInsertTail (
1301 IN OUT NET_MAP *Map,
1302 IN VOID *Key,
1303 IN VOID *Value OPTIONAL
1304 )
1305 {
1306 NET_MAP_ITEM *Item;
1307
1308 ASSERT (Map != NULL);
1309
1310 Item = NetMapAllocItem (Map);
1311
1312 if (Item == NULL) {
1313 return EFI_OUT_OF_RESOURCES;
1314 }
1315
1316 Item->Key = Key;
1317 Item->Value = Value;
1318 InsertTailList (&Map->Used, &Item->Link);
1319
1320 Map->Count++;
1321
1322 return EFI_SUCCESS;
1323 }
1324
1325
1326 /**
1327 Check whether the item is in the Map and return TRUE if it is.
1328
1329 @param[in] Map The netmap to search within.
1330 @param[in] Item The item to search.
1331
1332 @return TRUE if the item is in the netmap, otherwise FALSE.
1333
1334 **/
1335 BOOLEAN
1336 NetItemInMap (
1337 IN NET_MAP *Map,
1338 IN NET_MAP_ITEM *Item
1339 )
1340 {
1341 LIST_ENTRY *ListEntry;
1342
1343 NET_LIST_FOR_EACH (ListEntry, &Map->Used) {
1344 if (ListEntry == &Item->Link) {
1345 return TRUE;
1346 }
1347 }
1348
1349 return FALSE;
1350 }
1351
1352
1353 /**
1354 Find the key in the netmap and returns the point to the item contains the Key.
1355
1356 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1357 item with the key to search. It returns the point to the item contains the Key if found.
1358
1359 If Map is NULL, then ASSERT().
1360
1361 @param[in] Map The netmap to search within.
1362 @param[in] Key The key to search.
1363
1364 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1365
1366 **/
1367 NET_MAP_ITEM *
1368 EFIAPI
1369 NetMapFindKey (
1370 IN NET_MAP *Map,
1371 IN VOID *Key
1372 )
1373 {
1374 LIST_ENTRY *Entry;
1375 NET_MAP_ITEM *Item;
1376
1377 ASSERT (Map != NULL);
1378
1379 NET_LIST_FOR_EACH (Entry, &Map->Used) {
1380 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1381
1382 if (Item->Key == Key) {
1383 return Item;
1384 }
1385 }
1386
1387 return NULL;
1388 }
1389
1390
1391 /**
1392 Remove the node entry of the item from the netmap and return the key of the removed item.
1393
1394 Remove the node entry of the item from the Used doubly linked list of the netmap.
1395 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1396 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1397 Value will point to the value of the item. It returns the key of the removed item.
1398
1399 If Map is NULL, then ASSERT().
1400 If Item is NULL, then ASSERT().
1401 if item in not in the netmap, then ASSERT().
1402
1403 @param[in, out] Map The netmap to remove the item from.
1404 @param[in, out] Item The item to remove.
1405 @param[out] Value The variable to receive the value if not NULL.
1406
1407 @return The key of the removed item.
1408
1409 **/
1410 VOID *
1411 EFIAPI
1412 NetMapRemoveItem (
1413 IN OUT NET_MAP *Map,
1414 IN OUT NET_MAP_ITEM *Item,
1415 OUT VOID **Value OPTIONAL
1416 )
1417 {
1418 ASSERT ((Map != NULL) && (Item != NULL));
1419 ASSERT (NetItemInMap (Map, Item));
1420
1421 RemoveEntryList (&Item->Link);
1422 Map->Count--;
1423 InsertHeadList (&Map->Recycled, &Item->Link);
1424
1425 if (Value != NULL) {
1426 *Value = Item->Value;
1427 }
1428
1429 return Item->Key;
1430 }
1431
1432
1433 /**
1434 Remove the first node entry on the netmap and return the key of the removed item.
1435
1436 Remove the first node entry from the Used doubly linked list of the netmap.
1437 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1438 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1439 parameter Value will point to the value of the item. It returns the key of the removed item.
1440
1441 If Map is NULL, then ASSERT().
1442 If the Used doubly linked list is empty, then ASSERT().
1443
1444 @param[in, out] Map The netmap to remove the head from.
1445 @param[out] Value The variable to receive the value if not NULL.
1446
1447 @return The key of the item removed.
1448
1449 **/
1450 VOID *
1451 EFIAPI
1452 NetMapRemoveHead (
1453 IN OUT NET_MAP *Map,
1454 OUT VOID **Value OPTIONAL
1455 )
1456 {
1457 NET_MAP_ITEM *Item;
1458
1459 //
1460 // Often, it indicates a programming error to remove
1461 // the first entry in an empty list
1462 //
1463 ASSERT (Map && !IsListEmpty (&Map->Used));
1464
1465 Item = NET_LIST_HEAD (&Map->Used, NET_MAP_ITEM, Link);
1466 RemoveEntryList (&Item->Link);
1467 Map->Count--;
1468 InsertHeadList (&Map->Recycled, &Item->Link);
1469
1470 if (Value != NULL) {
1471 *Value = Item->Value;
1472 }
1473
1474 return Item->Key;
1475 }
1476
1477
1478 /**
1479 Remove the last node entry on the netmap and return the key of the removed item.
1480
1481 Remove the last node entry from the Used doubly linked list of the netmap.
1482 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1483 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1484 parameter Value will point to the value of the item. It returns the key of the removed item.
1485
1486 If Map is NULL, then ASSERT().
1487 If the Used doubly linked list is empty, then ASSERT().
1488
1489 @param[in, out] Map The netmap to remove the tail from.
1490 @param[out] Value The variable to receive the value if not NULL.
1491
1492 @return The key of the item removed.
1493
1494 **/
1495 VOID *
1496 EFIAPI
1497 NetMapRemoveTail (
1498 IN OUT NET_MAP *Map,
1499 OUT VOID **Value OPTIONAL
1500 )
1501 {
1502 NET_MAP_ITEM *Item;
1503
1504 //
1505 // Often, it indicates a programming error to remove
1506 // the last entry in an empty list
1507 //
1508 ASSERT (Map && !IsListEmpty (&Map->Used));
1509
1510 Item = NET_LIST_TAIL (&Map->Used, NET_MAP_ITEM, Link);
1511 RemoveEntryList (&Item->Link);
1512 Map->Count--;
1513 InsertHeadList (&Map->Recycled, &Item->Link);
1514
1515 if (Value != NULL) {
1516 *Value = Item->Value;
1517 }
1518
1519 return Item->Key;
1520 }
1521
1522
1523 /**
1524 Iterate through the netmap and call CallBack for each item.
1525
1526 It will contiue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1527 from the loop. It returns the CallBack's last return value. This function is
1528 delete safe for the current item.
1529
1530 If Map is NULL, then ASSERT().
1531 If CallBack is NULL, then ASSERT().
1532
1533 @param[in] Map The Map to iterate through.
1534 @param[in] CallBack The callback function to call for each item.
1535 @param[in] Arg The opaque parameter to the callback.
1536
1537 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1538 return EFI_SUCCESS.
1539 @retval Others It returns the CallBack's last return value.
1540
1541 **/
1542 EFI_STATUS
1543 EFIAPI
1544 NetMapIterate (
1545 IN NET_MAP *Map,
1546 IN NET_MAP_CALLBACK CallBack,
1547 IN VOID *Arg OPTIONAL
1548 )
1549 {
1550
1551 LIST_ENTRY *Entry;
1552 LIST_ENTRY *Next;
1553 LIST_ENTRY *Head;
1554 NET_MAP_ITEM *Item;
1555 EFI_STATUS Result;
1556
1557 ASSERT ((Map != NULL) && (CallBack != NULL));
1558
1559 Head = &Map->Used;
1560
1561 if (IsListEmpty (Head)) {
1562 return EFI_SUCCESS;
1563 }
1564
1565 NET_LIST_FOR_EACH_SAFE (Entry, Next, Head) {
1566 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1567 Result = CallBack (Map, Item, Arg);
1568
1569 if (EFI_ERROR (Result)) {
1570 return Result;
1571 }
1572 }
1573
1574 return EFI_SUCCESS;
1575 }
1576
1577
1578 /**
1579 Internal function to get the child handle of the NIC handle.
1580
1581 @param[in] Controller NIC controller handle.
1582 @param[out] ChildHandle Returned child handle.
1583
1584 @retval EFI_SUCCESS Successfully to get child handle.
1585 @retval Others Failed to get child handle.
1586
1587 **/
1588 EFI_STATUS
1589 NetGetChildHandle (
1590 IN EFI_HANDLE Controller,
1591 OUT EFI_HANDLE *ChildHandle
1592 )
1593 {
1594 EFI_STATUS Status;
1595 EFI_HANDLE *Handles;
1596 UINTN HandleCount;
1597 UINTN Index;
1598 EFI_DEVICE_PATH_PROTOCOL *ChildDeviceDevicePath;
1599 VENDOR_DEVICE_PATH *VendorDeviceNode;
1600
1601 //
1602 // Locate all EFI Hii Config Access protocols
1603 //
1604 Status = gBS->LocateHandleBuffer (
1605 ByProtocol,
1606 &gEfiHiiConfigAccessProtocolGuid,
1607 NULL,
1608 &HandleCount,
1609 &Handles
1610 );
1611 if (EFI_ERROR (Status) || (HandleCount == 0)) {
1612 return Status;
1613 }
1614
1615 Status = EFI_NOT_FOUND;
1616
1617 for (Index = 0; Index < HandleCount; Index++) {
1618
1619 Status = EfiTestChildHandle (Controller, Handles[Index], &gEfiManagedNetworkServiceBindingProtocolGuid);
1620 if (!EFI_ERROR (Status)) {
1621 //
1622 // Get device path on the child handle
1623 //
1624 Status = gBS->HandleProtocol (
1625 Handles[Index],
1626 &gEfiDevicePathProtocolGuid,
1627 (VOID **) &ChildDeviceDevicePath
1628 );
1629
1630 if (!EFI_ERROR (Status)) {
1631 while (!IsDevicePathEnd (ChildDeviceDevicePath)) {
1632 ChildDeviceDevicePath = NextDevicePathNode (ChildDeviceDevicePath);
1633 //
1634 // Parse one instance
1635 //
1636 if (ChildDeviceDevicePath->Type == HARDWARE_DEVICE_PATH &&
1637 ChildDeviceDevicePath->SubType == HW_VENDOR_DP) {
1638 VendorDeviceNode = (VENDOR_DEVICE_PATH *) ChildDeviceDevicePath;
1639 if (CompareMem (&VendorDeviceNode->Guid, &gEfiNicIp4ConfigVariableGuid, sizeof (EFI_GUID)) == 0) {
1640 //
1641 // Found item matched gEfiNicIp4ConfigVariableGuid
1642 //
1643 *ChildHandle = Handles[Index];
1644 FreePool (Handles);
1645 return EFI_SUCCESS;
1646 }
1647 }
1648 }
1649 }
1650 }
1651 }
1652
1653 FreePool (Handles);
1654 return Status;
1655 }
1656
1657
1658 /**
1659 This is the default unload handle for all the network drivers.
1660
1661 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1662 Uninstall all the protocols installed in the driver entry point.
1663
1664 @param[in] ImageHandle The drivers' driver image.
1665
1666 @retval EFI_SUCCESS The image is unloaded.
1667 @retval Others Failed to unload the image.
1668
1669 **/
1670 EFI_STATUS
1671 EFIAPI
1672 NetLibDefaultUnload (
1673 IN EFI_HANDLE ImageHandle
1674 )
1675 {
1676 EFI_STATUS Status;
1677 EFI_HANDLE *DeviceHandleBuffer;
1678 UINTN DeviceHandleCount;
1679 UINTN Index;
1680 EFI_DRIVER_BINDING_PROTOCOL *DriverBinding;
1681 EFI_COMPONENT_NAME_PROTOCOL *ComponentName;
1682 EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2;
1683
1684 //
1685 // Get the list of all the handles in the handle database.
1686 // If there is an error getting the list, then the unload
1687 // operation fails.
1688 //
1689 Status = gBS->LocateHandleBuffer (
1690 AllHandles,
1691 NULL,
1692 NULL,
1693 &DeviceHandleCount,
1694 &DeviceHandleBuffer
1695 );
1696
1697 if (EFI_ERROR (Status)) {
1698 return Status;
1699 }
1700
1701 //
1702 // Disconnect the driver specified by ImageHandle from all
1703 // the devices in the handle database.
1704 //
1705 for (Index = 0; Index < DeviceHandleCount; Index++) {
1706 Status = gBS->DisconnectController (
1707 DeviceHandleBuffer[Index],
1708 ImageHandle,
1709 NULL
1710 );
1711 }
1712
1713 //
1714 // Uninstall all the protocols installed in the driver entry point
1715 //
1716 for (Index = 0; Index < DeviceHandleCount; Index++) {
1717 Status = gBS->HandleProtocol (
1718 DeviceHandleBuffer[Index],
1719 &gEfiDriverBindingProtocolGuid,
1720 (VOID **) &DriverBinding
1721 );
1722
1723 if (EFI_ERROR (Status)) {
1724 continue;
1725 }
1726
1727 if (DriverBinding->ImageHandle != ImageHandle) {
1728 continue;
1729 }
1730
1731 gBS->UninstallProtocolInterface (
1732 ImageHandle,
1733 &gEfiDriverBindingProtocolGuid,
1734 DriverBinding
1735 );
1736 Status = gBS->HandleProtocol (
1737 DeviceHandleBuffer[Index],
1738 &gEfiComponentNameProtocolGuid,
1739 (VOID **) &ComponentName
1740 );
1741 if (!EFI_ERROR (Status)) {
1742 gBS->UninstallProtocolInterface (
1743 ImageHandle,
1744 &gEfiComponentNameProtocolGuid,
1745 ComponentName
1746 );
1747 }
1748
1749 Status = gBS->HandleProtocol (
1750 DeviceHandleBuffer[Index],
1751 &gEfiComponentName2ProtocolGuid,
1752 (VOID **) &ComponentName2
1753 );
1754 if (!EFI_ERROR (Status)) {
1755 gBS->UninstallProtocolInterface (
1756 ImageHandle,
1757 &gEfiComponentName2ProtocolGuid,
1758 ComponentName2
1759 );
1760 }
1761 }
1762
1763 //
1764 // Free the buffer containing the list of handles from the handle database
1765 //
1766 if (DeviceHandleBuffer != NULL) {
1767 gBS->FreePool (DeviceHandleBuffer);
1768 }
1769
1770 return EFI_SUCCESS;
1771 }
1772
1773
1774
1775 /**
1776 Create a child of the service that is identified by ServiceBindingGuid.
1777
1778 Get the ServiceBinding Protocol first, then use it to create a child.
1779
1780 If ServiceBindingGuid is NULL, then ASSERT().
1781 If ChildHandle is NULL, then ASSERT().
1782
1783 @param[in] Controller The controller which has the service installed.
1784 @param[in] Image The image handle used to open service.
1785 @param[in] ServiceBindingGuid The service's Guid.
1786 @param[in, out] ChildHandle The handle to receive the create child.
1787
1788 @retval EFI_SUCCESS The child is successfully created.
1789 @retval Others Failed to create the child.
1790
1791 **/
1792 EFI_STATUS
1793 EFIAPI
1794 NetLibCreateServiceChild (
1795 IN EFI_HANDLE Controller,
1796 IN EFI_HANDLE Image,
1797 IN EFI_GUID *ServiceBindingGuid,
1798 IN OUT EFI_HANDLE *ChildHandle
1799 )
1800 {
1801 EFI_STATUS Status;
1802 EFI_SERVICE_BINDING_PROTOCOL *Service;
1803
1804
1805 ASSERT ((ServiceBindingGuid != NULL) && (ChildHandle != NULL));
1806
1807 //
1808 // Get the ServiceBinding Protocol
1809 //
1810 Status = gBS->OpenProtocol (
1811 Controller,
1812 ServiceBindingGuid,
1813 (VOID **) &Service,
1814 Image,
1815 Controller,
1816 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1817 );
1818
1819 if (EFI_ERROR (Status)) {
1820 return Status;
1821 }
1822
1823 //
1824 // Create a child
1825 //
1826 Status = Service->CreateChild (Service, ChildHandle);
1827 return Status;
1828 }
1829
1830
1831 /**
1832 Destory a child of the service that is identified by ServiceBindingGuid.
1833
1834 Get the ServiceBinding Protocol first, then use it to destroy a child.
1835
1836 If ServiceBindingGuid is NULL, then ASSERT().
1837
1838 @param[in] Controller The controller which has the service installed.
1839 @param[in] Image The image handle used to open service.
1840 @param[in] ServiceBindingGuid The service's Guid.
1841 @param[in] ChildHandle The child to destory.
1842
1843 @retval EFI_SUCCESS The child is successfully destoried.
1844 @retval Others Failed to destory the child.
1845
1846 **/
1847 EFI_STATUS
1848 EFIAPI
1849 NetLibDestroyServiceChild (
1850 IN EFI_HANDLE Controller,
1851 IN EFI_HANDLE Image,
1852 IN EFI_GUID *ServiceBindingGuid,
1853 IN EFI_HANDLE ChildHandle
1854 )
1855 {
1856 EFI_STATUS Status;
1857 EFI_SERVICE_BINDING_PROTOCOL *Service;
1858
1859 ASSERT (ServiceBindingGuid != NULL);
1860
1861 //
1862 // Get the ServiceBinding Protocol
1863 //
1864 Status = gBS->OpenProtocol (
1865 Controller,
1866 ServiceBindingGuid,
1867 (VOID **) &Service,
1868 Image,
1869 Controller,
1870 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1871 );
1872
1873 if (EFI_ERROR (Status)) {
1874 return Status;
1875 }
1876
1877 //
1878 // destory the child
1879 //
1880 Status = Service->DestroyChild (Service, ChildHandle);
1881 return Status;
1882 }
1883
1884 /**
1885 Get handle with Simple Network Protocol installed on it.
1886
1887 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
1888 If Simple Network Protocol is already installed on the ServiceHandle, the
1889 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
1890 try to find its parent handle with SNP installed.
1891
1892 @param[in] ServiceHandle The handle where network service binding protocols are
1893 installed on.
1894 @param[out] Snp The pointer to store the address of the SNP instance.
1895 This is an optional parameter that may be NULL.
1896
1897 @return The SNP handle, or NULL if not found.
1898
1899 **/
1900 EFI_HANDLE
1901 EFIAPI
1902 NetLibGetSnpHandle (
1903 IN EFI_HANDLE ServiceHandle,
1904 OUT EFI_SIMPLE_NETWORK_PROTOCOL **Snp OPTIONAL
1905 )
1906 {
1907 EFI_STATUS Status;
1908 EFI_SIMPLE_NETWORK_PROTOCOL *SnpInstance;
1909 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1910 EFI_HANDLE SnpHandle;
1911
1912 //
1913 // Try to open SNP from ServiceHandle
1914 //
1915 SnpInstance = NULL;
1916 Status = gBS->HandleProtocol (ServiceHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
1917 if (!EFI_ERROR (Status)) {
1918 if (Snp != NULL) {
1919 *Snp = SnpInstance;
1920 }
1921 return ServiceHandle;
1922 }
1923
1924 //
1925 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
1926 //
1927 DevicePath = DevicePathFromHandle (ServiceHandle);
1928 if (DevicePath == NULL) {
1929 return NULL;
1930 }
1931
1932 SnpHandle = NULL;
1933 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &DevicePath, &SnpHandle);
1934 if (EFI_ERROR (Status)) {
1935 //
1936 // Failed to find SNP handle
1937 //
1938 return NULL;
1939 }
1940
1941 Status = gBS->HandleProtocol (SnpHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
1942 if (!EFI_ERROR (Status)) {
1943 if (Snp != NULL) {
1944 *Snp = SnpInstance;
1945 }
1946 return SnpHandle;
1947 }
1948
1949 return NULL;
1950 }
1951
1952 /**
1953 Retrieve VLAN ID of a VLAN device handle.
1954
1955 Search VLAN device path node in Device Path of specified ServiceHandle and
1956 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
1957 is not a VLAN device handle, and 0 will be returned.
1958
1959 @param[in] ServiceHandle The handle where network service binding protocols are
1960 installed on.
1961
1962 @return VLAN ID of the device handle, or 0 if not a VLAN device.
1963
1964 **/
1965 UINT16
1966 EFIAPI
1967 NetLibGetVlanId (
1968 IN EFI_HANDLE ServiceHandle
1969 )
1970 {
1971 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
1972 EFI_DEVICE_PATH_PROTOCOL *Node;
1973
1974 DevicePath = DevicePathFromHandle (ServiceHandle);
1975 if (DevicePath == NULL) {
1976 return 0;
1977 }
1978
1979 Node = DevicePath;
1980 while (!IsDevicePathEnd (Node)) {
1981 if (Node->Type == MESSAGING_DEVICE_PATH && Node->SubType == MSG_VLAN_DP) {
1982 return ((VLAN_DEVICE_PATH *) Node)->VlanId;
1983 }
1984 Node = NextDevicePathNode (Node);
1985 }
1986
1987 return 0;
1988 }
1989
1990 /**
1991 Find VLAN device handle with specified VLAN ID.
1992
1993 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
1994 This function will append VLAN device path node to the parent device path,
1995 and then use LocateDevicePath() to find the correct VLAN device handle.
1996
1997 @param[in] ControllerHandle The handle where network service binding protocols are
1998 installed on.
1999 @param[in] VlanId The configured VLAN ID for the VLAN device.
2000
2001 @return The VLAN device handle, or NULL if not found.
2002
2003 **/
2004 EFI_HANDLE
2005 EFIAPI
2006 NetLibGetVlanHandle (
2007 IN EFI_HANDLE ControllerHandle,
2008 IN UINT16 VlanId
2009 )
2010 {
2011 EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath;
2012 EFI_DEVICE_PATH_PROTOCOL *VlanDevicePath;
2013 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2014 VLAN_DEVICE_PATH VlanNode;
2015 EFI_HANDLE Handle;
2016
2017 ParentDevicePath = DevicePathFromHandle (ControllerHandle);
2018 if (ParentDevicePath == NULL) {
2019 return NULL;
2020 }
2021
2022 //
2023 // Construct VLAN device path
2024 //
2025 CopyMem (&VlanNode, &mNetVlanDevicePathTemplate, sizeof (VLAN_DEVICE_PATH));
2026 VlanNode.VlanId = VlanId;
2027 VlanDevicePath = AppendDevicePathNode (
2028 ParentDevicePath,
2029 (EFI_DEVICE_PATH_PROTOCOL *) &VlanNode
2030 );
2031 if (VlanDevicePath == NULL) {
2032 return NULL;
2033 }
2034
2035 //
2036 // Find VLAN device handle
2037 //
2038 Handle = NULL;
2039 DevicePath = VlanDevicePath;
2040 gBS->LocateDevicePath (
2041 &gEfiDevicePathProtocolGuid,
2042 &DevicePath,
2043 &Handle
2044 );
2045 if (!IsDevicePathEnd (DevicePath)) {
2046 //
2047 // Device path is not exactly match
2048 //
2049 Handle = NULL;
2050 }
2051
2052 FreePool (VlanDevicePath);
2053 return Handle;
2054 }
2055
2056 /**
2057 Get MAC address associated with the network service handle.
2058
2059 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2060 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2061 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2062
2063 @param[in] ServiceHandle The handle where network service binding protocols are
2064 installed on.
2065 @param[out] MacAddress The pointer to store the returned MAC address.
2066 @param[out] AddressSize The length of returned MAC address.
2067
2068 @retval EFI_SUCCESS MAC address is returned successfully.
2069 @retval Others Failed to get SNP mode data.
2070
2071 **/
2072 EFI_STATUS
2073 EFIAPI
2074 NetLibGetMacAddress (
2075 IN EFI_HANDLE ServiceHandle,
2076 OUT EFI_MAC_ADDRESS *MacAddress,
2077 OUT UINTN *AddressSize
2078 )
2079 {
2080 EFI_STATUS Status;
2081 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2082 EFI_SIMPLE_NETWORK_MODE *SnpMode;
2083 EFI_SIMPLE_NETWORK_MODE SnpModeData;
2084 EFI_MANAGED_NETWORK_PROTOCOL *Mnp;
2085 EFI_SERVICE_BINDING_PROTOCOL *MnpSb;
2086 EFI_HANDLE *SnpHandle;
2087 EFI_HANDLE MnpChildHandle;
2088
2089 ASSERT (MacAddress != NULL);
2090 ASSERT (AddressSize != NULL);
2091
2092 //
2093 // Try to get SNP handle
2094 //
2095 Snp = NULL;
2096 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2097 if (SnpHandle != NULL) {
2098 //
2099 // SNP found, use it directly
2100 //
2101 SnpMode = Snp->Mode;
2102 } else {
2103 //
2104 // Failed to get SNP handle, try to get MAC address from MNP
2105 //
2106 MnpChildHandle = NULL;
2107 Status = gBS->HandleProtocol (
2108 ServiceHandle,
2109 &gEfiManagedNetworkServiceBindingProtocolGuid,
2110 (VOID **) &MnpSb
2111 );
2112 if (EFI_ERROR (Status)) {
2113 return Status;
2114 }
2115
2116 //
2117 // Create a MNP child
2118 //
2119 Status = MnpSb->CreateChild (MnpSb, &MnpChildHandle);
2120 if (EFI_ERROR (Status)) {
2121 return Status;
2122 }
2123
2124 //
2125 // Open MNP protocol
2126 //
2127 Status = gBS->HandleProtocol (
2128 MnpChildHandle,
2129 &gEfiManagedNetworkProtocolGuid,
2130 (VOID **) &Mnp
2131 );
2132 if (EFI_ERROR (Status)) {
2133 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2134 return Status;
2135 }
2136
2137 //
2138 // Try to get SNP mode from MNP
2139 //
2140 Status = Mnp->GetModeData (Mnp, NULL, &SnpModeData);
2141 if (EFI_ERROR (Status)) {
2142 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2143 return Status;
2144 }
2145 SnpMode = &SnpModeData;
2146
2147 //
2148 // Destroy the MNP child
2149 //
2150 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2151 }
2152
2153 *AddressSize = SnpMode->HwAddressSize;
2154 CopyMem (MacAddress->Addr, SnpMode->CurrentAddress.Addr, SnpMode->HwAddressSize);
2155
2156 return EFI_SUCCESS;
2157 }
2158
2159 /**
2160 Convert MAC address of the NIC associated with specified Service Binding Handle
2161 to a unicode string. Callers are responsible for freeing the string storage.
2162
2163 Locate simple network protocol associated with the Service Binding Handle and
2164 get the mac address from SNP. Then convert the mac address into a unicode
2165 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2166 Plus one unicode character for the null-terminator.
2167
2168 @param[in] ServiceHandle The handle where network service binding protocol is
2169 installed on.
2170 @param[in] ImageHandle The image handle used to act as the agent handle to
2171 get the simple network protocol.
2172 @param[out] MacString The pointer to store the address of the string
2173 representation of the mac address.
2174
2175 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2176 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2177 @retval Others Failed to open the simple network protocol.
2178
2179 **/
2180 EFI_STATUS
2181 EFIAPI
2182 NetLibGetMacString (
2183 IN EFI_HANDLE ServiceHandle,
2184 IN EFI_HANDLE ImageHandle,
2185 OUT CHAR16 **MacString
2186 )
2187 {
2188 EFI_STATUS Status;
2189 EFI_MAC_ADDRESS MacAddress;
2190 UINT8 *HwAddress;
2191 UINTN HwAddressSize;
2192 UINT16 VlanId;
2193 CHAR16 *String;
2194 UINTN Index;
2195
2196 ASSERT (MacString != NULL);
2197
2198 //
2199 // Get MAC address of the network device
2200 //
2201 Status = NetLibGetMacAddress (ServiceHandle, &MacAddress, &HwAddressSize);
2202 if (EFI_ERROR (Status)) {
2203 return Status;
2204 }
2205
2206 //
2207 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2208 // If VLAN is configured, it will need extra 5 characters like "\0005".
2209 // Plus one unicode character for the null-terminator.
2210 //
2211 String = AllocateZeroPool ((2 * HwAddressSize + 5 + 1) * sizeof (CHAR16));
2212 if (String == NULL) {
2213 return EFI_OUT_OF_RESOURCES;
2214 }
2215 *MacString = String;
2216
2217 //
2218 // Convert the MAC address into a unicode string.
2219 //
2220 HwAddress = &MacAddress.Addr[0];
2221 for (Index = 0; Index < HwAddressSize; Index++) {
2222 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, *(HwAddress++), 2);
2223 }
2224
2225 //
2226 // Append VLAN ID if any
2227 //
2228 VlanId = NetLibGetVlanId (ServiceHandle);
2229 if (VlanId != 0) {
2230 *String++ = L'\\';
2231 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, VlanId, 4);
2232 }
2233
2234 //
2235 // Null terminate the Unicode string
2236 //
2237 *String = L'\0';
2238
2239 return EFI_SUCCESS;
2240 }
2241
2242 /**
2243 Detect media status for specified network device.
2244
2245 The underlying UNDI driver may or may not support reporting media status from
2246 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2247 will try to invoke Snp->GetStatus() to get the media status: if media already
2248 present, it return directly; if media not present, it will stop SNP and then
2249 restart SNP to get the latest media status, this give chance to get the correct
2250 media status for old UNDI driver which doesn't support reporting media status
2251 from GET_STATUS command.
2252 Note: there will be two limitations for current algorithm:
2253 1) for UNDI with this capability, in case of cable is not attached, there will
2254 be an redundant Stop/Start() process;
2255 2) for UNDI without this capability, in case that network cable is attached when
2256 Snp->Initialize() is invoked while network cable is unattached later,
2257 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2258 apps to wait for timeout time.
2259
2260 @param[in] ServiceHandle The handle where network service binding protocols are
2261 installed on.
2262 @param[out] MediaPresent The pointer to store the media status.
2263
2264 @retval EFI_SUCCESS Media detection success.
2265 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2266 @retval EFI_UNSUPPORTED Network device does not support media detection.
2267 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2268
2269 **/
2270 EFI_STATUS
2271 EFIAPI
2272 NetLibDetectMedia (
2273 IN EFI_HANDLE ServiceHandle,
2274 OUT BOOLEAN *MediaPresent
2275 )
2276 {
2277 EFI_STATUS Status;
2278 EFI_HANDLE SnpHandle;
2279 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2280 UINT32 InterruptStatus;
2281 UINT32 OldState;
2282 EFI_MAC_ADDRESS *MCastFilter;
2283 UINT32 MCastFilterCount;
2284 UINT32 EnableFilterBits;
2285 UINT32 DisableFilterBits;
2286 BOOLEAN ResetMCastFilters;
2287
2288 ASSERT (MediaPresent != NULL);
2289
2290 //
2291 // Get SNP handle
2292 //
2293 Snp = NULL;
2294 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2295 if (SnpHandle == NULL) {
2296 return EFI_INVALID_PARAMETER;
2297 }
2298
2299 //
2300 // Check whether SNP support media detection
2301 //
2302 if (!Snp->Mode->MediaPresentSupported) {
2303 return EFI_UNSUPPORTED;
2304 }
2305
2306 //
2307 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2308 //
2309 Status = Snp->GetStatus (Snp, &InterruptStatus, NULL);
2310 if (EFI_ERROR (Status)) {
2311 return Status;
2312 }
2313
2314 if (Snp->Mode->MediaPresent) {
2315 //
2316 // Media is present, return directly
2317 //
2318 *MediaPresent = TRUE;
2319 return EFI_SUCCESS;
2320 }
2321
2322 //
2323 // Till now, GetStatus() report no media; while, in case UNDI not support
2324 // reporting media status from GetStatus(), this media status may be incorrect.
2325 // So, we will stop SNP and then restart it to get the correct media status.
2326 //
2327 OldState = Snp->Mode->State;
2328 if (OldState >= EfiSimpleNetworkMaxState) {
2329 return EFI_DEVICE_ERROR;
2330 }
2331
2332 MCastFilter = NULL;
2333
2334 if (OldState == EfiSimpleNetworkInitialized) {
2335 //
2336 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2337 //
2338
2339 //
2340 // Backup current SNP receive filter settings
2341 //
2342 EnableFilterBits = Snp->Mode->ReceiveFilterSetting;
2343 DisableFilterBits = Snp->Mode->ReceiveFilterMask ^ EnableFilterBits;
2344
2345 ResetMCastFilters = TRUE;
2346 MCastFilterCount = Snp->Mode->MCastFilterCount;
2347 if (MCastFilterCount != 0) {
2348 MCastFilter = AllocateCopyPool (
2349 MCastFilterCount * sizeof (EFI_MAC_ADDRESS),
2350 Snp->Mode->MCastFilter
2351 );
2352 ASSERT (MCastFilter != NULL);
2353
2354 ResetMCastFilters = FALSE;
2355 }
2356
2357 //
2358 // Shutdown/Stop the simple network
2359 //
2360 Status = Snp->Shutdown (Snp);
2361 if (!EFI_ERROR (Status)) {
2362 Status = Snp->Stop (Snp);
2363 }
2364 if (EFI_ERROR (Status)) {
2365 goto Exit;
2366 }
2367
2368 //
2369 // Start/Initialize the simple network
2370 //
2371 Status = Snp->Start (Snp);
2372 if (!EFI_ERROR (Status)) {
2373 Status = Snp->Initialize (Snp, 0, 0);
2374 }
2375 if (EFI_ERROR (Status)) {
2376 goto Exit;
2377 }
2378
2379 //
2380 // Here we get the correct media status
2381 //
2382 *MediaPresent = Snp->Mode->MediaPresent;
2383
2384 //
2385 // Restore SNP receive filter settings
2386 //
2387 Status = Snp->ReceiveFilters (
2388 Snp,
2389 EnableFilterBits,
2390 DisableFilterBits,
2391 ResetMCastFilters,
2392 MCastFilterCount,
2393 MCastFilter
2394 );
2395
2396 if (MCastFilter != NULL) {
2397 FreePool (MCastFilter);
2398 }
2399
2400 return Status;
2401 }
2402
2403 //
2404 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2405 //
2406 if (OldState == EfiSimpleNetworkStopped) {
2407 //
2408 // SNP not start yet, start it
2409 //
2410 Status = Snp->Start (Snp);
2411 if (EFI_ERROR (Status)) {
2412 goto Exit;
2413 }
2414 }
2415
2416 //
2417 // Initialize the simple network
2418 //
2419 Status = Snp->Initialize (Snp, 0, 0);
2420 if (EFI_ERROR (Status)) {
2421 Status = EFI_DEVICE_ERROR;
2422 goto Exit;
2423 }
2424
2425 //
2426 // Here we get the correct media status
2427 //
2428 *MediaPresent = Snp->Mode->MediaPresent;
2429
2430 //
2431 // Shut down the simple network
2432 //
2433 Snp->Shutdown (Snp);
2434
2435 Exit:
2436 if (OldState == EfiSimpleNetworkStopped) {
2437 //
2438 // Original SNP sate is Stopped, restore to original state
2439 //
2440 Snp->Stop (Snp);
2441 }
2442
2443 if (MCastFilter != NULL) {
2444 FreePool (MCastFilter);
2445 }
2446
2447 return Status;
2448 }
2449
2450 /**
2451 Check the default address used by the IPv4 driver is static or dynamic (acquired
2452 from DHCP).
2453
2454 If the controller handle does not have the NIC Ip4 Config Protocol installed, the
2455 default address is static. If the EFI variable to save the configuration is not found,
2456 the default address is static. Otherwise, get the result from the EFI variable which
2457 saving the configuration.
2458
2459 @param[in] Controller The controller handle which has the NIC Ip4 Config Protocol
2460 relative with the default address to judge.
2461
2462 @retval TRUE If the default address is static.
2463 @retval FALSE If the default address is acquired from DHCP.
2464
2465 **/
2466 BOOLEAN
2467 NetLibDefaultAddressIsStatic (
2468 IN EFI_HANDLE Controller
2469 )
2470 {
2471 EFI_STATUS Status;
2472 EFI_HII_CONFIG_ROUTING_PROTOCOL *HiiConfigRouting;
2473 UINTN Len;
2474 NIC_IP4_CONFIG_INFO *ConfigInfo;
2475 BOOLEAN IsStatic;
2476 EFI_STRING ConfigHdr;
2477 EFI_STRING ConfigResp;
2478 EFI_STRING AccessProgress;
2479 EFI_STRING AccessResults;
2480 EFI_STRING String;
2481 EFI_HANDLE ChildHandle;
2482
2483 ConfigInfo = NULL;
2484 ConfigHdr = NULL;
2485 ConfigResp = NULL;
2486 AccessProgress = NULL;
2487 AccessResults = NULL;
2488 IsStatic = TRUE;
2489
2490 Status = gBS->LocateProtocol (
2491 &gEfiHiiConfigRoutingProtocolGuid,
2492 NULL,
2493 (VOID **) &HiiConfigRouting
2494 );
2495 if (EFI_ERROR (Status)) {
2496 return TRUE;
2497 }
2498
2499 Status = NetGetChildHandle (Controller, &ChildHandle);
2500 if (EFI_ERROR (Status)) {
2501 return TRUE;
2502 }
2503
2504 //
2505 // Construct config request string header
2506 //
2507 ConfigHdr = HiiConstructConfigHdr (&gEfiNicIp4ConfigVariableGuid, EFI_NIC_IP4_CONFIG_VARIABLE, ChildHandle);
2508 if (ConfigHdr == NULL) {
2509 return TRUE;
2510 }
2511
2512 Len = StrLen (ConfigHdr);
2513 ConfigResp = AllocateZeroPool ((Len + NIC_ITEM_CONFIG_SIZE * 2 + 100) * sizeof (CHAR16));
2514 if (ConfigResp == NULL) {
2515 goto ON_EXIT;
2516 }
2517 StrCpy (ConfigResp, ConfigHdr);
2518
2519 String = ConfigResp + Len;
2520 UnicodeSPrint (
2521 String,
2522 (8 + 4 + 7 + 4 + 1) * sizeof (CHAR16),
2523 L"&OFFSET=%04X&WIDTH=%04X",
2524 OFFSET_OF (NIC_IP4_CONFIG_INFO, Source),
2525 sizeof (UINT32)
2526 );
2527
2528 Status = HiiConfigRouting->ExtractConfig (
2529 HiiConfigRouting,
2530 ConfigResp,
2531 &AccessProgress,
2532 &AccessResults
2533 );
2534 if (EFI_ERROR (Status)) {
2535 goto ON_EXIT;
2536 }
2537
2538 ConfigInfo = AllocateZeroPool (NIC_ITEM_CONFIG_SIZE);
2539 if (ConfigInfo == NULL) {
2540 goto ON_EXIT;
2541 }
2542
2543 ConfigInfo->Source = IP4_CONFIG_SOURCE_STATIC;
2544 Len = NIC_ITEM_CONFIG_SIZE;
2545 Status = HiiConfigRouting->ConfigToBlock (
2546 HiiConfigRouting,
2547 AccessResults,
2548 (UINT8 *) ConfigInfo,
2549 &Len,
2550 &AccessProgress
2551 );
2552 if (EFI_ERROR (Status)) {
2553 goto ON_EXIT;
2554 }
2555
2556 IsStatic = (BOOLEAN) (ConfigInfo->Source == IP4_CONFIG_SOURCE_STATIC);
2557
2558 ON_EXIT:
2559
2560 if (AccessResults != NULL) {
2561 FreePool (AccessResults);
2562 }
2563 if (ConfigInfo != NULL) {
2564 FreePool (ConfigInfo);
2565 }
2566 if (ConfigResp != NULL) {
2567 FreePool (ConfigResp);
2568 }
2569 if (ConfigHdr != NULL) {
2570 FreePool (ConfigHdr);
2571 }
2572
2573 return IsStatic;
2574 }
2575
2576 /**
2577 Create an IPv4 device path node.
2578
2579 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2580 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2581 The length of the IPv4 device path node in bytes is 19.
2582 Get other info from parameters to make up the whole IPv4 device path node.
2583
2584 @param[in, out] Node Pointer to the IPv4 device path node.
2585 @param[in] Controller The controller handle.
2586 @param[in] LocalIp The local IPv4 address.
2587 @param[in] LocalPort The local port.
2588 @param[in] RemoteIp The remote IPv4 address.
2589 @param[in] RemotePort The remote port.
2590 @param[in] Protocol The protocol type in the IP header.
2591 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2592
2593 **/
2594 VOID
2595 EFIAPI
2596 NetLibCreateIPv4DPathNode (
2597 IN OUT IPv4_DEVICE_PATH *Node,
2598 IN EFI_HANDLE Controller,
2599 IN IP4_ADDR LocalIp,
2600 IN UINT16 LocalPort,
2601 IN IP4_ADDR RemoteIp,
2602 IN UINT16 RemotePort,
2603 IN UINT16 Protocol,
2604 IN BOOLEAN UseDefaultAddress
2605 )
2606 {
2607 Node->Header.Type = MESSAGING_DEVICE_PATH;
2608 Node->Header.SubType = MSG_IPv4_DP;
2609 SetDevicePathNodeLength (&Node->Header, 19);
2610
2611 CopyMem (&Node->LocalIpAddress, &LocalIp, sizeof (EFI_IPv4_ADDRESS));
2612 CopyMem (&Node->RemoteIpAddress, &RemoteIp, sizeof (EFI_IPv4_ADDRESS));
2613
2614 Node->LocalPort = LocalPort;
2615 Node->RemotePort = RemotePort;
2616
2617 Node->Protocol = Protocol;
2618
2619 if (!UseDefaultAddress) {
2620 Node->StaticIpAddress = TRUE;
2621 } else {
2622 Node->StaticIpAddress = NetLibDefaultAddressIsStatic (Controller);
2623 }
2624 }
2625
2626 /**
2627 Create an IPv6 device path node.
2628
2629 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2630 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2631 Get other info from parameters to make up the whole IPv6 device path node.
2632
2633 @param[in, out] Node Pointer to the IPv6 device path node.
2634 @param[in] Controller The controller handle.
2635 @param[in] LocalIp The local IPv6 address.
2636 @param[in] LocalPort The local port.
2637 @param[in] RemoteIp The remote IPv6 address.
2638 @param[in] RemotePort The remote port.
2639 @param[in] Protocol The protocol type in the IP header.
2640
2641 **/
2642 VOID
2643 EFIAPI
2644 NetLibCreateIPv6DPathNode (
2645 IN OUT IPv6_DEVICE_PATH *Node,
2646 IN EFI_HANDLE Controller,
2647 IN EFI_IPv6_ADDRESS *LocalIp,
2648 IN UINT16 LocalPort,
2649 IN EFI_IPv6_ADDRESS *RemoteIp,
2650 IN UINT16 RemotePort,
2651 IN UINT16 Protocol
2652 )
2653 {
2654 Node->Header.Type = MESSAGING_DEVICE_PATH;
2655 Node->Header.SubType = MSG_IPv6_DP;
2656 SetDevicePathNodeLength (&Node->Header, sizeof (IPv6_DEVICE_PATH));
2657
2658 CopyMem (&Node->LocalIpAddress, LocalIp, sizeof (EFI_IPv6_ADDRESS));
2659 CopyMem (&Node->RemoteIpAddress, RemoteIp, sizeof (EFI_IPv6_ADDRESS));
2660
2661 Node->LocalPort = LocalPort;
2662 Node->RemotePort = RemotePort;
2663
2664 Node->Protocol = Protocol;
2665 Node->StaticIpAddress = FALSE;
2666 }
2667
2668 /**
2669 Find the UNDI/SNP handle from controller and protocol GUID.
2670
2671 For example, IP will open a MNP child to transmit/receive
2672 packets, when MNP is stopped, IP should also be stopped. IP
2673 needs to find its own private data which is related the IP's
2674 service binding instance that is install on UNDI/SNP handle.
2675 Now, the controller is either a MNP or ARP child handle. But
2676 IP opens these handle BY_DRIVER, use that info, we can get the
2677 UNDI/SNP handle.
2678
2679 @param[in] Controller Then protocol handle to check.
2680 @param[in] ProtocolGuid The protocol that is related with the handle.
2681
2682 @return The UNDI/SNP handle or NULL for errors.
2683
2684 **/
2685 EFI_HANDLE
2686 EFIAPI
2687 NetLibGetNicHandle (
2688 IN EFI_HANDLE Controller,
2689 IN EFI_GUID *ProtocolGuid
2690 )
2691 {
2692 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenBuffer;
2693 EFI_HANDLE Handle;
2694 EFI_STATUS Status;
2695 UINTN OpenCount;
2696 UINTN Index;
2697
2698 Status = gBS->OpenProtocolInformation (
2699 Controller,
2700 ProtocolGuid,
2701 &OpenBuffer,
2702 &OpenCount
2703 );
2704
2705 if (EFI_ERROR (Status)) {
2706 return NULL;
2707 }
2708
2709 Handle = NULL;
2710
2711 for (Index = 0; Index < OpenCount; Index++) {
2712 if ((OpenBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {
2713 Handle = OpenBuffer[Index].ControllerHandle;
2714 break;
2715 }
2716 }
2717
2718 gBS->FreePool (OpenBuffer);
2719 return Handle;
2720 }
2721
2722 /**
2723 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2724
2725 @param[in] String The pointer to the Ascii string.
2726 @param[out] Ip4Address The pointer to the converted IPv4 address.
2727
2728 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2729 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2730
2731 **/
2732 EFI_STATUS
2733 EFIAPI
2734 NetLibAsciiStrToIp4 (
2735 IN CONST CHAR8 *String,
2736 OUT EFI_IPv4_ADDRESS *Ip4Address
2737 )
2738 {
2739 UINT8 Index;
2740 CHAR8 *Ip4Str;
2741 CHAR8 *TempStr;
2742 UINTN NodeVal;
2743
2744 if ((String == NULL) || (Ip4Address == NULL)) {
2745 return EFI_INVALID_PARAMETER;
2746 }
2747
2748 Ip4Str = (CHAR8 *) String;
2749
2750 for (Index = 0; Index < 4; Index++) {
2751 TempStr = Ip4Str;
2752
2753 while ((*Ip4Str != '\0') && (*Ip4Str != '.')) {
2754 Ip4Str++;
2755 }
2756
2757 //
2758 // The IPv4 address is X.X.X.X
2759 //
2760 if (*Ip4Str == '.') {
2761 if (Index == 3) {
2762 return EFI_INVALID_PARAMETER;
2763 }
2764 } else {
2765 if (Index != 3) {
2766 return EFI_INVALID_PARAMETER;
2767 }
2768 }
2769
2770 //
2771 // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the
2772 // first character that is not a valid decimal character, '.' or '\0' here.
2773 //
2774 NodeVal = AsciiStrDecimalToUintn (TempStr);
2775 if (NodeVal > 0xFF) {
2776 return EFI_INVALID_PARAMETER;
2777 }
2778
2779 Ip4Address->Addr[Index] = (UINT8) NodeVal;
2780
2781 Ip4Str++;
2782 }
2783
2784 return EFI_SUCCESS;
2785 }
2786
2787
2788 /**
2789 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2790 string is defined in RFC 4291 - Text Pepresentation of Addresses.
2791
2792 @param[in] String The pointer to the Ascii string.
2793 @param[out] Ip6Address The pointer to the converted IPv6 address.
2794
2795 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2796 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2797
2798 **/
2799 EFI_STATUS
2800 EFIAPI
2801 NetLibAsciiStrToIp6 (
2802 IN CONST CHAR8 *String,
2803 OUT EFI_IPv6_ADDRESS *Ip6Address
2804 )
2805 {
2806 UINT8 Index;
2807 CHAR8 *Ip6Str;
2808 CHAR8 *TempStr;
2809 CHAR8 *TempStr2;
2810 UINT8 NodeCnt;
2811 UINT8 TailNodeCnt;
2812 UINT8 AllowedCnt;
2813 UINTN NodeVal;
2814 BOOLEAN Short;
2815 BOOLEAN Update;
2816 BOOLEAN LeadZero;
2817 UINT8 LeadZeroCnt;
2818 UINT8 Cnt;
2819
2820 if ((String == NULL) || (Ip6Address == NULL)) {
2821 return EFI_INVALID_PARAMETER;
2822 }
2823
2824 Ip6Str = (CHAR8 *) String;
2825 AllowedCnt = 6;
2826 LeadZeroCnt = 0;
2827
2828 //
2829 // An IPv6 address leading with : looks strange.
2830 //
2831 if (*Ip6Str == ':') {
2832 if (*(Ip6Str + 1) != ':') {
2833 return EFI_INVALID_PARAMETER;
2834 } else {
2835 AllowedCnt = 7;
2836 }
2837 }
2838
2839 ZeroMem (Ip6Address, sizeof (EFI_IPv6_ADDRESS));
2840
2841 NodeCnt = 0;
2842 TailNodeCnt = 0;
2843 Short = FALSE;
2844 Update = FALSE;
2845 LeadZero = FALSE;
2846
2847 for (Index = 0; Index < 15; Index = (UINT8) (Index + 2)) {
2848 TempStr = Ip6Str;
2849
2850 while ((*Ip6Str != '\0') && (*Ip6Str != ':')) {
2851 Ip6Str++;
2852 }
2853
2854 if ((*Ip6Str == '\0') && (Index != 14)) {
2855 return EFI_INVALID_PARAMETER;
2856 }
2857
2858 if (*Ip6Str == ':') {
2859 if (*(Ip6Str + 1) == ':') {
2860 if ((NodeCnt > 6) ||
2861 ((*(Ip6Str + 2) != '\0') && (AsciiStrHexToUintn (Ip6Str + 2) == 0))) {
2862 //
2863 // ::0 looks strange. report error to user.
2864 //
2865 return EFI_INVALID_PARAMETER;
2866 }
2867 if ((NodeCnt == 6) && (*(Ip6Str + 2) != '\0') &&
2868 (AsciiStrHexToUintn (Ip6Str + 2) != 0)) {
2869 return EFI_INVALID_PARAMETER;
2870 }
2871
2872 //
2873 // Skip the abbreviation part of IPv6 address.
2874 //
2875 TempStr2 = Ip6Str + 2;
2876 while ((*TempStr2 != '\0')) {
2877 if (*TempStr2 == ':') {
2878 if (*(TempStr2 + 1) == ':') {
2879 //
2880 // :: can only appear once in IPv6 address.
2881 //
2882 return EFI_INVALID_PARAMETER;
2883 }
2884
2885 TailNodeCnt++;
2886 if (TailNodeCnt >= (AllowedCnt - NodeCnt)) {
2887 //
2888 // :: indicates one or more groups of 16 bits of zeros.
2889 //
2890 return EFI_INVALID_PARAMETER;
2891 }
2892 }
2893
2894 TempStr2++;
2895 }
2896
2897 Short = TRUE;
2898 Update = TRUE;
2899
2900 Ip6Str = Ip6Str + 2;
2901 } else {
2902 if (*(Ip6Str + 1) == '\0') {
2903 return EFI_INVALID_PARAMETER;
2904 }
2905 Ip6Str++;
2906 NodeCnt++;
2907 if ((Short && (NodeCnt > 6)) || (!Short && (NodeCnt > 7))) {
2908 //
2909 // There are more than 8 groups of 16 bits of zeros.
2910 //
2911 return EFI_INVALID_PARAMETER;
2912 }
2913 }
2914 }
2915
2916 //
2917 // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first
2918 // character that is not a valid hexadecimal character, ':' or '\0' here.
2919 //
2920 NodeVal = AsciiStrHexToUintn (TempStr);
2921 if ((NodeVal > 0xFFFF) || (Index > 14)) {
2922 return EFI_INVALID_PARAMETER;
2923 }
2924 if (NodeVal != 0) {
2925 if ((*TempStr == '0') &&
2926 ((*(TempStr + 2) == ':') || (*(TempStr + 3) == ':') ||
2927 (*(TempStr + 2) == '\0') || (*(TempStr + 3) == '\0'))) {
2928 return EFI_INVALID_PARAMETER;
2929 }
2930 if ((*TempStr == '0') && (*(TempStr + 4) != '\0') &&
2931 (*(TempStr + 4) != ':')) {
2932 return EFI_INVALID_PARAMETER;
2933 }
2934 } else {
2935 if (((*TempStr == '0') && (*(TempStr + 1) == '0') &&
2936 ((*(TempStr + 2) == ':') || (*(TempStr + 2) == '\0'))) ||
2937 ((*TempStr == '0') && (*(TempStr + 1) == '0') && (*(TempStr + 2) == '0') &&
2938 ((*(TempStr + 3) == ':') || (*(TempStr + 3) == '\0')))) {
2939 return EFI_INVALID_PARAMETER;
2940 }
2941 }
2942
2943 Cnt = 0;
2944 while ((TempStr[Cnt] != ':') && (TempStr[Cnt] != '\0')) {
2945 Cnt++;
2946 }
2947 if (LeadZeroCnt == 0) {
2948 if ((Cnt == 4) && (*TempStr == '0')) {
2949 LeadZero = TRUE;
2950 LeadZeroCnt++;
2951 }
2952 if ((Cnt != 0) && (Cnt < 4)) {
2953 LeadZero = FALSE;
2954 LeadZeroCnt++;
2955 }
2956 } else {
2957 if ((Cnt == 4) && (*TempStr == '0') && !LeadZero) {
2958 return EFI_INVALID_PARAMETER;
2959 }
2960 if ((Cnt != 0) && (Cnt < 4) && LeadZero) {
2961 return EFI_INVALID_PARAMETER;
2962 }
2963 }
2964
2965 Ip6Address->Addr[Index] = (UINT8) (NodeVal >> 8);
2966 Ip6Address->Addr[Index + 1] = (UINT8) (NodeVal & 0xFF);
2967
2968 //
2969 // Skip the groups of zeros by ::
2970 //
2971 if (Short && Update) {
2972 Index = (UINT8) (16 - (TailNodeCnt + 2) * 2);
2973 Update = FALSE;
2974 }
2975 }
2976
2977 if ((!Short && Index != 16) || (*Ip6Str != '\0')) {
2978 return EFI_INVALID_PARAMETER;
2979 }
2980
2981 return EFI_SUCCESS;
2982 }
2983
2984
2985 /**
2986 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
2987
2988 @param[in] String The pointer to the Ascii string.
2989 @param[out] Ip4Address The pointer to the converted IPv4 address.
2990
2991 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2992 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2993 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
2994
2995 **/
2996 EFI_STATUS
2997 EFIAPI
2998 NetLibStrToIp4 (
2999 IN CONST CHAR16 *String,
3000 OUT EFI_IPv4_ADDRESS *Ip4Address
3001 )
3002 {
3003 CHAR8 *Ip4Str;
3004 EFI_STATUS Status;
3005
3006 if ((String == NULL) || (Ip4Address == NULL)) {
3007 return EFI_INVALID_PARAMETER;
3008 }
3009
3010 Ip4Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3011 if (Ip4Str == NULL) {
3012 return EFI_OUT_OF_RESOURCES;
3013 }
3014
3015 UnicodeStrToAsciiStr (String, Ip4Str);
3016
3017 Status = NetLibAsciiStrToIp4 (Ip4Str, Ip4Address);
3018
3019 FreePool (Ip4Str);
3020
3021 return Status;
3022 }
3023
3024
3025 /**
3026 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
3027 the string is defined in RFC 4291 - Text Pepresentation of Addresses.
3028
3029 @param[in] String The pointer to the Ascii string.
3030 @param[out] Ip6Address The pointer to the converted IPv6 address.
3031
3032 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3033 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3034 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3035
3036 **/
3037 EFI_STATUS
3038 EFIAPI
3039 NetLibStrToIp6 (
3040 IN CONST CHAR16 *String,
3041 OUT EFI_IPv6_ADDRESS *Ip6Address
3042 )
3043 {
3044 CHAR8 *Ip6Str;
3045 EFI_STATUS Status;
3046
3047 if ((String == NULL) || (Ip6Address == NULL)) {
3048 return EFI_INVALID_PARAMETER;
3049 }
3050
3051 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3052 if (Ip6Str == NULL) {
3053 return EFI_OUT_OF_RESOURCES;
3054 }
3055
3056 UnicodeStrToAsciiStr (String, Ip6Str);
3057
3058 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3059
3060 FreePool (Ip6Str);
3061
3062 return Status;
3063 }
3064
3065 /**
3066 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3067 The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses
3068 Prefixes: ipv6-address/prefix-length.
3069
3070 @param[in] String The pointer to the Ascii string.
3071 @param[out] Ip6Address The pointer to the converted IPv6 address.
3072 @param[out] PrefixLength The pointer to the converted prefix length.
3073
3074 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3075 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3076 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3077
3078 **/
3079 EFI_STATUS
3080 EFIAPI
3081 NetLibStrToIp6andPrefix (
3082 IN CONST CHAR16 *String,
3083 OUT EFI_IPv6_ADDRESS *Ip6Address,
3084 OUT UINT8 *PrefixLength
3085 )
3086 {
3087 CHAR8 *Ip6Str;
3088 CHAR8 *PrefixStr;
3089 CHAR8 *TempStr;
3090 EFI_STATUS Status;
3091 UINT8 Length;
3092
3093 if ((String == NULL) || (Ip6Address == NULL) || (PrefixLength == NULL)) {
3094 return EFI_INVALID_PARAMETER;
3095 }
3096
3097 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3098 if (Ip6Str == NULL) {
3099 return EFI_OUT_OF_RESOURCES;
3100 }
3101
3102 UnicodeStrToAsciiStr (String, Ip6Str);
3103
3104 //
3105 // Get the sub string describing prefix length.
3106 //
3107 TempStr = Ip6Str;
3108 while (*TempStr != '\0' && (*TempStr != '/')) {
3109 TempStr++;
3110 }
3111
3112 if (*TempStr == '/') {
3113 PrefixStr = TempStr + 1;
3114 } else {
3115 PrefixStr = NULL;
3116 }
3117
3118 //
3119 // Get the sub string describing IPv6 address and convert it.
3120 //
3121 *TempStr = '\0';
3122
3123 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3124 if (EFI_ERROR (Status)) {
3125 goto Exit;
3126 }
3127
3128 //
3129 // If input string doesn't indicate the prefix length, return 0xff.
3130 //
3131 Length = 0xFF;
3132
3133 //
3134 // Convert the string to prefix length
3135 //
3136 if (PrefixStr != NULL) {
3137
3138 Status = EFI_INVALID_PARAMETER;
3139 Length = 0;
3140 while (*PrefixStr != '\0') {
3141 if (NET_IS_DIGIT (*PrefixStr)) {
3142 Length = (UINT8) (Length * 10 + (*PrefixStr - '0'));
3143 if (Length >= IP6_PREFIX_NUM) {
3144 goto Exit;
3145 }
3146 } else {
3147 goto Exit;
3148 }
3149
3150 PrefixStr++;
3151 }
3152 }
3153
3154 *PrefixLength = Length;
3155 Status = EFI_SUCCESS;
3156
3157 Exit:
3158
3159 FreePool (Ip6Str);
3160 return Status;
3161 }
3162
3163
3164
3165 /**
3166 This function obtains the system guid from the smbios table.
3167
3168 @param[out] SystemGuid The pointer of the returned system guid.
3169
3170 @retval EFI_SUCCESS Successfully obtained the system guid.
3171 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3172
3173 **/
3174 EFI_STATUS
3175 EFIAPI
3176 NetLibGetSystemGuid (
3177 OUT EFI_GUID *SystemGuid
3178 )
3179 {
3180 EFI_STATUS Status;
3181 SMBIOS_TABLE_ENTRY_POINT *SmbiosTable;
3182 SMBIOS_STRUCTURE_POINTER Smbios;
3183 SMBIOS_STRUCTURE_POINTER SmbiosEnd;
3184 CHAR8 *String;
3185
3186 SmbiosTable = NULL;
3187 Status = EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid, (VOID **) &SmbiosTable);
3188
3189 if (EFI_ERROR (Status) || SmbiosTable == NULL) {
3190 return EFI_NOT_FOUND;
3191 }
3192
3193 Smbios.Hdr = (SMBIOS_STRUCTURE *) (UINTN) SmbiosTable->TableAddress;
3194 SmbiosEnd.Raw = (UINT8 *) (UINTN) (SmbiosTable->TableAddress + SmbiosTable->TableLength);
3195
3196 do {
3197 if (Smbios.Hdr->Type == 1) {
3198 if (Smbios.Hdr->Length < 0x19) {
3199 //
3200 // Older version did not support UUID.
3201 //
3202 return EFI_NOT_FOUND;
3203 }
3204
3205 //
3206 // SMBIOS tables are byte packed so we need to do a byte copy to
3207 // prevend alignment faults on Itanium-based platform.
3208 //
3209 CopyMem (SystemGuid, &Smbios.Type1->Uuid, sizeof (EFI_GUID));
3210 return EFI_SUCCESS;
3211 }
3212
3213 //
3214 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3215 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3216 // to skip one SMBIOS structure.
3217 //
3218
3219 //
3220 // Step 1: Skip over formatted section.
3221 //
3222 String = (CHAR8 *) (Smbios.Raw + Smbios.Hdr->Length);
3223
3224 //
3225 // Step 2: Skip over unformated string section.
3226 //
3227 do {
3228 //
3229 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3230 // is terminated with an additional NULL(00h) BYTE.
3231 //
3232 for ( ; *String != 0; String++) {
3233 }
3234
3235 if (*(UINT8*)++String == 0) {
3236 //
3237 // Pointer to the next SMBIOS structure.
3238 //
3239 Smbios.Raw = (UINT8 *)++String;
3240 break;
3241 }
3242 } while (TRUE);
3243 } while (Smbios.Raw < SmbiosEnd.Raw);
3244 return EFI_NOT_FOUND;
3245 }