]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeNetLib/DxeNetLib.c
cfda3962bb82a3d072c90476937455869820ee1b
[mirror_edk2.git] / MdeModulePkg / Library / DxeNetLib / DxeNetLib.c
1 /** @file
2 Network library.
3
4 Copyright (c) 2005 - 2013, 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 #define DEFAULT_ZERO_START ((UINTN) ~0)
44
45 //
46 // All the supported IP4 maskes in host byte order.
47 //
48 GLOBAL_REMOVE_IF_UNREFERENCED IP4_ADDR gIp4AllMasks[IP4_MASK_NUM] = {
49 0x00000000,
50 0x80000000,
51 0xC0000000,
52 0xE0000000,
53 0xF0000000,
54 0xF8000000,
55 0xFC000000,
56 0xFE000000,
57
58 0xFF000000,
59 0xFF800000,
60 0xFFC00000,
61 0xFFE00000,
62 0xFFF00000,
63 0xFFF80000,
64 0xFFFC0000,
65 0xFFFE0000,
66
67 0xFFFF0000,
68 0xFFFF8000,
69 0xFFFFC000,
70 0xFFFFE000,
71 0xFFFFF000,
72 0xFFFFF800,
73 0xFFFFFC00,
74 0xFFFFFE00,
75
76 0xFFFFFF00,
77 0xFFFFFF80,
78 0xFFFFFFC0,
79 0xFFFFFFE0,
80 0xFFFFFFF0,
81 0xFFFFFFF8,
82 0xFFFFFFFC,
83 0xFFFFFFFE,
84 0xFFFFFFFF,
85 };
86
87 GLOBAL_REMOVE_IF_UNREFERENCED EFI_IPv4_ADDRESS mZeroIp4Addr = {{0, 0, 0, 0}};
88
89 //
90 // Any error level digitally larger than mNetDebugLevelMax
91 // will be silently discarded.
92 //
93 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mNetDebugLevelMax = NETDEBUG_LEVEL_ERROR;
94 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogPacketSeq = 0xDEADBEEF;
95
96 //
97 // You can change mSyslogDstMac mSyslogDstIp and mSyslogSrcIp
98 // here to direct the syslog packets to the syslog deamon. The
99 // default is broadcast to both the ethernet and IP.
100 //
101 GLOBAL_REMOVE_IF_UNREFERENCED UINT8 mSyslogDstMac[NET_ETHER_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
102 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogDstIp = 0xffffffff;
103 GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mSyslogSrcIp = 0;
104
105 GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *mMonthName[] = {
106 "Jan",
107 "Feb",
108 "Mar",
109 "Apr",
110 "May",
111 "Jun",
112 "Jul",
113 "Aug",
114 "Sep",
115 "Oct",
116 "Nov",
117 "Dec"
118 };
119
120 //
121 // VLAN device path node template
122 //
123 GLOBAL_REMOVE_IF_UNREFERENCED VLAN_DEVICE_PATH mNetVlanDevicePathTemplate = {
124 {
125 MESSAGING_DEVICE_PATH,
126 MSG_VLAN_DP,
127 {
128 (UINT8) (sizeof (VLAN_DEVICE_PATH)),
129 (UINT8) ((sizeof (VLAN_DEVICE_PATH)) >> 8)
130 }
131 },
132 0
133 };
134
135 /**
136 Locate the handles that support SNP, then open one of them
137 to send the syslog packets. The caller isn't required to close
138 the SNP after use because the SNP is opened by HandleProtocol.
139
140 @return The point to SNP if one is properly openned. Otherwise NULL
141
142 **/
143 EFI_SIMPLE_NETWORK_PROTOCOL *
144 SyslogLocateSnp (
145 VOID
146 )
147 {
148 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
149 EFI_STATUS Status;
150 EFI_HANDLE *Handles;
151 UINTN HandleCount;
152 UINTN Index;
153
154 //
155 // Locate the handles which has SNP installed.
156 //
157 Handles = NULL;
158 Status = gBS->LocateHandleBuffer (
159 ByProtocol,
160 &gEfiSimpleNetworkProtocolGuid,
161 NULL,
162 &HandleCount,
163 &Handles
164 );
165
166 if (EFI_ERROR (Status) || (HandleCount == 0)) {
167 return NULL;
168 }
169
170 //
171 // Try to open one of the ethernet SNP protocol to send packet
172 //
173 Snp = NULL;
174
175 for (Index = 0; Index < HandleCount; Index++) {
176 Status = gBS->HandleProtocol (
177 Handles[Index],
178 &gEfiSimpleNetworkProtocolGuid,
179 (VOID **) &Snp
180 );
181
182 if ((Status == EFI_SUCCESS) && (Snp != NULL) &&
183 (Snp->Mode->IfType == NET_IFTYPE_ETHERNET) &&
184 (Snp->Mode->MaxPacketSize >= NET_SYSLOG_PACKET_LEN)) {
185
186 break;
187 }
188
189 Snp = NULL;
190 }
191
192 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 Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished.
1071
1072 Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes.
1073 This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed
1074 has been removed from the list or not.
1075 If it has been removed, then restart the traversal from the head.
1076 If it hasn't been removed, then continue with the next node directly.
1077 This function will end the iterate and return the CallBack's last return value if error happens,
1078 or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list.
1079
1080 @param[in] List The head of the list.
1081 @param[in] CallBack Pointer to the callback function to destroy one node in the list.
1082 @param[in] Context Pointer to the callback function's context: corresponds to the
1083 parameter Context in NET_DESTROY_LINK_LIST_CALLBACK.
1084 @param[out] ListLength The length of the link list if the function returns successfully.
1085
1086 @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children.
1087 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
1088 @retval Others Return the CallBack's last return value.
1089
1090 **/
1091 EFI_STATUS
1092 EFIAPI
1093 NetDestroyLinkList (
1094 IN LIST_ENTRY *List,
1095 IN NET_DESTROY_LINK_LIST_CALLBACK CallBack,
1096 IN VOID *Context, OPTIONAL
1097 OUT UINTN *ListLength OPTIONAL
1098 )
1099 {
1100 UINTN PreviousLength;
1101 LIST_ENTRY *Entry;
1102 LIST_ENTRY *Ptr;
1103 UINTN Length;
1104 EFI_STATUS Status;
1105
1106 if (List == NULL || CallBack == NULL) {
1107 return EFI_INVALID_PARAMETER;
1108 }
1109
1110 Length = 0;
1111 do {
1112 PreviousLength = Length;
1113 Entry = GetFirstNode (List);
1114 while (!IsNull (List, Entry)) {
1115 Status = CallBack (Entry, Context);
1116 if (EFI_ERROR (Status)) {
1117 return Status;
1118 }
1119 //
1120 // Walk through the list to see whether the Entry has been removed or not.
1121 // If the Entry still exists, just try to destroy the next one.
1122 // If not, go back to the start point to iterate the list again.
1123 //
1124 for (Ptr = List->ForwardLink; Ptr != List; Ptr = Ptr->ForwardLink) {
1125 if (Ptr == Entry) {
1126 break;
1127 }
1128 }
1129 if (Ptr == Entry) {
1130 Entry = GetNextNode (List, Entry);
1131 } else {
1132 Entry = GetFirstNode (List);
1133 }
1134 }
1135 for (Length = 0, Ptr = List->ForwardLink; Ptr != List; Length++, Ptr = Ptr->ForwardLink);
1136 } while (Length != PreviousLength);
1137
1138 if (ListLength != NULL) {
1139 *ListLength = Length;
1140 }
1141 return EFI_SUCCESS;
1142 }
1143
1144 /**
1145 This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer.
1146
1147 @param[in] Handle Handle to be checked.
1148 @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer.
1149 @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
1150 if NumberOfChildren is 0.
1151
1152 @retval TURE Found the input Handle in ChildHandleBuffer.
1153 @retval FALSE Can't find the input Handle in ChildHandleBuffer.
1154
1155 **/
1156 BOOLEAN
1157 EFIAPI
1158 NetIsInHandleBuffer (
1159 IN EFI_HANDLE Handle,
1160 IN UINTN NumberOfChildren,
1161 IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
1162 )
1163 {
1164 UINTN Index;
1165
1166 if (NumberOfChildren == 0 || ChildHandleBuffer == NULL) {
1167 return FALSE;
1168 }
1169
1170 for (Index = 0; Index < NumberOfChildren; Index++) {
1171 if (Handle == ChildHandleBuffer[Index]) {
1172 return TRUE;
1173 }
1174 }
1175
1176 return FALSE;
1177 }
1178
1179
1180 /**
1181 Initialize the netmap. Netmap is a reposity to keep the <Key, Value> pairs.
1182
1183 Initialize the forward and backward links of two head nodes donated by Map->Used
1184 and Map->Recycled of two doubly linked lists.
1185 Initializes the count of the <Key, Value> pairs in the netmap to zero.
1186
1187 If Map is NULL, then ASSERT().
1188 If the address of Map->Used is NULL, then ASSERT().
1189 If the address of Map->Recycled is NULl, then ASSERT().
1190
1191 @param[in, out] Map The netmap to initialize.
1192
1193 **/
1194 VOID
1195 EFIAPI
1196 NetMapInit (
1197 IN OUT NET_MAP *Map
1198 )
1199 {
1200 ASSERT (Map != NULL);
1201
1202 InitializeListHead (&Map->Used);
1203 InitializeListHead (&Map->Recycled);
1204 Map->Count = 0;
1205 }
1206
1207
1208 /**
1209 To clean up the netmap, that is, release allocated memories.
1210
1211 Removes all nodes of the Used doubly linked list and free memory of all related netmap items.
1212 Removes all nodes of the Recycled doubly linked list and free memory of all related netmap items.
1213 The number of the <Key, Value> pairs in the netmap is set to be zero.
1214
1215 If Map is NULL, then ASSERT().
1216
1217 @param[in, out] Map The netmap to clean up.
1218
1219 **/
1220 VOID
1221 EFIAPI
1222 NetMapClean (
1223 IN OUT NET_MAP *Map
1224 )
1225 {
1226 NET_MAP_ITEM *Item;
1227 LIST_ENTRY *Entry;
1228 LIST_ENTRY *Next;
1229
1230 ASSERT (Map != NULL);
1231
1232 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Used) {
1233 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1234
1235 RemoveEntryList (&Item->Link);
1236 Map->Count--;
1237
1238 gBS->FreePool (Item);
1239 }
1240
1241 ASSERT ((Map->Count == 0) && IsListEmpty (&Map->Used));
1242
1243 NET_LIST_FOR_EACH_SAFE (Entry, Next, &Map->Recycled) {
1244 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1245
1246 RemoveEntryList (&Item->Link);
1247 gBS->FreePool (Item);
1248 }
1249
1250 ASSERT (IsListEmpty (&Map->Recycled));
1251 }
1252
1253
1254 /**
1255 Test whether the netmap is empty and return true if it is.
1256
1257 If the number of the <Key, Value> pairs in the netmap is zero, return TRUE.
1258
1259 If Map is NULL, then ASSERT().
1260
1261
1262 @param[in] Map The net map to test.
1263
1264 @return TRUE if the netmap is empty, otherwise FALSE.
1265
1266 **/
1267 BOOLEAN
1268 EFIAPI
1269 NetMapIsEmpty (
1270 IN NET_MAP *Map
1271 )
1272 {
1273 ASSERT (Map != NULL);
1274 return (BOOLEAN) (Map->Count == 0);
1275 }
1276
1277
1278 /**
1279 Return the number of the <Key, Value> pairs in the netmap.
1280
1281 @param[in] Map The netmap to get the entry number.
1282
1283 @return The entry number in the netmap.
1284
1285 **/
1286 UINTN
1287 EFIAPI
1288 NetMapGetCount (
1289 IN NET_MAP *Map
1290 )
1291 {
1292 return Map->Count;
1293 }
1294
1295
1296 /**
1297 Return one allocated item.
1298
1299 If the Recycled doubly linked list of the netmap is empty, it will try to allocate
1300 a batch of items if there are enough resources and add corresponding nodes to the begining
1301 of the Recycled doubly linked list of the netmap. Otherwise, it will directly remove
1302 the fist node entry of the Recycled doubly linked list and return the corresponding item.
1303
1304 If Map is NULL, then ASSERT().
1305
1306 @param[in, out] Map The netmap to allocate item for.
1307
1308 @return The allocated item. If NULL, the
1309 allocation failed due to resource limit.
1310
1311 **/
1312 NET_MAP_ITEM *
1313 NetMapAllocItem (
1314 IN OUT NET_MAP *Map
1315 )
1316 {
1317 NET_MAP_ITEM *Item;
1318 LIST_ENTRY *Head;
1319 UINTN Index;
1320
1321 ASSERT (Map != NULL);
1322
1323 Head = &Map->Recycled;
1324
1325 if (IsListEmpty (Head)) {
1326 for (Index = 0; Index < NET_MAP_INCREAMENT; Index++) {
1327 Item = AllocatePool (sizeof (NET_MAP_ITEM));
1328
1329 if (Item == NULL) {
1330 if (Index == 0) {
1331 return NULL;
1332 }
1333
1334 break;
1335 }
1336
1337 InsertHeadList (Head, &Item->Link);
1338 }
1339 }
1340
1341 Item = NET_LIST_HEAD (Head, NET_MAP_ITEM, Link);
1342 NetListRemoveHead (Head);
1343
1344 return Item;
1345 }
1346
1347
1348 /**
1349 Allocate an item to save the <Key, Value> pair to the head of the netmap.
1350
1351 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1352 to the beginning of the Used doubly linked list. The number of the <Key, Value>
1353 pairs in the netmap increase by 1.
1354
1355 If Map is NULL, then ASSERT().
1356
1357 @param[in, out] Map The netmap to insert into.
1358 @param[in] Key The user's key.
1359 @param[in] Value The user's value for the key.
1360
1361 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1362 @retval EFI_SUCCESS The item is inserted to the head.
1363
1364 **/
1365 EFI_STATUS
1366 EFIAPI
1367 NetMapInsertHead (
1368 IN OUT NET_MAP *Map,
1369 IN VOID *Key,
1370 IN VOID *Value OPTIONAL
1371 )
1372 {
1373 NET_MAP_ITEM *Item;
1374
1375 ASSERT (Map != NULL);
1376
1377 Item = NetMapAllocItem (Map);
1378
1379 if (Item == NULL) {
1380 return EFI_OUT_OF_RESOURCES;
1381 }
1382
1383 Item->Key = Key;
1384 Item->Value = Value;
1385 InsertHeadList (&Map->Used, &Item->Link);
1386
1387 Map->Count++;
1388 return EFI_SUCCESS;
1389 }
1390
1391
1392 /**
1393 Allocate an item to save the <Key, Value> pair to the tail of the netmap.
1394
1395 Allocate an item to save the <Key, Value> pair and add corresponding node entry
1396 to the tail of the Used doubly linked list. The number of the <Key, Value>
1397 pairs in the netmap increase by 1.
1398
1399 If Map is NULL, then ASSERT().
1400
1401 @param[in, out] Map The netmap to insert into.
1402 @param[in] Key The user's key.
1403 @param[in] Value The user's value for the key.
1404
1405 @retval EFI_OUT_OF_RESOURCES Failed to allocate the memory for the item.
1406 @retval EFI_SUCCESS The item is inserted to the tail.
1407
1408 **/
1409 EFI_STATUS
1410 EFIAPI
1411 NetMapInsertTail (
1412 IN OUT NET_MAP *Map,
1413 IN VOID *Key,
1414 IN VOID *Value OPTIONAL
1415 )
1416 {
1417 NET_MAP_ITEM *Item;
1418
1419 ASSERT (Map != NULL);
1420
1421 Item = NetMapAllocItem (Map);
1422
1423 if (Item == NULL) {
1424 return EFI_OUT_OF_RESOURCES;
1425 }
1426
1427 Item->Key = Key;
1428 Item->Value = Value;
1429 InsertTailList (&Map->Used, &Item->Link);
1430
1431 Map->Count++;
1432
1433 return EFI_SUCCESS;
1434 }
1435
1436
1437 /**
1438 Check whether the item is in the Map and return TRUE if it is.
1439
1440 @param[in] Map The netmap to search within.
1441 @param[in] Item The item to search.
1442
1443 @return TRUE if the item is in the netmap, otherwise FALSE.
1444
1445 **/
1446 BOOLEAN
1447 NetItemInMap (
1448 IN NET_MAP *Map,
1449 IN NET_MAP_ITEM *Item
1450 )
1451 {
1452 LIST_ENTRY *ListEntry;
1453
1454 NET_LIST_FOR_EACH (ListEntry, &Map->Used) {
1455 if (ListEntry == &Item->Link) {
1456 return TRUE;
1457 }
1458 }
1459
1460 return FALSE;
1461 }
1462
1463
1464 /**
1465 Find the key in the netmap and returns the point to the item contains the Key.
1466
1467 Iterate the Used doubly linked list of the netmap to get every item. Compare the key of every
1468 item with the key to search. It returns the point to the item contains the Key if found.
1469
1470 If Map is NULL, then ASSERT().
1471
1472 @param[in] Map The netmap to search within.
1473 @param[in] Key The key to search.
1474
1475 @return The point to the item contains the Key, or NULL if Key isn't in the map.
1476
1477 **/
1478 NET_MAP_ITEM *
1479 EFIAPI
1480 NetMapFindKey (
1481 IN NET_MAP *Map,
1482 IN VOID *Key
1483 )
1484 {
1485 LIST_ENTRY *Entry;
1486 NET_MAP_ITEM *Item;
1487
1488 ASSERT (Map != NULL);
1489
1490 NET_LIST_FOR_EACH (Entry, &Map->Used) {
1491 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1492
1493 if (Item->Key == Key) {
1494 return Item;
1495 }
1496 }
1497
1498 return NULL;
1499 }
1500
1501
1502 /**
1503 Remove the node entry of the item from the netmap and return the key of the removed item.
1504
1505 Remove the node entry of the item from the Used doubly linked list of the netmap.
1506 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1507 entry of the item to the Recycled doubly linked list of the netmap. If Value is not NULL,
1508 Value will point to the value of the item. It returns the key of the removed item.
1509
1510 If Map is NULL, then ASSERT().
1511 If Item is NULL, then ASSERT().
1512 if item in not in the netmap, then ASSERT().
1513
1514 @param[in, out] Map The netmap to remove the item from.
1515 @param[in, out] Item The item to remove.
1516 @param[out] Value The variable to receive the value if not NULL.
1517
1518 @return The key of the removed item.
1519
1520 **/
1521 VOID *
1522 EFIAPI
1523 NetMapRemoveItem (
1524 IN OUT NET_MAP *Map,
1525 IN OUT NET_MAP_ITEM *Item,
1526 OUT VOID **Value OPTIONAL
1527 )
1528 {
1529 ASSERT ((Map != NULL) && (Item != NULL));
1530 ASSERT (NetItemInMap (Map, Item));
1531
1532 RemoveEntryList (&Item->Link);
1533 Map->Count--;
1534 InsertHeadList (&Map->Recycled, &Item->Link);
1535
1536 if (Value != NULL) {
1537 *Value = Item->Value;
1538 }
1539
1540 return Item->Key;
1541 }
1542
1543
1544 /**
1545 Remove the first node entry on the netmap and return the key of the removed item.
1546
1547 Remove the first node entry from the Used doubly linked list of the netmap.
1548 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1549 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1550 parameter Value will point to the value of the item. It returns the key of the removed item.
1551
1552 If Map is NULL, then ASSERT().
1553 If the Used doubly linked list is empty, then ASSERT().
1554
1555 @param[in, out] Map The netmap to remove the head from.
1556 @param[out] Value The variable to receive the value if not NULL.
1557
1558 @return The key of the item removed.
1559
1560 **/
1561 VOID *
1562 EFIAPI
1563 NetMapRemoveHead (
1564 IN OUT NET_MAP *Map,
1565 OUT VOID **Value OPTIONAL
1566 )
1567 {
1568 NET_MAP_ITEM *Item;
1569
1570 //
1571 // Often, it indicates a programming error to remove
1572 // the first entry in an empty list
1573 //
1574 ASSERT (Map && !IsListEmpty (&Map->Used));
1575
1576 Item = NET_LIST_HEAD (&Map->Used, NET_MAP_ITEM, Link);
1577 RemoveEntryList (&Item->Link);
1578 Map->Count--;
1579 InsertHeadList (&Map->Recycled, &Item->Link);
1580
1581 if (Value != NULL) {
1582 *Value = Item->Value;
1583 }
1584
1585 return Item->Key;
1586 }
1587
1588
1589 /**
1590 Remove the last node entry on the netmap and return the key of the removed item.
1591
1592 Remove the last node entry from the Used doubly linked list of the netmap.
1593 The number of the <Key, Value> pairs in the netmap decrease by 1. Then add the node
1594 entry to the Recycled doubly linked list of the netmap. If parameter Value is not NULL,
1595 parameter Value will point to the value of the item. It returns the key of the removed item.
1596
1597 If Map is NULL, then ASSERT().
1598 If the Used doubly linked list is empty, then ASSERT().
1599
1600 @param[in, out] Map The netmap to remove the tail from.
1601 @param[out] Value The variable to receive the value if not NULL.
1602
1603 @return The key of the item removed.
1604
1605 **/
1606 VOID *
1607 EFIAPI
1608 NetMapRemoveTail (
1609 IN OUT NET_MAP *Map,
1610 OUT VOID **Value OPTIONAL
1611 )
1612 {
1613 NET_MAP_ITEM *Item;
1614
1615 //
1616 // Often, it indicates a programming error to remove
1617 // the last entry in an empty list
1618 //
1619 ASSERT (Map && !IsListEmpty (&Map->Used));
1620
1621 Item = NET_LIST_TAIL (&Map->Used, NET_MAP_ITEM, Link);
1622 RemoveEntryList (&Item->Link);
1623 Map->Count--;
1624 InsertHeadList (&Map->Recycled, &Item->Link);
1625
1626 if (Value != NULL) {
1627 *Value = Item->Value;
1628 }
1629
1630 return Item->Key;
1631 }
1632
1633
1634 /**
1635 Iterate through the netmap and call CallBack for each item.
1636
1637 It will contiue the traverse if CallBack returns EFI_SUCCESS, otherwise, break
1638 from the loop. It returns the CallBack's last return value. This function is
1639 delete safe for the current item.
1640
1641 If Map is NULL, then ASSERT().
1642 If CallBack is NULL, then ASSERT().
1643
1644 @param[in] Map The Map to iterate through.
1645 @param[in] CallBack The callback function to call for each item.
1646 @param[in] Arg The opaque parameter to the callback.
1647
1648 @retval EFI_SUCCESS There is no item in the netmap or CallBack for each item
1649 return EFI_SUCCESS.
1650 @retval Others It returns the CallBack's last return value.
1651
1652 **/
1653 EFI_STATUS
1654 EFIAPI
1655 NetMapIterate (
1656 IN NET_MAP *Map,
1657 IN NET_MAP_CALLBACK CallBack,
1658 IN VOID *Arg OPTIONAL
1659 )
1660 {
1661
1662 LIST_ENTRY *Entry;
1663 LIST_ENTRY *Next;
1664 LIST_ENTRY *Head;
1665 NET_MAP_ITEM *Item;
1666 EFI_STATUS Result;
1667
1668 ASSERT ((Map != NULL) && (CallBack != NULL));
1669
1670 Head = &Map->Used;
1671
1672 if (IsListEmpty (Head)) {
1673 return EFI_SUCCESS;
1674 }
1675
1676 NET_LIST_FOR_EACH_SAFE (Entry, Next, Head) {
1677 Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);
1678 Result = CallBack (Map, Item, Arg);
1679
1680 if (EFI_ERROR (Result)) {
1681 return Result;
1682 }
1683 }
1684
1685 return EFI_SUCCESS;
1686 }
1687
1688
1689 /**
1690 Internal function to get the child handle of the NIC handle.
1691
1692 @param[in] Controller NIC controller handle.
1693 @param[out] ChildHandle Returned child handle.
1694
1695 @retval EFI_SUCCESS Successfully to get child handle.
1696 @retval Others Failed to get child handle.
1697
1698 **/
1699 EFI_STATUS
1700 NetGetChildHandle (
1701 IN EFI_HANDLE Controller,
1702 OUT EFI_HANDLE *ChildHandle
1703 )
1704 {
1705 EFI_STATUS Status;
1706 EFI_HANDLE *Handles;
1707 UINTN HandleCount;
1708 UINTN Index;
1709 EFI_DEVICE_PATH_PROTOCOL *ChildDeviceDevicePath;
1710 VENDOR_DEVICE_PATH *VendorDeviceNode;
1711
1712 //
1713 // Locate all EFI Hii Config Access protocols
1714 //
1715 Status = gBS->LocateHandleBuffer (
1716 ByProtocol,
1717 &gEfiHiiConfigAccessProtocolGuid,
1718 NULL,
1719 &HandleCount,
1720 &Handles
1721 );
1722 if (EFI_ERROR (Status) || (HandleCount == 0)) {
1723 return Status;
1724 }
1725
1726 Status = EFI_NOT_FOUND;
1727
1728 for (Index = 0; Index < HandleCount; Index++) {
1729
1730 Status = EfiTestChildHandle (Controller, Handles[Index], &gEfiManagedNetworkServiceBindingProtocolGuid);
1731 if (!EFI_ERROR (Status)) {
1732 //
1733 // Get device path on the child handle
1734 //
1735 Status = gBS->HandleProtocol (
1736 Handles[Index],
1737 &gEfiDevicePathProtocolGuid,
1738 (VOID **) &ChildDeviceDevicePath
1739 );
1740
1741 if (!EFI_ERROR (Status)) {
1742 while (!IsDevicePathEnd (ChildDeviceDevicePath)) {
1743 ChildDeviceDevicePath = NextDevicePathNode (ChildDeviceDevicePath);
1744 //
1745 // Parse one instance
1746 //
1747 if (ChildDeviceDevicePath->Type == HARDWARE_DEVICE_PATH &&
1748 ChildDeviceDevicePath->SubType == HW_VENDOR_DP) {
1749 VendorDeviceNode = (VENDOR_DEVICE_PATH *) ChildDeviceDevicePath;
1750 if (CompareMem (&VendorDeviceNode->Guid, &gEfiNicIp4ConfigVariableGuid, sizeof (EFI_GUID)) == 0) {
1751 //
1752 // Found item matched gEfiNicIp4ConfigVariableGuid
1753 //
1754 *ChildHandle = Handles[Index];
1755 FreePool (Handles);
1756 return EFI_SUCCESS;
1757 }
1758 }
1759 }
1760 }
1761 }
1762 }
1763
1764 FreePool (Handles);
1765 return Status;
1766 }
1767
1768
1769 /**
1770 This is the default unload handle for all the network drivers.
1771
1772 Disconnect the driver specified by ImageHandle from all the devices in the handle database.
1773 Uninstall all the protocols installed in the driver entry point.
1774
1775 @param[in] ImageHandle The drivers' driver image.
1776
1777 @retval EFI_SUCCESS The image is unloaded.
1778 @retval Others Failed to unload the image.
1779
1780 **/
1781 EFI_STATUS
1782 EFIAPI
1783 NetLibDefaultUnload (
1784 IN EFI_HANDLE ImageHandle
1785 )
1786 {
1787 EFI_STATUS Status;
1788 EFI_HANDLE *DeviceHandleBuffer;
1789 UINTN DeviceHandleCount;
1790 UINTN Index;
1791 UINTN Index2;
1792 EFI_DRIVER_BINDING_PROTOCOL *DriverBinding;
1793 EFI_COMPONENT_NAME_PROTOCOL *ComponentName;
1794 EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2;
1795
1796 //
1797 // Get the list of all the handles in the handle database.
1798 // If there is an error getting the list, then the unload
1799 // operation fails.
1800 //
1801 Status = gBS->LocateHandleBuffer (
1802 AllHandles,
1803 NULL,
1804 NULL,
1805 &DeviceHandleCount,
1806 &DeviceHandleBuffer
1807 );
1808
1809 if (EFI_ERROR (Status)) {
1810 return Status;
1811 }
1812
1813 for (Index = 0; Index < DeviceHandleCount; Index++) {
1814 Status = gBS->HandleProtocol (
1815 DeviceHandleBuffer[Index],
1816 &gEfiDriverBindingProtocolGuid,
1817 (VOID **) &DriverBinding
1818 );
1819 if (EFI_ERROR (Status)) {
1820 continue;
1821 }
1822
1823 if (DriverBinding->ImageHandle != ImageHandle) {
1824 continue;
1825 }
1826
1827 //
1828 // Disconnect the driver specified by ImageHandle from all
1829 // the devices in the handle database.
1830 //
1831 for (Index2 = 0; Index2 < DeviceHandleCount; Index2++) {
1832 Status = gBS->DisconnectController (
1833 DeviceHandleBuffer[Index2],
1834 DriverBinding->DriverBindingHandle,
1835 NULL
1836 );
1837 }
1838
1839 //
1840 // Uninstall all the protocols installed in the driver entry point
1841 //
1842 gBS->UninstallProtocolInterface (
1843 DriverBinding->DriverBindingHandle,
1844 &gEfiDriverBindingProtocolGuid,
1845 DriverBinding
1846 );
1847
1848 Status = gBS->HandleProtocol (
1849 DeviceHandleBuffer[Index],
1850 &gEfiComponentNameProtocolGuid,
1851 (VOID **) &ComponentName
1852 );
1853 if (!EFI_ERROR (Status)) {
1854 gBS->UninstallProtocolInterface (
1855 DriverBinding->DriverBindingHandle,
1856 &gEfiComponentNameProtocolGuid,
1857 ComponentName
1858 );
1859 }
1860
1861 Status = gBS->HandleProtocol (
1862 DeviceHandleBuffer[Index],
1863 &gEfiComponentName2ProtocolGuid,
1864 (VOID **) &ComponentName2
1865 );
1866 if (!EFI_ERROR (Status)) {
1867 gBS->UninstallProtocolInterface (
1868 DriverBinding->DriverBindingHandle,
1869 &gEfiComponentName2ProtocolGuid,
1870 ComponentName2
1871 );
1872 }
1873 }
1874
1875 //
1876 // Free the buffer containing the list of handles from the handle database
1877 //
1878 if (DeviceHandleBuffer != NULL) {
1879 gBS->FreePool (DeviceHandleBuffer);
1880 }
1881
1882 return EFI_SUCCESS;
1883 }
1884
1885
1886
1887 /**
1888 Create a child of the service that is identified by ServiceBindingGuid.
1889
1890 Get the ServiceBinding Protocol first, then use it to create a child.
1891
1892 If ServiceBindingGuid is NULL, then ASSERT().
1893 If ChildHandle is NULL, then ASSERT().
1894
1895 @param[in] Controller The controller which has the service installed.
1896 @param[in] Image The image handle used to open service.
1897 @param[in] ServiceBindingGuid The service's Guid.
1898 @param[in, out] ChildHandle The handle to receive the create child.
1899
1900 @retval EFI_SUCCESS The child is successfully created.
1901 @retval Others Failed to create the child.
1902
1903 **/
1904 EFI_STATUS
1905 EFIAPI
1906 NetLibCreateServiceChild (
1907 IN EFI_HANDLE Controller,
1908 IN EFI_HANDLE Image,
1909 IN EFI_GUID *ServiceBindingGuid,
1910 IN OUT EFI_HANDLE *ChildHandle
1911 )
1912 {
1913 EFI_STATUS Status;
1914 EFI_SERVICE_BINDING_PROTOCOL *Service;
1915
1916
1917 ASSERT ((ServiceBindingGuid != NULL) && (ChildHandle != NULL));
1918
1919 //
1920 // Get the ServiceBinding Protocol
1921 //
1922 Status = gBS->OpenProtocol (
1923 Controller,
1924 ServiceBindingGuid,
1925 (VOID **) &Service,
1926 Image,
1927 Controller,
1928 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1929 );
1930
1931 if (EFI_ERROR (Status)) {
1932 return Status;
1933 }
1934
1935 //
1936 // Create a child
1937 //
1938 Status = Service->CreateChild (Service, ChildHandle);
1939 return Status;
1940 }
1941
1942
1943 /**
1944 Destroy a child of the service that is identified by ServiceBindingGuid.
1945
1946 Get the ServiceBinding Protocol first, then use it to destroy a child.
1947
1948 If ServiceBindingGuid is NULL, then ASSERT().
1949
1950 @param[in] Controller The controller which has the service installed.
1951 @param[in] Image The image handle used to open service.
1952 @param[in] ServiceBindingGuid The service's Guid.
1953 @param[in] ChildHandle The child to destroy.
1954
1955 @retval EFI_SUCCESS The child is successfully destroyed.
1956 @retval Others Failed to destroy the child.
1957
1958 **/
1959 EFI_STATUS
1960 EFIAPI
1961 NetLibDestroyServiceChild (
1962 IN EFI_HANDLE Controller,
1963 IN EFI_HANDLE Image,
1964 IN EFI_GUID *ServiceBindingGuid,
1965 IN EFI_HANDLE ChildHandle
1966 )
1967 {
1968 EFI_STATUS Status;
1969 EFI_SERVICE_BINDING_PROTOCOL *Service;
1970
1971 ASSERT (ServiceBindingGuid != NULL);
1972
1973 //
1974 // Get the ServiceBinding Protocol
1975 //
1976 Status = gBS->OpenProtocol (
1977 Controller,
1978 ServiceBindingGuid,
1979 (VOID **) &Service,
1980 Image,
1981 Controller,
1982 EFI_OPEN_PROTOCOL_GET_PROTOCOL
1983 );
1984
1985 if (EFI_ERROR (Status)) {
1986 return Status;
1987 }
1988
1989 //
1990 // destroy the child
1991 //
1992 Status = Service->DestroyChild (Service, ChildHandle);
1993 return Status;
1994 }
1995
1996 /**
1997 Get handle with Simple Network Protocol installed on it.
1998
1999 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2000 If Simple Network Protocol is already installed on the ServiceHandle, the
2001 ServiceHandle will be returned. If SNP is not installed on the ServiceHandle,
2002 try to find its parent handle with SNP installed.
2003
2004 @param[in] ServiceHandle The handle where network service binding protocols are
2005 installed on.
2006 @param[out] Snp The pointer to store the address of the SNP instance.
2007 This is an optional parameter that may be NULL.
2008
2009 @return The SNP handle, or NULL if not found.
2010
2011 **/
2012 EFI_HANDLE
2013 EFIAPI
2014 NetLibGetSnpHandle (
2015 IN EFI_HANDLE ServiceHandle,
2016 OUT EFI_SIMPLE_NETWORK_PROTOCOL **Snp OPTIONAL
2017 )
2018 {
2019 EFI_STATUS Status;
2020 EFI_SIMPLE_NETWORK_PROTOCOL *SnpInstance;
2021 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2022 EFI_HANDLE SnpHandle;
2023
2024 //
2025 // Try to open SNP from ServiceHandle
2026 //
2027 SnpInstance = NULL;
2028 Status = gBS->HandleProtocol (ServiceHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
2029 if (!EFI_ERROR (Status)) {
2030 if (Snp != NULL) {
2031 *Snp = SnpInstance;
2032 }
2033 return ServiceHandle;
2034 }
2035
2036 //
2037 // Failed to open SNP, try to get SNP handle by LocateDevicePath()
2038 //
2039 DevicePath = DevicePathFromHandle (ServiceHandle);
2040 if (DevicePath == NULL) {
2041 return NULL;
2042 }
2043
2044 SnpHandle = NULL;
2045 Status = gBS->LocateDevicePath (&gEfiSimpleNetworkProtocolGuid, &DevicePath, &SnpHandle);
2046 if (EFI_ERROR (Status)) {
2047 //
2048 // Failed to find SNP handle
2049 //
2050 return NULL;
2051 }
2052
2053 Status = gBS->HandleProtocol (SnpHandle, &gEfiSimpleNetworkProtocolGuid, (VOID **) &SnpInstance);
2054 if (!EFI_ERROR (Status)) {
2055 if (Snp != NULL) {
2056 *Snp = SnpInstance;
2057 }
2058 return SnpHandle;
2059 }
2060
2061 return NULL;
2062 }
2063
2064 /**
2065 Retrieve VLAN ID of a VLAN device handle.
2066
2067 Search VLAN device path node in Device Path of specified ServiceHandle and
2068 return its VLAN ID. If no VLAN device path node found, then this ServiceHandle
2069 is not a VLAN device handle, and 0 will be returned.
2070
2071 @param[in] ServiceHandle The handle where network service binding protocols are
2072 installed on.
2073
2074 @return VLAN ID of the device handle, or 0 if not a VLAN device.
2075
2076 **/
2077 UINT16
2078 EFIAPI
2079 NetLibGetVlanId (
2080 IN EFI_HANDLE ServiceHandle
2081 )
2082 {
2083 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2084 EFI_DEVICE_PATH_PROTOCOL *Node;
2085
2086 DevicePath = DevicePathFromHandle (ServiceHandle);
2087 if (DevicePath == NULL) {
2088 return 0;
2089 }
2090
2091 Node = DevicePath;
2092 while (!IsDevicePathEnd (Node)) {
2093 if (Node->Type == MESSAGING_DEVICE_PATH && Node->SubType == MSG_VLAN_DP) {
2094 return ((VLAN_DEVICE_PATH *) Node)->VlanId;
2095 }
2096 Node = NextDevicePathNode (Node);
2097 }
2098
2099 return 0;
2100 }
2101
2102 /**
2103 Find VLAN device handle with specified VLAN ID.
2104
2105 The VLAN child device handle is created by VLAN Config Protocol on ControllerHandle.
2106 This function will append VLAN device path node to the parent device path,
2107 and then use LocateDevicePath() to find the correct VLAN device handle.
2108
2109 @param[in] ControllerHandle The handle where network service binding protocols are
2110 installed on.
2111 @param[in] VlanId The configured VLAN ID for the VLAN device.
2112
2113 @return The VLAN device handle, or NULL if not found.
2114
2115 **/
2116 EFI_HANDLE
2117 EFIAPI
2118 NetLibGetVlanHandle (
2119 IN EFI_HANDLE ControllerHandle,
2120 IN UINT16 VlanId
2121 )
2122 {
2123 EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath;
2124 EFI_DEVICE_PATH_PROTOCOL *VlanDevicePath;
2125 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
2126 VLAN_DEVICE_PATH VlanNode;
2127 EFI_HANDLE Handle;
2128
2129 ParentDevicePath = DevicePathFromHandle (ControllerHandle);
2130 if (ParentDevicePath == NULL) {
2131 return NULL;
2132 }
2133
2134 //
2135 // Construct VLAN device path
2136 //
2137 CopyMem (&VlanNode, &mNetVlanDevicePathTemplate, sizeof (VLAN_DEVICE_PATH));
2138 VlanNode.VlanId = VlanId;
2139 VlanDevicePath = AppendDevicePathNode (
2140 ParentDevicePath,
2141 (EFI_DEVICE_PATH_PROTOCOL *) &VlanNode
2142 );
2143 if (VlanDevicePath == NULL) {
2144 return NULL;
2145 }
2146
2147 //
2148 // Find VLAN device handle
2149 //
2150 Handle = NULL;
2151 DevicePath = VlanDevicePath;
2152 gBS->LocateDevicePath (
2153 &gEfiDevicePathProtocolGuid,
2154 &DevicePath,
2155 &Handle
2156 );
2157 if (!IsDevicePathEnd (DevicePath)) {
2158 //
2159 // Device path is not exactly match
2160 //
2161 Handle = NULL;
2162 }
2163
2164 FreePool (VlanDevicePath);
2165 return Handle;
2166 }
2167
2168 /**
2169 Get MAC address associated with the network service handle.
2170
2171 There should be MNP Service Binding Protocol installed on the input ServiceHandle.
2172 If SNP is installed on the ServiceHandle or its parent handle, MAC address will
2173 be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.
2174
2175 @param[in] ServiceHandle The handle where network service binding protocols are
2176 installed on.
2177 @param[out] MacAddress The pointer to store the returned MAC address.
2178 @param[out] AddressSize The length of returned MAC address.
2179
2180 @retval EFI_SUCCESS MAC address is returned successfully.
2181 @retval Others Failed to get SNP mode data.
2182
2183 **/
2184 EFI_STATUS
2185 EFIAPI
2186 NetLibGetMacAddress (
2187 IN EFI_HANDLE ServiceHandle,
2188 OUT EFI_MAC_ADDRESS *MacAddress,
2189 OUT UINTN *AddressSize
2190 )
2191 {
2192 EFI_STATUS Status;
2193 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2194 EFI_SIMPLE_NETWORK_MODE *SnpMode;
2195 EFI_SIMPLE_NETWORK_MODE SnpModeData;
2196 EFI_MANAGED_NETWORK_PROTOCOL *Mnp;
2197 EFI_SERVICE_BINDING_PROTOCOL *MnpSb;
2198 EFI_HANDLE *SnpHandle;
2199 EFI_HANDLE MnpChildHandle;
2200
2201 ASSERT (MacAddress != NULL);
2202 ASSERT (AddressSize != NULL);
2203
2204 //
2205 // Try to get SNP handle
2206 //
2207 Snp = NULL;
2208 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2209 if (SnpHandle != NULL) {
2210 //
2211 // SNP found, use it directly
2212 //
2213 SnpMode = Snp->Mode;
2214 } else {
2215 //
2216 // Failed to get SNP handle, try to get MAC address from MNP
2217 //
2218 MnpChildHandle = NULL;
2219 Status = gBS->HandleProtocol (
2220 ServiceHandle,
2221 &gEfiManagedNetworkServiceBindingProtocolGuid,
2222 (VOID **) &MnpSb
2223 );
2224 if (EFI_ERROR (Status)) {
2225 return Status;
2226 }
2227
2228 //
2229 // Create a MNP child
2230 //
2231 Status = MnpSb->CreateChild (MnpSb, &MnpChildHandle);
2232 if (EFI_ERROR (Status)) {
2233 return Status;
2234 }
2235
2236 //
2237 // Open MNP protocol
2238 //
2239 Status = gBS->HandleProtocol (
2240 MnpChildHandle,
2241 &gEfiManagedNetworkProtocolGuid,
2242 (VOID **) &Mnp
2243 );
2244 if (EFI_ERROR (Status)) {
2245 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2246 return Status;
2247 }
2248
2249 //
2250 // Try to get SNP mode from MNP
2251 //
2252 Status = Mnp->GetModeData (Mnp, NULL, &SnpModeData);
2253 if (EFI_ERROR (Status)) {
2254 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2255 return Status;
2256 }
2257 SnpMode = &SnpModeData;
2258
2259 //
2260 // Destroy the MNP child
2261 //
2262 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2263 }
2264
2265 *AddressSize = SnpMode->HwAddressSize;
2266 CopyMem (MacAddress->Addr, SnpMode->CurrentAddress.Addr, SnpMode->HwAddressSize);
2267
2268 return EFI_SUCCESS;
2269 }
2270
2271 /**
2272 Convert MAC address of the NIC associated with specified Service Binding Handle
2273 to a unicode string. Callers are responsible for freeing the string storage.
2274
2275 Locate simple network protocol associated with the Service Binding Handle and
2276 get the mac address from SNP. Then convert the mac address into a unicode
2277 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2278 Plus one unicode character for the null-terminator.
2279
2280 @param[in] ServiceHandle The handle where network service binding protocol is
2281 installed on.
2282 @param[in] ImageHandle The image handle used to act as the agent handle to
2283 get the simple network protocol. This parameter is
2284 optional and may be NULL.
2285 @param[out] MacString The pointer to store the address of the string
2286 representation of the mac address.
2287
2288 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2289 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2290 @retval Others Failed to open the simple network protocol.
2291
2292 **/
2293 EFI_STATUS
2294 EFIAPI
2295 NetLibGetMacString (
2296 IN EFI_HANDLE ServiceHandle,
2297 IN EFI_HANDLE ImageHandle, OPTIONAL
2298 OUT CHAR16 **MacString
2299 )
2300 {
2301 EFI_STATUS Status;
2302 EFI_MAC_ADDRESS MacAddress;
2303 UINT8 *HwAddress;
2304 UINTN HwAddressSize;
2305 UINT16 VlanId;
2306 CHAR16 *String;
2307 UINTN Index;
2308
2309 ASSERT (MacString != NULL);
2310
2311 //
2312 // Get MAC address of the network device
2313 //
2314 Status = NetLibGetMacAddress (ServiceHandle, &MacAddress, &HwAddressSize);
2315 if (EFI_ERROR (Status)) {
2316 return Status;
2317 }
2318
2319 //
2320 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2321 // If VLAN is configured, it will need extra 5 characters like "\0005".
2322 // Plus one unicode character for the null-terminator.
2323 //
2324 String = AllocateZeroPool ((2 * HwAddressSize + 5 + 1) * sizeof (CHAR16));
2325 if (String == NULL) {
2326 return EFI_OUT_OF_RESOURCES;
2327 }
2328 *MacString = String;
2329
2330 //
2331 // Convert the MAC address into a unicode string.
2332 //
2333 HwAddress = &MacAddress.Addr[0];
2334 for (Index = 0; Index < HwAddressSize; Index++) {
2335 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, *(HwAddress++), 2);
2336 }
2337
2338 //
2339 // Append VLAN ID if any
2340 //
2341 VlanId = NetLibGetVlanId (ServiceHandle);
2342 if (VlanId != 0) {
2343 *String++ = L'\\';
2344 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, VlanId, 4);
2345 }
2346
2347 //
2348 // Null terminate the Unicode string
2349 //
2350 *String = L'\0';
2351
2352 return EFI_SUCCESS;
2353 }
2354
2355 /**
2356 Detect media status for specified network device.
2357
2358 The underlying UNDI driver may or may not support reporting media status from
2359 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2360 will try to invoke Snp->GetStatus() to get the media status: if media already
2361 present, it return directly; if media not present, it will stop SNP and then
2362 restart SNP to get the latest media status, this give chance to get the correct
2363 media status for old UNDI driver which doesn't support reporting media status
2364 from GET_STATUS command.
2365 Note: there will be two limitations for current algorithm:
2366 1) for UNDI with this capability, in case of cable is not attached, there will
2367 be an redundant Stop/Start() process;
2368 2) for UNDI without this capability, in case that network cable is attached when
2369 Snp->Initialize() is invoked while network cable is unattached later,
2370 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2371 apps to wait for timeout time.
2372
2373 @param[in] ServiceHandle The handle where network service binding protocols are
2374 installed on.
2375 @param[out] MediaPresent The pointer to store the media status.
2376
2377 @retval EFI_SUCCESS Media detection success.
2378 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2379 @retval EFI_UNSUPPORTED Network device does not support media detection.
2380 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2381
2382 **/
2383 EFI_STATUS
2384 EFIAPI
2385 NetLibDetectMedia (
2386 IN EFI_HANDLE ServiceHandle,
2387 OUT BOOLEAN *MediaPresent
2388 )
2389 {
2390 EFI_STATUS Status;
2391 EFI_HANDLE SnpHandle;
2392 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2393 UINT32 InterruptStatus;
2394 UINT32 OldState;
2395 EFI_MAC_ADDRESS *MCastFilter;
2396 UINT32 MCastFilterCount;
2397 UINT32 EnableFilterBits;
2398 UINT32 DisableFilterBits;
2399 BOOLEAN ResetMCastFilters;
2400
2401 ASSERT (MediaPresent != NULL);
2402
2403 //
2404 // Get SNP handle
2405 //
2406 Snp = NULL;
2407 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2408 if (SnpHandle == NULL) {
2409 return EFI_INVALID_PARAMETER;
2410 }
2411
2412 //
2413 // Check whether SNP support media detection
2414 //
2415 if (!Snp->Mode->MediaPresentSupported) {
2416 return EFI_UNSUPPORTED;
2417 }
2418
2419 //
2420 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2421 //
2422 Status = Snp->GetStatus (Snp, &InterruptStatus, NULL);
2423 if (EFI_ERROR (Status)) {
2424 return Status;
2425 }
2426
2427 if (Snp->Mode->MediaPresent) {
2428 //
2429 // Media is present, return directly
2430 //
2431 *MediaPresent = TRUE;
2432 return EFI_SUCCESS;
2433 }
2434
2435 //
2436 // Till now, GetStatus() report no media; while, in case UNDI not support
2437 // reporting media status from GetStatus(), this media status may be incorrect.
2438 // So, we will stop SNP and then restart it to get the correct media status.
2439 //
2440 OldState = Snp->Mode->State;
2441 if (OldState >= EfiSimpleNetworkMaxState) {
2442 return EFI_DEVICE_ERROR;
2443 }
2444
2445 MCastFilter = NULL;
2446
2447 if (OldState == EfiSimpleNetworkInitialized) {
2448 //
2449 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2450 //
2451
2452 //
2453 // Backup current SNP receive filter settings
2454 //
2455 EnableFilterBits = Snp->Mode->ReceiveFilterSetting;
2456 DisableFilterBits = Snp->Mode->ReceiveFilterMask ^ EnableFilterBits;
2457
2458 ResetMCastFilters = TRUE;
2459 MCastFilterCount = Snp->Mode->MCastFilterCount;
2460 if (MCastFilterCount != 0) {
2461 MCastFilter = AllocateCopyPool (
2462 MCastFilterCount * sizeof (EFI_MAC_ADDRESS),
2463 Snp->Mode->MCastFilter
2464 );
2465 ASSERT (MCastFilter != NULL);
2466
2467 ResetMCastFilters = FALSE;
2468 }
2469
2470 //
2471 // Shutdown/Stop the simple network
2472 //
2473 Status = Snp->Shutdown (Snp);
2474 if (!EFI_ERROR (Status)) {
2475 Status = Snp->Stop (Snp);
2476 }
2477 if (EFI_ERROR (Status)) {
2478 goto Exit;
2479 }
2480
2481 //
2482 // Start/Initialize the simple network
2483 //
2484 Status = Snp->Start (Snp);
2485 if (!EFI_ERROR (Status)) {
2486 Status = Snp->Initialize (Snp, 0, 0);
2487 }
2488 if (EFI_ERROR (Status)) {
2489 goto Exit;
2490 }
2491
2492 //
2493 // Here we get the correct media status
2494 //
2495 *MediaPresent = Snp->Mode->MediaPresent;
2496
2497 //
2498 // Restore SNP receive filter settings
2499 //
2500 Status = Snp->ReceiveFilters (
2501 Snp,
2502 EnableFilterBits,
2503 DisableFilterBits,
2504 ResetMCastFilters,
2505 MCastFilterCount,
2506 MCastFilter
2507 );
2508
2509 if (MCastFilter != NULL) {
2510 FreePool (MCastFilter);
2511 }
2512
2513 return Status;
2514 }
2515
2516 //
2517 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2518 //
2519 if (OldState == EfiSimpleNetworkStopped) {
2520 //
2521 // SNP not start yet, start it
2522 //
2523 Status = Snp->Start (Snp);
2524 if (EFI_ERROR (Status)) {
2525 goto Exit;
2526 }
2527 }
2528
2529 //
2530 // Initialize the simple network
2531 //
2532 Status = Snp->Initialize (Snp, 0, 0);
2533 if (EFI_ERROR (Status)) {
2534 Status = EFI_DEVICE_ERROR;
2535 goto Exit;
2536 }
2537
2538 //
2539 // Here we get the correct media status
2540 //
2541 *MediaPresent = Snp->Mode->MediaPresent;
2542
2543 //
2544 // Shut down the simple network
2545 //
2546 Snp->Shutdown (Snp);
2547
2548 Exit:
2549 if (OldState == EfiSimpleNetworkStopped) {
2550 //
2551 // Original SNP sate is Stopped, restore to original state
2552 //
2553 Snp->Stop (Snp);
2554 }
2555
2556 if (MCastFilter != NULL) {
2557 FreePool (MCastFilter);
2558 }
2559
2560 return Status;
2561 }
2562
2563 /**
2564 Check the default address used by the IPv4 driver is static or dynamic (acquired
2565 from DHCP).
2566
2567 If the controller handle does not have the NIC Ip4 Config Protocol installed, the
2568 default address is static. If the EFI variable to save the configuration is not found,
2569 the default address is static. Otherwise, get the result from the EFI variable which
2570 saving the configuration.
2571
2572 @param[in] Controller The controller handle which has the NIC Ip4 Config Protocol
2573 relative with the default address to judge.
2574
2575 @retval TRUE If the default address is static.
2576 @retval FALSE If the default address is acquired from DHCP.
2577
2578 **/
2579 BOOLEAN
2580 NetLibDefaultAddressIsStatic (
2581 IN EFI_HANDLE Controller
2582 )
2583 {
2584 EFI_STATUS Status;
2585 EFI_HII_CONFIG_ROUTING_PROTOCOL *HiiConfigRouting;
2586 UINTN Len;
2587 NIC_IP4_CONFIG_INFO *ConfigInfo;
2588 BOOLEAN IsStatic;
2589 EFI_STRING ConfigHdr;
2590 EFI_STRING ConfigResp;
2591 EFI_STRING AccessProgress;
2592 EFI_STRING AccessResults;
2593 EFI_STRING String;
2594 EFI_HANDLE ChildHandle;
2595
2596 ConfigInfo = NULL;
2597 ConfigHdr = NULL;
2598 ConfigResp = NULL;
2599 AccessProgress = NULL;
2600 AccessResults = NULL;
2601 IsStatic = TRUE;
2602
2603 Status = gBS->LocateProtocol (
2604 &gEfiHiiConfigRoutingProtocolGuid,
2605 NULL,
2606 (VOID **) &HiiConfigRouting
2607 );
2608 if (EFI_ERROR (Status)) {
2609 return TRUE;
2610 }
2611
2612 Status = NetGetChildHandle (Controller, &ChildHandle);
2613 if (EFI_ERROR (Status)) {
2614 return TRUE;
2615 }
2616
2617 //
2618 // Construct config request string header
2619 //
2620 ConfigHdr = HiiConstructConfigHdr (&gEfiNicIp4ConfigVariableGuid, EFI_NIC_IP4_CONFIG_VARIABLE, ChildHandle);
2621 if (ConfigHdr == NULL) {
2622 return TRUE;
2623 }
2624
2625 Len = StrLen (ConfigHdr);
2626 ConfigResp = AllocateZeroPool ((Len + NIC_ITEM_CONFIG_SIZE * 2 + 100) * sizeof (CHAR16));
2627 if (ConfigResp == NULL) {
2628 goto ON_EXIT;
2629 }
2630 StrCpy (ConfigResp, ConfigHdr);
2631
2632 String = ConfigResp + Len;
2633 UnicodeSPrint (
2634 String,
2635 (8 + 4 + 7 + 4 + 1) * sizeof (CHAR16),
2636 L"&OFFSET=%04X&WIDTH=%04X",
2637 OFFSET_OF (NIC_IP4_CONFIG_INFO, Source),
2638 sizeof (UINT32)
2639 );
2640
2641 Status = HiiConfigRouting->ExtractConfig (
2642 HiiConfigRouting,
2643 ConfigResp,
2644 &AccessProgress,
2645 &AccessResults
2646 );
2647 if (EFI_ERROR (Status)) {
2648 goto ON_EXIT;
2649 }
2650
2651 ConfigInfo = AllocateZeroPool (NIC_ITEM_CONFIG_SIZE);
2652 if (ConfigInfo == NULL) {
2653 goto ON_EXIT;
2654 }
2655
2656 ConfigInfo->Source = IP4_CONFIG_SOURCE_STATIC;
2657 Len = NIC_ITEM_CONFIG_SIZE;
2658 Status = HiiConfigRouting->ConfigToBlock (
2659 HiiConfigRouting,
2660 AccessResults,
2661 (UINT8 *) ConfigInfo,
2662 &Len,
2663 &AccessProgress
2664 );
2665 if (EFI_ERROR (Status)) {
2666 goto ON_EXIT;
2667 }
2668
2669 IsStatic = (BOOLEAN) (ConfigInfo->Source == IP4_CONFIG_SOURCE_STATIC);
2670
2671 ON_EXIT:
2672
2673 if (AccessResults != NULL) {
2674 FreePool (AccessResults);
2675 }
2676 if (ConfigInfo != NULL) {
2677 FreePool (ConfigInfo);
2678 }
2679 if (ConfigResp != NULL) {
2680 FreePool (ConfigResp);
2681 }
2682 if (ConfigHdr != NULL) {
2683 FreePool (ConfigHdr);
2684 }
2685
2686 return IsStatic;
2687 }
2688
2689 /**
2690 Create an IPv4 device path node.
2691
2692 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2693 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2694 Get other info from parameters to make up the whole IPv4 device path node.
2695
2696 @param[in, out] Node Pointer to the IPv4 device path node.
2697 @param[in] Controller The controller handle.
2698 @param[in] LocalIp The local IPv4 address.
2699 @param[in] LocalPort The local port.
2700 @param[in] RemoteIp The remote IPv4 address.
2701 @param[in] RemotePort The remote port.
2702 @param[in] Protocol The protocol type in the IP header.
2703 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2704
2705 **/
2706 VOID
2707 EFIAPI
2708 NetLibCreateIPv4DPathNode (
2709 IN OUT IPv4_DEVICE_PATH *Node,
2710 IN EFI_HANDLE Controller,
2711 IN IP4_ADDR LocalIp,
2712 IN UINT16 LocalPort,
2713 IN IP4_ADDR RemoteIp,
2714 IN UINT16 RemotePort,
2715 IN UINT16 Protocol,
2716 IN BOOLEAN UseDefaultAddress
2717 )
2718 {
2719 Node->Header.Type = MESSAGING_DEVICE_PATH;
2720 Node->Header.SubType = MSG_IPv4_DP;
2721 SetDevicePathNodeLength (&Node->Header, sizeof (IPv4_DEVICE_PATH));
2722
2723 CopyMem (&Node->LocalIpAddress, &LocalIp, sizeof (EFI_IPv4_ADDRESS));
2724 CopyMem (&Node->RemoteIpAddress, &RemoteIp, sizeof (EFI_IPv4_ADDRESS));
2725
2726 Node->LocalPort = LocalPort;
2727 Node->RemotePort = RemotePort;
2728
2729 Node->Protocol = Protocol;
2730
2731 if (!UseDefaultAddress) {
2732 Node->StaticIpAddress = TRUE;
2733 } else {
2734 Node->StaticIpAddress = NetLibDefaultAddressIsStatic (Controller);
2735 }
2736
2737 //
2738 // Set the Gateway IP address to default value 0:0:0:0.
2739 // Set the Subnet mask to default value 255:255:255:0.
2740 //
2741 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv4_ADDRESS));
2742 SetMem (&Node->SubnetMask, sizeof (EFI_IPv4_ADDRESS), 0xff);
2743 Node->SubnetMask.Addr[3] = 0;
2744 }
2745
2746 /**
2747 Create an IPv6 device path node.
2748
2749 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2750 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2751 Get other info from parameters to make up the whole IPv6 device path node.
2752
2753 @param[in, out] Node Pointer to the IPv6 device path node.
2754 @param[in] Controller The controller handle.
2755 @param[in] LocalIp The local IPv6 address.
2756 @param[in] LocalPort The local port.
2757 @param[in] RemoteIp The remote IPv6 address.
2758 @param[in] RemotePort The remote port.
2759 @param[in] Protocol The protocol type in the IP header.
2760
2761 **/
2762 VOID
2763 EFIAPI
2764 NetLibCreateIPv6DPathNode (
2765 IN OUT IPv6_DEVICE_PATH *Node,
2766 IN EFI_HANDLE Controller,
2767 IN EFI_IPv6_ADDRESS *LocalIp,
2768 IN UINT16 LocalPort,
2769 IN EFI_IPv6_ADDRESS *RemoteIp,
2770 IN UINT16 RemotePort,
2771 IN UINT16 Protocol
2772 )
2773 {
2774 Node->Header.Type = MESSAGING_DEVICE_PATH;
2775 Node->Header.SubType = MSG_IPv6_DP;
2776 SetDevicePathNodeLength (&Node->Header, sizeof (IPv6_DEVICE_PATH));
2777
2778 CopyMem (&Node->LocalIpAddress, LocalIp, sizeof (EFI_IPv6_ADDRESS));
2779 CopyMem (&Node->RemoteIpAddress, RemoteIp, sizeof (EFI_IPv6_ADDRESS));
2780
2781 Node->LocalPort = LocalPort;
2782 Node->RemotePort = RemotePort;
2783
2784 Node->Protocol = Protocol;
2785
2786 //
2787 // Set default value to IPAddressOrigin, PrefixLength.
2788 // Set the Gateway IP address to unspecified address.
2789 //
2790 Node->IpAddressOrigin = 0;
2791 Node->PrefixLength = IP6_PREFIX_LENGTH;
2792 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv6_ADDRESS));
2793 }
2794
2795 /**
2796 Find the UNDI/SNP handle from controller and protocol GUID.
2797
2798 For example, IP will open a MNP child to transmit/receive
2799 packets, when MNP is stopped, IP should also be stopped. IP
2800 needs to find its own private data which is related the IP's
2801 service binding instance that is install on UNDI/SNP handle.
2802 Now, the controller is either a MNP or ARP child handle. But
2803 IP opens these handle BY_DRIVER, use that info, we can get the
2804 UNDI/SNP handle.
2805
2806 @param[in] Controller Then protocol handle to check.
2807 @param[in] ProtocolGuid The protocol that is related with the handle.
2808
2809 @return The UNDI/SNP handle or NULL for errors.
2810
2811 **/
2812 EFI_HANDLE
2813 EFIAPI
2814 NetLibGetNicHandle (
2815 IN EFI_HANDLE Controller,
2816 IN EFI_GUID *ProtocolGuid
2817 )
2818 {
2819 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenBuffer;
2820 EFI_HANDLE Handle;
2821 EFI_STATUS Status;
2822 UINTN OpenCount;
2823 UINTN Index;
2824
2825 Status = gBS->OpenProtocolInformation (
2826 Controller,
2827 ProtocolGuid,
2828 &OpenBuffer,
2829 &OpenCount
2830 );
2831
2832 if (EFI_ERROR (Status)) {
2833 return NULL;
2834 }
2835
2836 Handle = NULL;
2837
2838 for (Index = 0; Index < OpenCount; Index++) {
2839 if ((OpenBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {
2840 Handle = OpenBuffer[Index].ControllerHandle;
2841 break;
2842 }
2843 }
2844
2845 gBS->FreePool (OpenBuffer);
2846 return Handle;
2847 }
2848
2849 /**
2850 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2851
2852 @param[in] String The pointer to the Ascii string.
2853 @param[out] Ip4Address The pointer to the converted IPv4 address.
2854
2855 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2856 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2857
2858 **/
2859 EFI_STATUS
2860 EFIAPI
2861 NetLibAsciiStrToIp4 (
2862 IN CONST CHAR8 *String,
2863 OUT EFI_IPv4_ADDRESS *Ip4Address
2864 )
2865 {
2866 UINT8 Index;
2867 CHAR8 *Ip4Str;
2868 CHAR8 *TempStr;
2869 UINTN NodeVal;
2870
2871 if ((String == NULL) || (Ip4Address == NULL)) {
2872 return EFI_INVALID_PARAMETER;
2873 }
2874
2875 Ip4Str = (CHAR8 *) String;
2876
2877 for (Index = 0; Index < 4; Index++) {
2878 TempStr = Ip4Str;
2879
2880 while ((*Ip4Str != '\0') && (*Ip4Str != '.')) {
2881 Ip4Str++;
2882 }
2883
2884 //
2885 // The IPv4 address is X.X.X.X
2886 //
2887 if (*Ip4Str == '.') {
2888 if (Index == 3) {
2889 return EFI_INVALID_PARAMETER;
2890 }
2891 } else {
2892 if (Index != 3) {
2893 return EFI_INVALID_PARAMETER;
2894 }
2895 }
2896
2897 //
2898 // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the
2899 // first character that is not a valid decimal character, '.' or '\0' here.
2900 //
2901 NodeVal = AsciiStrDecimalToUintn (TempStr);
2902 if (NodeVal > 0xFF) {
2903 return EFI_INVALID_PARAMETER;
2904 }
2905
2906 Ip4Address->Addr[Index] = (UINT8) NodeVal;
2907
2908 Ip4Str++;
2909 }
2910
2911 return EFI_SUCCESS;
2912 }
2913
2914
2915 /**
2916 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2917 string is defined in RFC 4291 - Text Pepresentation of Addresses.
2918
2919 @param[in] String The pointer to the Ascii string.
2920 @param[out] Ip6Address The pointer to the converted IPv6 address.
2921
2922 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2923 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2924
2925 **/
2926 EFI_STATUS
2927 EFIAPI
2928 NetLibAsciiStrToIp6 (
2929 IN CONST CHAR8 *String,
2930 OUT EFI_IPv6_ADDRESS *Ip6Address
2931 )
2932 {
2933 UINT8 Index;
2934 CHAR8 *Ip6Str;
2935 CHAR8 *TempStr;
2936 CHAR8 *TempStr2;
2937 UINT8 NodeCnt;
2938 UINT8 TailNodeCnt;
2939 UINT8 AllowedCnt;
2940 UINTN NodeVal;
2941 BOOLEAN Short;
2942 BOOLEAN Update;
2943 BOOLEAN LeadZero;
2944 UINT8 LeadZeroCnt;
2945 UINT8 Cnt;
2946
2947 if ((String == NULL) || (Ip6Address == NULL)) {
2948 return EFI_INVALID_PARAMETER;
2949 }
2950
2951 Ip6Str = (CHAR8 *) String;
2952 AllowedCnt = 6;
2953 LeadZeroCnt = 0;
2954
2955 //
2956 // An IPv6 address leading with : looks strange.
2957 //
2958 if (*Ip6Str == ':') {
2959 if (*(Ip6Str + 1) != ':') {
2960 return EFI_INVALID_PARAMETER;
2961 } else {
2962 AllowedCnt = 7;
2963 }
2964 }
2965
2966 ZeroMem (Ip6Address, sizeof (EFI_IPv6_ADDRESS));
2967
2968 NodeCnt = 0;
2969 TailNodeCnt = 0;
2970 Short = FALSE;
2971 Update = FALSE;
2972 LeadZero = FALSE;
2973
2974 for (Index = 0; Index < 15; Index = (UINT8) (Index + 2)) {
2975 TempStr = Ip6Str;
2976
2977 while ((*Ip6Str != '\0') && (*Ip6Str != ':')) {
2978 Ip6Str++;
2979 }
2980
2981 if ((*Ip6Str == '\0') && (Index != 14)) {
2982 return EFI_INVALID_PARAMETER;
2983 }
2984
2985 if (*Ip6Str == ':') {
2986 if (*(Ip6Str + 1) == ':') {
2987 if ((NodeCnt > 6) ||
2988 ((*(Ip6Str + 2) != '\0') && (AsciiStrHexToUintn (Ip6Str + 2) == 0))) {
2989 //
2990 // ::0 looks strange. report error to user.
2991 //
2992 return EFI_INVALID_PARAMETER;
2993 }
2994 if ((NodeCnt == 6) && (*(Ip6Str + 2) != '\0') &&
2995 (AsciiStrHexToUintn (Ip6Str + 2) != 0)) {
2996 return EFI_INVALID_PARAMETER;
2997 }
2998
2999 //
3000 // Skip the abbreviation part of IPv6 address.
3001 //
3002 TempStr2 = Ip6Str + 2;
3003 while ((*TempStr2 != '\0')) {
3004 if (*TempStr2 == ':') {
3005 if (*(TempStr2 + 1) == ':') {
3006 //
3007 // :: can only appear once in IPv6 address.
3008 //
3009 return EFI_INVALID_PARAMETER;
3010 }
3011
3012 TailNodeCnt++;
3013 if (TailNodeCnt >= (AllowedCnt - NodeCnt)) {
3014 //
3015 // :: indicates one or more groups of 16 bits of zeros.
3016 //
3017 return EFI_INVALID_PARAMETER;
3018 }
3019 }
3020
3021 TempStr2++;
3022 }
3023
3024 Short = TRUE;
3025 Update = TRUE;
3026
3027 Ip6Str = Ip6Str + 2;
3028 } else {
3029 if (*(Ip6Str + 1) == '\0') {
3030 return EFI_INVALID_PARAMETER;
3031 }
3032 Ip6Str++;
3033 NodeCnt++;
3034 if ((Short && (NodeCnt > 6)) || (!Short && (NodeCnt > 7))) {
3035 //
3036 // There are more than 8 groups of 16 bits of zeros.
3037 //
3038 return EFI_INVALID_PARAMETER;
3039 }
3040 }
3041 }
3042
3043 //
3044 // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first
3045 // character that is not a valid hexadecimal character, ':' or '\0' here.
3046 //
3047 NodeVal = AsciiStrHexToUintn (TempStr);
3048 if ((NodeVal > 0xFFFF) || (Index > 14)) {
3049 return EFI_INVALID_PARAMETER;
3050 }
3051 if (NodeVal != 0) {
3052 if ((*TempStr == '0') &&
3053 ((*(TempStr + 2) == ':') || (*(TempStr + 3) == ':') ||
3054 (*(TempStr + 2) == '\0') || (*(TempStr + 3) == '\0'))) {
3055 return EFI_INVALID_PARAMETER;
3056 }
3057 if ((*TempStr == '0') && (*(TempStr + 4) != '\0') &&
3058 (*(TempStr + 4) != ':')) {
3059 return EFI_INVALID_PARAMETER;
3060 }
3061 } else {
3062 if (((*TempStr == '0') && (*(TempStr + 1) == '0') &&
3063 ((*(TempStr + 2) == ':') || (*(TempStr + 2) == '\0'))) ||
3064 ((*TempStr == '0') && (*(TempStr + 1) == '0') && (*(TempStr + 2) == '0') &&
3065 ((*(TempStr + 3) == ':') || (*(TempStr + 3) == '\0')))) {
3066 return EFI_INVALID_PARAMETER;
3067 }
3068 }
3069
3070 Cnt = 0;
3071 while ((TempStr[Cnt] != ':') && (TempStr[Cnt] != '\0')) {
3072 Cnt++;
3073 }
3074 if (LeadZeroCnt == 0) {
3075 if ((Cnt == 4) && (*TempStr == '0')) {
3076 LeadZero = TRUE;
3077 LeadZeroCnt++;
3078 }
3079 if ((Cnt != 0) && (Cnt < 4)) {
3080 LeadZero = FALSE;
3081 LeadZeroCnt++;
3082 }
3083 } else {
3084 if ((Cnt == 4) && (*TempStr == '0') && !LeadZero) {
3085 return EFI_INVALID_PARAMETER;
3086 }
3087 if ((Cnt != 0) && (Cnt < 4) && LeadZero) {
3088 return EFI_INVALID_PARAMETER;
3089 }
3090 }
3091
3092 Ip6Address->Addr[Index] = (UINT8) (NodeVal >> 8);
3093 Ip6Address->Addr[Index + 1] = (UINT8) (NodeVal & 0xFF);
3094
3095 //
3096 // Skip the groups of zeros by ::
3097 //
3098 if (Short && Update) {
3099 Index = (UINT8) (16 - (TailNodeCnt + 2) * 2);
3100 Update = FALSE;
3101 }
3102 }
3103
3104 if ((!Short && Index != 16) || (*Ip6Str != '\0')) {
3105 return EFI_INVALID_PARAMETER;
3106 }
3107
3108 return EFI_SUCCESS;
3109 }
3110
3111
3112 /**
3113 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
3114
3115 @param[in] String The pointer to the Ascii string.
3116 @param[out] Ip4Address The pointer to the converted IPv4 address.
3117
3118 @retval EFI_SUCCESS Convert to IPv4 address successfully.
3119 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
3120 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3121
3122 **/
3123 EFI_STATUS
3124 EFIAPI
3125 NetLibStrToIp4 (
3126 IN CONST CHAR16 *String,
3127 OUT EFI_IPv4_ADDRESS *Ip4Address
3128 )
3129 {
3130 CHAR8 *Ip4Str;
3131 EFI_STATUS Status;
3132
3133 if ((String == NULL) || (Ip4Address == NULL)) {
3134 return EFI_INVALID_PARAMETER;
3135 }
3136
3137 Ip4Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3138 if (Ip4Str == NULL) {
3139 return EFI_OUT_OF_RESOURCES;
3140 }
3141
3142 UnicodeStrToAsciiStr (String, Ip4Str);
3143
3144 Status = NetLibAsciiStrToIp4 (Ip4Str, Ip4Address);
3145
3146 FreePool (Ip4Str);
3147
3148 return Status;
3149 }
3150
3151
3152 /**
3153 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
3154 the string is defined in RFC 4291 - Text Pepresentation of Addresses.
3155
3156 @param[in] String The pointer to the Ascii string.
3157 @param[out] Ip6Address The pointer to the converted IPv6 address.
3158
3159 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3160 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3161 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3162
3163 **/
3164 EFI_STATUS
3165 EFIAPI
3166 NetLibStrToIp6 (
3167 IN CONST CHAR16 *String,
3168 OUT EFI_IPv6_ADDRESS *Ip6Address
3169 )
3170 {
3171 CHAR8 *Ip6Str;
3172 EFI_STATUS Status;
3173
3174 if ((String == NULL) || (Ip6Address == NULL)) {
3175 return EFI_INVALID_PARAMETER;
3176 }
3177
3178 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3179 if (Ip6Str == NULL) {
3180 return EFI_OUT_OF_RESOURCES;
3181 }
3182
3183 UnicodeStrToAsciiStr (String, Ip6Str);
3184
3185 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3186
3187 FreePool (Ip6Str);
3188
3189 return Status;
3190 }
3191
3192 /**
3193 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3194 The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses
3195 Prefixes: ipv6-address/prefix-length.
3196
3197 @param[in] String The pointer to the Ascii string.
3198 @param[out] Ip6Address The pointer to the converted IPv6 address.
3199 @param[out] PrefixLength The pointer to the converted prefix length.
3200
3201 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3202 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3203 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3204
3205 **/
3206 EFI_STATUS
3207 EFIAPI
3208 NetLibStrToIp6andPrefix (
3209 IN CONST CHAR16 *String,
3210 OUT EFI_IPv6_ADDRESS *Ip6Address,
3211 OUT UINT8 *PrefixLength
3212 )
3213 {
3214 CHAR8 *Ip6Str;
3215 CHAR8 *PrefixStr;
3216 CHAR8 *TempStr;
3217 EFI_STATUS Status;
3218 UINT8 Length;
3219
3220 if ((String == NULL) || (Ip6Address == NULL) || (PrefixLength == NULL)) {
3221 return EFI_INVALID_PARAMETER;
3222 }
3223
3224 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3225 if (Ip6Str == NULL) {
3226 return EFI_OUT_OF_RESOURCES;
3227 }
3228
3229 UnicodeStrToAsciiStr (String, Ip6Str);
3230
3231 //
3232 // Get the sub string describing prefix length.
3233 //
3234 TempStr = Ip6Str;
3235 while (*TempStr != '\0' && (*TempStr != '/')) {
3236 TempStr++;
3237 }
3238
3239 if (*TempStr == '/') {
3240 PrefixStr = TempStr + 1;
3241 } else {
3242 PrefixStr = NULL;
3243 }
3244
3245 //
3246 // Get the sub string describing IPv6 address and convert it.
3247 //
3248 *TempStr = '\0';
3249
3250 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3251 if (EFI_ERROR (Status)) {
3252 goto Exit;
3253 }
3254
3255 //
3256 // If input string doesn't indicate the prefix length, return 0xff.
3257 //
3258 Length = 0xFF;
3259
3260 //
3261 // Convert the string to prefix length
3262 //
3263 if (PrefixStr != NULL) {
3264
3265 Status = EFI_INVALID_PARAMETER;
3266 Length = 0;
3267 while (*PrefixStr != '\0') {
3268 if (NET_IS_DIGIT (*PrefixStr)) {
3269 Length = (UINT8) (Length * 10 + (*PrefixStr - '0'));
3270 if (Length >= IP6_PREFIX_NUM) {
3271 goto Exit;
3272 }
3273 } else {
3274 goto Exit;
3275 }
3276
3277 PrefixStr++;
3278 }
3279 }
3280
3281 *PrefixLength = Length;
3282 Status = EFI_SUCCESS;
3283
3284 Exit:
3285
3286 FreePool (Ip6Str);
3287 return Status;
3288 }
3289
3290 /**
3291
3292 Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string.
3293 The text representation of address is defined in RFC 4291.
3294
3295 @param[in] Ip6Address The pointer to the IPv6 address.
3296 @param[out] String The buffer to return the converted string.
3297 @param[in] StringSize The length in bytes of the input String.
3298
3299 @retval EFI_SUCCESS Convert to string successfully.
3300 @retval EFI_INVALID_PARAMETER The input parameter is invalid.
3301 @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been
3302 updated with the size needed to complete the request.
3303 **/
3304 EFI_STATUS
3305 EFIAPI
3306 NetLibIp6ToStr (
3307 IN EFI_IPv6_ADDRESS *Ip6Address,
3308 OUT CHAR16 *String,
3309 IN UINTN StringSize
3310 )
3311 {
3312 UINT16 Ip6Addr[8];
3313 UINTN Index;
3314 UINTN LongestZerosStart;
3315 UINTN LongestZerosLength;
3316 UINTN CurrentZerosStart;
3317 UINTN CurrentZerosLength;
3318 CHAR16 Buffer[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"];
3319 CHAR16 *Ptr;
3320
3321 if (Ip6Address == NULL || String == NULL || StringSize == 0) {
3322 return EFI_INVALID_PARAMETER;
3323 }
3324
3325 //
3326 // Convert the UINT8 array to an UINT16 array for easy handling.
3327 //
3328 ZeroMem (Ip6Addr, sizeof (Ip6Addr));
3329 for (Index = 0; Index < 16; Index++) {
3330 Ip6Addr[Index / 2] |= (Ip6Address->Addr[Index] << ((1 - (Index % 2)) << 3));
3331 }
3332
3333 //
3334 // Find the longest zeros and mark it.
3335 //
3336 CurrentZerosStart = DEFAULT_ZERO_START;
3337 CurrentZerosLength = 0;
3338 LongestZerosStart = DEFAULT_ZERO_START;
3339 LongestZerosLength = 0;
3340 for (Index = 0; Index < 8; Index++) {
3341 if (Ip6Addr[Index] == 0) {
3342 if (CurrentZerosStart == DEFAULT_ZERO_START) {
3343 CurrentZerosStart = Index;
3344 CurrentZerosLength = 1;
3345 } else {
3346 CurrentZerosLength++;
3347 }
3348 } else {
3349 if (CurrentZerosStart != DEFAULT_ZERO_START) {
3350 if (CurrentZerosLength > 2 && (LongestZerosStart == (DEFAULT_ZERO_START) || CurrentZerosLength > LongestZerosLength)) {
3351 LongestZerosStart = CurrentZerosStart;
3352 LongestZerosLength = CurrentZerosLength;
3353 }
3354 CurrentZerosStart = DEFAULT_ZERO_START;
3355 CurrentZerosLength = 0;
3356 }
3357 }
3358 }
3359
3360 if (CurrentZerosStart != DEFAULT_ZERO_START && CurrentZerosLength > 2) {
3361 if (LongestZerosStart == DEFAULT_ZERO_START || LongestZerosLength < CurrentZerosLength) {
3362 LongestZerosStart = CurrentZerosStart;
3363 LongestZerosLength = CurrentZerosLength;
3364 }
3365 }
3366
3367 Ptr = Buffer;
3368 for (Index = 0; Index < 8; Index++) {
3369 if (LongestZerosStart != DEFAULT_ZERO_START && Index >= LongestZerosStart && Index < LongestZerosStart + LongestZerosLength) {
3370 if (Index == LongestZerosStart) {
3371 *Ptr++ = L':';
3372 }
3373 continue;
3374 }
3375 if (Index != 0) {
3376 *Ptr++ = L':';
3377 }
3378 Ptr += UnicodeSPrint(Ptr, 10, L"%x", Ip6Addr[Index]);
3379 }
3380
3381 if (LongestZerosStart != DEFAULT_ZERO_START && LongestZerosStart + LongestZerosLength == 8) {
3382 *Ptr++ = L':';
3383 }
3384 *Ptr = L'\0';
3385
3386 if ((UINTN)Ptr - (UINTN)Buffer > StringSize) {
3387 return EFI_BUFFER_TOO_SMALL;
3388 }
3389
3390 StrCpy (String, Buffer);
3391
3392 return EFI_SUCCESS;
3393 }
3394
3395 /**
3396 This function obtains the system guid from the smbios table.
3397
3398 @param[out] SystemGuid The pointer of the returned system guid.
3399
3400 @retval EFI_SUCCESS Successfully obtained the system guid.
3401 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3402
3403 **/
3404 EFI_STATUS
3405 EFIAPI
3406 NetLibGetSystemGuid (
3407 OUT EFI_GUID *SystemGuid
3408 )
3409 {
3410 EFI_STATUS Status;
3411 SMBIOS_TABLE_ENTRY_POINT *SmbiosTable;
3412 SMBIOS_STRUCTURE_POINTER Smbios;
3413 SMBIOS_STRUCTURE_POINTER SmbiosEnd;
3414 CHAR8 *String;
3415
3416 SmbiosTable = NULL;
3417 Status = EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid, (VOID **) &SmbiosTable);
3418
3419 if (EFI_ERROR (Status) || SmbiosTable == NULL) {
3420 return EFI_NOT_FOUND;
3421 }
3422
3423 Smbios.Hdr = (SMBIOS_STRUCTURE *) (UINTN) SmbiosTable->TableAddress;
3424 SmbiosEnd.Raw = (UINT8 *) (UINTN) (SmbiosTable->TableAddress + SmbiosTable->TableLength);
3425
3426 do {
3427 if (Smbios.Hdr->Type == 1) {
3428 if (Smbios.Hdr->Length < 0x19) {
3429 //
3430 // Older version did not support UUID.
3431 //
3432 return EFI_NOT_FOUND;
3433 }
3434
3435 //
3436 // SMBIOS tables are byte packed so we need to do a byte copy to
3437 // prevend alignment faults on Itanium-based platform.
3438 //
3439 CopyMem (SystemGuid, &Smbios.Type1->Uuid, sizeof (EFI_GUID));
3440 return EFI_SUCCESS;
3441 }
3442
3443 //
3444 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3445 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3446 // to skip one SMBIOS structure.
3447 //
3448
3449 //
3450 // Step 1: Skip over formatted section.
3451 //
3452 String = (CHAR8 *) (Smbios.Raw + Smbios.Hdr->Length);
3453
3454 //
3455 // Step 2: Skip over unformated string section.
3456 //
3457 do {
3458 //
3459 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3460 // is terminated with an additional NULL(00h) BYTE.
3461 //
3462 for ( ; *String != 0; String++) {
3463 }
3464
3465 if (*(UINT8*)++String == 0) {
3466 //
3467 // Pointer to the next SMBIOS structure.
3468 //
3469 Smbios.Raw = (UINT8 *)++String;
3470 break;
3471 }
3472 } while (TRUE);
3473 } while (Smbios.Raw < SmbiosEnd.Raw);
3474 return EFI_NOT_FOUND;
3475 }