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