Ejemplo n.º 1
0
static int asf_write_trailer(AVFormatContext *s)
{
    ASFContext *asf = s->priv_data;
    int64_t file_size, data_size;
    int ret;

    /* flush the current packet */
    if (asf->pb.buf_ptr > asf->pb.buffer)
        flush_packet(s);

    /* write index */
    data_size = avio_tell(s->pb);
    if (!asf->is_streamed && asf->next_start_sec) {
        if ((ret = update_index(s, asf->end_sec + 1, 0, 0, 0)) < 0)
            return ret;
        asf_write_index(s, asf->index_ptr, asf->maximum_packet, asf->next_start_sec);
    }
    avio_flush(s->pb);

    if (asf->is_streamed || !s->pb->seekable) {
        put_chunk(s, 0x4524, 0, 0); /* end of stream */
    } else {
        /* rewrite an updated header */
        file_size = avio_tell(s->pb);
        avio_seek(s->pb, 0, SEEK_SET);
        asf_write_header1(s, file_size, data_size - asf->data_offset);
    }

    av_freep(&asf->index_ptr);
    return 0;
}
Ejemplo n.º 2
0
void output_to_files(const std::vector<map_t>& permutations, const comma::command_line_options& options )
{
    std::size_t count = 0;
    std::size_t total_count = 1;
    for ( std::size_t p = 0; p < permutations.size(); ++p ) { total_count = total_count * permutations[p].values.size(); }
    
    std::string prefix = options.value<std::string>("--prefix", "");
    
    std::string dot = prefix.empty() ? "" : ".";
    
    // vector containing the current position in each input 
    std::vector <std::size_t> index(permutations.size());
    while (count < total_count)
    {
        std::string filename = prefix + dot + boost::lexical_cast<std::string>(count) + ".path-value"; 
        std::ofstream ostream(filename.c_str());
        for (std::size_t p = 0; p < permutations.size(); ++p)
        {
            ostream << permutations[p].path << "=" << permutations[p].values[index[p]] << std::endl;
        }
        ostream.close();
        update_index(permutations, index);
        count++;
    }
}
Ejemplo n.º 3
0
/* record a value in circular buffer */
void record_last_val(uint16_t val)
{
	int index = last_32.index;
	last_32.cnt++;
	last_32.vals[index] = val;
	last_32.index = update_index(last_32.index);
}
Ejemplo n.º 4
0
/*
input: p1 = target last position, p2 = target current position
		obs = obstacle position
main optimal algorthm entry
*/
COMMAND		optimal_vel( POSITION p1, POSITION p2, POSITION obs)
{

	POSITION	current_target, future_target, current_obs;
	POSITION	future_robot;
	STATE		target_state;
	COMMAND		cmd;
	float		current_gama, future_current, delta_theta, current_beta;

	current_target = p2;				//current & future target position
	target_state = predictor(p1, p2);
	future_target.x = current_target.x + target_state.velocity*T*cos(target_state.orient);
	future_target.y = current_target.y + target_state.velocity*T*sin(target_state.orient);

	current_obs = obs;					//get current obstacle position

	
	//update cost
	update_index(VSET, current_target, future_target, current_obs);

	//give a certain command, caculate the optimal index
	//for item in VSET:
	//	item.cost = index_cal( item,  )
	

	//if there is no obstacle, the current visible angle is positive
#ifdef DEBUG
	printf("x = %f y= %f\n", future_target.x, future_target.y);
#endif // DEBUG

	return find_optimal(VSET);
}
Ejemplo n.º 5
0
void write_last_vals(FILE *fp)
{
	int curr, end;
	int index = last_32.index;

	if (last_32.cnt == 32) {
		curr = 0;
		end = 31;
	}
	else if (last_32.cnt < 32) {
		curr = 0;
		end = index;
	} else {
		curr = index;
		end = index - 1;
	}
	if (fprintf(fp, "%s\n", "--Last 32 Values--") < 0) {
		LOG_MSG(ERR, STD_ERR, "error in writing to file");
		return;
	}
	while (curr != end) {
		if (fprintf(fp, "%d\n", last_32.vals[curr]) < 0)
			LOG_MSG(ERR, STD_ERR, "Unable to write to output file");
		curr = update_index(curr);
	}
	if (last_32.cnt >= 32)
		fprintf(fp, "%d\n", last_32.vals[curr]);
}
Ejemplo n.º 6
0
void Germline::new_index(string seed)
{
  bool rc = true ;
  index = KmerStoreFactory::createIndex<KmerAffect>(seed, rc);
  index->refs = 1;

  update_index();
}
Ejemplo n.º 7
0
static int
real_merge (SeafRepo *repo, SeafCommit *head, CloneTask *task)
{
    struct merge_options opts;
    char index_path[SEAF_PATH_MAX];
    struct index_state istate;
    char *root_id = NULL;
    int clean;

    memset (&istate, 0, sizeof(istate));
    snprintf (index_path, SEAF_PATH_MAX, "%s/%s", repo->manager->index_dir, repo->id);
    if (read_index_from (&istate, index_path) < 0) {
        seaf_warning ("Failed to load index.\n");
        return -1;
    }

    init_merge_options (&opts);
    opts.index = &istate;
    opts.worktree = task->worktree;
    opts.ancestor = "common ancestor";
    opts.branch1 = seaf->session->base.user_name;
    opts.branch2 = head->creator_name;
    opts.remote_head = head->commit_id;
    /* Don't need to check locked files on windows. */
    opts.force_merge = TRUE;
    if (repo->encrypted) {
        opts.crypt = seafile_crypt_new (repo->enc_version, 
                                        repo->enc_key, 
                                        repo->enc_iv);
    }

    /* Merge the downloaded branch with the current worktree contents.
     * EMPTY_SHA1 represents an empty common ancestor tree.
     */
    merge_recursive (&opts,
                     task->root_id, head->root_id, EMPTY_SHA1,
                     &clean, &root_id);
    g_free (root_id);

    if (update_index (&istate, index_path) < 0) {
        seaf_warning ("Failed to update index.\n");
        return -1;
    }

    /* We only update the worktree and index, but don't commit.
     * The next auto-commit cycle will check and do that for us.
     */

    discard_index (&istate);
    g_free (opts.crypt);
    clear_merge_options (&opts);

    return 0;
}
Ejemplo n.º 8
0
void
gitg_commit_refresh(GitgCommit *commit)
{
	g_return_if_fail(GITG_IS_COMMIT(commit));

	runner_cancel(commit);
	
	g_hash_table_foreach(commit->priv->files, (GHFunc)set_can_delete, commit);

	/* Read other files */
	if (commit->priv->repository)
		update_index(commit);
}
Ejemplo n.º 9
0
/* 1. Split: choose a new frame other than the one containing parent page. Write
      it out if it's used and then load it with a new page. Update the index accordingly.
   2. Redistributes records in the parent page. Overflow page may exist. Mind it!
   3. The insert the record again. If insertion fails, add an overflow page and insert
      it into the overflow page. */
void split_page_insert_again (struct page *target_page, char *depot, int *pos,
								bool *finished, bool *split, FILE *out_stream)
{
	int new_page_fnum;
	unsigned int pid_again;
	int ovp_pid;
	struct page *new_page, *overflow_page;
	char s_key[20];

	target_page->pin_cnt++;
	new_page_fnum = choose ();
	new_page = &buffer[new_page_fnum];
	target_page->pin_cnt--;

	if (used[new_page_fnum])
	{
		fseek (out_stream, sizeof (struct page) * new_page->pid, SEEK_SET);
		fwrite (new_page, sizeof (struct page), 1, out_stream);
	}
	used[new_page_fnum] = true;

	//prepare_page (target_page, tmp);
	init_page (new_page, target_page->local_depth + 1);
	update_index (target_page->pid, new_page->pid, target_page->local_depth + 1,
					power (2, target_page->local_depth), out_stream);

	unsigned int pid1 = target_page->pid, pid2 = new_page->pid; // debug
	redistribute (target_page, new_page, out_stream);
	assert (pid1 == target_page->pid && pid2 == new_page->pid); // debug
	*split = false;

	get_search_key (s_key, depot, *pos);
	pid_again = *index (hash_func(s_key), out_stream);
	if (pid_again == target_page->pid)
		ovp_pid = insert_record (target_page, depot, pos, finished, split, out_stream, true);
	else if (pid_again == new_page->pid)
		ovp_pid = insert_record (new_page, depot, pos, finished, split, out_stream, true);
	else
	{
		printf ("Page number panic!\n");
		exit (1);
	}

	if (*split)		// add overflow page.
	{
		assert (ovp_pid != -2 && ovp_pid != -3); // debug
		overflow_page = add_overflow_page (ovp_pid, out_stream);
		insert_record (overflow_page, depot, pos, finished, split, out_stream);
	}
}
Ejemplo n.º 10
0
b_type Subgraph::require(uint32_t type){
    Lock(require_lock); 
	if(head.free_num==0){
		//如果空闲块为0,则扩展子图文件,并建索引
		add_file();//按默认配置的大小分配
		update_index();//按默认配置大小对分配的文件建立索引。一定要和add_file大小配对
	}
	if(head.free_num>0)
	return requireRaw(type);
	else{
        Unlock(require_lock); 
		return INVALID_BLOCK;//返回无效块
    }
}
Ejemplo n.º 11
0
void delete_binlog_pos (long long pos, int binlog_replay) {
  struct binlog_pos t;
  t.pos = pos;
  t.crc32 = 0;
  t.timestamp = 0;
  binlog_pos_tree = tree_delete_binlog_pos (binlog_pos_tree, t);
  if (!binlog_pos_tree) {
    t = get_cur_binlog_position (binlog_replay);
  } else {
    struct tree_binlog_pos *T = tree_get_min_binlog_pos (binlog_pos_tree);
    assert (T);
    t = T->x;
  }
  update_index (t.pos, t.crc32, t.timestamp);
}
Ejemplo n.º 12
0
static int asf_write_packet(AVFormatContext *s, AVPacket *pkt)
{
    ASFContext *asf = s->priv_data;
    AVIOContext *pb = s->pb;
    ASFStream *stream;
    AVCodecContext *codec;
    uint32_t packet_number;
    int64_t pts;
    int start_sec;
    int flags = pkt->flags;
    int ret;
    uint64_t offset = avio_tell(pb);

    codec  = s->streams[pkt->stream_index]->codec;
    stream = &asf->streams[pkt->stream_index];

    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
        flags &= ~AV_PKT_FLAG_KEY;

    pts = (pkt->pts != AV_NOPTS_VALUE) ? pkt->pts : pkt->dts;
    av_assert0(pts != AV_NOPTS_VALUE);
    if (   pts < - PREROLL_TIME
        || pts > (INT_MAX-3)/10000LL * ASF_INDEXED_INTERVAL - PREROLL_TIME) {
        av_log(s, AV_LOG_ERROR, "input pts %"PRId64" is invalid\n", pts);
        return AVERROR(EINVAL);
    }
    pts *= 10000;
    asf->duration = FFMAX(asf->duration, pts + pkt->duration * 10000);

    packet_number = asf->nb_packets;
    put_frame(s, stream, s->streams[pkt->stream_index],
              pkt->dts, pkt->data, pkt->size, flags);

    start_sec = (int)((PREROLL_TIME * 10000 + pts + ASF_INDEXED_INTERVAL - 1)
              / ASF_INDEXED_INTERVAL);

    /* check index */
    if ((!asf->is_streamed) && (flags & AV_PKT_FLAG_KEY)) {
        uint16_t packet_count = asf->nb_packets - packet_number;
        ret = update_index(s, start_sec, packet_number, packet_count, offset);
        if (ret < 0)
            return ret;
    }
    asf->end_sec = start_sec;

    return 0;
}
Ejemplo n.º 13
0
void output_to_stdout(const std::vector<map_t>& permutations, const comma::command_line_options& options )
{
    std::string prefix = options.value<std::string>("--prefix", "permutations");
    std::size_t count = 0;
    std::size_t total_count = 1;
    for ( std::size_t p = 0; p < permutations.size(); ++p ) { total_count = total_count * permutations[p].values.size(); }
    std::vector <std::size_t> index(permutations.size());
    while (count < total_count)
    {
        for (std::size_t p = 0; p < permutations.size(); ++p)
        {
            std::cout << prefix << "[" << count << "]/" << permutations[p].path << "=" << permutations[p].values[index[p]] << std::endl;
        }
        update_index(permutations, index);
        count++;
    }
}
Ejemplo n.º 14
0
//格式化子图,创建子图的头,初始化索引结构等等,参数是该子图的block大小
//1
void Subgraph::format(uint32_t block_size){
	head.free_head=INVALID_BLOCK;
	head.vertex_head=INVALID_BLOCK;		
	head.vertex_tail=INVALID_BLOCK;		
	head.vertex_num=0;
	head.edge_num=0;
	head.free_num=0;
	head.block_num=0;
	head.block_size=block_size;
	//一个子图初始化一定大小
	add_file(atoi(getenv("INITSZ")));
	//初始化索引
	update_index(atoi(getenv("INITSZ")));
    //创建顶点的索引文件
	vertex_index.init(graph_dir+"/"+sub_key+"_"+getenv("VERTEX_INDEX_FILENAME"));
	vertex_index.format();
}
Ejemplo n.º 15
0
void LightTable::insert(AttrTuple & tuple)
{
	const auto &header = mTablefile.get_header();
	
	uint32_t addr;
	
	// Primary key
	if (header.primaryKeyIndex >= 0)
	{
		addr = insert_with_pk(tuple);
	}
	// No primary key
	else
	{
		addr = insert_no_pk(tuple);
	}

	update_index(tuple, addr);
}
Ejemplo n.º 16
0
Archivo: asfenc.c Proyecto: cnh/FFmpeg
static int asf_write_packet(AVFormatContext *s, AVPacket *pkt)
{
    ASFContext *asf = s->priv_data;
    ASFStream *stream;
    AVCodecContext *codec;
    uint32_t packet_number;
    int64_t pts;
    int start_sec;
    int flags = pkt->flags;
    int ret;

    codec  = s->streams[pkt->stream_index]->codec;
    stream = &asf->streams[pkt->stream_index];

    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
        flags &= ~AV_PKT_FLAG_KEY;

    pts = (pkt->pts != AV_NOPTS_VALUE) ? pkt->pts : pkt->dts;
    av_assert0(pts != AV_NOPTS_VALUE);
    pts *= 10000;
    asf->duration = FFMAX(asf->duration, pts + pkt->duration * 10000);

    packet_number = asf->nb_packets;
    put_frame(s, stream, s->streams[pkt->stream_index],
              pkt->dts, pkt->data, pkt->size, flags);

    start_sec = (int)((PREROLL_TIME * 10000 + pts + ASF_INDEXED_INTERVAL - 1)
              / ASF_INDEXED_INTERVAL);

    /* check index */
    if ((!asf->is_streamed) && (flags & AV_PKT_FLAG_KEY)) {
        uint16_t packet_count = asf->nb_packets - packet_number;
        if ((ret = update_index(s, start_sec, packet_number, packet_count)) < 0)
            return ret;
    }
    asf->end_sec = start_sec;

    return 0;
}
/* Public Method: update_indices(first_index,num_insertion)
 * -------------------------------------------------------------------------- 
 * Updates indices i_reac_zero, i_reac_one, i_product, given an insertion
 * of num_insertion molecules beginning at first_index into our genome.
 *
 * FOR NOW WE ONLY CONSIDER INSERTIONS, IE NUMINSERTIONS >= 0. 
 */
void HillPromReaction::update_mol_indices( int first_index , int num_insertion ) {
	_i_promoter = update_index( first_index , num_insertion , _i_promoter );
	_i_promoted = update_index( first_index , num_insertion , _i_promoted );
}
Ejemplo n.º 18
0
int srp_main(int argc, char **argv)
{
    CA_DB *db = NULL;
    CONF *conf = NULL;
    int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i;
    int doupdatedb = 0, mode = OPT_ERR;
    char *user = NULL, *passinarg = NULL, *passoutarg = NULL;
    char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL;
    char *randfile = NULL, *section = NULL;
    char **gNrow = NULL, *configfile = NULL;
    char *srpvfile = NULL, **pp, *prog;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, srp_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(srp_options);
            ret = 0;
            goto end;
        case OPT_VERBOSE:
            verbose++;
            break;
        case OPT_CONFIG:
            configfile = opt_arg();
            break;
        case OPT_NAME:
            section = opt_arg();
            break;
        case OPT_SRPVFILE:
            srpvfile = opt_arg();
            break;
        case OPT_ADD:
        case OPT_DELETE:
        case OPT_MODIFY:
        case OPT_LIST:
            if (mode != OPT_ERR) {
                BIO_printf(bio_err,
                           "%s: Only one of -add/delete-modify/-list\n",
                           prog);
                goto opthelp;
            }
            mode = o;
            break;
        case OPT_GN:
            gN = opt_arg();
            break;
        case OPT_USERINFO:
            userinfo = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_ENGINE:
            (void)setup_engine(opt_arg(), 0);
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (srpvfile && configfile) {
        BIO_printf(bio_err,
                   "-srpvfile and -configfile cannot be specified together.\n");
        goto end;
    }
    if (mode == OPT_ERR) {
        BIO_printf(bio_err,
                   "Exactly one of the options -add, -delete, -modify -list must be specified.\n");
        goto opthelp;
    }
    if ((mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD)
        && argc < 1) {
        BIO_printf(bio_err,
                   "Need at least one user for options -add, -delete, -modify. \n");
        goto opthelp;
    }
    if ((passin || passout) && argc != 1) {
        BIO_printf(bio_err,
                   "-passin, -passout arguments only valid with one user.\n");
        goto opthelp;
    }

    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
        BIO_printf(bio_err, "Error getting passwords\n");
        goto end;
    }

    if (!srpvfile) {
        if (!configfile)
            configfile = default_config_file;

        if (verbose)
            BIO_printf(bio_err, "Using configuration from %s\n",
                       configfile);
        conf = app_load_config(configfile);
        if (conf == NULL)
            goto end;
        if (configfile != default_config_file && !app_load_modules(conf))
            goto end;

        /* Lets get the config section we are using */
        if (section == NULL) {
            if (verbose)
                BIO_printf(bio_err,
                           "trying to read " ENV_DEFAULT_SRP
                           " in " BASE_SECTION "\n");

            section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP);
            if (section == NULL)
                goto end;
        }

        if (randfile == NULL)
            randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");

        if (verbose)
            BIO_printf(bio_err,
                       "trying to read " ENV_DATABASE " in section \"%s\"\n",
                       section);

        srpvfile = lookup_conf(conf, section, ENV_DATABASE);
        if (srpvfile == NULL)
            goto end;
    }
    if (randfile == NULL)
        ERR_clear_error();
    else
        app_RAND_load_file(randfile, 0);

    if (verbose)
        BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n",
                   srpvfile);

    db = load_index(srpvfile, NULL);
    if (db == NULL)
        goto end;

    /* Lets check some fields */
    for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
        pp = sk_OPENSSL_PSTRING_value(db->db->data, i);

        if (pp[DB_srptype][0] == DB_SRP_INDEX) {
            maxgN = i;
            if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0)
                gNindex = i;

            print_index(db, i, verbose > 1);
        }
    }

    if (verbose)
        BIO_printf(bio_err, "Database initialised\n");

    if (gNindex >= 0) {
        gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex);
        print_entry(db, gNindex, verbose > 1, "Default g and N");
    } else if (maxgN > 0 && !SRP_get_default_gN(gN)) {
        BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
        goto end;
    } else {
        if (verbose)
            BIO_printf(bio_err, "Database has no g N information.\n");
        gNrow = NULL;
    }

    if (verbose > 1)
        BIO_printf(bio_err, "Starting user processing\n");

    if (argc > 0)
        user = *(argv++);

    while (mode == OPT_LIST || user) {
        int userindex = -1;

        if (user != NULL && verbose > 1)
            BIO_printf(bio_err, "Processing user \"%s\"\n", user);
        if ((userindex = get_index(db, user, 'U')) >= 0) {
            print_user(db, userindex, (verbose > 0) || mode == OPT_LIST);
        }

        if (mode == OPT_LIST) {
            if (user == NULL) {
                BIO_printf(bio_err, "List all users\n");

                for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
                    print_user(db, i, 1);
                }
            } else if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, ignored. t\n", user);
                errors++;
            }
        } else if (mode == OPT_ADD) {
            if (userindex >= 0) {
                /* reactivation of a new user */
                char **row =
                    sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
                row[DB_srptype][0] = 'V';

                doupdatedb = 1;
            } else {
                char *row[DB_NUMBER];
                char *gNid;
                row[DB_srpverifier] = NULL;
                row[DB_srpsalt] = NULL;
                row[DB_srpinfo] = NULL;
                if (!
                    (gNid =
                     srp_create_user(user, &(row[DB_srpverifier]),
                                     &(row[DB_srpsalt]),
                                     gNrow ? gNrow[DB_srpsalt] : gN,
                                     gNrow ? gNrow[DB_srpverifier] : NULL,
                                     passout, verbose))) {
                    BIO_printf(bio_err,
                               "Cannot create srp verifier for user \"%s\", operation abandoned .\n",
                               user);
                    errors++;
                    goto end;
                }
                row[DB_srpid] = OPENSSL_strdup(user);
                row[DB_srptype] = OPENSSL_strdup("v");
                row[DB_srpgN] = OPENSSL_strdup(gNid);

                if ((row[DB_srpid] == NULL)
                    || (row[DB_srpgN] == NULL)
                    || (row[DB_srptype] == NULL)
                    || (row[DB_srpverifier] == NULL)
                    || (row[DB_srpsalt] == NULL)
                    || (userinfo
                        && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))
                    || !update_index(db, row)) {
                    OPENSSL_free(row[DB_srpid]);
                    OPENSSL_free(row[DB_srpgN]);
                    OPENSSL_free(row[DB_srpinfo]);
                    OPENSSL_free(row[DB_srptype]);
                    OPENSSL_free(row[DB_srpverifier]);
                    OPENSSL_free(row[DB_srpsalt]);
                    goto end;
                }
                doupdatedb = 1;
            }
        } else if (mode == OPT_MODIFY) {
            if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, operation ignored.\n",
                           user);
                errors++;
            } else {

                char **row =
                    sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                char type = row[DB_srptype][0];
                if (type == 'v') {
                    BIO_printf(bio_err,
                               "user \"%s\" already updated, operation ignored.\n",
                               user);
                    errors++;
                } else {
                    char *gNid;

                    if (row[DB_srptype][0] == 'V') {
                        int user_gN;
                        char **irow = NULL;
                        if (verbose)
                            BIO_printf(bio_err,
                                       "Verifying password for user \"%s\"\n",
                                       user);
                        if ((user_gN =
                             get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
                            irow =
                                sk_OPENSSL_PSTRING_value(db->db->data,
                                                         userindex);

                        if (!srp_verify_user
                            (user, row[DB_srpverifier], row[DB_srpsalt],
                             irow ? irow[DB_srpsalt] : row[DB_srpgN],
                             irow ? irow[DB_srpverifier] : NULL, passin,
                             verbose)) {
                            BIO_printf(bio_err,
                                       "Invalid password for user \"%s\", operation abandoned.\n",
                                       user);
                            errors++;
                            goto end;
                        }
                    }
                    if (verbose)
                        BIO_printf(bio_err, "Password for user \"%s\" ok.\n",
                                   user);

                    if (!
                        (gNid =
                         srp_create_user(user, &(row[DB_srpverifier]),
                                         &(row[DB_srpsalt]),
                                         gNrow ? gNrow[DB_srpsalt] : NULL,
                                         gNrow ? gNrow[DB_srpverifier] : NULL,
                                         passout, verbose))) {
                        BIO_printf(bio_err,
                                   "Cannot create srp verifier for user \"%s\", operation abandoned.\n",
                                   user);
                        errors++;
                        goto end;
                    }

                    row[DB_srptype][0] = 'v';
                    row[DB_srpgN] = OPENSSL_strdup(gNid);

                    if (row[DB_srpid] == NULL
                        || row[DB_srpgN] == NULL
                        || row[DB_srptype] == NULL
                        || row[DB_srpverifier] == NULL
                        || row[DB_srpsalt] == NULL
                        || (userinfo
                            && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo))
                                == NULL)))
                        goto end;

                    doupdatedb = 1;
                }
            }
        } else if (mode == OPT_DELETE) {
            if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, operation ignored. t\n",
                           user);
                errors++;
            } else {
                char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);

                BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);
                xpp[DB_srptype][0] = 'R';
                doupdatedb = 1;
            }
        }
        if (--argc > 0)
            user = *(argv++);
        else {
            user = NULL;
        }
    }

    if (verbose)
        BIO_printf(bio_err, "User procession done.\n");

    if (doupdatedb) {
        /* Lets check some fields */
        for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
            pp = sk_OPENSSL_PSTRING_value(db->db->data, i);

            if (pp[DB_srptype][0] == 'v') {
                pp[DB_srptype][0] = 'V';
                print_user(db, i, verbose);
            }
        }

        if (verbose)
            BIO_printf(bio_err, "Trying to update srpvfile.\n");
        if (!save_index(srpvfile, "new", db))
            goto end;

        if (verbose)
            BIO_printf(bio_err, "Temporary srpvfile created.\n");
        if (!rotate_index(srpvfile, "new", "old"))
            goto end;

        if (verbose)
            BIO_printf(bio_err, "srpvfile updated.\n");
    }

    ret = (errors != 0);
 end:
    if (errors != 0)
        if (verbose)
            BIO_printf(bio_err, "User errors %d.\n", errors);

    if (verbose)
        BIO_printf(bio_err, "SRP terminating with code %d.\n", ret);

    OPENSSL_free(passin);
    OPENSSL_free(passout);
    if (ret)
        ERR_print_errors(bio_err);
    if (randfile)
        app_RAND_write_file(randfile);
    NCONF_free(conf);
    free_index(db);
    return (ret);
}
Ejemplo n.º 19
0
static int
fast_forward_checkout (SeafRepo *repo, SeafCommit *head, CloneTask *task)
{
    SeafRepoManager *mgr = repo->manager;
    char index_path[SEAF_PATH_MAX];
    struct tree_desc trees[2];
    struct unpack_trees_options topts;
    struct index_state istate;
    int ret = 0;

    if (strcmp (head->root_id, task->root_id) == 0)
        return 0;

    memset (&istate, 0, sizeof(istate));
    snprintf (index_path, SEAF_PATH_MAX, "%s/%s", mgr->index_dir, repo->id);
    if (read_index_from (&istate, index_path) < 0) {
        seaf_warning ("Failed to load index.\n");
        return -1;
    }
    repo->index_corrupted = FALSE;

    fill_tree_descriptor (&trees[0], task->root_id);
    fill_tree_descriptor (&trees[1], head->root_id);

    memset(&topts, 0, sizeof(topts));
    topts.base = task->worktree;
    topts.head_idx = -1;
    topts.src_index = &istate;
    topts.update = 1;
    topts.merge = 1;
    topts.fn = twoway_merge;
    if (repo->encrypted) {
        topts.crypt = seafile_crypt_new (repo->enc_version, 
                                         repo->enc_key, 
                                         repo->enc_iv);
    }

    if (unpack_trees (2, trees, &topts) < 0) {
        seaf_warning ("Failed to merge commit %s with work tree.\n", head->commit_id);
        ret = -1;
        goto out;
    }

    if (update_worktree (&topts, FALSE,
                         head->commit_id,
                         head->creator_name,
                         NULL) < 0) {
        seaf_warning ("Failed to update worktree.\n");
        ret = -1;
        goto out;
    }

    discard_index (&istate);
    istate = topts.result;

    if (update_index (&istate, index_path) < 0) {
        seaf_warning ("Failed to update index.\n");
    }

out:
    tree_desc_free (&trees[0]);
    tree_desc_free (&trees[1]);

    g_free (topts.crypt);

    discard_index (&istate);

    return ret;
}
Ejemplo n.º 20
0
int MAIN(int argc, char **argv)
	{
	int add_user = 0;
	int list_user= 0;
	int delete_user= 0;
	int modify_user= 0;
	char * user = NULL;

	char *passargin = NULL, *passargout = NULL;
	char *passin = NULL, *passout = NULL;
        char * gN = NULL;
	int gNindex = -1;
	char ** gNrow = NULL;
	int maxgN = -1;

	char * userinfo = NULL;

	int badops=0;
	int ret=1;
	int errors=0;
	int verbose=0;
	int doupdatedb=0;
	char *configfile=NULL;
	char *dbfile=NULL;
	CA_DB *db=NULL;
	char **pp ;
	int i;
	long errorline = -1;
	char *randfile=NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif
	char *tofree=NULL;
	DB_ATTR db_attr;

#ifdef EFENCE
EF_PROTECT_FREE=1;
EF_PROTECT_BELOW=1;
EF_ALIGNMENT=0;
#endif

	apps_startup();

	conf = NULL;
	section = NULL;

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	argc--;
	argv++;
	while (argc >= 1 && badops == 0)
		{
		if	(strcmp(*argv,"-verbose") == 0)
			verbose++;
		else if	(strcmp(*argv,"-config") == 0)
			{
			if (--argc < 1) goto bad;
			configfile= *(++argv);
			}
		else if (strcmp(*argv,"-name") == 0)
			{
			if (--argc < 1) goto bad;
			section= *(++argv);
			}
		else if	(strcmp(*argv,"-srpvfile") == 0)
			{
			if (--argc < 1) goto bad;
			dbfile= *(++argv);
			}
		else if (strcmp(*argv,"-add") == 0)
			add_user=1;
		else if (strcmp(*argv,"-delete") == 0)
			delete_user=1;
		else if (strcmp(*argv,"-modify") == 0)
			modify_user=1;
		else if (strcmp(*argv,"-list") == 0)
			list_user=1;
		else if (strcmp(*argv,"-gn") == 0)
			{
			if (--argc < 1) goto bad;
			gN= *(++argv);
			}
		else if (strcmp(*argv,"-userinfo") == 0)
			{
			if (--argc < 1) goto bad;
			userinfo= *(++argv);
			}
		else if (strcmp(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (strcmp(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif

		else if (**argv == '-')
			{
bad:
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		else 
			break;
	
		argc--;
		argv++;
		}

	if (dbfile && configfile)
		{
		BIO_printf(bio_err,"-dbfile and -configfile cannot be specified together.\n");
		badops = 1;
		}
	if (add_user+delete_user+modify_user+list_user != 1)
		{
		BIO_printf(bio_err,"Exactly one of the options -add, -delete, -modify -list must be specified.\n");
		badops = 1;
		}
	if (delete_user+modify_user+delete_user== 1 && argc <= 0)
		{
		BIO_printf(bio_err,"Need at least one user for options -add, -delete, -modify. \n");
		badops = 1;
		}
	if ((passin || passout) && argc != 1 )
		{
		BIO_printf(bio_err,"-passin, -passout arguments only valid with one user.\n");
		badops = 1;
		}

	if (badops)
		{
		for (pp=srp_usage; (*pp != NULL); pp++)
			BIO_printf(bio_err,"%s",*pp);

		BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
		BIO_printf(bio_err,"                 load the file (or the files in the directory) into\n");
		BIO_printf(bio_err,"                 the random number generator\n");
		goto err;
		}

	ERR_load_crypto_strings();

#ifndef OPENSSL_NO_ENGINE
	setup_engine(bio_err, engine, 0);
#endif

	if(!app_passwd(bio_err, passargin, passargout, &passin, &passout))
		{
		BIO_printf(bio_err, "Error getting passwords\n");
		goto err;
		}

        if (!dbfile)
		{


	/*****************************************************************/
		tofree=NULL;
		if (configfile == NULL) configfile = getenv("OPENSSL_CONF");
		if (configfile == NULL) configfile = getenv("SSLEAY_CONF");
		if (configfile == NULL)
			{
			const char *s=X509_get_default_cert_area();
			size_t len;

#ifdef OPENSSL_SYS_VMS
			len = strlen(s)+sizeof(CONFIG_FILE);
			tofree=OPENSSL_malloc(len);
			strcpy(tofree,s);
#else
			len = strlen(s)+sizeof(CONFIG_FILE)+1;
			tofree=OPENSSL_malloc(len);
			BUF_strlcpy(tofree,s,len);
			BUF_strlcat(tofree,"/",len);
#endif
			BUF_strlcat(tofree,CONFIG_FILE,len);
			configfile=tofree;
			}

		VERBOSE BIO_printf(bio_err,"Using configuration from %s\n",configfile);
		conf = NCONF_new(NULL);
		if (NCONF_load(conf,configfile,&errorline) <= 0)
			{
			if (errorline <= 0)
				BIO_printf(bio_err,"error loading the config file '%s'\n",
					configfile);
			else
				BIO_printf(bio_err,"error on line %ld of config file '%s'\n"
					,errorline,configfile);
			goto err;
			}
		if(tofree)
			{
			OPENSSL_free(tofree);
			tofree = NULL;
			}

		if (!load_config(bio_err, conf))
			goto err;

	/* Lets get the config section we are using */
		if (section == NULL)
			{
			VERBOSE BIO_printf(bio_err,"trying to read " ENV_DEFAULT_SRP " in \" BASE_SECTION \"\n");

			section=NCONF_get_string(conf,BASE_SECTION,ENV_DEFAULT_SRP);
			if (section == NULL)
				{
				lookup_fail(BASE_SECTION,ENV_DEFAULT_SRP);
				goto err;
				}
			}
         
		if (randfile == NULL && conf)
	        	randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");

	
		VERBOSE BIO_printf(bio_err,"trying to read " ENV_DATABASE " in section \"%s\"\n",section);

		if ((dbfile=NCONF_get_string(conf,section,ENV_DATABASE)) == NULL)
			{
			lookup_fail(section,ENV_DATABASE);
			goto err;
			}

        	}
	if (randfile == NULL)
		ERR_clear_error();
       	else 
		app_RAND_load_file(randfile, bio_err, 0);

	VERBOSE BIO_printf(bio_err,"Trying to read SRP verifier file \"%s\"\n",dbfile);

	db = load_index(dbfile, &db_attr);
	if (db == NULL) goto err;

	/* Lets check some fields */
	for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
		{
		pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
	
		if (pp[DB_srptype][0] == DB_SRP_INDEX)
			{
			maxgN = i;
			if (gNindex < 0 && gN != NULL && !strcmp(gN, pp[DB_srpid]))
				gNindex = i;

			print_index(db, bio_err, i, verbose > 1);
			}
		}
	
	VERBOSE BIO_printf(bio_err, "Database initialised\n");

	if (gNindex >= 0)
		{
		gNrow = sk_OPENSSL_PSTRING_value(db->db->data,gNindex);
		print_entry(db, bio_err, gNindex, verbose > 1, "Default g and N");
		}
	else if (maxgN > 0 && !SRP_get_default_gN(gN))
		{
		BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
		goto err;
		}
	else
		{
		VERBOSE BIO_printf(bio_err, "Database has no g N information.\n");
		gNrow = NULL;
		}
	

	VVERBOSE BIO_printf(bio_err,"Starting user processing\n");

	if (argc > 0)
		user = *(argv++) ;

	while (list_user || user)
		{
		int userindex = -1;
		if (user) 
			VVERBOSE BIO_printf(bio_err, "Processing user \"%s\"\n", user);
		if ((userindex = get_index(db, user, 'U')) >= 0)
			{
			print_user(db, bio_err, userindex, (verbose > 0) || list_user);
			}
		
		if (list_user)
			{
			if (user == NULL)
				{
				BIO_printf(bio_err,"List all users\n");

				for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
					{
					print_user(db,bio_err, i, 1);
					}
				list_user = 0;
				}
			else if (userindex < 0)
				{
				BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n",
					   user);
				errors++;
				}
			}
		else if (add_user)
			{
			if (userindex >= 0)
				{
				/* reactivation of a new user */
				char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
				BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
				row[DB_srptype][0] = 'V';

				doupdatedb = 1;
				}
			else
				{
				char *row[DB_NUMBER] ; char *gNid;
				row[DB_srpverifier] = NULL;
				row[DB_srpsalt] = NULL;
				row[DB_srpinfo] = NULL;
				if (!(gNid = srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:gN,gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose)))
					{
						BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned .\n", user);
						errors++;
						goto err;
					}
				row[DB_srpid] = BUF_strdup(user);
				row[DB_srptype] = BUF_strdup("v");
				row[DB_srpgN] = BUF_strdup(gNid);

				if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] ||
					(userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))) || 
					!update_index(db, bio_err, row))
					{
					if (row[DB_srpid]) OPENSSL_free(row[DB_srpid]);
					if (row[DB_srpgN]) OPENSSL_free(row[DB_srpgN]);
					if (row[DB_srpinfo]) OPENSSL_free(row[DB_srpinfo]);
					if (row[DB_srptype]) OPENSSL_free(row[DB_srptype]);
					if (row[DB_srpverifier]) OPENSSL_free(row[DB_srpverifier]);
					if (row[DB_srpsalt]) OPENSSL_free(row[DB_srpsalt]);
					goto err;
					}
				doupdatedb = 1;
				}
			}
		else if (modify_user)
			{
			if (userindex < 0)
				{
				BIO_printf(bio_err,"user \"%s\" does not exist, operation ignored.\n",user);
				errors++;
				}
			else
				{

				char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
				char type = row[DB_srptype][0];
				if (type == 'v')
					{
					BIO_printf(bio_err,"user \"%s\" already updated, operation ignored.\n",user);
					errors++;
					}
				else
					{
					char *gNid;

					if (row[DB_srptype][0] == 'V')
						{
						int user_gN;
						char **irow = NULL;
						VERBOSE BIO_printf(bio_err,"Verifying password for user \"%s\"\n",user);
						if ( (user_gN = get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
							irow = (char **)sk_OPENSSL_PSTRING_value(db->db->data, userindex);

 						if (!srp_verify_user(user, row[DB_srpverifier], row[DB_srpsalt], irow ? irow[DB_srpsalt] : row[DB_srpgN], irow ? irow[DB_srpverifier] : NULL, passin, bio_err, verbose))
							{
							BIO_printf(bio_err, "Invalid password for user \"%s\", operation abandoned.\n", user);
							errors++;
							goto err;
							}
						} 
					VERBOSE BIO_printf(bio_err,"Password for user \"%s\" ok.\n",user);

					if (!(gNid=srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:NULL, gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose)))
						{
						BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned.\n", user);
						errors++;
						goto err;
						}

					row[DB_srptype][0] = 'v';
					row[DB_srpgN] = BUF_strdup(gNid);
 
					if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] ||
						(userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))))  
						goto err;

					doupdatedb = 1;
					}
				}
			}
		else if (delete_user)
			{
			if (userindex < 0)
				{
				BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored. t\n", user);
				errors++;
				}
			else
				{
				char **xpp = sk_OPENSSL_PSTRING_value(db->db->data,userindex);
				BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);

				xpp[DB_srptype][0] = 'R';
				
				doupdatedb = 1;
				}
			}
		if (--argc > 0)
			user = *(argv++) ;
		else
			{
			user = NULL;
			list_user = 0;
			}
		}

	VERBOSE BIO_printf(bio_err,"User procession done.\n");


	if (doupdatedb)
		{
		/* Lets check some fields */
		for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
			{
			pp = sk_OPENSSL_PSTRING_value(db->db->data,i);
	
			if (pp[DB_srptype][0] == 'v')
				{
				pp[DB_srptype][0] = 'V';
				print_user(db, bio_err, i, verbose);
				}
			}

		VERBOSE BIO_printf(bio_err, "Trying to update srpvfile.\n");
		if (!save_index(dbfile, "new", db)) goto err;
				
		VERBOSE BIO_printf(bio_err, "Temporary srpvfile created.\n");
		if (!rotate_index(dbfile, "new", "old")) goto err;

		VERBOSE BIO_printf(bio_err, "srpvfile updated.\n");
		}

	ret = (errors != 0);
err:
	if (errors != 0)
	VERBOSE BIO_printf(bio_err,"User errors %d.\n",errors);

	VERBOSE BIO_printf(bio_err,"SRP terminating with code %d.\n",ret);
	if(tofree)
		OPENSSL_free(tofree);
	if (ret) ERR_print_errors(bio_err);
	if (randfile) app_RAND_write_file(randfile, bio_err);
	if (conf) NCONF_free(conf);
	if (db) free_index(db);

	OBJ_cleanup();
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Ejemplo n.º 21
0
int main(int argc, char **argv)
{
    GDBM_FILE db;
    char *dbfile = "sift.db";
    int dbflags = 0;
    char *index_dir = 0;
    char *exec = 0;
    int dump = 0;

    struct option long_options[] = {
        {"index",required_argument, 0,  'i'},
        {"clean",no_argument,       &dbflags, GDBM_NEWDB},
        {"db",   required_argument, 0,  'b'},
        {"exec", required_argument, 0,  'e'},
        {"dump", no_argument,       &dump, 1},
        {"help", no_argument,       0,  'h'},
        {"verbose",no_argument,     &verbose, 1},
        {0,      0,                 0,   0}
    };

    while(1) {
        int option_index = 0;
        int c = getopt_long(argc, argv, "", long_options, &option_index);
        if(c == -1)
            break;

        switch (c) {
        case 'i':
            index_dir = optarg;
            break;
        case 'b':
            dbfile = optarg;
            break;
        case 'e':
            exec = optarg;
            break;
        case 'h':
            print_usage(stderr);
            return 0;
        case 0: // Flags
            break;
        default:
            return 1;
        }
    }

    if(index_dir) {
        db = gdbm_open(dbfile, 1024, GDBM_WRCREAT|dbflags, 0644, 0);
        if(!db) {
            fprintf(stderr, "Can't open '%s': %s\n", dbfile, gdbm_strerror(gdbm_errno));
            return 1;
        }

        fprintf(stderr, "Indexing '%s'\n", index_dir);
        update_index(index_dir, db);
        gdbm_close(db);
    }

    // Subsequent operations require no write access
    db = gdbm_open(dbfile, 1024, GDBM_READER, 0, 0);
    if(!db) {
        fprintf(stderr, "Can't open '%s': %s\n", dbfile, gdbm_strerror(gdbm_errno));
        return 1;
    }

    if(dump) {
        // This functionality doesn't seem to be available easily
        // using gdbmtool or similar thus I added it here
        datum key = gdbm_firstkey(db);

        while(key.dptr) {
            datum nextkey = gdbm_nextkey(db, key);
            puts(key.dptr);
            free(key.dptr);
            key = nextkey;
        }

        gdbm_close(db);
        return 0;
    }

    // At least space for argv[0] and terminating NUL
    char **exec_files = malloc(2*sizeof(char*));
    int num_exec_files = 1;
    exec_files[0] = exec;

    for(int i = optind; i < argc; i++) {
        struct match *matches;
        int num_matches = 0;

        fprintf(stderr, "Matching '%s'...\n", argv[i]);
        match_file(argv[i], db, &matches, &num_matches);

        num_exec_files += num_matches;
        exec_files = realloc(exec_files, (num_exec_files+1)*sizeof(char*));
        match_sort(matches, num_matches);

        for(int j = 0; j < num_matches; j++) {
            exec_files[num_exec_files - num_matches + j] = matches[j].file;
	    if(!isatty(STDOUT_FILENO))
		puts(matches[j].file);
	}

        free(matches);
    }

    if(exec) {
        if(verbose) {
            for(int i = 0; i < num_exec_files; i++)
                fprintf(stderr, "%s ", exec_files[i]);
            putc('\n', stderr);
        }

        gdbm_close(db);

        // terminate array with NUL
        exec_files[num_exec_files] = 0;

        execvp(exec, exec_files);
    }

    for(int i = 0; i < num_exec_files; i++)
        free(exec_files[i]);
    free(exec_files);

    gdbm_close(db);
    return 0;
}
Ejemplo n.º 22
0
static int
do_real_merge (SeafRepo *repo, 
               SeafBranch *head_branch,
               SeafCommit *head,
               SeafBranch *remote_branch, 
               SeafCommit *remote,
               SeafCommit *common,
               gboolean recover_merge,
               char **error)
{
    struct merge_options opts;
    char index_path[SEAF_PATH_MAX];
    struct index_state istate;
    char *root_id = NULL;
    SeafCommit *merged;
    int ret = 0, clean;

    memset (&istate, 0, sizeof(istate));
    snprintf (index_path, SEAF_PATH_MAX, "%s/%s", repo->manager->index_dir, repo->id);
    if (read_index_from (&istate, index_path) < 0) {
        g_warning ("Failed to load index.\n");
        *error = g_strdup ("Internal error.\n");
        return -1;
    }

    init_merge_options (&opts);
    opts.index = &istate;
    opts.worktree = repo->worktree;
    opts.ancestor = "common ancestor";
    opts.branch1 = seaf->session->base.user_name;
    opts.branch2 = remote->creator_name;
    opts.remote_head = remote->commit_id;
    opts.recover_merge = recover_merge;
    if (repo->encrypted) {
        opts.crypt = seafile_crypt_new (repo->enc_version, 
                                        repo->enc_key, 
                                        repo->enc_iv);
    }

    ret = merge_recursive (&opts,
                           head->root_id, remote->root_id, common->root_id,
                           &clean, &root_id);
    if (ret < 0)
        goto out;

    if (update_index (&istate, index_path) < 0) {
        *error = g_strdup ("Internal error.\n");
        ret = -1;
        goto out;
    }

    if (clean) {
        merged = seaf_commit_new (NULL,
                                  repo->id,
                                  root_id,
                                  repo->email ? repo->email
                                  : seaf->session->base.user_name,
                                  seaf->session->base.id,
                                  "Auto merge by seafile system",
                                  0);

        merged->parent_id = g_strdup(head->commit_id);
        merged->second_parent_id = g_strdup(remote->commit_id);

        seaf_repo_to_commit (repo, merged);

        if (seaf_commit_manager_add_commit (seaf->commit_mgr, merged) < 0) {
            seaf_commit_unref (merged);
            *error = g_strdup ("Internal error.\n");
            ret = -1;
            goto out;
        }
        seaf_branch_set_commit (head_branch, merged->commit_id);
        seaf_branch_manager_update_branch (seaf->branch_mgr, head_branch);
        g_debug ("Auto merged.\n");

        seaf_commit_unref (merged);
    } else {
        ret = -1;
        g_debug ("Auto merge failed.\n");
    }

out:
    if (root_id)
        g_free (root_id);
    g_free (opts.crypt);
    clear_merge_options (&opts);
    discard_index (&istate);
    return ret;
}
Ejemplo n.º 23
0
static int do_apply_stash(const char *prefix, struct stash_info *info,
			  int index, int quiet)
{
	int ret;
	int has_index = index;
	struct merge_options o;
	struct object_id c_tree;
	struct object_id index_tree;
	struct commit *result;
	const struct object_id *bases[1];

	read_cache_preload(NULL);
	if (refresh_cache(REFRESH_QUIET))
		return -1;

	if (write_cache_as_tree(&c_tree, 0, NULL))
		return error(_("cannot apply a stash in the middle of a merge"));

	if (index) {
		if (oideq(&info->b_tree, &info->i_tree) ||
		    oideq(&c_tree, &info->i_tree)) {
			has_index = 0;
		} else {
			struct strbuf out = STRBUF_INIT;

			if (diff_tree_binary(&out, &info->w_commit)) {
				strbuf_release(&out);
				return error(_("could not generate diff %s^!."),
					     oid_to_hex(&info->w_commit));
			}

			ret = apply_cached(&out);
			strbuf_release(&out);
			if (ret)
				return error(_("conflicts in index."
					       "Try without --index."));

			discard_cache();
			read_cache();
			if (write_cache_as_tree(&index_tree, 0, NULL))
				return error(_("could not save index tree"));

			reset_head();
		}
	}

	if (info->has_u && restore_untracked(&info->u_tree))
		return error(_("could not restore untracked files from stash"));

	init_merge_options(&o, the_repository);

	o.branch1 = "Updated upstream";
	o.branch2 = "Stashed changes";

	if (oideq(&info->b_tree, &c_tree))
		o.branch1 = "Version stash was based on";

	if (quiet)
		o.verbosity = 0;

	if (o.verbosity >= 3)
		printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);

	bases[0] = &info->b_tree;

	ret = merge_recursive_generic(&o, &c_tree, &info->w_tree, 1, bases,
				      &result);
	if (ret) {
		rerere(0);

		if (index)
			fprintf_ln(stderr, _("Index was not unstashed."));

		return ret;
	}

	if (has_index) {
		if (reset_tree(&index_tree, 0, 0))
			return -1;
	} else {
		struct strbuf out = STRBUF_INIT;

		if (get_newly_staged(&out, &c_tree)) {
			strbuf_release(&out);
			return -1;
		}

		if (reset_tree(&c_tree, 0, 1)) {
			strbuf_release(&out);
			return -1;
		}

		ret = update_index(&out);
		strbuf_release(&out);
		if (ret)
			return -1;

		discard_cache();
	}

	if (quiet) {
		if (refresh_cache(REFRESH_QUIET))
			warning("could not refresh index");
	} else {
		struct child_process cp = CHILD_PROCESS_INIT;

		/*
		 * Status is quite simple and could be replaced with calls to
		 * wt_status in the future, but it adds complexities which may
		 * require more tests.
		 */
		cp.git_cmd = 1;
		cp.dir = prefix;
		argv_array_push(&cp.args, "status");
		run_command(&cp);
	}

	return 0;
}
Ejemplo n.º 24
0
void Asset::copy_format(Asset *asset, int do_index)
{
	if(do_index) update_index(asset);

	audio_data = asset->audio_data;
	format = asset->format;
	channels = asset->channels;
	sample_rate = asset->sample_rate;
	bits = asset->bits;
	byte_order = asset->byte_order;
	signed_ = asset->signed_;
	header = asset->header;
	dither = asset->dither;
	mp3_bitrate = asset->mp3_bitrate;
	mp4a_bitrate = asset->mp4a_bitrate;
	mp4a_quantqual = asset->mp4a_quantqual;
	use_header = asset->use_header;
	aspect_ratio = asset->aspect_ratio;
	interlace_autofixoption = asset->interlace_autofixoption;
	interlace_mode = asset->interlace_mode;
	interlace_fixmethod = asset->interlace_fixmethod;

	video_data = asset->video_data;
	layers = asset->layers;
	frame_rate = asset->frame_rate;
	width = asset->width;
	height = asset->height;
	strcpy(vcodec, asset->vcodec);
	strcpy(acodec, asset->acodec);

	this->audio_length = asset->audio_length;
	this->video_length = asset->video_length;


	ampeg_bitrate = asset->ampeg_bitrate;
	ampeg_derivative = asset->ampeg_derivative;


	vorbis_vbr = asset->vorbis_vbr;
	vorbis_min_bitrate = asset->vorbis_min_bitrate;
	vorbis_bitrate = asset->vorbis_bitrate;
	vorbis_max_bitrate = asset->vorbis_max_bitrate;

	
	theora_fix_bitrate = asset->theora_fix_bitrate;
	theora_bitrate = asset->theora_bitrate;
	theora_quality = asset->theora_quality;
	theora_sharpness = asset->theora_sharpness;
	theora_keyframe_frequency = asset->theora_keyframe_frequency;
	theora_keyframe_force_frequency = asset->theora_keyframe_frequency;


	jpeg_quality = asset->jpeg_quality;

// mpeg parameters
	vmpeg_iframe_distance = asset->vmpeg_iframe_distance;
	vmpeg_pframe_distance = asset->vmpeg_pframe_distance;
	vmpeg_progressive = asset->vmpeg_progressive;
	vmpeg_denoise = asset->vmpeg_denoise;
	vmpeg_bitrate = asset->vmpeg_bitrate;
	vmpeg_derivative = asset->vmpeg_derivative;
	vmpeg_quantization = asset->vmpeg_quantization;
	vmpeg_cmodel = asset->vmpeg_cmodel;
	vmpeg_fix_bitrate = asset->vmpeg_fix_bitrate;
	vmpeg_seq_codes = asset->vmpeg_seq_codes;
	vmpeg_preset = asset->vmpeg_preset;
	vmpeg_field_order = asset->vmpeg_field_order;


	divx_bitrate = asset->divx_bitrate;
	divx_rc_period = asset->divx_rc_period;
	divx_rc_reaction_ratio = asset->divx_rc_reaction_ratio;
	divx_rc_reaction_period = asset->divx_rc_reaction_period;
	divx_max_key_interval = asset->divx_max_key_interval;
	divx_max_quantizer = asset->divx_max_quantizer;
	divx_min_quantizer = asset->divx_min_quantizer;
	divx_quantizer = asset->divx_quantizer;
	divx_quality = asset->divx_quality;
	divx_fix_bitrate = asset->divx_fix_bitrate;
	divx_use_deblocking = asset->divx_use_deblocking;

	h264_bitrate = asset->h264_bitrate;
	h264_quantizer = asset->h264_quantizer;
	h264_fix_bitrate = asset->h264_fix_bitrate;


	ms_bitrate = asset->ms_bitrate;
	ms_bitrate_tolerance = asset->ms_bitrate_tolerance;
	ms_interlaced = asset->ms_interlaced;
	ms_quantization = asset->ms_quantization;
	ms_gop_size = asset->ms_gop_size;
	ms_fix_bitrate = asset->ms_fix_bitrate;

	
	ac3_bitrate = asset->ac3_bitrate;
	
	png_use_alpha = asset->png_use_alpha;
	exr_use_alpha = asset->exr_use_alpha;
	exr_compression = asset->exr_compression;

	tiff_cmodel = asset->tiff_cmodel;
	tiff_compression = asset->tiff_compression;

	strcpy(pipe, asset->pipe);
	use_pipe = asset->use_pipe;

	strcpy(reel_name, asset->reel_name);
	reel_number = asset->reel_number;
	tcstart = asset->tcstart;
	tcend = asset->tcend;
	tcformat = asset->tcformat;
}