]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Library/DxeNetLib/DxeNetLib.c
f74dcdaeae860f94a2ab0133298934bb71cffc01
[mirror_edk2.git] / MdeModulePkg / Library / DxeNetLib / DxeNetLib.c
1 /** @file
2 Network library.
3
4 Copyright (c) 2005 - 2012, 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 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2134 return Status;
2135 }
2136
2137 //
2138 // Try to get SNP mode from MNP
2139 //
2140 Status = Mnp->GetModeData (Mnp, NULL, &SnpModeData);
2141 if (EFI_ERROR (Status)) {
2142 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2143 return Status;
2144 }
2145 SnpMode = &SnpModeData;
2146
2147 //
2148 // Destroy the MNP child
2149 //
2150 MnpSb->DestroyChild (MnpSb, MnpChildHandle);
2151 }
2152
2153 *AddressSize = SnpMode->HwAddressSize;
2154 CopyMem (MacAddress->Addr, SnpMode->CurrentAddress.Addr, SnpMode->HwAddressSize);
2155
2156 return EFI_SUCCESS;
2157 }
2158
2159 /**
2160 Convert MAC address of the NIC associated with specified Service Binding Handle
2161 to a unicode string. Callers are responsible for freeing the string storage.
2162
2163 Locate simple network protocol associated with the Service Binding Handle and
2164 get the mac address from SNP. Then convert the mac address into a unicode
2165 string. It takes 2 unicode characters to represent a 1 byte binary buffer.
2166 Plus one unicode character for the null-terminator.
2167
2168 @param[in] ServiceHandle The handle where network service binding protocol is
2169 installed on.
2170 @param[in] ImageHandle The image handle used to act as the agent handle to
2171 get the simple network protocol. This parameter is
2172 optional and may be NULL.
2173 @param[out] MacString The pointer to store the address of the string
2174 representation of the mac address.
2175
2176 @retval EFI_SUCCESS Convert the mac address a unicode string successfully.
2177 @retval EFI_OUT_OF_RESOURCES There are not enough memory resource.
2178 @retval Others Failed to open the simple network protocol.
2179
2180 **/
2181 EFI_STATUS
2182 EFIAPI
2183 NetLibGetMacString (
2184 IN EFI_HANDLE ServiceHandle,
2185 IN EFI_HANDLE ImageHandle, OPTIONAL
2186 OUT CHAR16 **MacString
2187 )
2188 {
2189 EFI_STATUS Status;
2190 EFI_MAC_ADDRESS MacAddress;
2191 UINT8 *HwAddress;
2192 UINTN HwAddressSize;
2193 UINT16 VlanId;
2194 CHAR16 *String;
2195 UINTN Index;
2196
2197 ASSERT (MacString != NULL);
2198
2199 //
2200 // Get MAC address of the network device
2201 //
2202 Status = NetLibGetMacAddress (ServiceHandle, &MacAddress, &HwAddressSize);
2203 if (EFI_ERROR (Status)) {
2204 return Status;
2205 }
2206
2207 //
2208 // It takes 2 unicode characters to represent a 1 byte binary buffer.
2209 // If VLAN is configured, it will need extra 5 characters like "\0005".
2210 // Plus one unicode character for the null-terminator.
2211 //
2212 String = AllocateZeroPool ((2 * HwAddressSize + 5 + 1) * sizeof (CHAR16));
2213 if (String == NULL) {
2214 return EFI_OUT_OF_RESOURCES;
2215 }
2216 *MacString = String;
2217
2218 //
2219 // Convert the MAC address into a unicode string.
2220 //
2221 HwAddress = &MacAddress.Addr[0];
2222 for (Index = 0; Index < HwAddressSize; Index++) {
2223 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, *(HwAddress++), 2);
2224 }
2225
2226 //
2227 // Append VLAN ID if any
2228 //
2229 VlanId = NetLibGetVlanId (ServiceHandle);
2230 if (VlanId != 0) {
2231 *String++ = L'\\';
2232 String += UnicodeValueToString (String, PREFIX_ZERO | RADIX_HEX, VlanId, 4);
2233 }
2234
2235 //
2236 // Null terminate the Unicode string
2237 //
2238 *String = L'\0';
2239
2240 return EFI_SUCCESS;
2241 }
2242
2243 /**
2244 Detect media status for specified network device.
2245
2246 The underlying UNDI driver may or may not support reporting media status from
2247 GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine
2248 will try to invoke Snp->GetStatus() to get the media status: if media already
2249 present, it return directly; if media not present, it will stop SNP and then
2250 restart SNP to get the latest media status, this give chance to get the correct
2251 media status for old UNDI driver which doesn't support reporting media status
2252 from GET_STATUS command.
2253 Note: there will be two limitations for current algorithm:
2254 1) for UNDI with this capability, in case of cable is not attached, there will
2255 be an redundant Stop/Start() process;
2256 2) for UNDI without this capability, in case that network cable is attached when
2257 Snp->Initialize() is invoked while network cable is unattached later,
2258 NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer
2259 apps to wait for timeout time.
2260
2261 @param[in] ServiceHandle The handle where network service binding protocols are
2262 installed on.
2263 @param[out] MediaPresent The pointer to store the media status.
2264
2265 @retval EFI_SUCCESS Media detection success.
2266 @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle.
2267 @retval EFI_UNSUPPORTED Network device does not support media detection.
2268 @retval EFI_DEVICE_ERROR SNP is in unknown state.
2269
2270 **/
2271 EFI_STATUS
2272 EFIAPI
2273 NetLibDetectMedia (
2274 IN EFI_HANDLE ServiceHandle,
2275 OUT BOOLEAN *MediaPresent
2276 )
2277 {
2278 EFI_STATUS Status;
2279 EFI_HANDLE SnpHandle;
2280 EFI_SIMPLE_NETWORK_PROTOCOL *Snp;
2281 UINT32 InterruptStatus;
2282 UINT32 OldState;
2283 EFI_MAC_ADDRESS *MCastFilter;
2284 UINT32 MCastFilterCount;
2285 UINT32 EnableFilterBits;
2286 UINT32 DisableFilterBits;
2287 BOOLEAN ResetMCastFilters;
2288
2289 ASSERT (MediaPresent != NULL);
2290
2291 //
2292 // Get SNP handle
2293 //
2294 Snp = NULL;
2295 SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);
2296 if (SnpHandle == NULL) {
2297 return EFI_INVALID_PARAMETER;
2298 }
2299
2300 //
2301 // Check whether SNP support media detection
2302 //
2303 if (!Snp->Mode->MediaPresentSupported) {
2304 return EFI_UNSUPPORTED;
2305 }
2306
2307 //
2308 // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data
2309 //
2310 Status = Snp->GetStatus (Snp, &InterruptStatus, NULL);
2311 if (EFI_ERROR (Status)) {
2312 return Status;
2313 }
2314
2315 if (Snp->Mode->MediaPresent) {
2316 //
2317 // Media is present, return directly
2318 //
2319 *MediaPresent = TRUE;
2320 return EFI_SUCCESS;
2321 }
2322
2323 //
2324 // Till now, GetStatus() report no media; while, in case UNDI not support
2325 // reporting media status from GetStatus(), this media status may be incorrect.
2326 // So, we will stop SNP and then restart it to get the correct media status.
2327 //
2328 OldState = Snp->Mode->State;
2329 if (OldState >= EfiSimpleNetworkMaxState) {
2330 return EFI_DEVICE_ERROR;
2331 }
2332
2333 MCastFilter = NULL;
2334
2335 if (OldState == EfiSimpleNetworkInitialized) {
2336 //
2337 // SNP is already in use, need Shutdown/Stop and then Start/Initialize
2338 //
2339
2340 //
2341 // Backup current SNP receive filter settings
2342 //
2343 EnableFilterBits = Snp->Mode->ReceiveFilterSetting;
2344 DisableFilterBits = Snp->Mode->ReceiveFilterMask ^ EnableFilterBits;
2345
2346 ResetMCastFilters = TRUE;
2347 MCastFilterCount = Snp->Mode->MCastFilterCount;
2348 if (MCastFilterCount != 0) {
2349 MCastFilter = AllocateCopyPool (
2350 MCastFilterCount * sizeof (EFI_MAC_ADDRESS),
2351 Snp->Mode->MCastFilter
2352 );
2353 ASSERT (MCastFilter != NULL);
2354
2355 ResetMCastFilters = FALSE;
2356 }
2357
2358 //
2359 // Shutdown/Stop the simple network
2360 //
2361 Status = Snp->Shutdown (Snp);
2362 if (!EFI_ERROR (Status)) {
2363 Status = Snp->Stop (Snp);
2364 }
2365 if (EFI_ERROR (Status)) {
2366 goto Exit;
2367 }
2368
2369 //
2370 // Start/Initialize the simple network
2371 //
2372 Status = Snp->Start (Snp);
2373 if (!EFI_ERROR (Status)) {
2374 Status = Snp->Initialize (Snp, 0, 0);
2375 }
2376 if (EFI_ERROR (Status)) {
2377 goto Exit;
2378 }
2379
2380 //
2381 // Here we get the correct media status
2382 //
2383 *MediaPresent = Snp->Mode->MediaPresent;
2384
2385 //
2386 // Restore SNP receive filter settings
2387 //
2388 Status = Snp->ReceiveFilters (
2389 Snp,
2390 EnableFilterBits,
2391 DisableFilterBits,
2392 ResetMCastFilters,
2393 MCastFilterCount,
2394 MCastFilter
2395 );
2396
2397 if (MCastFilter != NULL) {
2398 FreePool (MCastFilter);
2399 }
2400
2401 return Status;
2402 }
2403
2404 //
2405 // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted
2406 //
2407 if (OldState == EfiSimpleNetworkStopped) {
2408 //
2409 // SNP not start yet, start it
2410 //
2411 Status = Snp->Start (Snp);
2412 if (EFI_ERROR (Status)) {
2413 goto Exit;
2414 }
2415 }
2416
2417 //
2418 // Initialize the simple network
2419 //
2420 Status = Snp->Initialize (Snp, 0, 0);
2421 if (EFI_ERROR (Status)) {
2422 Status = EFI_DEVICE_ERROR;
2423 goto Exit;
2424 }
2425
2426 //
2427 // Here we get the correct media status
2428 //
2429 *MediaPresent = Snp->Mode->MediaPresent;
2430
2431 //
2432 // Shut down the simple network
2433 //
2434 Snp->Shutdown (Snp);
2435
2436 Exit:
2437 if (OldState == EfiSimpleNetworkStopped) {
2438 //
2439 // Original SNP sate is Stopped, restore to original state
2440 //
2441 Snp->Stop (Snp);
2442 }
2443
2444 if (MCastFilter != NULL) {
2445 FreePool (MCastFilter);
2446 }
2447
2448 return Status;
2449 }
2450
2451 /**
2452 Check the default address used by the IPv4 driver is static or dynamic (acquired
2453 from DHCP).
2454
2455 If the controller handle does not have the NIC Ip4 Config Protocol installed, the
2456 default address is static. If the EFI variable to save the configuration is not found,
2457 the default address is static. Otherwise, get the result from the EFI variable which
2458 saving the configuration.
2459
2460 @param[in] Controller The controller handle which has the NIC Ip4 Config Protocol
2461 relative with the default address to judge.
2462
2463 @retval TRUE If the default address is static.
2464 @retval FALSE If the default address is acquired from DHCP.
2465
2466 **/
2467 BOOLEAN
2468 NetLibDefaultAddressIsStatic (
2469 IN EFI_HANDLE Controller
2470 )
2471 {
2472 EFI_STATUS Status;
2473 EFI_HII_CONFIG_ROUTING_PROTOCOL *HiiConfigRouting;
2474 UINTN Len;
2475 NIC_IP4_CONFIG_INFO *ConfigInfo;
2476 BOOLEAN IsStatic;
2477 EFI_STRING ConfigHdr;
2478 EFI_STRING ConfigResp;
2479 EFI_STRING AccessProgress;
2480 EFI_STRING AccessResults;
2481 EFI_STRING String;
2482 EFI_HANDLE ChildHandle;
2483
2484 ConfigInfo = NULL;
2485 ConfigHdr = NULL;
2486 ConfigResp = NULL;
2487 AccessProgress = NULL;
2488 AccessResults = NULL;
2489 IsStatic = TRUE;
2490
2491 Status = gBS->LocateProtocol (
2492 &gEfiHiiConfigRoutingProtocolGuid,
2493 NULL,
2494 (VOID **) &HiiConfigRouting
2495 );
2496 if (EFI_ERROR (Status)) {
2497 return TRUE;
2498 }
2499
2500 Status = NetGetChildHandle (Controller, &ChildHandle);
2501 if (EFI_ERROR (Status)) {
2502 return TRUE;
2503 }
2504
2505 //
2506 // Construct config request string header
2507 //
2508 ConfigHdr = HiiConstructConfigHdr (&gEfiNicIp4ConfigVariableGuid, EFI_NIC_IP4_CONFIG_VARIABLE, ChildHandle);
2509 if (ConfigHdr == NULL) {
2510 return TRUE;
2511 }
2512
2513 Len = StrLen (ConfigHdr);
2514 ConfigResp = AllocateZeroPool ((Len + NIC_ITEM_CONFIG_SIZE * 2 + 100) * sizeof (CHAR16));
2515 if (ConfigResp == NULL) {
2516 goto ON_EXIT;
2517 }
2518 StrCpy (ConfigResp, ConfigHdr);
2519
2520 String = ConfigResp + Len;
2521 UnicodeSPrint (
2522 String,
2523 (8 + 4 + 7 + 4 + 1) * sizeof (CHAR16),
2524 L"&OFFSET=%04X&WIDTH=%04X",
2525 OFFSET_OF (NIC_IP4_CONFIG_INFO, Source),
2526 sizeof (UINT32)
2527 );
2528
2529 Status = HiiConfigRouting->ExtractConfig (
2530 HiiConfigRouting,
2531 ConfigResp,
2532 &AccessProgress,
2533 &AccessResults
2534 );
2535 if (EFI_ERROR (Status)) {
2536 goto ON_EXIT;
2537 }
2538
2539 ConfigInfo = AllocateZeroPool (NIC_ITEM_CONFIG_SIZE);
2540 if (ConfigInfo == NULL) {
2541 goto ON_EXIT;
2542 }
2543
2544 ConfigInfo->Source = IP4_CONFIG_SOURCE_STATIC;
2545 Len = NIC_ITEM_CONFIG_SIZE;
2546 Status = HiiConfigRouting->ConfigToBlock (
2547 HiiConfigRouting,
2548 AccessResults,
2549 (UINT8 *) ConfigInfo,
2550 &Len,
2551 &AccessProgress
2552 );
2553 if (EFI_ERROR (Status)) {
2554 goto ON_EXIT;
2555 }
2556
2557 IsStatic = (BOOLEAN) (ConfigInfo->Source == IP4_CONFIG_SOURCE_STATIC);
2558
2559 ON_EXIT:
2560
2561 if (AccessResults != NULL) {
2562 FreePool (AccessResults);
2563 }
2564 if (ConfigInfo != NULL) {
2565 FreePool (ConfigInfo);
2566 }
2567 if (ConfigResp != NULL) {
2568 FreePool (ConfigResp);
2569 }
2570 if (ConfigHdr != NULL) {
2571 FreePool (ConfigHdr);
2572 }
2573
2574 return IsStatic;
2575 }
2576
2577 /**
2578 Create an IPv4 device path node.
2579
2580 The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.
2581 The header subtype of IPv4 device path node is MSG_IPv4_DP.
2582 Get other info from parameters to make up the whole IPv4 device path node.
2583
2584 @param[in, out] Node Pointer to the IPv4 device path node.
2585 @param[in] Controller The controller handle.
2586 @param[in] LocalIp The local IPv4 address.
2587 @param[in] LocalPort The local port.
2588 @param[in] RemoteIp The remote IPv4 address.
2589 @param[in] RemotePort The remote port.
2590 @param[in] Protocol The protocol type in the IP header.
2591 @param[in] UseDefaultAddress Whether this instance is using default address or not.
2592
2593 **/
2594 VOID
2595 EFIAPI
2596 NetLibCreateIPv4DPathNode (
2597 IN OUT IPv4_DEVICE_PATH *Node,
2598 IN EFI_HANDLE Controller,
2599 IN IP4_ADDR LocalIp,
2600 IN UINT16 LocalPort,
2601 IN IP4_ADDR RemoteIp,
2602 IN UINT16 RemotePort,
2603 IN UINT16 Protocol,
2604 IN BOOLEAN UseDefaultAddress
2605 )
2606 {
2607 Node->Header.Type = MESSAGING_DEVICE_PATH;
2608 Node->Header.SubType = MSG_IPv4_DP;
2609 SetDevicePathNodeLength (&Node->Header, sizeof (IPv4_DEVICE_PATH));
2610
2611 CopyMem (&Node->LocalIpAddress, &LocalIp, sizeof (EFI_IPv4_ADDRESS));
2612 CopyMem (&Node->RemoteIpAddress, &RemoteIp, sizeof (EFI_IPv4_ADDRESS));
2613
2614 Node->LocalPort = LocalPort;
2615 Node->RemotePort = RemotePort;
2616
2617 Node->Protocol = Protocol;
2618
2619 if (!UseDefaultAddress) {
2620 Node->StaticIpAddress = TRUE;
2621 } else {
2622 Node->StaticIpAddress = NetLibDefaultAddressIsStatic (Controller);
2623 }
2624
2625 //
2626 // Set the Gateway IP address to default value 0:0:0:0.
2627 // Set the Subnet mask to default value 255:255:255:0.
2628 //
2629 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv4_ADDRESS));
2630 SetMem (&Node->SubnetMask, sizeof (EFI_IPv4_ADDRESS), 0xff);
2631 Node->SubnetMask.Addr[3] = 0;
2632 }
2633
2634 /**
2635 Create an IPv6 device path node.
2636
2637 The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.
2638 The header subtype of IPv6 device path node is MSG_IPv6_DP.
2639 Get other info from parameters to make up the whole IPv6 device path node.
2640
2641 @param[in, out] Node Pointer to the IPv6 device path node.
2642 @param[in] Controller The controller handle.
2643 @param[in] LocalIp The local IPv6 address.
2644 @param[in] LocalPort The local port.
2645 @param[in] RemoteIp The remote IPv6 address.
2646 @param[in] RemotePort The remote port.
2647 @param[in] Protocol The protocol type in the IP header.
2648
2649 **/
2650 VOID
2651 EFIAPI
2652 NetLibCreateIPv6DPathNode (
2653 IN OUT IPv6_DEVICE_PATH *Node,
2654 IN EFI_HANDLE Controller,
2655 IN EFI_IPv6_ADDRESS *LocalIp,
2656 IN UINT16 LocalPort,
2657 IN EFI_IPv6_ADDRESS *RemoteIp,
2658 IN UINT16 RemotePort,
2659 IN UINT16 Protocol
2660 )
2661 {
2662 Node->Header.Type = MESSAGING_DEVICE_PATH;
2663 Node->Header.SubType = MSG_IPv6_DP;
2664 SetDevicePathNodeLength (&Node->Header, sizeof (IPv6_DEVICE_PATH));
2665
2666 CopyMem (&Node->LocalIpAddress, LocalIp, sizeof (EFI_IPv6_ADDRESS));
2667 CopyMem (&Node->RemoteIpAddress, RemoteIp, sizeof (EFI_IPv6_ADDRESS));
2668
2669 Node->LocalPort = LocalPort;
2670 Node->RemotePort = RemotePort;
2671
2672 Node->Protocol = Protocol;
2673
2674 //
2675 // Set default value to IPAddressOrigin, PrefixLength.
2676 // Set the Gateway IP address to unspecified address.
2677 //
2678 Node->IpAddressOrigin = 0;
2679 Node->PrefixLength = IP6_PREFIX_LENGTH;
2680 ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv6_ADDRESS));
2681 }
2682
2683 /**
2684 Find the UNDI/SNP handle from controller and protocol GUID.
2685
2686 For example, IP will open a MNP child to transmit/receive
2687 packets, when MNP is stopped, IP should also be stopped. IP
2688 needs to find its own private data which is related the IP's
2689 service binding instance that is install on UNDI/SNP handle.
2690 Now, the controller is either a MNP or ARP child handle. But
2691 IP opens these handle BY_DRIVER, use that info, we can get the
2692 UNDI/SNP handle.
2693
2694 @param[in] Controller Then protocol handle to check.
2695 @param[in] ProtocolGuid The protocol that is related with the handle.
2696
2697 @return The UNDI/SNP handle or NULL for errors.
2698
2699 **/
2700 EFI_HANDLE
2701 EFIAPI
2702 NetLibGetNicHandle (
2703 IN EFI_HANDLE Controller,
2704 IN EFI_GUID *ProtocolGuid
2705 )
2706 {
2707 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenBuffer;
2708 EFI_HANDLE Handle;
2709 EFI_STATUS Status;
2710 UINTN OpenCount;
2711 UINTN Index;
2712
2713 Status = gBS->OpenProtocolInformation (
2714 Controller,
2715 ProtocolGuid,
2716 &OpenBuffer,
2717 &OpenCount
2718 );
2719
2720 if (EFI_ERROR (Status)) {
2721 return NULL;
2722 }
2723
2724 Handle = NULL;
2725
2726 for (Index = 0; Index < OpenCount; Index++) {
2727 if ((OpenBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) {
2728 Handle = OpenBuffer[Index].ControllerHandle;
2729 break;
2730 }
2731 }
2732
2733 gBS->FreePool (OpenBuffer);
2734 return Handle;
2735 }
2736
2737 /**
2738 Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS.
2739
2740 @param[in] String The pointer to the Ascii string.
2741 @param[out] Ip4Address The pointer to the converted IPv4 address.
2742
2743 @retval EFI_SUCCESS Convert to IPv4 address successfully.
2744 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL.
2745
2746 **/
2747 EFI_STATUS
2748 EFIAPI
2749 NetLibAsciiStrToIp4 (
2750 IN CONST CHAR8 *String,
2751 OUT EFI_IPv4_ADDRESS *Ip4Address
2752 )
2753 {
2754 UINT8 Index;
2755 CHAR8 *Ip4Str;
2756 CHAR8 *TempStr;
2757 UINTN NodeVal;
2758
2759 if ((String == NULL) || (Ip4Address == NULL)) {
2760 return EFI_INVALID_PARAMETER;
2761 }
2762
2763 Ip4Str = (CHAR8 *) String;
2764
2765 for (Index = 0; Index < 4; Index++) {
2766 TempStr = Ip4Str;
2767
2768 while ((*Ip4Str != '\0') && (*Ip4Str != '.')) {
2769 Ip4Str++;
2770 }
2771
2772 //
2773 // The IPv4 address is X.X.X.X
2774 //
2775 if (*Ip4Str == '.') {
2776 if (Index == 3) {
2777 return EFI_INVALID_PARAMETER;
2778 }
2779 } else {
2780 if (Index != 3) {
2781 return EFI_INVALID_PARAMETER;
2782 }
2783 }
2784
2785 //
2786 // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the
2787 // first character that is not a valid decimal character, '.' or '\0' here.
2788 //
2789 NodeVal = AsciiStrDecimalToUintn (TempStr);
2790 if (NodeVal > 0xFF) {
2791 return EFI_INVALID_PARAMETER;
2792 }
2793
2794 Ip4Address->Addr[Index] = (UINT8) NodeVal;
2795
2796 Ip4Str++;
2797 }
2798
2799 return EFI_SUCCESS;
2800 }
2801
2802
2803 /**
2804 Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the
2805 string is defined in RFC 4291 - Text Pepresentation of Addresses.
2806
2807 @param[in] String The pointer to the Ascii string.
2808 @param[out] Ip6Address The pointer to the converted IPv6 address.
2809
2810 @retval EFI_SUCCESS Convert to IPv6 address successfully.
2811 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
2812
2813 **/
2814 EFI_STATUS
2815 EFIAPI
2816 NetLibAsciiStrToIp6 (
2817 IN CONST CHAR8 *String,
2818 OUT EFI_IPv6_ADDRESS *Ip6Address
2819 )
2820 {
2821 UINT8 Index;
2822 CHAR8 *Ip6Str;
2823 CHAR8 *TempStr;
2824 CHAR8 *TempStr2;
2825 UINT8 NodeCnt;
2826 UINT8 TailNodeCnt;
2827 UINT8 AllowedCnt;
2828 UINTN NodeVal;
2829 BOOLEAN Short;
2830 BOOLEAN Update;
2831 BOOLEAN LeadZero;
2832 UINT8 LeadZeroCnt;
2833 UINT8 Cnt;
2834
2835 if ((String == NULL) || (Ip6Address == NULL)) {
2836 return EFI_INVALID_PARAMETER;
2837 }
2838
2839 Ip6Str = (CHAR8 *) String;
2840 AllowedCnt = 6;
2841 LeadZeroCnt = 0;
2842
2843 //
2844 // An IPv6 address leading with : looks strange.
2845 //
2846 if (*Ip6Str == ':') {
2847 if (*(Ip6Str + 1) != ':') {
2848 return EFI_INVALID_PARAMETER;
2849 } else {
2850 AllowedCnt = 7;
2851 }
2852 }
2853
2854 ZeroMem (Ip6Address, sizeof (EFI_IPv6_ADDRESS));
2855
2856 NodeCnt = 0;
2857 TailNodeCnt = 0;
2858 Short = FALSE;
2859 Update = FALSE;
2860 LeadZero = FALSE;
2861
2862 for (Index = 0; Index < 15; Index = (UINT8) (Index + 2)) {
2863 TempStr = Ip6Str;
2864
2865 while ((*Ip6Str != '\0') && (*Ip6Str != ':')) {
2866 Ip6Str++;
2867 }
2868
2869 if ((*Ip6Str == '\0') && (Index != 14)) {
2870 return EFI_INVALID_PARAMETER;
2871 }
2872
2873 if (*Ip6Str == ':') {
2874 if (*(Ip6Str + 1) == ':') {
2875 if ((NodeCnt > 6) ||
2876 ((*(Ip6Str + 2) != '\0') && (AsciiStrHexToUintn (Ip6Str + 2) == 0))) {
2877 //
2878 // ::0 looks strange. report error to user.
2879 //
2880 return EFI_INVALID_PARAMETER;
2881 }
2882 if ((NodeCnt == 6) && (*(Ip6Str + 2) != '\0') &&
2883 (AsciiStrHexToUintn (Ip6Str + 2) != 0)) {
2884 return EFI_INVALID_PARAMETER;
2885 }
2886
2887 //
2888 // Skip the abbreviation part of IPv6 address.
2889 //
2890 TempStr2 = Ip6Str + 2;
2891 while ((*TempStr2 != '\0')) {
2892 if (*TempStr2 == ':') {
2893 if (*(TempStr2 + 1) == ':') {
2894 //
2895 // :: can only appear once in IPv6 address.
2896 //
2897 return EFI_INVALID_PARAMETER;
2898 }
2899
2900 TailNodeCnt++;
2901 if (TailNodeCnt >= (AllowedCnt - NodeCnt)) {
2902 //
2903 // :: indicates one or more groups of 16 bits of zeros.
2904 //
2905 return EFI_INVALID_PARAMETER;
2906 }
2907 }
2908
2909 TempStr2++;
2910 }
2911
2912 Short = TRUE;
2913 Update = TRUE;
2914
2915 Ip6Str = Ip6Str + 2;
2916 } else {
2917 if (*(Ip6Str + 1) == '\0') {
2918 return EFI_INVALID_PARAMETER;
2919 }
2920 Ip6Str++;
2921 NodeCnt++;
2922 if ((Short && (NodeCnt > 6)) || (!Short && (NodeCnt > 7))) {
2923 //
2924 // There are more than 8 groups of 16 bits of zeros.
2925 //
2926 return EFI_INVALID_PARAMETER;
2927 }
2928 }
2929 }
2930
2931 //
2932 // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first
2933 // character that is not a valid hexadecimal character, ':' or '\0' here.
2934 //
2935 NodeVal = AsciiStrHexToUintn (TempStr);
2936 if ((NodeVal > 0xFFFF) || (Index > 14)) {
2937 return EFI_INVALID_PARAMETER;
2938 }
2939 if (NodeVal != 0) {
2940 if ((*TempStr == '0') &&
2941 ((*(TempStr + 2) == ':') || (*(TempStr + 3) == ':') ||
2942 (*(TempStr + 2) == '\0') || (*(TempStr + 3) == '\0'))) {
2943 return EFI_INVALID_PARAMETER;
2944 }
2945 if ((*TempStr == '0') && (*(TempStr + 4) != '\0') &&
2946 (*(TempStr + 4) != ':')) {
2947 return EFI_INVALID_PARAMETER;
2948 }
2949 } else {
2950 if (((*TempStr == '0') && (*(TempStr + 1) == '0') &&
2951 ((*(TempStr + 2) == ':') || (*(TempStr + 2) == '\0'))) ||
2952 ((*TempStr == '0') && (*(TempStr + 1) == '0') && (*(TempStr + 2) == '0') &&
2953 ((*(TempStr + 3) == ':') || (*(TempStr + 3) == '\0')))) {
2954 return EFI_INVALID_PARAMETER;
2955 }
2956 }
2957
2958 Cnt = 0;
2959 while ((TempStr[Cnt] != ':') && (TempStr[Cnt] != '\0')) {
2960 Cnt++;
2961 }
2962 if (LeadZeroCnt == 0) {
2963 if ((Cnt == 4) && (*TempStr == '0')) {
2964 LeadZero = TRUE;
2965 LeadZeroCnt++;
2966 }
2967 if ((Cnt != 0) && (Cnt < 4)) {
2968 LeadZero = FALSE;
2969 LeadZeroCnt++;
2970 }
2971 } else {
2972 if ((Cnt == 4) && (*TempStr == '0') && !LeadZero) {
2973 return EFI_INVALID_PARAMETER;
2974 }
2975 if ((Cnt != 0) && (Cnt < 4) && LeadZero) {
2976 return EFI_INVALID_PARAMETER;
2977 }
2978 }
2979
2980 Ip6Address->Addr[Index] = (UINT8) (NodeVal >> 8);
2981 Ip6Address->Addr[Index + 1] = (UINT8) (NodeVal & 0xFF);
2982
2983 //
2984 // Skip the groups of zeros by ::
2985 //
2986 if (Short && Update) {
2987 Index = (UINT8) (16 - (TailNodeCnt + 2) * 2);
2988 Update = FALSE;
2989 }
2990 }
2991
2992 if ((!Short && Index != 16) || (*Ip6Str != '\0')) {
2993 return EFI_INVALID_PARAMETER;
2994 }
2995
2996 return EFI_SUCCESS;
2997 }
2998
2999
3000 /**
3001 Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS.
3002
3003 @param[in] String The pointer to the Ascii string.
3004 @param[out] Ip4Address The pointer to the converted IPv4 address.
3005
3006 @retval EFI_SUCCESS Convert to IPv4 address successfully.
3007 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address 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 NetLibStrToIp4 (
3014 IN CONST CHAR16 *String,
3015 OUT EFI_IPv4_ADDRESS *Ip4Address
3016 )
3017 {
3018 CHAR8 *Ip4Str;
3019 EFI_STATUS Status;
3020
3021 if ((String == NULL) || (Ip4Address == NULL)) {
3022 return EFI_INVALID_PARAMETER;
3023 }
3024
3025 Ip4Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3026 if (Ip4Str == NULL) {
3027 return EFI_OUT_OF_RESOURCES;
3028 }
3029
3030 UnicodeStrToAsciiStr (String, Ip4Str);
3031
3032 Status = NetLibAsciiStrToIp4 (Ip4Str, Ip4Address);
3033
3034 FreePool (Ip4Str);
3035
3036 return Status;
3037 }
3038
3039
3040 /**
3041 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of
3042 the string is defined in RFC 4291 - Text Pepresentation of Addresses.
3043
3044 @param[in] String The pointer to the Ascii string.
3045 @param[out] Ip6Address The pointer to the converted IPv6 address.
3046
3047 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3048 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3049 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3050
3051 **/
3052 EFI_STATUS
3053 EFIAPI
3054 NetLibStrToIp6 (
3055 IN CONST CHAR16 *String,
3056 OUT EFI_IPv6_ADDRESS *Ip6Address
3057 )
3058 {
3059 CHAR8 *Ip6Str;
3060 EFI_STATUS Status;
3061
3062 if ((String == NULL) || (Ip6Address == NULL)) {
3063 return EFI_INVALID_PARAMETER;
3064 }
3065
3066 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3067 if (Ip6Str == NULL) {
3068 return EFI_OUT_OF_RESOURCES;
3069 }
3070
3071 UnicodeStrToAsciiStr (String, Ip6Str);
3072
3073 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3074
3075 FreePool (Ip6Str);
3076
3077 return Status;
3078 }
3079
3080 /**
3081 Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length.
3082 The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses
3083 Prefixes: ipv6-address/prefix-length.
3084
3085 @param[in] String The pointer to the Ascii string.
3086 @param[out] Ip6Address The pointer to the converted IPv6 address.
3087 @param[out] PrefixLength The pointer to the converted prefix length.
3088
3089 @retval EFI_SUCCESS Convert to IPv6 address successfully.
3090 @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL.
3091 @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource.
3092
3093 **/
3094 EFI_STATUS
3095 EFIAPI
3096 NetLibStrToIp6andPrefix (
3097 IN CONST CHAR16 *String,
3098 OUT EFI_IPv6_ADDRESS *Ip6Address,
3099 OUT UINT8 *PrefixLength
3100 )
3101 {
3102 CHAR8 *Ip6Str;
3103 CHAR8 *PrefixStr;
3104 CHAR8 *TempStr;
3105 EFI_STATUS Status;
3106 UINT8 Length;
3107
3108 if ((String == NULL) || (Ip6Address == NULL) || (PrefixLength == NULL)) {
3109 return EFI_INVALID_PARAMETER;
3110 }
3111
3112 Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8));
3113 if (Ip6Str == NULL) {
3114 return EFI_OUT_OF_RESOURCES;
3115 }
3116
3117 UnicodeStrToAsciiStr (String, Ip6Str);
3118
3119 //
3120 // Get the sub string describing prefix length.
3121 //
3122 TempStr = Ip6Str;
3123 while (*TempStr != '\0' && (*TempStr != '/')) {
3124 TempStr++;
3125 }
3126
3127 if (*TempStr == '/') {
3128 PrefixStr = TempStr + 1;
3129 } else {
3130 PrefixStr = NULL;
3131 }
3132
3133 //
3134 // Get the sub string describing IPv6 address and convert it.
3135 //
3136 *TempStr = '\0';
3137
3138 Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address);
3139 if (EFI_ERROR (Status)) {
3140 goto Exit;
3141 }
3142
3143 //
3144 // If input string doesn't indicate the prefix length, return 0xff.
3145 //
3146 Length = 0xFF;
3147
3148 //
3149 // Convert the string to prefix length
3150 //
3151 if (PrefixStr != NULL) {
3152
3153 Status = EFI_INVALID_PARAMETER;
3154 Length = 0;
3155 while (*PrefixStr != '\0') {
3156 if (NET_IS_DIGIT (*PrefixStr)) {
3157 Length = (UINT8) (Length * 10 + (*PrefixStr - '0'));
3158 if (Length >= IP6_PREFIX_NUM) {
3159 goto Exit;
3160 }
3161 } else {
3162 goto Exit;
3163 }
3164
3165 PrefixStr++;
3166 }
3167 }
3168
3169 *PrefixLength = Length;
3170 Status = EFI_SUCCESS;
3171
3172 Exit:
3173
3174 FreePool (Ip6Str);
3175 return Status;
3176 }
3177
3178
3179
3180 /**
3181 This function obtains the system guid from the smbios table.
3182
3183 @param[out] SystemGuid The pointer of the returned system guid.
3184
3185 @retval EFI_SUCCESS Successfully obtained the system guid.
3186 @retval EFI_NOT_FOUND Did not find the SMBIOS table.
3187
3188 **/
3189 EFI_STATUS
3190 EFIAPI
3191 NetLibGetSystemGuid (
3192 OUT EFI_GUID *SystemGuid
3193 )
3194 {
3195 EFI_STATUS Status;
3196 SMBIOS_TABLE_ENTRY_POINT *SmbiosTable;
3197 SMBIOS_STRUCTURE_POINTER Smbios;
3198 SMBIOS_STRUCTURE_POINTER SmbiosEnd;
3199 CHAR8 *String;
3200
3201 SmbiosTable = NULL;
3202 Status = EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid, (VOID **) &SmbiosTable);
3203
3204 if (EFI_ERROR (Status) || SmbiosTable == NULL) {
3205 return EFI_NOT_FOUND;
3206 }
3207
3208 Smbios.Hdr = (SMBIOS_STRUCTURE *) (UINTN) SmbiosTable->TableAddress;
3209 SmbiosEnd.Raw = (UINT8 *) (UINTN) (SmbiosTable->TableAddress + SmbiosTable->TableLength);
3210
3211 do {
3212 if (Smbios.Hdr->Type == 1) {
3213 if (Smbios.Hdr->Length < 0x19) {
3214 //
3215 // Older version did not support UUID.
3216 //
3217 return EFI_NOT_FOUND;
3218 }
3219
3220 //
3221 // SMBIOS tables are byte packed so we need to do a byte copy to
3222 // prevend alignment faults on Itanium-based platform.
3223 //
3224 CopyMem (SystemGuid, &Smbios.Type1->Uuid, sizeof (EFI_GUID));
3225 return EFI_SUCCESS;
3226 }
3227
3228 //
3229 // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts:
3230 // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed
3231 // to skip one SMBIOS structure.
3232 //
3233
3234 //
3235 // Step 1: Skip over formatted section.
3236 //
3237 String = (CHAR8 *) (Smbios.Raw + Smbios.Hdr->Length);
3238
3239 //
3240 // Step 2: Skip over unformated string section.
3241 //
3242 do {
3243 //
3244 // Each string is terminated with a NULL(00h) BYTE and the sets of strings
3245 // is terminated with an additional NULL(00h) BYTE.
3246 //
3247 for ( ; *String != 0; String++) {
3248 }
3249
3250 if (*(UINT8*)++String == 0) {
3251 //
3252 // Pointer to the next SMBIOS structure.
3253 //
3254 Smbios.Raw = (UINT8 *)++String;
3255 break;
3256 }
3257 } while (TRUE);
3258 } while (Smbios.Raw < SmbiosEnd.Raw);
3259 return EFI_NOT_FOUND;
3260 }