X-Git-Url: https://git.proxmox.com/?p=mirror_edk2.git;a=blobdiff_plain;f=MdeModulePkg%2FLibrary%2FDxeNetLib%2FDxeNetLib.c;h=174c3c83f71cb513ef2beb547fadc40190d70c39;hp=f58783cdfd3f8046b77b3301fc9f6b97ee8f6339;hb=216f79703b8cb8dc65abdd768bedb2bcdbc1a1f8;hpb=779ae3579848a36319d67a6ba012b4b9aa88aa6b diff --git a/MdeModulePkg/Library/DxeNetLib/DxeNetLib.c b/MdeModulePkg/Library/DxeNetLib/DxeNetLib.c index f58783cdfd..174c3c83f7 100644 --- a/MdeModulePkg/Library/DxeNetLib/DxeNetLib.c +++ b/MdeModulePkg/Library/DxeNetLib/DxeNetLib.c @@ -1,8 +1,8 @@ /** @file Network library. -Copyright (c) 2005 - 2009, Intel Corporation.
-All rights reserved. This program and the accompanying materials +Copyright (c) 2005 - 2012, Intel Corporation. All rights reserved.
+This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php @@ -13,6 +13,8 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. #include +#include + #include #include #include @@ -20,8 +22,10 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. #include #include #include +#include #include +#include #include #include @@ -33,8 +37,10 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. #include #include #include +#include #define NIC_ITEM_CONFIG_SIZE sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE +#define DEFAULT_ZERO_START ((UINTN) ~0) // // All the supported IP4 maskes in host byte order. @@ -375,6 +381,7 @@ SyslogBuildPacket ( // Pri = ((NET_SYSLOG_FACILITY & 31) << 3) | (Level & 7); gRT->GetTime (&Time, NULL); + ASSERT ((Time.Month <= 12) && (Time.Month >= 1)); // // Use %a to format the ASCII strings, %s to format UNICODE strings @@ -442,6 +449,7 @@ SyslogBuildPacket ( **/ CHAR8 * +EFIAPI NetDebugASPrint ( IN CHAR8 *Format, ... @@ -481,6 +489,7 @@ NetDebugASPrint ( than the mNetDebugLevelMax. Or, it has been sent out. **/ EFI_STATUS +EFIAPI NetDebugOutput ( IN UINT32 Level, IN UINT8 *Module, @@ -675,6 +684,7 @@ NetIp4IsUnicast ( **/ BOOLEAN +EFIAPI NetIp6IsValidUnicast ( IN EFI_IPv6_ADDRESS *Ip6 ) @@ -711,6 +721,7 @@ NetIp6IsValidUnicast ( **/ BOOLEAN +EFIAPI NetIp6IsUnspecifiedAddr ( IN EFI_IPv6_ADDRESS *Ip6 ) @@ -736,6 +747,7 @@ NetIp6IsUnspecifiedAddr ( **/ BOOLEAN +EFIAPI NetIp6IsLinkLocalAddr ( IN EFI_IPv6_ADDRESS *Ip6 ) @@ -773,6 +785,7 @@ NetIp6IsLinkLocalAddr ( **/ BOOLEAN +EFIAPI NetIp6IsNetEqual ( EFI_IPv6_ADDRESS *Ip1, EFI_IPv6_ADDRESS *Ip2, @@ -783,7 +796,7 @@ NetIp6IsNetEqual ( UINT8 Bit; UINT8 Mask; - ASSERT (Ip1 != NULL && Ip2 != NULL); + ASSERT ((Ip1 != NULL) && (Ip2 != NULL) && (PrefixLength < IP6_PREFIX_NUM)); if (PrefixLength == 0) { return TRUE; @@ -799,6 +812,7 @@ NetIp6IsNetEqual ( if (Bit > 0) { Mask = (UINT8) (0xFF << (8 - Bit)); + ASSERT (Byte < 16); if ((Ip1->Addr[Byte] & Mask) != (Ip2->Addr[Byte] & Mask)) { return FALSE; } @@ -821,6 +835,7 @@ NetIp6IsNetEqual ( **/ EFI_IPv6_ADDRESS * +EFIAPI Ip6Swap128 ( EFI_IPv6_ADDRESS *Ip6 ) @@ -899,7 +914,7 @@ NetGetUint32 ( byte stream. @param[in, out] Buf The buffer to put the UINT32. - @param[in] Data The data to put. + @param[in] Data The data to be converted and put into the byte stream. **/ VOID @@ -1051,6 +1066,115 @@ NetListInsertBefore ( PostEntry->BackLink = NewEntry; } +/** + Safe destroy nodes in a linked list, and return the length of the list after all possible operations finished. + + Destroy network child instance list by list traversals is not safe due to graph dependencies between nodes. + This function performs a safe traversal to destroy these nodes by checking to see if the node being destroyed + has been removed from the list or not. + If it has been removed, then restart the traversal from the head. + If it hasn't been removed, then continue with the next node directly. + This function will end the iterate and return the CallBack's last return value if error happens, + or retrun EFI_SUCCESS if 2 complete passes are made with no changes in the number of children in the list. + + @param[in] List The head of the list. + @param[in] CallBack Pointer to the callback function to destroy one node in the list. + @param[in] Context Pointer to the callback function's context: corresponds to the + parameter Context in NET_DESTROY_LINK_LIST_CALLBACK. + @param[out] ListLength The length of the link list if the function returns successfully. + + @retval EFI_SUCCESS Two complete passes are made with no changes in the number of children. + @retval EFI_INVALID_PARAMETER The input parameter is invalid. + @retval Others Return the CallBack's last return value. + +**/ +EFI_STATUS +EFIAPI +NetDestroyLinkList ( + IN LIST_ENTRY *List, + IN NET_DESTROY_LINK_LIST_CALLBACK CallBack, + IN VOID *Context, OPTIONAL + OUT UINTN *ListLength OPTIONAL +) +{ + UINTN PreviousLength; + LIST_ENTRY *Entry; + LIST_ENTRY *Ptr; + UINTN Length; + EFI_STATUS Status; + + if (List == NULL || CallBack == NULL) { + return EFI_INVALID_PARAMETER; + } + + Length = 0; + do { + PreviousLength = Length; + Entry = GetFirstNode (List); + while (!IsNull (List, Entry)) { + Status = CallBack (Entry, Context); + if (EFI_ERROR (Status)) { + return Status; + } + // + // Walk through the list to see whether the Entry has been removed or not. + // If the Entry still exists, just try to destroy the next one. + // If not, go back to the start point to iterate the list again. + // + for (Ptr = List->ForwardLink; Ptr != List; Ptr = Ptr->ForwardLink) { + if (Ptr == Entry) { + break; + } + } + if (Ptr == Entry) { + Entry = GetNextNode (List, Entry); + } else { + Entry = GetFirstNode (List); + } + } + for (Length = 0, Ptr = List->ForwardLink; Ptr != List; Length++, Ptr = Ptr->ForwardLink); + } while (Length != PreviousLength); + + if (ListLength != NULL) { + *ListLength = Length; + } + return EFI_SUCCESS; +} + +/** + This function checks the input Handle to see if it's one of these handles in ChildHandleBuffer. + + @param[in] Handle Handle to be checked. + @param[in] NumberOfChildren Number of Handles in ChildHandleBuffer. + @param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL + if NumberOfChildren is 0. + + @retval TURE Found the input Handle in ChildHandleBuffer. + @retval FALSE Can't find the input Handle in ChildHandleBuffer. + +**/ +BOOLEAN +NetIsInHandleBuffer ( + IN EFI_HANDLE Handle, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer OPTIONAL +) +{ + UINTN Index; + + if (NumberOfChildren == 0 || ChildHandleBuffer == NULL) { + return FALSE; + } + + for (Index = 0; Index < NumberOfChildren; Index++) { + if (Handle == ChildHandleBuffer[Index]) { + return TRUE; + } + } + + return FALSE; +} + /** Initialize the netmap. Netmap is a reposity to keep the pairs. @@ -1530,7 +1654,7 @@ EFIAPI NetMapIterate ( IN NET_MAP *Map, IN NET_MAP_CALLBACK CallBack, - IN VOID *Arg + IN VOID *Arg OPTIONAL ) { @@ -1561,6 +1685,86 @@ NetMapIterate ( } +/** + Internal function to get the child handle of the NIC handle. + + @param[in] Controller NIC controller handle. + @param[out] ChildHandle Returned child handle. + + @retval EFI_SUCCESS Successfully to get child handle. + @retval Others Failed to get child handle. + +**/ +EFI_STATUS +NetGetChildHandle ( + IN EFI_HANDLE Controller, + OUT EFI_HANDLE *ChildHandle + ) +{ + EFI_STATUS Status; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *ChildDeviceDevicePath; + VENDOR_DEVICE_PATH *VendorDeviceNode; + + // + // Locate all EFI Hii Config Access protocols + // + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiHiiConfigAccessProtocolGuid, + NULL, + &HandleCount, + &Handles + ); + if (EFI_ERROR (Status) || (HandleCount == 0)) { + return Status; + } + + Status = EFI_NOT_FOUND; + + for (Index = 0; Index < HandleCount; Index++) { + + Status = EfiTestChildHandle (Controller, Handles[Index], &gEfiManagedNetworkServiceBindingProtocolGuid); + if (!EFI_ERROR (Status)) { + // + // Get device path on the child handle + // + Status = gBS->HandleProtocol ( + Handles[Index], + &gEfiDevicePathProtocolGuid, + (VOID **) &ChildDeviceDevicePath + ); + + if (!EFI_ERROR (Status)) { + while (!IsDevicePathEnd (ChildDeviceDevicePath)) { + ChildDeviceDevicePath = NextDevicePathNode (ChildDeviceDevicePath); + // + // Parse one instance + // + if (ChildDeviceDevicePath->Type == HARDWARE_DEVICE_PATH && + ChildDeviceDevicePath->SubType == HW_VENDOR_DP) { + VendorDeviceNode = (VENDOR_DEVICE_PATH *) ChildDeviceDevicePath; + if (CompareMem (&VendorDeviceNode->Guid, &gEfiNicIp4ConfigVariableGuid, sizeof (EFI_GUID)) == 0) { + // + // Found item matched gEfiNicIp4ConfigVariableGuid + // + *ChildHandle = Handles[Index]; + FreePool (Handles); + return EFI_SUCCESS; + } + } + } + } + } + } + + FreePool (Handles); + return Status; +} + + /** This is the default unload handle for all the network drivers. @@ -1735,7 +1939,7 @@ NetLibCreateServiceChild ( /** - Destory a child of the service that is identified by ServiceBindingGuid. + Destroy a child of the service that is identified by ServiceBindingGuid. Get the ServiceBinding Protocol first, then use it to destroy a child. @@ -1744,10 +1948,10 @@ NetLibCreateServiceChild ( @param[in] Controller The controller which has the service installed. @param[in] Image The image handle used to open service. @param[in] ServiceBindingGuid The service's Guid. - @param[in] ChildHandle The child to destory. + @param[in] ChildHandle The child to destroy. - @retval EFI_SUCCESS The child is successfully destoried. - @retval Others Failed to destory the child. + @retval EFI_SUCCESS The child is successfully destroyed. + @retval Others Failed to destroy the child. **/ EFI_STATUS @@ -1781,7 +1985,7 @@ NetLibDestroyServiceChild ( } // - // destory the child + // destroy the child // Status = Service->DestroyChild (Service, ChildHandle); return Status; @@ -1900,9 +2104,9 @@ NetLibGetVlanId ( This function will append VLAN device path node to the parent device path, and then use LocateDevicePath() to find the correct VLAN device handle. - @param[in] ServiceHandle The handle where network service binding protocols are + @param[in] ControllerHandle The handle where network service binding protocols are installed on. - @param[in] VLanId The configured VLAN ID for the VLAN device. + @param[in] VlanId The configured VLAN ID for the VLAN device. @return The VLAN device handle, or NULL if not found. @@ -2036,6 +2240,7 @@ NetLibGetMacAddress ( (VOID **) &Mnp ); if (EFI_ERROR (Status)) { + MnpSb->DestroyChild (MnpSb, MnpChildHandle); return Status; } @@ -2044,6 +2249,7 @@ NetLibGetMacAddress ( // Status = Mnp->GetModeData (Mnp, NULL, &SnpModeData); if (EFI_ERROR (Status)) { + MnpSb->DestroyChild (MnpSb, MnpChildHandle); return Status; } SnpMode = &SnpModeData; @@ -2072,7 +2278,8 @@ NetLibGetMacAddress ( @param[in] ServiceHandle The handle where network service binding protocol is installed on. @param[in] ImageHandle The image handle used to act as the agent handle to - get the simple network protocol. + get the simple network protocol. This parameter is + optional and may be NULL. @param[out] MacString The pointer to store the address of the string representation of the mac address. @@ -2085,7 +2292,7 @@ EFI_STATUS EFIAPI NetLibGetMacString ( IN EFI_HANDLE ServiceHandle, - IN EFI_HANDLE ImageHandle, + IN EFI_HANDLE ImageHandle, OPTIONAL OUT CHAR16 **MacString ) { @@ -2143,6 +2350,214 @@ NetLibGetMacString ( return EFI_SUCCESS; } +/** + Detect media status for specified network device. + + The underlying UNDI driver may or may not support reporting media status from + GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine + will try to invoke Snp->GetStatus() to get the media status: if media already + present, it return directly; if media not present, it will stop SNP and then + restart SNP to get the latest media status, this give chance to get the correct + media status for old UNDI driver which doesn't support reporting media status + from GET_STATUS command. + Note: there will be two limitations for current algorithm: + 1) for UNDI with this capability, in case of cable is not attached, there will + be an redundant Stop/Start() process; + 2) for UNDI without this capability, in case that network cable is attached when + Snp->Initialize() is invoked while network cable is unattached later, + NetLibDetectMedia() will report MediaPresent as TRUE, causing upper layer + apps to wait for timeout time. + + @param[in] ServiceHandle The handle where network service binding protocols are + installed on. + @param[out] MediaPresent The pointer to store the media status. + + @retval EFI_SUCCESS Media detection success. + @retval EFI_INVALID_PARAMETER ServiceHandle is not valid network device handle. + @retval EFI_UNSUPPORTED Network device does not support media detection. + @retval EFI_DEVICE_ERROR SNP is in unknown state. + +**/ +EFI_STATUS +EFIAPI +NetLibDetectMedia ( + IN EFI_HANDLE ServiceHandle, + OUT BOOLEAN *MediaPresent + ) +{ + EFI_STATUS Status; + EFI_HANDLE SnpHandle; + EFI_SIMPLE_NETWORK_PROTOCOL *Snp; + UINT32 InterruptStatus; + UINT32 OldState; + EFI_MAC_ADDRESS *MCastFilter; + UINT32 MCastFilterCount; + UINT32 EnableFilterBits; + UINT32 DisableFilterBits; + BOOLEAN ResetMCastFilters; + + ASSERT (MediaPresent != NULL); + + // + // Get SNP handle + // + Snp = NULL; + SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp); + if (SnpHandle == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Check whether SNP support media detection + // + if (!Snp->Mode->MediaPresentSupported) { + return EFI_UNSUPPORTED; + } + + // + // Invoke Snp->GetStatus() to refresh MediaPresent field in SNP mode data + // + Status = Snp->GetStatus (Snp, &InterruptStatus, NULL); + if (EFI_ERROR (Status)) { + return Status; + } + + if (Snp->Mode->MediaPresent) { + // + // Media is present, return directly + // + *MediaPresent = TRUE; + return EFI_SUCCESS; + } + + // + // Till now, GetStatus() report no media; while, in case UNDI not support + // reporting media status from GetStatus(), this media status may be incorrect. + // So, we will stop SNP and then restart it to get the correct media status. + // + OldState = Snp->Mode->State; + if (OldState >= EfiSimpleNetworkMaxState) { + return EFI_DEVICE_ERROR; + } + + MCastFilter = NULL; + + if (OldState == EfiSimpleNetworkInitialized) { + // + // SNP is already in use, need Shutdown/Stop and then Start/Initialize + // + + // + // Backup current SNP receive filter settings + // + EnableFilterBits = Snp->Mode->ReceiveFilterSetting; + DisableFilterBits = Snp->Mode->ReceiveFilterMask ^ EnableFilterBits; + + ResetMCastFilters = TRUE; + MCastFilterCount = Snp->Mode->MCastFilterCount; + if (MCastFilterCount != 0) { + MCastFilter = AllocateCopyPool ( + MCastFilterCount * sizeof (EFI_MAC_ADDRESS), + Snp->Mode->MCastFilter + ); + ASSERT (MCastFilter != NULL); + + ResetMCastFilters = FALSE; + } + + // + // Shutdown/Stop the simple network + // + Status = Snp->Shutdown (Snp); + if (!EFI_ERROR (Status)) { + Status = Snp->Stop (Snp); + } + if (EFI_ERROR (Status)) { + goto Exit; + } + + // + // Start/Initialize the simple network + // + Status = Snp->Start (Snp); + if (!EFI_ERROR (Status)) { + Status = Snp->Initialize (Snp, 0, 0); + } + if (EFI_ERROR (Status)) { + goto Exit; + } + + // + // Here we get the correct media status + // + *MediaPresent = Snp->Mode->MediaPresent; + + // + // Restore SNP receive filter settings + // + Status = Snp->ReceiveFilters ( + Snp, + EnableFilterBits, + DisableFilterBits, + ResetMCastFilters, + MCastFilterCount, + MCastFilter + ); + + if (MCastFilter != NULL) { + FreePool (MCastFilter); + } + + return Status; + } + + // + // SNP is not in use, it's in state of EfiSimpleNetworkStopped or EfiSimpleNetworkStarted + // + if (OldState == EfiSimpleNetworkStopped) { + // + // SNP not start yet, start it + // + Status = Snp->Start (Snp); + if (EFI_ERROR (Status)) { + goto Exit; + } + } + + // + // Initialize the simple network + // + Status = Snp->Initialize (Snp, 0, 0); + if (EFI_ERROR (Status)) { + Status = EFI_DEVICE_ERROR; + goto Exit; + } + + // + // Here we get the correct media status + // + *MediaPresent = Snp->Mode->MediaPresent; + + // + // Shut down the simple network + // + Snp->Shutdown (Snp); + +Exit: + if (OldState == EfiSimpleNetworkStopped) { + // + // Original SNP sate is Stopped, restore to original state + // + Snp->Stop (Snp); + } + + if (MCastFilter != NULL) { + FreePool (MCastFilter); + } + + return Status; +} + /** Check the default address used by the IPv4 driver is static or dynamic (acquired from DHCP). @@ -2174,6 +2589,7 @@ NetLibDefaultAddressIsStatic ( EFI_STRING AccessProgress; EFI_STRING AccessResults; EFI_STRING String; + EFI_HANDLE ChildHandle; ConfigInfo = NULL; ConfigHdr = NULL; @@ -2183,10 +2599,15 @@ NetLibDefaultAddressIsStatic ( IsStatic = TRUE; Status = gBS->LocateProtocol ( - &gEfiHiiConfigRoutingProtocolGuid, - NULL, - (VOID **) &HiiConfigRouting - ); + &gEfiHiiConfigRoutingProtocolGuid, + NULL, + (VOID **) &HiiConfigRouting + ); + if (EFI_ERROR (Status)) { + return TRUE; + } + + Status = NetGetChildHandle (Controller, &ChildHandle); if (EFI_ERROR (Status)) { return TRUE; } @@ -2194,7 +2615,7 @@ NetLibDefaultAddressIsStatic ( // // Construct config request string header // - ConfigHdr = HiiConstructConfigHdr (&gEfiNicIp4ConfigVariableGuid, EFI_NIC_IP4_CONFIG_VARIABLE, Controller); + ConfigHdr = HiiConstructConfigHdr (&gEfiNicIp4ConfigVariableGuid, EFI_NIC_IP4_CONFIG_VARIABLE, ChildHandle); if (ConfigHdr == NULL) { return TRUE; } @@ -2225,7 +2646,7 @@ NetLibDefaultAddressIsStatic ( goto ON_EXIT; } - ConfigInfo = AllocateZeroPool (sizeof (NIC_ITEM_CONFIG_SIZE)); + ConfigInfo = AllocateZeroPool (NIC_ITEM_CONFIG_SIZE); if (ConfigInfo == NULL) { goto ON_EXIT; } @@ -2268,7 +2689,6 @@ ON_EXIT: The header type of IPv4 device path node is MESSAGING_DEVICE_PATH. The header subtype of IPv4 device path node is MSG_IPv4_DP. - The length of the IPv4 device path node in bytes is 19. Get other info from parameters to make up the whole IPv4 device path node. @param[in, out] Node Pointer to the IPv4 device path node. @@ -2296,7 +2716,7 @@ NetLibCreateIPv4DPathNode ( { Node->Header.Type = MESSAGING_DEVICE_PATH; Node->Header.SubType = MSG_IPv4_DP; - SetDevicePathNodeLength (&Node->Header, 19); + SetDevicePathNodeLength (&Node->Header, sizeof (IPv4_DEVICE_PATH)); CopyMem (&Node->LocalIpAddress, &LocalIp, sizeof (EFI_IPv4_ADDRESS)); CopyMem (&Node->RemoteIpAddress, &RemoteIp, sizeof (EFI_IPv4_ADDRESS)); @@ -2311,6 +2731,14 @@ NetLibCreateIPv4DPathNode ( } else { Node->StaticIpAddress = NetLibDefaultAddressIsStatic (Controller); } + + // + // Set the Gateway IP address to default value 0:0:0:0. + // Set the Subnet mask to default value 255:255:255:0. + // + ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv4_ADDRESS)); + SetMem (&Node->SubnetMask, sizeof (EFI_IPv4_ADDRESS), 0xff); + Node->SubnetMask.Addr[3] = 0; } /** @@ -2352,7 +2780,14 @@ NetLibCreateIPv6DPathNode ( Node->RemotePort = RemotePort; Node->Protocol = Protocol; - Node->StaticIpAddress = FALSE; + + // + // Set default value to IPAddressOrigin, PrefixLength. + // Set the Gateway IP address to unspecified address. + // + Node->IpAddressOrigin = 0; + Node->PrefixLength = IP6_PREFIX_LENGTH; + ZeroMem (&Node->GatewayIpAddress, sizeof (EFI_IPv6_ADDRESS)); } /** @@ -2399,7 +2834,7 @@ NetLibGetNicHandle ( Handle = NULL; for (Index = 0; Index < OpenCount; Index++) { - if (OpenBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) { + if ((OpenBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { Handle = OpenBuffer[Index].ControllerHandle; break; } @@ -2408,3 +2843,631 @@ NetLibGetNicHandle ( gBS->FreePool (OpenBuffer); return Handle; } + +/** + Convert one Null-terminated ASCII string (decimal dotted) to EFI_IPv4_ADDRESS. + + @param[in] String The pointer to the Ascii string. + @param[out] Ip4Address The pointer to the converted IPv4 address. + + @retval EFI_SUCCESS Convert to IPv4 address successfully. + @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL. + +**/ +EFI_STATUS +EFIAPI +NetLibAsciiStrToIp4 ( + IN CONST CHAR8 *String, + OUT EFI_IPv4_ADDRESS *Ip4Address + ) +{ + UINT8 Index; + CHAR8 *Ip4Str; + CHAR8 *TempStr; + UINTN NodeVal; + + if ((String == NULL) || (Ip4Address == NULL)) { + return EFI_INVALID_PARAMETER; + } + + Ip4Str = (CHAR8 *) String; + + for (Index = 0; Index < 4; Index++) { + TempStr = Ip4Str; + + while ((*Ip4Str != '\0') && (*Ip4Str != '.')) { + Ip4Str++; + } + + // + // The IPv4 address is X.X.X.X + // + if (*Ip4Str == '.') { + if (Index == 3) { + return EFI_INVALID_PARAMETER; + } + } else { + if (Index != 3) { + return EFI_INVALID_PARAMETER; + } + } + + // + // Convert the string to IPv4 address. AsciiStrDecimalToUintn stops at the + // first character that is not a valid decimal character, '.' or '\0' here. + // + NodeVal = AsciiStrDecimalToUintn (TempStr); + if (NodeVal > 0xFF) { + return EFI_INVALID_PARAMETER; + } + + Ip4Address->Addr[Index] = (UINT8) NodeVal; + + Ip4Str++; + } + + return EFI_SUCCESS; +} + + +/** + Convert one Null-terminated ASCII string to EFI_IPv6_ADDRESS. The format of the + string is defined in RFC 4291 - Text Pepresentation of Addresses. + + @param[in] String The pointer to the Ascii string. + @param[out] Ip6Address The pointer to the converted IPv6 address. + + @retval EFI_SUCCESS Convert to IPv6 address successfully. + @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL. + +**/ +EFI_STATUS +EFIAPI +NetLibAsciiStrToIp6 ( + IN CONST CHAR8 *String, + OUT EFI_IPv6_ADDRESS *Ip6Address + ) +{ + UINT8 Index; + CHAR8 *Ip6Str; + CHAR8 *TempStr; + CHAR8 *TempStr2; + UINT8 NodeCnt; + UINT8 TailNodeCnt; + UINT8 AllowedCnt; + UINTN NodeVal; + BOOLEAN Short; + BOOLEAN Update; + BOOLEAN LeadZero; + UINT8 LeadZeroCnt; + UINT8 Cnt; + + if ((String == NULL) || (Ip6Address == NULL)) { + return EFI_INVALID_PARAMETER; + } + + Ip6Str = (CHAR8 *) String; + AllowedCnt = 6; + LeadZeroCnt = 0; + + // + // An IPv6 address leading with : looks strange. + // + if (*Ip6Str == ':') { + if (*(Ip6Str + 1) != ':') { + return EFI_INVALID_PARAMETER; + } else { + AllowedCnt = 7; + } + } + + ZeroMem (Ip6Address, sizeof (EFI_IPv6_ADDRESS)); + + NodeCnt = 0; + TailNodeCnt = 0; + Short = FALSE; + Update = FALSE; + LeadZero = FALSE; + + for (Index = 0; Index < 15; Index = (UINT8) (Index + 2)) { + TempStr = Ip6Str; + + while ((*Ip6Str != '\0') && (*Ip6Str != ':')) { + Ip6Str++; + } + + if ((*Ip6Str == '\0') && (Index != 14)) { + return EFI_INVALID_PARAMETER; + } + + if (*Ip6Str == ':') { + if (*(Ip6Str + 1) == ':') { + if ((NodeCnt > 6) || + ((*(Ip6Str + 2) != '\0') && (AsciiStrHexToUintn (Ip6Str + 2) == 0))) { + // + // ::0 looks strange. report error to user. + // + return EFI_INVALID_PARAMETER; + } + if ((NodeCnt == 6) && (*(Ip6Str + 2) != '\0') && + (AsciiStrHexToUintn (Ip6Str + 2) != 0)) { + return EFI_INVALID_PARAMETER; + } + + // + // Skip the abbreviation part of IPv6 address. + // + TempStr2 = Ip6Str + 2; + while ((*TempStr2 != '\0')) { + if (*TempStr2 == ':') { + if (*(TempStr2 + 1) == ':') { + // + // :: can only appear once in IPv6 address. + // + return EFI_INVALID_PARAMETER; + } + + TailNodeCnt++; + if (TailNodeCnt >= (AllowedCnt - NodeCnt)) { + // + // :: indicates one or more groups of 16 bits of zeros. + // + return EFI_INVALID_PARAMETER; + } + } + + TempStr2++; + } + + Short = TRUE; + Update = TRUE; + + Ip6Str = Ip6Str + 2; + } else { + if (*(Ip6Str + 1) == '\0') { + return EFI_INVALID_PARAMETER; + } + Ip6Str++; + NodeCnt++; + if ((Short && (NodeCnt > 6)) || (!Short && (NodeCnt > 7))) { + // + // There are more than 8 groups of 16 bits of zeros. + // + return EFI_INVALID_PARAMETER; + } + } + } + + // + // Convert the string to IPv6 address. AsciiStrHexToUintn stops at the first + // character that is not a valid hexadecimal character, ':' or '\0' here. + // + NodeVal = AsciiStrHexToUintn (TempStr); + if ((NodeVal > 0xFFFF) || (Index > 14)) { + return EFI_INVALID_PARAMETER; + } + if (NodeVal != 0) { + if ((*TempStr == '0') && + ((*(TempStr + 2) == ':') || (*(TempStr + 3) == ':') || + (*(TempStr + 2) == '\0') || (*(TempStr + 3) == '\0'))) { + return EFI_INVALID_PARAMETER; + } + if ((*TempStr == '0') && (*(TempStr + 4) != '\0') && + (*(TempStr + 4) != ':')) { + return EFI_INVALID_PARAMETER; + } + } else { + if (((*TempStr == '0') && (*(TempStr + 1) == '0') && + ((*(TempStr + 2) == ':') || (*(TempStr + 2) == '\0'))) || + ((*TempStr == '0') && (*(TempStr + 1) == '0') && (*(TempStr + 2) == '0') && + ((*(TempStr + 3) == ':') || (*(TempStr + 3) == '\0')))) { + return EFI_INVALID_PARAMETER; + } + } + + Cnt = 0; + while ((TempStr[Cnt] != ':') && (TempStr[Cnt] != '\0')) { + Cnt++; + } + if (LeadZeroCnt == 0) { + if ((Cnt == 4) && (*TempStr == '0')) { + LeadZero = TRUE; + LeadZeroCnt++; + } + if ((Cnt != 0) && (Cnt < 4)) { + LeadZero = FALSE; + LeadZeroCnt++; + } + } else { + if ((Cnt == 4) && (*TempStr == '0') && !LeadZero) { + return EFI_INVALID_PARAMETER; + } + if ((Cnt != 0) && (Cnt < 4) && LeadZero) { + return EFI_INVALID_PARAMETER; + } + } + + Ip6Address->Addr[Index] = (UINT8) (NodeVal >> 8); + Ip6Address->Addr[Index + 1] = (UINT8) (NodeVal & 0xFF); + + // + // Skip the groups of zeros by :: + // + if (Short && Update) { + Index = (UINT8) (16 - (TailNodeCnt + 2) * 2); + Update = FALSE; + } + } + + if ((!Short && Index != 16) || (*Ip6Str != '\0')) { + return EFI_INVALID_PARAMETER; + } + + return EFI_SUCCESS; +} + + +/** + Convert one Null-terminated Unicode string (decimal dotted) to EFI_IPv4_ADDRESS. + + @param[in] String The pointer to the Ascii string. + @param[out] Ip4Address The pointer to the converted IPv4 address. + + @retval EFI_SUCCESS Convert to IPv4 address successfully. + @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip4Address is NULL. + @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource. + +**/ +EFI_STATUS +EFIAPI +NetLibStrToIp4 ( + IN CONST CHAR16 *String, + OUT EFI_IPv4_ADDRESS *Ip4Address + ) +{ + CHAR8 *Ip4Str; + EFI_STATUS Status; + + if ((String == NULL) || (Ip4Address == NULL)) { + return EFI_INVALID_PARAMETER; + } + + Ip4Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8)); + if (Ip4Str == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + UnicodeStrToAsciiStr (String, Ip4Str); + + Status = NetLibAsciiStrToIp4 (Ip4Str, Ip4Address); + + FreePool (Ip4Str); + + return Status; +} + + +/** + Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS. The format of + the string is defined in RFC 4291 - Text Pepresentation of Addresses. + + @param[in] String The pointer to the Ascii string. + @param[out] Ip6Address The pointer to the converted IPv6 address. + + @retval EFI_SUCCESS Convert to IPv6 address successfully. + @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL. + @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource. + +**/ +EFI_STATUS +EFIAPI +NetLibStrToIp6 ( + IN CONST CHAR16 *String, + OUT EFI_IPv6_ADDRESS *Ip6Address + ) +{ + CHAR8 *Ip6Str; + EFI_STATUS Status; + + if ((String == NULL) || (Ip6Address == NULL)) { + return EFI_INVALID_PARAMETER; + } + + Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8)); + if (Ip6Str == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + UnicodeStrToAsciiStr (String, Ip6Str); + + Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address); + + FreePool (Ip6Str); + + return Status; +} + +/** + Convert one Null-terminated Unicode string to EFI_IPv6_ADDRESS and prefix length. + The format of the string is defined in RFC 4291 - Text Pepresentation of Addresses + Prefixes: ipv6-address/prefix-length. + + @param[in] String The pointer to the Ascii string. + @param[out] Ip6Address The pointer to the converted IPv6 address. + @param[out] PrefixLength The pointer to the converted prefix length. + + @retval EFI_SUCCESS Convert to IPv6 address successfully. + @retval EFI_INVALID_PARAMETER The string is mal-formated or Ip6Address is NULL. + @retval EFI_OUT_OF_RESOURCES Fail to perform the operation due to lack of resource. + +**/ +EFI_STATUS +EFIAPI +NetLibStrToIp6andPrefix ( + IN CONST CHAR16 *String, + OUT EFI_IPv6_ADDRESS *Ip6Address, + OUT UINT8 *PrefixLength + ) +{ + CHAR8 *Ip6Str; + CHAR8 *PrefixStr; + CHAR8 *TempStr; + EFI_STATUS Status; + UINT8 Length; + + if ((String == NULL) || (Ip6Address == NULL) || (PrefixLength == NULL)) { + return EFI_INVALID_PARAMETER; + } + + Ip6Str = (CHAR8 *) AllocatePool ((StrLen (String) + 1) * sizeof (CHAR8)); + if (Ip6Str == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + UnicodeStrToAsciiStr (String, Ip6Str); + + // + // Get the sub string describing prefix length. + // + TempStr = Ip6Str; + while (*TempStr != '\0' && (*TempStr != '/')) { + TempStr++; + } + + if (*TempStr == '/') { + PrefixStr = TempStr + 1; + } else { + PrefixStr = NULL; + } + + // + // Get the sub string describing IPv6 address and convert it. + // + *TempStr = '\0'; + + Status = NetLibAsciiStrToIp6 (Ip6Str, Ip6Address); + if (EFI_ERROR (Status)) { + goto Exit; + } + + // + // If input string doesn't indicate the prefix length, return 0xff. + // + Length = 0xFF; + + // + // Convert the string to prefix length + // + if (PrefixStr != NULL) { + + Status = EFI_INVALID_PARAMETER; + Length = 0; + while (*PrefixStr != '\0') { + if (NET_IS_DIGIT (*PrefixStr)) { + Length = (UINT8) (Length * 10 + (*PrefixStr - '0')); + if (Length >= IP6_PREFIX_NUM) { + goto Exit; + } + } else { + goto Exit; + } + + PrefixStr++; + } + } + + *PrefixLength = Length; + Status = EFI_SUCCESS; + +Exit: + + FreePool (Ip6Str); + return Status; +} + +/** + + Convert one EFI_IPv6_ADDRESS to Null-terminated Unicode string. + The text representation of address is defined in RFC 4291. + + @param[in] Ip6Address The pointer to the IPv6 address. + @param[out] String The buffer to return the converted string. + @param[in] StringSize The length in bytes of the input String. + + @retval EFI_SUCCESS Convert to string successfully. + @retval EFI_INVALID_PARAMETER The input parameter is invalid. + @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small for the result. BufferSize has been + updated with the size needed to complete the request. +**/ +EFI_STATUS +EFIAPI +NetLibIp6ToStr ( + IN EFI_IPv6_ADDRESS *Ip6Address, + OUT CHAR16 *String, + IN UINTN StringSize + ) +{ + UINT16 Ip6Addr[8]; + UINTN Index; + UINTN LongestZerosStart; + UINTN LongestZerosLength; + UINTN CurrentZerosStart; + UINTN CurrentZerosLength; + CHAR16 Buffer[sizeof"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"]; + CHAR16 *Ptr; + + if (Ip6Address == NULL || String == NULL || StringSize == 0) { + return EFI_INVALID_PARAMETER; + } + + // + // Convert the UINT8 array to an UINT16 array for easy handling. + // + ZeroMem (Ip6Addr, sizeof (Ip6Addr)); + for (Index = 0; Index < 16; Index++) { + Ip6Addr[Index / 2] |= (Ip6Address->Addr[Index] << ((1 - (Index % 2)) << 3)); + } + + // + // Find the longest zeros and mark it. + // + CurrentZerosStart = DEFAULT_ZERO_START; + CurrentZerosLength = 0; + LongestZerosStart = DEFAULT_ZERO_START; + LongestZerosLength = 0; + for (Index = 0; Index < 8; Index++) { + if (Ip6Addr[Index] == 0) { + if (CurrentZerosStart == DEFAULT_ZERO_START) { + CurrentZerosStart = Index; + CurrentZerosLength = 1; + } else { + CurrentZerosLength++; + } + } else { + if (CurrentZerosStart != DEFAULT_ZERO_START) { + if (CurrentZerosLength > 2 && (LongestZerosStart == (DEFAULT_ZERO_START) || CurrentZerosLength > LongestZerosLength)) { + LongestZerosStart = CurrentZerosStart; + LongestZerosLength = CurrentZerosLength; + } + CurrentZerosStart = DEFAULT_ZERO_START; + CurrentZerosLength = 0; + } + } + } + + if (CurrentZerosStart != DEFAULT_ZERO_START && CurrentZerosLength > 2) { + if (LongestZerosStart == DEFAULT_ZERO_START || LongestZerosLength < CurrentZerosLength) { + LongestZerosStart = CurrentZerosStart; + LongestZerosLength = CurrentZerosLength; + } + } + + Ptr = Buffer; + for (Index = 0; Index < 8; Index++) { + if (LongestZerosStart != DEFAULT_ZERO_START && Index >= LongestZerosStart && Index < LongestZerosStart + LongestZerosLength) { + if (Index == LongestZerosStart) { + *Ptr++ = L':'; + } + continue; + } + if (Index != 0) { + *Ptr++ = L':'; + } + Ptr += UnicodeSPrint(Ptr, 10, L"%x", Ip6Addr[Index]); + } + + if (LongestZerosStart != DEFAULT_ZERO_START && LongestZerosStart + LongestZerosLength == 8) { + *Ptr++ = L':'; + } + *Ptr = L'\0'; + + if ((UINTN)Ptr - (UINTN)Buffer > StringSize) { + return EFI_BUFFER_TOO_SMALL; + } + + StrCpy (String, Buffer); + + return EFI_SUCCESS; +} + +/** + This function obtains the system guid from the smbios table. + + @param[out] SystemGuid The pointer of the returned system guid. + + @retval EFI_SUCCESS Successfully obtained the system guid. + @retval EFI_NOT_FOUND Did not find the SMBIOS table. + +**/ +EFI_STATUS +EFIAPI +NetLibGetSystemGuid ( + OUT EFI_GUID *SystemGuid + ) +{ + EFI_STATUS Status; + SMBIOS_TABLE_ENTRY_POINT *SmbiosTable; + SMBIOS_STRUCTURE_POINTER Smbios; + SMBIOS_STRUCTURE_POINTER SmbiosEnd; + CHAR8 *String; + + SmbiosTable = NULL; + Status = EfiGetSystemConfigurationTable (&gEfiSmbiosTableGuid, (VOID **) &SmbiosTable); + + if (EFI_ERROR (Status) || SmbiosTable == NULL) { + return EFI_NOT_FOUND; + } + + Smbios.Hdr = (SMBIOS_STRUCTURE *) (UINTN) SmbiosTable->TableAddress; + SmbiosEnd.Raw = (UINT8 *) (UINTN) (SmbiosTable->TableAddress + SmbiosTable->TableLength); + + do { + if (Smbios.Hdr->Type == 1) { + if (Smbios.Hdr->Length < 0x19) { + // + // Older version did not support UUID. + // + return EFI_NOT_FOUND; + } + + // + // SMBIOS tables are byte packed so we need to do a byte copy to + // prevend alignment faults on Itanium-based platform. + // + CopyMem (SystemGuid, &Smbios.Type1->Uuid, sizeof (EFI_GUID)); + return EFI_SUCCESS; + } + + // + // Go to the next SMBIOS structure. Each SMBIOS structure may include 2 parts: + // 1. Formatted section; 2. Unformatted string section. So, 2 steps are needed + // to skip one SMBIOS structure. + // + + // + // Step 1: Skip over formatted section. + // + String = (CHAR8 *) (Smbios.Raw + Smbios.Hdr->Length); + + // + // Step 2: Skip over unformated string section. + // + do { + // + // Each string is terminated with a NULL(00h) BYTE and the sets of strings + // is terminated with an additional NULL(00h) BYTE. + // + for ( ; *String != 0; String++) { + } + + if (*(UINT8*)++String == 0) { + // + // Pointer to the next SMBIOS structure. + // + Smbios.Raw = (UINT8 *)++String; + break; + } + } while (TRUE); + } while (Smbios.Raw < SmbiosEnd.Raw); + return EFI_NOT_FOUND; +}