示例#1
0
void DecodeYouTubeFormats(char *Formats, ListNode *Vars)
{
char *Token=NULL, *Tempstr=NULL, *TypeCode=NULL, *URL=NULL, *ptr;

ptr=GetToken(Formats,",",&Token,0);
while (ptr)
{
	YouTubeFormatGetData(Token, &URL, &TypeCode);
	switch (atoi(TypeCode))
	{
			case 5:
			SetVar(Vars,"item:flv:400x240",URL);
			break;

			case 6:
			SetVar(Vars,"item:flv:480x270",URL);
			break;

			case 13:
			SetVar(Vars,"item:3gp",URL);
			break;

			case 17:
			SetVar(Vars,"item:3gp:176x144",URL);
			break;

			case 18:
			SetVar(Vars,"item:mp4:480x360",URL);
			break;

			case 22:
			SetVar(Vars,"item:mp4:1280x720",URL);
			break;

			case 34:
			SetVar(Vars,"item:flv-h264:640x360",URL);
			break;

			case 35:
			SetVar(Vars,"item:flv-h264:854x480",URL);
			break;

			case 36:
			SetVar(Vars,"item:3gp:400x240",URL);
			break;


			case 37:
			SetVar(Vars,"item:mp4:1920x1080",URL);
			break;

			case 38:
			SetVar(Vars,"item:mp4:4096x3072",URL);
			break;

			case 43:
			SetVar(Vars,"item:webm:640x360",URL);
			break;

			case 44:
			SetVar(Vars,"item:webm:854x480",URL);
			break;

			case 45:
			SetVar(Vars,"item:webm:1280x720",URL);
			break;

			case 46:
			SetVar(Vars,"item:webm:1920x1080",URL);
			break;

			case 82:
			SetVar(Vars,"item:mp4-3D:640x360",URL);
			break;

			case 83:
			SetVar(Vars,"item:mp4-3D:854x240",URL);
			break;

			case 84:
			SetVar(Vars,"item:mp4-3D:1280x720",URL);
			break;

			case 85:
			SetVar(Vars,"item:mp4-3D:1920x520",URL);
			break;

			case 100:
			SetVar(Vars,"item:webm-3D:640x360",URL);
			break;

			case 101:
			SetVar(Vars,"item:webm-3D:854x480",URL);
			break;

			case 102:
			SetVar(Vars,"item:webm-3D:1280x720",URL);
			break;



			default:
			//	if (! Flags & FLAG_QUIET)
			if (StrLen(ptr)) fprintf(stderr,"Unknown youtube format [%s]\n",Token);
			break;
		}
ptr=GetToken(ptr,",",&Token,0);
}

DestroyString(TypeCode);
DestroyString(URL);
DestroyString(Token);
DestroyString(Tempstr);
}
示例#2
0
文件: MemoryTest.c 项目: b-man/edk2
/**
  Perform the memory test base on the memory test intensive level,
  and update the memory resource.

  @param  Level         The memory test intensive level.

  @retval EFI_STATUS    Success test all the system memory and update
                        the memory resource

**/
EFI_STATUS
EFIAPI
BdsMemoryTest (
  IN EXTENDMEM_COVERAGE_LEVEL Level
  )
{
  EFI_STATUS                        Status;
  EFI_STATUS                        KeyStatus;
  EFI_STATUS                        InitStatus;
  EFI_STATUS                        ReturnStatus;
  BOOLEAN                           RequireSoftECCInit;
  EFI_GENERIC_MEMORY_TEST_PROTOCOL  *GenMemoryTest;
  UINT64                            TestedMemorySize;
  UINT64                            TotalMemorySize;
  UINTN                             TestPercent;
  UINT64                            PreviousValue;
  BOOLEAN                           ErrorOut;
  BOOLEAN                           TestAbort;
  EFI_INPUT_KEY                     Key;
  CHAR16                            StrPercent[80];
  CHAR16                            *StrTotalMemory;
  CHAR16                            *Pos;
  CHAR16                            *TmpStr;
  EFI_GRAPHICS_OUTPUT_BLT_PIXEL     Foreground;
  EFI_GRAPHICS_OUTPUT_BLT_PIXEL     Background;
  EFI_GRAPHICS_OUTPUT_BLT_PIXEL     Color;
  BOOLEAN                           IsFirstBoot;
  UINT32                            TempData;
  UINTN                             StrTotalMemorySize;

  ReturnStatus = EFI_SUCCESS;
  ZeroMem (&Key, sizeof (EFI_INPUT_KEY));

  StrTotalMemorySize = 128;
  Pos = AllocateZeroPool (StrTotalMemorySize);

  if (Pos == NULL) {
    return ReturnStatus;
  }

  StrTotalMemory    = Pos;

  TestedMemorySize  = 0;
  TotalMemorySize   = 0;
  PreviousValue     = 0;
  ErrorOut          = FALSE;
  TestAbort         = FALSE;

  SetMem (&Foreground, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0xff);
  SetMem (&Background, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0x0);
  SetMem (&Color, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0xff);

  RequireSoftECCInit = FALSE;

  Status = gBS->LocateProtocol (
                  &gEfiGenericMemTestProtocolGuid,
                  NULL,
                  (VOID **) &GenMemoryTest
                  );
  if (EFI_ERROR (Status)) {
    FreePool (Pos);
    return EFI_SUCCESS;
  }

  InitStatus = GenMemoryTest->MemoryTestInit (
                                GenMemoryTest,
                                Level,
                                &RequireSoftECCInit
                                );
  if (InitStatus == EFI_NO_MEDIA) {
    //
    // The PEI codes also have the relevant memory test code to check the memory,
    // it can select to test some range of the memory or all of them. If PEI code
    // checks all the memory, this BDS memory test will has no not-test memory to
    // do the test, and then the status of EFI_NO_MEDIA will be returned by
    // "MemoryTestInit". So it does not need to test memory again, just return.
    //
    FreePool (Pos);
    return EFI_SUCCESS;
  }

  if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
    TmpStr = GetStringById (STRING_TOKEN (STR_ESC_TO_SKIP_MEM_TEST));

    if (TmpStr != NULL) {
      PrintXY (10, 10, NULL, NULL, TmpStr);
      FreePool (TmpStr);
    }
  } else {
    DEBUG ((EFI_D_INFO, "Enter memory test.\n"));
  }
  do {
    Status = GenMemoryTest->PerformMemoryTest (
                              GenMemoryTest,
                              &TestedMemorySize,
                              &TotalMemorySize,
                              &ErrorOut,
                              TestAbort
                              );
    if (ErrorOut && (Status == EFI_DEVICE_ERROR)) {
      TmpStr = GetStringById (STRING_TOKEN (STR_SYSTEM_MEM_ERROR));
      if (TmpStr != NULL) {
        PrintXY (10, 10, NULL, NULL, TmpStr);
        FreePool (TmpStr);
      }

      ASSERT (0);
    }

    if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
      TempData = (UINT32) DivU64x32 (TotalMemorySize, 16);
      TestPercent = (UINTN) DivU64x32 (
                              DivU64x32 (MultU64x32 (TestedMemorySize, 100), 16),
                              TempData
                              );
      if (TestPercent != PreviousValue) {
        UnicodeValueToStringS (StrPercent, sizeof (StrPercent), 0, TestPercent, 0);
        TmpStr = GetStringById (STRING_TOKEN (STR_MEMORY_TEST_PERCENT));
        if (TmpStr != NULL) {
          //
          // TmpStr size is 64, StrPercent is reserved to 16.
          //
          StrnCatS (
            StrPercent,
            sizeof (StrPercent) / sizeof (CHAR16),
            TmpStr,
            sizeof (StrPercent) / sizeof (CHAR16) - StrLen (StrPercent) - 1
            );
          PrintXY (10, 10, NULL, NULL, StrPercent);
          FreePool (TmpStr);
        }

        TmpStr = GetStringById (STRING_TOKEN (STR_PERFORM_MEM_TEST));
        if (TmpStr != NULL) {
          PlatformBdsShowProgress (
            Foreground,
            Background,
            TmpStr,
            Color,
            TestPercent,
            (UINTN) PreviousValue
            );
          FreePool (TmpStr);
        }
      }

      PreviousValue = TestPercent;
    } else {
      DEBUG ((EFI_D_INFO, "Perform memory test (ESC to skip).\n"));
    }

    if (!PcdGetBool (PcdConInConnectOnDemand)) {
      KeyStatus     = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
      if (!EFI_ERROR (KeyStatus) && (Key.ScanCode == SCAN_ESC)) {
        if (!RequireSoftECCInit) {
          if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
            TmpStr = GetStringById (STRING_TOKEN (STR_PERFORM_MEM_TEST));
            if (TmpStr != NULL) {
              PlatformBdsShowProgress (
                Foreground,
                Background,
                TmpStr,
                Color,
                100,
                (UINTN) PreviousValue
                );
              FreePool (TmpStr);
            }

            PrintXY (10, 10, NULL, NULL, L"100");
          }
          Status = GenMemoryTest->Finished (GenMemoryTest);
          goto Done;
        }

        TestAbort = TRUE;
      }
    }
  } while (Status != EFI_NOT_FOUND);

  Status = GenMemoryTest->Finished (GenMemoryTest);

Done:
  if (!FeaturePcdGet(PcdBootlogoOnlyEnable)) {
    UnicodeValueToStringS (StrTotalMemory, StrTotalMemorySize, COMMA_TYPE, TotalMemorySize, 0);
    if (StrTotalMemory[0] == L',') {
      StrTotalMemory++;
      StrTotalMemorySize -= sizeof (CHAR16);
    }

    TmpStr = GetStringById (STRING_TOKEN (STR_MEM_TEST_COMPLETED));
    if (TmpStr != NULL) {
      StrnCatS (
        StrTotalMemory,
        StrTotalMemorySize / sizeof (CHAR16),
        TmpStr,
        StrTotalMemorySize / sizeof (CHAR16) - StrLen (StrTotalMemory) - 1
        );
      FreePool (TmpStr);
    }

    PrintXY (10, 10, NULL, NULL, StrTotalMemory);
    PlatformBdsShowProgress (
      Foreground,
      Background,
      StrTotalMemory,
      Color,
      100,
      (UINTN) PreviousValue
      );

  } else {
    DEBUG ((EFI_D_INFO, "%d bytes of system memory tested OK\r\n", TotalMemorySize));
  }

  FreePool (Pos);


  //
  // Use a DynamicHii type pcd to save the boot status, which is used to
  // control configuration mode, such as FULL/MINIMAL/NO_CHANGES configuration.
  //
  IsFirstBoot = PcdGetBool(PcdBootState);
  if (IsFirstBoot) {
    Status = PcdSetBoolS(PcdBootState, FALSE);
    if (EFI_ERROR (Status)) {
      DEBUG ((EFI_D_ERROR, "Set PcdBootState to FALSE failed.\n"));
    }
  }

  return ReturnStatus;
}
示例#3
0
EFIAPI
TrimFilePathToAbsolutePath (
    IN CHAR16 *Path
)
{
    CHAR16  *TempString;
    UINTN   TempSize;

    if (Path == NULL) {
        return NULL;
    }

    //
    // Fix up the '/' vs '\'
    //
    for (TempString = Path ; (TempString != NULL) && (*TempString != CHAR_NULL); TempString++) {
        if (*TempString == L'/') {
            *TempString = L'\\';
        }
    }

    //
    // Fix up the ..
    //
    while ((TempString = StrStr (Path, L"\\..\\")) != NULL) {
        *TempString  = CHAR_NULL;
        TempString  += 4;
        RemoveLastItemFromPath (Path);
        TempSize     = StrSize (TempString);
        CopyMem (Path + StrLen (Path), TempString, TempSize);
    }

    if (((TempString = StrStr (Path, L"\\..")) != NULL) && (*(TempString + 3) == CHAR_NULL)) {
        *TempString  = CHAR_NULL;
        RemoveLastItemFromPath (Path);
    }

    //
    // Fix up the .
    //
    while ((TempString = StrStr (Path, L"\\.\\")) != NULL) {
        *TempString  = CHAR_NULL;
        TempString  += 2;
        TempSize     = StrSize (TempString);
        CopyMem(Path + StrLen (Path), TempString, TempSize);
    }

    if (((TempString = StrStr (Path, L"\\.")) != NULL) && (*(TempString + 2) == CHAR_NULL)) {
        *(TempString + 1) = CHAR_NULL;
    }

    while ((TempString = StrStr (Path, L"\\\\")) != NULL) {
        *TempString  = CHAR_NULL;
        TempString  += 1;
        TempSize     = StrSize(TempString);
        CopyMem(Path + StrLen(Path), TempString, TempSize);
    }

    if (((TempString = StrStr(Path, L"\\\\")) != NULL) && (*(TempString + 1) == CHAR_NULL)) {
        *(TempString) = CHAR_NULL;
    }

    return Path;
}
示例#4
0
EFI_STATUS
GuidMain (
  IN EFI_HANDLE               ImageHandle,
  IN EFI_SYSTEM_TABLE         *SystemTable
  )
/*++

Routine Description:

  Code for external shell "guid" command.

Arguments:

  ImageHandle - The image handle
  SystemTable - The system table

Returns:

--*/
{
  PROTOCOL_INFO           *Prot;
  UINTN                   Len;
  UINTN                   SLen;
  EFI_STATUS              Status;

  SHELL_VAR_CHECK_CODE    RetCode;
  CHAR16                  *Useful;
  SHELL_VAR_CHECK_PACKAGE ChkPck;

  ZeroMem (&ChkPck, sizeof (SHELL_VAR_CHECK_PACKAGE));
  EFI_SHELL_APP_INIT (ImageHandle, SystemTable);
  
  //
  // Enable tab key which can pause the output
  //
  EnableOutputTabPause();

  Status = LibInitializeStrings (&HiiHandle, STRING_ARRAY_NAME, &EfiGuidGuid);
  if (EFI_ERROR (Status)) {
    return Status;
  }

  if (!EFI_PROPER_VERSION (0, 99)) {
    PrintToken (
      STRING_TOKEN (STR_SHELLENV_GNC_COMMAND_NOT_SUPPORT),
      HiiHandle,
      L"guid",
      EFI_VERSION_0_99 
      );
    Status = EFI_UNSUPPORTED;
    goto Done;
  }
  //
  // Initializing variable to aVOID level 4 warning
  //
  RetCode = LibCheckVariables (SI, GuidCheckList, &ChkPck, &Useful);

  if (VarCheckOk != RetCode) {
    switch (RetCode) {
    case VarCheckUnknown:
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_UNKNOWN_FLAG), HiiHandle, L"guid", Useful);
      break;

    case VarCheckDuplicate:
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_DUP_FLAG), HiiHandle, L"guid", Useful);
      break;

    default:
      break;
    }

    Status = EFI_INVALID_PARAMETER;
    goto Done;
  }

  if (LibCheckVarGetFlag (&ChkPck, L"-b") != NULL) {
    EnablePageBreak (DEFAULT_INIT_ROW, DEFAULT_AUTO_LF);
  }

  if (LibCheckVarGetFlag (&ChkPck, L"-?")) {
    if (ChkPck.ValueCount > 0 ||
        ChkPck.FlagCount > 2 ||
        (2 == ChkPck.FlagCount && !LibCheckVarGetFlag (&ChkPck, L"-b"))
        ) {
      PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiHandle, L"guid");
      Status = EFI_INVALID_PARAMETER;
    } else {
      PrintToken (STRING_TOKEN (STR_GUID_VERBOSEHELP), HiiHandle);
      Status = EFI_SUCCESS;
    }

    goto Done;
  }

  if (ChkPck.ValueCount > 0) {
    PrintToken (STRING_TOKEN (STR_SHELLENV_GNC_TOO_MANY), HiiHandle, L"guid");
    Status = EFI_INVALID_PARAMETER;
    goto Done;
  }
  //
  // Find the protocol entry for this id
  //
  Status  = EFI_SUCCESS;
  SLen    = 0;
  Prot    = NULL;
  ShellInitProtocolInfoEnumerator ();
  do {
    Status = ShellNextProtocolInfo (&Prot);
    if (Prot == NULL && Status == EFI_SUCCESS) {
      break;
    }

    Len = StrLen (Prot->IdString);
    if (StrLen (Prot->IdString) > SLen) {
      SLen = Len;
    }
  } while (Prot != NULL);

  ShellResetProtocolInfoEnumerator ();
  do {
    Status = ShellNextProtocolInfo (&Prot);
    if (Prot == NULL && Status == EFI_SUCCESS) {
      break;
    }
    //
    // Can't use Lib function to dump the guid as it may lookup the
    // "short name" for it
    //
    if (GetExecutionBreak ()) {
      Status = EFI_ABORTED;
      break;
    }

    PrintToken (
      STRING_TOKEN (STR_SHELLENV_PROTID_FOURTEEN_VARS),
      HiiHandle,
      SLen,
      Prot->IdString,
      Prot->ProtocolId.Data1,
      Prot->ProtocolId.Data2,
      Prot->ProtocolId.Data3,
      Prot->ProtocolId.Data4[0],
      Prot->ProtocolId.Data4[1],
      Prot->ProtocolId.Data4[2],
      Prot->ProtocolId.Data4[3],
      Prot->ProtocolId.Data4[4],
      Prot->ProtocolId.Data4[5],
      Prot->ProtocolId.Data4[6],
      Prot->ProtocolId.Data4[7],
      (Prot->DumpToken || Prot->DumpInfo) ? L'*' : L' '
      );
  } while (Prot != NULL);

  ShellCloseProtocolInfoEnumerator ();

Done:
  LibCheckVarFreeVarList (&ChkPck);
  LibUnInitializeStrings ();
  return Status;
}
示例#5
0
文件: cgi.c 项目: ColumPaget/Hashrat
static void CGIDrawHashResult(const char *Hash)
{
	printf("<p /><p />\r\n");
	printf("<table align=center bgcolor=#FFBBBB>\r\n");
	printf("<tr><th bgcolor=red><font color=white>Your Hash is:</font></th></tr>\r\n");
//	printf("<tr><td><b>%s</b></td>\r\n",Hash);
//	printf("<tr><td>Here it is in a text box so you can 'select all'</td>\r\n");
	printf("<tr><td align=center><textarea align=center rows=1 cols=%d readonly style=\"font-weight: bold;  font-size:16px\">%s</textarea></td>\n",StrLen(Hash)+2, Hash);
	printf("</table>\r\n");
	printf("<p /><p />\r\n");
}
示例#6
0
/**
  The internal function prints to the EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL
  protocol instance.

  @param Column          The position of the output string.
  @param Row             The position of the output string.
  @param Out             The EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL instance.
  @param Fmt             The format string.
  @param Args            The additional argument for the variables in the format string.

  @return Number of Unicode character printed.

**/
UINTN
PrintInternal (
  IN UINTN                            Column,
  IN UINTN                            Row,
  IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *Out,
  IN CHAR16                           *Fmt,
  IN VA_LIST                          Args
  )
{
  CHAR16  *Buffer;
  CHAR16  *BackupBuffer;
  UINTN   Index;
  UINTN   PreviousIndex;
  UINTN   Count;

  //
  // For now, allocate an arbitrarily long buffer
  //
  Buffer        = AllocateZeroPool (0x10000);
  BackupBuffer  = AllocateZeroPool (0x10000);
  ASSERT (Buffer);
  ASSERT (BackupBuffer);

  if (Column != (UINTN) -1) {
    Out->SetCursorPosition (Out, Column, Row);
  }

  UnicodeVSPrint (Buffer, 0x10000, Fmt, Args);

  Out->Mode->Attribute = Out->Mode->Attribute & 0x7f;

  Out->SetAttribute (Out, Out->Mode->Attribute);

  Index         = 0;
  PreviousIndex = 0;
  Count         = 0;

  do {
    for (; (Buffer[Index] != NARROW_CHAR) && (Buffer[Index] != WIDE_CHAR) && (Buffer[Index] != 0); Index++) {
      BackupBuffer[Index] = Buffer[Index];
    }

    if (Buffer[Index] == 0) {
      break;
    }
    //
    // Null-terminate the temporary string
    //
    BackupBuffer[Index] = 0;

    //
    // Print this out, we are about to switch widths
    //
    Out->OutputString (Out, &BackupBuffer[PreviousIndex]);
    Count += StrLen (&BackupBuffer[PreviousIndex]);

    //
    // Preserve the current index + 1, since this is where we will start printing from next
    //
    PreviousIndex = Index + 1;

    //
    // We are at a narrow or wide character directive.  Set attributes and strip it and print it
    //
    if (Buffer[Index] == NARROW_CHAR) {
      //
      // Preserve bits 0 - 6 and zero out the rest
      //
      Out->Mode->Attribute = Out->Mode->Attribute & 0x7f;
      Out->SetAttribute (Out, Out->Mode->Attribute);
    } else {
      //
      // Must be wide, set bit 7 ON
      //
      Out->Mode->Attribute = Out->Mode->Attribute | EFI_WIDE_ATTRIBUTE;
      Out->SetAttribute (Out, Out->Mode->Attribute);
    }

    Index++;

  } while (Buffer[Index] != 0);

  //
  // We hit the end of the string - print it
  //
  Out->OutputString (Out, &BackupBuffer[PreviousIndex]);
  Count += StrLen (&BackupBuffer[PreviousIndex]);

  FreePool (Buffer);
  FreePool (BackupBuffer);
  return Count;
}
示例#7
0
char *FormatFancyDirItem(char *RetStr, int count, TPathItem *File, const char *MimeIconsURL, int Flags)
{
char *Tempstr=NULL, *FileType=NULL, *DateStr=NULL, *DisplayName=NULL, *Interact=NULL;
char *Comment=NULL, *CheckBox=NULL, *ptr;
char *bgcolor;
ListNode *Vars;

	
	Vars=ListCreate();
	LoadFileProperties(File->Path, Vars);

/*
	ptr=GetVar(Vars,"comment");
	if (StrLen(ptr)) 
	{
		Comment=MCopyStr(Comment," title=\"",ptr,"\" ",NULL);
	}
	else Comment=CopyStr(Comment,"");
*/

	Comment=FormatFancyDirComment(Comment, Vars);

		if ((count % 2)==0) bgcolor="#FFFFFF";
		else bgcolor="#CCCCCC";

		if ((Now - File->Mtime) < 60)
		{
			DateStr=FormatStr(DateStr,"<font color=red>%d seconds ago</font>",Now - File->Mtime);
		}
		else DateStr=CopyStr(DateStr,GetDateStrFromSecs("%Y/%m/%d %H:%M:%S",File->Mtime,NULL));

		FileType=FormatFileType(FileType, File, Vars, MimeIconsURL);
		//Okay, start building the actual table row
		RetStr=MCatStr(RetStr, "<tr bgcolor=\"",bgcolor,"\">",NULL);
		Interact=CopyStr(Interact,"");
		CheckBox=CopyStr(CheckBox,"");

		if (strcmp(File->Name,"..")==0) 
		{
			DisplayName=CopyStr(DisplayName,".. (Parent Directory)");
			if (Settings.DirListFlags & DIR_INTERACTIVE) CheckBox=CopyStr(CheckBox,"<td align=\"center\">&nbsp;</td>");
		}
		else 
		{
			if (Settings.DisplayNameLen && (StrLen(File->Name) > Settings.DisplayNameLen)) 
			{
			DisplayName=CopyStrLen(DisplayName,File->Name,Settings.DisplayNameLen);
			DisplayName=CatStr(DisplayName,"...");
			}
			else DisplayName=CopyStr(DisplayName,File->Name);


		if (Settings.DirListFlags & DIR_INTERACTIVE)
		{
			if (Flags & SELECT_ALL) CheckBox=MCatStr(CheckBox,"<td align=\"center\"><input type=\"checkbox\" name=\"selected\" value=\"",File->Name,"\" checked /></td>",NULL);
			else CheckBox=MCatStr(CheckBox,"<td align=\"center\"><input type=\"checkbox\" name=\"selected\" value=\"",File->Name,"\" /></td>",NULL);

			//Interaction string will be added to end of line
			Interact=MCatStr(Interact,"<input type='submit' name='edit:",File->URL,"' value='Edit' /> ",NULL);
			Interact=MCatStr(Interact,"<input type='submit' name='del:",File->URL,"' value='Del' /> ",NULL);
			
			//one day, but not yet
			//if (strncasecmp(File->ContentType,"audio/",6)==0) Interact=MCatStr(Interact,"<input type=\"button\" onclick=\"javascript: addaudio('",File->URL,"');\" value=\"Play\" /> ",NULL);
		}
		}

		Tempstr=FormatStr(Tempstr,"%s<td title=\"%s\">%s</td><td><a href=\"%s\" title=\"%s\">%s</a></td><td align=right> &nbsp; %s</td><td align=right> &nbsp; %s</td><td align=center>%s</td>",CheckBox,Comment,FileType,File->URL, File->Path, DisplayName, DateStr, GetHumanReadableDataQty((double) File->Size,0), Interact);

		//Append it all to our output
		RetStr=MCatStr(RetStr,Tempstr,"</tr>\r\n",NULL);

		DestroyString(DisplayName);
		DestroyString(FileType);
		DestroyString(Interact);
		DestroyString(Comment);
		DestroyString(Tempstr);
		DestroyString(DateStr);

	ListDestroy(Vars,DestroyString);

return(RetStr);
}
示例#8
0
// RPC client connect
UINT EcConnect(char *host, UINT port, char *password, RPC **rpc)
{
	SOCK *s;
	UCHAR password_hash[SHA1_SIZE];
	UCHAR rand[SHA1_SIZE];
	UCHAR response[SHA1_SIZE];
	bool retcode;
	// Validate arguments
	if (host == NULL)
	{
		host = "localhost";
	}
	if (port == 0)
	{
		port = EL_ADMIN_PORT;
	}
	if (password == NULL)
	{
		password = "";
	}
	if (rpc == NULL)
	{
		return ERR_INTERNAL_ERROR;
	}

	// Connect to the server
	s = Connect(host, port);
	if (s == NULL)
	{
		// Connection failure
		return ERR_CONNECT_FAILED;
	}

	SetTimeout(s, 5000);

	// Hash the password
	Hash(password_hash, password, StrLen(password), true);

	// Receive the random number
	Zero(rand, sizeof(rand));
	RecvAll(s, rand, sizeof(rand), false);
	SecurePassword(response, password_hash, rand);

	// Send a response
	SendAll(s, response, sizeof(response), false);

	// Receive results
	retcode = false;
	if (RecvAll(s, &retcode, sizeof(retcode), false) == false)
	{
		// Disconnect
		ReleaseSock(s);
		return ERR_PROTOCOL_ERROR;
	}
	retcode = Endian32(retcode);

	if (retcode == false)
	{
		// Password incorrect
		ReleaseSock(s);
		return ERR_AUTH_FAILED;
	}

	// Successful connection
	SetTimeout(s, INFINITE);

	*rpc = StartRpcClient(s, NULL);

	ReleaseSock(s);

	return ERR_NO_ERROR;
}
示例#9
0
static void PrvImgView(WND wnd)
{
	int fd, len;
	ruint16 i, j;
	char tmp[10];
	struct img_data *picture;
	unsigned char *p;
	COLORVAL color;

	MemSet(tmp, 0, 10);
	fd = RalOpenFile((char *)&fileList[imgfocusedList]);
	if (fd == -1 ) 
	{
		GdiTextOut(wnd, "File Not Found", StrLen("File Not Found"), 20, 300);
		return ;
	}
	//GdiTextOut(wnd, "check", StrLen("test"), 140, 10);
	picture = NULL;
	len = StrLen(fileList[imgfocusedList]);
	p = &fileList[imgfocusedList][len-3];
	if ( !StrNCmp(p, "jpg", 3) || !StrNCmp(p, "JPG", 3) )
	{
		picture = img_jpeg_read(fd, 240, 320);
	}
	else if ( !StrNCmp(p, "gif", 3) || !StrNCmp(p, "GIF", 3) )
	{
		picture = img_gif_read(fd, 240, 320);
	}
	else if ( !StrNCmp(p, "png", 3) || !StrNCmp(p, "PNG", 3) )
	{
		picture = img_png_read(fd, 240, 320);
	}
	
	if (picture == NULL)
	{
		GdiTextOut(wnd, "Image File Read fail", StrLen("Image File Read fail"), 20, 300);
		return ;
	}

	imgStateID = IMAGEVIEW_STATE_FILE_SHOW;

	GdiLockScreen(wnd);
	GdiClrScreen(wnd, COLOR_BLACK);
	StrIToA(picture->size, tmp);
	//GdiTextOut(wnd, tmp, StrLen(tmp), 100, 310);

	p = picture->data;
	for(i=0; i<picture->height; i++)
	{
		for(j=0; j<picture->width; j++)
		{
			color = *p <<8 | (*(p+1) );
			GdiSetPixel(wnd, j, i, color );
			p += 2;
		}
	}
	GdiTextOut(wnd, fileList[imgfocusedList], StrLen(fileList[imgfocusedList]), 80, 300);


	if (picture) 
	{
		if (picture->data)
			free(picture->data);
		free(picture);
	}
	GdiUnlockScreen(wnd);

}
/**
  return the next parameter from a command line string;

  This function moves the next parameter from Walker into TempParameter and moves
  Walker up past that parameter for recursive calling.  When the final parameter
  is moved *Walker will be set to NULL;

  Temp Parameter must be large enough to hold the parameter before calling this
  function.

  @param[in, out] Walker        pointer to string of command line.  Adjusted to
                                reminaing command line on return
  @param[in, out] TempParameter pointer to string of command line item extracted.

**/
VOID
EFIAPI
GetNextParameter(
  CHAR16 **Walker,
  CHAR16 **TempParameter
  )
{
  CHAR16 *NextDelim;
  CHAR16 *TempLoc;

  ASSERT(Walker           != NULL);
  ASSERT(*Walker          != NULL);
  ASSERT(TempParameter    != NULL);
  ASSERT(*TempParameter   != NULL);

  //
  // make sure we dont have any leading spaces
  //
  while ((*Walker)[0] == L' ') {
      (*Walker)++;
  }

  //
  // make sure we still have some params now...
  //
  if (StrLen(*Walker) == 0) {
    ASSERT((*Walker)[0] == CHAR_NULL);
    *Walker = NULL;
    return;
  }

  //
  // we have a quoted parameter
  // could be the last parameter, but SHOULD have a trailing quote
  //
  if ((*Walker)[0] == L'\"') {
    NextDelim = NULL;
    for (TempLoc = *Walker + 1 ; TempLoc != NULL && *TempLoc != CHAR_NULL ; TempLoc++) {
      if (*TempLoc == L'^' && *(TempLoc+1) == L'\"') {
        TempLoc++;
      } else if (*TempLoc == L'\"') {
        NextDelim = TempLoc;
        break;
      }
    }

    if (NextDelim - ((*Walker)+1) == 0) {
      //
      // found ""
      //
      StrCpy(*TempParameter, L"");
      *Walker = NextDelim + 1;
    } else if (NextDelim != NULL) {
      StrnCpy(*TempParameter, (*Walker)+1, NextDelim - ((*Walker)+1));
      *Walker = NextDelim + 1;
    } else {
      //
      // last one... someone forgot the training quote!
      //
      StrCpy(*TempParameter, *Walker);
      *Walker = NULL;
    }
    for (TempLoc = *TempParameter ; TempLoc != NULL && *TempLoc != CHAR_NULL ; TempLoc++) {
      if (*TempLoc == L'^' && *(TempLoc+1) == L'\"') {
        CopyMem(TempLoc, TempLoc+1, StrSize(TempLoc) - sizeof(TempLoc[0]));
      }
    }
  } else {
    //
    // we have a regular parameter (no quote) OR
    // we have the final parameter (no trailing space)
    //
    NextDelim = StrStr((*Walker), L" ");
    if (NextDelim != NULL) {
      StrnCpy(*TempParameter, *Walker, NextDelim - (*Walker));
      (*TempParameter)[NextDelim - (*Walker)] = CHAR_NULL;
      *Walker = NextDelim+1;
    } else {
      //
      // last one.
      //
      StrCpy(*TempParameter, *Walker);
      *Walker = NULL;
    }
    for (NextDelim = *TempParameter ; NextDelim != NULL && *NextDelim != CHAR_NULL ; NextDelim++) {
      if (*NextDelim == L'^' && *(NextDelim+1) == L'^') {
        CopyMem(NextDelim, NextDelim+1, StrSize(NextDelim) - sizeof(NextDelim[0]));
      }
    }
    while ((*TempParameter)[StrLen(*TempParameter)-1] == L' ') {
      (*TempParameter)[StrLen(*TempParameter)-1] = CHAR_NULL;
    }
    while ((*TempParameter)[0] == L' ') {
      CopyMem(*TempParameter, (*TempParameter)+1, StrSize(*TempParameter) - sizeof((*TempParameter)[0]));
    }
  }
  return;
}
示例#11
0
/**
  Get selection for OneOf and OrderedList (Left/Right will be ignored).

  @param  MenuOption        Pointer to the current input menu.

  @retval EFI_SUCCESS       If Option input is processed successfully
  @retval EFI_DEVICE_ERROR  If operation fails

**/
EFI_STATUS
GetSelectionInputPopUp (
  IN  UI_MENU_OPTION              *MenuOption
  )
{
  EFI_STATUS              Status;
  EFI_INPUT_KEY           Key;
  UINTN                   Index;
  CHAR16                  *StringPtr;
  CHAR16                  *TempStringPtr;
  UINTN                   Index2;
  UINTN                   TopOptionIndex;
  UINTN                   HighlightOptionIndex;
  UINTN                   Start;
  UINTN                   End;
  UINTN                   Top;
  UINTN                   Bottom;
  UINTN                   PopUpMenuLines;
  UINTN                   MenuLinesInView;
  UINTN                   PopUpWidth;
  CHAR16                  Character;
  INT32                   SavedAttribute;
  BOOLEAN                 ShowDownArrow;
  BOOLEAN                 ShowUpArrow;
  UINTN                   DimensionsWidth;
  LIST_ENTRY              *Link;
  BOOLEAN                 OrderedList;
  UINT8                   *ValueArray;
  UINT8                   *ReturnValue;
  UINT8                   ValueType;
  EFI_HII_VALUE           HiiValue;
  DISPLAY_QUESTION_OPTION         *OneOfOption;
  DISPLAY_QUESTION_OPTION         *CurrentOption;
  FORM_DISPLAY_ENGINE_STATEMENT  *Question;
  INTN                    Result;
  EFI_IFR_ORDERED_LIST    *OrderList;

  DimensionsWidth   = gStatementDimensions.RightColumn - gStatementDimensions.LeftColumn;

  ValueArray        = NULL;
  ValueType         = 0;
  CurrentOption     = NULL;
  ShowDownArrow     = FALSE;
  ShowUpArrow       = FALSE;

  StringPtr = AllocateZeroPool ((gOptionBlockWidth + 1) * 2);
  ASSERT (StringPtr);

  ZeroMem (&HiiValue, sizeof (EFI_HII_VALUE));

  Question = MenuOption->ThisTag;
  if (Question->OpCode->OpCode == EFI_IFR_ORDERED_LIST_OP) {
    Link = GetFirstNode (&Question->OptionListHead);
    OneOfOption = DISPLAY_QUESTION_OPTION_FROM_LINK (Link);
    ValueArray = Question->CurrentValue.Buffer;
    ValueType =  OneOfOption->OptionOpCode->Type;
    OrderedList = TRUE;
    OrderList = (EFI_IFR_ORDERED_LIST *) Question->OpCode;
  } else {
    OrderedList = FALSE;
    OrderList = NULL;
  }

  //
  // Calculate Option count
  //
  PopUpMenuLines = 0;
  if (OrderedList) {
    AdjustOptionOrder(Question, &PopUpMenuLines);
  } else {
    Link = GetFirstNode (&Question->OptionListHead);
    while (!IsNull (&Question->OptionListHead, Link)) {
      OneOfOption = DISPLAY_QUESTION_OPTION_FROM_LINK (Link);
      PopUpMenuLines++;
      Link = GetNextNode (&Question->OptionListHead, Link);
    }
  }

  //
  // Get the number of one of options present and its size
  //
  PopUpWidth = 0;
  HighlightOptionIndex = 0;
  Link = GetFirstNode (&Question->OptionListHead);
  for (Index = 0; Index < PopUpMenuLines; Index++) {
    OneOfOption = DISPLAY_QUESTION_OPTION_FROM_LINK (Link);

    StringPtr = GetToken (OneOfOption->OptionOpCode->Option, gFormData->HiiHandle);
    if (StrLen (StringPtr) > PopUpWidth) {
      PopUpWidth = StrLen (StringPtr);
    }
    FreePool (StringPtr);
    HiiValue.Type = OneOfOption->OptionOpCode->Type;
    SetValuesByType (&HiiValue.Value, &OneOfOption->OptionOpCode->Value, HiiValue.Type);
    if (!OrderedList && (CompareHiiValue (&Question->CurrentValue, &HiiValue, &Result, NULL) == EFI_SUCCESS) && (Result == 0)) {
      //
      // Find current selected Option for OneOf
      //
      HighlightOptionIndex = Index;
    }

    Link = GetNextNode (&Question->OptionListHead, Link);
  }

  //
  // Perform popup menu initialization.
  //
  PopUpWidth = PopUpWidth + POPUP_PAD_SPACE_COUNT;

  SavedAttribute = gST->ConOut->Mode->Attribute;
  gST->ConOut->SetAttribute (gST->ConOut, GetPopupColor ());

  if ((PopUpWidth + POPUP_FRAME_WIDTH) > DimensionsWidth) {
    PopUpWidth = DimensionsWidth - POPUP_FRAME_WIDTH;
  }

  Start  = (DimensionsWidth - PopUpWidth - POPUP_FRAME_WIDTH) / 2 + gStatementDimensions.LeftColumn;
  End    = Start + PopUpWidth + POPUP_FRAME_WIDTH;
  Top    = gStatementDimensions.TopRow;
  Bottom = gStatementDimensions.BottomRow - 1;

  MenuLinesInView = Bottom - Top - 1;
  if (MenuLinesInView >= PopUpMenuLines) {
    Top     = Top + (MenuLinesInView - PopUpMenuLines) / 2;
    Bottom  = Top + PopUpMenuLines + 1;
  } else {
    ShowDownArrow = TRUE;
  }

  if (HighlightOptionIndex > (MenuLinesInView - 1)) {
    TopOptionIndex = HighlightOptionIndex - MenuLinesInView + 1;
  } else {
    TopOptionIndex = 0;
  }

  do {
    //
    // Clear that portion of the screen
    //
    ClearLines (Start, End, Top, Bottom, GetPopupColor ());

    //
    // Draw "One of" pop-up menu
    //
    Character = BOXDRAW_DOWN_RIGHT;
    PrintCharAt (Start, Top, Character);
    for (Index = Start; Index + 2 < End; Index++) {
      if ((ShowUpArrow) && ((Index + 1) == (Start + End) / 2)) {
        Character = GEOMETRICSHAPE_UP_TRIANGLE;
      } else {
        Character = BOXDRAW_HORIZONTAL;
      }

      PrintCharAt ((UINTN)-1, (UINTN)-1, Character);
    }

    Character = BOXDRAW_DOWN_LEFT;
    PrintCharAt ((UINTN)-1, (UINTN)-1, Character);
    Character = BOXDRAW_VERTICAL;
    for (Index = Top + 1; Index < Bottom; Index++) {
      PrintCharAt (Start, Index, Character);
      PrintCharAt (End - 1, Index, Character);
    }

    //
    // Move to top Option
    //
    Link = GetFirstNode (&Question->OptionListHead);
    for (Index = 0; Index < TopOptionIndex; Index++) {
      Link = GetNextNode (&Question->OptionListHead, Link);
    }

    //
    // Display the One of options
    //
    Index2 = Top + 1;
    for (Index = TopOptionIndex; (Index < PopUpMenuLines) && (Index2 < Bottom); Index++) {
      OneOfOption = DISPLAY_QUESTION_OPTION_FROM_LINK (Link);
      Link = GetNextNode (&Question->OptionListHead, Link);

      StringPtr = GetToken (OneOfOption->OptionOpCode->Option, gFormData->HiiHandle);
      ASSERT (StringPtr != NULL);
      //
      // If the string occupies multiple lines, truncate it to fit in one line,
      // and append a "..." for indication.
      //
      if (StrLen (StringPtr) > (PopUpWidth - 1)) {
        TempStringPtr = AllocateZeroPool (sizeof (CHAR16) * (PopUpWidth - 1));
        ASSERT ( TempStringPtr != NULL );
        CopyMem (TempStringPtr, StringPtr, (sizeof (CHAR16) * (PopUpWidth - 5)));
        FreePool (StringPtr);
        StringPtr = TempStringPtr;
        StrCat (StringPtr, L"...");
      }

      if (Index == HighlightOptionIndex) {
          //
          // Highlight the selected one
          //
          CurrentOption = OneOfOption;

          gST->ConOut->SetAttribute (gST->ConOut, GetPickListColor ());
          PrintStringAt (Start + 2, Index2, StringPtr);
          gST->ConOut->SetAttribute (gST->ConOut, GetPopupColor ());
        } else {
          gST->ConOut->SetAttribute (gST->ConOut, GetPopupColor ());
          PrintStringAt (Start + 2, Index2, StringPtr);
        }

      Index2++;
      FreePool (StringPtr);
    }

    Character = BOXDRAW_UP_RIGHT;
    PrintCharAt (Start, Bottom, Character);
    for (Index = Start; Index + 2 < End; Index++) {
      if ((ShowDownArrow) && ((Index + 1) == (Start + End) / 2)) {
        Character = GEOMETRICSHAPE_DOWN_TRIANGLE;
      } else {
        Character = BOXDRAW_HORIZONTAL;
      }

      PrintCharAt ((UINTN)-1, (UINTN)-1, Character);
    }

    Character = BOXDRAW_UP_LEFT;
    PrintCharAt ((UINTN)-1, (UINTN)-1, Character);

    //
    // Get User selection
    //
    Key.UnicodeChar = CHAR_NULL;
    if ((gDirection == SCAN_UP) || (gDirection == SCAN_DOWN)) {
      Key.ScanCode  = gDirection;
      gDirection    = 0;
      goto TheKey;
    }

    Status = WaitForKeyStroke (&Key);

TheKey:
    switch (Key.UnicodeChar) {
    case '+':
      if (OrderedList) {
        if ((TopOptionIndex > 0) && (TopOptionIndex == HighlightOptionIndex)) {
          //
          // Highlight reaches the top of the popup window, scroll one menu item.
          //
          TopOptionIndex--;
          ShowDownArrow = TRUE;
        }

        if (TopOptionIndex == 0) {
          ShowUpArrow = FALSE;
        }

        if (HighlightOptionIndex > 0) {
          HighlightOptionIndex--;

          ASSERT (CurrentOption != NULL);
          SwapListEntries (CurrentOption->Link.BackLink, &CurrentOption->Link);
        }
      }
      break;

    case '-':
      //
      // If an ordered list op-code, we will allow for a popup of +/- keys
      // to create an ordered list of items
      //
      if (OrderedList) {
        if (((TopOptionIndex + MenuLinesInView) < PopUpMenuLines) &&
            (HighlightOptionIndex == (TopOptionIndex + MenuLinesInView - 1))) {
          //
          // Highlight reaches the bottom of the popup window, scroll one menu item.
          //
          TopOptionIndex++;
          ShowUpArrow = TRUE;
        }

        if ((TopOptionIndex + MenuLinesInView) == PopUpMenuLines) {
          ShowDownArrow = FALSE;
        }

        if (HighlightOptionIndex < (PopUpMenuLines - 1)) {
          HighlightOptionIndex++;

          ASSERT (CurrentOption != NULL);
          SwapListEntries (&CurrentOption->Link, CurrentOption->Link.ForwardLink);
        }
      }
      break;

    case CHAR_NULL:
      switch (Key.ScanCode) {
      case SCAN_UP:
      case SCAN_DOWN:
        if (Key.ScanCode == SCAN_UP) {
          if ((TopOptionIndex > 0) && (TopOptionIndex == HighlightOptionIndex)) {
            //
            // Highlight reaches the top of the popup window, scroll one menu item.
            //
            TopOptionIndex--;
            ShowDownArrow = TRUE;
          }

          if (TopOptionIndex == 0) {
            ShowUpArrow = FALSE;
          }

          if (HighlightOptionIndex > 0) {
            HighlightOptionIndex--;
          }
        } else {
          if (((TopOptionIndex + MenuLinesInView) < PopUpMenuLines) &&
              (HighlightOptionIndex == (TopOptionIndex + MenuLinesInView - 1))) {
            //
            // Highlight reaches the bottom of the popup window, scroll one menu item.
            //
            TopOptionIndex++;
            ShowUpArrow = TRUE;
          }

          if ((TopOptionIndex + MenuLinesInView) == PopUpMenuLines) {
            ShowDownArrow = FALSE;
          }

          if (HighlightOptionIndex < (PopUpMenuLines - 1)) {
            HighlightOptionIndex++;
          }
        }
        break;

      case SCAN_ESC:
        gST->ConOut->SetAttribute (gST->ConOut, SavedAttribute);

        //
        // Restore link list order for orderedlist
        //
        if (OrderedList) {
          HiiValue.Type = ValueType;
          HiiValue.Value.u64 = 0;
          for (Index = 0; Index < OrderList->MaxContainers; Index++) {
            HiiValue.Value.u64 = GetArrayData (ValueArray, ValueType, Index);
            if (HiiValue.Value.u64 == 0) {
              break;
            }

            OneOfOption = ValueToOption (Question, &HiiValue);
            if (OneOfOption == NULL) {
              return EFI_NOT_FOUND;
            }

            RemoveEntryList (&OneOfOption->Link);
            InsertTailList (&Question->OptionListHead, &OneOfOption->Link);
          }
        }

        return EFI_DEVICE_ERROR;

      default:
        break;
      }

      break;

    case CHAR_CARRIAGE_RETURN:
      //
      // return the current selection
      //
      if (OrderedList) {
        ReturnValue = AllocateZeroPool (Question->CurrentValue.BufferLen);
        ASSERT (ReturnValue != NULL);
        Index = 0;
        Link = GetFirstNode (&Question->OptionListHead);
        while (!IsNull (&Question->OptionListHead, Link)) {
          OneOfOption = DISPLAY_QUESTION_OPTION_FROM_LINK (Link);
          Link = GetNextNode (&Question->OptionListHead, Link);

          SetArrayData (ReturnValue, ValueType, Index, OneOfOption->OptionOpCode->Value.u64);

          Index++;
          if (Index > OrderList->MaxContainers) {
            break;
          }
        }
        if (CompareMem (ReturnValue, ValueArray, Question->CurrentValue.BufferLen) == 0) {
          FreePool (ReturnValue);
          return EFI_DEVICE_ERROR;
        } else {
          gUserInput->InputValue.Buffer = ReturnValue;
          gUserInput->InputValue.BufferLen = Question->CurrentValue.BufferLen;
          Status = EFI_SUCCESS;
        }
      } else {
        ASSERT (CurrentOption != NULL);
        gUserInput->InputValue.Type = CurrentOption->OptionOpCode->Type;
        if (IsValuesEqual (&Question->CurrentValue.Value, &CurrentOption->OptionOpCode->Value, gUserInput->InputValue.Type)) {
          return EFI_DEVICE_ERROR;
        } else {
          SetValuesByType (&gUserInput->InputValue.Value, &CurrentOption->OptionOpCode->Value, gUserInput->InputValue.Type);
          Status = EFI_SUCCESS;
        }
      }

      gST->ConOut->SetAttribute (gST->ConOut, SavedAttribute);

      return EFI_SUCCESS;
      
    default:
      break;
    }
  } while (TRUE);

}
/**
  Function to populate Argc and Argv.

  This function parses the CommandLine and divides it into standard C style Argc/Argv
  parameters for inclusion in EFI_SHELL_PARAMETERS_PROTOCOL.  this supports space
  delimited and quote surrounded parameter definition.

  @param[in] CommandLine         String of command line to parse
  @param[in, out] Argv           pointer to array of strings; one for each parameter
  @param[in, out] Argc           pointer to number of strings in Argv array

  @return EFI_SUCCESS           the operation was sucessful
  @return EFI_OUT_OF_RESOURCES  a memory allocation failed.
**/
EFI_STATUS
EFIAPI
ParseCommandLineToArgs(
  IN CONST CHAR16 *CommandLine,
  IN OUT CHAR16 ***Argv,
  IN OUT UINTN *Argc
  )
{
  UINTN       Count;
  CHAR16      *TempParameter;
  CHAR16      *Walker;
  CHAR16      *NewParam;
  UINTN       Size;

  ASSERT(Argc != NULL);
  ASSERT(Argv != NULL);

  if (CommandLine == NULL || StrLen(CommandLine)==0) {
    (*Argc) = 0;
    (*Argv) = NULL;
    return (EFI_SUCCESS);
  }

  Size = StrSize(CommandLine);
  TempParameter = AllocateZeroPool(Size);
  if (TempParameter == NULL) {
    return (EFI_OUT_OF_RESOURCES);
  }

  for ( Count = 0
      , Walker = (CHAR16*)CommandLine
      ; Walker != NULL && *Walker != CHAR_NULL
      ; GetNextParameter(&Walker, &TempParameter)
      , Count++
     );

/*  Count = 0;
  Walker = (CHAR16*)CommandLine;
  while(Walker != NULL) {
    GetNextParameter(&Walker, &TempParameter);
    Count++;
  }
*/
  //
  // lets allocate the pointer array
  //
  (*Argv) = AllocateZeroPool((Count)*sizeof(CHAR16*));
  if (*Argv == NULL) {
    SHELL_FREE_NON_NULL(TempParameter);
    return (EFI_OUT_OF_RESOURCES);
  }

  *Argc = 0;
  Walker = (CHAR16*)CommandLine;
  while(Walker != NULL && *Walker != CHAR_NULL) {
    SetMem16(TempParameter, Size, CHAR_NULL);
    GetNextParameter(&Walker, &TempParameter);
    NewParam = AllocateZeroPool(StrSize(TempParameter));
    ASSERT(NewParam != NULL);
    StrCpy(NewParam, TempParameter);
    ((CHAR16**)(*Argv))[(*Argc)] = NewParam;
    (*Argc)++;
  }
  ASSERT(Count >= (*Argc));
  SHELL_FREE_NON_NULL(TempParameter);
  return (EFI_SUCCESS);
}
示例#13
0
文件: SemihostFs.c 项目: Cutty/edk2
EFI_STATUS
FileOpen (
  IN  EFI_FILE    *File,
  OUT EFI_FILE    **NewHandle,
  IN  CHAR16      *FileName,
  IN  UINT64      OpenMode,
  IN  UINT64      Attributes
  )
{
  SEMIHOST_FCB  *FileFcb = NULL;
  EFI_STATUS    Status   = EFI_SUCCESS;
  UINTN         SemihostHandle;
  CHAR8         *AsciiFileName;
  UINT32        SemihostMode;
  BOOLEAN       IsRoot;

  if ((FileName == NULL) || (NewHandle == NULL)) {
    return EFI_INVALID_PARAMETER;
  }

  // Semihost interface requires ASCII filenames
  AsciiFileName = AllocatePool ((StrLen (FileName) + 1) * sizeof (CHAR8));
  if (AsciiFileName == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  UnicodeStrToAsciiStr (FileName, AsciiFileName);

  if ((AsciiStrCmp (AsciiFileName, "\\") == 0) ||
      (AsciiStrCmp (AsciiFileName, "/")  == 0) ||
      (AsciiStrCmp (AsciiFileName, "")   == 0) ||
      (AsciiStrCmp (AsciiFileName, ".")  == 0)) {
    // Opening '/', '\', '.', or the NULL pathname is trying to open the root directory
    IsRoot = TRUE;

    // Root directory node doesn't have a name.
    FreePool (AsciiFileName);
    AsciiFileName = NULL;
  } else {
    // Translate EFI_FILE_MODE into Semihosting mode
    if (OpenMode & EFI_FILE_MODE_WRITE) {
      SemihostMode = SEMIHOST_FILE_MODE_WRITE | SEMIHOST_FILE_MODE_BINARY;
    } else if (OpenMode & EFI_FILE_MODE_READ) {
      SemihostMode = SEMIHOST_FILE_MODE_READ  | SEMIHOST_FILE_MODE_BINARY;
    } else {
      return EFI_UNSUPPORTED;
    }

    // Add the creation flag if necessary
    if (OpenMode & EFI_FILE_MODE_CREATE) {
      SemihostMode |= SEMIHOST_FILE_MODE_CREATE;
    }

    // Call the semihosting interface to open the file.
    Status = SemihostFileOpen (AsciiFileName, SemihostMode, &SemihostHandle);
    if (EFI_ERROR(Status)) {
      return Status;
    }
    
    IsRoot = FALSE;
  }

  // Allocate a control block and fill it
  FileFcb = AllocateFCB ();
  if (FileFcb == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  FileFcb->FileName       = AsciiFileName;
  FileFcb->SemihostHandle = SemihostHandle;
  FileFcb->Position       = 0;
  FileFcb->IsRoot         = IsRoot;

  InsertTailList (&gFileList, &FileFcb->Link);

  *NewHandle = &FileFcb->File;

  return Status;
}
示例#14
0
文件: SetVar.c 项目: jief666/clover
/**
  Function to parse the Data by the type of Data, and save in the Buffer.

  @param[in]      Data                A pointer to a buffer to be parsed.
  @param[out]     Buffer              A pointer to a buffer to hold the return data.
  @param[in,out]  BufferSize          On input, indicates the size of Buffer in bytes.
                                      On output,indicates the size of data return in Buffer.
                                      Or the size in bytes of the buffer needed to obtain.

  @retval   EFI_INVALID_PARAMETER     The Buffer or BufferSize is NULL.
  @retval   EFI_BUFFER_TOO_SMALL      The Buffer is too small to hold the data.
  @retval   EFI_OUT_OF_RESOURCES      A memory allcation failed.
  @retval   EFI_SUCCESS               The Data parsed successful and save in the Buffer.
**/
EFI_STATUS
ParseParameterData (
  IN CONST CHAR16   *Data,
  OUT VOID          *Buffer,
  IN OUT UINTN      *BufferSize
  )
{
  UINT64                    HexNumber;
  UINTN                     HexNumberLen;
  UINTN                     Size;
  CHAR8                     *AsciiBuffer;
  DATA_TYPE                 DataType;
  EFI_DEVICE_PATH_PROTOCOL  *DevPath;
  EFI_STATUS                Status;

  HexNumber                 = 0;
  HexNumberLen              = 0;
  Size                      = 0;
  AsciiBuffer               = NULL;
  DevPath                   = NULL;
  Status                    = EFI_SUCCESS;

  if (Data == NULL || BufferSize == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  DataType = TestDataType (Data);
  if (DataType == DataTypeHexNumber) {
    //
    // hex number
    //
    StrHexToUint64S (Data + 2, NULL, &HexNumber);
    HexNumberLen = StrLen (Data + 2);
    if (HexNumberLen >= 1 && HexNumberLen <= 2) {
      Size = 1;
    } else if (HexNumberLen >= 3 && HexNumberLen <= 4) {
      Size = 2;
    } else if (HexNumberLen >= 5 && HexNumberLen <= 8) {
      Size = 4;
    } else if (HexNumberLen >= 9 && HexNumberLen <= 16) {
      Size = 8;
    }
    if (Buffer != NULL && *BufferSize >= Size) {
      CopyMem(Buffer, (VOID *)&HexNumber, Size);
    } else {
      Status = EFI_BUFFER_TOO_SMALL;
    }
    *BufferSize = Size;
  } else if (DataType == DataTypeHexArray) {
    //
    // hex array
    //
    if (*Data == L'H') {
      Data = Data + 1;
    }

    Size = StrLen (Data) / 2;
    if (Buffer != NULL && *BufferSize >= Size) {
      StrHexToBytes(Data, StrLen  (Data), (UINT8 *)Buffer, Size);
    } else {
      Status = EFI_BUFFER_TOO_SMALL;
    }
    *BufferSize = Size;
  } else if (DataType == DataTypeAscii) {
    //
    // ascii text
    //
    if (*Data == L'S') {
      Data = Data + 1;
    }
    AsciiBuffer = AllocateZeroPool (StrSize (Data) / 2);
    if (AsciiBuffer == NULL) {
      Status = EFI_OUT_OF_RESOURCES;
    } else {
      AsciiSPrint (AsciiBuffer, StrSize (Data) / 2, "%s", (CHAR8 *)Data);

      Size = StrSize (Data) / 2 - 1;
      if (Buffer != NULL && *BufferSize >= Size) {
        CopyMem (Buffer, AsciiBuffer, Size);
      } else {
        Status = EFI_BUFFER_TOO_SMALL;
      }
      *BufferSize = Size;
    }
    SHELL_FREE_NON_NULL (AsciiBuffer);
  } else if (DataType == DataTypeUnicode) {
    //
    // unicode text
    //
    if (*Data == L'L') {
      Data = Data + 1;
    }
    Size = StrSize (Data) - sizeof (CHAR16);
    if (Buffer != NULL && *BufferSize >= Size) {
      CopyMem (Buffer, Data, Size);
    } else {
      Status = EFI_BUFFER_TOO_SMALL;
    }
    *BufferSize = Size;
  } else if (DataType == DataTypeDevicePath) {
    if (*Data == L'P') {
      Data = Data + 1;
    } else if (StrnCmp (Data, L"--", 2) == 0) {
      Data = Data + 2;
    }
    DevPath = ConvertTextToDevicePath (Data);
    if (DevPath == NULL) {
      ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SETVAR_ERROR_DPFT), gShellDebug1HiiHandle, L"setvar");
      Status = EFI_INVALID_PARAMETER;
    } else {
      Size = GetDevicePathSize (DevPath);
      if (Buffer != NULL && *BufferSize >= Size) {
        CopyMem (Buffer, DevPath, Size);
      } else {
        Status = EFI_BUFFER_TOO_SMALL;
      }
      *BufferSize = Size;
    }
    SHELL_FREE_NON_NULL (DevPath);
  } else {
    Status = EFI_INVALID_PARAMETER;
  }

  return Status;
}
示例#15
0
EFI_STATUS
add_boot_option(EFI_DEVICE_PATH *hddp, EFI_DEVICE_PATH *fulldp,
		CHAR16 *filename, CHAR16 *label, CHAR16 *arguments)
{
	static int i = 0;
	CHAR16 varname[] = L"Boot0000";
	CHAR16 hexmap[] = L"0123456789ABCDEF";
	EFI_GUID global = EFI_GLOBAL_VARIABLE;
	EFI_STATUS rc;

	for(; i <= 0xffff; i++) {
		varname[4] = hexmap[(i & 0xf000) >> 12];
		varname[5] = hexmap[(i & 0x0f00) >> 8];
		varname[6] = hexmap[(i & 0x00f0) >> 4];
		varname[7] = hexmap[(i & 0x000f) >> 0];

		void *var = LibGetVariable(varname, &global);
		if (!var) {
			int size = sizeof(UINT32) + sizeof (UINT16) +
				StrLen(label)*2 + 2 + DevicePathSize(hddp) +
				StrLen(arguments) * 2;

			CHAR8 *data = AllocateZeroPool(size);
			CHAR8 *cursor = data;
			*(UINT32 *)cursor = LOAD_OPTION_ACTIVE;
			cursor += sizeof (UINT32);
			*(UINT16 *)cursor = DevicePathSize(hddp);
			cursor += sizeof (UINT16);
			StrCpy((CHAR16 *)cursor, label);
			cursor += StrLen(label)*2 + 2;
			CopyMem(cursor, hddp, DevicePathSize(hddp));
			cursor += DevicePathSize(hddp);
			StrCpy((CHAR16 *)cursor, arguments);

			Print(L"Creating boot entry \"%s\" with label \"%s\" "
					L"for file \"%s\"\n",
				varname, label, filename);

			if (!first_new_option) {
				first_new_option = DuplicateDevicePath(fulldp);
				first_new_option_args = arguments;
				first_new_option_size = StrLen(arguments) * sizeof (CHAR16);
			}

			rc = uefi_call_wrapper(RT->SetVariable, 5, varname,
				&global, EFI_VARIABLE_NON_VOLATILE |
					 EFI_VARIABLE_BOOTSERVICE_ACCESS |
					 EFI_VARIABLE_RUNTIME_ACCESS,
				size, data);

			FreePool(data);

			if (EFI_ERROR(rc)) {
				Print(L"Could not create variable: %d\n", rc);
				return rc;
			}

			CHAR16 *newbootorder = AllocateZeroPool(sizeof (CHAR16)
							* (nbootorder + 1));
			if (!newbootorder)
				return EFI_OUT_OF_RESOURCES;

			int j = 0;
			if (nbootorder) {
				for (j = 0; j < nbootorder; j++)
					newbootorder[j] = bootorder[j];
				FreePool(bootorder);
			}
			newbootorder[j] = i & 0xffff;
			bootorder = newbootorder;
			nbootorder += 1;
#ifdef DEBUG_FALLBACK
			Print(L"nbootorder: %d\nBootOrder: ", nbootorder);
			for (j = 0 ; j < nbootorder ; j++)
				Print(L"%04x ", bootorder[j]);
			Print(L"\n");
#endif

			return EFI_SUCCESS;
		}
	}
	return EFI_OUT_OF_RESOURCES;
}
示例#16
0
static void PrvImgListView(WND wnd)
{
	FntID PrevFntID = 1;

	rint32 i;
	rint32 width=0;
	rint32 j=0;
	
	unsigned short tmp1,tmp2;
	GdiLockScreen(wnd);
	GdiClrScreen(wnd, COLOR_WHITE);

	for(i=0; i<MAX_LST_NUMBER; i++)
	{
		if(fileList[i][0]  != 0)
		{
			if(fileListIdentifier[i] & 0x10 /*==1*/ )
				GdiTextOut(wnd, "D",StrLen("D"),(ruint16)(LIST_TEXT_X),(ruint16)(LIST_TEXT_Y+(LIST_TEXT_SPACE*i)));
			else
			{

				GdiTextOut(wnd, "F",StrLen("F"),(ruint16)(LIST_TEXT_X),(ruint16)(LIST_TEXT_Y+(LIST_TEXT_SPACE*i)));
			}
		}
				
		width=0;
		j=0;
		while(fileList[i][j] != 0)
		{
			if(fileList[i][j]>0x80) // Hangul
			{	
				PrevFntID = FntGetFont(&FntGlobalContext);
				FntSetFont(&FntGlobalContext, FntIDUnicode12Han/*FntIDUnicode16*/);
				tmp1 = fileList[i][j];
				tmp1 = tmp1<<8;
				j++;
				tmp1= tmp1 | fileList[i][j];
				HanCodeConvert(tmp1, (ruint32 *)&tmp2,EUC,IW);
				tmp2-=0xac00;
			}
			else
			{
				PrevFntID = FntGetFont(&FntGlobalContext);
				FntSetFont(&FntGlobalContext, FntIDUnicode12BL/*FntIDAlpha*/);
				tmp2 = fileList[i][j];
			}
			width = width + GdiTextOutW(wnd, (ruint16)(LIST_TEXT_X+15 + width),(ruint16)(LIST_TEXT_Y+(LIST_TEXT_SPACE*i)), &tmp2, 1);//한 글자 식 한다.
			j++;
			FntSetFont(&FntGlobalContext, PrevFntID);

					
			if(width >= FILE_NAME_WIDTH_MAX)
			{
				 GdiTextOut(wnd, "~",StrLen("~"),(ruint16)(LIST_TEXT_X+15 + width),(ruint16)(LIST_TEXT_Y+(LIST_TEXT_SPACE*i)));
				 break;
			}
		}
		if(imgfocusedList == i)
		{
			GdiDrawLine(wnd,(rint32)(LIST_TEXT_X +15), (rint32)(LIST_TEXT_FOCUS_Y+(imgfocusedList*LIST_TEXT_FOCUS_LINE_SPACE)),
				(rint32)(LIST_TEXT_X +15 + width) , (rint32)(LIST_TEXT_FOCUS_Y+(imgfocusedList*LIST_TEXT_FOCUS_LINE_SPACE)));
		}
	}
	// Drawing ScrollBar
	{
		rint32 tmp;
		rect txvrect1; 
		rect txvrect2; 
		if(imgtotalFileNum%MAX_LST_NUMBER)
		{
			tmp = (imgtotalFileNum/MAX_LST_NUMBER) + 1;
		}
		else
		{
			tmp = imgtotalFileNum/MAX_LST_NUMBER;
		}
		txvrect1.bottom=SCROLL_BAR_RECT_HEIGHT;
		txvrect1.left=SCROLL_BAR_RECT_WIDTH;
		txvrect1.right=SCROLL_BAR_RECT_X;
		txvrect1.top=SCROLL_BAR_RECT_Y;

		GdiRectangle(wnd,&txvrect1);

		GdiSetFgColor(wnd,COLOR_RED) ; 

		txvrect2.top=txvrect1.top + (imglistCount/MAX_LST_NUMBER)*((txvrect1.bottom - txvrect1.top)/tmp);
		txvrect2.bottom=txvrect2.top + (txvrect1.bottom-txvrect1.top)/tmp;
		txvrect2.left=txvrect1.left-2;
		txvrect2.right=txvrect1.right+2;
			
			
		if(imgtotalFileNum == (imglistCount+1))
		{
			txvrect2.bottom = txvrect1.bottom;
			GdiRectangle(wnd,&txvrect2);
		}
		else
		{
			GdiRectangle(wnd,&txvrect2);
		}
	}
	GdiSetFgColor(wnd,COLOR_BLACK) ;
	// Drawing ScrollBar...

	GdiUnlockScreen(wnd);

}
示例#17
0
EFI_STATUS
find_boot_option(EFI_DEVICE_PATH *dp, CHAR16 *filename, CHAR16 *label,
		CHAR16 *arguments, UINT16 *optnum)
{
	int size = sizeof(UINT32) + sizeof (UINT16) +
		StrLen(label)*2 + 2 + DevicePathSize(dp) +
		StrLen(arguments) * 2 + 2;

	CHAR8 *data = AllocateZeroPool(size);
	if (!data)
		return EFI_OUT_OF_RESOURCES;
	CHAR8 *cursor = data;
	*(UINT32 *)cursor = LOAD_OPTION_ACTIVE;
	cursor += sizeof (UINT32);
	*(UINT16 *)cursor = DevicePathSize(dp);
	cursor += sizeof (UINT16);
	StrCpy((CHAR16 *)cursor, label);
	cursor += StrLen(label)*2 + 2;
	CopyMem(cursor, dp, DevicePathSize(dp));
	cursor += DevicePathSize(dp);
	StrCpy((CHAR16 *)cursor, arguments);

	int i = 0;
	CHAR16 varname[] = L"Boot0000";
	CHAR16 hexmap[] = L"0123456789ABCDEF";
	EFI_GUID global = EFI_GLOBAL_VARIABLE;
	EFI_STATUS rc;

	CHAR8 *candidate = AllocateZeroPool(size);
	if (!candidate) {
		FreePool(data);
		return EFI_OUT_OF_RESOURCES;
	}

	for(i = 0; i < nbootorder && i < 0x10000; i++) {
		varname[4] = hexmap[(bootorder[i] & 0xf000) >> 12];
		varname[5] = hexmap[(bootorder[i] & 0x0f00) >> 8];
		varname[6] = hexmap[(bootorder[i] & 0x00f0) >> 4];
		varname[7] = hexmap[(bootorder[i] & 0x000f) >> 0];

		UINTN candidate_size = size;
		rc = uefi_call_wrapper(RT->GetVariable, 5, varname, &global,
					NULL, &candidate_size, candidate);
		if (EFI_ERROR(rc))
			continue;

		if (candidate_size != size)
			continue;

		if (CompareMem(candidate, data, size))
			continue;

		/* at this point, we have duplicate data. */
		*optnum = i;
		FreePool(candidate);
		FreePool(data);
		return EFI_SUCCESS;
	}
	FreePool(candidate);
	FreePool(data);
	return EFI_NOT_FOUND;
}
示例#18
0
void VaultTextNoteNode::SetVisitInfo (const plAgeInfoStruct & info) {
    
    ARRAY(wchar_t) buf;
    
    for (unsigned i = 0; i < kNumAgeInfoFields; ++i) {
        switch (i) {
            case kAgeFilename: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeFilename(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeInstName: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeInstanceName(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeUserName: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeUserDefinedName(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeDesc: {
                wchar_t src[128];
                StrToUnicode(src, info.GetAgeDescription(), arrsize(src));
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeInstGuid: {
                plUUID guid = *info.GetAgeInstanceGuid();
                wchar_t src[64];
                wcsncpy(src, guid.AsString().ToWchar(), 64);
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeLanguage: {
                wchar_t src[32];
                StrPrintf(src, arrsize(src), L"%u", info.GetAgeLanguage());
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;
            
            case kAgeSequence: {
                wchar_t src[32];
                StrPrintf(src, arrsize(src), L"%u", info.GetAgeSequenceNumber());
                unsigned len = StrLen(src);
                wchar_t * dst = buf.New(len);
                memcpy(dst, src, len * sizeof(src[0]));
            }
            break;

            DEFAULT_FATAL(i);
        }
        
        wchar_t * sep = buf.New(1);
        *sep = L'|';            
    }
    
    wchar_t * term = buf.New(1);
    *term = 0;
    
    SetNoteText(buf.Ptr());
}
示例#19
0
//yes, '***', three levels of pointer! It's an array of pointers that
//has to be passed into the function as a pointer
int LoadDir(char *Path, HTTPSession *Session, int Flags, TPathItem ***fl_ptr)
{
char *Tempstr=NULL, *URL=NULL, *Dir=NULL;
glob_t Glob;
struct stat Stat;
TPathItem *File, **Files;
ListNode *Curr;
int i, val, fcount=0;

Tempstr=MCopyStr(Tempstr,Path,"/*",NULL);
glob(Tempstr,0,0,&Glob);


Dir=CopyStr(Dir,Session->URL);
Dir=SlashTerminateDirectoryPath(Dir);
//Allocate As Many Items As glob found, plus VPaths, plus one for '..'

val=Glob.gl_pathc+1;
if (Settings.DirListFlags & DIR_SHOW_VPATHS) val+=ListSize(Settings.VPaths);

*fl_ptr=(TPathItem **) calloc(val , sizeof(TPathItem *));
Files=*fl_ptr;

//if we are at '/' then don't offer a parent directory
if (StrLen(Path) > 1)
{
Tempstr=ParentDirectory(Tempstr, Session->URL);
URL=FormatURL(URL,Session,Tempstr);
Files[0]=PathItemCreate(PATHTYPE_DIR,Tempstr,"..");
fcount++;
}


//LoadVPaths if in top-level dir
if (Settings.DirListFlags & DIR_SHOW_VPATHS) 
{
	if (strcmp(Path,Session->StartDir)==0)
	{
		Curr=ListGetNext(Settings.VPaths);
		while (Curr)
		{	
			File=(TPathItem *) Curr->Item;
			if ((File->Type==PATHTYPE_EXTFILE) && (strcmp(File->URL,"/") !=0)) 
			{
				Files[fcount]=PathItemCreate(PATHTYPE_DIR,File->URL,File->URL);
				fcount++;
			}
		Curr=ListGetNext(Curr);
		}
	}
}

for (i=0; i < Glob.gl_pathc; i++)
{
  Tempstr=MCopyStr(Tempstr,Dir,GetBasename(Glob.gl_pathv[i]),NULL);
	URL=FormatURL(URL,Session,Tempstr);

  if (stat(Glob.gl_pathv[i],&Stat) > -1)
	{
  if (S_ISDIR(Stat.st_mode)) File=PathItemCreate(PATHTYPE_DIR,URL,Glob.gl_pathv[i]);
  else File=PathItemCreate(PATHTYPE_FILE,URL,Glob.gl_pathv[i]);
  File->Mtime=Stat.st_mtime;
  File->Size=Stat.st_size;
	}
  Files[fcount]=File;
	fcount++;
}


switch (Flags & SORT_TYPE_MASK)
{
case SORT_SIZE: qsort(Files,fcount,sizeof(TPathItem *),FilesSortSizeCmp); break;
case SORT_RSIZE: qsort(Files,fcount,sizeof(TPathItem *),FilesRSortSizeCmp); break;
case SORT_TIME: qsort(Files,fcount,sizeof(TPathItem *),FilesSortTimeCmp); break;
case SORT_RTIME: qsort(Files,fcount,sizeof(TPathItem *),FilesRSortTimeCmp); break;
case SORT_NAME: qsort(Files,fcount,sizeof(TPathItem *),FilesSortNameCmp); break;
case SORT_RNAME: qsort(Files,fcount,sizeof(TPathItem *),FilesRSortNameCmp); break;
}


globfree(&Glob);
DestroyString(Dir);
DestroyString(URL);
DestroyString(Tempstr);

//i will equal 'Glob.pathc' at end of loop, we also added '..' so return i+1 
return(fcount);
}
示例#20
0
bool VaultTextNoteNode::GetVisitInfo (plAgeInfoStruct * info) {

    wchar_t * mem;
    const wchar_t * str = mem = wcsdup(GetNoteText());
    
    for (unsigned i = 0; i < kNumAgeInfoFields; ++i) {
        
        wchar_t token[1024];
        switch (i) {
            case kAgeFilename: {
                StrTokenize(&str, token, arrsize(token), L"|", 1);
                if (StrLen(token) > 0) {
                    char ansi[1024];
                    StrToAnsi(ansi, token, arrsize(ansi));
                    info->SetAgeFilename(ansi);
                }
            }
            break;
            
            case kAgeInstName: {
                StrTokenize(&str, token, arrsize(token), L"|", 1);
                if (StrLen(token) > 0) {
                    char ansi[1024];
                    StrToAnsi(ansi, token, arrsize(ansi));
                    info->SetAgeInstanceName(ansi);
                }
            }
            break;
            
            case kAgeUserName: {
                StrTokenize(&str, token, arrsize(token), L"|", 1);
                if (StrLen(token) > 0) {
                    char ansi[1024];
                    StrToAnsi(ansi, token, arrsize(ansi));
                    info->SetAgeUserDefinedName(ansi);
                }
            }
            break;
            
            case kAgeDesc: {
                StrTokenize(&str, token, arrsize(token), L"|", 1);
                if (StrLen(token) > 0) {
                    char ansi[1024];
                    StrToAnsi(ansi, token, arrsize(ansi));
                    info->SetAgeDescription(ansi);
                }
            }
            break;
            
            case kAgeInstGuid: {
                StrTokenize(&str, token, arrsize(token), L"|", 1);
                if (StrLen(token) > 0) {
                    plUUID uuid(plString::FromWchar(token));
                    info->SetAgeInstanceGuid(&uuid);
                }
            }
            break;
            
            case kAgeLanguage: {
                StrTokenize(&str, token, arrsize(token), L"|", 1);
                if (StrLen(token) > 0) {
                    info->SetAgeLanguage(StrToUnsigned(token, nil, 10));
                }
            }
            break;
            
            case kAgeSequence: {
                StrTokenize(&str, token, arrsize(token), L"|", 1);
                if (StrLen(token) > 0) {
                    info->SetAgeSequenceNumber(StrToUnsigned(token, nil, 10));
                }
            }
            break;

            DEFAULT_FATAL(i);
        }
    }

    free(mem);
    return true;
}
示例#21
0
int HTTPServerSendPackedDir(STREAM *S, HTTPSession *Session, const char *Dir)
{
char *Tempstr=NULL, *DirName=NULL, *FileName=NULL, *ptr;
char *Extn=NULL, *PackType=NULL, *Name=NULL, *Value=NULL;
char *PackList=NULL;
TFileMagic *FM;
HTTPSession *Response;
STREAM *Pipe;

	chdir(Dir);
	//unset session reuse, because we will close session to indicate end of package
	Session->Flags &= ~SESSION_REUSE;

	//do this so we can strcmp it
	PackList=CopyStr(PackList,"");

	Response=HTTPSessionResponse(Session);
	Response->ResponseCode=CopyStr(Response->ResponseCode,"200 OK");

	ptr=GetNameValuePair(Session->Arguments, "&","=",&Name,&Value);
	while (ptr)
	{
		if ( StrLen(Name) )
		{
		if	(strcasecmp(Name,"packtype")==0)
		{
			PackType=CopyStr(PackType,Value);
			Extn=MCopyStr(Extn, ".", Value, NULL);
			FM=GetFileMagicForFile(Extn, NULL);
			Response->ContentType=CopyStr(Response->ContentType, FM->ContentType);
		}
		else if (strcasecmp(Name,"selected")==0) 
		{
			if (strcmp(PackList," *") !=0) PackList=MCatStr(PackList, " ", Value, NULL);
		}
		}
		
	ptr=GetNameValuePair(ptr, "&","=",&Name,&Value);
	}

	if (StrLen(PackList)==0) PackList=CopyStr(PackList, " *");
	DirName=CopyStr(DirName,Dir);
	StripDirectorySlash(DirName);
	ptr=GetBasename(DirName);

	if (! StrLen(ptr)) ptr="rootdir";

	FileName=MCopyStr(FileName,Session->Host,"-",Session->UserName,"-",ptr,Extn,NULL);
	strrep(FileName,' ','_');

	Tempstr=MCopyStr(Tempstr,"attachment; filename=",FileName,NULL);
	SetVar(Response->Headers,"Content-disposition",Tempstr);

	ptr=GetNameValuePair(Settings.PackFormats, ",",":", &Name, &Value);
	while (ptr)
	{
	if (strcasecmp(Name, PackType)==0)
	{
		if (strcasecmp(Value,"internal")==0)
		{
			if (strcasecmp(Name,"tar")==0) 
			{
				HTTPServerSendHeaders(S, Response, 0); 
				TarFiles(S, PackList);
			}
		}
		else
		{
		HTTPServerSendHeaders(S, Response, 0); 
		Tempstr=MCopyStr(Tempstr,Value,PackList,NULL);
		Pipe=STREAMSpawnCommand(Tempstr, COMMS_BY_PIPE);
		STREAMSendFile(Pipe, S, 0, SENDFILE_KERNEL| SENDFILE_LOOP);
		STREAMClose(Pipe);
		}
	}
	ptr=GetNameValuePair(ptr, ",",":", &Name, &Value);
	}

	STREAMFlush(S);

DestroyString(FileName);
DestroyString(Tempstr);
DestroyString(DirName);
DestroyString(PackList);
DestroyString(PackType);
DestroyString(Name);
DestroyString(Value);
DestroyString(Extn);


//This true means 'please close the connection' as our tarballs/zips are transferred using
//connection: close to indicate end of transfer
return(STREAM_CLOSED);
}
示例#22
0
// Assign (const char *)
//------------------------------------------------------------------------------
void AString::Assign( const char * string )
{
	Assign( string, string + StrLen( string ) );
}
示例#23
0
/**
  Refresh the text mode page.

  @param CallbackData    The BMM context data.

**/
VOID
UpdateConModePage (
  IN BMM_CALLBACK_DATA                *CallbackData
  )
{
  UINTN                         Mode;
  UINTN                         Index;
  UINTN                         Col;
  UINTN                         Row;
  CHAR16                        ModeString[50];
  CHAR16                        *PStr;
  UINTN                         MaxMode;
  UINTN                         ValidMode;
  EFI_STRING_ID                 *ModeToken;
  EFI_STATUS                    Status;
  VOID                          *OptionsOpCodeHandle;
  EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL  *ConOut;

  ConOut    = gST->ConOut;
  Index     = 0;
  ValidMode = 0;
  MaxMode   = (UINTN) (ConOut->Mode->MaxMode);

  CallbackData->BmmAskSaveOrNot = TRUE;

  UpdatePageStart (CallbackData);

  //
  // Check valid mode
  //
  for (Mode = 0; Mode < MaxMode; Mode++) {
    Status = ConOut->QueryMode (ConOut, Mode, &Col, &Row);
    if (EFI_ERROR (Status)) {
      continue;
    }
    ValidMode++;
  }

  if (ValidMode == 0) {
    return;
  }

  OptionsOpCodeHandle = HiiAllocateOpCodeHandle ();
  ASSERT (OptionsOpCodeHandle != NULL);

  ModeToken           = AllocateZeroPool (sizeof (EFI_STRING_ID) * ValidMode);
  ASSERT(ModeToken != NULL);

  //
  // Determin which mode should be the first entry in menu
  //
  GetConsoleOutMode (CallbackData);

  //
  // Build text mode options
  //
  for (Mode = 0; Mode < MaxMode; Mode++) {
    Status = ConOut->QueryMode (ConOut, Mode, &Col, &Row);
    if (EFI_ERROR (Status)) {
      continue;
    }
    
    //
    // Build mode string Column x Row
    //
    UnicodeValueToString (ModeString, 0, Col, 0);
    PStr = &ModeString[0];
    StrnCat (PStr, L" x ", StrLen(L" x ") + 1);
    PStr = PStr + StrLen (PStr);
    UnicodeValueToString (PStr , 0, Row, 0);

    ModeToken[Index] = HiiSetString (CallbackData->BmmHiiHandle, 0, ModeString, NULL);

    if (Mode == CallbackData->BmmFakeNvData.ConsoleOutMode) {
      HiiCreateOneOfOptionOpCode (
        OptionsOpCodeHandle,
        ModeToken[Index],
        EFI_IFR_OPTION_DEFAULT,
        EFI_IFR_TYPE_NUM_SIZE_16,
        (UINT16) Mode
        );
    } else {
      HiiCreateOneOfOptionOpCode (
        OptionsOpCodeHandle,
        ModeToken[Index],
        0,
        EFI_IFR_TYPE_NUM_SIZE_16,
        (UINT16) Mode
        );
    }
    Index++;
  }

  HiiCreateOneOfOpCode (
    mStartOpCodeHandle,
    (EFI_QUESTION_ID) CON_MODE_QUESTION_ID,
    VARSTORE_ID_BOOT_MAINT,
    CON_MODE_VAR_OFFSET,
    STRING_TOKEN (STR_CON_MODE_SETUP),
    STRING_TOKEN (STR_CON_MODE_SETUP),
    EFI_IFR_FLAG_RESET_REQUIRED,
    EFI_IFR_NUMERIC_SIZE_2,
    OptionsOpCodeHandle,
    NULL
    );

  HiiFreeOpCodeHandle (OptionsOpCodeHandle);
  FreePool (ModeToken);

  UpdatePageEnd (CallbackData);
}
示例#24
0
//curl -X POST -d "client_id=CLIENT_ID_HERE&client_secret=CLIENT_SECRET_HERE&grant_type=password&username=YOUR_EMAIL&password=YOUR_PASSWORD" -Ss https://mastodon.social/oauth/token
int OAuthGrant(OAUTH *Ctx, const char *URL, const char *PostArgs)
{
    STREAM *S;
    char *Tempstr=NULL;
    int len, result=FALSE;

    Tempstr=MCopyStr(Tempstr,URL,"?",PostArgs,NULL);
    S=HTTPMethod("POST",URL,"application/x-www-form-urlencoded; charset=UTF-8",PostArgs,StrLen(PostArgs));
    if (S)
    {
        sleep(1);
        Tempstr=STREAMReadDocument(Tempstr, S);

        result=OAuthParseReply(Ctx, STREAMGetValue(S, "HTTP:Content-Type"), Tempstr);
        STREAMClose(S);
    }

    DestroyString(Tempstr);

    return(result);
}
示例#25
0
文件: cgi.c 项目: ColumPaget/Hashrat
void CGIDisplayPage()
{
char *HashType=NULL, *Encoding=NULL, *LineEnding=NULL, *SegmentChar=NULL,  *Text=NULL, *Hash=NULL, *Token=NULL, *OptionsFile=NULL;
const char *ptr;
HashratCtx *Ctx;
ListNode *Items;
int Flags, i, OutputLength=0, SegmentLength=0;

SegmentChar=CopyStr(SegmentChar, " ");
Items=ListCreate();

//We don't need to read anything from disk, so in case we're running
//as root, or something like that, let's try to chroot, so no weird attacks are possible

//shouldn't work, because we shouldn't be running as root
chdir("/var/empty");
chroot(".");

//Send HTTP Headers
printf("Content-type: text/html\r\n");
printf("Connection: close\r\n");
printf("Cache-control: private, max-age=0, no-cache\r\n");
printf("\r\n");


Flags=CGIParseArgs(getenv("QUERY_STRING"),"&","=",&HashType, &Encoding, &LineEnding, &Text, &OutputLength, &SegmentLength, &SegmentChar, &OptionsFile);

printf("<body><html><form>\r\n");

printf("<h2 align=center>Hashrat: Online hash calculator</h2>\r\n");
printf("<div align=center>Version: %s, Licence: GPLv3, Author: Colum Paget, BugReports: colums projects at gmail dot com</div><p/>\r\n",VERSION);

if (Flags & CGI_DOHASH)
{
	Ctx=(HashratCtx *) calloc(1,sizeof(HashratCtx));
	Ctx->HashType=CopyStr(Ctx->HashType,HashType);
	Ctx->Encoding |=ENCODE_HEX;

	i=MatchTokenFromList(Encoding, EncodingNames, 0);
	if (i > -1) Ctx->Encoding=Encodings[i];
	
	if (StrLen(LineEnding))
	{
	if (strcmp(LineEnding, "crlf")==0) Text=CatStr(Text,"\r\n");
	if (strcmp(LineEnding, "lf")==0) Text=CatStr(Text,"\n");
	if (strcmp(LineEnding, "cr")==0) Text=CatStr(Text,"\r");
	}

	ProcessData(&Hash, Ctx, Text, StrLen(Text));

	Token=ReformatHash(Token, Hash, OutputLength, SegmentLength, SegmentChar[0]);
	CGIDrawHashResult(Token);
}

printf("<table align=center bgcolor=#BBBBBB>\r\n");
printf("<tr>\r\n");
printf("<th colspan=2 bgcolor=blue><font color=white>New Hash</font></th>\r\n");

if (Flags & CGI_NOOPTIONS) 
{
	printf("<input type=hidden name=\"HashType\" value=\"%s\">\n",HashType);
	printf("<input type=hidden name=\"Encoding\" value=\"%s\">\n",Encoding);
	printf("<input type=hidden name=\"LineEnding\" value=\"%s\">\n",LineEnding);
	printf("<input type=hidden name=\"OutputLength\" value=\"%d\">\n",OutputLength);
	printf("<input type=hidden name=\"SegmentLength\" value=\"%d\">\n",SegmentLength);
	if (StrLen(SegmentChar)) printf("<input type=hidden name=\"SegmentChar\" value=\"%s\">\n",SegmentChar);
	printf("<input type=hidden name=\"NoOptions\" value=\"Y\">\n");
	//if (StrLen(OptionsFile)) printf("<input type=hidden name=\"OptionsFile\" value=\"%d\">\n",OptionsFile);
}
else CGIDisplayOptions(HashType, Encoding, LineEnding, OutputLength);

printf("<tr>\r\n");
CGIDrawTextInput(Flags);
printf("</tr>\r\n");


printf("<tr><td colspan=4><input type=submit value=\"Hash it!\"></td></tr>\r\n");
printf("</table>\r\n");


printf("</form></html></body>\r\n");

fflush(NULL);

ListDestroy(Items, Destroy);

Destroy(LineEnding);
Destroy(OptionsFile);
Destroy(SegmentChar);
Destroy(Encoding);
Destroy(HashType);
Destroy(Token);
Destroy(Hash);
Destroy(Text);
}
示例#26
0
/* Retrieve the default category/categories from the document */
UInt16 GetDefaultCategories
    (
    DocumentInfo* docInfo
    )
    /* THROWS */
{
    UInt16      categories;
    MemHandle   handle;
    Err         err;

    handle      = NULL;
    categories  = 0;

    if ( docInfo->location == RAM )
        err = OpenRAMDocument( docInfo );
    else
        err = OpenVFSDocument( docInfo );
    THROW_IF( err != errNone, err );

    GetIndexData();

    ErrTry {
        Header* categoryRecord;
        Char*   name;
        UInt16  totalSize;
        UInt16  size;
        UInt8   index;

        handle = FindRecord( CATEGORY_ID, NULL );
        if ( handle != NULL ) {
            categoryRecord  = MemHandleLock( handle );
            size            = 0;
            totalSize       = categoryRecord->size;
            name            = (Char*)( categoryRecord + 1 );
            do {
                index = GetCategoryIndex( name );
                if ( index == dmAllCategories ) {
                    index = AddCategoryToFreePosition( name );
                }
                if ( index != dmAllCategories )
                    categories |= ( 1 << index );

                size    += StrLen( name ) + 1;
                name    += StrLen( name ) + 1;
            } while ( size < totalSize );

            MemHandleUnlock( handle );
            FreeRecordHandle( &handle );
        }
        else {
            categories = 0;
        }
    }
    ErrCatch( UNUSED_PARAM( err ) ) {
        categories = 0;
    } ErrEndCatch

    if ( docInfo->location == RAM ) {
        CloseRAMDocument();
    }
    else {
        if ( handle != NULL )
            MemHandleFree( handle );
        CloseVFSDocument();
    }

    if ( categories == 0 )
        return UNFILED_CATEGORY;
    else
        return categories;
}
示例#27
0
文件: MemoryTest.c 项目: b-man/edk2
/**

  Show progress bar with title above it. It only works in Graphics mode.


  @param TitleForeground Foreground color for Title.
  @param TitleBackground Background color for Title.
  @param Title           Title above progress bar.
  @param ProgressColor   Progress bar color.
  @param Progress        Progress (0-100)
  @param PreviousValue   The previous value of the progress.

  @retval  EFI_STATUS       Success update the progress bar

**/
EFI_STATUS
PlatformBdsShowProgress (
  IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleForeground,
  IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleBackground,
  IN CHAR16                        *Title,
  IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ProgressColor,
  IN UINTN                         Progress,
  IN UINTN                         PreviousValue
  )
{
  EFI_STATUS                     Status;
  EFI_GRAPHICS_OUTPUT_PROTOCOL   *GraphicsOutput;
  EFI_UGA_DRAW_PROTOCOL          *UgaDraw;
  UINT32                         SizeOfX;
  UINT32                         SizeOfY;
  UINT32                         ColorDepth;
  UINT32                         RefreshRate;
  EFI_GRAPHICS_OUTPUT_BLT_PIXEL  Color;
  UINTN                          BlockHeight;
  UINTN                          BlockWidth;
  UINTN                          BlockNum;
  UINTN                          PosX;
  UINTN                          PosY;
  UINTN                          Index;

  if (Progress > 100) {
    return EFI_INVALID_PARAMETER;
  }

  UgaDraw = NULL;
  Status = gBS->HandleProtocol (
                  gST->ConsoleOutHandle,
                  &gEfiGraphicsOutputProtocolGuid,
                  (VOID **) &GraphicsOutput
                  );
  if (EFI_ERROR (Status) && FeaturePcdGet (PcdUgaConsumeSupport)) {
    GraphicsOutput = NULL;

    Status = gBS->HandleProtocol (
                    gST->ConsoleOutHandle,
                    &gEfiUgaDrawProtocolGuid,
                    (VOID **) &UgaDraw
                    );
  }
  if (EFI_ERROR (Status)) {
    return EFI_UNSUPPORTED;
  }

  SizeOfX = 0;
  SizeOfY = 0;
  if (GraphicsOutput != NULL) {
    SizeOfX = GraphicsOutput->Mode->Info->HorizontalResolution;
    SizeOfY = GraphicsOutput->Mode->Info->VerticalResolution;
  } else if (UgaDraw != NULL) {
    Status = UgaDraw->GetMode (
                        UgaDraw,
                        &SizeOfX,
                        &SizeOfY,
                        &ColorDepth,
                        &RefreshRate
                        );
    if (EFI_ERROR (Status)) {
      return EFI_UNSUPPORTED;
    }
  } else {
    return EFI_UNSUPPORTED;
  }

  BlockWidth  = SizeOfX / 100;
  BlockHeight = SizeOfY / 50;

  BlockNum    = Progress;

  PosX        = 0;
  PosY        = SizeOfY * 48 / 50;

  if (BlockNum == 0) {
    //
    // Clear progress area
    //
    SetMem (&Color, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), 0x0);

    if (GraphicsOutput != NULL) {
      Status = GraphicsOutput->Blt (
                          GraphicsOutput,
                          &Color,
                          EfiBltVideoFill,
                          0,
                          0,
                          0,
                          PosY - EFI_GLYPH_HEIGHT - 1,
                          SizeOfX,
                          SizeOfY - (PosY - EFI_GLYPH_HEIGHT - 1),
                          SizeOfX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)
                          );
    } else if (FeaturePcdGet (PcdUgaConsumeSupport)) {
      Status = UgaDraw->Blt (
                          UgaDraw,
                          (EFI_UGA_PIXEL *) &Color,
                          EfiUgaVideoFill,
                          0,
                          0,
                          0,
                          PosY - EFI_GLYPH_HEIGHT - 1,
                          SizeOfX,
                          SizeOfY - (PosY - EFI_GLYPH_HEIGHT - 1),
                          SizeOfX * sizeof (EFI_UGA_PIXEL)
                          );
    } else {
      return EFI_UNSUPPORTED;
    }
  }
  //
  // Show progress by drawing blocks
  //
  for (Index = PreviousValue; Index < BlockNum; Index++) {
    PosX = Index * BlockWidth;
    if (GraphicsOutput != NULL) {
      Status = GraphicsOutput->Blt (
                          GraphicsOutput,
                          &ProgressColor,
                          EfiBltVideoFill,
                          0,
                          0,
                          PosX,
                          PosY,
                          BlockWidth - 1,
                          BlockHeight,
                          (BlockWidth) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)
                          );
    } else if (FeaturePcdGet (PcdUgaConsumeSupport)) {
      Status = UgaDraw->Blt (
                          UgaDraw,
                          (EFI_UGA_PIXEL *) &ProgressColor,
                          EfiUgaVideoFill,
                          0,
                          0,
                          PosX,
                          PosY,
                          BlockWidth - 1,
                          BlockHeight,
                          (BlockWidth) * sizeof (EFI_UGA_PIXEL)
                          );
    } else {
      return EFI_UNSUPPORTED;
    }
  }

  PrintXY (
    (SizeOfX - StrLen (Title) * EFI_GLYPH_WIDTH) / 2,
    PosY - EFI_GLYPH_HEIGHT - 1,
    &TitleForeground,
    &TitleBackground,
    Title
    );

  return EFI_SUCCESS;
}
示例#28
0
// Read the virtual host option (extended)
void NiLoadVhOptionEx(VH_OPTION *o, FOLDER *root)
{
	FOLDER *host, *nat, *dhcp;
	char mac_address[MAX_SIZE];
	// Validate arguments
	if (o == NULL || root == NULL)
	{
		return;
	}

	host = CfgGetFolder(root, "VirtualHost");
	nat = CfgGetFolder(root, "VirtualRouter");
	dhcp = CfgGetFolder(root, "VirtualDhcpServer");

	Zero(o, sizeof(VH_OPTION));

	GenMacAddress(o->MacAddress);
	if (CfgGetStr(host, "VirtualHostMacAddress", mac_address, sizeof(mac_address)))
	{
		BUF *b = StrToBin(mac_address);
		if (b != NULL)
		{
			if (b->Size == 6)
			{
				Copy(o->MacAddress, b->Buf, 6);
			}
		}
		FreeBuf(b);
	}
	CfgGetIp(host, "VirtualHostIp", &o->Ip);
	CfgGetIp(host, "VirtualHostIpSubnetMask", &o->Mask);

	o->UseNat = CfgGetBool(nat, "NatEnabled");
	o->Mtu = CfgGetInt(nat, "NatMtu");
	o->NatTcpTimeout = CfgGetInt(nat, "NatTcpTimeout");
	o->NatUdpTimeout = CfgGetInt(nat, "NatUdpTimeout");

	o->UseDhcp = CfgGetBool(dhcp, "DhcpEnabled");
	CfgGetIp(dhcp, "DhcpLeaseIPStart", &o->DhcpLeaseIPStart);
	CfgGetIp(dhcp, "DhcpLeaseIPEnd", &o->DhcpLeaseIPEnd);
	CfgGetIp(dhcp, "DhcpSubnetMask", &o->DhcpSubnetMask);
	o->DhcpExpireTimeSpan = CfgGetInt(dhcp, "DhcpExpireTimeSpan");
	CfgGetIp(dhcp, "DhcpGatewayAddress", &o->DhcpGatewayAddress);
	CfgGetIp(dhcp, "DhcpDnsServerAddress", &o->DhcpDnsServerAddress);
	CfgGetIp(dhcp, "DhcpDnsServerAddress2", &o->DhcpDnsServerAddress2);
	CfgGetStr(dhcp, "DhcpDomainName", o->DhcpDomainName, sizeof(o->DhcpDomainName));

	CfgGetStr(dhcp, "DhcpPushRoutes", o->DhcpPushRoutes, sizeof(o->DhcpPushRoutes));

// Test code
//	StrCpy(o->DhcpPushRoutes, sizeof(o->DhcpPushRoutes),
//		"130.158.6.0/24/192.168.9.2 130.158.80.244/255.255.255.255/192.168.9.2");

	NormalizeClasslessRouteTableStr(o->DhcpPushRoutes, sizeof(o->DhcpPushRoutes), o->DhcpPushRoutes);
	o->ApplyDhcpPushRoutes = true;

	Trim(o->DhcpDomainName);
	if (StrLen(o->DhcpDomainName) == 0)
	{
		//GetDomainName(o->DhcpDomainName, sizeof(o->DhcpDomainName));
	}

	o->SaveLog = CfgGetBool(root, "SaveLog");
}
示例#29
0
/**
  Returns information about a file.

  @param  This            A pointer to the EFI_FILE_PROTOCOL instance that is the file
                          handle the requested information is for.
  @param  InformationType The type identifier for the information being requested.
  @param  BufferSize      On input, the size of Buffer. On output, the amount of data
                          returned in Buffer. In both cases, the size is measured in bytes.
  @param  Buffer          A pointer to the data buffer to return. The buffer's type is
                          indicated by InformationType.

  @retval EFI_SUCCESS          The information was returned.
  @retval EFI_UNSUPPORTED      The InformationType is not known.
  @retval EFI_NO_MEDIA         The device has no medium.
  @retval EFI_DEVICE_ERROR     The device reported an error.
  @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
  @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small to read the current directory entry.
                               BufferSize has been updated with the size needed to complete
                               the request.
**/
EFI_STATUS
EFIAPI
FvSimpleFileSystemGetInfo (
    IN     EFI_FILE_PROTOCOL    *This,
    IN     EFI_GUID             *InformationType,
    IN OUT UINTN                *BufferSize,
    OUT VOID                 *Buffer
)
{
    FV_FILESYSTEM_FILE           *File;
    EFI_FILE_SYSTEM_INFO         *FsInfoOut;
    EFI_FILE_SYSTEM_VOLUME_LABEL *FsVolumeLabel;
    FV_FILESYSTEM_INSTANCE       *Instance;
    UINTN                        Size;
    EFI_STATUS                   Status;

    File = FVFS_FILE_FROM_FILE_THIS (This);

    if (CompareGuid (InformationType, &gEfiFileSystemInfoGuid)) {
        //
        // Return filesystem info
        //
        Instance = File->Instance;

        Size = sizeof (EFI_FILE_SYSTEM_INFO) + StrSize (Instance->VolumeLabel) - sizeof (CHAR16);

        if (*BufferSize < Size) {
            *BufferSize = Size;
            return EFI_BUFFER_TOO_SMALL;
        }

        //
        // Cast output buffer for convenience
        //
        FsInfoOut = (EFI_FILE_SYSTEM_INFO *) Buffer;

        CopyMem (FsInfoOut, &mFsInfoTemplate, sizeof (EFI_FILE_SYSTEM_INFO));
        Status = StrnCpyS (FsInfoOut->VolumeLabel, (*BufferSize - OFFSET_OF (EFI_FILE_SYSTEM_INFO, VolumeLabel)) / sizeof (CHAR16), Instance->VolumeLabel, StrLen (Instance->VolumeLabel));
        ASSERT_EFI_ERROR (Status);
        FsInfoOut->Size = Size;
        return Status;
    } else if (CompareGuid (InformationType, &gEfiFileInfoGuid)) {
        //
        // Return file info
        //
        return FvFsGetFileInfo (File->FvFileInfo, BufferSize, (EFI_FILE_INFO *) Buffer);
    } else if (CompareGuid (InformationType, &gEfiFileSystemVolumeLabelInfoIdGuid)) {
        //
        // Return Volume Label
        //
        Instance = File->Instance;
        Size     = sizeof (EFI_FILE_SYSTEM_VOLUME_LABEL) + StrSize (Instance->VolumeLabel) - sizeof (CHAR16);;
        if (*BufferSize < Size) {
            *BufferSize = Size;
            return EFI_BUFFER_TOO_SMALL;
        }

        FsVolumeLabel = (EFI_FILE_SYSTEM_VOLUME_LABEL*) Buffer;
        Status        = StrnCpyS (FsVolumeLabel->VolumeLabel, (*BufferSize - OFFSET_OF (EFI_FILE_SYSTEM_VOLUME_LABEL, VolumeLabel)) / sizeof (CHAR16), Instance->VolumeLabel, StrLen (Instance->VolumeLabel));
        ASSERT_EFI_ERROR (Status);
        return Status;
    } else {
        return EFI_UNSUPPORTED;
    }
}
示例#30
0
/**
  Set information about a file.

  @param[in]  Fcb   A pointer to the description of the open file.
  @param[in]  Info  A pointer to the file information to write.

  @retval  EFI_SUCCESS           The information was set.
  @retval  EFI_ACCESS_DENIED     An attempt is made to change the name of a file
                                 to a file that is already present.
  @retval  EFI_ACCESS_DENIED     An attempt is being made to change the
                                 EFI_FILE_DIRECTORY Attribute.
  @retval  EFI_ACCESS_DENIED     The file is a read-only file or has been
                                 opened in read-only mode and an attempt is
                                 being made to modify a field other than
                                 Attribute.
  @retval  EFI_WRITE_PROTECTED   An attempt is being made to modify a
                                 read-only attribute.
  @retval  EFI_DEVICE_ERROR      The last issued semi-hosting operation failed.
  @retval  EFI_OUT_OF_RESOURCES  A allocation needed to process the request failed.

**/
STATIC
EFI_STATUS
SetFileInfo (
  IN  SEMIHOST_FCB   *Fcb,
  IN  EFI_FILE_INFO  *Info
  )
{
  EFI_STATUS     Status;
  RETURN_STATUS  Return;
  BOOLEAN        FileSizeIsDifferent;
  BOOLEAN        FileNameIsDifferent;
  BOOLEAN        ReadOnlyIsDifferent;
  CHAR8          *AsciiFileName;
  UINTN          FileSize;
  UINTN          Length;
  UINTN          SemihostHandle;

  //
  // A directory can not be changed to a file and a file can
  // not be changed to a directory.
  //
  if (((Info->Attribute & EFI_FILE_DIRECTORY) != 0) != Fcb->IsRoot) {
    return EFI_ACCESS_DENIED;
  }

  AsciiFileName = AllocatePool (StrLen (Info->FileName) + 1);
  if (AsciiFileName == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  UnicodeStrToAsciiStr (Info->FileName, AsciiFileName);

  FileSizeIsDifferent = (Info->FileSize != Fcb->Info.FileSize);
  FileNameIsDifferent = (AsciiStrCmp (AsciiFileName, Fcb->FileName) != 0);
  ReadOnlyIsDifferent = CompareMem (
                          &Info->CreateTime,
                          &Fcb->Info.CreateTime,
                          3 * sizeof (EFI_TIME)
                          ) != 0;

  //
  // For a read-only file or a file opened in read-only mode, only
  // the Attribute field can be modified. As the root directory is
  // read-only (i.e. VolumeOpen()), this protects the root directory
  // description.
  //
  if ((Fcb->OpenMode == EFI_FILE_MODE_READ)     ||
      (Fcb->Info.Attribute & EFI_FILE_READ_ONLY)  ) {
    if (FileSizeIsDifferent || FileNameIsDifferent || ReadOnlyIsDifferent) {
      Status = EFI_ACCESS_DENIED;
      goto Error;
    }
  }

  if (ReadOnlyIsDifferent) {
    Status = EFI_WRITE_PROTECTED;
    goto Error;
  }

  Status = EFI_DEVICE_ERROR;

  if (FileSizeIsDifferent) {
    FileSize = Info->FileSize;
    if (Fcb->Info.FileSize < FileSize) {
      Status = ExtendFile (Fcb, FileSize - Fcb->Info.FileSize);
      if (EFI_ERROR (Status)) {
        goto Error;
      }
      //
      // The read/write position from the host file system point of view
      // is at the end of the file. If the position from this module
      // point of view is smaller than the new file size, then
      // ask the host file system to move to that position.
      //
      if (Fcb->Position < FileSize) {
        FileSetPosition (&Fcb->File, Fcb->Position);
      }
    }
    Fcb->Info.FileSize = FileSize;

    Return = SemihostFileLength (Fcb->SemihostHandle, &Length);
    if (RETURN_ERROR (Return)) {
      goto Error;
    }
    Fcb->Info.PhysicalSize = Length;
  }

  //
  // Note down in RAM the Attribute field but we can not ask
  // for its modification to the host file system as the
  // semi-host interface does not provide this feature.
  //
  Fcb->Info.Attribute = Info->Attribute;

  if (FileNameIsDifferent) {
    Return = SemihostFileOpen (
               AsciiFileName,
               SEMIHOST_FILE_MODE_READ | SEMIHOST_FILE_MODE_BINARY,
               &SemihostHandle
               );
    if (!RETURN_ERROR (Return)) {
      SemihostFileClose (SemihostHandle);
      Status = EFI_ACCESS_DENIED;
      goto Error;
    }

    Return = SemihostFileRename (Fcb->FileName, AsciiFileName);
    if (RETURN_ERROR (Return)) {
      goto Error;
    }
    FreePool (Fcb->FileName);
    Fcb->FileName = AsciiFileName;
    AsciiFileName = NULL;
  }

  Status = EFI_SUCCESS;

Error:
  if (AsciiFileName != NULL) {
    FreePool (AsciiFileName);
  }

  return Status;
}