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