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