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