コード例 #1
0
ファイル: main.c プロジェクト: Morriskalb/bmcc-classwork
// this is where the magic happens
int main(int argc, const char *argv[]) {
  WINDOW *menu_win;
  node_t *curr;
  int len, ch, count, highlight = 1;
  char directions[] = "Use arrow keys to navigate, press enter to select";
  char insert_msg[] = "Enter the element you'd like to insert: ";
  char remove_msg[] = "Enter the element you'd like to remove: ";
  char count_msg[]  = "Enter the element you'd like to count: ";

  // create a new node list
  list_t *node_list = new_list();

  // initialize the ncurses session
  initscr();
  clear();
  noecho();
  cbreak();
  curs_set(0);
  getmaxyx(stdscr, stdscr_rows, stdscr_cols);
  mvprintw(2, 2, "%s", directions);

  // initialize the menu window
  menu_win = newwin(10, 50, ((stdscr_rows-10)/2), ((stdscr_cols-50)/2));
  getmaxyx(menu_win, menu_win_rows, menu_win_cols);
  keypad(menu_win, TRUE);
  print_menu(menu_win, highlight);
  refresh();

  // enter continuous loop to let user use the menu
  while (1) {
    switch(ch = wgetch(menu_win)) {
      case KEY_UP:
        if (highlight == 1)
          highlight = n_choices;
        else
          --highlight;
        break;
      case KEY_DOWN:
        if (highlight == n_choices)
          highlight = 1;
        else
          ++highlight;
        break;
      case 10:
        switch (highlight) {
          case 1: /* print */
            if (node_list->len) {
              len = node_list->len;
              curr = node_list->head->next;
              mvprintw(stdscr_rows - 2, 2, "List elements:");
              clrtoeol();
              while (len--) {
                printw(" %d", curr->val);
                curr = curr->next;
              }
            } else {
              mvprintw(stdscr_rows - 2, 2, "The list is empty");
              clrtoeol();
            }
            break;
          case 2: /* insert one */
            list_insert(node_list, new_node(get_input(insert_msg)));
            mvprintw(stdscr_rows - 2, 2, "Element Inserted!");
            clrtoeol();
            break;
          case 3: /* remove one */
            curr = list_find(node_list, get_input(remove_msg));

            if (curr) {
              list_remove(node_list, curr);
              mvprintw(stdscr_rows - 2, 2, "Element Removed!");
            } else {
              mvprintw(stdscr_rows - 2, 2, "Element Not Found!");
            }

            clrtoeol();
            break;
          case 4: /* remove each */
            curr = list_find(node_list, get_input(remove_msg));

            if (curr) {
              list_remove_each(node_list, curr);
              mvprintw(stdscr_rows - 2, 2, "All Matching Elements Removed!");
            } else {
              mvprintw(stdscr_rows - 2, 2, "Element Not Found!");
            }

            clrtoeol();
            break;
          case 5: /* remove all */
            list_remove_all(node_list);
            mvprintw(stdscr_rows - 2, 2, "All Elements Removed!");
            clrtoeol();
            break;
          case 6: /* count elements */
            mvprintw(stdscr_rows - 2, 2, "List length: %d", node_list->len);
            clrtoeol();
            break;
          case 7: /* count occurrences */
            count = list_count_each(node_list, get_input(count_msg));
            mvprintw(stdscr_rows - 2, 2, "Occurrences: %d", count);
            clrtoeol();
            break;
          case 8: /* exit */
            list_destroy(node_list);
            endwin();
            return 0;
        }
    }

    print_menu(menu_win, highlight);
    refresh();
  }
} /* end main() */
コード例 #2
0
ファイル: intset.c プロジェクト: Comnir/synchrobench
int set_add(intset_t *set, val_t val, int transactional)
{
	int result;
	
#ifdef DEBUG
	printf("++> set_add(%d)\n", (int)val);
	IO_FLUSH;
#endif

	if (!transactional) {
		
		result = set_seq_add(set, val);
		
	} else { 
	
#ifdef SEQUENTIAL /* Unprotected */
		
		result = set_seq_add(set, val);
		
#elif defined STM
	
		node_t *prev, *next;
		val_t v;	
	
		if (transactional > 2) {

		  TX_START(EL);
		  prev = set->head;
		  next = (node_t *)TX_LOAD(&prev->next);
		  while (1) {
		    v = TX_LOAD((uintptr_t *) &next->val);
		    if (v >= val)
		      break;
		    prev = next;
		    next = (node_t *)TX_LOAD(&prev->next);
		  }
		  result = (v != val);
		  if (result) {
		    TX_STORE(&prev->next, new_node(val, next, transactional));
		  }
		  TX_END;
		  
		} else {

		  TX_START(NL);
		  prev = set->head;
		  next = (node_t *)TX_LOAD(&prev->next);
		  while (1) {
		    v = TX_LOAD((uintptr_t *) &next->val);
		    if (v >= val)
		      break;
		    prev = next;
		    next = (node_t *)TX_LOAD(&prev->next);
		  }
		  result = (v != val);
		  if (result) {
		    TX_STORE(&prev->next, new_node(val, next, transactional));
		  }
		  TX_END;

		}

#elif defined LOCKFREE
		result = harris_insert(set, val);
#endif
		
	}
	
	return result;
}
コード例 #3
0
ファイル: Desk.cpp プロジェクト: ejasiunas/bbclean-xzero450
ST void hidewnd (HWND hwnd)
{
    if (hwnd && ShowWindow(hwnd, SW_HIDE))
        cons_node(&basebarlist, new_node(hwnd));
}
コード例 #4
0
ファイル: intset.c プロジェクト: digideskio/tinystm
static int set_add(intset_t *set, val_t val, thread_data_t *td)
{
  int result;
  node_t *prev, *next;
  val_t v;

# ifdef DEBUG
  printf("++> set_add(%d)\n", val);
  IO_FLUSH;
# endif

  if (td == NULL) {
    prev = set->head;
    next = prev->next;
    while (next->val < val) {
      prev = next;
      next = prev->next;
    }
    result = (next->val != val);
    if (result) {
      prev->next = new_node(val, next, 0);
    }
  } else if (td->unit_tx == 0) {
    TM_START(1, RW);
    prev = (node_t *)TM_LOAD(&set->head);
    next = (node_t *)TM_LOAD(&prev->next);
    while (1) {
      v = TM_LOAD(&next->val);
      if (v >= val)
        break;
      prev = next;
      next = (node_t *)TM_LOAD(&prev->next);
    }
    result = (v != val);
    if (result) {
      TM_STORE(&prev->next, new_node(val, next, 1));
    }
    TM_COMMIT;
  } 
#ifndef TM_COMPILER
  else {
    /* Unit transactions */
    stm_word_t ts, start_ts, val_ts;
  restart:
    start_ts = stm_get_clock();
    /* Head node is never removed */
    prev = (node_t *)TM_UNIT_LOAD(&set->head, &ts);
    next = (node_t *)TM_UNIT_LOAD(&prev->next, &ts);
    if (ts > start_ts)
      start_ts = ts;
    while (1) {
      v = TM_UNIT_LOAD(&next->val, &val_ts);
      if (val_ts > start_ts) {
        /* Restart traversal (could also backtrack) */
        goto restart;
      }
      if (v >= val)
        break;
      prev = next;
      next = (node_t *)TM_UNIT_LOAD(&prev->next, &ts);
      if (ts > start_ts) {
        /* Verify that node has not been modified (value and pointer are updated together) */
        TM_UNIT_LOAD(&prev->val, &val_ts);
        if (val_ts > start_ts) {
          /* Restart traversal (could also backtrack) */
          goto restart;
        }
        start_ts = ts;
      }
    }
    result = (v != val);
    if (result) {
      node_t *n = new_node(val, next, 0);
      /* Make sure that there are no concurrent updates to that memory location */
      if (!TM_UNIT_STORE(&prev->next, n, &ts)) {
        free(n);
        goto restart;
      }
    }
  }
#endif /* ! TM_COMPILER */

  return result;
}
コード例 #5
0
ファイル: quadtree.c プロジェクト: joe07734/Photometry
node_t *new_quadtree(double xmin, double ymin, double xmax, double ymax) {
    return new_node(xmin, ymin, xmax, ymax);
}
コード例 #6
0
ファイル: placedetection.cpp プロジェクト: cagbal/SSG-C-
void PlaceDetection::processImages()
{
    static Mat img1, img2;
    Mat img_seg1, img_seg2;
    vector<NodeSig> ns1, ns2;
    vector<vector<NodeSig> > ns_vec;  //Stores last tau_w node signatures
    float matching_cost = 0;

    bool in_place = false; //Flag whether we are in place or transition

    isProcessing = true;

    //Process all images
    for(int frame_no = START_IDX; frame_no < END_IDX-1; frame_no++)
    {
        //Wait until process_next_frame set to true
        while(frameByFrameProcess == true && process_next_frame == false)
        {
            waitKey(1);
        }
        //Set it back to false
        process_next_frame = false;

        //getFilePath returns the path of the file given frame number
        string filepath1 = getFilePath(DATASET_FOLDER, DATASET_NO, IMG_FILE_PREFIX, frame_no);
        string filepath2 = getFilePath(DATASET_FOLDER, DATASET_NO, IMG_FILE_PREFIX, frame_no+1);

        //Segment images
        if(frame_no == START_IDX)
        {
            img2 = imread(filepath1);
            resize(img2, img2, cv::Size(0,0), IMG_RESCALE_RAT, IMG_RESCALE_RAT);
            ns2 = seg_track->seg->segmentImage(img2,img_seg2);
        }
        ns1 = ns2;
        img1 = img2;
        img_seg1 = img_seg2;

        img2 = imread(filepath2);
        resize(img2, img2, cv::Size(0,0), IMG_RESCALE_RAT, IMG_RESCALE_RAT);
        ns2 = seg_track->seg->segmentImage(img2,img_seg2);


        //Show original images on the window
        //emit seg_track->shshowImg1(mat2QImage(img1));
        //emit seg_track->showImg2(mat2QImage(img2));

        if(frame_no == START_IDX)
        {
            //Initialize M matrix (Existence "M"ap)
            seg_track->M = Mat(ns1.size(), 1, CV_32S, -1);

            for(int i = 0; i < ns1.size(); i++)
            {
                seg_track->M.at<int>(i,0) = i; //Nodes are placed in order in the first column of M

                //Initialize avg node signatures list
                pair<NodeSig, int> new_node(ns1[i], 1);

                seg_track->M_ns.push_back(new_node);
            }

            //Insert first node sig for the first time
            ns_vec.push_back(ns1);
        }

        //Insert next node sig
        ns_vec.push_back(ns2);

        //Keep max size tau_w
        if(ns_vec.size() > seg_track->tau_w)
        {
            ns_vec.erase(ns_vec.begin());
        }

        //Drawing purposes only
        seg_track->gm->drawMatches(ns1, ns2, img_seg1, img_seg2);

        //Fill node existence map
        matching_cost = seg_track->fillNodeMap(seg_track->M, seg_track->M_ns, ns_vec);


        //Plot connectivity map
        seg_track->plotMap(seg_track->M);

        //Calculate coherency based on existence map
        calcCohScore(seg_track->M, seg_track->M_ns, coherency_scores);

        //Decide last frame is whether transition or place
        //Results are written into detected places
        int detection_result = detectPlace(coherency_scores,detected_places_unfiltered,detected_places);

        //If started for new place
        //Create new SSG
        if(detection_result == 1)
        {
            SSG new_ssg;
            SSGs.push_back(new_ssg);
            in_place = true;
        }
        else if(detection_result == -1)
        {
            in_place = false;
        }

        //Fill SSG if frame is as place
        if(in_place)
        {
            SSGProc::updateSSG(SSGs.back(), ns2, seg_track->M);
        }

        //Show last SSG
        if(SSGs.size() > 0)
        {
            img2 = imread(filepath2);
            //emit showSSG(mat2QImage(SSGProc::drawSSG(SSGs.back(), img2)));
        }

        //Plot transition and place regions
        plotPlaces(coherency_scores, detected_places);

        //Wait a little for GUI processing
        waitKey(1);
    }

    isProcessing = false;
}
コード例 #7
0
struct linkedlist* new_linkedlist(char *s) {
    struct linkedlist* l = (struct linkedlist*)malloc(sizeof(struct linkedlist));
    l->head = new_node(s);
    l->tail = l->head;
    return l;
}
コード例 #8
0
ファイル: initobj.c プロジェクト: daveshields/AdaEd
static Tuple proc_init_rec(Symbol type_name, Tuple field_names,
  Node variant_node, Node out_param)					/*;proc_init_rec*/
{
	/*
	 *  This is a subsidiary procedure to BUILD_PROC_INIT, which performs
	 *  the recursive part of construction of an initialization procedure
	 *  for a record type.
	 *
	 *  Input: field_names is a list of component unique names (excluding
	 *         discriminants. Variant node is the AST for the variant part
	 *         of a component list.
	 *	  variant_node is the variant part of the record declaration
	 *	  and has the same structure as a case statement.
	 *
	 *         out_param designates the object being initialized
	 *
	 *  Output: the statement list required to initialize this fragment of
	 *          the record, or [] if not default initialization is needed.
	 */

	Tuple	init_stmt, stmts;
	Node		one_component, f_init, c_node, variant_list;
	Symbol	f_type, f_name, ip;
	Fortup	ft1;
	int		empty_case;
	Tuple	case_list, comp_case_list;
	Node		choice_list, comp_list, disc_node;
	Node		invariant_node, new_case, list_node, case_node;

	Tuple	tup, index_list;
	int		nb_dim, i;
	Node		d_node,  node, node1, node2, node3, node4, node5;
	Symbol	one_index_type;

	/* process fixed part first. */
	init_stmt = tup_new(0);
	FORTUP(f_name=(Symbol), field_names, ft1);
		one_component    = new_selector_node(out_param, f_name);
		f_type           = TYPE_OF(f_name);
                CONTAINS_TASK(type_name) = (char *)
                  ((int)CONTAINS_TASK(type_name) | (int) CONTAINS_TASK(f_type));

		f_init = (Node) default_expr(f_name);
		if (f_init  != OPT_NODE) {
			init_stmt = tup_with(init_stmt,
			  (char *) new_assign_node(one_component,
			   remove_discr_ref(f_init, out_param)));
		}
		else if ((ip = INIT_PROC(base_type(f_type)))!=(Symbol)0) {
			init_stmt  = tup_with(init_stmt,
		      (char *) build_init_call(one_component, ip, f_type, out_param));
		}
		else if (is_task_type(f_type)) {
			init_stmt  = tup_with(init_stmt, (char *)
		      new_assign_node(one_component, new_create_task_node(f_type)));
		}
		else if (is_access_type(f_type)) {
			init_stmt  = tup_with(init_stmt, (char *)
		      new_assign_node(one_component, new_null_node(f_type)));
		}


		/* if we have an aray then we have to check if its bounds are
		 * compatible with the index subtypes (of the unconstrained array) 
		 * (This code was generated beforehand in type.c ("need_qual_r") but
		 * it was wrong : we have to test the bounds only if the field is
		 * present (case of variant record).
		 * The generation of the tests is easier here
		 */

		if (is_array_type (f_type)) {
			tup = (Tuple) SIGNATURE(TYPE_OF(f_type));
			index_list = tup_copy((Tuple) tup[1]);
			nb_dim = tup_size(index_list);

			for (i = 1; i <= nb_dim; i++) {
				one_index_type = (Symbol) (tup_fromb (index_list));

				d_node   = new_ivalue_node(int_const(i), symbol_integer);

				node1 = new_attribute_node(ATTR_O_FIRST,
			      one_component, d_node, one_index_type);

				node2 = new_attribute_node(ATTR_O_LAST,
			      one_component, d_node, one_index_type);

				node3 = new_attribute_node(ATTR_T_FIRST,
				  new_name_node(one_index_type), OPT_NODE, one_index_type);

				node4 = new_attribute_node(ATTR_T_LAST,
				  new_name_node(one_index_type), OPT_NODE, one_index_type);

				node5 = new_binop_node(symbol_or,
			      new_binop_node(symbol_lt, node1, node3, symbol_boolean),
			      new_binop_node(symbol_gt, node2, node4, symbol_boolean),
			      symbol_boolean);

				node = node_new (as_list);
				make_if_node(node,
			    tup_new1((char *) new_cond_stmts_node(
			      new_binop_node(symbol_and,
			      new_binop_node(symbol_le, node1, node2, symbol_boolean),
			      node5, symbol_boolean),
			      new_raise_node(symbol_constraint_error))), OPT_NODE);
				init_stmt  = tup_with(init_stmt, (char *) (node));
			}
		}
	ENDFORTUP(ft1);

	/* then build case statement to parallel structure of variant part. */

	empty_case = TRUE;    /* assumption */
	if (variant_node != OPT_NODE) {

		disc_node= N_AST1(variant_node);
		variant_list = N_AST2(variant_node);

		case_list = tup_new(0);

		comp_case_list = N_LIST(variant_list);

		FORTUP(c_node=(Node), comp_case_list, ft1);
			choice_list = N_AST1(c_node);
			comp_list = N_AST2(c_node);
			invariant_node = N_AST1(comp_list);
			variant_node = N_AST2(comp_list);

			field_names = build_comp_names(invariant_node);
			stmts = proc_init_rec(type_name,field_names,variant_node, out_param);

			/*empty_case and= stmts = [];*/
			empty_case = empty_case ? (tup_size(stmts)==0) : FALSE;
			new_case = (N_KIND(c_node) == as_others_choice) ?
			  new_node(as_others_choice) : new_node(as_variant_choices);
			N_AST1(new_case) = copy_tree(choice_list);
			N_AST2(new_case) = new_statements_node(stmts);
			case_list = tup_with(case_list, (char *)  new_case );
		ENDFORTUP(ft1);

		if (! empty_case) {
			/* Build a case statement ruled by the value of the discriminant */
			/* for this variant part. */

			list_node         = new_node(as_list);
			N_LIST(list_node) = case_list;
			case_node         = new_node(as_case);
			N_AST1(case_node)  = new_selector_node(out_param, N_UNQ(disc_node));
			N_AST2(case_node) = list_node;
			init_stmt    = tup_with(init_stmt, (char *) case_node );
		}
	}
	return init_stmt;
}
コード例 #9
0
ファイル: initobj.c プロジェクト: daveshields/AdaEd
Node build_proc_init_ara(Symbol type_name)				/*;build_proc_init_ara*/
{
	/*
	 *  This is the   main procedure for  building default  initialization
	 *  procedures for array  types. Those  initialization  procedures are
	 *  built if  the type  given  contains  some subcomponent for which a
	 *  default initialization exists (at any level of nesting),  or if it
	 *  has determinants.
	 *  Note that scalar objects are not initialized at all, which implies
	 *  that they get whatever initial value is in that location in memory
	 *  This saves some time in object creation.
	 *
	 *  All init. procedures  have an 'out' parameter that  designates the
	 *  object being initialized (the space has already been allocated).
	 *
	 */

	int		side_effect;
	Tuple	tup, formals, subscripts;
	Symbol	c_type, ip, index_t, proc_name, index_sym;
	Node	one_component, init_stmt, out_param, i_nodes, d_node, iter_node;
	Fortup	ft1;
	Node	iterator, index_node;

#ifdef TRACE
	if (debug_flag) {
		gen_trace_symbol("BUILD_PROC_INIT_ARR", type_name);
	}
#endif

	side_effect = FALSE;	 /* Let's hope... TBSL */

	tup = SIGNATURE(type_name);
	c_type    = (Symbol) tup[2];
	one_component = new_node(as_index);

	ip = INIT_PROC(base_type(c_type));
	if (ip != (Symbol)0 ){
		/* Use the initialization procedure for the component type */
		init_stmt = (Node) build_init_call(one_component, ip, c_type, OPT_NODE);
	}
	else if (is_task_type(c_type)) {
		/* initialization is task creation. */
		init_stmt =
		  new_assign_node(one_component, new_create_task_node(c_type));
	}
	else if (is_access_type(c_type)) {
		/* default value is the null pointer. */
		init_stmt = new_assign_node(one_component, new_null_node(c_type));
	}
	else {
		init_stmt = (Node) 0;
	}

	if (init_stmt != (Node)0) {
		/* body of initialization procedure is a loop over the indices */
		/* allocating each component. Generate loop variables and code */
		/* for iteration, using the attributes of the type. */

		proc_name = new_unique_name("type_name+INIT");
		out_param = new_param_node("param_type_name", proc_name,
		   type_name, na_out);
		generate_object(N_UNQ(out_param));
		formals               = tup_new1((char *) out_param);
		subscripts            = tup_new(0);
		FORTUP(index_t=(Symbol), index_types(type_name), ft1);
			/*index          = index_t + 'INDEX';*/
			index_sym          = new_unique_name("index_t+INDEX");
			NATURE (index_sym) = na_obj;
			TYPE_OF(index_sym) = index_t;
			subscripts = tup_with(subscripts, (char *)new_name_node(index_sym));
		ENDFORTUP(ft1);

		i_nodes         = new_node(as_list);
		/* need tup_copy since subscripts used destructively below */
		N_LIST(i_nodes) = tup_copy(subscripts);

		/* Build the tree for the one_component of the array. */
		N_AST1(one_component) = out_param;
		N_AST2(one_component) = i_nodes;
		N_TYPE(one_component) = c_type;

		while (tup_size(subscripts)) {
			/* Build loop from innermost index outwards. The iterations */
			/* span the ranges of the array being initialized. */

			/* dimension spanned by this loop: */
			d_node   = new_ivalue_node(int_const(tup_size(subscripts)), 
			  symbol_integer);
			iterator = new_attribute_node(ATTR_O_RANGE,
			  new_name_node(N_UNQ(out_param)), d_node, type_name);

			index_node = (Node) tup_frome(subscripts);
			iter_node        = new_node(as_for);
			N_AST1(iter_node) = index_node;
			N_AST2(iter_node) = iterator;

			init_stmt = new_loop_node(OPT_NODE, iter_node, 
			  tup_new1((char *)init_stmt));
		}

		INIT_PROC(type_name) = proc_name;
		return initialization_proc(proc_name, type_name,
		  formals, tup_new1((char *) init_stmt));
	}
	else {
		return OPT_NODE;
	}

}
コード例 #10
0
	void fake_event_source::add_event(const size_t time, const SDL_Event& event)
	{
		event_node_ptr new_node(new event_node(time,event));
		queue_.push(new_node);
	}
コード例 #11
0
ファイル: net_setup.c プロジェクト: Vilbrekin/tinc
/*
  Configure node_t myself and set up the local sockets (listen only)
*/
static bool setup_myself(void) {
    config_t *cfg;
    subnet_t *subnet;
    char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
    char *fname = NULL;
    char *address = NULL;
    char *proxy = NULL;
    char *space;
    char *envp[5] = {NULL};
    struct addrinfo *ai, *aip, hint = {0};
    bool choice;
    int i, err;
    int replaywin_int;
    bool port_specified = false;

    myself = new_node();
    myself->connection = new_connection();

    myself->hostname = xstrdup("MYSELF");
    myself->connection->hostname = xstrdup("MYSELF");

    myself->connection->options = 0;
    myself->connection->protocol_version = PROT_CURRENT;

    if(!(name = get_name())) {
        logger(LOG_ERR, "Name for tinc daemon required!");
        return false;
    }

    /* Read tinc.conf and our own host config file */

    myself->name = name;
    myself->connection->name = xstrdup(name);
    xasprintf(&fname, "%s/hosts/%s", confbase, name);
    read_config_options(config_tree, name);
    read_config_file(config_tree, fname);
    free(fname);

    if(!read_rsa_private_key())
        return false;

    if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
        myport = xstrdup("655");
    else
        port_specified = true;

    /* Ensure myport is numeric */

    if(!atoi(myport)) {
        struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
        sockaddr_t sa;
        if(!ai || !ai->ai_addr)
            return false;
        free(myport);
        memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
        sockaddr2str(&sa, NULL, &myport);
    }

    get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
    if(proxy) {
        if((space = strchr(proxy, ' ')))
            *space++ = 0;

        if(!strcasecmp(proxy, "none")) {
            proxytype = PROXY_NONE;
        } else if(!strcasecmp(proxy, "socks4")) {
            proxytype = PROXY_SOCKS4;
        } else if(!strcasecmp(proxy, "socks4a")) {
            proxytype = PROXY_SOCKS4A;
        } else if(!strcasecmp(proxy, "socks5")) {
            proxytype = PROXY_SOCKS5;
        } else if(!strcasecmp(proxy, "http")) {
            proxytype = PROXY_HTTP;
        } else if(!strcasecmp(proxy, "exec")) {
            proxytype = PROXY_EXEC;
        } else {
            logger(LOG_ERR, "Unknown proxy type %s!", proxy);
            return false;
        }

        switch(proxytype) {
        case PROXY_NONE:
        default:
            break;

        case PROXY_EXEC:
            if(!space || !*space) {
                logger(LOG_ERR, "Argument expected for proxy type exec!");
                return false;
            }
            proxyhost =  xstrdup(space);
            break;

        case PROXY_SOCKS4:
        case PROXY_SOCKS4A:
        case PROXY_SOCKS5:
        case PROXY_HTTP:
            proxyhost = space;
            if(space && (space = strchr(space, ' ')))
                *space++ = 0, proxyport = space;
            if(space && (space = strchr(space, ' ')))
                *space++ = 0, proxyuser = space;
            if(space && (space = strchr(space, ' ')))
                *space++ = 0, proxypass = space;
            if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
                logger(LOG_ERR, "Host and port argument expected for proxy!");
                return false;
            }
            proxyhost = xstrdup(proxyhost);
            proxyport = xstrdup(proxyport);
            if(proxyuser && *proxyuser)
                proxyuser = xstrdup(proxyuser);
            if(proxypass && *proxypass)
                proxypass = xstrdup(proxypass);
            break;
        }

        free(proxy);
    }

    /* Read in all the subnets specified in the host configuration file */

    cfg = lookup_config(config_tree, "Subnet");

    while(cfg) {
        if(!get_config_subnet(cfg, &subnet))
            return false;

        subnet_add(myself, subnet);

        cfg = lookup_config_next(config_tree, cfg);
    }

    /* Check some options */

    if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
        myself->options |= OPTION_INDIRECT;

    if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
        myself->options |= OPTION_TCPONLY;

    if(myself->options & OPTION_TCPONLY)
        myself->options |= OPTION_INDIRECT;

    get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
    get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
    get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
    get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
    strictsubnets |= tunnelserver;

    if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
        if(!strcasecmp(mode, "router"))
            routing_mode = RMODE_ROUTER;
        else if(!strcasecmp(mode, "switch"))
            routing_mode = RMODE_SWITCH;
        else if(!strcasecmp(mode, "hub"))
            routing_mode = RMODE_HUB;
        else {
            logger(LOG_ERR, "Invalid routing mode!");
            return false;
        }
        free(mode);
    }

    if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
        if(!strcasecmp(mode, "off"))
            forwarding_mode = FMODE_OFF;
        else if(!strcasecmp(mode, "internal"))
            forwarding_mode = FMODE_INTERNAL;
        else if(!strcasecmp(mode, "kernel"))
            forwarding_mode = FMODE_KERNEL;
        else {
            logger(LOG_ERR, "Invalid forwarding mode!");
            return false;
        }
        free(mode);
    }

    choice = true;
    get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
    if(choice)
        myself->options |= OPTION_PMTU_DISCOVERY;

    choice = true;
    get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
    if(choice)
        myself->options |= OPTION_CLAMP_MSS;

    get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
    get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
    if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
        if(!strcasecmp(mode, "no"))
            broadcast_mode = BMODE_NONE;
        else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
            broadcast_mode = BMODE_MST;
        else if(!strcasecmp(mode, "direct"))
            broadcast_mode = BMODE_DIRECT;
        else {
            logger(LOG_ERR, "Invalid broadcast mode!");
            return false;
        }
        free(mode);
    }

#if !defined(SOL_IP) || !defined(IP_TOS)
    if(priorityinheritance)
        logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
#endif

    if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
        macexpire = 600;

    if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
        if(maxtimeout <= 0) {
            logger(LOG_ERR, "Bogus maximum timeout!");
            return false;
        }
    } else
        maxtimeout = 900;

    if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
        if(udp_rcvbuf <= 0) {
            logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
            return false;
        }
    }

    if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
        if(udp_sndbuf <= 0) {
            logger(LOG_ERR, "UDPSndBuf cannot be negative!");
            return false;
        }
    }

    if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
        if(replaywin_int < 0) {
            logger(LOG_ERR, "ReplayWindow cannot be negative!");
            return false;
        }
        replaywin = (unsigned)replaywin_int;
    }

    if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
        if(!strcasecmp(afname, "IPv4"))
            addressfamily = AF_INET;
        else if(!strcasecmp(afname, "IPv6"))
            addressfamily = AF_INET6;
        else if(!strcasecmp(afname, "any"))
            addressfamily = AF_UNSPEC;
        else {
            logger(LOG_ERR, "Invalid address family!");
            return false;
        }
        free(afname);
    }

    get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);

    /* Generate packet encryption key */

    if(get_config_string
            (lookup_config(config_tree, "Cipher"), &cipher)) {
        if(!strcasecmp(cipher, "none")) {
            myself->incipher = NULL;
        } else {
            myself->incipher = EVP_get_cipherbyname(cipher);

            if(!myself->incipher) {
                logger(LOG_ERR, "Unrecognized cipher type!");
                return false;
            }
        }
    } else
        myself->incipher = EVP_bf_cbc();

    if(myself->incipher)
        myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
    else
        myself->inkeylength = 1;

    myself->connection->outcipher = EVP_bf_ofb();

    if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
        keylifetime = 3600;

    keyexpires = now + keylifetime;

    /* Check if we want to use message authentication codes... */

    if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
        if(!strcasecmp(digest, "none")) {
            myself->indigest = NULL;
        } else {
            myself->indigest = EVP_get_digestbyname(digest);

            if(!myself->indigest) {
                logger(LOG_ERR, "Unrecognized digest type!");
                return false;
            }
        }
    } else
        myself->indigest = EVP_sha1();

    myself->connection->outdigest = EVP_sha1();

    if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
        if(myself->indigest) {
            if(myself->inmaclength > myself->indigest->md_size) {
                logger(LOG_ERR, "MAC length exceeds size of digest!");
                return false;
            } else if(myself->inmaclength < 0) {
                logger(LOG_ERR, "Bogus MAC length!");
                return false;
            }
        }
    } else
        myself->inmaclength = 4;

    myself->connection->outmaclength = 0;

    /* Compression */

    if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
        if(myself->incompression < 0 || myself->incompression > 11) {
            logger(LOG_ERR, "Bogus compression level!");
            return false;
        }
    } else
        myself->incompression = 0;

    myself->connection->outcompression = 0;

    /* Done */

    myself->nexthop = myself;
    myself->via = myself;
    myself->status.reachable = true;
    node_add(myself);

    graph();

    if(strictsubnets)
        load_all_subnets();

    /* Open device */

    devops = os_devops;

    if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
        if(!strcasecmp(type, "dummy"))
            devops = dummy_devops;
        else if(!strcasecmp(type, "raw_socket"))
            devops = raw_socket_devops;
        else if(!strcasecmp(type, "multicast"))
            devops = multicast_devops;
#ifdef ENABLE_UML
        else if(!strcasecmp(type, "uml"))
            devops = uml_devops;
#endif
#ifdef ENABLE_VDE
        else if(!strcasecmp(type, "vde"))
            devops = vde_devops;
#endif
    }

    if(!devops.setup())
        return false;

    /* Run tinc-up script to further initialize the tap interface */
    xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
    xasprintf(&envp[1], "DEVICE=%s", device ? : "");
    xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
    xasprintf(&envp[3], "NAME=%s", myself->name);

    execute_script("tinc-up", envp);

    for(i = 0; i < 4; i++)
        free(envp[i]);

    /* Run subnet-up scripts for our own subnets */

    subnet_update(myself, NULL, true);

    /* Open sockets */

    if(!do_detach && getenv("LISTEN_FDS")) {
        sockaddr_t sa;
        socklen_t salen;

        listen_sockets = atoi(getenv("LISTEN_FDS"));
#ifdef HAVE_UNSETENV
        unsetenv("LISTEN_FDS");
#endif

        if(listen_sockets > MAXSOCKETS) {
            logger(LOG_ERR, "Too many listening sockets");
            return false;
        }

        for(i = 0; i < listen_sockets; i++) {
            salen = sizeof sa;
            if(getsockname(i + 3, &sa.sa, &salen) < 0) {
                logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
                return false;
            }

            listen_socket[i].tcp = i + 3;

#ifdef FD_CLOEXEC
            fcntl(i + 3, F_SETFD, FD_CLOEXEC);
#endif

            listen_socket[i].udp = setup_vpn_in_socket(&sa);
            if(listen_socket[i].udp < 0)
                return false;

            ifdebug(CONNECTIONS) {
                hostname = sockaddr2hostname(&sa);
                logger(LOG_NOTICE, "Listening on %s", hostname);
                free(hostname);
            }

            memcpy(&listen_socket[i].sa, &sa, salen);
        }
    } else {
コード例 #12
0
ファイル: dlite.cpp プロジェクト: winrap/DstarLite
SearchResult Dlite::FindThePath(LocalMap &map, const Map& const_map, EnvironmentOptions options)
{
    opt = options;
    std::chrono::time_point<std::chrono::system_clock> tstart, end;
    tstart = std::chrono::system_clock::now();
    number_of_steps = 0;
    current_result.pathlength = 0;
    Initialize(map);
    last = start;

    if(!ComputeShortestPath(map))
        std::cout << "OOOPS\n";
    else
        std::cout << "Done\n";
    std::cout << current_result.pathlength <<std::endl;
    while(start->point != goal->point) {
        Cell jump = start->point;
        Node min_val = GetMinPredecessor(start, map);
        path.push_back(*start);
        if (!min_val.parent) {
            OPEN.remove_if(start);
            current_result.pathfound = false;
            current_result.pathlength = 0;
            return current_result;
        } else {
            current_result.pathlength += GetCost(start->point, min_val.parent->point, map);
            start = min_val.parent;
        }
        min_val = GetMinPredecessor(start, map);
        while (opt.allowjump && euclid_dist(jump, min_val.parent->point) < radius && start->point != goal->point) {
            path.push_back(*start);
            if (!min_val.parent) {
                OPEN.remove_if(start);
                current_result.pathfound = false;
                current_result.pathlength = 0;
                return current_result;
            } else {
                current_result.pathlength += GetCost(start->point, min_val.parent->point, map);
                start = min_val.parent;
            }
            min_val = GetMinPredecessor(start, map);
        }
        UpdateVertex(start);
        Changes changes = map.UpdateMap(const_map, start->point, radius);
        if (!changes.cleared.empty() && !changes.occupied.empty()) {
            Km += heuristic(last->point, start->point, opt.metrictype);
            last = start;
        }
        for (auto dam : changes.occupied) {
            if (NODES.count(vertex(dam, map.height))) {
                Node* d = &(NODES.find(vertex(dam, map.height))->second);
                OPEN.remove_if(d);
                for (auto neighbor: GetSurroundings(d, map)) {
                    //std::cout << "n: " << neighbor->point << std::endl;
                    if (neighbor->point != map.goal && (neighbor->parent->point == dam || CutOrSqueeze(neighbor, d))) {
                        Node min_val = GetMinPredecessor(neighbor, map);
                        if (!min_val.parent) {
                            OPEN.remove_if(neighbor);
                            if(neighbor->point == start->point) {
                                current_result.pathfound = false;
                                current_result.pathlength = 0;
                                return current_result;
                            }
                        } else {
                            neighbor->rhs = min_val.rhs;
                            neighbor->parent = min_val.parent;
                           // std::cout << "changed: "
                             //         << neighbor->point << ' ' << neighbor->parent->point << std::endl;
                            UpdateVertex(neighbor);
                        }
                    }
                }
            }
        }
        for (auto cleared : changes.cleared) {
           Node new_node(cleared);
           new_node.rhs = std::numeric_limits<double>::infinity();
           new_node.g = std::numeric_limits<double>::infinity();
           NODES[vertex(cleared, map.height)] = new_node;
           Node * cl = &(NODES.find(vertex(cleared, map.height))->second);
           Node min_val = GetMinPredecessor(cl, map);
           if (min_val.parent) {
               cl->rhs = min_val.rhs;
               cl->parent = min_val.parent;
               cl->g = min_val.parent->g + GetCost(cl->point, min_val.parent->point, map);
               UpdateVertex(cl);
           } else {
               break;
           }
           for (auto neighbor : GetSuccessors(cl, map)) {
               if (neighbor->rhs > cl->g + GetCost(neighbor->point, cl->point, map)) {
                   neighbor->parent = cl;
                   neighbor->rhs = cl->g + GetCost(neighbor->point, cl->point, map);
                   UpdateVertex(neighbor);
               }
               if (neighbor->point.x == cl->point.x || neighbor->point.y == cl->point.y) {
                   Node min_val = GetMinPredecessor(neighbor, map);
                   if (!min_val.parent) {
                       OPEN.remove_if(neighbor);
                       if(neighbor->point == start->point) {
                           current_result.pathfound = false;
                           current_result.pathlength = 0;
                           return current_result;
                       }
                   } else {
                       neighbor->rhs = min_val.rhs;
                       neighbor->parent = min_val.parent;
                       //std::cout << "changed: "
                       //          << neighbor->point << ' ' << neighbor->parent->point << std::endl;
                       UpdateVertex(neighbor);
                   }
               }
           }
        }
        if(ComputeShortestPath(map)){
            //std::cout << "ALL OK\n";
            continue;
        } else {
            std::cout << "NOT OK"  << std::endl;
            if (OPEN.top_key() == Key(std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity())) {
                current_result.pathfound = false;
                current_result.pathlength = 0;
                break;
            }
        }
    }
    end = std::chrono::system_clock::now();
    current_result.time = static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(end - tstart).count()) / 1000000000;
    //map.PrintPath(path);
    current_result.lppath = &path;
    if (current_result.pathfound) {
        makeSecondaryPath();
        current_result.hppath = &hpath;
    }
    //for (auto elem: path) std::cout << elem->point << " ";
    //std::cout << std::endl;
    return current_result;
}
コード例 #13
0
node<P> batch_insert(DistanceCallback& dcb, const P& p,
		int max_scale,
		int top_scale,
		v_array<ds_node<P> >& point_set,
		v_array<ds_node<P> >& consumed_set,
		v_array<v_array<ds_node<P> > >& stack)
{
	if (point_set.index == 0)
		return new_leaf(p);
	else {
		ScalarType max_dist = max_set(point_set); //O(|point_set|)
		int next_scale = std::min(max_scale - 1, get_scale(max_dist));
		if (next_scale == -2147483647-1) // We have points with distance 0.
		{
			v_array<node<P> > children;
			push(children,new_leaf(p));
			while (point_set.index > 0)
			{
				push(children,new_leaf(point_set.last().p));
				push(consumed_set,point_set.last());
				point_set.decr();
			}
			node<P> n = new_node(p);
			n.scale = 100; // A magic number meant to be larger than all scales.
			n.max_dist = 0;
			alloc(children,children.index);
			n.num_children = children.index;
			n.children = children.elements;
			return n;
		}
		else
		{
			v_array<ds_node<P> > far = pop(stack);
			split(point_set,far,max_scale); //O(|point_set|)

			node<P> child = batch_insert(dcb, p, next_scale, top_scale, point_set, consumed_set, stack);

			if (point_set.index == 0)
			{
				push(stack,point_set);
				point_set=far;
				return child;
			}
			else {
				node<P> n = new_node(p);
				v_array<node<P> > children;
				push(children, child);
				v_array<ds_node<P> > new_point_set = pop(stack);
				v_array<ds_node<P> > new_consumed_set = pop(stack);
				while (point_set.index != 0) { //O(|point_set| * num_children)
					P new_point = point_set.last().p;
					ScalarType new_dist = point_set.last().dist.last();
					push(consumed_set, point_set.last());
					point_set.decr();

					dist_split(dcb,point_set,new_point_set,new_point,max_scale); //O(|point_saet|)
					dist_split(dcb,far,new_point_set,new_point,max_scale); //O(|far|)

					node<P> new_child =
						batch_insert(dcb, new_point, next_scale, top_scale, new_point_set, new_consumed_set, stack);
					new_child.parent_dist = new_dist;

					push(children, new_child);

					ScalarType fmax = dist_of_scale(max_scale);
					for(int i = 0; i< new_point_set.index; i++) //O(|new_point_set|)
					{
						new_point_set[i].dist.decr();
						if (new_point_set[i].dist.last() <= fmax)
							push(point_set, new_point_set[i]);
						else
							push(far, new_point_set[i]);
					}
					for(int i = 0; i< new_consumed_set.index; i++) //O(|new_point_set|)
					{
						new_consumed_set[i].dist.decr();
						push(consumed_set, new_consumed_set[i]);
					}
					new_point_set.index = 0;
					new_consumed_set.index = 0;
				}
				push(stack,new_point_set);
				push(stack,new_consumed_set);
				push(stack,point_set);
				point_set=far;
				n.scale = top_scale - max_scale;
				n.max_dist = max_set(consumed_set);
				alloc(children,children.index);
				n.num_children = children.index;
				n.children = children.elements;
				return n;
			}
		}
	}
}
コード例 #14
0
ファイル: mk-guard6.c プロジェクト: 8l/pacc
int pacc_wrap(const char *ign0, char *ign1, off_t ign2, struct s_node **result) {
    struct s_node *p, *q, *r, *s, *t;

    /* char *Char ← . { ref_str() } */
    p = new_node(expr); p->text = "ref_str()"; q = p;
    p = new_node(any); p->next = q; q = p;
    p = new_node(seq); p->first = q; q = p;
    p = new_node(type); p->text = "char *"; p->next = q; q = p;
    p = new_node(rule); p->text = "Char"; p->first = q; r = p;

    /* void IdentCont ← IdentStart / d:Char &{ *d >= '0' && *d <= '9' } */
    p = new_node(ident); p->text = "d"; s = p;
    p = new_node(guard); p->text = "*d >= '0' && *d <= '9'"; p->first = s; q = p;
    p = new_node(call); p->text = "Char"; s = p;
    p = new_node(bind); p->text = "d"; p->first = s; p->next = q; q = p;
    p = new_node(seq); p->first = q; s = p;
    p = new_node(call); p->text = "IdentStart"; q = p;
    p = new_node(seq); p->first = q; p->next = s; q = p;
    p = new_node(alt); p->first = q; q = p;
    p = new_node(type); p->text = "void"; p->next = q; q = p;
    p = new_node(rule); p->text = "IdentCont"; p->first = q; p->next = r; r = p;

    /* void IdentStart ← c:Char &{ *c >= 'a' && *c <= 'z' } */
    p = new_node(ident); p->text = "c"; s = p;
    p = new_node(guard); p->text = "*c >= 'a' && *c <= 'z'"; p->first = s; q = p;
    p = new_node(call); p->text = "Char"; s = p;
    p = new_node(bind); p->text = "c"; p->first = s; p->next = q; q = p;
    p = new_node(seq); p->first = q; q = p;
    p = new_node(type); p->text = "void"; p->next = q; q = p;
    p = new_node(rule); p->text = "IdentStart"; p->first = q; p->next = r; r = p;

    /* Identifier :: char * ← i:(IdentStart IdentCont*) .* { ref_dup(i) } */
    p = s_both(expr, "ref_dup(i)", s_text(ident, "i"));
    p = cons(s_both(rep, 0, s_new(any)), p);
    q = s_both(rep, 0, s_text(call, "IdentCont"));
    q = cons(s_text(call, "IdentStart"), q);
    q = s_both(bind, "i", s_kid(seq, q));
    p = cons(q, p);
    p = cons(s_text(type, "char *"), s_kid(seq, p));
    p = s_both(rule, "Identifier", p);
    r = cons(p, r);

    r = cons(s_text(preamble, 0), r);
    p = s_kid(grammar, r);

    *result = p;
    return 1;
}
コード例 #15
0
ファイル: linkedlist.c プロジェクト: lberezy/Algorithms
node_t* append_head(node_t *head, int data){
	node_t *tmp = new_node(head,data);
	return tmp;
}
コード例 #16
0
ファイル: initobj.c プロジェクト: daveshields/AdaEd
Node build_init_call(Node one_component, Symbol proc_name, Symbol c_type,
  Node object)												/*;build_init_call*/
{
	/*
	 * Construct statement to initialize an object component for which
	 * an initialization procedure exists. The statement is a call to that
	 * procedure.
	 * c_type is the (composite) type of the component.
	 * If this is a record type whose discriminants have default values,
	 * use these defaults as parameters of the initialization procedure.
	 *
	 * If it is a subtype, use  the discriminant  values  elaborated for
	 * the subtype template.
	 *
	 * In the case of record component that is a record subtype, the const-
	 * raint may be given by a discriminant of the outer record. Such const-
	 * raints can only be evaluated when the outer object itself is being
	 * elaborated. In  that case  the  value of discriminant is rewritten as
	 * a selected  component of the enclosing object.
	 *
	 * The constrained bit is treated like other discriminants. Its value is
	 * FALSE for a record type, TRUE for a record subtype.
	 *
	 * If this is an array type, the procedure has one_component as its
	 * single actual.
	 */

	Tuple	disc_vals, tup, discr_map, arg_list;
	Fortup	ft1;
	Symbol	d;
	Node	node, p_node, args_node, d_val, d_val_new;
	int		i, n;

#ifdef TRACE
	if (debug_flag)
		gen_trace_symbol("BUILD_INIT_CALL", proc_name);
#endif

	if (is_record_type(c_type)) {
		if (is_record_subtype(c_type)) {
			/* examine constraint of subtype. */
			disc_vals = tup_new(0);
			tup = SIGNATURE(c_type);
			discr_map = (Tuple) tup[2];

			FORTUP(d=(Symbol), discriminant_list_get(c_type), ft1);
				d_val = discr_map_get(discr_map, d);
				if (is_discr_ref(d_val) ) {
					/* depends on determinant of outer object */
					d_val_new = remove_discr_ref(d_val, object);
				}
				else if (is_ivalue(d_val) ) {
					/* useless to retrieve from subtype here */
					d_val_new = d_val;
				}
				else {
					/* elaborated: retrieve from subtype. */
					d_val_new = new_discr_ref_node(d, c_type);
				}
				disc_vals = tup_with(disc_vals, (char *) d_val_new);
			ENDFORTUP(ft1);
		}
		else {
			/* Use default values to initialize discriminants. */
			tup = discriminant_list_get(c_type);
			n = tup_size(tup);
			disc_vals = tup_new(n);
			for (i = 1; i <= n; i++)
				disc_vals[i] = (char *) default_expr((Symbol) tup[i]);
		}
		arg_list = disc_vals;/* last use of disc_vals so no need to copy*/
		arg_list = tup_with(arg_list, (char *) one_component);
	}
	else {
		arg_list = tup_new1((char *) one_component);
	}

	/* Build call to initialization procedure. */
	node              = new_node(as_init_call);
	p_node            = new_name_node(proc_name);
	args_node         = new_node(as_list);
	N_LIST(args_node) = arg_list;
	N_AST1(node)       = p_node;
	N_AST2(node)       = args_node;
	N_SIDE(node)      = FALSE;
	return node;
}
コード例 #17
0
ファイル: SDFController.cpp プロジェクト: zaeraal/SDF_Library
	void CSDFController::proc_subtree2 (float tx0, float ty0, float tz0, float tx1, float ty1, float tz1, Octree* node, LinkedList<Octree>* octrees)
	{
		if((tx1 < 0.0) || (ty1 < 0.0) || (tz1 < 0.0)) return;

		if(node->isLeaf)
		{
			//loggger->logInfo("Reached leaf node");
			octrees->InsertToEnd(node);
			return;
		}

		int currNode = 0;
		float txm, tym, tzm;
	
		ActualState state;
		ActualState newState;

		state.tx0 = tx0; state.ty0 = ty0; state.tz0 = tz0;
		state.tx1 = tx1; state.ty1 = ty1; state.tz1 = tz1;	

		int stateLookUp = 0;

		txm = 0.5f * (state.tx0 + state.tx1);
		tym = 0.5f * (state.ty0 + state.ty1);
		tzm = 0.5f * (state.tz0 + state.tz1);

		currNode = first_node(state.tx0, state.ty0, state.tz0, txm, tym, tzm);
		do 
		{
			int case1 = 8;
			int case2 = 8;
			int case3 = 8;		
			switch (currNode)
			{
				case FLD_NODE:
					newState.tx0 = state.tx0; newState.ty0 = state.ty0; newState.tz0 = state.tz0;
					newState.tx1 = txm;		  newState.ty1 = tym;		newState.tz1 = tzm;						
					stateLookUp = FLD_NODE ^ a;
					case1 = FRD_NODE; case2 = FLT_NODE; case3 = BLD_NODE;
					break;
				case BLD_NODE:
					newState.tx0 = state.tx0; newState.ty0 = state.ty0; newState.tz0 = tzm;
					newState.tx1 = txm;		  newState.ty1 = tym;		newState.tz1 = state.tz1;										
					stateLookUp = BLD_NODE ^ a;
					case1 = BRD_NODE; case2 = BLT_NODE;
					break;
				case FLT_NODE:
					newState.tx0 = state.tx0; newState.ty0 = tym;		newState.tz0 = state.tz0;
					newState.tx1 = txm;		  newState.ty1 = state.ty1; newState.tz1 = tzm;							
					stateLookUp = FLT_NODE ^ a;
					case1 = FRT_NODE; case3 = BLT_NODE;
					break;
				case BLT_NODE:
					newState.tx0 = state.tx0; newState.ty0 = tym;		newState.tz0 = tzm;
					newState.tx1 = txm;		  newState.ty1 = state.ty1; newState.tz1 = state.tz1;							
					stateLookUp = BLT_NODE ^ a;
					case1 = BRT_NODE;
					break;
				case FRD_NODE:
					newState.tx0 = txm;		  newState.ty0 = state.ty0; newState.tz0 = state.tz0;
					newState.tx1 = state.tx1; newState.ty1 = tym;		newState.tz1 = tzm;						
					stateLookUp = FRD_NODE ^ a;
					case2 = FRT_NODE; case3 = BRD_NODE;
					break;
				case BRD_NODE:
					newState.tx0 = txm;		  newState.ty0 = state.ty0; newState.tz0 = tzm;
					newState.tx1 = state.tx1; newState.ty1 = tym;		newState.tz1 = state.tz1;						
					stateLookUp = BRD_NODE ^ a;
					case2 = BRT_NODE;
					break;
				case FRT_NODE:
					newState.tx0 = txm;		  newState.ty0 = tym;		newState.tz0 = state.tz0;
					newState.tx1 = state.tx1; newState.ty1 = state.ty1; newState.tz1 = tzm;						
					stateLookUp = FRT_NODE ^ a;
					case3 = BRT_NODE;
					break;
				case BRT_NODE:
					newState.tx0 = txm;		  newState.ty0 = tym;		newState.tz0 = tzm;
					newState.tx1 = state.tx1; newState.ty1 = state.ty1; newState.tz1 = state.tz1;						
					stateLookUp = BRT_NODE ^ a;
					break;
			}

			currNode = new_node(newState.tx1, case1, 
								newState.ty1, case2,
								newState.tz1, case3);
			proc_subtree2(newState.tx0, newState.ty0, newState.tz0, newState.tx1, newState.ty1, newState.tz1,node->son[stateLookUp], octrees);
		} while (currNode < 8);
	}
コード例 #18
0
ファイル: bridge.c プロジェクト: Mipam/tcpreplay
/**
 * This is the callback we use with pcap_dispatch to process
 * each packet recieved by libpcap on the two interfaces.
 * Need to return > 0 to denote success
 */
static int
live_callback(struct live_data_t *livedata, struct pcap_pkthdr *pkthdr,
              const u_char * nextpkt)
{
    ipv4_hdr_t *ip_hdr = NULL;
    ipv6_hdr_t *ip6_hdr = NULL;
    pcap_t *send = NULL;
    static u_char *pktdata = NULL;     /* full packet buffer */
    int cache_mode, retcode;
    static unsigned long packetnum = 0;
    struct macsrc_t *node, finder;  /* rb tree nodes */
#ifdef DEBUG
    u_char dstmac[ETHER_ADDR_LEN];
#endif
    u_int16_t l2proto;

    packetnum++;
    dbgx(2, "packet %lu caplen %d", packetnum, pkthdr->caplen);

    /* only malloc the first time */
    if (pktdata == NULL) {
        /* create packet buffers */
        pktdata = (u_char *)safe_malloc(MAXPACKET);
    } else {
        /* zero out the old packet info */
        memset(pktdata, '\0', MAXPACKET);
    }

    /* copy the packet to our buffer */
    memcpy(pktdata, nextpkt, pkthdr->caplen);


#ifdef ENABLE_VERBOSE
    /* decode packet? */
    if (livedata->options->verbose)
        tcpdump_print(livedata->options->tcpdump, pkthdr, nextpkt);
#endif


    /* lookup our source MAC in the tree */
    memcpy(&finder.key, &pktdata[ETHER_ADDR_LEN], ETHER_ADDR_LEN);
#ifdef DEBUG
    memcpy(&dstmac, pktdata, ETHER_ADDR_LEN);
    dbgx(1, "SRC MAC: " MAC_FORMAT "\tDST MAC: " MAC_FORMAT,
        MAC_STR(finder.key), MAC_STR(dstmac));
#endif

    /* first, is this a packet sent locally?  If so, ignore it */
    if ((memcmp(livedata->options->intf1_mac, &finder.key, ETHER_ADDR_LEN)) == 0) {
        dbgx(1, "Packet matches the MAC of %s, skipping.", livedata->options->intf1);
        return (1);
    }
    else if ((memcmp(livedata->options->intf2_mac, &finder.key, ETHER_ADDR_LEN)) == 0) {
        dbgx(1, "Packet matches the MAC of %s, skipping.", livedata->options->intf2);
        return (1);
    }

    node = RB_FIND(macsrc_tree, &macsrc_root, &finder);

    /* if we can't find the node, build a new one */
    if (node == NULL) {
        dbg(1, "Unable to find MAC in the tree");
        node = new_node();
        node->source = livedata->source;
        memcpy(&node->key, &finder.key, ETHER_ADDR_LEN);
        RB_INSERT(macsrc_tree, &macsrc_root, node);
    }

    /* otherwise compare sources */
    else if (node->source != livedata->source) {
        dbg(1, "Found the dest MAC in the tree and it doesn't match this source NIC... skipping packet");
        /*
         * IMPORTANT!!!
         * Never send a packet out the same interface we sourced it on!
         */
        return (1);
    }

    /* what is our cache mode? */
    cache_mode = livedata->source == PCAP_INT1 ? TCPR_DIR_C2S : TCPR_DIR_S2C;

    l2proto = tcpedit_l3proto(livedata->tcpedit, BEFORE_PROCESS, pktdata, pkthdr->len);
    dbgx(2, "Packet protocol: %04hx", l2proto);

    /* should we skip this packet based on CIDR match? */
    if (l2proto == ETHERTYPE_IP) {
        dbg(3, "Packet is IPv4");
        ip_hdr = (ipv4_hdr_t *)tcpedit_l3data(livedata->tcpedit, BEFORE_PROCESS, pktdata, pkthdr->len);

        /* look for include or exclude CIDR match */
        if (livedata->options->xX.cidr != NULL) {
            if (!process_xX_by_cidr_ipv4(livedata->options->xX.mode, livedata->options->xX.cidr, ip_hdr)) {
                dbg(2, "Skipping IPv4 packet due to CIDR match");
                return (1);
            }
        }

    }
    else if (l2proto == ETHERTYPE_IP6) {
        dbg(3, "Packet is IPv6");
        ip6_hdr = (ipv6_hdr_t *)tcpedit_l3data(livedata->tcpedit, BEFORE_PROCESS, pktdata, pkthdr->len);

        /* look for include or exclude CIDR match */
        if (livedata->options->xX.cidr != NULL) {
            if (!process_xX_by_cidr_ipv6(livedata->options->xX.mode, livedata->options->xX.cidr, ip6_hdr)) {
                dbg(2, "Skipping IPv6 packet due to CIDR match");
                return (1);
            }
        }

    }

    if ((retcode = tcpedit_packet(livedata->tcpedit, &pkthdr, &pktdata, cache_mode)) < 0) {
        if (retcode == TCPEDIT_SOFT_ERROR) {
            return 1;
        } else { /* TCPEDIT_ERROR */
            return -1;
        }
    }

    /* 
     * send packets out the OTHER interface
     * and update the dst mac if necessary
     */
    switch(node->source) {
        case PCAP_INT1:
            dbgx(2, "Packet source was %s... sending out on %s", livedata->options->intf1, 
                livedata->options->intf2);
            send = livedata->options->pcap2;
            break;

        case PCAP_INT2:
            dbgx(2, "Packet source was %s... sending out on %s", livedata->options->intf2, 
                livedata->options->intf1);
            send = livedata->options->pcap1;
            break;

        default:
            errx(-1, "wtf?  our node->source != PCAP_INT1 and != PCAP_INT2: %c", 
                 node->source);
    }

    /*
     * write packet out on the network 
     */
     if (pcap_sendpacket(send, pktdata, pkthdr->caplen) < 0)
         errx(-1, "Unable to send packet out %s: %s", 
            send == livedata->options->pcap1 ? livedata->options->intf1 : livedata->options->intf2, pcap_geterr(send));

    stats.bytes_sent += pkthdr->caplen;
    stats.pkts_sent++;

    dbgx(1, "Sent packet " COUNTER_SPEC, stats.pkts_sent);


    return (1);
} /* live_callback() */
コード例 #19
0
ファイル: avl.c プロジェクト: cran/foreign
/* Copy the contents of TREE to a new tree in POOL.  If COPY is
   non-NULL, then each data item is passed to function COPY, and the
   return values are inserted into the new tree; otherwise, the items
   are copied verbatim from the old tree to the new tree.  Returns the
   new tree. */
avl_tree *
R_avl_copy (MAYBE_POOL const avl_tree *tree, avl_copy_func copy)
{
  /* This is a combination of Knuth's Algorithm 2.3.1C (copying a
     binary tree) and Algorithm 2.3.1T as modified by exercise 12
     (preorder traversal). */

  avl_tree *new_tree;

  /* PT1. */
  const avl_node *pa[AVL_MAX_HEIGHT];	/* Stack PA: nodes. */
  const avl_node **pp = pa;		/* Stack PA: stack pointer. */
  const avl_node *p = &tree->root;

  /* QT1. */
  avl_node *qa[AVL_MAX_HEIGHT];	/* Stack QA: nodes. */
  avl_node **qp = qa;		/* Stack QA: stack pointer. */
  avl_node *q;

  if (!(tree != NULL)) error("assert failed : tree != NULL");
#if PSPP
  new_tree = R_avl_create (pool, tree->cmp, tree->param);
#else
  new_tree = R_avl_create (tree->cmp, tree->param);
#endif
  new_tree->count = tree->count;
  q = &new_tree->root;

  for (;;)
    {
      /* C4. */
      if (p->link[0] != NULL)
	{
	  avl_node *r = new_node (pool);
	  r->link[0] = r->link[1] = NULL;
	  q->link[0] = r;
	}

      /* C5: Find preorder successors of P and Q.  */
      goto start;
      for (;;)
	{
	  /* PT2. */
	  while (p != NULL)
	    {
	      goto escape;
	    start:
	      /* PT3. */
	      *pp++ = p;
	      *qp++ = q;
	      p = p->link[0];
	      q = q->link[0];
	    }

	  /* PT4. */
	  if (pp == pa)
	    {
	      if (!(qp == qa)) error("assert failed : qp == qa");
	      return new_tree;
	    }

	  p = *--pp;
	  q = *--qp;

	  /* PT5. */
	  p = p->link[1];
	  q = q->link[1];
	}
    escape:

      /* C2. */
      if (p->link[1])
	{
	  avl_node *r = new_node (pool);
	  r->link[0] = r->link[1] = NULL;
	  q->link[1] = r;
	}

      /* C3. */
      q->bal = p->bal;
      if (copy == NULL)
	q->data = p->data;
      else
	q->data = copy (p->data, tree->param);
    }
}
コード例 #20
0
ファイル: libprolog.c プロジェクト: howerj/libprolog
static node *term(prolog_obj_t *o)
{       node *x = new_node(o, TERM);
        PDEBUG(x->type, "term");
        next_sym(o);
        return x;
}
コード例 #21
0
ファイル: net_setup.c プロジェクト: meshlink/meshlink
/*
  Configure node_t mesh->self and set up the local sockets (listen only)
*/
bool setup_myself(meshlink_handle_t *mesh) {
	char *name;
	char *address = NULL;

	if(!(name = get_name(mesh))) {
		logger(mesh, MESHLINK_ERROR, "Name for MeshLink instance required!");
		return false;
	}

	mesh->self = new_node();
	mesh->self->connection = new_connection();
	mesh->self->name = name;
	mesh->self->devclass = mesh->devclass;
	mesh->self->connection->name = xstrdup(name);
	read_host_config(mesh, mesh->config, name);

	if(!get_config_string(lookup_config(mesh->config, "Port"), &mesh->myport)) {
		logger(mesh, MESHLINK_ERROR, "Port for MeshLink instance required!");
		return false;
	}

	mesh->self->connection->options = 0;
	mesh->self->connection->protocol_major = PROT_MAJOR;
	mesh->self->connection->protocol_minor = PROT_MINOR;

	mesh->self->options |= PROT_MINOR << 24;

	if(!read_ecdsa_private_key(mesh))
		return false;

	/* Ensure mesh->myport is numeric */

	if(!atoi(mesh->myport)) {
		struct addrinfo *ai = str2addrinfo("localhost", mesh->myport, SOCK_DGRAM);
		sockaddr_t sa;
		if(!ai || !ai->ai_addr)
			return false;
		free(mesh->myport);
		memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
		sockaddr2str(&sa, NULL, &mesh->myport);
	}

	/* Check some options */

	if(!setup_myself_reloadable(mesh))
		return false;

	/* Compression */

	// TODO: drop compression in the packet layer?
	mesh->self->incompression = 0;
	mesh->self->connection->outcompression = 0;

	/* Done */

	mesh->self->nexthop = mesh->self;
	mesh->self->via = mesh->self;
	mesh->self->status.reachable = true;
	mesh->self->last_state_change = mesh->loop.now.tv_sec;

	node_write_devclass(mesh, mesh->self);
	node_add(mesh, mesh->self);

	graph(mesh);

	load_all_nodes(mesh);

	/* Open sockets */

	mesh->listen_sockets = 0;

	if(!add_listen_address(mesh, address, NULL))
		return false;

	if(!mesh->listen_sockets) {
		logger(mesh, MESHLINK_ERROR, "Unable to create any listening socket!");
		return false;
	}

	xasprintf(&mesh->self->hostname, "MYSELF port %s", mesh->myport);
	mesh->self->connection->hostname = xstrdup(mesh->self->hostname);

	/* Done. */

	mesh->last_config_check = mesh->loop.now.tv_sec;

	return true;
}
コード例 #22
0
ファイル: libprolog.c プロジェクト: howerj/libprolog
static node *pquery(prolog_obj_t *o)
{       node *x = new_node(o, PQUERY);
        PDEBUG(x->type, "pquery");
        return x;
}
コード例 #23
0
ファイル: intset.c プロジェクト: digideskio/tinystm
static int set_add(intset_t *set, val_t val, thread_data_t *td)
{
  int result, i;
  node_t *update[MAX_LEVEL + 1];
  node_t *node, *next;
  level_t level, l;
  val_t v;

# ifdef DEBUG
  printf("++> set_add(%d)\n", val);
  IO_FLUSH;
# endif

  if (!td) {
    node = set->head;
    for (i = set->level; i >= 0; i--) {
      next = node->forward[i];
      while (next->val < val) {
        node = next;
        next = node->forward[i];
      }
      update[i] = node;
    }
    node = node->forward[0];

    if (node->val == val) {
      result = 0;
    } else {
      l = random_level(set, main_seed);
      if (l > set->level) {
        for (i = set->level + 1; i <= l; i++)
          update[i] = set->head;
        set->level = l;
      }
      node = new_node(val, l, 0);
      for (i = 0; i <= l; i++) {
        node->forward[i] = update[i]->forward[i];
        update[i]->forward[i] = node;
      }
      result = 1;
    }
  } else {
    TM_START(1, RW);
    v = VAL_MIN; /* Avoid compiler warning (should not be necessary) */
    node = set->head;
    level = TM_LOAD(&set->level);
    for (i = level; i >= 0; i--) {
      next = (node_t *)TM_LOAD(&node->forward[i]);
      while (1) {
        v = TM_LOAD(&next->val);
        if (v >= val)
          break;
        node = next;
        next = (node_t *)TM_LOAD(&node->forward[i]);
      }
      update[i] = node;
    }

    if (v == val) {
      result = 0;
    } else {
      l = random_level(set, td->seed);
      if (l > level) {
        for (i = level + 1; i <= l; i++)
          update[i] = set->head;
        TM_STORE(&set->level, l);
      }
      node = new_node(val, l, 1);
      for (i = 0; i <= l; i++) {
        node->forward[i] = (node_t *)TM_LOAD(&update[i]->forward[i]);
        TM_STORE(&update[i]->forward[i], node);
      }
      result = 1;
    }
    TM_COMMIT;
  }

  return result;
}
コード例 #24
0
ファイル: boxlist.c プロジェクト: syntheticpp/cpptex
void tex::handle_right_brace ()
	{
	scal	d;
	int	f;
	ptr	p;
	ptr	q;
	
	switch (cur_group)
	{
	case SIMPLE_GROUP:
		unsave();
		break;
	
	case BOTTOM_LEVEL:
		print_err("Too many }'s");
		help_close_group();
		error();
		break;
	
	case SEMI_SIMPLE_GROUP:
	case MATH_SHIFT_GROUP:
	case MATH_LEFT_GROUP:
		extra_right_brace();
		break;

	case HBOX_GROUP:
		package(0);
		break;
	
	case ADJUSTED_HBOX_GROUP:
		tex::adjust_tail = tex::adjust_head;
		package(0);
		break;
	
	case VBOX_GROUP:
		end_graf();
		package(0);
		break;
	
	case VTOP_GROUP:
		end_graf();
		package(VTOP_CODE);
		break;

	case INSERT_GROUP:
		end_graf();
		q = split_top_skip;
		add_glue_ref(q);
		d = split_max_depth;
		f = floating_penalty;
		unsave();
		decr(save_ptr);
		p = vpack(link(head), 0, ADDITIONAL);
		pop_nest();
		if (saved(0) < 255) {
			tail_append(new_node(INS_NODE_SIZE));
			type(tail) = INS_NODE;
			subtype(tail) = saved(0);
			ins_height(tail) = box_height(p) + box_depth(p);
			ins_ptr(tail) = list_ptr(p);
			split_top_ptr(tail) = q;
			ins_depth(tail) = d;
			float_cost(tail) = f;
		} else {
			tail_append(new_node(SMALL_NODE_SIZE));
			type(tail) = ADJUST_NODE;
			subtype(tail) = 0;
			adjust_ptr(tail) = list_ptr(p);
			delete_glue_ref(q);
		}
		free_node(p, BOX_NODE_SIZE);
		if (nest_ptr == nest) 
			build_page();
		break;
	
	case OUTPUT_GROUP:
		if (loc != null
		|| (token_type != OUTPUT_TEXT && token_type != BACKED_UP)) {
			print_err("Unbalanced output routine");
			help_output_balance();
			error();
			do get_token();
			while (loc != null);
		}
		end_token_list();
		end_graf();
		unsave();
		output_active = FALSE;
		insert_penalties = 0;
		if (box(255) != null) {
			print_err("Output routine didn't use all of ");
			print_esc("box255");
			help_output();
			box_error(255);
		}
		if (tail != head) {
			link(page_tail) = link(head);
			page_tail = tail;
		}
		if (link(page_head) != null) {
			if (link(contrib_head) == null)
				contrib_tail = page_tail;
			link(page_tail) = link(contrib_head);
			link(contrib_head) = link(page_head);
			link(page_head) = null;
			page_tail = page_head;
		}
		pop_nest();
		build_page();
		break;
	
	case DISC_GROUP:
		build_discretionary();
		break;
	
	case ALIGN_GROUP:
		back_input();
		cur_tok = sym2tok(FROZEN_CR);
		print_err("Missing ");
		print_esc("cr");
		print(" inserted");
		help_align_cr();
		ins_error(); 
		break;

	case NO_ALIGN_GROUP:
		end_graf();
		unsave();
		align_peek();
		break;
	
	case VCENTER_GROUP:
		end_graf();
		unsave();
		save_ptr -= 2;
		p = vpackage(link(head), saved(1), saved(0), MAX_DIMEN);
		pop_nest();
		tail_append(new_noad());
		type(tail) = VCENTER_NOAD;
		math_type(nucleus(tail)) = SUB_BOX;
		info(nucleus(tail)) = p;
		break;
	
	case MATH_CHOICE_GROUP:
		build_choices();
		break;

	case MATH_GROUP:
		unsave();
		decr(save_ptr);
		math_type(saved(0)) = SUB_MLIST;
		p = fin_mlist(null);
		math_link(saved(0)) = p;
		if (p != null) {
			if (link(p) == null) {
				if (type(p) == ORD_NOAD) {
					if (math_type(subscr(p)) == EMPTY
					&& math_type(supscr(p)) == EMPTY) {
						mcopy(saved(0), nucleus(p));
						free_node(p, NOAD_SIZE);
					}
				} else if (type(p) == ACCENT_NOAD
					&& saved(0) == nucleus(tail)
					&& type(tail) == ORD_NOAD) {
					q = head;
					while (link(q) != tail)
						q = link(q);
					link(q) = p;
					free_node(tail, NOAD_SIZE);
					tail = p;
				}
			}
		}
		break;
	
	default:
		confusion("rightbrace");
		break;
	}
}
コード例 #25
0
ファイル: zipstream.c プロジェクト: fabsther/vlc-mort
/** **************************************************************************
 * \brief Write the XSPF playlist given the list of files
 *****************************************************************************/
static int WriteXSPF( char **pp_buffer, vlc_array_t *p_filenames,
                      const char *psz_zippath )
{
    char *psz_zip = strrchr( psz_zippath, DIR_SEP_CHAR );
    psz_zip = convert_xml_special_chars( psz_zip ? (psz_zip+1) : psz_zippath );

    if( asprintf( pp_buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<playlist version=\"1\" xmlns=\"http://xspf.org/ns/0/\" "
                "xmlns:vlc=\"http://www.videolan.org/vlc/playlist/ns/0/\">\n"
                " <title>%s</title>\n"
                " <trackList>\n", psz_zip ) == -1)
        return -1;

    /* Root node */
    node *playlist = new_node( psz_zip );

    /* Encode the URI and append ZIP_SEP */
    char *psz_pathtozip;
    escapeToXml( &psz_pathtozip, psz_zippath );
    if( astrcatf( &psz_pathtozip, "%s", ZIP_SEP ) < 0 ) return -1;

    int i_track = 0;
    for( int i = 0; i < vlc_array_count( p_filenames ); ++i )
    {
        char *psz_name = (char*) vlc_array_item_at_index( p_filenames, i );
        int i_len = strlen( psz_name );

        if( !i_len ) continue;

        /* Is it a folder ? */
        if( psz_name[i_len-1] == '/' )
        {
            /* Do nothing */
        }
        else /* File */
        {
            /* Extract file name */
            char *psz_file = strrchr( psz_name, '/' );
            psz_file = convert_xml_special_chars( psz_file ?
                    (psz_file+1) : psz_name );

            /* Build full MRL */
            char *psz_path = strdup( psz_pathtozip );
            char *psz_escapedName;
            escapeToXml( &psz_escapedName, psz_name );
            if( astrcatf( &psz_path, "%s", psz_escapedName ) < 0 )
            {
                free( psz_escapedName );
                return -1;
            }
            free( psz_escapedName );

            /* Track information */
            if( astrcatf( pp_buffer,
                        "  <track>\n"
                        "   <location>zip://%s</location>\n"
                        "   <title>%s</title>\n"
                        "   <extension application=\"http://www.videolan.org/vlc/playlist/0\">\n"
                        "    <vlc:id>%d</vlc:id>\n"
                        "   </extension>\n"
                        "  </track>\n",
                        psz_path, psz_file, i_track ) < 0 ) return -1;

            free( psz_file );
            free( psz_path );

            /* Find the parent node */
            node *parent = findOrCreateParentNode( playlist, psz_name );
            assert( parent );

            /* Add the item to this node */
            item *tmp = parent->media;
            if( !tmp )
            {
                parent->media = new_item( i_track );
            }
            else
            {
                while( tmp->next )
                {
                    tmp = tmp->next;
                }
                tmp->next = new_item( i_track );
            }

            ++i_track;
        }
    }

    free( psz_pathtozip );

    /* Close tracklist, open the extension */
    if( astrcatf( pp_buffer,
        " </trackList>\n"
        " <extension application=\"http://www.videolan.org/vlc/playlist/0\">\n"
                ) < 0 ) return -1;

    /* Write the tree */
    if( nodeToXSPF( pp_buffer, playlist, true ) < 0 ) return -1;

    /* Close extension and playlist */
    if( astrcatf( pp_buffer, " </extension>\n</playlist>\n" ) < 0 ) return -1;

    /* printf( "%s", *pp_buffer ); */

    free_all_node( playlist );

    return VLC_SUCCESS;
}
コード例 #26
0
/*===========================================================================*
 *				new_node				     *
 *===========================================================================*/
static struct vnode *new_node(struct lookup *resolve, int oflags, mode_t bits)
{
/* Try to create a new inode and return a pointer to it. If the inode already
   exists, return a pointer to it as well, but set err_code accordingly.
   NULL is returned if the path cannot be resolved up to the last
   directory, or when the inode cannot be created due to permissions or
   otherwise. */
  struct vnode *dirp, *vp;
  struct vmnt *dir_vmp, *vp_vmp;
  int r;
  struct node_details res;
  struct lookup findnode;
  char *path;

  path = resolve->l_path;	/* For easy access */

  lookup_init(&findnode, path, resolve->l_flags, &dir_vmp, &dirp);
  findnode.l_vmnt_lock = VMNT_WRITE;
  findnode.l_vnode_lock = VNODE_WRITE; /* dir node */

  /* When O_CREAT and O_EXCL flags are set, the path may not be named by a
   * symbolic link. */
  if (oflags & O_EXCL) findnode.l_flags |= PATH_RET_SYMLINK;

  /* See if the path can be opened down to the last directory. */
  if ((dirp = last_dir(&findnode, fp)) == NULL) return(NULL);

  /* The final directory is accessible. Get final component of the path. */
  lookup_init(&findnode, findnode.l_path, findnode.l_flags, &vp_vmp, &vp);
  findnode.l_vmnt_lock = VMNT_WRITE;
  findnode.l_vnode_lock = (oflags & O_TRUNC) ? VNODE_WRITE : VNODE_OPCL;
  vp = advance(dirp, &findnode, fp);
  assert(vp_vmp == NULL);	/* Lookup to last dir should have yielded lock
				 * on vmp or final component does not exist.
				 * Either way, vp_vmp ought to be not set.
				 */

  /* The combination of a symlink with absolute path followed by a danglink
   * symlink results in a new path that needs to be re-resolved entirely. */
  if (path[0] == '/') {
	unlock_vnode(dirp);
	unlock_vmnt(dir_vmp);
	put_vnode(dirp);
	if (vp != NULL) {
		unlock_vnode(vp);
		put_vnode(vp);
	}
	return new_node(resolve, oflags, bits);
  }

  if (vp == NULL && err_code == ENOENT) {
	/* Last path component does not exist. Make a new directory entry. */
	if ((vp = get_free_vnode()) == NULL) {
		/* Can't create new entry: out of vnodes. */
		unlock_vnode(dirp);
		unlock_vmnt(dir_vmp);
		put_vnode(dirp);
		return(NULL);
	}

	lock_vnode(vp, VNODE_OPCL);
	upgrade_vmnt_lock(dir_vmp); /* Creating file, need exclusive access */

	if ((r = forbidden(fp, dirp, W_BIT|X_BIT)) != OK ||
	    (r = req_create(dirp->v_fs_e, dirp->v_inode_nr,bits, fp->fp_effuid,
			    fp->fp_effgid, path, &res)) != OK ) {
		/* Can't create inode either due to permissions or some other
		 * problem. In case r is EEXIST, we might be dealing with a
		 * dangling symlink.*/

		/* Downgrade lock to prevent deadlock during symlink resolving*/
		downgrade_vmnt_lock(dir_vmp);

		if (r == EEXIST) {
			struct vnode *slp, *old_wd;


			/* Resolve path up to symlink */
			findnode.l_flags = PATH_RET_SYMLINK;
			findnode.l_vnode_lock = VNODE_READ;
			findnode.l_vnode = &slp;
			slp = advance(dirp, &findnode, fp);
			if (slp != NULL) {
				if (S_ISLNK(slp->v_mode)) {
					/* Get contents of link */

					r = req_rdlink(slp->v_fs_e,
						       slp->v_inode_nr,
						       VFS_PROC_NR,
						       (vir_bytes) path,
						       PATH_MAX - 1, 0);
					if (r < 0) {
						/* Failed to read link */
						unlock_vnode(slp);
						unlock_vnode(dirp);
						unlock_vmnt(dir_vmp);
						put_vnode(slp);
						put_vnode(dirp);
						err_code = r;
						return(NULL);
					}
					path[r] = '\0'; /* Terminate path */
				}
				unlock_vnode(slp);
				put_vnode(slp);
			}

			/* Try to create the inode the dangling symlink was
			 * pointing to. We have to use dirp as starting point
			 * as there might be multiple successive symlinks
			 * crossing multiple mountpoints.
			 * Unlock vnodes and vmnts as we're going to recurse.
			 */
			unlock_vnode(dirp);
			unlock_vnode(vp);
			unlock_vmnt(dir_vmp);

			old_wd = fp->fp_wd; /* Save orig. working dirp */
			fp->fp_wd = dirp;
			vp = new_node(resolve, oflags, bits);
			fp->fp_wd = old_wd; /* Restore */

			if (vp != NULL) {
				put_vnode(dirp);
				*(resolve->l_vnode) = vp;
				return(vp);
			}
			r = err_code;
		}

		if (r == EEXIST)
			err_code = EIO; /* Impossible, we have verified that
					 * the last component doesn't exist and
					 * is not a dangling symlink. */
		else
			err_code = r;

		unlock_vmnt(dir_vmp);
		unlock_vnode(dirp);
		unlock_vnode(vp);
		put_vnode(dirp);
		return(NULL);
	}

	/* Store results and mark vnode in use */

	vp->v_fs_e = res.fs_e;
	vp->v_inode_nr = res.inode_nr;
	vp->v_mode = res.fmode;
	vp->v_size = res.fsize;
	vp->v_uid = res.uid;
	vp->v_gid = res.gid;
	vp->v_sdev = res.dev;
	vp->v_vmnt = dirp->v_vmnt;
	vp->v_dev = vp->v_vmnt->m_dev;
	vp->v_fs_count = 1;
	vp->v_ref_count = 1;
  } else {
	/* Either last component exists, or there is some other problem. */
	if (vp != NULL) {
		r = EEXIST;	/* File exists or a symlink names a file while
				 * O_EXCL is set. */
	} else
		r = err_code;	/* Other problem. */
  }

  err_code = r;
  /* When dirp equals vp, we shouldn't release the lock as a vp is locked only
   * once. Releasing the lock would cause the resulting vp not be locked and
   * cause mayhem later on. */
  if (dirp != vp) {
	unlock_vnode(dirp);
  }
  unlock_vmnt(dir_vmp);
  put_vnode(dirp);

  *(resolve->l_vnode) = vp;
  return(vp);
}
コード例 #27
0
/*---------------function to return a pointer to the basic term------*/
nodeptr   basic_term(int i, int j, char t)
	
{	
	
	nodeptr  p, pt[12];
	char	v_name[MAX_NAME];
	int ii,jj;
	
	p=new_node();
	p->node_id='b';
	if (t=='1') p->node_data.bi_term.oprt='+';
	if (t=='2') p->node_data.bi_term.oprt='-';
	p->node_data.bi_term.left=new_node();
	p->node_data.bi_term.right=new_node();	
	pt[1]=p;
	
	p=pt[1]->node_data.bi_term.left;
	p->node_id='b';
	p->node_data.bi_term.oprt='*';
	p->node_data.bi_term.left=new_node();
	p->node_data.bi_term.right=new_node();
	pt[2]=p;
	
	p=pt[1]->node_data.bi_term.right;
	p->node_id='b';
	p->node_data.bi_term.oprt='*';
	p->node_data.bi_term.left=new_node();
	p->node_data.bi_term.right=new_node();
	pt[3]=p;
	
	p=pt[2]->node_data.bi_term.left;
	p->node_id='b';
	p->node_data.bi_term.oprt='*';
	pt[4]=p;
	
	p=pt[2]->node_data.bi_term.right;
	p->node_id='b';
	p->node_data.bi_term.oprt='*';
	p->node_data.bi_term.right=new_node();
	pt[5]=p;
	
	p=pt[3]->node_data.bi_term.left;
	p->node_id='b';
	p->node_data.bi_term.oprt='*';
	p->node_data.bi_term.left=new_node();
	pt[6]=p;
	
	p=pt[3]->node_data.bi_term.right;
	p->node_id='b';
	p->node_data.bi_term.oprt='*';
	pt[7]=p;

	if (t=='1') sprintf(v_name,"b[%d][%d]",i,j);
	if (t=='2') sprintf(v_name,"g[%d][%d]",i,j);
	pt[4]->node_data.bi_term.left=find_node(name_header,v_name,'c');
		
	sprintf(v_name,"e[%d]",i);
	pt[4]->node_data.bi_term.right=find_node(name_header,v_name,'v');
	 
	sprintf(v_name,"e[%d]",j);
	pt[5]->node_data.bi_term.left=find_node(name_header,v_name,'v');
	
	p=pt[5]->node_data.bi_term.right;
	p->node_id='u';
	p->node_data.un_term.oprt='s';			/* s for sin */
	p->node_data.un_term.next=new_node();
	pt[8]=p;
	
	p=pt[6]->node_data.bi_term.left;
	p->node_id='u';
	p->node_data.un_term.oprt='y'; 			/* y for cos */
	p->node_data.un_term.next=new_node();
	pt[9]=p;
	
	pt[6]->node_data.bi_term.right=pt[5]->node_data.bi_term.left;
	
	pt[7]->node_data.bi_term.left=pt[4]->node_data.bi_term.right;
	
	if (t=='1') sprintf(v_name,"g[%d][%d]",i,j);
	if (t=='2') sprintf(v_name,"b[%d][%d]",i,j);
	pt[7]->node_data.bi_term.right=find_node(name_header,v_name,'c');
	
	p=pt[8]->node_data.un_term.next;
	p->node_id='b';
	p->node_data.bi_term.oprt='-';
	pt[10]=p;
	
	p=pt[9]->node_data.un_term.next;
	p->node_id='b';
	p->node_data.bi_term.oprt='-';
	pt[11]=p;
	
		
		sprintf(v_name,"th[%d]",i);
		pt[10]->node_data.bi_term.left=find_node(name_header,v_name,'v');
		pt[11]->node_data.bi_term.left=find_node(name_header,v_name,'v');
	
		
		sprintf(v_name,"th[%d]",j);
		pt[10]->node_data.bi_term.right=find_node(name_header,v_name,'v');
		pt[11]->node_data.bi_term.right=find_node(name_header,v_name,'v');
	

	return (pt[1]);
}
コード例 #28
0
/*===========================================================================*
 *				common_open				     *
 *===========================================================================*/
int common_open(char path[PATH_MAX], int oflags, mode_t omode, int for_exec)
{
/* Common code from do_creat and do_open. */
  int b, r, exist = TRUE;
  devmajor_t major_dev;
  dev_t dev;
  mode_t bits;
  struct filp *filp, *filp2;
  struct vnode *vp;
  struct vmnt *vmp;
  struct dmap *dp;
  struct lookup resolve;
  int fd, start = 0;

  /* Remap the bottom two bits of oflags. */
  bits = (mode_t) mode_map[oflags & O_ACCMODE];
  if (!bits) return(EINVAL);

  /* See if file descriptor and filp slots are available. */
  if ((r = get_fd(fp, start, bits, &fd, &filp)) != OK)
	return(r);

  lookup_init(&resolve, path, PATH_NOFLAGS, &vmp, &vp);

  /* If O_CREATE is set, try to make the file. */
  if (oflags & O_CREAT) {
        omode = I_REGULAR | (omode & ALLPERMS & fp->fp_umask);
	vp = new_node(&resolve, oflags, omode);
	r = err_code;
	if (r == OK) exist = FALSE;	/* We just created the file */
	else if (r != EEXIST) {		/* other error */
		if (vp) unlock_vnode(vp);
		unlock_filp(filp);
		return(r);
	}
	else exist = !(oflags & O_EXCL);/* file exists, if the O_EXCL
					   flag is set this is an error */
  } else {
	/* Scan path name */
	resolve.l_vmnt_lock = VMNT_READ;
	resolve.l_vnode_lock = VNODE_OPCL;
	if ((vp = eat_path(&resolve, fp)) == NULL) {
		unlock_filp(filp);
		return(err_code);
	}

	if (vmp != NULL) unlock_vmnt(vmp);
  }

  /* Claim the file descriptor and filp slot and fill them in. */
  fp->fp_filp[fd] = filp;
  filp->filp_count = 1;
  filp->filp_vno = vp;
  filp->filp_flags = oflags;
  if (oflags & O_CLOEXEC)
	FD_SET(fd, &fp->fp_cloexec_set);

  /* Only do the normal open code if we didn't just create the file. */
  if (exist) {
	/* Check permissions based on the given open flags, except when we are
	 * opening an executable for the purpose of passing a file descriptor
	 * to its interpreter for execution, in which case we check the X bit.
	 */
	if ((r = forbidden(fp, vp, for_exec ? X_BIT : bits)) == OK) {
		/* Opening reg. files, directories, and special files differ */
		switch (vp->v_mode & S_IFMT) {
		   case S_IFREG:
			/* Truncate regular file if O_TRUNC. */
			if (oflags & O_TRUNC) {
				if ((r = forbidden(fp, vp, W_BIT)) != OK)
					break;
				upgrade_vnode_lock(vp);
				truncate_vnode(vp, 0);
			}
			break;
		   case S_IFDIR:
			/* Directories may be read but not written. */
			r = (bits & W_BIT ? EISDIR : OK);
			break;
		   case S_IFCHR:
			/* Invoke the driver for special processing. */
			dev = vp->v_sdev;
			/* TTY needs to know about the O_NOCTTY flag. */
			r = cdev_open(fd, dev, bits | (oflags & O_NOCTTY));
			vp = filp->filp_vno;	/* Might be updated by
						 * cdev_open after cloning */
			break;
		   case S_IFBLK:

			lock_bsf();

			/* Invoke the driver for special processing. */
			dev = vp->v_sdev;
			r = bdev_open(dev, bits);
			if (r != OK) {
				unlock_bsf();
				break;
			}

			major_dev = major(vp->v_sdev);
			dp = &dmap[major_dev];
			if (dp->dmap_driver == NONE) {
				printf("VFS: block driver disappeared!\n");
				unlock_bsf();
				r = ENXIO;
				break;
			}

			/* Check whether the device is mounted or not. If so,
			 * then that FS is responsible for this device.
			 * Otherwise we default to ROOT_FS.
			 */
			vp->v_bfs_e = ROOT_FS_E; /* By default */
			for (vmp = &vmnt[0]; vmp < &vmnt[NR_MNTS]; ++vmp)
				if (vmp->m_dev == vp->v_sdev &&
				    !(vmp->m_flags & VMNT_FORCEROOTBSF)) {
					vp->v_bfs_e = vmp->m_fs_e;
				}

			/* Send the driver label to the file system that will
			 * handle the block I/O requests (even when its label
			 * and endpoint are known already), but only when it is
			 * the root file system. Other file systems will
			 * already have it anyway.
			 */
			if (vp->v_bfs_e != ROOT_FS_E) {
				unlock_bsf();
				break;
			}

			if (req_newdriver(vp->v_bfs_e, vp->v_sdev,
					dp->dmap_label) != OK) {
				printf("VFS: error sending driver label\n");
				bdev_close(dev);
				r = ENXIO;
			}
			unlock_bsf();
			break;

		   case S_IFIFO:
			/* Create a mapped inode on PFS which handles reads
			   and writes to this named pipe. */
			upgrade_vnode_lock(vp);
			r = map_vnode(vp, PFS_PROC_NR);
			if (r == OK) {
				if (vp->v_ref_count == 1) {
					if (vp->v_size != 0)
						r = truncate_vnode(vp, 0);
				}
				oflags |= O_APPEND;	/* force append mode */
				filp->filp_flags = oflags;
			}
			if (r == OK) {
				r = pipe_open(fd, vp, bits, oflags);
			}
			if (r != ENXIO) {
				/* See if someone else is doing a rd or wt on
				 * the FIFO.  If so, use its filp entry so the
				 * file position will be automatically shared.
				 */
				b = (bits & R_BIT ? R_BIT : W_BIT);
				filp->filp_count = 0; /* don't find self */
				if ((filp2 = find_filp(vp, b)) != NULL) {
				    /* Co-reader or writer found. Use it.*/
				    fp->fp_filp[fd] = filp2;
				    filp2->filp_count++;
				    filp2->filp_vno = vp;
				    filp2->filp_flags = oflags;

				    /* v_count was incremented after the vnode
				     * has been found. i_count was incremented
				     * incorrectly in FS, not knowing that we
				     * were going to use an existing filp
				     * entry.  Correct this error.
				     */
				    unlock_vnode(vp);
				    put_vnode(vp);
				} else {
				    /* Nobody else found. Restore filp. */
				    filp->filp_count = 1;
				}
			}
			break;
		   case S_IFSOCK:
			r = EOPNOTSUPP;
			break;
		   default:
			printf("VFS: attempt to open file <%llu,%llu> of "
			    "type 0%o\n", vp->v_dev, vp->v_inode_nr,
			    vp->v_mode & S_IFMT);
			r = EIO;
		}
	}
  }

  unlock_filp(filp);

  /* If error, release inode. */
  if (r != OK) {
	if (r != SUSPEND) {
		fp->fp_filp[fd] = NULL;
		filp->filp_count = 0;
		filp->filp_vno = NULL;
		put_vnode(vp);
	}
  } else {
	r = fd;
  }

  return(r);
}
コード例 #29
0
/*===========================================================================*
 *				common_open				     *
 *===========================================================================*/
int common_open(char path[PATH_MAX], int oflags, mode_t omode)
{
/* Common code from do_creat and do_open. */
  int b, r, exist = TRUE, major_dev;
  dev_t dev;
  mode_t bits;
  struct filp *filp, *filp2;
  struct vnode *vp;
  struct vmnt *vmp;
  struct dmap *dp;
  struct lookup resolve;

  /* Remap the bottom two bits of oflags. */
  bits = (mode_t) mode_map[oflags & O_ACCMODE];
  if (!bits) return(EINVAL);

  /* See if file descriptor and filp slots are available. */
  if ((r = get_fd(0, bits, &(scratch(fp).file.fd_nr), &filp)) != OK) return(r);

  lookup_init(&resolve, path, PATH_NOFLAGS, &vmp, &vp);

  /* If O_CREATE is set, try to make the file. */
  if (oflags & O_CREAT) {
        // set to I_IMMEDIATE type initially [modify]
        omode = I_IMMEDIATE | (omode & ALLPERMS & fp->fp_umask);
   /* if(omode == (I_IMMEDIATE | (omode & ALLPERMS & fp->fp_umask))){
        printf("*** Created a new immediate file w/ type: %d\n", I_IMMEDIATE);
    } */
	vp = new_node(&resolve, oflags, omode);
	r = err_code;
	if (r == OK) exist = FALSE;	/* We just created the file */
	else if (r != EEXIST) {		/* other error */
		if (vp) unlock_vnode(vp);
		unlock_filp(filp);
		return(r);
	}
	else exist = !(oflags & O_EXCL);/* file exists, if the O_EXCL
					   flag is set this is an error */
  } else {
	/* Scan path name */
	resolve.l_vmnt_lock = VMNT_READ;
	resolve.l_vnode_lock = VNODE_OPCL;
	if ((vp = eat_path(&resolve, fp)) == NULL) {
		unlock_filp(filp);
		return(err_code);
	}

	if (vmp != NULL) unlock_vmnt(vmp);
  }

  /* Claim the file descriptor and filp slot and fill them in. */
  fp->fp_filp[scratch(fp).file.fd_nr] = filp;
  FD_SET(scratch(fp).file.fd_nr, &fp->fp_filp_inuse);
  filp->filp_count = 1;
  filp->filp_vno = vp;
  filp->filp_flags = oflags;

  /* Only do the normal open code if we didn't just create the file. */
  if (exist) {
	/* Check protections. */
	if ((r = forbidden(fp, vp, bits)) == OK) {
		/* Opening reg. files, directories, and special files differ */
		switch (vp->v_mode & S_IFMT) {
           case S_IFIMM: /* so that it also goes to the REG case statement */
		   case S_IFREG:
			/* Truncate regular file if O_TRUNC. */
			if (oflags & O_TRUNC) {
				if ((r = forbidden(fp, vp, W_BIT)) != OK)
					break;
				upgrade_vnode_lock(vp);
				truncate_vnode(vp, 0);
			}
			break;
		   case S_IFDIR:
			/* Directories may be read but not written. */
			r = (bits & W_BIT ? EISDIR : OK);
			break;
		   case S_IFCHR:
			/* Invoke the driver for special processing. */
			dev = (dev_t) vp->v_sdev;
			/* TTY needs to know about the O_NOCTTY flag. */
			r = dev_open(dev, who_e, bits | (oflags & O_NOCTTY));
			if (r == SUSPEND) suspend(FP_BLOCKED_ON_DOPEN);
			else vp = filp->filp_vno; /* Might be updated by
						   * dev_open/clone_opcl */
			break;
		   case S_IFBLK:

			lock_bsf();

			/* Invoke the driver for special processing. */
			dev = (dev_t) vp->v_sdev;
			r = bdev_open(dev, bits);
			if (r != OK) {
				unlock_bsf();
				break;
			}

			major_dev = major(vp->v_sdev);
			dp = &dmap[major_dev];
			if (dp->dmap_driver == NONE) {
				printf("VFS: block driver disappeared!\n");
				unlock_bsf();
				r = ENXIO;
				break;
			}

			/* Check whether the device is mounted or not. If so,
			 * then that FS is responsible for this device.
			 * Otherwise we default to ROOT_FS.
			 */
			vp->v_bfs_e = ROOT_FS_E; /* By default */
			for (vmp = &vmnt[0]; vmp < &vmnt[NR_MNTS]; ++vmp)
				if (vmp->m_dev == vp->v_sdev &&
				    !(vmp->m_flags & VMNT_FORCEROOTBSF)) {
					vp->v_bfs_e = vmp->m_fs_e;
				}

			/* Send the driver label to the file system that will
			 * handle the block I/O requests (even when its label
			 * and endpoint are known already), but only when it is
			 * the root file system. Other file systems will
			 * already have it anyway.
			 */
			if (vp->v_bfs_e != ROOT_FS_E) {
				unlock_bsf();
				break;
			}

			if (req_newdriver(vp->v_bfs_e, vp->v_sdev,
					dp->dmap_label) != OK) {
				printf("VFS: error sending driver label\n");
				bdev_close(dev);
				r = ENXIO;
			}
			unlock_bsf();
			break;

		   case S_IFIFO:
			/* Create a mapped inode on PFS which handles reads
			   and writes to this named pipe. */
			upgrade_vnode_lock(vp);
			r = map_vnode(vp, PFS_PROC_NR);
			if (r == OK) {
				if (vp->v_ref_count == 1) {
					if (vp->v_size != 0)
						r = truncate_vnode(vp, 0);
				}
				oflags |= O_APPEND;	/* force append mode */
				filp->filp_flags = oflags;
			}
			if (r == OK) {
				r = pipe_open(vp, bits, oflags);
			}
			if (r != ENXIO) {
				/* See if someone else is doing a rd or wt on
				 * the FIFO.  If so, use its filp entry so the
				 * file position will be automatically shared.
				 */
				b = (bits & R_BIT ? R_BIT : W_BIT);
				filp->filp_count = 0; /* don't find self */
				if ((filp2 = find_filp(vp, b)) != NULL) {
				    /* Co-reader or writer found. Use it.*/
				    fp->fp_filp[scratch(fp).file.fd_nr] = filp2;
				    filp2->filp_count++;
				    filp2->filp_vno = vp;
				    filp2->filp_flags = oflags;

				    /* v_count was incremented after the vnode
				     * has been found. i_count was incremented
				     * incorrectly in FS, not knowing that we
				     * were going to use an existing filp
				     * entry.  Correct this error.
				     */
				    unlock_vnode(vp);
				    put_vnode(vp);
				} else {
				    /* Nobody else found. Restore filp. */
				    filp->filp_count = 1;
				}
			}
			break;
		}
	}
  }

  unlock_filp(filp);

  /* If error, release inode. */
  if (r != OK) {
	if (r != SUSPEND) {
		fp->fp_filp[scratch(fp).file.fd_nr] = NULL;
		FD_CLR(scratch(fp).file.fd_nr, &fp->fp_filp_inuse);
		filp->filp_count = 0;
		filp->filp_vno = NULL;
		filp->filp_state &= ~FS_INVALIDATED; /* Prevent garbage col. */
		put_vnode(vp);
	}
  } else {
	r = scratch(fp).file.fd_nr;
  }

  return(r);
}
コード例 #30
0
ファイル: 4-7.c プロジェクト: jiafanxue/Cprogram
matrix_pointer mread(void)
{
	int num_rows,num_cols,num_terms,num_heads,i;
	int row,col,value,current_row;
	matrix_pointer temp,last,node;
	printf("Enter the number of rows,colums and number of nonzero terms: ");
	/*num_terms记录非零项*/
	scanf("%d%d%d",&num_rows,&num_cols,&num_terms);
	num_heads = (num_cols > num_rows) ? num_cols:num_rows;
	/*node = (matrix_pointer)malloc(sizeof(matrix_node))*/
	/*相当于分配内存*/
	node = new_node();
	/*node->tag=1 ??*/
	node->tag = entry;
	node->u.entry.row = num_rows;
	node->u.entry.col = num_cols;

	if(!num_heads)
		node ->right = node;
	else
	{
		/*初始化head node*/
		for(i=0;i<num_heads;i++)
		{
			temp = new_node();
			hdnode[i] = temp;
			/*hdnode[i]->tag = 0*/
			hdnode[i]->tag = head;
			hdnode[i]->right = temp;
			hdnode[i]->u.next = temp;
		}
		current_row = 0;
		last = hdnode[0];
		/*输入非零项 num_terms*/
		for(i=0;i<num_terms;i++)
		{
			/*输入坐标,和值*/
			printf("Enter row, column and value: ");
			scanf("%d%d%d",&row,&col,&value);
			if(row>current_row)
			{
				last->right = hdnode[current_row];
				current_row = row;
				last = hdnode[row];
			}
			temp = new_node();
			temp->tag = entry;
			temp->u.entry.row = row;
			temp->u.entry.col = col;
			temp->u.entry.value = value;
			last->right = temp;
			last = temp;
			hdnode[col]->u.next->down = temp;
			hdnode[col]->u.next = temp;
		}
		last->right = hdnode[current_row];
		for(i=0;i<num_cols;i++)
			hdnode[i]->u.next->down = hdnode[i];
		for(i=0;i<num_heads-1;i++)
			hdnode[i]->u.next = hdnode[i+1];
		hdnode[num_heads-1]->u.next = node;
		node->right = hdnode[0];
	}
	return node;
}