Exemple #1
0
void rdp_free(rdpRdp* rdp)
{
    if (rdp)
    {
        crypto_rc4_free(rdp->rc4_decrypt_key);
        crypto_rc4_free(rdp->rc4_encrypt_key);
        crypto_des3_free(rdp->fips_encrypt);
        crypto_des3_free(rdp->fips_decrypt);
        crypto_hmac_free(rdp->fips_hmac);
        freerdp_settings_free(rdp->settings);
        freerdp_settings_free(rdp->settingsCopy);
        transport_free(rdp->transport);
        license_free(rdp->license);
        input_free(rdp->input);
        update_free(rdp->update);
        fastpath_free(rdp->fastpath);
        nego_free(rdp->nego);
        mcs_free(rdp->mcs);
        redirection_free(rdp->redirection);
        autodetect_free(rdp->autodetect);
        heartbeat_free(rdp->heartbeat);
        multitransport_free(rdp->multitransport);
        bulk_free(rdp->bulk);
        free(rdp);
    }
}
//---------------------------------------------------------------------
int update_ota_cloud(char *repository, char *file_path)
{
	update_cfg_cloud_t *pUpdateCfg;
	
	if(TaskOTA){
		printf("\n\r[%s] Update task has created.", __FUNCTION__);
		return 0;
	}
	pUpdateCfg = update_malloc(sizeof(update_cfg_cloud_t));
	if(pUpdateCfg == NULL){
		printf("\n\r[%s] Alloc update cfg failed.", __FUNCTION__);
		goto exit;
	}
	if(strlen(repository) > (REPOSITORY_LEN-1)){
		printf("\n\r[%s] Repository length is too long.", __FUNCTION__);
		goto exit;
	}
	if(strlen(file_path) > (FILE_PATH_LEN-1)){
		printf("\n\r[%s] File path length is too long.", __FUNCTION__);
		goto exit;
	}
	strcpy((char*)pUpdateCfg->repository, repository);
	strcpy((char*)pUpdateCfg->file_path, file_path);

	TaskOTA = sys_thread_new("OTA_server", update_ota_cloud_task, pUpdateCfg, STACK_SIZE, TASK_PRIORITY);
	if(TaskOTA == NULL){	  	
		printf("\n\r[%s] Create update task failed", __FUNCTION__);
		goto exit;
	}

exit:
	update_free(pUpdateCfg);
	return 0;
}
Exemple #3
0
void rdp_free(rdpRdp* rdp)
{
	if (rdp != NULL)
	{
		settings_free(rdp->settings);
		transport_free(rdp->transport);
		license_free(rdp->license);
		input_free(rdp->input);
		update_free(rdp->update);
		mcs_free(rdp->mcs);
		xfree(rdp);
	}
}
Exemple #4
0
void rdp_free(rdpRdp* rdp)
{
	if (rdp != NULL)
	{
		settings_free(rdp->settings);
		transport_free(rdp->transport);
		license_free(rdp->license);
		input_free(rdp->input);
		update_free(rdp->update);
		fastpath_free(rdp->fastpath);
		nego_free(rdp->nego);
		mcs_free(rdp->mcs);
		redirection_free(rdp->redirection);
		mppc_free(rdp);
		xfree(rdp);
	}
}
Exemple #5
0
void rdp_free(rdpRdp* rdp)
{
	if (rdp != NULL)
	{
		crypto_rc4_free(rdp->rc4_decrypt_key);
		crypto_rc4_free(rdp->rc4_encrypt_key);
		crypto_des3_free(rdp->fips_encrypt);
		crypto_des3_free(rdp->fips_decrypt);
		crypto_hmac_free(rdp->fips_hmac);
		extension_free(rdp->extension);
		settings_free(rdp->settings);
		transport_free(rdp->transport);
		license_free(rdp->license);
		input_free(rdp->input);
		update_free(rdp->update);
		fastpath_free(rdp->fastpath);
		nego_free(rdp->nego);
		mcs_free(rdp->mcs);
		redirection_free(rdp->redirection);
		mppc_free(rdp);
		xfree(rdp);
	}
}
//---------------------------------------------------------------------
int update_ota_local(char *ip, int port)
{
	update_cfg_local_t *pUpdateCfg;
	
	if(TaskOTA){
		printf("\n\r[%s] Update task has created.", __FUNCTION__);
		return 0;
	}
	pUpdateCfg = update_malloc(sizeof(update_cfg_local_t));
	if(pUpdateCfg == NULL){
		printf("\n\r[%s] Alloc update cfg failed", __FUNCTION__);
		return -1;
	}
	pUpdateCfg->ip_addr = inet_addr(ip);
	pUpdateCfg->port = ntohs(port);

	TaskOTA = sys_thread_new("OTA_server", update_ota_local_task, pUpdateCfg, STACK_SIZE, TASK_PRIORITY);
	if(TaskOTA == NULL){
	  	update_free(pUpdateCfg);
		printf("\n\r[%s] Create update task failed", __FUNCTION__);
	}
	return 0;
}
Exemple #7
0
rdpRdp* rdp_new(rdpContext* context)
{
    rdpRdp* rdp;
    DWORD flags;
    BOOL newSettings = FALSE;

    rdp = (rdpRdp*) calloc(1, sizeof(rdpRdp));
    if (!rdp)
        return NULL;

    rdp->context = context;
    rdp->instance = context->instance;

    flags = 0;

    if (context->ServerMode)
        flags |= FREERDP_SETTINGS_SERVER_MODE;

    if (!context->settings)
    {
        context->settings = freerdp_settings_new(flags);
        if (!context->settings)
            goto out_free;
        newSettings = TRUE;
    }

    rdp->settings = context->settings;
    rdp->settings->instance = context->instance;

    if (context->instance)
        context->instance->settings = rdp->settings;

    rdp->transport = transport_new(rdp->settings);
    if (!rdp->transport)
        goto out_free_settings;

    rdp->transport->rdp = rdp;

    rdp->license = license_new(rdp);
    if (!rdp->license)
        goto out_free_transport;

    rdp->input = input_new(rdp);
    if (!rdp->input)
        goto out_free_license;

    rdp->update = update_new(rdp);
    if (!rdp->update)
        goto out_free_input;

    rdp->fastpath = fastpath_new(rdp);
    if (!rdp->fastpath)
        goto out_free_update;

    rdp->nego = nego_new(rdp->transport);
    if (!rdp->nego)
        goto out_free_fastpath;

    rdp->mcs = mcs_new(rdp->transport);
    if (!rdp->mcs)
        goto out_free_nego;

    rdp->redirection = redirection_new();
    if (!rdp->redirection)
        goto out_free_mcs;

    rdp->autodetect = autodetect_new();
    if (!rdp->autodetect)
        goto out_free_redirection;

    rdp->heartbeat = heartbeat_new();
    if (!rdp->heartbeat)
        goto out_free_autodetect;

    rdp->multitransport = multitransport_new();
    if (!rdp->multitransport)
        goto out_free_heartbeat;

    rdp->bulk = bulk_new(context);
    if (!rdp->bulk)
        goto out_free_multitransport;

    return rdp;

out_free_multitransport:
    multitransport_free(rdp->multitransport);
out_free_heartbeat:
    heartbeat_free(rdp->heartbeat);
out_free_autodetect:
    autodetect_free(rdp->autodetect);
out_free_redirection:
    redirection_free(rdp->redirection);
out_free_mcs:
    mcs_free(rdp->mcs);
out_free_nego:
    nego_free(rdp->nego);
out_free_fastpath:
    fastpath_free(rdp->fastpath);
out_free_update:
    update_free(rdp->update);
out_free_input:
    input_free(rdp->input);
out_free_license:
    license_free(rdp->license);
out_free_transport:
    transport_free(rdp->transport);
out_free_settings:
    if (newSettings)
        freerdp_settings_free(rdp->settings);
out_free:
    free(rdp);
    return NULL;
}
/*
 * Program entry point.
 */
int
main(int argc, char** argv)
{
        /*
         * Standard command-line parsing.
         */
        const HASH_T *options = parse_cmdline(argc, argv, arg_opts);
        if(options == NULL || hash_get(options, "help") != NULL) {
                show_usage(argc, argv, arg_opts);
                return EXIT_FAILURE;
        }

        const char *url = hash_get(options, "url");
        const char *principal = hash_get(options, "principal");
        CREDENTIALS_T *credentials = NULL;
        const char *password = hash_get(options, "credentials");
        if(password != NULL) {
                credentials = credentials_create_password(password);
        }
        const char *topic_name = hash_get(options, "topic");
        const long seconds = atol(hash_get(options, "seconds"));

        /*
         * Setup for condition variable.
         */
        apr_initialize();
        apr_pool_create(&pool, NULL);
        apr_thread_mutex_create(&mutex, APR_THREAD_MUTEX_UNNESTED, pool);
        apr_thread_cond_create(&cond, pool);

        /*
         * Create a session with the Diffusion server.
         */
        SESSION_T *session;
        DIFFUSION_ERROR_T error = { 0 };
        session = session_create(url, principal, credentials, NULL, NULL, &error);
        if(session == NULL) {
                fprintf(stderr, "TEST: Failed to create session\n");
                fprintf(stderr, "ERR : %s\n", error.message);
                return EXIT_FAILURE;
        }

        /*
         * Create a topic holding simple string content.
         */
        TOPIC_DETAILS_T *string_topic_details = create_topic_details_single_value(M_DATA_TYPE_STRING);
        const ADD_TOPIC_PARAMS_T add_topic_params = {
                .topic_path = topic_name,
                .details = string_topic_details,
                .on_topic_added = on_topic_added,
                .on_topic_add_failed = on_topic_add_failed,
                .on_discard = on_topic_add_discard,
        };

        apr_thread_mutex_lock(mutex);
        add_topic(session, add_topic_params);
        apr_thread_cond_wait(cond, mutex);
        apr_thread_mutex_unlock(mutex);

        topic_details_free(string_topic_details);

        /*
         * Define the handlers for add_update_source()
         */
        const UPDATE_SOURCE_REGISTRATION_PARAMS_T update_reg_params = {
                .topic_path = topic_name,
                .on_init = on_update_source_init,
                .on_registered = on_update_source_registered,
                .on_active = on_update_source_active,
                .on_standby = on_update_source_standby,
                .on_close = on_update_source_closed
        };

        /*
         * Register an updater.
         */
        apr_thread_mutex_lock(mutex);
        CONVERSATION_ID_T *updater_id = register_update_source(session, update_reg_params);
        apr_thread_cond_wait(cond, mutex);
        apr_thread_mutex_unlock(mutex);

        /*
         * Define default parameters for an update source.
         */
        UPDATE_SOURCE_PARAMS_T update_source_params_base = {
                .updater_id = updater_id,
                .topic_path = topic_name,
                .on_success = on_update_success,
                .on_failure = on_update_failure
        };

        time_t end_time = time(NULL) + seconds;

        while(time(NULL) < end_time) {

                if(active) {
                        /*
                         * Create an update structure containing the current time.
                         */
                        BUF_T *buf = buf_create();
                        const time_t time_now = time(NULL);
                        buf_write_string(buf, ctime(&time_now));

                        CONTENT_T *content = content_create(CONTENT_ENCODING_NONE, buf);

                        UPDATE_T *upd = update_create(UPDATE_ACTION_REFRESH,
                                                      UPDATE_TYPE_CONTENT,
                                                      content);

                        UPDATE_SOURCE_PARAMS_T update_source_params = update_source_params_base;
                        update_source_params.update = upd;

                        /*
                         * Update the topic.
                         */
                        update(session, update_source_params);

                        content_free(content);
                        update_free(upd);
                        buf_free(buf);
                }

                sleep(1);
        }

        if(active) {
                UPDATE_SOURCE_DEREGISTRATION_PARAMS_T update_dereg_params = {
                        .updater_id = updater_id,
                        .on_deregistered = on_update_source_deregistered
                };

                apr_thread_mutex_lock(mutex);
                deregister_update_source(session, update_dereg_params);
                apr_thread_cond_wait(cond, mutex);
                apr_thread_mutex_unlock(mutex);
        }

        /*
         * Close session and free resources.
         */
        session_close(session, NULL);
        session_free(session);

        conversation_id_free(updater_id);
        credentials_free(credentials);

        apr_thread_mutex_destroy(mutex);
        apr_thread_cond_destroy(cond);
        apr_pool_destroy(pool);
        apr_terminate();

        return EXIT_SUCCESS;

}
Exemple #9
0
NTSTATUS
WINAPI
VfatChkdsk(IN PUNICODE_STRING DriveRoot,
           IN BOOLEAN FixErrors,
           IN BOOLEAN Verbose,
           IN BOOLEAN CheckOnlyIfDirty,
           IN BOOLEAN ScanDrive,
           IN PFMIFSCALLBACK Callback)
{
#if 0
    BOOLEAN verify;
    BOOLEAN salvage_files;
#endif
    //ULONG free_clusters;
    //DOS_FS fs;

    /* Store callback pointer */
    ChkdskCallback = Callback;
    FsCheckMemQueue = NULL;

    /* Set parameters */
    FsCheckFlags = 0;
    if (Verbose)
        FsCheckFlags |= FSCHECK_VERBOSE;

    FsCheckTotalFiles = 0;

#if 0
    verify = TRUE;
    salvage_files = TRUE;

    /* Open filesystem */
    fs_open(DriveRoot,FixErrors);

    if (CheckOnlyIfDirty && !fs_isdirty())
    {
        /* No need to check FS */
        return fs_close(FALSE);
    }

    read_boot(&fs);
    if (verify)
        VfatPrint("Starting check/repair pass.\n");

    while (read_fat(&fs), scan_root(&fs))
        qfree(&FsCheckMemQueue);

    if (ScanDrive)
        fix_bad(&fs);

    if (salvage_files)
        reclaim_file(&fs);
    else
        reclaim_free(&fs);

    free_clusters = update_free(&fs);
    file_unused();
    qfree(&FsCheckMemQueue);
    if (verify)
    {
        VfatPrint("Starting verification pass.\n");
        read_fat(&fs);
        scan_root(&fs);
        reclaim_free(&fs);
        qfree(&FsCheckMemQueue);
    }

    if (fs_changed())
    {
        if (FixErrors)
        {
            if (FsCheckFlags & FSCHECK_INTERACTIVE)
                FixErrors = get_key("yn","Perform changes ? (y/n)") == 'y';
            else
                VfatPrint("Performing changes.\n");
        }
        else
        {
            VfatPrint("Leaving file system unchanged.\n");
        }
    }

    VfatPrint("%wZ: %u files, %lu/%lu clusters\n", DriveRoot,
        FsCheckTotalFiles, fs.clusters - free_clusters, fs.clusters );

    if (FixErrors)
    {
        /* Dismount the volume */
        fs_dismount();

        /* Unlock the volume */
        fs_lock(FALSE);
    }

    /* Close the volume */
    return fs_close(FixErrors) ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL;
#else
    return STATUS_SUCCESS;
#endif
}
int cardpeek_update_perform(void)
{
    const char* cardpeek_update_file = path_config_get_string(PATH_CONFIG_FILE_CARDPEEK_UPDATE);
    a_string_t *contents;
    update_t *update;
    int remove;
    update_item_t *item;
    time_t now = time(NULL);
    int updated = 0;
    char *url = NULL;
    char *local_file;
    char *local_dnld;
    unsigned char digest[SHA256_DIGEST_LENGTH];
    a_string_t *url_request;
    unsigned first_update;

    first_update = (unsigned)luax_variable_get_integer("cardpeek.updates.first_update");
    
    /* STEP 1: get cardpeek.update file */

    url=luax_variable_get_strdup("cardpeek.updates.url");

    if (url==NULL)
        url = g_strdup(DEFAULT_UPDATE_URL);

    log_printf(LOG_INFO,"Fetching '%s'",url);

    url_request = a_strnew(NULL);
    a_sprintf(url_request,"%s?u=%x&v=%s",url,first_update,VERSION);

    if (http_download(a_strval(url_request),cardpeek_update_file)==0)
    {
        g_free(url);
        return 0;
    }
    g_free(url);
    a_strfree(url_request);


    /* STEP 2: parse file */

    if ((contents=file_get_contents(cardpeek_update_file))==NULL)
    {
        log_printf(LOG_ERROR,"failed to read update file information.");
        unlink(cardpeek_update_file);
        return 0;
    }

    update = update_new();

    if ((update_load(update,a_strval(contents),a_strlen(contents)))==0)
    {
        unlink(cardpeek_update_file);
        a_strfree(contents);
        update_free(update);
        return 0;
    }
    a_strfree(contents);

    /* log_printf(LOG_DEBUG,"Updates correctly loaded from '%s'",cardpeek_update_file); */
    if ((remove = update_filter_version(update,VERSION))>0)
        log_printf(LOG_WARNING,"%d updates will not be installed because they require a newer version of Cardpeek.");
    
    remove = update_filter_files(update);

    if (update->item_count)
        log_printf(LOG_INFO,"A total of %d files will be updated, %d files are kept unchanged.",update->item_count,remove);
    else
        log_printf(LOG_INFO,"No files will be updated, %d files are kept unchanged.",remove);

    item = update->items;

    while (item)
    {
        local_dnld = new_path(PATH_CONFIG_FOLDER_CARDPEEK,item->file,".download");
        local_file = new_path(PATH_CONFIG_FOLDER_CARDPEEK,item->file,NULL);

        if (http_download(item->url,local_dnld)!=0)
        {        
            if (sha256sum(local_dnld,digest))
            {
                if (memcmp(digest,bytestring_get_data(&item->digest),SHA256_DIGEST_LENGTH)==0)
                {
                    unlink(local_file);

                    if (rename(local_dnld,local_file)==0)
                    {
                        log_printf(LOG_INFO,"Successfuly updated %s", local_file);
                        updated++;
                    }
                    else
                    {
                        log_printf(LOG_ERROR,"Failed to copy %s to %s: %s", 
                                local_dnld,
                                local_file, 
                                strerror(errno));
                    }
                }
                else
                {
                    log_printf(LOG_WARNING,"File %s was not updated: authentication failed.",local_file);
                }
            }
            unlink(local_dnld);
        }
        g_free(local_dnld);
        g_free(local_file);
        item =  item->next; 
    }

    if (updated == update->item_count)
    {    
        luax_variable_set_integer("cardpeek.updates.next_update",(int)(now+7*(24*3600)));  
        luax_config_table_save();
    }

    unlink(cardpeek_update_file);
    update_free(update);

    /* STEP 3: finish */

    return 1;

}
Exemple #11
0
int main(int argc, char **argv)
{
    DOS_FS fs;
    int salvage_files, verify, c;
    uint32_t free_clusters = 0;

    memset(&fs, 0, sizeof(fs));
    salvage_files = verify = 0;
    rw = interactive = 1;
    check_atari();

    while ((c = getopt(argc, argv, "Aac:d:bflnprtu:vVwy")) != -1)
	switch (c) {
	case 'A':		/* toggle Atari format */
	    atari_format = !atari_format;
	    break;
	case 'a':
	case 'p':
	case 'y':
	    rw = 1;
	    interactive = 0;
	    salvage_files = 1;
	    break;
	case 'b':
	    rw = 0;
	    interactive = 0;
	    boot_only = 1;
	    break;
	case 'c':
	    set_dos_codepage(atoi(optarg));
	    break;
	case 'd':
	    file_add(optarg, fdt_drop);
	    break;
	case 'f':
	    salvage_files = 1;
	    break;
	case 'l':
	    list = 1;
	    break;
	case 'n':
	    rw = 0;
	    interactive = 0;
	    break;
	case 'r':
	    rw = 1;
	    interactive = 1;
	    break;
	case 't':
	    test = 1;
	    break;
	case 'u':
	    file_add(optarg, fdt_undelete);
	    break;
	case 'v':
	    verbose = 1;
	    break;
	case 'V':
	    verify = 1;
	    break;
	case 'w':
	    write_immed = 1;
	    break;
	default:
	    usage(argv[0]);
	}
    set_dos_codepage(-1);	/* set default codepage if none was given in command line */
    if ((test || write_immed) && !rw) {
	fprintf(stderr, "-t and -w can not be used in read only mode\n");
	exit(2);
    }
    if (optind != argc - 1)
	usage(argv[0]);

    printf("fsck.fat " VERSION " (" VERSION_DATE ")\n");
    fs_open(argv[optind], rw);

    read_boot(&fs);
    if (boot_only)
	goto exit;

    if (verify)
	printf("Starting check/repair pass.\n");
    while (read_fat(&fs), scan_root(&fs))
	qfree(&mem_queue);
    if (test)
	fix_bad(&fs);
    if (salvage_files)
	reclaim_file(&fs);
    else
	reclaim_free(&fs);
    free_clusters = update_free(&fs);
    file_unused();
    qfree(&mem_queue);
    if (verify) {
	n_files = 0;
	printf("Starting verification pass.\n");
	read_fat(&fs);
	scan_root(&fs);
	reclaim_free(&fs);
	qfree(&mem_queue);
    }

exit:
    if (fs_changed()) {
	if (rw) {
	    if (interactive)
		rw = get_key("yn", "Perform changes ? (y/n)") == 'y';
	    else
		printf("Performing changes.\n");
	} else
	    printf("Leaving filesystem unchanged.\n");
    }

    if (!boot_only)
	printf("%s: %u files, %lu/%lu clusters\n", argv[optind],
	       n_files, (unsigned long)fs.clusters - free_clusters, (unsigned long)fs.clusters);

    return fs_close(rw) ? 1 : 0;
}
Exemple #12
0
int main(int argc,char **argv)
{
    DOS_FS fs;
    int rw,salvage_files,verify,c;
	unsigned n_files_check=0, n_files_verify=0;
    unsigned long free_clusters;

    rw = salvage_files = verify = 0;
    interactive = 1;
    check_atari();

    while ((c = getopt(argc,argv,"Aad:flnprtu:vVwy")) != EOF)
	switch (c) {
	    case 'A': /* toggle Atari format */
	  	atari_format = !atari_format;
		break;
	    case 'a':
	    case 'p':
	    case 'y':
		rw = 1;
		interactive = 0;
		salvage_files = 1;
		break;
	    case 'd':
		file_add(optarg,fdt_drop);
		break;
	    case 'f':
		salvage_files = 1;
		break;
	    case 'l':
		list = 1;
		break;
	    case 'n':
		rw = 0;
		interactive = 0;
		break;
	    case 'r':
		rw = 1;
		interactive = 1;
		break;
	    case 't':
		test = 1;
		break;
	    case 'u':
		file_add(optarg,fdt_undelete);
		break;
	    case 'v':
		verbose = 1;
		printf("dosfsck " VERSION " (" VERSION_DATE ")\n");
		break;
	    case 'V':
		verify = 1;
		break;
	    case 'w':
		write_immed = 1;
		break;
	    default:
		usage(argv[0]);
	}
    if ((test || write_immed) && !rw) {
	fprintf(stderr,"-t and -w require -a or -r\n");
	exit(2);
    }
    if (optind != argc-1) usage(argv[0]);

    printf( "dosfsck " VERSION ", " VERSION_DATE ", FAT32, LFN\n" );
    fs_open(argv[optind],rw);
    read_boot(&fs);
    if (verify) printf("Starting check/repair pass.\n");
    while (read_fat(&fs), scan_root(&fs)) qfree(&mem_queue);
    if (test) fix_bad(&fs);
    if (salvage_files) reclaim_file(&fs);
    else reclaim_free(&fs);
    free_clusters = update_free(&fs);
    file_unused();
    qfree(&mem_queue);
	n_files_check = n_files;
    if (verify) {
		n_files = 0;
		printf("Starting verification pass.\n");
		read_fat(&fs);
		scan_root(&fs);
		reclaim_free(&fs);
		qfree(&mem_queue);
		n_files_verify = n_files;
    }

    if (fs_changed()) {
	if (rw) {
	    if (interactive)
		rw = get_key("yn","Perform changes ? (y/n)") == 'y';
	    else printf("Performing changes.\n");
	}
	else
	    printf("Leaving file system unchanged.\n");
    }

    printf( "%s: %u files, %lu/%lu clusters\n", argv[optind],
	    n_files, fs.clusters - free_clusters, fs.clusters );

    return fs_close(rw) ? 1 : 0;
}
static void update_ota_local_task(void *param)
{
	int server_socket = 0;
	struct sockaddr_in server_addr;
	char *buf;
	int read_bytes, size = 0, i;
	update_cfg_local_t *cfg = (update_cfg_local_t*)param;
	uint32_t address, checksum = 0;
#if CONFIG_WRITE_MAC_TO_FLASH
	char mac[ETH_ALEN];
#endif
	printf("\n\r[%s] Update task start", __FUNCTION__);
	buf = update_malloc(BUF_SIZE);
	if(!buf){
		printf("\n\r[%s] Alloc buffer failed", __FUNCTION__);
		goto update_ota_exit;
	}
	// Connect socket
	server_socket = socket(AF_INET, SOCK_STREAM, 0);
	if(server_socket < 0){
		printf("\n\r[%s] Create socket failed", __FUNCTION__);
		goto update_ota_exit;
	}
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = cfg->ip_addr;
	server_addr.sin_port = cfg->port;

	if(connect(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1){
		printf("\n\r[%s] socket connect failed", __FUNCTION__);
		goto update_ota_exit;
	}
	// Erase config sectors
	if(flash_EraseSector(CONFIG_SECTOR) < 0){
		printf("\n\r[%s] Erase sector failed", __FUNCTION__);
		goto update_ota_exit;
	}
#if CONFIG_WRITE_MAC_TO_FLASH
	// Read MAC address
 	if(flash_Read(FLASH_ADD_STORE_MAC, mac, ETH_ALEN) < 0){
		printf("\n\r[%s] Read MAC error", __FUNCTION__);
		goto update_ota_exit;
 	}	
#endif
	// Erase update sectors
	for(i = UPDATE_SECTOR; i <= FLASH_Sector_11; i += 8){
		if(flash_EraseSector(i) < 0){
			printf("\n\r[%s] Erase sector failed", __FUNCTION__);
			goto update_ota_exit;
		}
	}
	// Write update sectors
	address = flash_SectorAddress(UPDATE_SECTOR);
	printf("\n\r");
	while(1){
		read_bytes = read(server_socket, buf, BUF_SIZE);
		if(read_bytes == 0) break; // Read end
		if(read_bytes < 0){
			printf("\n\r[%s] Read socket failed", __FUNCTION__);
			goto update_ota_exit;
		}
		if(flash_Wrtie(address + size, buf, read_bytes) < 0){
			printf("\n\r[%s] Write sector failed", __FUNCTION__);
			goto update_ota_exit;
		}
		size += read_bytes;
		for(i = 0; i < read_bytes; i ++)
			checksum += buf[i];
		printf("\rUpdate file size = %d  ", size);
	}
#if CONFIG_WRITE_MAC_TO_FLASH
	//Write MAC address
	if(!(mac[0]==0xff&&mac[1]==0xff&&mac[2]==0xff&&mac[3]==0xff&&mac[4]==0xff&&mac[5]==0xff)){
		if(flash_Wrtie(FLASH_ADD_STORE_MAC, mac, ETH_ALEN) < 0){
			printf("\n\r[%s] Write MAC failed", __FUNCTION__);
			goto update_ota_exit;
		}	
	}
#endif
	// Write config sectors
	address = flash_SectorAddress(CONFIG_SECTOR);
	if( (flash_Wrtie(address, (char*)&size, 4) < 0) || 
		(flash_Wrtie(address+4, (char*)&checksum, 4) < 0) ){
		printf("\n\r[%s] Write sector failed", __FUNCTION__);
		goto update_ota_exit;
	}
	printf("\n\r[%s] Update OTA success!", __FUNCTION__);
update_ota_exit:
	if(buf)
		update_free(buf);
	if(server_socket >= 0)
		close(server_socket);
	if(param)
		update_free(param);
	TaskOTA = NULL;
	printf("\n\r[%s] Update task exit", __FUNCTION__);
	vTaskDelete(NULL);
	return;
}
static void update_ota_cloud_task(void *param)
{
	struct updater_ctx ctx;
	char *buf, flag_a = 0;
	int read_bytes, size = 0, i;
	uint32_t address, checksum = 0;
	update_cfg_cloud_t *cfg = (update_cfg_cloud_t*)param;
	uint16_t a = 0;
#if CONFIG_WRITE_MAC_TO_FLASH
	char mac[ETH_ALEN];
#endif	
	printf("\n\r[%s] Update task start", __FUNCTION__);
	buf = update_malloc(BUF_SIZE);
	if(!buf){
		printf("\n\r[%s] Alloc buffer failed", __FUNCTION__);
		goto update_ota_exit_1;
	}
	// Init ctx
	if(updater_init_ctx(&ctx, (char*)cfg->repository, (char*)cfg->file_path) != 0) {
		printf("\n\r[%s] Cloud ctx init failed", __FUNCTION__);
		goto update_ota_exit_1;
	}
	printf("\n\r[%s] Firmware link: %s, size = %d bytes, checksum = 0x%08x, version = %s\n", __FUNCTION__, 
		ctx.link, ctx.size, ctx.checksum, ctx.version);

	// Erase config sectors
	for(i = CONFIG_SECTOR; i < APPLICATION_SECTOR; i += FLASH_PAGE_SIZE){
		if(flash_EraseSector(i) < 0){
			printf("\n\r[%s] Erase sector failed", __FUNCTION__);
			goto update_ota_exit;
		}
	}
#if CONFIG_WRITE_MAC_TO_FLASH
	// Read MAC address
 	if(flash_Read(FLASH_ADD_STORE_MAC, mac, ETH_ALEN) < 0){
		printf("\n\r[%s] Read MAC error", __FUNCTION__);
		goto update_ota_exit;
 	}	
#endif

	// Erase update sectors
	for(i = UPDATE_SECTOR; i < FLASH_Sector_0 + FLASH_SIZE; i += FLASH_PAGE_SIZE){
		if(flash_EraseSector(i) < 0){
			printf("\n\r[%s] Erase sector failed", __FUNCTION__);
			goto update_ota_exit;
		}
	}
	// Write update sectors
	address = UPDATE_SECTOR;
	printf("\n\r");
	while(ctx.bytes < ctx.size){
		read_bytes = updater_read_bytes(&ctx, (unsigned char*)buf, BUF_SIZE);
		if(read_bytes == 0) break; // Read end
		if(read_bytes < 0){
			printf("\n\r[%s] Read socket failed", __FUNCTION__);
			goto update_ota_exit;
		}
		if(flag_a == 0){
			if(read_bytes % 2 != 0){
				a = buf[read_bytes - 1];
				flag_a = 1;
				if(flash_Wrtie(address + size, buf, read_bytes - 1) < 0){
					printf("\n\r[%s] Write sector failed", __FUNCTION__);
					goto update_ota_exit;
				}
				size += read_bytes - 1;
			}
			else{
				if(flash_Wrtie(address + size, buf, read_bytes) < 0){
					printf("\n\r[%s] Write sector failed", __FUNCTION__);
					goto update_ota_exit;
				}
				size += read_bytes;
			}
		}
		else{
			a = buf[0]<< 8 |a;
			if(flash_Wrtie(address + size, (char*)(&a), 2) < 0){
				printf("\n\r[%s] Write sector failed", __FUNCTION__);
				goto update_ota_exit;
			}
			size += 2;
			a = 0;
			flag_a = 0;
			if((read_bytes - 1) % 2 != 0){
				a = buf[read_bytes - 1];
				flag_a = 1;
				if(flash_Wrtie(address + size, buf + 1, read_bytes - 2) < 0){
					printf("\n\r[%s] Write sector failed", __FUNCTION__);
					goto update_ota_exit;
				}
				size += read_bytes - 2;
			}
			else{ 
				if(flash_Wrtie(address + size, buf + 1, read_bytes - 1) < 0){
					printf("\n\r[%s] Write sector failed", __FUNCTION__);
					goto update_ota_exit;
				}
				size += read_bytes - 1;
			}
		}	
		for(i = 0; i < read_bytes; i ++)
			checksum += buf[i];
		printf("\rUpdate file size = %d/%d bytes   ", ctx.bytes, ctx.size);
	}
	if(flag_a){
		if(flash_Wrtie(address + size, (char*)(&a), 2) < 0){
			printf("\n\r[%s] Write sector failed", __FUNCTION__);
			goto update_ota_exit;
		}
		size += 1;
	}
	printf("\n\r[%s] ctx checksum = %08x, computed checksum = %08x\n", __FUNCTION__, ctx.checksum, checksum);
	if(checksum != ctx.checksum){
		printf("\n\r[%s] Checksum error", __FUNCTION__);
		goto update_ota_exit;
	}
#if CONFIG_WRITE_MAC_TO_FLASH
	//Write MAC address
	if(!(mac[0]==0xff&&mac[1]==0xff&&mac[2]==0xff&&mac[3]==0xff&&mac[4]==0xff&&mac[5]==0xff)){
		if(flash_Wrtie(FLASH_ADD_STORE_MAC, mac, ETH_ALEN) < 0){
			printf("\n\r[%s] Write MAC failed", __FUNCTION__);
			goto update_ota_exit;
		}	
	}
#endif

	// Write config sectors
	address = CONFIG_SECTOR;
	if( (flash_Wrtie(address, (char*)&size, 4) < 0) || 
		(flash_Wrtie(address+4, (char*)&checksum, 4) < 0) ){
		printf("\n\r[%s] Write sector failed", __FUNCTION__);
		goto update_ota_exit;
	}
	printf("\n\r[%s] Update OTA success!", __FUNCTION__);
	
update_ota_exit:
	updater_free_ctx(&ctx);
update_ota_exit_1:
	if(buf)
		update_free(buf);
	if(param)
		update_free(param);
	TaskOTA = NULL;
	printf("\n\r[%s] Update task exit", __FUNCTION__);
	vTaskDelete(NULL);
	return;
}
static void update_ota_local_task(void *param)
{
	int server_socket;
	struct sockaddr_in server_addr;
	unsigned char *buf;
        union { uint32_t u; unsigned char c[4]; } file_checksum;
	int read_bytes = 0, size = 0, i = 0;
	update_cfg_local_t *cfg = (update_cfg_local_t *)param;
	uint32_t address, checksum = 0;
	flash_t	flash;
	uint32_t NewImg2BlkSize = 0, NewImg2Len = 0, NewImg2Addr = 0, file_info[3];
	uint32_t Img2Len = 0;
	int ret = -1 ;
	//uint8_t signature[8] = {0x38,0x31,0x39,0x35,0x38,0x37,0x31,0x31};
	uint32_t IMAGE_x = 0, ImgxLen = 0, ImgxAddr = 0;
#if WRITE_OTA_ADDR
	uint32_t ota_addr = 0x80000;
#endif
#if CONFIG_CUSTOM_SIGNATURE
	char custom_sig[32] = "Customer Signature-modelxxx";
	uint32_t read_custom_sig[8];
#endif
	printf("\n\r[%s] Update task start", __FUNCTION__);
	buf = update_malloc(BUF_SIZE);
	if(!buf){
		printf("\n\r[%s] Alloc buffer failed", __FUNCTION__);
		goto update_ota_exit;
	}
	// Connect socket
	server_socket = socket(AF_INET, SOCK_STREAM, 0);
	if(server_socket < 0){
		printf("\n\r[%s] Create socket failed", __FUNCTION__);
		goto update_ota_exit;
	}
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = cfg->ip_addr;
	server_addr.sin_port = cfg->port;

	if(connect(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1){
		printf("\n\r[%s] socket connect failed", __FUNCTION__);
		goto update_ota_exit;
	}
	DBG_INFO_MSG_OFF(_DBG_SPI_FLASH_);

#if 1
	// The upgraded image2 pointer must 4K aligned and should not overlap with Default Image2
	flash_read_word(&flash, IMAGE_2, &Img2Len);
	IMAGE_x = IMAGE_2 + Img2Len + 0x10;
	flash_read_word(&flash, IMAGE_x, &ImgxLen);
	flash_read_word(&flash, IMAGE_x+4, &ImgxAddr);
	if(ImgxAddr==0x30000000){
		printf("\n\r[%s] IMAGE_3 0x%x Img3Len 0x%x", __FUNCTION__, IMAGE_x, ImgxLen);
	}else{
		printf("\n\r[%s] no IMAGE_3", __FUNCTION__);
		// no image3
		IMAGE_x = IMAGE_2;
		ImgxLen = Img2Len;
	}
#if WRITE_OTA_ADDR
	if((ota_addr > IMAGE_x) && ((ota_addr < (IMAGE_x+ImgxLen))) ||
            (ota_addr < IMAGE_x) ||
            ((ota_addr & 0xfff) != 0)||
	      (ota_addr == ~0x0)){
		printf("\n\r[%s] illegal ota addr 0x%x", __FUNCTION__, ota_addr);
		goto update_ota_exit;
	}else
	    write_ota_addr_to_system_data( &flash, ota_addr);
#endif
	//Get upgraded image 2 addr from offset
	flash_read_word(&flash, OFFSET_DATA, &NewImg2Addr);
	if((NewImg2Addr > IMAGE_x) && ((NewImg2Addr < (IMAGE_x+ImgxLen))) ||
            (NewImg2Addr < IMAGE_x) ||
            ((NewImg2Addr & 0xfff) != 0)||
	      (NewImg2Addr == ~0x0)){
		printf("\n\r[%s] Invalid OTA Address 0x%x", __FUNCTION__, NewImg2Addr);
		goto update_ota_exit;
	}
#else
	//For test, hard code addr
	NewImg2Addr = 0x80000;	
#endif
	
	//Clear file_info
	memset(file_info, 0, sizeof(file_info));
	
	if(file_info[0] == 0){
		printf("\n\r[%s] Read info first", __FUNCTION__);
		read_bytes = read(server_socket, file_info, sizeof(file_info));
		// !X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X
		// !W checksum !W padding 0 !W file size !W
		// !X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X!X
		printf("\n\r[%s] info %d bytes", __FUNCTION__, read_bytes);
		printf("\n\r[%s] tx chechsum 0x%x, file size 0x%x", __FUNCTION__, file_info[0],file_info[2]);
		if(file_info[2] == 0){
			printf("\n\r[%s] No checksum and file size", __FUNCTION__);
			goto update_ota_exit;
		}
	}
	
#if SWAP_UPDATE
	uint32_t SigImage0,SigImage1;
	uint32_t Part1Addr=0xFFFFFFFF, Part2Addr=0xFFFFFFFF, ATSCAddr=0xFFFFFFFF;
	uint32_t OldImg2Addr;
	flash_read_word(&flash, 0x18, &Part1Addr);
	Part1Addr = (Part1Addr&0xFFFF)*1024;	// first partition
	Part2Addr = NewImg2Addr;
	
	// read Part1/Part2 signature
	flash_read_word(&flash, Part1Addr+8, &SigImage0);
	flash_read_word(&flash, Part1Addr+12, &SigImage1);
	printf("\n\r[%s] Part1 Sig %x", __FUNCTION__, SigImage0);
	if(SigImage0==0x30303030 && SigImage1==0x30303030)
		ATSCAddr = Part1Addr;		// ATSC signature
	else if(SigImage0==0x35393138 && SigImage1==0x31313738)	
		OldImg2Addr = Part1Addr;	// newer version, change to older version
	else
		NewImg2Addr = Part1Addr;	// update to older version	
	
	flash_read_word(&flash, Part2Addr+8, &SigImage0);
	flash_read_word(&flash, Part2Addr+12, &SigImage1);
	printf("\n\r[%s] Part2 Sig %x", __FUNCTION__, SigImage0);
	if(SigImage0==0x30303030 && SigImage1==0x30303030)
		ATSCAddr = Part2Addr;		// ATSC signature
	else if(SigImage0==0x35393138 && SigImage1==0x31313738)
		OldImg2Addr = Part2Addr;
	else
		NewImg2Addr = Part2Addr;
	
	// update ATSC clear partitin first
	if(ATSCAddr != ~0x0){
		OldImg2Addr = NewImg2Addr;
		NewImg2Addr = ATSCAddr;
	}
	
	printf("\n\r[%s] New %x, Old %x", __FUNCTION__, NewImg2Addr, OldImg2Addr);
	
	if( NewImg2Addr==Part1Addr ){
		if( file_info[2] > (Part2Addr-Part1Addr) ){	// firmware size too large
			printf("\n\r[%s] Part1 size < OTA size", __FUNCTION__);
			goto update_ota_exit;
			// or update to partition2
			// NewImg2Addr = Part2Addr;	
		}
	}
		
#endif

	//Erase upgraded image 2 region
	if(NewImg2Len == 0){
		NewImg2Len = file_info[2];
		printf("\n\r[%s] NewImg2Len %d  ", __FUNCTION__, NewImg2Len);
		if((int)NewImg2Len > 0){
			NewImg2BlkSize = ((NewImg2Len - 1)/4096) + 1;
			printf("\n\r[%s] NewImg2BlkSize %d  0x%8x", __FUNCTION__, NewImg2BlkSize, NewImg2BlkSize);
			for( i = 0; i < NewImg2BlkSize; i++)
				flash_erase_sector(&flash, NewImg2Addr + i * 4096);
		}else{
			printf("\n\r[%s] Size INVALID", __FUNCTION__);
			goto update_ota_exit;
		}
	}	
	
	printf("\n\r[%s] NewImg2Addr 0x%x", __FUNCTION__, NewImg2Addr);
        
        // reset
        file_checksum.u = 0;
	// Write New Image 2 sector
	if(NewImg2Addr != ~0x0){
		address = NewImg2Addr;
		printf("\n\r");
		while(1){
			memset(buf, 0, BUF_SIZE);
			read_bytes = read(server_socket, buf, BUF_SIZE);
			if(read_bytes == 0) break; // Read end
			if(read_bytes < 0){
				printf("\n\r[%s] Read socket failed", __FUNCTION__);
				goto update_ota_exit;
			}
				checksum += file_checksum.c[0];              // not read end, this is not attached checksum
				checksum += file_checksum.c[1];
				checksum += file_checksum.c[2];
				checksum += file_checksum.c[3];
			//printf("\n\r[%s] read_bytes %d", __FUNCTION__, read_bytes);
			
			#if 1
			if(flash_stream_write(&flash, address + size, read_bytes, buf) < 0){
				printf("\n\r[%s] Write sector failed", __FUNCTION__);
				goto update_ota_exit;
			}
			size += read_bytes;
			for(i = 0; i < read_bytes-4; i ++)
				checksum += buf[i];
			file_checksum.c[0] = buf[read_bytes-4];      // checksum attached at file end
			file_checksum.c[1] = buf[read_bytes-3];
			file_checksum.c[2] = buf[read_bytes-2];
			file_checksum.c[3] = buf[read_bytes-1];
			#else
			size += read_bytes;
			for(i = 0; i < read_bytes-4; i ++){
				checksum += buf[i];				
			}	
			file_checksum.c[0] = buf[read_bytes-4];      // checksum attached at file end
			file_checksum.c[1] = buf[read_bytes-3];
			file_checksum.c[2] = buf[read_bytes-2];
			file_checksum.c[3] = buf[read_bytes-1];
			#endif			
		}
		printf("\n\r");
		printf("\n\rUpdate file size = %d  checksum 0x%x  attached checksum 0x%x", size, checksum, file_checksum.u);
#if CONFIG_WRITE_MAC_TO_FLASH
		//Write MAC address
		if(!(mac[0]==0xff&&mac[1]==0xff&&mac[2]==0xff&&mac[3]==0xff&&mac[4]==0xff&&mac[5]==0xff)){
			if(flash_write_word(&flash, FLASH_ADD_STORE_MAC, mac, ETH_ALEN) < 0){
				printf("\n\r[%s] Write MAC failed", __FUNCTION__);
				goto update_ota_exit;
			}	
		}
#endif
		//printf("\n\r checksum 0x%x  file_info 0x%x  ", checksum, *(file_info));
#if CONFIG_CUSTOM_SIGNATURE
		for(i = 0; i < 8; i ++){
		    flash_read_word(&flash, NewImg2Addr + 0x28 + i *4, read_custom_sig + i);
		}
		printf("\n\r[%s] read_custom_sig %s", __FUNCTION__ , (char*)read_custom_sig);
#endif
		// compare checksum with received checksum
		//if(!memcmp(&checksum,file_info,sizeof(checksum))
		if( (file_checksum.u == checksum)
#if CONFIG_CUSTOM_SIGNATURE
			&& !strcmp((char*)read_custom_sig,custom_sig)
#endif
			){
			
			//Set signature in New Image 2 addr + 8 and + 12
			uint32_t sig_readback0,sig_readback1;
			flash_write_word(&flash,NewImg2Addr + 8, 0x35393138);
			flash_write_word(&flash,NewImg2Addr + 12, 0x31313738);
			flash_read_word(&flash, NewImg2Addr + 8, &sig_readback0);
			flash_read_word(&flash, NewImg2Addr + 12, &sig_readback1);
			printf("\n\r[%s] signature %x,%x,  checksum 0x%x", __FUNCTION__ , sig_readback0, sig_readback1, checksum);
#if SWAP_UPDATE
			if(OldImg2Addr != ~0x0){
				flash_write_word(&flash,OldImg2Addr + 8, 0x35393130);
				flash_write_word(&flash,OldImg2Addr + 12, 0x31313738);
				flash_read_word(&flash, OldImg2Addr + 8, &sig_readback0);
				flash_read_word(&flash, OldImg2Addr + 12, &sig_readback1);
				printf("\n\r[%s] old signature %x,%x", __FUNCTION__ , sig_readback0, sig_readback1);
			}
#endif			
			printf("\n\r[%s] Update OTA success!", __FUNCTION__);
			
			ret = 0;
		}
	}
update_ota_exit:
	if(buf)
		update_free(buf);
	if(server_socket >= 0)
		close(server_socket);
	if(param)
		update_free(param);
	TaskOTA = NULL;
	printf("\n\r[%s] Update task exit", __FUNCTION__);	
	if(!ret){
		printf("\n\r[%s] Ready to reboot", __FUNCTION__);	
		ota_platform_reset();
	}
	vTaskDelete(NULL);	
	return;

}