Пример #1
0
int replace(block *bl1, block *bl2) {
  int delta_cost = -get_wire_cost_for_block(bl1) - get_wire_cost_for_block(bl2);

  delta_cost -= get_area_cost(get_boundary(c_tree, TOP_LEVEL | MIN),
			      get_boundary(c_tree, SECOND_LEVEL | MIN),
			      get_boundary(c_tree, TOP_LEVEL | MAX),
			      get_boundary(c_tree, SECOND_LEVEL | MAX));
  delta_cost -= get_overlap_cost(-rem_bl(c_tree, bl1)) + 
    get_overlap_cost(-rem_bl(c_tree, bl2));
  

  coor temp_pos1 = bl1->pos1;
  bl1->pos1 = bl2->pos1;
  bl2->pos1 = temp_pos1;

  delta_cost += get_overlap_cost(add_bl(c_tree, bl1)) + 
    get_overlap_cost(add_bl(c_tree, bl2));
  delta_cost += get_area_cost(get_boundary(c_tree, TOP_LEVEL | MIN),
			      get_boundary(c_tree, SECOND_LEVEL | MIN),
			      get_boundary(c_tree, TOP_LEVEL | MAX),
			      get_boundary(c_tree, SECOND_LEVEL | MAX));
  
  delta_cost += get_wire_cost_for_block(bl1) + get_wire_cost_for_block(bl2);
  return delta_cost;
}
static apr_status_t upload_filter_init(ap_filter_t* f) {
  upload_conf* conf = ap_get_module_config(f->r->per_dir_config,&upload_module);
  upload_ctx* ctx = apr_palloc(f->r->pool, sizeof(upload_ctx)) ;
  // check content-type, get boundary or error
  const char* ctype = apr_table_get(f->r->headers_in, "Content-Type") ;

  if ( ! ctype || ! conf->file_field ||
	strncmp ( ctype , "multipart/form-data", 19 ) ) {
    ap_remove_input_filter(f) ;
    return APR_SUCCESS ;
  }

  ctx->pool = f->r->pool ;
  ctx->form = apr_table_make(ctx->pool, conf->form_size) ;
  ctx->boundary = get_boundary(f->r->pool, ctype) ;
  ctx->parse_state = p_none ;
  ctx->key = ctx->val = 0 ;
  ctx->file_field = conf->file_field ;
  ctx->is_file = 0 ;
  ctx->leftover = 0 ;
//  ctx->bbin = apr_brigade_create(f->r->pool, f->r->connection->bucket_alloc) ;

  /* save the table in request_config */
  ap_set_module_config(f->r->request_config, &upload_module, ctx->form) ;

  f->ctx = ctx ;
  return APR_SUCCESS ;
}
Пример #3
0
int myinterp(ML_Operator *mydata, int leng1, double p[], int leng2, double ap[])
{
   int i, fine_i, fine_size, coarse_size, proc_id;
   double ghost;
   struct data *data;
   ML_Operator *mat_in;

   mat_in = (ML_Operator *) mydata;
   data = (struct data *) ML_Get_MyMatvecData(mat_in);
   coarse_size = data->from_size;
   fine_size   = data->to_size;
   proc_id     = data->processor_info[PROC_ID];

   for (i = 0; i < fine_size; i++) ap[i] = 0.0;
   fine_i = 1 - proc_id;
   for (i = 0; i < coarse_size; i++) {
      ap[fine_i] += p[i];
      ap[fine_i+1] += .5*p[i];
      if (fine_i != 0) ap[fine_i-1] += .5*p[i];
      fine_i += 2;
   }
   ghost = get_boundary(p, coarse_size, data->processor_info);
   if (proc_id == 0) ap[fine_i - 1] += .5*ghost;

   return 0;
}
Пример #4
0
int mysmooth(ML_Smoother *mydata, int leng1, double x[], int leng2, double rhs[])
{
   int i, size, ntimes, j, k, color, proc_id;
   struct data *data;
   double ghost;
   ML_Smoother *smoo_in;

   smoo_in = (ML_Smoother *) mydata;
   data    = (struct data *) ML_Get_MySmootherData(smoo_in);
   size    = data->size;
   ntimes  = data->ntimes;
   proc_id = data->processor_info[PROC_ID];

   if (size == 0) return 0;

   for (j = 0; j < ntimes; j++) {
      color = proc_id;
      for (k = 0; k < 2; k++) {
         for (i = color; i < size; i += 2) {
            x[i] = rhs[i]/4. + x[i]/2.;
            if (i !=      0) x[i] += x[i-1]/4.;
            if (i != size-1) x[i] += x[i+1]/4.;
         }
         ghost = get_boundary(x, size, data->processor_info);
         if (color == 0) {
            if (proc_id == 0) x[size-1] += ghost/4.;
            else              x[     0] += ghost/4.;
         }
         color = 1 - color;
      }
   }
   return 0;
}
Пример #5
0
int algorithms::Planner<IROBOT>::find_next_owner(int cell, const CONFIG& bnd_cfg ) const
{
    for (int index : get_cell(cell).get_boundaries()) {
        int neighbor = get_boundary(index).otherside(cell);
        if(get_cell(neighbor).on_boundary(bnd_cfg.vector(), 1e-15))
            return neighbor;
    }
    return NOT_FOUND;
}
Пример #6
0
int rotate(block *bl, int deg) {
  deg = deg % 3;
  int delta_cost = -get_wire_cost_for_block(bl);
  if (deg != 1) { //unless the rotation is 180 degrees, the dimensions of the block neeed to change
    coor new_pos2;
    new_pos2.x = bl->pos2.y;
    new_pos2.y = bl->pos2.x;
    delta_cost -= get_area_cost(get_boundary(c_tree, TOP_LEVEL | MIN),
				get_boundary(c_tree, SECOND_LEVEL | MIN),
				get_boundary(c_tree, TOP_LEVEL | MAX),
				get_boundary(c_tree, SECOND_LEVEL | MAX));
    delta_cost -= get_overlap_cost(-rem_bl(c_tree, bl));
    

    bl->pos2 = new_pos2;
    delta_cost += get_overlap_cost(add_bl(c_tree, bl));
    delta_cost += get_area_cost(get_boundary(c_tree, TOP_LEVEL | MIN),
				get_boundary(c_tree, SECOND_LEVEL | MIN),
				get_boundary(c_tree, TOP_LEVEL | MAX),
				get_boundary(c_tree, SECOND_LEVEL | MAX));
  }

  wire_node *w_node = bl->wire_list;
  while (w_node != NULL) { 
    //IDEA: these wire recalculations in rotate operation can be done in parallel
    coor pos = w_node->primary ? w_node->wire->pos1 : w_node->wire->pos2;
    coor new_pos;
    
    switch (deg) {
    case 0:
      new_pos.x = bl->pos2.x - pos.y;
      new_pos.y = pos.x;
      break;
    case 1:
      new_pos.x = bl->pos2.x - pos.x;
      new_pos.y = bl->pos2.y - pos.y;
      break;
    case 2:
      new_pos.x = pos.y;
      new_pos.y = bl->pos2.y - pos.x;
    }

    if (w_node->primary)
      w_node->wire->pos1 = new_pos;
    else
      w_node->wire->pos2 = new_pos;
    
    delta_cost += get_wire_length_cost(wire_len(w_node->wire));

    w_node = w_node->next;
  }

  return delta_cost;
}
Пример #7
0
void algorithms::Planner<IROBOT>::find_next_owners(int cell, const CONFIG& bnd_cfg, std::vector<int>& result) const
{
    result.clear();
    for (int index : get_cell(cell).get_boundaries()) {
        int neighbor = get_boundary(index).otherside(cell);
        if(get_cell(neighbor).on_boundary(bnd_cfg, 1e-15))
            result.emplace_back( neighbor );
        
    }
}
int main(void) {
  int x1, x2, y1, y2, add_amt;
  circ_tree *tree = create_circ_tree();
  for (;;) {
    print_tree(tree, 10, PRINT_CELLS);
    print_tree(tree, 10, PRINT_NODES);
    printf("Boundaries min: (%d, %d), max: (%d, %d)\n", 
	   get_boundary(tree, TOP_LEVEL | MIN),
	   get_boundary(tree, SECOND_LEVEL | MIN),
	   get_boundary(tree, TOP_LEVEL | MAX),
	   get_boundary(tree, SECOND_LEVEL | MAX)); 
    puts("Enter the add amount and the coordinates of the cell");
    scanf("%d %d %d %d %d", &add_amt, &x1, &y1, &x2, &y2);
    if (x1 < 0)
      break;
    printf("Added block, %d cells collided.\n", add_block(tree, x1, y1, x2, y2, add_amt));

  }
}
Пример #9
0
int move(block *bl, int x, int y) {
  int delta_cost = -get_wire_cost_for_block(bl);

  delta_cost -= get_area_cost(get_boundary(c_tree, TOP_LEVEL | MIN),
			      get_boundary(c_tree, SECOND_LEVEL | MIN),
			      get_boundary(c_tree, TOP_LEVEL | MAX),
			      get_boundary(c_tree, SECOND_LEVEL | MAX));
  delta_cost -= get_overlap_cost(-rem_bl(c_tree, bl));
  
  bl->pos1.x += x;
  bl->pos1.y += y;
  delta_cost += get_overlap_cost(add_bl(c_tree, bl));
  delta_cost += get_area_cost(get_boundary(c_tree, TOP_LEVEL | MIN),
			      get_boundary(c_tree, SECOND_LEVEL | MIN),
			      get_boundary(c_tree, TOP_LEVEL | MAX),
			      get_boundary(c_tree, SECOND_LEVEL | MAX));
  
  delta_cost += get_wire_cost_for_block(bl);
  return delta_cost;
}
Пример #10
0
static void dochecksign(struct mimestack *stack,
                        FILE *content_fp,
                        FILE *out_fp,
                        const char *content_filename,
                        const char *signature_filename,
                        int argc,
                        char **argv)
{
    struct gpgmime_forkinfo gpg;
    int i;
    const char *new_boundary;
    const char *output;

    if (gpgmime_forkchecksign(NULL, content_filename,
                              signature_filename,
                              argc, argv,
                              &gpg))
    {
        perror("fork");
        exit(1);
    }

    i=gpgmime_finish(&gpg);

    output=gpgmime_getoutput(&gpg);

    new_boundary=get_boundary(stack, output, content_fp);

    open_result_multipart(out_fp, i, new_boundary, output,
                          gpgmime_getcharset(&gpg));
    fprintf(out_fp, "\n--%s\n", new_boundary);
    if (my_rewind(content_fp) < 0)
    {
        perror("fseek");
        exit(1);
    }
    while ((i=getc(content_fp)) != EOF)
    {
        if (i == '\r')
            continue;
        putc(i, out_fp);
    }
    fprintf(out_fp, "\n--%s--\n", new_boundary);
}
Пример #11
0
int main() {
    // Model, Domain and Boundary
    const auto flow = std::make_unique<Flow>("Couette3D");
    const auto lbmodel = flow->get_lbmodel();
    const auto domain = flow->get_domain();
    const auto boundary = flow->get_boundary();

    // Define problem and its data
    const auto problem = std::make_unique<PLBPD>(lbmodel, domain, boundary);
    auto simdata =
        SimData(domain->get_dimensions(), lbmodel->get_num_directions());

    // Solve problem
    problem->initialize(simdata);
    simdata.write_state("init_state.h5");
    problem->march_in_time(flow->get_num_timesteps(), simdata);
    simdata.write_state("final_state.h5");
    problem->print_times();
}
Пример #12
0
int my_comm(double *vec, void *idata)
{
   struct data *data;
   double ghost_value;
   int    proc_id;

   data    = (struct data *) idata;
   if (data->processor_info[NUM_PROCS] < 2 ) return 0;
   proc_id = data->processor_info[PROC_ID];
   ghost_value = get_boundary(vec, data->from_size, data->processor_info);

   if (proc_id == 0) {
      if ( data->from_size <=  data->to_size)
         vec[data->from_size] = ghost_value;
   }
   else {
      if ( data->from_size >=  data->to_size)
         vec[data->from_size] = ghost_value;
   }
   return 0;
}
Пример #13
0
int myrestrict(ML_Operator *mydata, int leng1, double p[], int leng2, double ap[])
{
   int i, fine_i, coarse_size, proc_id;
   struct data *data;
   double ghost;
   ML_Operator *mat_in;

   mat_in = (ML_Operator *) mydata;
   data = (struct data *) ML_Get_MyMatvecData(mat_in);
   coarse_size = data->to_size;
   proc_id   = data->processor_info[PROC_ID];
   fine_i = 1 - proc_id;
   for (i = 0; i < coarse_size; i++) {
      ap[i] = .5*p[fine_i] + .25*p[fine_i+1];
      if (fine_i != 0) ap[i] += .25*p[fine_i-1];
      ap[i] *= 4.;
      fine_i += 2;
   }
   ghost = get_boundary(p, fine_i, data->processor_info);
   if (proc_id == 1) ap[0] += ghost;
   return 0;
}
Пример #14
0
int mymatvec(ML_Operator *mydata, int leng1, double p[], int leng2, double ap[])
{
   int i, size, proc_id;
   double ghost;
   struct data *data;
   ML_Operator *mat_in;

   mat_in = (ML_Operator *) mydata;
   data = (struct data *) ML_Get_MyMatvecData(mat_in);
   size = data->to_size;
   proc_id   = data->processor_info[PROC_ID];
   for (i = 0; i < size; i++ ) {
      ap[i] = 2*p[i];
      if (i !=      0) ap[i] -= p[i-1];
      if (i != size-1) ap[i] -= p[i+1];
   }
   ghost = get_boundary(p, size, data->processor_info);
   if (proc_id == 0) ap[size-1] -= ghost;
   else              ap[0]      -= ghost;

   return 0;
}
Пример #15
0
std::vector<typename IROBOT::CONFIG> algorithms::Planner<IROBOT>::AStar(const IROBOT& robot, const CONFIG& start, const CONFIG& goal)
{
    
    double smallest_radius = get_smallest_radius();
    // Find the cells containing the start and the goal
    int start_cell = NOT_FOUND, goal_cell = NOT_FOUND;
    for (int i = 0; i < cells.size(); ++i) {
        if( cells[i].contains(goal.vector()))
            goal_cell = i;
        if (cells[i].contains(start.vector())) {
            start_cell = i;
            std::cout << "Start cell potential : " << cells[i].get_potential() << '\n';
        }
    }
    for (Boundary<IROBOT>& boundary : all_boundaries)
        boundary.reset();
    
    if( start_cell == NOT_FOUND)
        throw "start config is not in any cell!";
    else if (goal_cell == NOT_FOUND )
        throw "goal config is not in any cell!";
    
    // Initialize for the nodes
    nodes.clear();
    nodes.reserve(1000000);
    int start_node = get_new_info(start);
    get_info(start_node).came_from = -1;
    int goal_node = get_new_info(goal);
    get_info(goal_node).cell = goal_cell;
    int metric_query = 0;
    std::cout << "Initialize the queue of AStar\n";
    // Initialize for the queue
    std::priority_queue<AStar_node> openset;
    {
        double g_score_start = 0.0;
        int current_cell_index = start_cell;
        double interval = (std::log(cells[current_cell_index].radius() / smallest_radius) + 1) * smallest_radius;
        for (int boundary_index : cells[current_cell_index].get_boundaries()) {
            int begin, end;
            get_boundary(boundary_index).get_boundary_configs(*this, interval, begin, end);
            for (int vertex = begin; vertex < end; ++vertex) {
                double tentative_g_score = g_score_start + IROBOT::metric(robot, start, nodes[vertex].cfg);
                nodes[vertex].came_from = start_node;
                nodes[vertex].g_score = tentative_g_score;
                nodes[vertex].f_score = tentative_g_score + cells[current_cell_index].get_potential();
                nodes[vertex].heuristic = cells[current_cell_index].get_potential();
                nodes[vertex].cell = start_cell;
                nodes[vertex].set_open();
                openset.emplace(vertex, nodes[vertex].f_score);
                ++metric_query;
            }
            
        }
    }
    std::cout << "Start AStar\n";
    // Starting A*
    while (!openset.empty()) {
        int current_node = openset.top().info_index;
        openset.pop();
        if (nodes[current_node].is_closed())
            continue;
        get_info(current_node).set_closed();
        if (current_node == goal_node) {
            std::cout << "Find Goal by expolring " << nodes.size() << " nodes with " << metric_query << " queries\n";
            return this->trace_back(nodes[current_node], start, goal);
        }
        
        int prev_cell;
        int current_cell;
        // Special case for start's neighbor
        if (nodes[current_node].came_from == start_node) {
            prev_cell = nodes[current_node].cell;
            current_cell = prev_cell;
        } else {
            prev_cell = nodes[nodes[current_node].came_from].cell;
            current_cell = find_next_owner(prev_cell, nodes[nodes[current_node].came_from].cfg); // search the neighbors of prev cell to see which cell contians current_cfg, that is the current_cell. ( there is only one such cell )
            
        }
        get_info(current_node).cell = current_cell;
        
        // time to check if the path has common cells.
        int neighbor_cell_index = find_next_owner(current_cell, nodes[current_node].cfg); // get the cell that also contains current config
        if( neighbor_cell_index == NOT_FOUND ) {
            continue;
        }
        cells[current_cell].set_visited();
        cells[neighbor_cell_index].set_visited();
        // Special case for goal's neighbor
        if (cells[neighbor_cell_index].contains(goal.vector())) {
            if( !nodes[goal_node].is_open() ) {
                nodes[goal_node].set_open();
                nodes[goal_node].g_score = get_info(current_node).g_score + IROBOT::metric(robot, nodes[current_node].cfg, goal);
                nodes[goal_node].came_from = current_node;
                openset.emplace(goal_node, nodes[goal_node].g_score);
                ++metric_query;
            } else {
                double distance_to_goal = IROBOT::metric(robot, nodes[current_node].cfg, goal);
                ++metric_query;
                if (get_info(current_node).g_score + distance_to_goal < nodes[goal_node].g_score) {
                    // 1. remove the neighbor_cfg from openset
                    // 2. re-add neighbor_cfg to openset with new priority.
                    nodes[goal_node].g_score = get_info(current_node).g_score + distance_to_goal;
                    nodes[goal_node].came_from = current_node;
                    openset.emplace(goal_node, nodes[goal_node].g_score);
                }
            }
            continue;
        }
        
        int neighbor_count = 0;
        // Compute successors
        for (int boundary_index : cells[neighbor_cell_index].get_boundaries()) {
            double interval = (std::log(cells[neighbor_cell_index].radius() / smallest_radius) + 1) * smallest_radius;
            int begin, end;
            get_boundary(boundary_index).get_boundary_configs(*this, interval, begin, end);
            for (int neighbor = begin; neighbor < end; ++neighbor) {
                if (nodes[neighbor].is_closed())    // already in closed set
                    continue;
                if (nodes[neighbor].is_open() && nodes[neighbor].g_score <= nodes[current_node].g_score)
                    continue;
                ++neighbor_count;
                double tentative_g_score = get_info(current_node).g_score + IROBOT::metric(robot, nodes[current_node].cfg, nodes[neighbor].cfg);
                ++metric_query;
                if (!nodes[neighbor].is_open() || tentative_g_score < nodes[neighbor].g_score)
                {
                    nodes[neighbor].came_from = current_node;
                    nodes[neighbor].g_score = tentative_g_score;
                    
                    nodes[neighbor].f_score = nodes[neighbor].g_score + cells[neighbor_cell_index].get_potential();
                    nodes[neighbor].heuristic = cells[neighbor_cell_index].get_potential();
                    if( !nodes[neighbor].is_open() ) {
                        //get_info(neighbor).f_score = get_info(neighbor).g_score + metric(robot, get_info(neighbor).cfg, goal);
                        nodes[neighbor].set_open();
                        openset.emplace(neighbor, nodes[neighbor].f_score);
                    } else{
                        //get_info(neighbor).f_score = get_info(neighbor).g_score + get_info(neighbor).heuristic;
                        // 1. remove the neighbor_cfg from openset
                        // 2. re-add neighbor_cfg to openset with new priority.
                        openset.emplace(neighbor, nodes[neighbor].f_score); // (two steps are done inside)
                    }
                }
            }
        }
        //std::cout << neighbor_count << '\n';
    }
    throw "The path doesn't exist";
}
Пример #16
0
static void dogpgsign(struct mimestack **stack, struct header *h, int *iseof,
                      FILE *fpin, FILE *fpout,
                      int argc,
                      char **argv)
{
    struct header *hp;
    char buf[BUFSIZ];
    struct gpgmime_forkinfo gpg;
    int clos_flag=0;
    struct mimestack *b=0;
    int rc;
    char signed_content_name[TEMPNAMEBUFSIZE];
    int signed_content;
    FILE *signed_content_fp;
    const char *boundary;
    int need_crlf;

    for (hp=h; hp; hp=hp->next)
    {
        if (encode_header(hp->header))
            continue;
        fprintf(fpout, "%s", hp->header);
    }

    signed_content=mimegpg_tempfile(signed_content_name);
    if (signed_content < 0 ||
            (signed_content_fp=fdopen(signed_content, "w+")) == NULL)
    {
        if (signed_content >= 0)
        {
            close(signed_content);
            unlink(signed_content_name);
        }
        perror("mktemp");
        exit(1);
    }
    noexec(signed_content_fp);
    unlink(signed_content_name);	/* UNIX semantics */

    for (hp=h; hp; hp=hp->next)
    {
        const char *p;

        if (!encode_header(hp->header))
            continue;

        for (p=hp->header; *p; p++)
        {
            if (*p == '\r')
                continue;

            if (*p == '\n')
                putc('\r', signed_content_fp);
            putc(*p, signed_content_fp);
        }
    }

    /*
    ** Chew the content until the next MIME boundary.
    */
    need_crlf=1;
    while (!*iseof)
    {
        const char *p;

        if (fgets(buf, sizeof(buf), fpin) == NULL)
        {
            *iseof=1;
            break;
        }

        if (need_crlf)
        {
            if ((b=is_boundary(*stack, buf, &clos_flag)) != NULL)
                break;

            fprintf(signed_content_fp, "\r\n");
        }

        need_crlf=0;
        for (;;)
        {
            for (p=buf; *p; p++)
            {
                if (*p == '\r')
                    continue;
                if (*p == '\n')
                {
                    need_crlf=1;
                    break;
                }

                putc(*p, signed_content_fp);
            }
            if (*p == '\n')
                break;

            if (fgets(buf, sizeof(buf), fpin) == NULL)
            {
                *iseof=1;
                break;
            }
        }
    }

    /*
    ** This needs some 'splainin.  Note that we spit out a newline at
    ** the BEGINNING of each line, above.  This generates the blank
    ** header->body separator line.  Now, if we're NOT doing multiline
    ** content, we need to follow the last line of the content with a
    ** newline.  If we're already doing multiline content, that extra
    ** newline (if it exists) is already there.
    */

    if (!*stack)
    {
        fprintf(signed_content_fp, "\r\n");
    }

    if (fflush(signed_content_fp) < 0 || ferror(signed_content_fp))
    {
        perror(signed_content_name);
        exit(1);
    }

    boundary=get_boundary(*stack, "", signed_content_fp);

    if (my_rewind(signed_content_fp) < 0)
    {
        perror(signed_content_name);
        exit(1);
    }

    if (gpgmime_fork_signencrypt(NULL, GPG_SE_SIGN,
                                 argc, argv,
                                 &dumpgpg, fpout,
                                 &gpg))
    {
        perror("fork");
        exit(1);
    }

    fprintf(fpout, "Content-Type: multipart/signed;\n"
            "    boundary=\"%s\";\n"
            "    micalg=pgp-sha1;"
            " protocol=\"application/pgp-signature\"\n"
            "\n"
            "This is a mimegpg-signed message.  If you see this text, it means that\n"
            "your E-mail software does not support MIME-formatted messages.\n"
            "\n--%s\n",
            boundary, boundary);

    while (fgets(buf, sizeof(buf), signed_content_fp) != NULL)
    {
        const char *p;

        gpgmime_write(&gpg, buf, strlen(buf));

        for (p=buf; *p; p++)
            if (*p != '\r')
                putc(*p, fpout);
    }

    fprintf(fpout, "\n--%s\n"
            "Content-Type: application/pgp-signature\n"
            "Content-Transfer-Encoding: 7bit\n\n", boundary);

    rc=gpgmime_finish(&gpg);

    if (rc)
    {
        fprintf(stderr, "%s",
                gpgmime_getoutput(&gpg));
        exit(1);
    }

    fprintf(fpout, "\n--%s--\n", boundary);

    fclose(signed_content_fp);
    if (*iseof)
        return;

    fprintf(fpout, "\n--%s%s\n", b->boundary, clos_flag ? "--":"");

    if (clos_flag)
    {
        pop_mimestack_to(stack, b);
        find_boundary(stack, iseof, fpin, fpout, 1);
    }
}
Пример #17
0
static void dogpgencrypt(struct mimestack **stack,
                         struct header *h, int *iseof,
                         FILE *fpin, FILE *fpout,
                         int argc,
                         char **argv,
                         int dosign)
{
    struct header *hp;
    char buf[BUFSIZ];
    struct gpgmime_forkinfo gpg;
    int clos_flag=0;
    struct mimestack *b=0;
    int rc;
    const char *boundary;
    int need_crlf;

    boundary=get_boundary(*stack, "", NULL);

    if (gpgmime_fork_signencrypt(NULL,
                                 (dosign ? GPG_SE_SIGN:0) | GPG_SE_ENCRYPT,
                                 argc, argv,
                                 &dumpgpg, fpout,
                                 &gpg))
    {
        perror("fork");
        exit(1);
    }

    for (hp=h; hp; hp=hp->next)
    {
        if (encode_header(hp->header))
            continue;
        fprintf(fpout, "%s", hp->header);
    }

    fprintf(fpout, "Content-Type: multipart/encrypted;\n"
            "    boundary=\"%s\";\n"
            "    protocol=\"application/pgp-encrypted\"\n"
            "\n"
            "This is a mimegpg-encrypted message.  If you see this text, it means\n"
            "that your E-mail software does not support MIME formatted messages.\n"
            "\n--%s\n"
            "Content-Type: application/pgp-encrypted\n"
            "Content-Transfer-Encoding: 7bit\n"
            "\n"
            "Version: 1\n"
            "\n--%s\n"
            "Content-Type: application/octet-stream\n"
            "Content-Transfer-Encoding: 7bit\n\n",
            boundary, boundary, boundary);

    /* For Eudora compatiblity */
    gpgmime_write(&gpg, "Mime-Version: 1.0\r\n", 19);

    for (hp=h; hp; hp=hp->next)
    {
        const char *p;

        if (!encode_header(hp->header))
            continue;

        for (p=hp->header; *p; p++)
        {
            if (*p == '\r')
                continue;

            if (*p == '\n')
                gpgmime_write(&gpg, "\r\n", 2);
            else
                gpgmime_write(&gpg, p, 1);
        }
    }

    /*
    ** Chew the content until the next MIME boundary.
    */
    need_crlf=1;

    while (!*iseof)
    {
        const char *p;

        if (fgets(buf, sizeof(buf), fpin) == NULL)
        {
            *iseof=1;
            break;
        }

        if (need_crlf)
        {
            if ((b=is_boundary(*stack, buf, &clos_flag)) != NULL)
                break;

            gpgmime_write(&gpg, "\r\n", 2);
        }

        need_crlf=0;
        for (;;)
        {
            for (p=buf; *p; p++)
            {
                if (*p == '\r')
                    continue;
                if (*p == '\n')
                {
                    need_crlf=1;
                    break;
                }

                gpgmime_write(&gpg, p, 1);
            }
            if (*p == '\n')
                break;

            if (fgets(buf, sizeof(buf), fpin) == NULL)
            {
                *iseof=1;
                break;
            }
        }
    }

    /*
    ** This needs some 'splainin.  Note that we spit out a newline at
    ** the BEGINNING of each line, above.  This generates the blank
    ** header->body separator line.  Now, if we're NOT doing multiline
    ** content, we need to follow the last line of the content with a
    ** newline.  If we're already doing multiline content, that extra
    ** newline (if it exists) is already there.
    */

    if (!*stack)
    {
        gpgmime_write(&gpg, "\r\n", 2);
    }

    rc=gpgmime_finish(&gpg);

    if (rc)
    {
        fprintf(stderr, "%s",
                gpgmime_getoutput(&gpg));
        exit(1);
    }

    fprintf(fpout, "\n--%s--\n", boundary);

    if (*iseof)
        return;

    fprintf(fpout, "\n--%s%s\n", b->boundary, clos_flag ? "--":"");

    if (clos_flag)
    {
        pop_mimestack_to(stack, b);
        find_boundary(stack, iseof, fpin, fpout, 1);
    }
}
Пример #18
0
static void dodecrypt(struct mimestack **stack, int *iseof,
                      FILE *fpin, FILE *fpout, int argc, char **argv,
                      const char *temp_file, FILE *realout)
{
    struct gpgmime_forkinfo gpg;
    char buf[BUFSIZ];
    int is_closing;
    struct mimestack *b=NULL;
    int dowrite=1;
    int rc;
    const char *new_boundary;
    const char *output;

    if (gpgmime_forkdecrypt(NULL, argc, argv, &dumpdecrypt, fpout, &gpg))
    {
        perror("fork");
        exit(1);
    }

    for (;;)
    {
        if (fgets(buf, sizeof(buf), fpin) == NULL)
        {
            *iseof=1;
            break;
        }

        if (dowrite)
            gpgmime_write(&gpg, buf, strlen(buf));

        if (!(b=is_boundary(*stack, buf, &is_closing)))
            continue;
        dowrite=0;
        if (!is_closing)
            continue;
        break;
    }

    rc=gpgmime_finish(&gpg);
    if (fflush(fpout) || ferror(fpout) || my_rewind(fpout) < 0)
    {
        perror(temp_file);
        fclose(fpout);
        unlink(temp_file);
        exit(1);
    }

    if (*iseof)
        return;

    output=gpgmime_getoutput(&gpg),

    new_boundary=get_boundary(*stack, output, rc ? NULL:fpout);

    open_result_multipart(realout, rc, new_boundary,
                          output,
                          gpgmime_getcharset(&gpg));

    if (rc == 0)
    {
        int c;

        if (fseek(fpout, 0L, SEEK_SET) < 0)
        {
            perror(temp_file);
            fclose(fpout);
            unlink(temp_file);
            exit(1);
        }

        fprintf(realout, "\n--%s\n", new_boundary);

        while ((c=getc(fpout)) != EOF)
            if (c != '\r')
                putc(c, realout);
    }

    fprintf(realout, "\n--%s--\n", new_boundary);
    pop_mimestack_to(stack, b);
}
Пример #19
0
 int request_parser::parse(request_parser::parsed_data& toFill) const
 {
   // Read boundary and body
   size_t boundaryLen, bodyLen;
   char* boundary,* body;
   boundary = get_boundary(boundaryLen);
   int httpCode = read_body(body, bodyLen);
   if (!boundary)
     return (HTTP_BAD_REQUEST);
   if ((OK) != httpCode)
     return httpCode;
   
   // Example of body starts with next three lines:
   //   -----------------------------75180758514773109461831266709 /*this is boundary*/
   //   Content-Disposition: form-data; name="fileToUpload"; filename="main.cpp" 
   //   Content-Type: text/x-c++src
   // To parse data we can skip first 'boundaryLen' bytes and then extract first line.
   // From that line we want to fetch value of filename. Next, we get to the last line
   // and move past it. Until we reach a new boundary we read all that data as a file data.
   
   // Skip boundary
   body += boundaryLen;
   while (*body == '\n' || *body == '\r') ++body;
   
   // Find file name attribute
   auto range = boost::ifind_first(body, "filename=\"");
   if (range.empty()) return (HTTP_BAD_REQUEST);
   
   // Initialize file name and size
   char* filename = range.end();
   get<FILE_NAME>(toFill) = filename;
   while (*filename != '\"') ++filename;
   get<FILE_NAME_LEN>(toFill) = static_cast<size_t>(filename - range.end());
   
   // Skip two lines (this line and Content-Type line)
   body = filename + 1;
   while (*body != '\n' && *body != '\r') ++body; // Move to the end of line
   while (*body == '\n' || *body == '\r') ++body; // Move to next line skipping new line chars (skipped FIRST line at the end)
   while (*body != '\n' && *body != '\r') ++body; // Move to the end of line
   while (*body == '\n' || *body == '\r') ++body; // Move to next line skipping new line chars (skipped TWO lines in total)
   
   // Find next boundary, that will be end of file. File begins at 'body'
   get<FILE_CONTENT>(toFill) = body;
   range = boost::find_first(body, boundary);
   get<FILE_CONTENT_LEN>(toFill) = range.begin() - get<FILE_CONTENT>(toFill);
   
   // Move to the next line
   body = range.end();
   while (*body == '\n' || *body == '\r') ++body;
   
   // Skip 2 lines
   while (*body != '\n' && *body != '\r') ++body; // Move to the end of line
   while (*body == '\n' || *body == '\r') ++body; // Move to next line skipping new line chars (skipped FIRST line at the end)
   while (*body != '\n' && *body != '\r') ++body; // Move to the end of line
   while (*body == '\n' || *body == '\r') ++body; // Move to next line skipping new line chars (skipped TWO lines in total)
   
   // Find next boundary, content of tests.xml begins at 'body'
   get<TESTS_CONTENT>(toFill) = body;
   range = boost::find_first(body, boundary);
   get<TESTS_CONTENT_LEN>(toFill) = range.begin() - get<TESTS_CONTENT>(toFill);
   return 0;
 }
Пример #20
0
static evhtp_res
upload_headers_cb (evhtp_request_t *req, evhtp_headers_t *hdr, void *arg)
{
    SearpcClient *rpc_client = NULL;
    char *token, *repo_id = NULL, *user = NULL;
    char *boundary = NULL;
    gint64 content_len;
    char *progress_id = NULL;
    char *err_msg = NULL;
    RecvFSM *fsm = NULL;
    Progress *progress = NULL;

    /* URL format: http://host:port/[upload|update]/<token>?X-Progress-ID=<uuid> */
    token = req->uri->path->file;
    if (!token) {
        seaf_warning ("[upload] No token in url.\n");
        err_msg = "Invalid URL";
        goto err;
    }

    rpc_client = ccnet_create_pooled_rpc_client (seaf->client_pool,
                                                 NULL,
                                                 "seafserv-rpcserver");

    if (check_access_token (rpc_client, token, &repo_id, &user) < 0) {
        seaf_warning ("[upload] Invalid token.\n");
        err_msg = "Access denied";
        goto err;
    }

    boundary = get_boundary (hdr);
    if (!boundary) {
        goto err;
    }

    if (get_progress_info (req, hdr, &content_len, &progress_id) < 0)
        goto err;

    progress = g_new0 (Progress, 1);
    progress->size = content_len;

    fsm = g_new0 (RecvFSM, 1);
    fsm->boundary = boundary;
    fsm->repo_id = repo_id;
    fsm->user = user;
    fsm->line = evbuffer_new ();
    fsm->form_kvs = g_hash_table_new_full (g_str_hash, g_str_equal,
                                           g_free, g_free);
    fsm->progress_id = progress_id;
    fsm->progress = progress;

    pthread_mutex_lock (&pg_lock);
    g_hash_table_insert (upload_progress, g_strdup(progress_id), progress);
    pthread_mutex_unlock (&pg_lock);

    /* Set up per-request hooks, so that we can read file data piece by piece. */
    evhtp_set_hook (&req->hooks, evhtp_hook_on_read, upload_read_cb, fsm);
    evhtp_set_hook (&req->hooks, evhtp_hook_on_request_fini, upload_finish_cb, fsm);
    /* Set arg for upload_cb or update_cb. */
    req->cbarg = fsm;

    ccnet_rpc_client_free (rpc_client);

    return EVHTP_RES_OK;

err:
    /* Don't receive any data before the connection is closed. */
    evhtp_request_pause (req);

    /* Set keepalive to 0. This will cause evhtp to close the
     * connection after sending the reply.
     */
    req->keepalive = 0;
    if (err_msg)
        evbuffer_add_printf (req->buffer_out, "%s\n", err_msg);
    evhtp_send_reply (req, EVHTP_RES_BADREQ);

    if (rpc_client)
        ccnet_rpc_client_free (rpc_client);

    g_free (repo_id);
    g_free (user);
    g_free (boundary);
    return EVHTP_RES_OK;
}
Пример #21
0
static int snd_pcm_cras_delay(snd_pcm_ioplug_t *io, snd_pcm_sframes_t *delayp)
{
	snd_pcm_uframes_t limit;
	int rc;
	struct snd_pcm_cras *pcm_cras;
	struct timespec latency;

	pcm_cras = (struct snd_pcm_cras *)io->private_data;

	rc = get_boundary(io->pcm, &limit);
	if ((rc < 0) || (limit == 0)) {
		*delayp = 0;
		return -EINVAL;
	}

	/* To get the delay, first calculate the latency between now and the
	 * playback/capture sample time for the old hw_ptr we tracked, note that
	 * for playback path this latency could be negative. Then add it up with
	 * the difference between appl_ptr and the old hw_ptr.
	 */
	if (io->stream == SND_PCM_STREAM_PLAYBACK) {
		/* Do not compute latency if playback_sample_time is not set */
		if (pcm_cras->playback_sample_time.tv_sec == 0 &&
		    pcm_cras->playback_sample_time.tv_nsec == 0) {
			latency.tv_sec = 0;
			latency.tv_nsec = 0;
		} else {
			cras_client_calc_playback_latency(
					&pcm_cras->playback_sample_time,
					&latency);
		}

		*delayp = limit +
			  io->appl_ptr -
			  pcm_cras->playback_sample_index +
			  latency.tv_sec * io->rate +
			  latency.tv_nsec / (1000000000L / (long)io->rate);
	} else {
		/* Do not compute latency if capture_sample_time is not set */
		if (pcm_cras->capture_sample_time.tv_sec == 0 &&
		    pcm_cras->capture_sample_time.tv_nsec == 0) {
			latency.tv_sec = 0;
			latency.tv_nsec = 0;
		} else {
			cras_client_calc_capture_latency(
					&pcm_cras->capture_sample_time,
					&latency);
		}

		*delayp = limit +
			  pcm_cras->capture_sample_index -
			  io->appl_ptr +
			  latency.tv_sec * io->rate +
			  latency.tv_nsec / (1000000000L / (long)io->rate);
	}

	/* Both appl and hw pointers wrap at the pcm boundary. */
	*delayp %= limit;

	return 0;
}
Пример #22
0
 const SimplexSet<FaceKey> &Tetrahedron::face_keys() const noexcept{
     return get_boundary();
 }