Exemplo n.º 1
0
static int juti_getgrouplist(const char *uname, gid_t agroup, gid_t **groups_res, char*** group_names_res, int *grpcnt)
{
	struct group *grp;
	int bail;
   int ret = 0;
   int maxgroups = 0;
   gid_t *groups = NULL;
   char  **group_names = NULL;
   int ngroups = 0;
   int i = 0;
   
	setgrent();
	while ((grp = getgrent())) {
      for (bail = 0, i = 0; bail == 0 && i < ngroups; i++) {
			if (groups[i] == grp->gr_gid) {
				bail = 1;
         }
      }
		if (bail) {
			continue;
      }
		if (grp->gr_gid == agroup) {
         if(add_group(grp, &groups, &group_names, &ngroups, &maxgroups) != 0) {
            ret = -1;
            goto error;
         }
         continue;
      }
		for (i = 0; grp->gr_mem[i]; i++) {
			if (strcmp(grp->gr_mem[i], uname) == 0) {
            if(add_group(grp, &groups, &group_names, &ngroups, &maxgroups) != 0) {
               ret = -1;
               goto error;
            }
			}
		}
	}

	endgrent();
   
error:

   if (ret != 0) {
      if (groups != NULL) {
         free(groups);
      }
      for (i=0; i < ngroups; i++) {
         free(group_names[i]);
      }
      if (group_names != NULL) {
         free(group_names);
      }
   } else {
      *groups_res = groups;   
      *group_names_res = group_names;
      *grpcnt = ngroups;
   }
   
	return ret;
}
Exemplo n.º 2
0
player_ai::player_ai() {
	mov_down = 0;
	mov_up = 0;
	mov_left = 0;
	mov_right = 0;
	jump_ok = false;
	jump_delay = 0;
	iterator = 0;
	time_passed = 0;
	current_anim = "idle";
	rotating = false;
	selected_sprite = NULL;
	add_group("mousectrl");
	add_group("kctrl");
	add_group("tctrl");
	inventory_active = false;
	a_down = 0;
	d_down = 0;
	left_down = 0;
	right_down = 0;
	up_down = 0;
	down_down = 0;
	inited = false;

}
Exemplo n.º 3
0
//---------------------------------------------------------------------------------------
void ToolPageSymbols::create_tool_groups()
{
    wxBoxSizer *pMainSizer = GetMainSizer();

    add_group( LENMUS_NEW GrpHarmony(this, pMainSizer, k_mouse_mode_data_entry) );
    add_group( LENMUS_NEW GrpSymbols(this, pMainSizer, k_mouse_mode_data_entry) );

	create_layout();
    select_group(k_grp_Harmony);
}
Exemplo n.º 4
0
BOOL near Calendar::build_calendar_groups(GroupObjectPtr *skeleton_group,
								GroupObjectPtr *date_group,
								GroupObjectPtr *graphic_group,
								GroupObjectPtr *text_group)
{
	return	   (*date_group = add_group(DATE_PANEL, 0)) != NULL
				&& (*text_group = add_group(TEXT_PANEL, OBJECT_FLAG_locked)) != NULL
				&& (*graphic_group = add_group(GRAPHIC_PANEL, OBJECT_FLAG_locked)) != NULL
				&& (*skeleton_group = add_group(SKELETON_PANEL, 0)) != NULL;
}
//---------------------------------------------------------------------------------------
void ToolPageRhythmicDictation::create_tool_groups()
{
    wxBoxSizer *pMainSizer = GetMainSizer();

    add_group( LENMUS_NEW GrpNoteDuration(this, pMainSizer) );
    add_group( LENMUS_NEW GrpNoteDots(this, pMainSizer) );
    add_group( LENMUS_NEW GrpBarlines2(this, pMainSizer) );


	create_layout();
	select_group(k_grp_NoteDuration);
}
Exemplo n.º 6
0
static int
display_entry(int offset)
{
    lseek(dbase_fd, offset + HDRSIZE, L_SET);
    if (read(dbase_fd, &pre, sizeof(struct prentry)) < 0) {
	fprintf(stderr, "pt_util: error reading entry %d: %s\n",
		offset, strerror(errno));
	exit(1);
    }

    fix_pre(&pre);

    if ((pre.flags & PRFREE) == 0) {
	if (pre.flags & PRGRP) {
	    if (flags & DO_GRP)
		add_group(pre.id);
	} else {
	    if (print_id(pre.id) && (flags & DO_USR))
		fprintf(dfp, FMT_BASE, pre.name, pre.flags, pre.ngroups,
			pre.id, pre.owner, pre.creator);
	    checkin(&pre);
	}
    }
    return (nflag ? pre.nextName : pre.nextID);
}
Exemplo n.º 7
0
static void
add_groups(iks *tag, int class_no, int level, struct acl_class *ac)
{
    iks *x;
    // global permissions
    for (x = iks_find(tag, "group"); x; x = iks_next_tag(x)) {
        if (iks_strcmp(iks_name(x), "group") == 0)
            add_group(x, level, ac);
    }
    // class permissions
    x = iks_find_with_attrib(tag, "class", "name", model_get_path(class_no));
    for (x = iks_find(x, "group"); x; x = iks_next_tag(x)) {
        if (iks_strcmp(iks_name(x), "group") == 0)
            add_group(x, level, ac);
    }
}
Exemplo n.º 8
0
config_context_t::group& config_context_t::get_group(const std::string& name)
{
	if (!m_groups[name])
		add_group(name);

	return *m_groups[name];
}
Exemplo n.º 9
0
static xmlNodePtr
add_lesson (GPInstructLesson *lesson,
            xmlNodePtr parent_node)
{
	GPInstructLessonElement *curr_lesson_element;

	GList *lesson_elements;
	GList *curr_lesson_elements;

	xmlNodePtr current_node = xmlNewTextChild (parent_node, NULL,
	                                           BAD_CAST "lesson", NULL);
	xmlSetProp (current_node, BAD_CAST "title",
	            BAD_CAST gpinstruct_lesson_get_title (lesson));
	xmlSetProp (current_node, BAD_CAST "single-score",
	            gpinstruct_lesson_get_single_score (lesson)?BAD_CAST "true":BAD_CAST "false");

	lesson_elements = gpinstruct_lesson_get_lesson_elements (lesson);
	curr_lesson_elements = lesson_elements;

	while (curr_lesson_elements)
	{
		curr_lesson_element = GPINSTRUCT_LESSON_ELEMENT (curr_lesson_elements->data);

		if (GPINSTRUCT_IS_LESSON_DISCUSSION (curr_lesson_element))
			add_discussion (GPINSTRUCT_LESSON_DISCUSSION (curr_lesson_element),
			                current_node);
		else if (GPINSTRUCT_IS_LESSON_READING (curr_lesson_element))
			add_reading (GPINSTRUCT_LESSON_READING (curr_lesson_element),
			             current_node);
		else if (GPINSTRUCT_IS_LESSON_TEST_MULTI_CHOICE (curr_lesson_element))
			add_multi_choice_test (GPINSTRUCT_LESSON_TEST_MULTI_CHOICE (curr_lesson_element),
			                       current_node);
		else if (GPINSTRUCT_IS_LESSON_TEST_WORD_POOL (curr_lesson_element))
			add_word_pool_test (GPINSTRUCT_LESSON_TEST_WORD_POOL (curr_lesson_element),
			                    current_node);
		else if (GPINSTRUCT_IS_LESSON_TEST_ORDER (curr_lesson_element))
			add_order_test (GPINSTRUCT_LESSON_TEST_ORDER (curr_lesson_element),
			                current_node);
		else if (GPINSTRUCT_IS_LESSON_TEST_TEXT (curr_lesson_element))
			add_text_test (GPINSTRUCT_LESSON_TEST_TEXT (curr_lesson_element),
			               current_node);
		else if (GPINSTRUCT_IS_LESSON_TEST_SCRAMBLED (curr_lesson_element))
			add_scrambled_test (GPINSTRUCT_LESSON_TEST_SCRAMBLED (curr_lesson_element),
			                    current_node);
		else if (GPINSTRUCT_IS_LESSON_ELEMENT_GROUP (curr_lesson_element))
			add_group (GPINSTRUCT_LESSON_ELEMENT_GROUP (curr_lesson_element),
			           current_node);

		curr_lesson_elements = curr_lesson_elements->next;
	}

	g_list_free (lesson_elements);

	return current_node;
}
Exemplo n.º 10
0
/*
 * Read all of the groups statistics information.
 *
 * IN:
 * @groups:                The lists of groups.
 * @device_name:           The given device name.
 */
int read_all_groups(cg_group_lists* groups, const char* device_name) {

	int ret = 0, level;
	void *handle;
	struct cgroup_file_info info;
	cg_group* group = NULL;
	if (!groups || !device_name) {
		fprintf(stderr, "rd_stats: the input parameters is invalid.\n");
		return -1;
	}
	/** Clear the history information.*/
	clear_group(groups);
	/** Start the traversing of the directory. */
	ret = cgroup_walk_tree_begin(device_name, BASE_DIR, DEPTH, &handle, &info,
			&level);
	if (ret)
		goto err;
	/** Walk to the next. */
	while (!(ret = cgroup_walk_tree_next(0, &handle, &info, level))) {
		if (info.type == CGROUP_FILE_TYPE_DIR) {
			/** Initialized the group but the cpuset statistics information and the io
			 *  statistics information is NULL.*/
			if ((ret = init_group(&group, info.path, info.full_path))) {
#ifdef DEBUG
				fprintf(stderr,
						"rd_stats: initialize the group failed, group name: %s, path: %s.\n",
						info.path, info.full_path);
#endif
				goto err;
			}
			/** Add the group into the lists.*/
			if (group && add_group(groups, group)) {
#ifdef DEBUG
				fprintf(stderr,
						"rd_stats: add the group into lists failed, group name: %s, path: %s.\n",
						info.path, info.full_path);
#endif
				goto err;
			}
			group = NULL;
		}
	}
	/** End the traversing.*/
	cgroup_walk_tree_end(&handle);
	return 0;

	err: if (group)
		uninit_group(group);
	group = NULL;
	clear_group(groups);
	cgroup_walk_tree_end(&handle);
	return ret;
}
Exemplo n.º 11
0
bool mesos_state_t::parse_groups(const std::string& json)
{
	Json::Value root;
	Json::Reader reader;
	if(reader.parse(json, root, false))
	{
		return handle_groups(root, add_group(root, 0));
	}
	else
	{
		throw sinsp_exception("Invalid JSON (Marathon groups parsing failed).");
	}
}
Exemplo n.º 12
0
static void ok_callback(grouplist *current_group)
{
	if (group_name == NULL
		|| gtk_entry_get_text(GTK_ENTRY(group_name)) == NULL
		|| strlen(gtk_entry_get_text(GTK_ENTRY(group_name))) == 0)
		return;

	if (current_group)
		rename_group(current_group,
			gtk_entry_get_text(GTK_ENTRY(group_name)));
	else
		add_group(gtk_entry_get_text(GTK_ENTRY(group_name)));
}
Exemplo n.º 13
0
bool mesos_state_t::handle_groups(const Json::Value& root, marathon_group::ptr_t to_group, const std::string& framework_id)
{
	Json::Value groups = root["groups"];
	if(!groups.isNull() && groups.isArray())
	{
		for(const auto& group : groups)
		{
			add_group(group, to_group, framework_id);
		}
	}
	else
	{
		g_logger.log("No groups found.", sinsp_logger::SEV_WARNING);
		return false;
	}
	return true;
}
Exemplo n.º 14
0
bool mesos_state_t::parse_groups(Json::Value&& root, const std::string& framework_id)
{
	add_group(root, 0, framework_id);
#ifdef HAS_CAPTURE
	if(m_is_captured)
	{
		Json::Value capt;
		capture_groups(root, framework_id, capt, true);
		enqueue_capture_event(capture::MARATHON_GROUPS, Json::FastWriter().write(capt));
	}
#endif // HAS_CAPTURE
	if(m_verbose)
	{
		std::cout << Json::FastWriter().write(root) << std::endl;
	}
	return true;
}
Exemplo n.º 15
0
/* This function checks, if the user is a member of this group and if
   yes, add the group id to the list.  Return nonzero is we couldn't
   handle the group because the user is not in the member list.  */
static int
check_and_add_group (const char *user, gid_t group, long int *start,
		     long int *size, gid_t **groupsp, long int limit,
		     struct group *grp)
{
  char **member;

  /* Don't add main group to list of groups.  */
  if (grp->gr_gid == group)
    return 0;

  for (member = grp->gr_mem; *member != NULL; ++member)
    if (strcmp (*member, user) == 0)
      {
	add_group (start, size, groupsp, limit, grp->gr_gid);
	return 0;
      }

  return 1;
}
Exemplo n.º 16
0
static int
display_entry(int offset)
{
    lseek(dbase_fd, offset + HDRSIZE, L_SET);
    read(dbase_fd, &pre, sizeof(struct prentry));

    fix_pre(&pre);

    if ((pre.flags & PRFREE) == 0) {
	if (pre.flags & PRGRP) {
	    if (flags & DO_GRP)
		add_group(pre.id);
	} else {
	    if (print_id(pre.id) && (flags & DO_USR))
		fprintf(dfp, FMT_BASE, pre.name, pre.flags, pre.ngroups,
			pre.id, pre.owner, pre.creator);
	    checkin(&pre);
	}
    }
    return (nflag ? pre.nextName : pre.nextID);
}
Exemplo n.º 17
0
void evented::add_groups(std::list<std::string> groups) {
	for (std::list<std::string>::iterator it = groups.begin(); it
			!= groups.end(); ++it) {
		add_group(*it);
	}
}
Exemplo n.º 18
0
  /* This function does bulk of the forward phase heavylifting */
  void operator()() {
    /* Some variables that determine when to stop */
    const double SENTINEL = std::numeric_limits<double>::min();
    double best_gain  = SENTINEL;
    double prev_cost  = SENTINEL;
    double best_confidence = SENTINEL;

    /** 
     * Add each of the forced candidates to the list of selected candidates 
     * and compute an initial model so that we can compute residual later 
     */
    if (0<forced.size()) {
      typename SetContainer::iterator first = forced.begin();
      while (first != forced.end()) {
        add_group (*first);
        selected.push_back (*first);
        ++first;
      }
      Solver::solve (test_A, x, y, lambda, M, (N*selected.size())); 
      best_gain = prev_cost = 
         CostFunctor::cost (test_A, y, x, lambda, M, (N*selected.size())); 
      best_confidence = ConfidenceFunctor::confidence 
                           (test_A, y, y_inv, x, M, N*(1+selected.size())); 
    }

    /**
     * each iteration corresponds to picking one group. we need to only 
     * pick the remaining groups --- we have already included all forced ones.
     */
    const int num_iters = MAX_ITERS-selected.size();
    for (int iter = 0; iter<num_iters; ++iter) {
#if USE_PFUNC
      task root_task;
      attribute root_attribute (false /*nested*/, false /*grouped*/);
#endif

      double iter_time = micro_time();

      /* Compute the residual for this iteration */
      CostFunctor::residual (test_A, x, y, r, M, (selected.size()*N));

      /* evaluate all the candidates, get the best */
      Evaluator evaluator 
        (&A, &r, &kpi_weights, &factorizer, &map, &filter, lambda, M, N);
#if USE_PFUNC
      ReduceType evaluate (my_space, evaluator, *global_taskmgr);
      pfunc::spawn (*global_taskmgr, root_task, root_attribute, evaluate);
      pfunc::wait (*global_taskmgr, root_task);
#else
      evaluator (my_space);
#endif
      /* reduce with the global minimum */
      value_type local_best = evaluator.get_result();
      value_type global_best = find_global_min (local_best);

      /* Create the new model and some statistics about this model */
      add_group (global_best.first);
      Solver::solve (test_A, x, y, lambda, M, N*(1+selected.size())); 
      const double cost = 
        CostFunctor::cost (test_A, x, y, lambda, M, N*(1+selected.size())); 
      const double gain = ((SENTINEL==prev_cost)?(cost):(prev_cost-cost));
      const double confidence = ConfidenceFunctor::confidence 
                           (test_A, y, y_inv, x, M, N*(1+selected.size())); 

      /* Check to see if this is the optimal confidence. If so, variance */
      if ((SENTINEL==best_confidence) || 
          (compare (confidence,best_confidence))) {
        best_confidence = confidence;
        variance = CostFunctor::cost 
          (test_A, x, y, 0.0/*NO REGUL*/, M, N*(1+selected.size())); 
      }

      /* Check if we need to stop --- if so, don't add current candidate */
      if (stop (best_gain, gain, confidence)) {
        if (ROOT==mpi_rank && 2<debug) {
          printf ("stopping at iteration %d\n", iter);
          printf ("cost = %lf, gain = %lf, confidence = %lf\n", 
                            cost, gain, confidence);
        }
        break;
      } 

      if (ROOT==mpi_rank && 2<debug) 
        printf ("selecting %d with cost = %lf, local best = %d, cost = %lf\n",
          global_best.first, cost, local_best.first, local_best.second);

      /* Add to the list of selected KPIs */
      selected.push_back (global_best.first); 

      /* Set up gain and prev_cost */
      prev_cost = cost;
      if (gain>best_gain) best_gain=gain;

      iter_time = micro_time()-iter_time;
      if (mpi_rank==ROOT && 2<debug) {
        printf ("Iteration %d: %lf (per sec)\n", 
             iter, (mpi_size*(my_space.end()-my_space.begin()))/iter_time);
      }
    }

    /**
     * Compute the intercept for this model.
     * 1. Initialize the intercept to be the non-lagged column sum of the KPI.
     * 2. Subtract beta[i]*avg of each of the lagged columns of the predictors.
     *
     * NOTE: Not everyone has this KPI! So, the owner of this KPI should take
     * the initiative to work out the intercept and send it to everyone.
     */
    intercept = get_average (target);
    for (size_t i=0; i<selected.size(); ++i) for (int j=0; j<N; ++j) 
      intercept -= ((x[(i*N)+j]) * get_average (selected[i], j));
  }
Exemplo n.º 19
0
/* 
 * Read and process buxfer commands
 * Return -1 to indicate user has quit
 * Return 1 to indicate broadcast message must be sent to all other users
 * Return 0 otherwise
 */
int process_args(int cmd_argc, char **cmd_argv, Client *c, Pool *p) 
{
    Group *g;
    char *buf;
    char *username = c->username;

    if (cmd_argc <= 0) {
        return 0;

    } else if (strcmp(cmd_argv[0], "quit") == 0 && cmd_argc == 1) {
        return -1;  // -1 indicates used has quit
        
    } else if (strcmp(cmd_argv[0], "add_group") == 0 && cmd_argc == 2) {
        
        // add group
        buf = add_group(&p->group, cmd_argv[1]);  
        Write(c->soc, buf);

        // add user
        if ((g = find_group(p->group, cmd_argv[1])) == NULL) {    
            buf = "Cannot add user. Group does not exist";    
        } else{
            buf = add_user(g, username);                               
            strncpy(c->groupname, cmd_argv[1], MAXLINE);    // set groupname for this client            
            Write(c->soc, buf);   
            return 1;       // Return 1 indicates notification should be sent to all other users
        }   

    } else if (strcmp(cmd_argv[0], "list_groups") == 0 && cmd_argc == 1) {
        buf = list_groups(p->group);
    
    } else if (strcmp(cmd_argv[0], "list_users") == 0 && cmd_argc == 2) {
        if ((g = find_group(p->group, cmd_argv[1])) == NULL) {
            buf = "Group does not exist";
        } else {
            buf = list_users(g);
        }
      
    } else if (strcmp(cmd_argv[0], "user_balance") == 0 && cmd_argc == 2) {
        if ((g = find_group(p->group, cmd_argv[1])) == NULL) {
            buf = "Group does not exist";
        } else {
            buf = user_balance(g, username);            
        }
        
    } else if (strcmp(cmd_argv[0], "add_xct") == 0 && cmd_argc == 3) {
        if ((g = find_group(p->group, cmd_argv[1])) == NULL) {
            buf = "Group does not exist";            
        } else {
            char *end;
            double amount = strtod(cmd_argv[2], &end);
            if (end == cmd_argv[2]) {
                buf = "Incorrect number format";
            } else {
                buf = add_xct(g, username, amount);
            }
        }

    } else {
        buf = "Incorrect syntax";
    }

    // Write output to client
    Write(c->soc, buf);     // Write output to client
    return 0;
}
Exemplo n.º 20
0
void main_loop(pDataStruct workingData){
	char *commandList[] = {"set", "get", "add", "delete","exit","help","ls","cat","cd"};
	char *setList[] = {"date", "user", "group","help"};
	char *getList[] = {"date", "user", "group", "workingDir","help", "userlist", "grouplist", "usersingroup"};
	char *addList[] = {"user", "group", "file", "directory", "usertogroup","perm", "appendfile","help"};
	char *deleteList[] = {"user", "group", "file", "directory", "usertogroup","perm", "filebytes","help"};
	char arg[16][MAXCOMMAND];
	char command[MAXCOMMAND];
	int argnum, i, j, tempNum, cmd, size;
	char *c;
	char temp[MAXPATH];
	char *tempBuf;
	unsigned char *rcvBuf;
	pNode tempNode = NULL;
	pUser tempUser = NULL;
	pGroup tempGroup = NULL;
	pFile tempFile = NULL;
	pPerms tempPerms = NULL;
	pFileChunk tempFileChunk = NULL;
	pGroupUserList tempGroupUserList = NULL;

	while(1){
		argnum = i = j = tempNum = cmd = 0;
		c = 0;
		bzero(temp, sizeof(temp));
		tempBuf = NULL;
		tempNode = NULL;
		tempUser = NULL;
		tempGroup = NULL;
		tempFile = NULL;
		tempPerms = NULL;
		tempFileChunk = NULL;
		tempGroupUserList = NULL;		
		bzero(command, sizeof(command));
		print_prompt(workingData);
		get_string(command, MAXCOMMAND-1, "");
		for (j = 0;j<16;j++){
			bzero(arg[j],MAXCOMMAND);
		}
		argnum = parse_arg(arg, command);
		tempNum = 0;
		cmd = 100;

		for (i=0;i<sizeof(commandList)/4;i++){
			if (strcmp(commandList[i],arg[0]) == 0 ){
				cmd = i;
			}
		}
		switch(cmd)
		{
			case 0x0 : //set
				cmd = 100;
				for (i=0;i<sizeof(setList)/4;i++){
					if (strcmp(setList[i],arg[1]) == 0){
						cmd = i;
					}
				}
				switch(cmd)
				{

					case 0 : //set date
						workingData->date = get_time();
						break;//end set date

					case 1 : //set user

						if ( strcmp(arg[2],"") == 0){
							puts("missing user name or number");
							break;
						}
						tempUser = find_user(arg[2],workingData);
						if ( tempUser != NULL ){
							workingData->currentUser = tempUser;
						} else { 
							printf("unknown user: @s\n",arg[2]);
						}
						break;//end set user

					case 2 : //set group

						if ( strcmp(arg[2], "") == 0){
							puts("missing group name or number");
							break;
						}
						tempGroup = find_group(arg[2], workingData);
						if ( tempGroup != NULL){
							workingData->currentGroup = tempGroup;
						} else {
							printf("unknown group: @s\n",arg[2]);
						}
						break;

					case 3 : //set help
						print_help(setList,(sizeof(setList)/4));
						break;//end set help

					default :
						printf("Invalid command: @s\n",arg[1]);

				}

				break;//end set 

			case 1 ://get
				cmd = 100;
				for (i=0;i<sizeof(getList)/4;i++){
					if (strcmp(getList[i],arg[1]) == 0){
						cmd = i;
					}
				}
				switch(cmd)
				{

					case 0 : //get date
						strofdate( workingData->date);
						break;//end get date

					case 1 : //get user
						printf("@s\n",workingData->currentUser->name);
						break;//end get user

					case 2 : //get group
						printf("@s\n",workingData->currentGroup->name);
						break;//end get group

					case 3 : //get workingDir
						bzero(temp,MAXPATH);
						str_of_path( temp, workingData, workingData->workingDir);
						printf("@s/\n",temp);
						break;//end get workingDir

					case 4 : //get help
						print_help(getList,(sizeof(getList)/4));
						break;//end get help

					case 5 : //get userlist
						print_user_list(workingData);

						break;//end get userlist

					case 6 : //get grouplist
						print_group_list(workingData);
						break;//end get grouplist

					case 7 : //get usersingroup
						if ( strcmp(arg[2], "") == 0){
							puts("missing group name or number");
							break;
						}
						tempGroup = find_group(arg[2], workingData);
						if ( tempGroup != NULL ){
							print_users_in_group(tempGroup);
							break;
						}
						printf("unknown group: @s\n",arg[2]);
						break;//end get useringroup						

					default :
						printf("Invalid command: @s\n",arg[1]);
				}

				break;//end get

			case 2 ://add
				cmd = 100;
				for (i=0;i<sizeof(addList)/4;i++){
					if ( strcmp(addList[i],arg[1]) == 0 ){
						cmd = i;
					}
				}
				switch(cmd)
				{
					case 0 : //add user

						if ( strcmp(arg[2],"") == 0 ){
							bzero(temp,MAXPATH);
							get_string(temp, 128, "UserName");
							strcpy(arg[2],temp);
						}
						tempUser = find_user( arg[2], workingData);
						if ( tempUser == NULL ){
							add_user( arg[2], workingData );
						} else {
							puts("Username already in use");
						}
						break;//end add user

					case 1 : //add group
						if ( strcmp(arg[2],"") == 0 ){
							bzero(temp,MAXPATH);
							get_string(temp, 128, "GroupName");
							strcpy(arg[2], temp);
						}
						tempGroup = find_group( arg[2], workingData);
						if ( tempGroup == NULL ){
							add_group( arg[2], workingData );
						} else {
							puts("Groupname already in use");
						}
						break;//end add group

					case 2 : //add file
						//add file name size
						tempNum = atoi(arg[3]);
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						if ( tempNum > MAXUPLOAD ){
							puts("Too big");
							break;
						}
						if ( find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode) != NULL ){
							puts("There is another file or directory with that name");
							break;
						}
						if ( tempNum > 0){
							rcvBuf = mallocOrDie(tempNum,"Failed to allocate tempBuf");
							puts("-----Begin File-----");//five - 
							if ( tempNum != receive_bytes(rcvBuf,tempNum) ){
								die("Failed to reveive file");
								break;
							}
						} else {rcvBuf = NULL;}
						tempNode = add_file( workingData->workingDir, workingData->date, tempNum, arg[2], (char *)rcvBuf, workingData->currentUser );
						break;//end add file

					case 3 : //add directory

						if (strcmp(arg[2],"") == 0){
							puts("Directory name required");
							break;
						}
						if ( find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode) != NULL ){
							puts("There is another file or directory with that name");
							break;
						}
						tempNode = add_directory( workingData->date, arg[2], workingData->workingDir, workingData->currentUser );
						break;//end add directory

					case 4 : //add useringroup
						if (strcmp(arg[2],"") == 0){
							puts("username or number required");
							break;
						}
						tempUser = find_user( arg[2], workingData);
						if ( tempUser != NULL ){//user exists
							tempGroupUserList = is_user_in_group( tempUser, workingData->currentGroup );
							if ( tempGroupUserList == NULL ){//user is not already in group	
								add_user_to_group( tempUser, workingData->currentGroup );
							} else {printf("@s is already in @s\n",arg[2], workingData->currentGroup->name);}
						} else {
							puts("User does not exist, add user first");
						}

						break;//end add useringroup
						
					case 5 : //add perm
						if (  ( strcmp(arg[2],"") == 0 )||( strcmp(arg[2]," ") == 0 )  ){//arg[2] name of file or dir
							puts("name of file or directory required");
							break;
						}
						if (!(  (strcmp(arg[3],"user") == 0) ^ (strcmp(arg[3],"group") == 0) )) {//arg[3] user, group
							puts("'user' or 'group'");
							break;
						}
						if (strcmp(arg[4],"") == 0){
							puts("user name, group name, or number required");//arg[4] name or number of user or group
							break;
						}
						tempNode = find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode );//validate file or dir
						if (tempNode == NULL){
							puts("Invalid file or directory");
							break;
						}
						if (tempNode->type == LINK){
							tempNode = tempNode->directoryHeadNode;
							break;
						}
						if (strcmp(arg[3],"user") == 0){
							tempUser = find_user(arg[4],workingData);
							tempGroup = NULL;
							if (tempUser == NULL){
								printf("user @s not found\n",arg[4]);
								break;
							}
						} else {
							tempGroup = find_group(arg[4],workingData);
							tempUser = NULL;
							if (tempGroup == NULL){
								printf("group @s not found\n",arg[4]);
								break;
							}
						}

						validate_current_perms(tempNode, workingData);
						tempPerms = add_perm(tempUser, tempGroup, tempNode ); 
						break;//end add perm

					case 6 : //add appendfile
						tempNum = atoi(arg[3]);
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						if ( tempNum > MAXUPLOAD ){
							puts("Too big");
							break;
						}
						tempFile = find_file_by_name(arg[2],workingData->workingDir);
						if (  tempFile == NULL ){
							puts("No file in working directory by that name");
							break;
						}
						if ( tempNum > 0){
							tempBuf = mallocOrDie(tempNum,"Failed to allocate tempBuf");
							puts("-----Begin File-----");//five - 
							if ( tempNum != receive_bytes((unsigned char *)tempBuf,tempNum) ){
								die("Failed to reveive file");
								break;
							}
						} else {
							tempBuf = NULL;
							puts("Can not add 0 bytes to file");
							break;
						}
						tempFileChunk = add_file_chunk( tempBuf, tempFile, tempNum );
						break;//end add appendfile

					case 7 : //add help
						print_help(addList, (sizeof(addList)/4));	
						break;//end add help

					default :
						printf("Invalid command: @s\n",arg[1]);
				}

				break;//end add
			case 3 ://delete 	
				cmd = 100;
				for (i=0;i<sizeof(deleteList)/4;i++){
					if ( strcmp(deleteList[i],arg[1]) == 0 ){
						cmd = i;
					}
				}
				switch(cmd)
				{

					case 0 : //delete user
						bzero(temp,MAXPATH);
						if ( strcmp(arg[2],"") == 0 ){
							get_string(temp, 128, "User Name or number");
							strcpy(arg[2],temp);
						}
						tempUser = find_user( arg[2], workingData);
						if ( tempUser != NULL ){
							remove_user(tempUser , workingData );
						} else {
							puts("No such user found");
						}
						break;//end delete user

					case 1 : //delete group
						bzero(temp,MAXPATH);
						if ( strcmp(arg[2],"") == 0 ){
							get_string(temp, 128, "Group Name or number");
							strcpy(arg[2],temp);
						}
						tempGroup = find_group( arg[2], workingData);
						if ( tempGroup != NULL ){
							remove_group(tempGroup , workingData );
						} else {
							puts("no such group found");
						}
						break;//end delete group 

					case 2 : //delete file 
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						tempNode = find_file_node_by_name(arg[2],workingData->workingDir);
						if (tempNode == NULL){
							puts("No such file");
							break;
						}
						delete_node(tempNode, workingData);
						break;//end delete file 

					case 3 : //delete directory
						if (strcmp(arg[2],"") == 0){
							puts("Directory name required");
							break;
						}
						tempNode = find_directory_by_name(arg[2],workingData->workingDir);
						if (tempNode == NULL){
							puts("No such directory");
							break;
						}
						delete_node(tempNode, workingData);
						break;//end delete directory

					case 4 : //delete usertogroup
						if (strcmp(arg[2],"") == 0){
							puts("User name required");
							break;
						}
						if (strcmp(arg[3],"") == 0){
							puts("group name required");
							break;
						}
						tempUser = find_user(arg[2],workingData);
						if (tempUser == NULL){
							puts("No such user");
							break;
						}
						tempGroup = find_group(arg[3],workingData);
						if (tempGroup == NULL){
							puts("No such group");
							break;
						}
						tempGroupUserList = is_user_in_group(tempUser, tempGroup);
						if (tempGroupUserList == NULL){
							puts("User is not in group");
							break;
						}
						remove_user_from_group(tempUser, tempGroup);
						break;//end delete usertogroup

					case 5 : //delete perm
						if (strcmp(arg[3],"") == 0){
							puts("User or group name required");
							break;
						}
						if (strcmp(arg[2],"") == 0){
							puts("file name required");
							break;
						}
						tempNode = find_node_by_name(arg[2],workingData->workingDir->directoryHeadNode);
						if (tempNode == NULL){
							puts("No such file");
							break;
						}
						tempPerms = find_perm_by_name(arg[3],tempNode,workingData);
						if (tempPerms != NULL){
							delete_perms(tempNode, tempPerms);
						} else {
							puts("No such user permission on file");
						}
						break;//end delete perm

					case 6 : //delete filebytes [file] [numbytes]
						if (strcmp(arg[2],"") == 0){
							puts("Filename required");
							break;
						}
						size = strict_atoi(arg[3]);
						if (size == 0){
							puts("zero bytes deleted");
							break;
						}
						//validate file						
						tempNode = find_file_node_by_name(arg[2],workingData->workingDir);
						tempFile = tempNode->file;
						if (tempNode == NULL){
							puts("No such file");
							printf("@s\n",arg[2]);
							break;
						}
						tempNum = get_file_size(tempFile);
						if (size > tempNum){
							puts("Too many bytes");
						} 
						//tempNum is new file size
						tempNum = tempNum - size;
						delete_file_bytes(tempFile, tempNum);
						break;//end delete file 

					case 7 : //delete help
						print_help(deleteList, (sizeof(deleteList)/4));	
						break;//end delete help

					default:
						print_help(deleteList, (sizeof(deleteList)/4));	
						//break;//end delete help

				}
				break;//end delete
				

			case 4 ://cgc_exit
				puts("exiting");
				goto cgc_exit;
				break;

			case 5 ://help
				print_help(commandList, (sizeof(commandList)/4));
				break;
			case 6 ://ls
				print_working_dir(workingData);
				break;
			case 7 ://cat
				if (strcmp(arg[1],"") == 0){
					puts("Filename required");
					break;
				}
				tempFile = find_file_by_name(arg[1], workingData->workingDir);							
				if ( tempFile != NULL ){
					tempFileChunk = tempFile->head;
					puts("-----Begin File-----");//five - 
					while ( tempFileChunk != NULL ){
						if (tempFileChunk->chunkSize != cgc_write(tempFileChunk,tempFileChunk->chunkSize)){
							puts("file write failed");
						}
/*
						c = tempFileChunk->chunk;
						for ( i = 0; i < tempFileChunk->chunkSize; i++ ){//putc each byte of every chunk
							putc( *c);
							c++;
						}
*/						
						tempFileChunk = tempFileChunk->next;	
					}
					puts("-----END File-----");//five - 
				}
				break;
			case 8 ://cd
				if (strcmp(arg[1],"") == 0){
					puts("directory required");
					break;
				}
				if (strcmp(arg[1],"..") == 0){
					if (workingData->workingDir->parent != NULL){
						workingData->workingDir = workingData->workingDir->parent;
					}
					break;
				}
				tempNode = find_directory_by_name(arg[1],workingData->workingDir);
				if ( tempNode != NULL ){
					workingData->workingDir = tempNode;
					break;
				}
				puts("No such directory in working directory");
				break;//end cd

			default :
				printf("Invalid command @s\n",arg[0]);
				print_help(commandList, (sizeof(commandList)/4));
				
		}
	}
	cgc_exit:
	return;
}
Exemplo n.º 21
0
int load_contacts_from_file(const char *file)
{
	FILE *fp;
	extern int contactparse();
	extern FILE *contactin;
	LList *cts = NULL;

	if (!(fp = fopen(file, "r")))
		return 0;
	contactin = fp;

	contactparse();

	fclose(fp);

	/* rename logs from old format (contact->nick) to new 
	   (contact->nick "-" contact->group->name) */

	if (temp_groups && groups) {
		while (temp_groups) {
			grouplist *grp = (grouplist *)temp_groups->data;
			grouplist *oldgrp = NULL;
			if ((oldgrp = find_grouplist_by_name(grp->name)) ==
				NULL) {
				eb_debug(DBG_CORE, "adding group %s\n",
					grp->name);
				add_group(grp->name);
				oldgrp = find_grouplist_by_name(grp->name);
			}
			while (grp->members) {
				struct contact *con =
					(struct contact *)grp->members->data;
				if (!find_contact_in_group_by_nick(con->nick,
						oldgrp)) {
					LList *w = con->accounts;
					int sid = 0;
					while (w) {
						eb_account *ea =
							(eb_account *)w->data;
						if (find_account_by_handle(ea->
								handle,
								ea->
								service_id)) {
							con->accounts =
								l_list_remove
								(con->accounts,
								ea);
							w = con->accounts;
						} else {
							sid = ea->service_id;
							w = w->next;
						}
					}
					if (!l_list_empty(con->accounts)
						&& con->accounts->data) {
						eb_debug(DBG_CORE,
							" adding contact %s\n",
							con->nick);
						add_new_contact(grp->name,
							con->nick, sid);
						w = con->accounts;
						while (w) {
							add_account_silent(con->
								nick,
								(eb_account *)
								w->data);
							eb_debug(DBG_CORE,
								"  adding account %s\n",
								((eb_account *)
									w->
									data)->
								handle);
							w = w->next;
						}
					}
				} else {
					while (con->accounts) {
						eb_account *ea =
							(eb_account *)con->
							accounts->data;
						if (!find_account_by_handle(ea->
								handle,
								ea->
								service_id)) {
							add_account_silent(con->
								nick, ea);
							eb_debug(DBG_CORE,
								"  adding account to ex.ct %s\n",
								ea->handle);
						}
						con->accounts =
							con->accounts->next;
					}
				}
				grp->members = grp->members->next;
			}

			temp_groups = temp_groups->next;
		}
	} else if (temp_groups) {
		eb_debug(DBG_CORE, "First pass\n");
		groups = temp_groups;
	}

	if (groups) {
		update_contact_list();
		write_contact_list();
	}

	cts = get_all_contacts();
	for (; cts && cts->data; cts = cts->next) {
		struct contact *c = (struct contact *)cts->data;
		FILE *test = NULL;
		char buff[NAME_MAX];
		eb_debug(DBG_CORE, "contact:%s\n", c->nick);
		make_safe_filename(buff, c->nick, c->group->name);
		if ((test = fopen(buff, "r")) != NULL)
			fclose(test);
		else
			rename_nick_log(NULL, c->nick, c->group->name, c->nick);
	}
	return 1;
}
Exemplo n.º 22
0
static void
read_group(FILE *gfile, char *fname)
{
	char  line[2048], *p, *k, *u, *g;
	int   line_no = 0, len, colon;

	while (read_line(gfile, line, sizeof(line))) {
		line_no++;
		len = strlen(line);

		if (len > 0) {
			if (line[0] == '#')
				continue;
		}

		/*
		 * Check if we have the whole line
		 */
		if (line[len-1] != '\n') {
			fprintf(stderr, "line %d in \"%s\" is too long\n",
			    line_no, fname);
		} else {
			line[len-1] = '\0';
		}

		p = (char *)&line;

		k = p; colon = 0;
		while (*k != '\0') {
			if (*k == ':')
				colon++;
			k++;
		}

		if (colon > 0) {
			k = p;			/* save start of key  */
			while (*p != ':')
				p++;		/* find first "colon" */
			if (*p==':')
				*p++ = '\0';	/* terminate key */
			if (strlen(k) == 1) {
				if (*k == '+')
					continue;
			}
		}

		if (colon < 3) {
			fprintf(stderr, "syntax error at line %d in \"%s\"\n",
			    line_no, fname);
			continue;
		}

		while (*p != ':')
			p++;			/* find second "colon" */
		if (*p==':')
			*p++ = '\0';		/* terminate passwd */
		g = p;
		while (*p != ':')
			p++;			/* find third "colon" */
		if (*p==':')
			*p++ = '\0';		/* terminate gid */

		u = p;

		while (*u != '\0') {
			while (!isgsep(*p))
				p++;		/* find separator */
			if (*p != '\0') {
				*p = '\0';
				if (u != p)
					add_group(u, g);
				p++;
			} else {
				if (u != p)
					add_group(u, g);
			}
			u = p;
		}
	}
}
Exemplo n.º 23
0
static HRESULT
fill_groups( struct d3dadapter9 *This )
{
    DISPLAY_DEVICEW dd;
    DEVMODEW dm;
    POINT pt;
    HDC hdc;
    HRESULT hr;
    int i, j, k;

    WCHAR wdisp[] = {'D','I','S','P','L','A','Y',0};

    ZeroMemory(&dd, sizeof(dd));
    ZeroMemory(&dm, sizeof(dm));
    dd.cb = sizeof(dd);
    dm.dmSize = sizeof(dm);

    for (i = 0; EnumDisplayDevicesW(NULL, i, &dd, 0); ++i) {
        struct adapter_group *group = add_group(This);
        if (!group) {
            ERR("Out of memory.\n");
            return E_OUTOFMEMORY;
        }

        hdc = CreateDCW(wdisp, dd.DeviceName, NULL, NULL);
        if (!hdc) {
            remove_group(This);
            WARN("Unable to create DC for display %d.\n", i);
            goto end_group;
        }

        hr = present_create_adapter9(This->gdi_display, hdc, &group->adapter);
        DeleteDC(hdc);
        if (FAILED(hr)) {
            remove_group(This);
            goto end_group;
        }

        CopyMemory(group->devname, dd.DeviceName, sizeof(group->devname));
        for (j = 0; EnumDisplayDevicesW(group->devname, j, &dd, 0); ++j) {
            struct output *out = add_output(This);
            boolean orient = FALSE, monit = FALSE;
            if (!out) {
                ERR("Out of memory.\n");
                return E_OUTOFMEMORY;
            }

            for (k = 0; EnumDisplaySettingsExW(dd.DeviceName, k, &dm, 0); ++k) {
                D3DDISPLAYMODEEX *mode = add_mode(This);
                if (!out) {
                    ERR("Out of memory.\n");
                    return E_OUTOFMEMORY;
                }

                mode->Size = sizeof(D3DDISPLAYMODEEX);
                mode->Width = dm.dmPelsWidth;
                mode->Height = dm.dmPelsHeight;
                mode->RefreshRate = dm.dmDisplayFrequency;
                mode->ScanLineOrdering =
                    (dm.dmDisplayFlags & DM_INTERLACED) ?
                        D3DSCANLINEORDERING_INTERLACED :
                        D3DSCANLINEORDERING_PROGRESSIVE;

                switch (dm.dmBitsPerPel) {
                    case 32: mode->Format = D3DFMT_X8R8G8B8; break;
                    case 24: mode->Format = D3DFMT_R8G8B8; break;
                    case 16: mode->Format = D3DFMT_R5G6B5; break;
                    case 8:
                        remove_mode(This);
                        goto end_mode;

                    default:
                        remove_mode(This);
                        WARN("Unknown format (%u bpp) in display %d, monitor "
                             "%d, mode %d.\n", dm.dmBitsPerPel, i, j, k);
                        goto end_mode;
                }

                if (!orient) {
                    switch (dm.dmDisplayOrientation) {
                        case DMDO_DEFAULT:
                            out->rotation = D3DDISPLAYROTATION_IDENTITY;
                            break;

                        case DMDO_90:
                            out->rotation = D3DDISPLAYROTATION_90;
                            break;

                        case DMDO_180:
                            out->rotation = D3DDISPLAYROTATION_180;
                            break;

                        case DMDO_270:
                            out->rotation = D3DDISPLAYROTATION_270;
                            break;

                        default:
                            remove_output(This);
                            WARN("Unknown display rotation in display %d, "
                                 "monitor %d\n", i, j);
                            goto end_output;
                    }
                    orient = TRUE;
                }

                if (!monit) {
                    pt.x = dm.dmPosition.x;
                    pt.y = dm.dmPosition.y;
                    out->monitor = MonitorFromPoint(pt, 0);
                    if (!out->monitor) {
                        remove_output(This);
                        WARN("Unable to get monitor handle for display %d, "
                             "monitor %d.\n", i, j);
                        goto end_output;
                    }
                    monit = TRUE;
                }

end_mode:
                ZeroMemory(&dm, sizeof(dm));
                dm.dmSize = sizeof(dm);
            }

end_output:
            ZeroMemory(&dd, sizeof(dd));
            dd.cb = sizeof(dd);
        }

end_group:
        ZeroMemory(&dd, sizeof(dd));
        dd.cb = sizeof(dd);
    }

    return D3D_OK;
}
Exemplo n.º 24
0
Group *rna_Main_groups_new(Main *UNUSED(bmain), const char *name)
{
	return add_group(name);
}
Exemplo n.º 25
0
/* Get the next group from NSS  (+ entry). If the NSS module supports
   initgroups_dyn, get all entries at once.  */
static enum nss_status
getgrent_next_nss (ent_t *ent, char *buffer, size_t buflen, const char *user,
		   gid_t group, long int *start, long int *size,
		   gid_t **groupsp, long int limit, int *errnop)
{
  enum nss_status status;
  struct group grpbuf;

  /* Try nss_initgroups_dyn if supported. We also need getgrgid_r.
     If this function is not supported, step through the whole group
     database with getgrent_r.  */
  if (! ent->skip_initgroups_dyn)
    {
      long int mystart = 0;
      long int mysize = limit <= 0 ? *size : limit;
      gid_t *mygroups = malloc (mysize * sizeof (gid_t));

      if (mygroups == NULL)
	return NSS_STATUS_TRYAGAIN;

      /* For every gid in the list we get from the NSS module,
	 get the whole group entry. We need to do this, since we
	 need the group name to check if it is in the blacklist.
	 In worst case, this is as twice as slow as stepping with
	 getgrent_r through the whole group database. But for large
	 group databases this is faster, since the user can only be
	 in a limited number of groups.  */
      if (nss_initgroups_dyn (user, group, &mystart, &mysize, &mygroups,
			      limit, errnop) == NSS_STATUS_SUCCESS)
	{
	  status = NSS_STATUS_NOTFOUND;

	  /* If there is no blacklist we can trust the underlying
	     initgroups implementation.  */
	  if (ent->blacklist.current <= 1)
	    for (int i = 0; i < mystart; i++)
	      add_group (start, size, groupsp, limit, mygroups[i]);
	  else
	    {
	      /* A temporary buffer. We use the normal buffer, until we find
		 an entry, for which this buffer is to small.  In this case, we
		 overwrite the pointer with one to a bigger buffer.  */
	      char *tmpbuf = buffer;
	      size_t tmplen = buflen;
	      bool use_malloc = false;

	      for (int i = 0; i < mystart; i++)
		{
		  while ((status = nss_getgrgid_r (mygroups[i], &grpbuf,
						   tmpbuf, tmplen, errnop))
			 == NSS_STATUS_TRYAGAIN
			 && *errnop == ERANGE)
                    {
                      if (__libc_use_alloca (tmplen * 2))
                        {
                          if (tmpbuf == buffer)
                            {
                              tmplen *= 2;
                              tmpbuf = __alloca (tmplen);
                            }
                          else
                            tmpbuf = extend_alloca (tmpbuf, tmplen, tmplen * 2);
                        }
                      else
                        {
                          tmplen *= 2;
                          char *newbuf = realloc (use_malloc ? tmpbuf : NULL, tmplen);

                          if (newbuf == NULL)
                            {
                              status = NSS_STATUS_TRYAGAIN;
			      goto done;
                            }
                          use_malloc = true;
                          tmpbuf = newbuf;
                        }
                    }

		  if (__builtin_expect  (status != NSS_STATUS_NOTFOUND, 1))
		    {
		      if (__builtin_expect  (status != NSS_STATUS_SUCCESS, 0))
		        goto done;

		      if (!in_blacklist (grpbuf.gr_name,
					 strlen (grpbuf.gr_name), ent)
			  && check_and_add_group (user, group, start, size,
						  groupsp, limit, &grpbuf))
			{
			  if (nss_setgrent != NULL)
			    {
			      nss_setgrent (1);
			      ent->need_endgrent = true;
			    }
			  ent->skip_initgroups_dyn = true;

			  goto iter;
			}
		    }
		}

	      status = NSS_STATUS_NOTFOUND;

 done:
	      if (use_malloc)
	        free (tmpbuf);
	    }

	  free (mygroups);

	  return status;
	}

      free (mygroups);
    }

  /* If we come here, the NSS module does not support initgroups_dyn
     or we were confronted with a split group.  In these cases we have
     to step through the whole list ourself.  */
 iter:
  do
    {
      if ((status = nss_getgrent_r (&grpbuf, buffer, buflen, errnop)) !=
	  NSS_STATUS_SUCCESS)
	break;
    }
  while (in_blacklist (grpbuf.gr_name, strlen (grpbuf.gr_name), ent));

  if (status == NSS_STATUS_SUCCESS)
    check_and_add_group (user, group, start, size, groupsp, limit, &grpbuf);

  return status;
}
Exemplo n.º 26
0
int main (int argc, char **argv)
{
	char buf[BUFSIZ];
	char *fields[8];
	int nfields;
	char *cp;
	const struct passwd *pw;
	struct passwd newpw;
	int errors = 0;
	int line = 0;
	uid_t uid;
	gid_t gid;
#ifdef USE_PAM
	int *lines = NULL;
	char **usernames = NULL;
	char **passwords = NULL;
	unsigned int nusers = 0;
#endif				/* USE_PAM */

	Prog = Basename (argv[0]);

	(void) setlocale (LC_ALL, "");
	(void) bindtextdomain (PACKAGE, LOCALEDIR);
	(void) textdomain (PACKAGE);

	/* FIXME: will not work with an input file */
	process_root_flag ("-R", argc, argv);

	OPENLOG ("newusers");

	process_flags (argc, argv);

	check_perms ();

	is_shadow = spw_file_present ();

#ifdef SHADOWGRP
	is_shadow_grp = sgr_file_present ();
#endif
#ifdef ENABLE_SUBIDS
	is_sub_uid = sub_uid_file_present () && !rflg;
	is_sub_gid = sub_gid_file_present () && !rflg;
#endif				/* ENABLE_SUBIDS */

	open_files ();

	/*
	 * Read each line. The line has the same format as a password file
	 * entry, except that certain fields are not constrained to be
	 * numerical values. If a group ID is entered which does not already
	 * exist, an attempt is made to allocate the same group ID as the
	 * numerical user ID. Should that fail, the next available group ID
	 * over 100 is allocated. The pw_gid field will be updated with that
	 * value.
	 */
	while (fgets (buf, (int) sizeof buf, stdin) != (char *) 0) {
		line++;
		cp = strrchr (buf, '\n');
		if (NULL != cp) {
			*cp = '\0';
		} else {
			if (feof (stdin) == 0) {
				fprintf (stderr,
				         _("%s: line %d: line too long\n"),
				         Prog, line);
				errors++;
				continue;
			}
		}

		/*
		 * Break the string into fields and screw around with them.
		 * There MUST be 7 colon separated fields, although the
		 * values aren't that particular.
		 */
		for (cp = buf, nfields = 0; nfields < 7; nfields++) {
			fields[nfields] = cp;
			cp = strchr (cp, ':');
			if (NULL != cp) {
				*cp = '\0';
				cp++;
			} else {
				break;
			}
		}
		if (nfields != 6) {
			fprintf (stderr, _("%s: line %d: invalid line\n"),
			         Prog, line);
			errors++;
			continue;
		}

		/*
		 * First check if we have to create or update an user
		 */
		pw = pw_locate (fields[0]);
		/* local, no need for xgetpwnam */
		if (   (NULL == pw)
		    && (getpwnam (fields[0]) != NULL)) {
			fprintf (stderr, _("%s: cannot update the entry of user %s (not in the passwd database)\n"), Prog, fields[0]);
			errors++;
			continue;
		}

		if (   (NULL == pw)
		    && (get_user_id (fields[2], &uid) != 0)) {
			fprintf (stderr,
			         _("%s: line %d: can't create user\n"),
			         Prog, line);
			errors++;
			continue;
		}

		/*
		 * Processed is the group name. A new group will be
		 * created if the group name is non-numeric and does not
		 * already exist. If the group name is a number (which is not
		 * an existing GID), a group with the same name as the user
		 * will be created, with the given GID. The given or created
		 * group will be the primary group of the user. If
		 * there is no named group to be a member of, the UID will
		 * be figured out and that value will be a candidate for a
		 * new group, if that group ID exists, a whole new group ID
		 * will be made up.
		 */
		if (   (NULL == pw)
		    && (add_group (fields[0], fields[3], &gid, uid) != 0)) {
			fprintf (stderr,
			         _("%s: line %d: can't create group\n"),
			         Prog, line);
			errors++;
			continue;
		}

		/*
		 * Now we work on the user ID. It has to be specified either
		 * as a numerical value, or left blank. If it is a numerical
		 * value, that value will be used, otherwise the next
		 * available user ID is computed and used. After this there
		 * will at least be a (struct passwd) for the user.
		 */
		if (   (NULL == pw)
		    && (add_user (fields[0], uid, gid) != 0)) {
			fprintf (stderr,
			         _("%s: line %d: can't create user\n"),
			         Prog, line);
			errors++;
			continue;
		}

		/*
		 * The password, gecos field, directory, and shell fields
		 * all come next.
		 */
		pw = pw_locate (fields[0]);
		if (NULL == pw) {
			fprintf (stderr,
			         _("%s: line %d: user '%s' does not exist in %s\n"),
			         Prog, line, fields[0], pw_dbname ());
			errors++;
			continue;
		}
		newpw = *pw;

#ifdef USE_PAM
		/* keep the list of user/password for later update by PAM */
		nusers++;
		lines     = realloc (lines,     sizeof (lines[0])     * nusers);
		usernames = realloc (usernames, sizeof (usernames[0]) * nusers);
		passwords = realloc (passwords, sizeof (passwords[0]) * nusers);
		lines[nusers-1]     = line;
		usernames[nusers-1] = strdup (fields[0]);
		passwords[nusers-1] = strdup (fields[1]);
#endif				/* USE_PAM */
		if (add_passwd (&newpw, fields[1]) != 0) {
			fprintf (stderr,
			         _("%s: line %d: can't update password\n"),
			         Prog, line);
			errors++;
			continue;
		}
		if ('\0' != fields[4][0]) {
			newpw.pw_gecos = fields[4];
		}

		if ('\0' != fields[5][0]) {
			newpw.pw_dir = fields[5];
		}

		if ('\0' != fields[6][0]) {
			newpw.pw_shell = fields[6];
		}

		if (   ('\0' != fields[5][0])
		    && (access (newpw.pw_dir, F_OK) != 0)) {
/* FIXME: should check for directory */
			mode_t msk = 0777 & ~getdef_num ("UMASK",
			                                 GETDEF_DEFAULT_UMASK);
			if (mkdir (newpw.pw_dir, msk) != 0) {
				fprintf (stderr,
				         _("%s: line %d: mkdir %s failed: %s\n"),
				         Prog, line, newpw.pw_dir,
				         strerror (errno));
			} else if (chown (newpw.pw_dir,
			                  newpw.pw_uid,
			                  newpw.pw_gid) != 0) {
				fprintf (stderr,
				         _("%s: line %d: chown %s failed: %s\n"),
				         Prog, line, newpw.pw_dir,
				         strerror (errno));
			}
		}

		/*
		 * Update the password entry with the new changes made.
		 */
		if (pw_update (&newpw) == 0) {
			fprintf (stderr,
			         _("%s: line %d: can't update entry\n"),
			         Prog, line);
			errors++;
			continue;
		}

#ifdef ENABLE_SUBIDS
		/*
		 * Add subordinate uids if the user does not have them.
		 */
		if (is_sub_uid && !sub_uid_assigned(fields[0])) {
			uid_t sub_uid_start = 0;
			unsigned long sub_uid_count = 0;
			if (find_new_sub_uids(fields[0], &sub_uid_start, &sub_uid_count) == 0) {
				if (sub_uid_add(fields[0], sub_uid_start, sub_uid_count) == 0) {
					fprintf (stderr,
						_("%s: failed to prepare new %s entry\n"),
						Prog, sub_uid_dbname ());
				}
			} else {
				fprintf (stderr,
					_("%s: can't find subordinate user range\n"),
					Prog);
				errors++;
			}
		}

		/*
		 * Add subordinate gids if the user does not have them.
		 */
		if (is_sub_gid && !sub_gid_assigned(fields[0])) {
			gid_t sub_gid_start = 0;
			unsigned long sub_gid_count = 0;
			if (find_new_sub_gids(fields[0], &sub_gid_start, &sub_gid_count) == 0) {
				if (sub_gid_add(fields[0], sub_gid_start, sub_gid_count) == 0) {
					fprintf (stderr,
						_("%s: failed to prepare new %s entry\n"),
						Prog, sub_uid_dbname ());
				}
			} else {
				fprintf (stderr,
					_("%s: can't find subordinate group range\n"),
					Prog);
				errors++;
			}
		}
#endif				/* ENABLE_SUBIDS */
	}

	/*
	 * Any detected errors will cause the entire set of changes to be
	 * aborted. Unlocking the password file will cause all of the
	 * changes to be ignored. Otherwise the file is closed, causing the
	 * changes to be written out all at once, and then unlocked
	 * afterwards.
	 */
	if (0 != errors) {
		fprintf (stderr,
		         _("%s: error detected, changes ignored\n"), Prog);
		fail_exit (EXIT_FAILURE);
	}

	close_files ();

	nscd_flush_cache ("passwd");
	nscd_flush_cache ("group");
	sssd_flush_cache (SSSD_DB_PASSWD | SSSD_DB_GROUP);

#ifdef USE_PAM
	unsigned int i;
	/* Now update the passwords using PAM */
	for (i = 0; i < nusers; i++) {
		if (do_pam_passwd_non_interactive ("newusers", usernames[i], passwords[i]) != 0) {
			fprintf (stderr,
			         _("%s: (line %d, user %s) password not changed\n"),
			         Prog, lines[i], usernames[i]);
			errors++;
		}
	}
#endif				/* USE_PAM */

	return ((0 == errors) ? EXIT_SUCCESS : EXIT_FAILURE);
}
Exemplo n.º 27
0
int cfg_read(Cfg *cfg) 
{ 
    CfgLoc *loc; 
    CfgLoc *loc_inc; 
    List *lines;
    List *expand; 
    List *stack; 
    Octstr *name;
    Octstr *value;
    Octstr *filename; 
    CfgGroup *grp;
    long equals;
    long lineno;
    long error_lineno;
    
    loc = loc_inc = NULL;

    /* 
     * expand initial main config file and add it to the recursion 
     * stack to protect against cycling 
     */ 
    if ((lines = expand_file(cfg->filename, 1)) == NULL) { 
        panic(0, "Failed to load main configuration file `%s'. Aborting!", 
              octstr_get_cstr(cfg->filename)); 
    } 
    stack = gwlist_create(); 
    gwlist_insert(stack, 0, octstr_duplicate(cfg->filename)); 

    grp = NULL;
    lineno = 0;
    error_lineno = 0;
    while (error_lineno == 0 && (loc = gwlist_extract_first(lines)) != NULL) { 
        octstr_strip_blanks(loc->line); 
        if (octstr_len(loc->line) == 0) { 
            if (grp != NULL && add_group(cfg, grp) == -1) { 
                error_lineno = loc->line_no; 
                destroy_group(grp); 
            } 
            grp = NULL; 
        } else if (octstr_get_char(loc->line, 0) != '#') { 
            equals = octstr_search_char(loc->line, '=', 0); 
            if (equals == -1) { 
                error(0, "An equals sign ('=') is missing on line %ld of file %s.", 
                      loc->line_no, octstr_get_cstr(loc->filename)); 
                error_lineno = loc->line_no; 
            } else  
             
            /* 
             * check for special config directives, like include or conditional 
             * directives here 
             */ 
            if (octstr_search(loc->line, octstr_imm("include"), 0) != -1) { 
                filename = octstr_copy(loc->line, equals + 1, octstr_len(loc->line)); 
                parse_value(filename); 
 
                /* check if we are cycling */ 
                if (gwlist_search(stack, filename, octstr_item_match) != NULL) { 
                    panic(0, "Recursive include for config file `%s' detected " 
                             "(on line %ld of file %s).", 
                          octstr_get_cstr(filename), loc->line_no,  
                          octstr_get_cstr(loc->filename)); 
                } else {     
                    List *files = gwlist_create();
                    Octstr *file;
                    struct stat filestat;

                    /* check if included file is a directory */
                    if (lstat(octstr_get_cstr(filename), &filestat) != 0) {
                        error(errno, "lstat failed: couldn't stat `%s'", 
                              octstr_get_cstr(filename));
                        panic(0, "Failed to include `%s' "
                              "(on line %ld of file %s). Aborting!",  
                              octstr_get_cstr(filename), loc->line_no,  
                              octstr_get_cstr(loc->filename)); 
                    }
                    
                    /* 
                     * is a directory, create a list with files of
                     * this directory and load all as part of the
                     * whole configuration.
                     */
                    if (S_ISDIR(filestat.st_mode)) {
                        DIR *dh;
                        struct dirent *diritem;

                        debug("gwlib.cfg", 0, "Loading include dir `%s' "
                              "(on line %ld of file %s).",  
                              octstr_get_cstr(filename), loc->line_no,  
                              octstr_get_cstr(loc->filename)); 

                        dh = opendir(octstr_get_cstr(filename));
                        while ((diritem = readdir(dh))) {
                            Octstr *fileitem;

                            fileitem = octstr_duplicate(filename);
                            octstr_append_cstr(fileitem, "/");
                            octstr_append_cstr(fileitem, diritem->d_name);

                            lstat(octstr_get_cstr(fileitem), &filestat);
                            if (!S_ISDIR(filestat.st_mode)) {
                                gwlist_insert(files, 0, fileitem);
                            } else {
                            	octstr_destroy(fileitem);
                            }
                        }
                        closedir(dh);
                    } 
		    
                    /* is a file, create a list with it */
                    else {
                        gwlist_insert(files, 0, octstr_duplicate(filename));
                    }

                    /* include files */
                    while ((file = gwlist_extract_first(files)) != NULL) {

                        gwlist_insert(stack, 0, octstr_duplicate(file)); 
                        debug("gwlib.cfg", 0, "Loading include file `%s' (on line %ld of file %s).",  
                              octstr_get_cstr(file), loc->line_no,  
                              octstr_get_cstr(loc->filename)); 

                        /*  
                         * expand the given include file and add it to the current 
                         * processed main while loop 
                         */ 
                        if ((expand = expand_file(file, 0)) != NULL) {
                            while ((loc_inc = gwlist_extract_first(expand)) != NULL) 
                                gwlist_insert(lines, 0, loc_inc); 
                        } else { 
                            panic(0, "Failed to load whole configuration. Aborting!"); 
                        } 
                 
                        gwlist_destroy(expand, NULL); 
                        cfgloc_destroy(loc_inc);
                        octstr_destroy(file);
                    }
                    gwlist_destroy(files, octstr_destroy_item);
                } 
                octstr_destroy(filename); 
            }  
             
            /* 
             * this is a "normal" line, so process it accodingly 
             */ 
            else  { 
                name = octstr_copy(loc->line, 0, equals); 
                octstr_strip_blanks(name); 
                value = octstr_copy(loc->line, equals + 1, octstr_len(loc->line)); 
                parse_value(value); 
 
    	    	if (grp == NULL)
                    grp = create_group(); 
                 
                if (grp->configfile != NULL) {
                    octstr_destroy(grp->configfile); 
                    grp->configfile = NULL;
                }
                grp->configfile = octstr_duplicate(cfg->filename); 

                cfg_set(grp, name, value); 
                octstr_destroy(name); 
                octstr_destroy(value); 
            } 
        } 

        cfgloc_destroy(loc); 
    }

    if (grp != NULL && add_group(cfg, grp) == -1) {
        error_lineno = 1; 
        destroy_group(grp); 
    }

    gwlist_destroy(lines, NULL); 
    gwlist_destroy(stack, octstr_destroy_item); 

    if (error_lineno != 0) {
        error(0, "Error found on line %ld of file `%s'.",  
	          error_lineno, octstr_get_cstr(cfg->filename)); 
        return -1; 
    }

    return 0;
}
Exemplo n.º 28
0
int group_callback(const char *shortvar, const char *var, const char *arguments, const char *value, lc_flags_t flags, void *extra){
    switch(flags){
        case LC_FLAGS_SECTIONSTART:
            //printf("new group %s\n",arguments);
            if(current_group){
                printf("can't include a section into a section\n");
                return LC_CBRET_ERROR;
            }
            if(list_find(groups,arguments)){
                printf("group %s defined twice\n",arguments);
                return LC_CBRET_ERROR;
            }
            current_group=malloc(sizeof(struct group));
            memset(current_group,0,sizeof(struct group));
            groups=list_add(groups,arguments,current_group);
            current_group_name=strdup(arguments);
            break;
        case LC_FLAGS_SECTIONEND:
            //printf("end of group\n\n");
            current_group=NULL;
            break;
        default:
            //printf("%s - %s\n", shortvar, value);
            if(!strcasecmp(shortvar,"user")){
                char *ptr;
                char *user=(char *)value;
                do{
                    ptr=strchr(user,',');
                    if(ptr){
                        *ptr=0;
                        ++ptr;
                    }
                    while(*user==' ')
                        ++user;
                    add_user(user);
                    user=ptr;
                } while (user);
            }
            if(!strcasecmp(shortvar,"group")){
                char *ptr;
                char *group=(char *)value;
                do{
                    ptr=strchr(group,',');
                    if(ptr){
                        *ptr=0;
                        ++ptr;
                    }
                    while(*group==' ')
                        ++group;
                    add_group(group);
                    group=ptr;
                } while (group);
            }
            if(!strcasecmp(shortvar,"uid")){
                current_group->uid=strdup(value);
            }
            if(!strcasecmp(shortvar,"gid")){
                current_group->gid=strdup(value);
            }
            if(!strcasecmp(shortvar,"chroot")){
                current_group->chroot=strdup(value);
            }
            if(!strcasecmp(shortvar,"nopassword"))
                current_group->nopassword=1;
    }
    return LC_CBRET_OKAY;
}
Exemplo n.º 29
0
/*
 * NOTE: the "groups" string will be modified in place by strtok()
 */
void
obtain_user_info(const char *user, const char *groups)
{
    struct passwd *pw;
    int i;
    uid_t uid = -1;

    /* no user specified? use the current uid. */
    if (!user) {
        uid = getuid();
        pw = getpwuid(uid);
    }
    else {
        /* try to resolve the pw struct from the user string */
        pw = getpwnam(user);

        /* if it fails, try to treat it as a number */
        if (!pw) {
            char *endptr = (char *)user;

            /* try by id as well */
            uid = strtol(user, &endptr, 0);
            if (uid == ULONG_MAX || *endptr != '\0') {
                fprintf(stderr, "[!] Invalid user id: %s!\n", user);
                exit(1);
            }

            pw = getpwuid(uid);
        }
    }
    if (!pw) {
        fprintf(stderr, "[!] Unable to find uid %lu, trying anyway...\n", (unsigned long)uid);
        g_uid = uid;
        g_ngroups = 0;
    }
    else
        g_uid = pw->pw_uid;

    /* find out what groups the current or specified user is in */
    if (!user) {
        int num = getgroups(0, g_groups);
        if (num > g_ngroups) {
            fprintf(stderr, "[!] Too many groups!\n");
            exit(1);
        }
        if ((g_ngroups = getgroups(g_ngroups, g_groups)) == -1) {
            perror("[!] Unable to getgroups");
            exit(1);
        }

        /* make sure our gid is in the groups */
        if (!in_group(pw->pw_gid))
            add_group(pw->pw_gid);
    }
    else if (pw) {
        /* since we are passing the max, we shouldn't have an issue with failed return */
        getgrouplist(pw->pw_name, pw->pw_gid, g_groups, &g_ngroups);
    }
    /* else we have no way of knowing, the user doesn't exist =) */

    /* append any extra groups */
    if (groups) {
        char *grnam = strtok((char *)groups, ",");

        while (grnam) {
            struct group *pg = getgrnam(grnam);
            gid_t gid;

            if (!pg) {
                char *endptr = grnam;

                gid = strtoul(grnam, &endptr, 0);
                /* a bad number indicates a probably mistake */
                if (gid == ULONG_MAX || *endptr != '\0') {
                    fprintf(stderr, "[!] Unknown/invalid group: %s\n", grnam);
                    exit(1);
                }

                /* try again */
                pg = getgrgid(gid);
            }

            if (!pg) {
                /* this is just a warning, add the number and keep processing others */
                fprintf(stderr, "[!] Unable to find gid %s, trying anyway...\n", grnam);
                if (!in_group(gid))
                    add_group(gid);
            }
            else if (!in_group(pg->gr_gid))
                add_group(pg->gr_gid);

            /* process the next group name. */
            grnam = strtok(NULL, ",");
        }
    }

    /* print what we found :) */
    if (pw)
        printf("[*] uid=%u(%s), groups=", pw->pw_uid, pw->pw_name);
    else
        printf("[*] uid=%u(?), groups=", g_uid);

    for (i = 0; i < g_ngroups; i++) {
        struct group *pg = getgrgid(g_groups[i]);

        if (pg)
            printf("%u(%s)", pg->gr_gid, pg->gr_name);
        else
            printf("%u(?)", g_groups[i]);
        if (i != g_ngroups - 1)
            printf(",");
    }
    printf("\n");
}
Exemplo n.º 30
0
int main(int ac, char **av)
{
	struct database *db;
	struct group *group = NULL;
	char *line = NULL;
	size_t linesz = 0;
	if (!av[1]) {
		printf("%s database\n", av[0]);
		exit(1);
	}
	printf("dbtest\n");
	db = open_db(av[1], 1);
	while (printf("> "),
		fflush(stdout),
		getline(&line, &linesz, stdin) > 0) {
		char *p = line + strlen(line) - 1;
		while (p >= line && isspace(*p))
			*p-- = 0;
		switch (line[0]) {
		case 's':
			C(sync_db(db));
			break;
		case 'q':
			C(close_db(db));
			exit(0);
		case 'g':
			group = find_group(db, line + 1);
			if (group)
				printf("found\n");
			break;
		case 'G':
			NEEDGROUP;
			C(delete_group(db, group));
			group = NULL;
			break;
		case 'a': {
			int existed = 0;
			group = add_group(db, line + 1, &existed);
			if (existed)
				printf("existed\n");
			break;
		}
		case 'v':
			NEEDGROUP;
			printf("%s\n", entry_val(group, line + 1));
			break;
		case 'c': {
			p = line + 1;
			char *entry = strsep(&p, ",");
			NEEDGROUP;
			change_entry(db, group, entry, strsep(&p, ""));
			break;
		}
		case 'L':
			NEEDGROUP;
			clone_group(db, group, line + 1);
			break;
		case 'f': {
			struct group *g;
			p = line + 1;
			char *entry = strsep(&p, ",");
			char *val = strsep(&p, "");
			g = NULL;
			int nr = 0;
			while ((g = find_entry(db, g, entry, val)) != NULL) {
				if (nr == 0)
					group = g;
				nr++;
				dump_group(group, stdout);
			}
			if (nr == 0)
				printf("not found\n");
			break;
		}
		case 'C':
			NEEDGROUP;
			add_comment(db, group, line + 1);
			break;
		case 'd':
			NEEDGROUP;
			dump_group(group, stdout);
			break;
		case 'D':
			dump_database(db, stdout);
			break;
		default:
			usage();
			break;
		}
	}
	return 0;
}