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