Example #1
0
/****************************************************************************
 * Update check
 ***************************************************************************/
int CheckUpdate() {
    if (!networkinitialized)
        return -1;

    int revnumber = 0;
    int currentrev = atoi(GetRev());

	if (Settings.beta_upgrades) {
		revnumber = CheckForBetaUpdate();
	} else {
#ifdef FULLCHANNEL
		struct block file = downloadfile("http://www.techjawa.com/usbloadergx/wadrev.txt");
#else
		struct block file = downloadfile("http://www.techjawa.com/usbloadergx/rev.txt");
#endif
		char revtxt[10];

		u8  i;
		if (file.data != NULL) {
			for (i=0; i<9 || i < file.size; i++)
				revtxt[i] = file.data[i];
			revtxt[i] = 0;
			revnumber = atoi(revtxt);
			free(file.data);
		}
	}

    if (revnumber > currentrev)
        return revnumber;
    else
        return -1;
}
/****************************************************************************
 * Update the Icon.png file
 ***************************************************************************/
bool UpdateTask::DownloadIconPNG(void)
{
	if(!IsNetworkInit())
		return false;

	struct block file = downloadfile(iconUpdateURL);
	if(!file.data)
		return false;

	CreateSubfolder(Settings.UpdatePath);

	//! append slash if it is missing
	std::string destPath = Settings.UpdatePath;
	if(destPath.size() > 0 && destPath[destPath.size()-1] != '/')
		destPath += '/';

	destPath += "icon.png";

	FILE * pFile = fopen(destPath.c_str(), "wb");
	if(!pFile)
		return false;

	fwrite(file.data, 1, file.size, pFile);
	fclose(pFile);
	free(file.data);

	return true;
}
Example #3
0
bool getCoverFromServer(char* url, char* imgPath, int v, int max){

	struct block file;
	char* pch;

	sprintf(self.debugMsg, TX.getting, url);
	Paint_Progress_Generic(v, max,self.debugMsg);

	file = downloadfile(url);

	if(file.data != NULL && file.size >= 4000){
	    char* msg = CFMalloc(20*sizeof(char));
	    strncpy(msg, (char*)file.data,20);
	    pch = strtok(msg, " ");
	    if(strcmp(pch,"<!DOCTYPE")==0) //test for a bad file
	     {
		   CFFree(msg);
		   CFFree(file.data);
		   return false;
	     }  
	    CFFree(msg);
	    unlink(imgPath);
 		saveFile(imgPath, file);
		CFFree(file.data);
		sprintf(self.debugMsg, TX.done );
		Paint_Progress_Generic(v, max,self.debugMsg);
		return true;
	}
	
	return false;
}
Example #4
0
BOOL CPicDowloadThread::URLDownloadPicture(LPCTSTR lptUrl, LPCTSTR lptPicPath, HINSTANCE hDll)
{
#ifdef USE_WININET_DOWNLOAD
	
	//hDll = LoadLibrary(_T("HtttpDownload.dll"));
	if (hDll == 0 )
	{
		return FALSE;
	}
	http_downloadfile downloadfile = (http_downloadfile)(GetProcAddress(hDll, "http_downloadfile"));
	if (downloadfile == NULL)
	{
		return FALSE;
	}
	std::string strUrl, strFileName;
	tStringToString(strUrl, lptUrl);
	tStringToString(strFileName, lptPicPath);
	return downloadfile(strUrl.c_str(), NULL, strFileName.c_str(), FALSE, NULL);
#else 
	HRESULT	hr = URLDownloadToFile(NULL, lptUrl, lptPicPath, 0, 0);
	if (hr != S_OK)
	{
		OutputDebugString(lptUrl);
		OutputDebugString(_T("Picture download failed \n"));
		return FALSE;
	}
	else
		return TRUE;
#endif
	
	
}
bool HTML_Stream::LoadLink(const char * url)
{
	if (!IsNetworkInit()) return false;

	struct block file = downloadfile(url);

	if (!file.data || !file.size) return false;

	if (HTML_File) free(HTML_File);

	HTML_File = (char *) file.data;
	filesize = file.size;
	position = 0;

	return true;
}
int WiiSave::InternalDownload(std::string url, std::string filepath)
{
	if (url.empty()) return -1;
	
	StartManageProgress(tr("Downloading file..."), "www.wiisave.com");
	
	HTML_Stream HTML(url.c_str());

	HTML.FindStringEnd("location='");
	char * location = HTML.CopyString("'");
	if(location)
	{
		url = url.erase(23);
		url += location;
		
		free(location);
	}
	else
	{
		ManageProgressStop();
		return -2;
	}
	
	struct block file = downloadfile(url.c_str());
	if (!file.data || !file.size)
	{
		ManageProgressStop();
		return -3;
	}

	FILE * File = fopen(filepath.c_str(), "wb");
	if(!File)
	{
		ManageProgressStop();
		return -4;
	}
	
	fwrite(file.data, 1, file.size, File);
	
	fclose(File);
	ManageProgressStop();
	
	return 1;
}
Example #7
0
void add_game_to_card(const char *gameid)
{
	int i;

	char *url = (char *) malloc(MAX_URL_SIZE); // Too much memory, but only like 10 bytes
	memset(url, 0, sizeof(url));

	for (i = 0; i < amount_of_providers && providers != NULL; i++)
	{
		if (strlen(providers[i].url) > 0 && strlen(providers[i].key) > 0)
		{
			strcpy(url, (char *) providers[i].url);
			str_replace(url, (char *) "{KEY}", (char *) providers[i].key, MAX_URL_SIZE);
			str_replace(url, (char *) "{ID6}", (char *) gameid, MAX_URL_SIZE);

			downloadfile(NULL, 0, (char *) url, NULL, NULL);
		}
	}
	SAFE_FREE(url);
}
Example #8
0
bool downloadTitles(){
	//WindowPrompt(TX.error, "Error initializing network\nTitles.txt can't be downloaded.", &okButton, 0);
	char titlesPath[100];
	struct block file;
	
	//snprintf(titlesPath, sizeof(titlesPath), "%s/titles.txt", USBLOADER_PATH);
	snprintf(titlesPath, sizeof(titlesPath), "%s/titles.txt", dynPath.dir_usb_loader);
	
	//file = downloadfile("http://www.wiiboxart.com/titles.txt");
	file = downloadfile("http://wiitdb.com/titles.txt");
	if(file.data != NULL){
		
                char* pch;
                char* msg = CFMalloc(20*sizeof(char));
                strncpy(msg, (char*)file.data,20);
                pch = strtok(msg, " ");
                if(strcmp(pch,"<!DOCTYPE")==0) //test for a bad file
                {
                    CFFree(msg);
                    CFFree(file.data);
                    return false;
                }
                CFFree(msg);
                unlink(titlesPath);
                if(saveFile(titlesPath, file))
                {
                        CFFree(file.data);
                        return true;
                }
                else{
                    CFFree(file.data);
                    return false;
                }
        }
    return false;
}
void DownloadDialog::Load(tinyxml2::XMLElement * node)
{
    CHECK_BOOL(node != NULL,
        L"Expected 'downloaddialog' node");

    CHECK_BOOL(0 == strcmp(node->Value(), "downloaddialog"),
        L"Expected 'downloaddialog' node, got '" << DVLib::string2wstring(node->Value()) << L"'");

    caption = node->Attribute("dialog_caption");
    help_message = node->Attribute("dialog_message");
    downloading_message = node->Attribute("dialog_message_downloading");
    copying_message = node->Attribute("dialog_message_copying");
    connecting_message = node->Attribute("dialog_message_connecting");
    sendingrequest_message = node->Attribute("dialog_message_sendingrequest");
    start_caption = node->Attribute("buttonstart_caption");
    cancel_caption = node->Attribute("buttoncancel_caption");
    auto_start = DVLib::wstring2bool(DVLib::UTF8string2wstring(node->Attribute("autostartdownload")), false);

    for (tinyxml2::XMLNode* child = node->FirstChildElement(); child; child = child->NextSibling())
    {
        tinyxml2::XMLElement * node_element = child->ToElement();
        if (node_element == NULL)
            continue;

        auto_any<DownloadFile *, close_delete> downloadfile(new DownloadFile());
        downloadfile->Load(node_element);
        downloadfiles.push_back(downloadfile);
    }

    if (downloadfiles.empty())
    {
        THROW_EX("Invalid  Download dialog '" << caption << L"', requires at least one download file.");
    }

    LOG(L"Loaded 'download' configuration '" << caption << L"' with " << downloadfiles.size() << " file(s)");
}
Example #10
0
/****************************************************************************
 * MenuLanguageSelect
 ***************************************************************************/
int MenuLanguageSelect() {
    int cnt = 0;
    int ret = 0, choice = 0;
    int scrollon;
    int returnhere = 0;

    GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume);
	// because destroy GuiSound must wait while sound playing is finished, we use a global sound
	if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);
	//	GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);

    char imgPath[100];

    snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path);
    GuiImageData btnOutline(imgPath, button_dialogue_box_png);
    snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path);
    GuiImageData settingsbg(imgPath, settings_background_png);

    GuiTrigger trigA;
    trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);
    GuiTrigger trigB;
    trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B);

    char fullpath[100];
    int countfiles = GetAllDirFiles(Settings.languagefiles_path);

    if (!strcmp("", Settings.languagefiles_path)) {
        sprintf(fullpath, "%s", tr("Standard"));
    } else {
        sprintf(fullpath, "%s", Settings.languagefiles_path);
    }

    GuiText titleTxt(fullpath, 24, (GXColor) {0, 0, 0, 255});
    titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
    titleTxt.SetPosition(0,0);
    GuiButton pathBtn(300, 50);
    pathBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    pathBtn.SetPosition(0,28);
    pathBtn.SetLabel(&titleTxt);
    pathBtn.SetSoundOver(&btnSoundOver);
    pathBtn.SetSoundClick(btnClick2);
    pathBtn.SetTrigger(&trigA);
    pathBtn.SetEffectGrow();

    GuiImage oggmenubackground(&settingsbg);
    oggmenubackground.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
    oggmenubackground.SetPosition(0, 0);

    GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext);
    backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage backBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        backBtnTxt.SetWidescreen(CFG.widescreen);
        backBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton backBtn(btnOutline.GetWidth(), btnOutline.GetHeight());
    backBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    backBtn.SetPosition(-190, 400);
    backBtn.SetLabel(&backBtnTxt);
    backBtn.SetImage(&backBtnImg);
    backBtn.SetSoundOver(&btnSoundOver);
    backBtn.SetSoundClick(btnClick2);
    backBtn.SetTrigger(&trigA);
    backBtn.SetTrigger(&trigB);
    backBtn.SetEffectGrow();

    GuiText defaultBtnTxt(tr("Default") , 22, THEME.prompttext);
    defaultBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage defaultBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        defaultBtnTxt.SetWidescreen(CFG.widescreen);
        defaultBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton defaultBtn(btnOutline.GetWidth(), btnOutline.GetHeight());
    defaultBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    defaultBtn.SetPosition(190, 400);
    defaultBtn.SetLabel(&defaultBtnTxt);
    defaultBtn.SetImage(&defaultBtnImg);
    defaultBtn.SetSoundOver(&btnSoundOver);
    defaultBtn.SetSoundClick(btnClick2);
    defaultBtn.SetTrigger(&trigA);
    defaultBtn.SetEffectGrow();

    GuiText updateBtnTxt(tr("Update Files") , 22, THEME.prompttext);
    updateBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage updateBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        updateBtnTxt.SetWidescreen(CFG.widescreen);
        updateBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton updateBtn(btnOutline.GetWidth(), btnOutline.GetHeight());
    updateBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    updateBtn.SetPosition(0, 400);
    updateBtn.SetLabel(&updateBtnTxt);
    updateBtn.SetImage(&updateBtnImg);
    updateBtn.SetSoundOver(&btnSoundOver);
    updateBtn.SetSoundClick(btnClick2);
    updateBtn.SetTrigger(&trigA);
    updateBtn.SetEffectGrow();

    customOptionList options2(countfiles);

    for (cnt = 0; cnt < countfiles; cnt++) {
        char filename[64];
        strlcpy(filename, GetFileName(cnt), sizeof(filename));
        char *dot = strchr(filename, '.');
        if (dot) *dot='\0';
        options2.SetName(cnt, "%s", filename);
        options2.SetValue(cnt, NULL);

    }

    if (cnt < 9) {
        scrollon = 0;
    } else {
        scrollon = 1;
    }

    GuiCustomOptionBrowser optionBrowser4(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, scrollon, 10);
    optionBrowser4.SetPosition(0, 90);
    optionBrowser4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);

    HaltGui();
    GuiWindow w(screenwidth, screenheight);
    w.Append(&oggmenubackground);
    w.Append(&pathBtn);
    w.Append(&backBtn);
    w.Append(&defaultBtn);
    w.Append(&updateBtn);
    w.Append(&optionBrowser4);
    mainWindow->Append(&w);

    w.SetEffect(EFFECT_FADE, 20);
    ResumeGui();

    while (w.GetEffect()>0) usleep(50);

    while (!returnhere) {

        if (shutdown == 1)
            Sys_Shutdown();
        else if (reset == 1)
            Sys_Reboot();

        else if (backBtn.GetState() == STATE_CLICKED) {

            backBtn.ResetState();
            break;
        }

        else if (defaultBtn.GetState() == STATE_CLICKED) {
            choice = WindowPrompt(tr("Loading standard language."),0,tr("OK"), tr("Cancel"));
            if (choice == 1) {
                sprintf(Settings.language_path, "notset");
                cfg_save_global();
                gettextCleanUp();
				HaltGui();
                CFG_Load();
				ResumeGui();
                returnhere = 2;
            }
            defaultBtn.ResetState();
			//optionBrowser4.SetFocus(1); // commented out to prevent crash
        }

        else if (updateBtn.GetState() == STATE_CLICKED) {
            choice = WindowPrompt(tr("Update all Language Files"),tr("Do you wish to update/download all language files?"),tr("OK"), tr("Cancel"));
            if (choice == 1) {

                bool network = true;
                if (!IsNetworkInit()) {
                    network = NetworkInitPrompt();
                }

                if (network) {
                    const char URL[60] = "http://usbloader-gui.googlecode.com/svn/trunk/Languages/";
                    char fullURL[300];
                    FILE *pfile;

                    URL_List LinkList(URL);
                    int listsize = LinkList.GetURLCount();

                    subfoldercreate(Settings.languagefiles_path);

                    for (int i = 0; i < listsize; i++) {

                        ShowProgress(tr("Updating Language Files:"), 0, LinkList.GetURL(i), i, listsize-1);

                        if (strcasecmp(".lang", strrchr(LinkList.GetURL(i), '.')) == 0) {

                            snprintf(fullURL, sizeof(fullURL), "%s%s", URL, LinkList.GetURL(i));

                            struct block file = downloadfile(fullURL);

                            if (file.data && file.size) {
                                char filepath[300];

                                snprintf(filepath, sizeof(filepath), "%s%s", Settings.languagefiles_path, LinkList.GetURL(i));
                                pfile = fopen(filepath, "wb");
                                fwrite(file.data, 1, file.size, pfile);
                                fclose(pfile);

                            }

                            free(file.data);
                        }
                    }
                    ProgressStop();
                    returnhere = 1;
                    break;
                }
            }
			updateBtn.ResetState();
			//optionBrowser4.SetFocus(1); // commented out to prevent crash
        }

        else if (pathBtn.GetState() == STATE_CLICKED) {
            w.Remove(&optionBrowser4);
            w.Remove(&backBtn);
            w.Remove(&pathBtn);
            w.Remove(&defaultBtn);
            char entered[43] = "";
            strlcpy(entered, Settings.languagefiles_path, sizeof(entered));
            int result = OnScreenKeyboard(entered,43,0);
            w.Append(&optionBrowser4);
            w.Append(&pathBtn);
            w.Append(&backBtn);
            w.Append(&defaultBtn);
            if ( result == 1 ) {
                int len = (strlen(entered)-1);
                if (entered[len] !='/')
                    strncat (entered, "/", 1);
                strlcpy(Settings.languagefiles_path, entered, sizeof(Settings.languagefiles_path));
                WindowPrompt(tr("Languagepath changed."),0,tr("OK"));
                if (isInserted(bootDevice)) {
                    cfg_save_global();
                    returnhere = 1;
                    break;
                } else {
                    WindowPrompt(tr("No SD-Card inserted!"), tr("Insert an SD-Card to save."), tr("OK"));
                }
            }
            if (countfiles > 0) {
                optionBrowser4.SetFocus(1);
            }
            pathBtn.ResetState();
        }

        ret = optionBrowser4.GetClickedOption();

        if (ret>=0) {
            choice = WindowPrompt(tr("Do you want to change language?"), 0, tr("Yes"), tr("Cancel"));
            if (choice == 1) {
                if (isInserted(bootDevice)) {
                    snprintf(Settings.language_path, sizeof(Settings.language_path), "%s%s", Settings.languagefiles_path, GetFileName(ret));
                    cfg_save_global();
                    if (!checkfile(Settings.language_path)) {
                        sprintf(Settings.language_path, tr("not set"));
                        WindowPrompt(tr("File not found."),tr("Loading standard language."),tr("OK"));
                    }
                    gettextCleanUp();
					HaltGui();
					CFG_Load();
					ResumeGui();
                    returnhere = 2;
                    break;
                } else {
                    WindowPrompt(tr("No SD-Card inserted!"), tr("Insert an SD-Card to save."), tr("OK"), 0,0,0,-1);
                }
            }
            optionBrowser4.SetFocus(1);
        }

    }

    w.SetEffect(EFFECT_FADE, -20);
    while (w.GetEffect()>0) usleep(50);

    HaltGui();
    mainWindow->Remove(&w);
    ResumeGui();

    return returnhere;
}
Example #11
0
/****************************************************************************
 * Update the language files
 ***************************************************************************/
bool UpdateTask::UpdateLanguageFiles(void)
{
	if(!IsNetworkInit())
		return false;

	char langpath[150];
	snprintf(langpath, sizeof(langpath), "%s", Settings.LanguagePath);
	if(langpath[strlen(langpath)-1] != '/')
	{
		char * ptr = strrchr(langpath, '/');
		if(ptr)
			ptr[1] = '\0';
	}

	if(!CreateSubfolder(langpath))
	{
		ThrowMsg(tr("Error:"), "%s", tr("Cannot create directory: "), langpath);
		return -1;
	}

	URL_List LinkList(languageUpdateURL);

	if(LinkList.GetURLCount() <= 0)
	{
		ThrowMsg(tr("Error:"), tr("No files found."));
		return -1;
	}

	ProgressWindow::Instance()->StartProgress(tr("Downloading files..."));
	ProgressWindow::Instance()->SetUnit(tr("files"));

	u32 FilesDownloaded = 0;

	for (int i = 0; i < LinkList.GetURLCount(); i++)
	{
		if(ProgressWindow::Instance()->IsCanceled())
			continue;

		ShowProgress(i, LinkList.GetURLCount(), LinkList.GetURL(i));

		char * fileext = strrchr(LinkList.GetURL(i), '.');
		if(!fileext)
			continue;

		if (strcasecmp(fileext, ".lang") != 0)
			continue;

		char fullURL[MAXPATHLEN];
		if(LinkList.IsFullURL(i))
			snprintf(fullURL, sizeof(fullURL), "%s", LinkList.GetURL(i));
		else
			snprintf(fullURL, sizeof(fullURL), "%s%s", languageUpdateURL, LinkList.GetURL(i));

		struct block file = downloadfile(fullURL);

		if (file.data && file.size > 0)
		{
			snprintf(fullURL, sizeof(fullURL), "%s%s", langpath, LinkList.GetURL(i));
			FILE * filePtr = fopen(fullURL, "wb");
			if(filePtr)
			{
				fwrite(file.data, 1, file.size, filePtr);
				fclose(filePtr);
				FilesDownloaded++;
			}
		}

		if(file.data)
			free(file.data);
	}

	// finish up the progress for this file
	ProgressWindow::Instance()->FinishProgress((LinkList.GetURLCount()-1)*20*1024);
	ProgressWindow::Instance()->StopProgress();
	ProgressWindow::Instance()->SetUnit(NULL);

	return FilesDownloaded;
}
void fontDownload(string fontname)
{
	bool stop = true;

	GuiWindow promptWindow(520,360);
	promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	promptWindow.SetPosition(0, -10);
	GuiTrigger trigA;
	trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);


	GuiImageData dialogBox(Theme.dialog_background);
	GuiImage dialogBoxImg(&dialogBox);

	GuiImageData btnOutline(Theme.button_small);
	GuiImage btn1Img(&btnOutline);
	GuiImage btn2Img(&btnOutline);

	GuiImageData btnOutlineOver(Theme.button_small_focus);
	GuiImage btn1ImgOver(&btnOutlineOver);
	GuiImage btn2ImgOver(&btnOutlineOver);

	GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
	titleTxt.SetPosition(0, 40);
	GuiText downloadTxt(tr("Downloading file..."), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	downloadTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	downloadTxt.SetPosition(0, -20);

	GuiText msgTxt(tr("please wait"), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	msgTxt.SetPosition(0, 20);

	GuiText btn1Txt(tr("OK"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255});
	GuiButton btn1(btnOutline.GetWidth(), btnOutline.GetHeight());

	btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM);
	btn1.SetPosition(0, -25);
	btn1.SetLabel(&btn1Txt);
	btn1.SetImage(&btn1Img);
	btn1.SetImageOver(&btn1ImgOver);
	btn1.SetTrigger(&trigA);
	btn1.SetState(STATE_SELECTED);
	btn1.SetEffectGrow();

	promptWindow.Append(&dialogBoxImg);
	promptWindow.Append(&titleTxt);
	promptWindow.Append(&downloadTxt);
	promptWindow.Append(&msgTxt);


	HaltGui();
	mainWindow->SetState(STATE_DISABLED);
	mainWindow->Append(&promptWindow);
	mainWindow->ChangeFocus(&promptWindow);
	ResumeGui();

	char buffer[100];
	msgTxt.SetText(fontname.c_str());
	sprintf(buffer, "http://www.nanolx.org/hbf/Fonts/%s", fontname.c_str());
	struct block file = downloadfile(buffer);
	if (file.data && file.size > 0 && folder_exists())
	{
		FILE * data = fopen((Settings.device_dat + ":/config/HBF/Fonts/"+ fontname).c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
	}
	if(file.data)
		free(file.data);

	msgTxt.SetText("");
	downloadTxt.SetText(tr("finished"));

	promptWindow.Append(&btn1);


	while(stop)
	{
		usleep(100);

		if(btn1.GetState() == STATE_CLICKED)
			stop = false;
	}

	HaltGui();
	mainWindow->Remove(&promptWindow);
	mainWindow->SetState(STATE_DEFAULT);
	ResumeGui();
}
Example #13
0
/****************************************************************************
 * Checking if an Update is available
 ***************************************************************************/
int UpdateTask::CheckForUpdate(void)
{
	if(!IsNetworkInit())
		return -1;

	int revnumber = 0;
	int currentrev = atoi(SvnRev());

	struct block file = downloadfile(appUpdateURL);
	if(!file.data)
		return -2;

	file.data[file.size-1] = 0;

	char *revPtr = strstr((char*)file.data, "rev=\"");
	if(!revPtr) {
		free(file.data);
		return -3;
	}
	revPtr += strlen("rev=\"");

	revnumber = atoi(revPtr);

	if (revnumber <= currentrev)
		return 0;

	char *downloadLink = strstr(revPtr, "link=\"");
	if(!downloadLink) {
		free(file.data);
		return -4;
	}
	downloadLink += strlen("link=\"");

	char *ptr = strchr(downloadLink, '"');
	if(!ptr) {
		free(file.data);
		return -5;
	}
	*ptr = 0;

	char text[100];
	sprintf(text, tr("Update to Rev%i available"), revnumber);

	PromptWindow * Prompt = new PromptWindow(text, tr("Do you want to update now ?"), tr("Yes"), tr("Show Changelog"), tr("Cancel"));
	Prompt->DimBackground(true);
	Application::Instance()->Append(Prompt);
	Application::Instance()->SetUpdateOnly(Prompt);

	int choice;

	while((choice = Prompt->GetChoice()) < 0)
		usleep(10000);

	Application::Instance()->PushForDelete(Prompt);

	if(choice == 1)
	{
		if(DownloadApp(downloadLink) >= 0)
		{
			Prompt = new PromptWindow(tr("Update successfully finished"), tr("Do you want to reboot now ?"), tr("Yes"), tr("No"));
			Prompt->DimBackground(true);
			Application::Instance()->Append(Prompt);
			Application::Instance()->SetUpdateOnly(Prompt);

			while((choice = Prompt->GetChoice()) < 0)
				usleep(10000);

			Application::Instance()->PushForDelete(Prompt);

			if(choice)
				RebootApp();
		}
	}
	else if(choice == 2)
	{
		ChangeLog Changelog;
		Changelog.DownloadChangeLog(revnumber-5, revnumber);
		if(!Changelog.Show())
			ThrowMsg(tr("Error:"), tr("Failed to get the Changelog."));
	}

	return revnumber;
}
Example #14
0
void CMenu::_CheatSettings() {
	s32 padsState;
	WPADData *wd;
	u32 btn;
	WPAD_Rumble(WPAD_CHAN_0, 0);

	// try to load cheat file
	int txtavailable=0;
	m_cheatSettingsPage = 1; // init page
	
	txtavailable = m_cheatfile.openTxtfile(fmt("%s/%s.txt", m_txtCheatDir.c_str(), m_cf.getId().c_str())); 
	
	_showCheatSettings();
	_textCheatSettings();
	
	if (txtavailable)
		m_btnMgr.setText(m_cheatLblTitle,wfmt(L"%s",m_cheatfile.getGameName().c_str()));
	else 
		m_btnMgr.setText(m_cheatLblTitle,L"");
	
	while (true)
	{
		WPAD_ScanPads();
		padsState = WPAD_ButtonsDown(0);
		wd = WPAD_Data(0);
		btn = _btnRepeat(wd->btns_h);
		if ((padsState & (WPAD_BUTTON_HOME | WPAD_BUTTON_B)) != 0)
			break;
		if (wd->ir.valid)
			m_btnMgr.mouse(wd->ir.x - m_cur.width() / 2, wd->ir.y - m_cur.height() / 2);
		else if ((padsState & WPAD_BUTTON_UP) != 0)
			m_btnMgr.up();
		else if ((padsState & WPAD_BUTTON_DOWN) != 0)
			m_btnMgr.down();
		if ((padsState & WPAD_BUTTON_MINUS) != 0)
		{
			if (m_cheatSettingsPage > 1)
				--m_cheatSettingsPage;
			_hideCheatSettings();
			_showCheatSettings();
			m_btnMgr.click(m_cheatBtnPageM);
		}
		else if ((padsState & WPAD_BUTTON_PLUS) != 0)
		{
			_hideCheatSettings();
			if (m_cheatSettingsPage < (m_cheatfile.getCnt()+CHEATSPERPAGE-1)/CHEATSPERPAGE)
				++m_cheatSettingsPage;
			_showCheatSettings();
			m_btnMgr.click(m_cheatBtnPageP);
		}		
		if ((padsState & WPAD_BUTTON_A) != 0)
		{
			m_btnMgr.click();
			if (m_btnMgr.selected() == m_cheatBtnBack)
				break;
			else if (m_btnMgr.selected() == m_cheatBtnPageM)
			{
				_hideCheatSettings();
				if (m_cheatSettingsPage > 1)
					--m_cheatSettingsPage;
				_showCheatSettings();
			}
			else if (m_btnMgr.selected() == m_cheatBtnPageP)
			{
				_hideCheatSettings();
				if (m_cheatSettingsPage < (m_cheatfile.getCnt()+CHEATSPERPAGE-1)/CHEATSPERPAGE)
					++m_cheatSettingsPage;
				_showCheatSettings();
			}
				
			for (int i = 0; i < CHEATSPERPAGE; ++i)
				if (m_btnMgr.selected() == m_cheatBtnItem[i]) {
					// handling code for clicked cheat
					m_cheatfile.sCheatSelected[(m_cheatSettingsPage-1)*CHEATSPERPAGE + i] = !m_cheatfile.sCheatSelected[(m_cheatSettingsPage-1)*CHEATSPERPAGE + i];
					_showCheatSettings();
				}
			
			if (m_btnMgr.selected() == m_cheatBtnApply)
			{
				int operation_ok,check = 0;
				//checks if at least one cheat is selected
				for (unsigned int i=0; i < m_cheatfile.getCnt(); ++i) {
					if (m_cheatfile.sCheatSelected[i] == true) 
						{
						check = 1;
						break;
						}
					
					}
					
				if (check)
				{
					operation_ok = m_cheatfile.createGCT(fmt("%s/%s.gct", m_cheatDir.c_str(), m_cf.getId().c_str())); 
					operation_ok = m_cheatfile.createTXT(fmt("%s/%s.txt", m_txtCheatDir.c_str(), m_cf.getId().c_str())); 
					
				}
					
				m_cfg.setOptBool(m_cf.getId(), "cheat",1);
				if (operation_ok)
					break;
			}

			if (m_btnMgr.selected() == m_cheatBtnDownload)
			{
				// Download cheat code
				m_btnMgr.hide(m_cheatLblTitle);
				
				u32 bufferSize = 0x100000;	// Maximum download size 1 MB
				SmartBuf buffer;
				block cheatfile;
				FILE *file;
				char ip[16];
				
				if (!m_networkInit && _initNetwork(ip) < 0) {
					m_btnMgr.hide(m_cheatLblTitle);
					break;
				}
				m_networkInit = true;

				buffer = smartCoverAlloc(bufferSize);
				cheatfile = downloadfile(buffer.get(), bufferSize, sfmt(GECKOURL, m_cf.getId().c_str()).c_str(),CMenu::_downloadProgress, this);

				if (cheatfile.data != NULL && cheatfile.size > 65 && cheatfile.data[0] != '<') {
					// cheat file was downloaded and presumably no 404
					file = fopen(fmt("%s/%s.txt", m_txtCheatDir.c_str(), m_cf.getId().c_str()), "wb");
							
					if (file != NULL)
					{
						fwrite(cheatfile.data, 1, cheatfile.size, file);
						fclose(file);
						break;
					}
				}
				else
				{
					// cheat code not found, show result
					m_btnMgr.setText(m_cheatLblItem[0], _t("cheat4", L"Download not found."));
					m_btnMgr.setText(m_cheatLblItem[1], wfmt(L"http://www.geckocodes.org/codes/R/%s.txt",m_cf.getId().c_str()));
					m_btnMgr.show(m_cheatLblItem[1]);
				}
			}
		}
		_mainLoopCommon(wd);
	}
	_hideCheatSettings();
}
Example #15
0
int UpdateLanguageFiles()
{
	if(!CreateSubfolder(Settings.languagefiles_path))
	{
		ShowError(tr("Could not create path: %s"), Settings.languagefiles_path);
		return -1;
	}

	if(!IsNetworkInit())
	{
		ShowError(tr("Network is not initiated."));
		return -2;
	}

	DirList Dir(Settings.languagefiles_path, ".lang");

	//give up now if we didn't find any
	if (Dir.GetFilecount() == 0)
	{
		if(WindowPrompt(tr("Error:"), tr("No language files to update on your devices! Do you want to download new language files?"), tr("Yes"), tr("No")))
			return DownloadAllLanguageFiles();

		return -2;
	}

	char savepath[150];
	char codeurl[200];

	//we assume that the network will already be init by another function
	// ( that has gui eletents in it because this one doesn't)
	int done = 0;

	//build the URL, save path, and download each file and save it
	for(int i = 0; i < Dir.GetFilecount(); ++i)
	{
		snprintf(codeurl, sizeof(codeurl), "%s%s?p=%s", LanguageFilesURL, Dir.GetFilename(i), GetRev());
		snprintf(savepath, sizeof(savepath), "%s/%s", Settings.languagefiles_path, Dir.GetFilename(i));

		struct block file = downloadfile(codeurl);

		ShowProgress(tr("Updating Language Files:"), 0, Dir.GetFilename(i), i, Dir.GetFilecount(), false, true);

		if (file.data != NULL)
		{
			FILE * pfile;
			pfile = fopen(savepath, "wb");
			if (pfile != NULL)
			{
				fwrite(file.data, 1, file.size, pfile);
				fclose(pfile);
				done++;
			}
			free(file.data);
		}
	}

	ProgressStop();

	// reload current language file
	if(Settings.language_path[0] != 0)
		Settings.LoadLanguage(Settings.language_path, CONSOLE_DEFAULT);
	else
		Settings.LoadLanguage(NULL, CONSOLE_DEFAULT);

	// return the number of files we updated
	return done;
}
string FontList()
{
	string downloadfont = "error";
	bool stop = false;

	char buffer[100];
	sprintf(buffer, "http://www.nanolx.org/hbf/Fonts/");

	struct block file = downloadfile(buffer);
	if (file.data != NULL)
	{
		string source_fonts = (char*)file.data;
		vector<string> fonts;

		while(1)
		{
			if((signed)source_fonts.find("../Fonts/") == -1)
				break;

			source_fonts.erase(0, source_fonts.find("../Fonts/"));
			source_fonts.erase(0, source_fonts.find("s/") +2);

			fonts.push_back(source_fonts.substr(0, source_fonts.find("\"")));

			source_fonts.erase(0, source_fonts.find("<"));
		}

		free(file.data);

		GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
		titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
		titleTxt.SetPosition(0, 40);

		GuiWindow promptWindow(520,360);
		promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
		promptWindow.SetPosition(0, -10);
		GuiTrigger trigA;
		trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);

		GuiImageData dialogBox(Theme.dialog_background);
		GuiImage dialogBoxImg(&dialogBox);

		int place = 23;
		int y = 150;
		int i = 0;
		int number = 5;
		int selection = 0;
		int textScrollPos = 0;
		int selctionPos = y;

		GuiText selectionTxt(">>                                                                    <<", 20, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
		selectionTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
		selectionTxt.SetPosition(0, y);

		GuiText upTxt("c", 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
		upTxt.SetFont(symbol_ttf, symbol_ttf_size);
		upTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
		upTxt.SetPosition(0, y -20);

		GuiText downTxt("d", 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
		downTxt.SetFont(symbol_ttf, symbol_ttf_size);
		downTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
		downTxt.SetPosition(0, y + (place * (number-1)) + 15);

		GuiText * Entrie[number];

		for(i=0; i < number && i < (signed)fonts.size(); i++)
		{
			Entrie[i] = new GuiText(fonts[i].c_str(), 20, (GXColor) {Theme.text_1, Theme.text_2, Theme.text_3, 255});
			Entrie[i]->SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
			Entrie[i]->SetPosition(0, y);
			Entrie[i]->SetMaxWidth(300, SCROLL_HORIZONTAL);
			y += place;
		}

		promptWindow.Append(&dialogBoxImg);
		promptWindow.Append(&titleTxt);
		promptWindow.Append(&selectionTxt);

		for(int x=0; x < i; x++)
			promptWindow.Append(Entrie[x]);

		if((signed)fonts.size() >= number)
		{
			promptWindow.Append(&upTxt);
			promptWindow.Append(&downTxt);
		}

		promptWindow.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50);
		HaltGui();
		mainWindow->SetState(STATE_DISABLED);
		mainWindow->Append(&promptWindow);
		mainWindow->ChangeFocus(&promptWindow);
		ResumeGui();

		while(!stop)
		{
			usleep(100);

			if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP) || PAD_ButtonsDown(0) & PAD_BUTTON_UP
			   || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_UP)
			{
				selection--;
				if(selection < 0)
				{
					selection = 0;
					textScrollPos--;
					if(textScrollPos < 0)
						textScrollPos = 0;

					for(int x=0; x < number && x < (signed)fonts.size(); x++)
						Entrie[x]->SetText(fonts[x + textScrollPos].c_str());
				}
				selectionTxt.SetPosition(0, selection * place + selctionPos);

				HaltResumeGui();
			}

			if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN) || PAD_ButtonsDown(0) & PAD_BUTTON_DOWN
			   || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_DOWN)
			{
				selection++;
				if(selection == (signed)fonts.size())
					selection = fonts.size() -1;
				if(selection > number -1)
				{
					selection = number -1;
					textScrollPos++;
					if(textScrollPos > (signed)fonts.size() - number)
						textScrollPos = fonts.size() - number;

					for(int x=0; x < number && x < (signed)fonts.size(); x++)
						Entrie[x]->SetText(fonts[x + textScrollPos].c_str());
				}
				selectionTxt.SetPosition(0, selection * place + selctionPos);

				HaltResumeGui();
			}

			if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A) || PAD_ButtonsDown(0) & PAD_BUTTON_A
			   || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_A)
			{
				downloadfont = fonts[selection + textScrollPos];
				stop = true;
			}

			if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B) || PAD_ButtonsDown(0) & PAD_BUTTON_B
			   || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_B)
			{
				downloadfont = "NULL";
				stop = true;
			}
		}

		promptWindow.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50);
		while(promptWindow.GetEffect() > 0) usleep(100);
		HaltGui();
		mainWindow->Remove(&promptWindow);
		mainWindow->SetState(STATE_DEFAULT);
		ResumeGui();
	}

	return downloadfont;
}
Example #17
0
int main()
{
	const char build_time[] = __DATE__ " " __TIME__;

	dlCounter = 0;

	ret = 0;

	gfxInitDefault();

	consoleInit(GFX_TOP, &topScreen);
	consoleInit(GFX_BOTTOM, &bottomScreen);
	consoleSelect(&topScreen);
	/*printf("%s by %s\n", APPTITLE, APPAUTHOR);*/
	printf("Koopa Cruiser by jsa\n");
	printf("Version: %s\n", VERSION);

	//printf("--dev build--\n");
	printf("Modified: %s\n", __TIMESTAMP__);
	printf("Built: %s\n\n", build_time);
	printf("Press X to save the page\n");
	printf("Press START to exit.\n");
	printf("Press B to start the swkbd applet\n\n");
	gfxFlushBuffers();

	httpcInit();

	//Change this to your own URL.
	url = "http://mabel.nonm.co.uk/woop/view.php";

	printf("Loading %s\n\n",url);
	gfxFlushBuffers();

	ret = httpcOpenContext(&context, url , 0);
	//printf("return from httpcOpenContext: %"PRId32"\n",ret);
	gfxFlushBuffers();

	if(ret==0)
	{
		ret=http_download(&context);
		//printf("return from http_download: %"PRId32"\n",ret);
		gfxFlushBuffers();
		httpcCloseContext(&context);
	}

	// Main loop
	while (aptMainLoop())
	{
		gspWaitForVBlank();
		hidScanInput();

		// Your code goes here

		u32 kDown = hidKeysDown();
		if (kDown & KEY_START)
			break; // break in order to return to hbmenu

		if (kDown & KEY_X)
	    {
	        downloadfile();
	    }

		/*if (kDown & KEY_B)
			{
				printf("Launching swkbd.\n");
				if(APT_PrepareToStartLibraryApplet(APPID_MIIVERSE_POSTING)) printf("Preparing to launch applet\n");
				Result rc = APT_LaunchLibraryApplet(APPID_MIIVERSE_POSTING, 0, NULL, 0);
				if (rc) printf("APT_LaunchLibraryApplet: %08lX\n", rc);
				printf("this is probably broken!\n");
			}*/
			if(kDown & KEY_B)
			{
				printf("woah!\n");
				swkbd_Init();
				char buf[256];
				strcpy(buf,"Hello world!");
			}
			if(kDown & KEY_SELECT)
			{
				swkbd_GetStr(buf, 256);
				printf(buf);
				printf("\n");
			}

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();
	}

	// Exit services
	httpcExit();
	gfxExit();
	return 0;
}
int
getremote(char *filename, peer_t *peer, char *range, CURL *curlhandle)
{
#ifdef	TIMEIT
	struct timeval		start_time, end_time;
	unsigned long long	s, e;
#endif
	CURLcode	curlcode;
	struct in_addr	in;
	struct stat	buf;
	FILE		*file;
	useconds_t	stall;
	char		*tempfilename;
	char		*dirfile, *basefile;
	char		url[PATH_MAX];
	char		*dir;
	char		*ptr;

#ifdef	TIMEIT
	gettimeofday(&start_time, NULL);
#endif

	in.s_addr = peer->ip;

#ifdef	DEBUG
	logmsg("getremote: get file (%s) from (%s)\n", filename, inet_ntoa(in));
#endif

	status = HTTP_OK;

	/*
	 * we know the file is not on the local hard disk (because getlocal()
	 * is called before this function), so try to download the file
	 * from a peer
	 */

	/*
	 * first, let's see if the file systems have been formatted. if
	 * so, then copy over all the files that were downloaded in the
	 * first part of the installation (e.g., stage2.img, product.img)
	 * and set up a symbolic link from the ramdisk area to the disk.
	 */

	if (stat("/mnt/sysimage", &buf) == 0) {
		if (stat("/mnt/sysimage/install", &buf) != 0) {
			if (stat("/install", &buf) == 0) {
				system("/usr/bin/cp -R /install /mnt/sysimage");
				system("/usr/bin/rm -rf /install");
			} else {
				/*
				 * /install doesn't exist on the ramdisk, so
				 * just create a directory on the hard disk
				 */
				mkdir("/mnt/sysimage/install", 0755);
			}
			symlink("/mnt/sysimage/install", "/install");
		}
	}

#ifdef	TIMEIT
	gettimeofday(&end_time, NULL);
	s = (start_time.tv_sec * 1000000) + start_time.tv_usec;
	e = (end_time.tv_sec * 1000000) + end_time.tv_usec;
	logmsg("getremote:svc time1: %lld usec\n", (e - s));
#endif

	/*
	 * make sure the destination directory exists
	 */
	if ((dir = strdup(filename)) != NULL) {
		if ((ptr = rindex(dir, '/')) != NULL) {
			*ptr = '\0';
			if (stat(dir, &buf) != 0) {
				createdir(dir);
			}
		}

		free(dir);
	}

#ifdef	TIMEIT
	gettimeofday(&end_time, NULL);
	s = (start_time.tv_sec * 1000000) + start_time.tv_usec;
	e = (end_time.tv_sec * 1000000) + end_time.tv_usec;
	logmsg("getremote:svc time2: %lld usec\n", (e - s));
#endif

	if ((dirfile = strdup(filename)) == NULL) {
		logmsg("getremote:strdup failed:errno (%d)\n", errno);
		return(-1);
	}

	if ((basefile = strdup(filename)) == NULL) {
		logmsg("getremote:strdup failed:errno (%d)\n", errno);
		return(-1);
	}

	if ((tempfilename = tempnam(dirname(dirfile), basename(basefile))) ==
			NULL) {
		free(dirfile);
		free(basefile);
		logmsg("getremote:tempnam():failed\n");
		return(-1);
	}

	free(dirfile);
	free(basefile);

	/*
	 * make a 'http://' url and get the file.
	 */
	if ((file = fopen(tempfilename, "w")) == NULL) {
		logmsg("getremote:fopen():failed\n");
		free(tempfilename);
		return(-1);
	}

#ifdef	TIMEIT
	gettimeofday(&end_time, NULL);
	s = (start_time.tv_sec * 1000000) + start_time.tv_usec;
	e = (end_time.tv_sec * 1000000) + end_time.tv_usec;
	logmsg("getremote:svc time3: %lld usec\n", (e - s));
#endif

	/*
	 * tell curl to save it to disk (save it to the file pointed
	 * to by 'file'
	 */
	if ((curlcode = curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA,
			file)) != CURLE_OK) {
		logmsg("getremote:curl_easy_setopt():failed:(%d)\n", curlcode);
		free(tempfilename);
		return(-1);
	}

	if (makeurl("http://", filename, inet_ntoa(in), url, sizeof(url)) != 0){
		logmsg("getremote:makeurl():failed:(%d)", errno);
		free(tempfilename);
		return(-1);
	}

	if (fromip != NULL) {
		free(fromip);
	}
	fromip = strdup(inet_ntoa(in));

#ifdef	TIMEIT
	gettimeofday(&end_time, NULL);
	s = (start_time.tv_sec * 1000000) + start_time.tv_usec;
	e = (end_time.tv_sec * 1000000) + end_time.tv_usec;
	logmsg("getremote:svc time4: %lld usec\n", (e - s));
#endif

	stall = 10000;

	while (stall < 1000000) {
		if (downloadfile(curlhandle, url, NULL) < 0) {
			status = HTTP_NOT_FOUND;
		}
#ifdef	DEBUG
		logmsg("getremote:download status %d : stall %d\n",
			status, stall);
#endif

		if ((status >= HTTP_OK) && (status <= HTTP_MULTI_STATUS)) {
			/*
			 * success. break out of loop
			 */
			break;
		} else {
			logmsg("getremote:downloadfile:failed:url %s\n", url);

			if (peer->state == DOWNLOADING) {
				stall *= 10;
				usleep(stall);	
			} else {
				/*
				 * don't return on failure here. we still need
				 * to do some cleanup
				 */
				status = HTTP_NOT_FOUND;
				break;
			}
		}
	}

	fclose(file);

#ifdef	TIMEIT
	gettimeofday(&end_time, NULL);
	s = (start_time.tv_sec * 1000000) + start_time.tv_usec;
	e = (end_time.tv_sec * 1000000) + end_time.tv_usec;
	logmsg("getremote:svc time5: %lld usec\n", (e - s));
#endif

	/*
	 * we downloaded the file from a peer, so read it and output it
	 * to stdout
	 */
	if ((status >= HTTP_OK) && (status <= HTTP_MULTI_STATUS)) {
		/*
		 * now do an atomic move
		 */
		if (rename(tempfilename, filename) < 0) {
			logmsg("getremote:rename():failed:(%d)\n", errno);
			free(tempfilename);
			return(-1);
		}
		
		if (outputfile(filename, range) != 0) {
			logmsg("getremote:outputfile():failed:(%d)\n", errno);
			free(tempfilename);
			return(-1);
		}
	} else {
		/*
		 * on a failure, a zero-byte length file will be
		 * left on the disk -- this is because of the fopen().
		 * remove this zero-length file.
		 */
		unlink(filename);
		unlink(tempfilename);
		free(tempfilename);
		return(-1);	
	}

#ifdef	TIMEIT
	gettimeofday(&end_time, NULL);
	s = (start_time.tv_sec * 1000000) + start_time.tv_usec;
	e = (end_time.tv_sec * 1000000) + end_time.tv_usec;
	logmsg("getremote:svc time6: %lld usec\n", (e - s));
#endif

	free(tempfilename);
	return(0);
}
Example #19
0
/****************************************************************************
 * WindowPrompt
 *
 * Displays a prompt window to user, with information, an error message, or
 * presenting a user with a choice
 ***************************************************************************/
void
updatePrompt(string rev)
{
//	bool stop = true;

	GuiWindow promptWindow(520,360);
	promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	promptWindow.SetPosition(0, -10);
	GuiTrigger trigA;
	trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);


	GuiImageData dialogBox(Theme.dialog_background);
	GuiImage dialogBoxImg(&dialogBox);

	GuiImageData btnOutline(Theme.button_small);
	GuiImage btn1Img(&btnOutline);
	GuiImage btn2Img(&btnOutline);

	GuiImageData btnOutlineOver(Theme.button_small_focus);
	GuiImage btn1ImgOver(&btnOutlineOver);
	GuiImage btn2ImgOver(&btnOutlineOver);

	GuiText titleTxt(tr("Update"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
	titleTxt.SetPosition(0, 40);
	GuiText downloadTxt(tr("Downloading file..."), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	downloadTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	downloadTxt.SetPosition(0, -20);

	GuiText msgTxt(tr("please wait"), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});
	msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
	msgTxt.SetPosition(0, 20);

	GuiText btn1Txt(tr("Yes"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255});
	GuiButton btn1(btnOutline.GetWidth(), btnOutline.GetHeight());

	btn1.SetAlignment(ALIGN_LEFT, ALIGN_BOTTOM);
	btn1.SetPosition(20, -25);
	btn1.SetLabel(&btn1Txt);
	btn1.SetImage(&btn1Img);
	btn1.SetImageOver(&btn1ImgOver);
	btn1.SetTrigger(&trigA);
	btn1.SetState(STATE_SELECTED);
	btn1.SetEffectGrow();

	GuiText btn2Txt(tr("No"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255});
	GuiButton btn2(btnOutline.GetWidth(), btnOutline.GetHeight());

	btn2.SetAlignment(ALIGN_RIGHT, ALIGN_BOTTOM);
	btn2.SetPosition(-20, -25);
	btn2.SetLabel(&btn2Txt);
	btn2.SetImage(&btn2Img);
	btn2.SetImageOver(&btn2ImgOver);
	btn2.SetTrigger(&trigA);
	btn2.SetEffectGrow();

	promptWindow.Append(&dialogBoxImg);
	promptWindow.Append(&titleTxt);
	promptWindow.Append(&downloadTxt);
	promptWindow.Append(&msgTxt);

	HaltGui();
	mainWindow->SetState(STATE_DISABLED);
	mainWindow->Append(&promptWindow);
	mainWindow->ChangeFocus(&promptWindow);
	ResumeGui();

	char url[100];
#ifdef STBOOTVWII
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st.vwii/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st.vwii/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone/prev.dol").c_str(), std::ios_base::binary);
#elif VWII
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL.vwii/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL.vwii/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter.vWii/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter.vWii/prev.dol").c_str(), std::ios_base::binary);
#elif STDBOOT
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL.st/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter.Standalone/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter.Standalone/prev.dol").c_str(), std::ios_base::binary);
#else
	if(rev == "Beta")
		sprintf(url, "http://www.nanolx.org/hbf/DOL/Beta/boot.dol");
	else
		sprintf(url, "http://www.nanolx.org/hbf/DOL/rev%s/boot.dol", rev.c_str());

	// copy boot.dol to prev.dol
	std::ifstream infile((Settings.device_dat + ":/apps/HomebrewFilter/boot.dol").c_str(), std::ios_base::binary);
	std::ofstream outfile((Settings.device_dat + ":/apps/HomebrewFilter/prev.dol").c_str(), std::ios_base::binary);
#endif

	outfile << infile.rdbuf();

	struct block file = downloadfile(url);
	if (file.data && file.size > 0)
	{
		// write file
#ifdef STBOOTVWII
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter.vWii.Standalone/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#elif VWII
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter.vWii").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter.vWii").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter.vWii/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#elif STDBOOT
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter.Standalone").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter.Standalone").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter.Standalone/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#else
		if(opendir(check_path(Settings.device_dat + ":/apps/HomebrewFilter").c_str()) == NULL)
				mkdir((Settings.device_dat + ":/apps/HomebrewFilter").c_str(), 0777);

		FILE * data = fopen((Settings.device_dat + ":/apps/HomebrewFilter/boot.dol").c_str(), "wb");
		if(data)
		{
			fwrite(file.data, 1, file.size, data);
			fclose(data);
		}
#endif
		if(file.data)
			free(file.data);

		boot_buffer = true;
		updatehbf = true;
	}
	else
	{
		if(file.data)
			free(file.data);
	}

	HaltGui();
	mainWindow->Remove(&promptWindow);
	mainWindow->SetState(STATE_DEFAULT);
	ResumeGui();
}
Example #20
0
int DownloadAllLanguageFiles(int revision)
{
	if(!CreateSubfolder(Settings.languagefiles_path))
	{
		ShowError(tr("Could not create path: %s"), Settings.languagefiles_path);
		return -1;
	}

	if(!IsNetworkInit())
	{
		ShowError(tr("Network is not initiated."));
		return -2;
	}
	char fullURL[300];

	URL_List LinkList(LanguageFilesURL);
	int listsize = LinkList.GetURLCount();
	int files_downloaded = 0;
	char target[6];
	if(revision > 0)
		snprintf(target, sizeof(target), "%d", revision);
	else
		snprintf(target, sizeof(target), "%s", GetRev());

	ShowProgress(tr("Updating Language Files:"), 0, 0, 0, listsize, false, true);

	for (int i = 0; i < listsize; i++)
	{
		const char * filename = strrchr(LinkList.GetURL(i), '/');
		if(filename) filename++;
		else filename = LinkList.GetURL(i);

		if(!filename)
			continue;

		const char * FileExt = strrchr(filename, '.');
		if (!FileExt || strcasecmp(FileExt, ".lang") != 0)
			continue;

		debughelper_printf("%s\n", filename);

		ShowProgress(tr("Updating Language Files:"), 0, filename, i, listsize, false, true);

		snprintf(fullURL, sizeof(fullURL), "%s%s?p=%s", LanguageFilesURL, filename, target);

		struct block file = downloadfile(fullURL);
		if (file.data)
		{
			char filepath[300];
			snprintf(filepath, sizeof(filepath), "%s/%s", Settings.languagefiles_path, filename);
			FILE * pfile = fopen(filepath, "wb");
			if(pfile)
			{
				fwrite(file.data, 1, file.size, pfile);
				fclose(pfile);
				files_downloaded++;
			}
			free(file.data);
		}
	}

	ProgressStop();

	// reload current language file
	if(Settings.language_path[0] != 0)
		Settings.LoadLanguage(Settings.language_path, CONSOLE_DEFAULT);
	else
		Settings.LoadLanguage(NULL, CONSOLE_DEFAULT);

	return files_downloaded;
}
Example #21
0
/**
 * Downloads the contents of a URL to memory
 * This method is not threadsafe (because networking is not threadsafe on the Wii)
 */
struct block downloadfile(const char *url)
{
	int sslcontext = -1;

	//Check if the url starts with "http://", if not it is not considered a valid url
	if (strncmp(url, "http://", strlen("http://")) == 0)
		http_port = 80;
	else if(strncmp(url, "https://", strlen("https://")) == 0)
	{
		http_port = 443;
		gprintf("Initializing ssl...\n");
		if(ssl_init() < 0)
			return emptyblock;
	}
	else
		return emptyblock;

	//Locate the path part of the url by searching for '/' past "http://"
	char *path = 0;
	if(http_port == 443)
		path = strchr(url + strlen("https://"), '/');
	else
		path = strchr(url + strlen("http://"), '/');

	//At the very least the url has to end with '/', ending with just a domain is invalid
	if (path == NULL)
	{
		//printf("URL '%s' has no PATH part\n", url);
		return emptyblock;
	}

	//Extract the domain part out of the url
	int domainlength = path - url - strlen("http://") - (http_port == 443 ? 1 : 0);

	if (domainlength == 0)
	{
		//printf("No domain part in URL '%s'\n", url);
		return emptyblock;
	}

	char domain[domainlength + 1];
	strlcpy(domain, url + strlen("http://") + (http_port == 443 ? 1 : 0), domainlength + 1);

	//Parsing of the URL is done, start making an actual connection
	u32 ipaddress = getipbynamecached(domain);

	if (ipaddress == 0)
	{
		//printf("\ndomain %s could not be resolved", domain);
		return emptyblock;
	}

	s32 connection = tcp_connect(ipaddress, http_port);

	if (connection < 0)
	{
		//printf("Error establishing connection");
		return emptyblock;
	}

	if(http_port == 443)
	{
		//patched out anyways so just to set something
		sslcontext = ssl_new((u8*)domain,0);

		if(sslcontext < 0)
		{
			//gprintf("ssl_new\n");
			result = HTTPR_ERR_CONNECT;
			net_close (connection);
			return emptyblock;
		}
		//patched out anyways so just to set something
		ssl_setbuiltinclientcert(sslcontext,0);
		if(ssl_connect(sslcontext,connection) < 0)
		{
			//gprintf("ssl_connect\n");
			result = HTTPR_ERR_CONNECT;
			ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
		int ret = ssl_handshake(sslcontext);
		if(ret < 0)
		{
			//gprintf("ssl_handshake %i\n", ret);
			result = HTTPR_ERR_STATUS;
			ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
	}

	// Remove Referer from the request header for incompatible websites (ex. Cloudflare proxy)
	char referer[domainlength + 12];
	snprintf(referer, sizeof(referer), "Referer: %s\r\n", domain);
	if(strstr(url, "geckocodes"))
	{
		strcpy(referer, "");
	}

	//Form a nice request header to send to the webserver
	char* headerformat = "GET %s HTTP/1.0\r\nHost: %s\r\n%sUser-Agent: USBLoaderGX r%s\r\n\r\n";
	char header[strlen(headerformat) + strlen(path) + strlen(domain) + strlen(referer) + 100];
	sprintf(header, headerformat, path, domain, referer, GetRev());
	//gprintf("\nHTTP Request:\n");
	//gprintf("%s\n",header);

	//Do the request and get the response
	tcp_write(http_port == 443 ? sslcontext : connection, header);
	read_header( http_port == 443 ? sslcontext : connection);

	if (http_status >= 400) // Not found
	{
		//gprintf("HTTP ERROR: %d\n", http_status);
		return emptyblock;
	}

	if(!content_length)
		content_length = 0;

	// create data buffer to return
	struct block response;
	response.data = malloc(content_length);
	response.size = content_length;
	if (response.data == NULL)
	{
		return emptyblock;
	}

	if (http_status == 200)
	{
		if(displayProgressWindow)
		{
			ProgressCancelEnable(true);
			StartProgress(tr("Downloading file..."), tr("Please wait"), 0, false, false);
		}

		int ret = tcp_readData(http_port == 443 ? sslcontext : connection, &response.data, content_length);
		if(!ret)
		{
			free(response.data);
			result = HTTPR_ERR_RECEIVE;
			if(http_port == 443)
				ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
	}
	else if (http_status == 302) // 302 FOUND (redirected link)
	{
		// close current connection
		if(http_port == 443)
			ssl_shutdown(sslcontext);
		net_close (connection);

		// prevent infinite loops
		retryloop++;
		if(retryloop > 3)
		{
			retryloop = 0;
			return emptyblock;
		}

		struct block redirected = downloadfile(content_location);
		if(redirected.size == 0)
			return emptyblock;

		// copy the newURL data into the original data
		u8 * tmp = realloc(response.data, redirected.size);
		if (tmp == NULL)
		{
			gprintf("Could not allocate enough memory for new URL. Download canceled.\n");
			free(response.data);
			response.size = 0;
			free(redirected.data);
			result = HTTPR_ERR_RECEIVE;
			if(http_port == 443)
				ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
		response.data = tmp;
		memcpy(response.data, redirected.data, redirected.size);
		free(redirected.data);
		response.size = redirected.size;

	}
	retryloop = 0;
	
	// reset progress window if used
	if(displayProgressWindow)
	{
		ProgressStop();
		ProgressCancelEnable(false);
		displayProgressWindow = false;
	}

	return response;
}